transport.con commit fetch: support filters (acb0c57)
   1#include "cache.h"
   2#include "config.h"
   3#include "transport.h"
   4#include "run-command.h"
   5#include "pkt-line.h"
   6#include "fetch-pack.h"
   7#include "remote.h"
   8#include "connect.h"
   9#include "send-pack.h"
  10#include "walker.h"
  11#include "bundle.h"
  12#include "dir.h"
  13#include "refs.h"
  14#include "branch.h"
  15#include "url.h"
  16#include "submodule.h"
  17#include "string-list.h"
  18#include "sha1-array.h"
  19#include "sigchain.h"
  20
  21static void set_upstreams(struct transport *transport, struct ref *refs,
  22        int pretend)
  23{
  24        struct ref *ref;
  25        for (ref = refs; ref; ref = ref->next) {
  26                const char *localname;
  27                const char *tmp;
  28                const char *remotename;
  29                int flag = 0;
  30                /*
  31                 * Check suitability for tracking. Must be successful /
  32                 * already up-to-date ref create/modify (not delete).
  33                 */
  34                if (ref->status != REF_STATUS_OK &&
  35                        ref->status != REF_STATUS_UPTODATE)
  36                        continue;
  37                if (!ref->peer_ref)
  38                        continue;
  39                if (is_null_oid(&ref->new_oid))
  40                        continue;
  41
  42                /* Follow symbolic refs (mainly for HEAD). */
  43                localname = ref->peer_ref->name;
  44                remotename = ref->name;
  45                tmp = resolve_ref_unsafe(localname, RESOLVE_REF_READING,
  46                                         NULL, &flag);
  47                if (tmp && flag & REF_ISSYMREF &&
  48                        starts_with(tmp, "refs/heads/"))
  49                        localname = tmp;
  50
  51                /* Both source and destination must be local branches. */
  52                if (!localname || !starts_with(localname, "refs/heads/"))
  53                        continue;
  54                if (!remotename || !starts_with(remotename, "refs/heads/"))
  55                        continue;
  56
  57                if (!pretend)
  58                        install_branch_config(BRANCH_CONFIG_VERBOSE,
  59                                localname + 11, transport->remote->name,
  60                                remotename);
  61                else
  62                        printf(_("Would set upstream of '%s' to '%s' of '%s'\n"),
  63                                localname + 11, remotename + 11,
  64                                transport->remote->name);
  65        }
  66}
  67
  68struct bundle_transport_data {
  69        int fd;
  70        struct bundle_header header;
  71};
  72
  73static struct ref *get_refs_from_bundle(struct transport *transport, int for_push)
  74{
  75        struct bundle_transport_data *data = transport->data;
  76        struct ref *result = NULL;
  77        int i;
  78
  79        if (for_push)
  80                return NULL;
  81
  82        if (data->fd > 0)
  83                close(data->fd);
  84        data->fd = read_bundle_header(transport->url, &data->header);
  85        if (data->fd < 0)
  86                die ("Could not read bundle '%s'.", transport->url);
  87        for (i = 0; i < data->header.references.nr; i++) {
  88                struct ref_list_entry *e = data->header.references.list + i;
  89                struct ref *ref = alloc_ref(e->name);
  90                oidcpy(&ref->old_oid, &e->oid);
  91                ref->next = result;
  92                result = ref;
  93        }
  94        return result;
  95}
  96
  97static int fetch_refs_from_bundle(struct transport *transport,
  98                               int nr_heads, struct ref **to_fetch)
  99{
 100        struct bundle_transport_data *data = transport->data;
 101        return unbundle(&data->header, data->fd,
 102                        transport->progress ? BUNDLE_VERBOSE : 0);
 103}
 104
 105static int close_bundle(struct transport *transport)
 106{
 107        struct bundle_transport_data *data = transport->data;
 108        if (data->fd > 0)
 109                close(data->fd);
 110        free(data);
 111        return 0;
 112}
 113
 114struct git_transport_data {
 115        struct git_transport_options options;
 116        struct child_process *conn;
 117        int fd[2];
 118        unsigned got_remote_heads : 1;
 119        struct oid_array extra_have;
 120        struct oid_array shallow;
 121};
 122
 123static int set_git_option(struct git_transport_options *opts,
 124                          const char *name, const char *value)
 125{
 126        if (!strcmp(name, TRANS_OPT_UPLOADPACK)) {
 127                opts->uploadpack = value;
 128                return 0;
 129        } else if (!strcmp(name, TRANS_OPT_RECEIVEPACK)) {
 130                opts->receivepack = value;
 131                return 0;
 132        } else if (!strcmp(name, TRANS_OPT_THIN)) {
 133                opts->thin = !!value;
 134                return 0;
 135        } else if (!strcmp(name, TRANS_OPT_FOLLOWTAGS)) {
 136                opts->followtags = !!value;
 137                return 0;
 138        } else if (!strcmp(name, TRANS_OPT_KEEP)) {
 139                opts->keep = !!value;
 140                return 0;
 141        } else if (!strcmp(name, TRANS_OPT_UPDATE_SHALLOW)) {
 142                opts->update_shallow = !!value;
 143                return 0;
 144        } else if (!strcmp(name, TRANS_OPT_DEPTH)) {
 145                if (!value)
 146                        opts->depth = 0;
 147                else {
 148                        char *end;
 149                        opts->depth = strtol(value, &end, 0);
 150                        if (*end)
 151                                die(_("transport: invalid depth option '%s'"), value);
 152                }
 153                return 0;
 154        } else if (!strcmp(name, TRANS_OPT_DEEPEN_SINCE)) {
 155                opts->deepen_since = value;
 156                return 0;
 157        } else if (!strcmp(name, TRANS_OPT_DEEPEN_NOT)) {
 158                opts->deepen_not = (const struct string_list *)value;
 159                return 0;
 160        } else if (!strcmp(name, TRANS_OPT_DEEPEN_RELATIVE)) {
 161                opts->deepen_relative = !!value;
 162                return 0;
 163        } else if (!strcmp(name, TRANS_OPT_FROM_PROMISOR)) {
 164                opts->from_promisor = !!value;
 165                return 0;
 166        } else if (!strcmp(name, TRANS_OPT_NO_DEPENDENTS)) {
 167                opts->no_dependents = !!value;
 168                return 0;
 169        } else if (!strcmp(name, TRANS_OPT_LIST_OBJECTS_FILTER)) {
 170                parse_list_objects_filter(&opts->filter_options, value);
 171                return 0;
 172        }
 173        return 1;
 174}
 175
 176static int connect_setup(struct transport *transport, int for_push)
 177{
 178        struct git_transport_data *data = transport->data;
 179        int flags = transport->verbose > 0 ? CONNECT_VERBOSE : 0;
 180
 181        if (data->conn)
 182                return 0;
 183
 184        switch (transport->family) {
 185        case TRANSPORT_FAMILY_ALL: break;
 186        case TRANSPORT_FAMILY_IPV4: flags |= CONNECT_IPV4; break;
 187        case TRANSPORT_FAMILY_IPV6: flags |= CONNECT_IPV6; break;
 188        }
 189
 190        data->conn = git_connect(data->fd, transport->url,
 191                                 for_push ? data->options.receivepack :
 192                                 data->options.uploadpack,
 193                                 flags);
 194
 195        return 0;
 196}
 197
 198static struct ref *get_refs_via_connect(struct transport *transport, int for_push)
 199{
 200        struct git_transport_data *data = transport->data;
 201        struct ref *refs;
 202
 203        connect_setup(transport, for_push);
 204        get_remote_heads(data->fd[0], NULL, 0, &refs,
 205                         for_push ? REF_NORMAL : 0,
 206                         &data->extra_have,
 207                         &data->shallow);
 208        data->got_remote_heads = 1;
 209
 210        return refs;
 211}
 212
 213static int fetch_refs_via_pack(struct transport *transport,
 214                               int nr_heads, struct ref **to_fetch)
 215{
 216        int ret = 0;
 217        struct git_transport_data *data = transport->data;
 218        struct ref *refs;
 219        char *dest = xstrdup(transport->url);
 220        struct fetch_pack_args args;
 221        struct ref *refs_tmp = NULL;
 222
 223        memset(&args, 0, sizeof(args));
 224        args.uploadpack = data->options.uploadpack;
 225        args.keep_pack = data->options.keep;
 226        args.lock_pack = 1;
 227        args.use_thin_pack = data->options.thin;
 228        args.include_tag = data->options.followtags;
 229        args.verbose = (transport->verbose > 1);
 230        args.quiet = (transport->verbose < 0);
 231        args.no_progress = !transport->progress;
 232        args.depth = data->options.depth;
 233        args.deepen_since = data->options.deepen_since;
 234        args.deepen_not = data->options.deepen_not;
 235        args.deepen_relative = data->options.deepen_relative;
 236        args.check_self_contained_and_connected =
 237                data->options.check_self_contained_and_connected;
 238        args.cloning = transport->cloning;
 239        args.update_shallow = data->options.update_shallow;
 240        args.from_promisor = data->options.from_promisor;
 241        args.no_dependents = data->options.no_dependents;
 242        args.filter_options = data->options.filter_options;
 243
 244        if (!data->got_remote_heads) {
 245                connect_setup(transport, 0);
 246                get_remote_heads(data->fd[0], NULL, 0, &refs_tmp, 0,
 247                                 NULL, &data->shallow);
 248                data->got_remote_heads = 1;
 249        }
 250
 251        refs = fetch_pack(&args, data->fd, data->conn,
 252                          refs_tmp ? refs_tmp : transport->remote_refs,
 253                          dest, to_fetch, nr_heads, &data->shallow,
 254                          &transport->pack_lockfile);
 255        close(data->fd[0]);
 256        close(data->fd[1]);
 257        if (finish_connect(data->conn))
 258                ret = -1;
 259        data->conn = NULL;
 260        data->got_remote_heads = 0;
 261        data->options.self_contained_and_connected =
 262                args.self_contained_and_connected;
 263
 264        if (refs == NULL)
 265                ret = -1;
 266        if (report_unmatched_refs(to_fetch, nr_heads))
 267                ret = -1;
 268
 269        free_refs(refs_tmp);
 270        free_refs(refs);
 271        free(dest);
 272        return ret;
 273}
 274
 275static int push_had_errors(struct ref *ref)
 276{
 277        for (; ref; ref = ref->next) {
 278                switch (ref->status) {
 279                case REF_STATUS_NONE:
 280                case REF_STATUS_UPTODATE:
 281                case REF_STATUS_OK:
 282                        break;
 283                default:
 284                        return 1;
 285                }
 286        }
 287        return 0;
 288}
 289
 290int transport_refs_pushed(struct ref *ref)
 291{
 292        for (; ref; ref = ref->next) {
 293                switch(ref->status) {
 294                case REF_STATUS_NONE:
 295                case REF_STATUS_UPTODATE:
 296                        break;
 297                default:
 298                        return 1;
 299                }
 300        }
 301        return 0;
 302}
 303
 304void transport_update_tracking_ref(struct remote *remote, struct ref *ref, int verbose)
 305{
 306        struct refspec rs;
 307
 308        if (ref->status != REF_STATUS_OK && ref->status != REF_STATUS_UPTODATE)
 309                return;
 310
 311        rs.src = ref->name;
 312        rs.dst = NULL;
 313
 314        if (!remote_find_tracking(remote, &rs)) {
 315                if (verbose)
 316                        fprintf(stderr, "updating local tracking ref '%s'\n", rs.dst);
 317                if (ref->deletion) {
 318                        delete_ref(NULL, rs.dst, NULL, 0);
 319                } else
 320                        update_ref("update by push", rs.dst,
 321                                        ref->new_oid.hash, NULL, 0, 0);
 322                free(rs.dst);
 323        }
 324}
 325
 326static void print_ref_status(char flag, const char *summary,
 327                             struct ref *to, struct ref *from, const char *msg,
 328                             int porcelain, int summary_width)
 329{
 330        if (porcelain) {
 331                if (from)
 332                        fprintf(stdout, "%c\t%s:%s\t", flag, from->name, to->name);
 333                else
 334                        fprintf(stdout, "%c\t:%s\t", flag, to->name);
 335                if (msg)
 336                        fprintf(stdout, "%s (%s)\n", summary, msg);
 337                else
 338                        fprintf(stdout, "%s\n", summary);
 339        } else {
 340                fprintf(stderr, " %c %-*s ", flag, summary_width, summary);
 341                if (from)
 342                        fprintf(stderr, "%s -> %s", prettify_refname(from->name), prettify_refname(to->name));
 343                else
 344                        fputs(prettify_refname(to->name), stderr);
 345                if (msg) {
 346                        fputs(" (", stderr);
 347                        fputs(msg, stderr);
 348                        fputc(')', stderr);
 349                }
 350                fputc('\n', stderr);
 351        }
 352}
 353
 354static void print_ok_ref_status(struct ref *ref, int porcelain, int summary_width)
 355{
 356        if (ref->deletion)
 357                print_ref_status('-', "[deleted]", ref, NULL, NULL,
 358                                 porcelain, summary_width);
 359        else if (is_null_oid(&ref->old_oid))
 360                print_ref_status('*',
 361                        (starts_with(ref->name, "refs/tags/") ? "[new tag]" :
 362                        "[new branch]"),
 363                        ref, ref->peer_ref, NULL, porcelain, summary_width);
 364        else {
 365                struct strbuf quickref = STRBUF_INIT;
 366                char type;
 367                const char *msg;
 368
 369                strbuf_add_unique_abbrev(&quickref, ref->old_oid.hash,
 370                                         DEFAULT_ABBREV);
 371                if (ref->forced_update) {
 372                        strbuf_addstr(&quickref, "...");
 373                        type = '+';
 374                        msg = "forced update";
 375                } else {
 376                        strbuf_addstr(&quickref, "..");
 377                        type = ' ';
 378                        msg = NULL;
 379                }
 380                strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash,
 381                                         DEFAULT_ABBREV);
 382
 383                print_ref_status(type, quickref.buf, ref, ref->peer_ref, msg,
 384                                 porcelain, summary_width);
 385                strbuf_release(&quickref);
 386        }
 387}
 388
 389static int print_one_push_status(struct ref *ref, const char *dest, int count,
 390                                 int porcelain, int summary_width)
 391{
 392        if (!count) {
 393                char *url = transport_anonymize_url(dest);
 394                fprintf(porcelain ? stdout : stderr, "To %s\n", url);
 395                free(url);
 396        }
 397
 398        switch(ref->status) {
 399        case REF_STATUS_NONE:
 400                print_ref_status('X', "[no match]", ref, NULL, NULL,
 401                                 porcelain, summary_width);
 402                break;
 403        case REF_STATUS_REJECT_NODELETE:
 404                print_ref_status('!', "[rejected]", ref, NULL,
 405                                 "remote does not support deleting refs",
 406                                 porcelain, summary_width);
 407                break;
 408        case REF_STATUS_UPTODATE:
 409                print_ref_status('=', "[up to date]", ref,
 410                                 ref->peer_ref, NULL, porcelain, summary_width);
 411                break;
 412        case REF_STATUS_REJECT_NONFASTFORWARD:
 413                print_ref_status('!', "[rejected]", ref, ref->peer_ref,
 414                                 "non-fast-forward", porcelain, summary_width);
 415                break;
 416        case REF_STATUS_REJECT_ALREADY_EXISTS:
 417                print_ref_status('!', "[rejected]", ref, ref->peer_ref,
 418                                 "already exists", porcelain, summary_width);
 419                break;
 420        case REF_STATUS_REJECT_FETCH_FIRST:
 421                print_ref_status('!', "[rejected]", ref, ref->peer_ref,
 422                                 "fetch first", porcelain, summary_width);
 423                break;
 424        case REF_STATUS_REJECT_NEEDS_FORCE:
 425                print_ref_status('!', "[rejected]", ref, ref->peer_ref,
 426                                 "needs force", porcelain, summary_width);
 427                break;
 428        case REF_STATUS_REJECT_STALE:
 429                print_ref_status('!', "[rejected]", ref, ref->peer_ref,
 430                                 "stale info", porcelain, summary_width);
 431                break;
 432        case REF_STATUS_REJECT_SHALLOW:
 433                print_ref_status('!', "[rejected]", ref, ref->peer_ref,
 434                                 "new shallow roots not allowed",
 435                                 porcelain, summary_width);
 436                break;
 437        case REF_STATUS_REMOTE_REJECT:
 438                print_ref_status('!', "[remote rejected]", ref,
 439                                 ref->deletion ? NULL : ref->peer_ref,
 440                                 ref->remote_status, porcelain, summary_width);
 441                break;
 442        case REF_STATUS_EXPECTING_REPORT:
 443                print_ref_status('!', "[remote failure]", ref,
 444                                 ref->deletion ? NULL : ref->peer_ref,
 445                                 "remote failed to report status",
 446                                 porcelain, summary_width);
 447                break;
 448        case REF_STATUS_ATOMIC_PUSH_FAILED:
 449                print_ref_status('!', "[rejected]", ref, ref->peer_ref,
 450                                 "atomic push failed", porcelain, summary_width);
 451                break;
 452        case REF_STATUS_OK:
 453                print_ok_ref_status(ref, porcelain, summary_width);
 454                break;
 455        }
 456
 457        return 1;
 458}
 459
 460static int measure_abbrev(const struct object_id *oid, int sofar)
 461{
 462        char hex[GIT_MAX_HEXSZ + 1];
 463        int w = find_unique_abbrev_r(hex, oid->hash, DEFAULT_ABBREV);
 464
 465        return (w < sofar) ? sofar : w;
 466}
 467
 468int transport_summary_width(const struct ref *refs)
 469{
 470        int maxw = -1;
 471
 472        for (; refs; refs = refs->next) {
 473                maxw = measure_abbrev(&refs->old_oid, maxw);
 474                maxw = measure_abbrev(&refs->new_oid, maxw);
 475        }
 476        if (maxw < 0)
 477                maxw = FALLBACK_DEFAULT_ABBREV;
 478        return (2 * maxw + 3);
 479}
 480
 481void transport_print_push_status(const char *dest, struct ref *refs,
 482                                  int verbose, int porcelain, unsigned int *reject_reasons)
 483{
 484        struct ref *ref;
 485        int n = 0;
 486        char *head;
 487        int summary_width = transport_summary_width(refs);
 488
 489        head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
 490
 491        if (verbose) {
 492                for (ref = refs; ref; ref = ref->next)
 493                        if (ref->status == REF_STATUS_UPTODATE)
 494                                n += print_one_push_status(ref, dest, n,
 495                                                           porcelain, summary_width);
 496        }
 497
 498        for (ref = refs; ref; ref = ref->next)
 499                if (ref->status == REF_STATUS_OK)
 500                        n += print_one_push_status(ref, dest, n,
 501                                                   porcelain, summary_width);
 502
 503        *reject_reasons = 0;
 504        for (ref = refs; ref; ref = ref->next) {
 505                if (ref->status != REF_STATUS_NONE &&
 506                    ref->status != REF_STATUS_UPTODATE &&
 507                    ref->status != REF_STATUS_OK)
 508                        n += print_one_push_status(ref, dest, n,
 509                                                   porcelain, summary_width);
 510                if (ref->status == REF_STATUS_REJECT_NONFASTFORWARD) {
 511                        if (head != NULL && !strcmp(head, ref->name))
 512                                *reject_reasons |= REJECT_NON_FF_HEAD;
 513                        else
 514                                *reject_reasons |= REJECT_NON_FF_OTHER;
 515                } else if (ref->status == REF_STATUS_REJECT_ALREADY_EXISTS) {
 516                        *reject_reasons |= REJECT_ALREADY_EXISTS;
 517                } else if (ref->status == REF_STATUS_REJECT_FETCH_FIRST) {
 518                        *reject_reasons |= REJECT_FETCH_FIRST;
 519                } else if (ref->status == REF_STATUS_REJECT_NEEDS_FORCE) {
 520                        *reject_reasons |= REJECT_NEEDS_FORCE;
 521                }
 522        }
 523        free(head);
 524}
 525
 526void transport_verify_remote_names(int nr_heads, const char **heads)
 527{
 528        int i;
 529
 530        for (i = 0; i < nr_heads; i++) {
 531                const char *local = heads[i];
 532                const char *remote = strrchr(heads[i], ':');
 533
 534                if (*local == '+')
 535                        local++;
 536
 537                /* A matching refspec is okay.  */
 538                if (remote == local && remote[1] == '\0')
 539                        continue;
 540
 541                remote = remote ? (remote + 1) : local;
 542                if (check_refname_format(remote,
 543                                REFNAME_ALLOW_ONELEVEL|REFNAME_REFSPEC_PATTERN))
 544                        die("remote part of refspec is not a valid name in %s",
 545                                heads[i]);
 546        }
 547}
 548
 549static int git_transport_push(struct transport *transport, struct ref *remote_refs, int flags)
 550{
 551        struct git_transport_data *data = transport->data;
 552        struct send_pack_args args;
 553        int ret;
 554
 555        if (!data->got_remote_heads) {
 556                struct ref *tmp_refs;
 557                connect_setup(transport, 1);
 558
 559                get_remote_heads(data->fd[0], NULL, 0, &tmp_refs, REF_NORMAL,
 560                                 NULL, &data->shallow);
 561                data->got_remote_heads = 1;
 562        }
 563
 564        memset(&args, 0, sizeof(args));
 565        args.send_mirror = !!(flags & TRANSPORT_PUSH_MIRROR);
 566        args.force_update = !!(flags & TRANSPORT_PUSH_FORCE);
 567        args.use_thin_pack = data->options.thin;
 568        args.verbose = (transport->verbose > 0);
 569        args.quiet = (transport->verbose < 0);
 570        args.progress = transport->progress;
 571        args.dry_run = !!(flags & TRANSPORT_PUSH_DRY_RUN);
 572        args.porcelain = !!(flags & TRANSPORT_PUSH_PORCELAIN);
 573        args.atomic = !!(flags & TRANSPORT_PUSH_ATOMIC);
 574        args.push_options = transport->push_options;
 575        args.url = transport->url;
 576
 577        if (flags & TRANSPORT_PUSH_CERT_ALWAYS)
 578                args.push_cert = SEND_PACK_PUSH_CERT_ALWAYS;
 579        else if (flags & TRANSPORT_PUSH_CERT_IF_ASKED)
 580                args.push_cert = SEND_PACK_PUSH_CERT_IF_ASKED;
 581        else
 582                args.push_cert = SEND_PACK_PUSH_CERT_NEVER;
 583
 584        ret = send_pack(&args, data->fd, data->conn, remote_refs,
 585                        &data->extra_have);
 586
 587        close(data->fd[1]);
 588        close(data->fd[0]);
 589        ret |= finish_connect(data->conn);
 590        data->conn = NULL;
 591        data->got_remote_heads = 0;
 592
 593        return ret;
 594}
 595
 596static int connect_git(struct transport *transport, const char *name,
 597                       const char *executable, int fd[2])
 598{
 599        struct git_transport_data *data = transport->data;
 600        data->conn = git_connect(data->fd, transport->url,
 601                                 executable, 0);
 602        fd[0] = data->fd[0];
 603        fd[1] = data->fd[1];
 604        return 0;
 605}
 606
 607static int disconnect_git(struct transport *transport)
 608{
 609        struct git_transport_data *data = transport->data;
 610        if (data->conn) {
 611                if (data->got_remote_heads)
 612                        packet_flush(data->fd[1]);
 613                close(data->fd[0]);
 614                close(data->fd[1]);
 615                finish_connect(data->conn);
 616        }
 617
 618        free(data);
 619        return 0;
 620}
 621
 622void transport_take_over(struct transport *transport,
 623                         struct child_process *child)
 624{
 625        struct git_transport_data *data;
 626
 627        if (!transport->smart_options)
 628                die("BUG: taking over transport requires non-NULL "
 629                    "smart_options field.");
 630
 631        data = xcalloc(1, sizeof(*data));
 632        data->options = *transport->smart_options;
 633        data->conn = child;
 634        data->fd[0] = data->conn->out;
 635        data->fd[1] = data->conn->in;
 636        data->got_remote_heads = 0;
 637        transport->data = data;
 638
 639        transport->set_option = NULL;
 640        transport->get_refs_list = get_refs_via_connect;
 641        transport->fetch = fetch_refs_via_pack;
 642        transport->push = NULL;
 643        transport->push_refs = git_transport_push;
 644        transport->disconnect = disconnect_git;
 645        transport->smart_options = &(data->options);
 646
 647        transport->cannot_reuse = 1;
 648}
 649
 650static int is_file(const char *url)
 651{
 652        struct stat buf;
 653        if (stat(url, &buf))
 654                return 0;
 655        return S_ISREG(buf.st_mode);
 656}
 657
 658static int external_specification_len(const char *url)
 659{
 660        return strchr(url, ':') - url;
 661}
 662
 663static const struct string_list *protocol_whitelist(void)
 664{
 665        static int enabled = -1;
 666        static struct string_list allowed = STRING_LIST_INIT_DUP;
 667
 668        if (enabled < 0) {
 669                const char *v = getenv("GIT_ALLOW_PROTOCOL");
 670                if (v) {
 671                        string_list_split(&allowed, v, ':', -1);
 672                        string_list_sort(&allowed);
 673                        enabled = 1;
 674                } else {
 675                        enabled = 0;
 676                }
 677        }
 678
 679        return enabled ? &allowed : NULL;
 680}
 681
 682enum protocol_allow_config {
 683        PROTOCOL_ALLOW_NEVER = 0,
 684        PROTOCOL_ALLOW_USER_ONLY,
 685        PROTOCOL_ALLOW_ALWAYS
 686};
 687
 688static enum protocol_allow_config parse_protocol_config(const char *key,
 689                                                        const char *value)
 690{
 691        if (!strcasecmp(value, "always"))
 692                return PROTOCOL_ALLOW_ALWAYS;
 693        else if (!strcasecmp(value, "never"))
 694                return PROTOCOL_ALLOW_NEVER;
 695        else if (!strcasecmp(value, "user"))
 696                return PROTOCOL_ALLOW_USER_ONLY;
 697
 698        die("unknown value for config '%s': %s", key, value);
 699}
 700
 701static enum protocol_allow_config get_protocol_config(const char *type)
 702{
 703        char *key = xstrfmt("protocol.%s.allow", type);
 704        char *value;
 705
 706        /* first check the per-protocol config */
 707        if (!git_config_get_string(key, &value)) {
 708                enum protocol_allow_config ret =
 709                        parse_protocol_config(key, value);
 710                free(key);
 711                free(value);
 712                return ret;
 713        }
 714        free(key);
 715
 716        /* if defined, fallback to user-defined default for unknown protocols */
 717        if (!git_config_get_string("protocol.allow", &value)) {
 718                enum protocol_allow_config ret =
 719                        parse_protocol_config("protocol.allow", value);
 720                free(value);
 721                return ret;
 722        }
 723
 724        /* fallback to built-in defaults */
 725        /* known safe */
 726        if (!strcmp(type, "http") ||
 727            !strcmp(type, "https") ||
 728            !strcmp(type, "git") ||
 729            !strcmp(type, "ssh") ||
 730            !strcmp(type, "file"))
 731                return PROTOCOL_ALLOW_ALWAYS;
 732
 733        /* known scary; err on the side of caution */
 734        if (!strcmp(type, "ext"))
 735                return PROTOCOL_ALLOW_NEVER;
 736
 737        /* unknown; by default let them be used only directly by the user */
 738        return PROTOCOL_ALLOW_USER_ONLY;
 739}
 740
 741int is_transport_allowed(const char *type, int from_user)
 742{
 743        const struct string_list *whitelist = protocol_whitelist();
 744        if (whitelist)
 745                return string_list_has_string(whitelist, type);
 746
 747        switch (get_protocol_config(type)) {
 748        case PROTOCOL_ALLOW_ALWAYS:
 749                return 1;
 750        case PROTOCOL_ALLOW_NEVER:
 751                return 0;
 752        case PROTOCOL_ALLOW_USER_ONLY:
 753                if (from_user < 0)
 754                        from_user = git_env_bool("GIT_PROTOCOL_FROM_USER", 1);
 755                return from_user;
 756        }
 757
 758        die("BUG: invalid protocol_allow_config type");
 759}
 760
 761void transport_check_allowed(const char *type)
 762{
 763        if (!is_transport_allowed(type, -1))
 764                die("transport '%s' not allowed", type);
 765}
 766
 767struct transport *transport_get(struct remote *remote, const char *url)
 768{
 769        const char *helper;
 770        struct transport *ret = xcalloc(1, sizeof(*ret));
 771
 772        ret->progress = isatty(2);
 773
 774        if (!remote)
 775                die("No remote provided to transport_get()");
 776
 777        ret->got_remote_refs = 0;
 778        ret->remote = remote;
 779        helper = remote->foreign_vcs;
 780
 781        if (!url && remote->url)
 782                url = remote->url[0];
 783        ret->url = url;
 784
 785        /* maybe it is a foreign URL? */
 786        if (url) {
 787                const char *p = url;
 788
 789                while (is_urlschemechar(p == url, *p))
 790                        p++;
 791                if (starts_with(p, "::"))
 792                        helper = xstrndup(url, p - url);
 793        }
 794
 795        if (helper) {
 796                transport_helper_init(ret, helper);
 797        } else if (starts_with(url, "rsync:")) {
 798                die("git-over-rsync is no longer supported");
 799        } else if (url_is_local_not_ssh(url) && is_file(url) && is_bundle(url, 1)) {
 800                struct bundle_transport_data *data = xcalloc(1, sizeof(*data));
 801                transport_check_allowed("file");
 802                ret->data = data;
 803                ret->get_refs_list = get_refs_from_bundle;
 804                ret->fetch = fetch_refs_from_bundle;
 805                ret->disconnect = close_bundle;
 806                ret->smart_options = NULL;
 807        } else if (!is_url(url)
 808                || starts_with(url, "file://")
 809                || starts_with(url, "git://")
 810                || starts_with(url, "ssh://")
 811                || starts_with(url, "git+ssh://") /* deprecated - do not use */
 812                || starts_with(url, "ssh+git://") /* deprecated - do not use */
 813                ) {
 814                /*
 815                 * These are builtin smart transports; "allowed" transports
 816                 * will be checked individually in git_connect.
 817                 */
 818                struct git_transport_data *data = xcalloc(1, sizeof(*data));
 819                ret->data = data;
 820                ret->set_option = NULL;
 821                ret->get_refs_list = get_refs_via_connect;
 822                ret->fetch = fetch_refs_via_pack;
 823                ret->push_refs = git_transport_push;
 824                ret->connect = connect_git;
 825                ret->disconnect = disconnect_git;
 826                ret->smart_options = &(data->options);
 827
 828                data->conn = NULL;
 829                data->got_remote_heads = 0;
 830        } else {
 831                /* Unknown protocol in URL. Pass to external handler. */
 832                int len = external_specification_len(url);
 833                char *handler = xmemdupz(url, len);
 834                transport_helper_init(ret, handler);
 835        }
 836
 837        if (ret->smart_options) {
 838                ret->smart_options->thin = 1;
 839                ret->smart_options->uploadpack = "git-upload-pack";
 840                if (remote->uploadpack)
 841                        ret->smart_options->uploadpack = remote->uploadpack;
 842                ret->smart_options->receivepack = "git-receive-pack";
 843                if (remote->receivepack)
 844                        ret->smart_options->receivepack = remote->receivepack;
 845        }
 846
 847        return ret;
 848}
 849
 850int transport_set_option(struct transport *transport,
 851                         const char *name, const char *value)
 852{
 853        int git_reports = 1, protocol_reports = 1;
 854
 855        if (transport->smart_options)
 856                git_reports = set_git_option(transport->smart_options,
 857                                             name, value);
 858
 859        if (transport->set_option)
 860                protocol_reports = transport->set_option(transport, name,
 861                                                        value);
 862
 863        /* If either report is 0, report 0 (success). */
 864        if (!git_reports || !protocol_reports)
 865                return 0;
 866        /* If either reports -1 (invalid value), report -1. */
 867        if ((git_reports == -1) || (protocol_reports == -1))
 868                return -1;
 869        /* Otherwise if both report unknown, report unknown. */
 870        return 1;
 871}
 872
 873void transport_set_verbosity(struct transport *transport, int verbosity,
 874        int force_progress)
 875{
 876        if (verbosity >= 1)
 877                transport->verbose = verbosity <= 3 ? verbosity : 3;
 878        if (verbosity < 0)
 879                transport->verbose = -1;
 880
 881        /**
 882         * Rules used to determine whether to report progress (processing aborts
 883         * when a rule is satisfied):
 884         *
 885         *   . Report progress, if force_progress is 1 (ie. --progress).
 886         *   . Don't report progress, if force_progress is 0 (ie. --no-progress).
 887         *   . Don't report progress, if verbosity < 0 (ie. -q/--quiet ).
 888         *   . Report progress if isatty(2) is 1.
 889         **/
 890        if (force_progress >= 0)
 891                transport->progress = !!force_progress;
 892        else
 893                transport->progress = verbosity >= 0 && isatty(2);
 894}
 895
 896static void die_with_unpushed_submodules(struct string_list *needs_pushing)
 897{
 898        int i;
 899
 900        fprintf(stderr, _("The following submodule paths contain changes that can\n"
 901                        "not be found on any remote:\n"));
 902        for (i = 0; i < needs_pushing->nr; i++)
 903                fprintf(stderr, "  %s\n", needs_pushing->items[i].string);
 904        fprintf(stderr, _("\nPlease try\n\n"
 905                          "     git push --recurse-submodules=on-demand\n\n"
 906                          "or cd to the path and use\n\n"
 907                          "     git push\n\n"
 908                          "to push them to a remote.\n\n"));
 909
 910        string_list_clear(needs_pushing, 0);
 911
 912        die(_("Aborting."));
 913}
 914
 915static int run_pre_push_hook(struct transport *transport,
 916                             struct ref *remote_refs)
 917{
 918        int ret = 0, x;
 919        struct ref *r;
 920        struct child_process proc = CHILD_PROCESS_INIT;
 921        struct strbuf buf;
 922        const char *argv[4];
 923
 924        if (!(argv[0] = find_hook("pre-push")))
 925                return 0;
 926
 927        argv[1] = transport->remote->name;
 928        argv[2] = transport->url;
 929        argv[3] = NULL;
 930
 931        proc.argv = argv;
 932        proc.in = -1;
 933
 934        if (start_command(&proc)) {
 935                finish_command(&proc);
 936                return -1;
 937        }
 938
 939        sigchain_push(SIGPIPE, SIG_IGN);
 940
 941        strbuf_init(&buf, 256);
 942
 943        for (r = remote_refs; r; r = r->next) {
 944                if (!r->peer_ref) continue;
 945                if (r->status == REF_STATUS_REJECT_NONFASTFORWARD) continue;
 946                if (r->status == REF_STATUS_REJECT_STALE) continue;
 947                if (r->status == REF_STATUS_UPTODATE) continue;
 948
 949                strbuf_reset(&buf);
 950                strbuf_addf( &buf, "%s %s %s %s\n",
 951                         r->peer_ref->name, oid_to_hex(&r->new_oid),
 952                         r->name, oid_to_hex(&r->old_oid));
 953
 954                if (write_in_full(proc.in, buf.buf, buf.len) < 0) {
 955                        /* We do not mind if a hook does not read all refs. */
 956                        if (errno != EPIPE)
 957                                ret = -1;
 958                        break;
 959                }
 960        }
 961
 962        strbuf_release(&buf);
 963
 964        x = close(proc.in);
 965        if (!ret)
 966                ret = x;
 967
 968        sigchain_pop(SIGPIPE);
 969
 970        x = finish_command(&proc);
 971        if (!ret)
 972                ret = x;
 973
 974        return ret;
 975}
 976
 977int transport_push(struct transport *transport,
 978                   int refspec_nr, const char **refspec, int flags,
 979                   unsigned int *reject_reasons)
 980{
 981        *reject_reasons = 0;
 982        transport_verify_remote_names(refspec_nr, refspec);
 983
 984        if (transport->push) {
 985                /* Maybe FIXME. But no important transport uses this case. */
 986                if (flags & TRANSPORT_PUSH_SET_UPSTREAM)
 987                        die("This transport does not support using --set-upstream");
 988
 989                return transport->push(transport, refspec_nr, refspec, flags);
 990        } else if (transport->push_refs) {
 991                struct ref *remote_refs;
 992                struct ref *local_refs = get_local_heads();
 993                int match_flags = MATCH_REFS_NONE;
 994                int verbose = (transport->verbose > 0);
 995                int quiet = (transport->verbose < 0);
 996                int porcelain = flags & TRANSPORT_PUSH_PORCELAIN;
 997                int pretend = flags & TRANSPORT_PUSH_DRY_RUN;
 998                int push_ret, ret, err;
 999
1000                if (check_push_refs(local_refs, refspec_nr, refspec) < 0)
1001                        return -1;
1002
1003                remote_refs = transport->get_refs_list(transport, 1);
1004
1005                if (flags & TRANSPORT_PUSH_ALL)
1006                        match_flags |= MATCH_REFS_ALL;
1007                if (flags & TRANSPORT_PUSH_MIRROR)
1008                        match_flags |= MATCH_REFS_MIRROR;
1009                if (flags & TRANSPORT_PUSH_PRUNE)
1010                        match_flags |= MATCH_REFS_PRUNE;
1011                if (flags & TRANSPORT_PUSH_FOLLOW_TAGS)
1012                        match_flags |= MATCH_REFS_FOLLOW_TAGS;
1013
1014                if (match_push_refs(local_refs, &remote_refs,
1015                                    refspec_nr, refspec, match_flags)) {
1016                        return -1;
1017                }
1018
1019                if (transport->smart_options &&
1020                    transport->smart_options->cas &&
1021                    !is_empty_cas(transport->smart_options->cas))
1022                        apply_push_cas(transport->smart_options->cas,
1023                                       transport->remote, remote_refs);
1024
1025                set_ref_status_for_push(remote_refs,
1026                        flags & TRANSPORT_PUSH_MIRROR,
1027                        flags & TRANSPORT_PUSH_FORCE);
1028
1029                if (!(flags & TRANSPORT_PUSH_NO_HOOK))
1030                        if (run_pre_push_hook(transport, remote_refs))
1031                                return -1;
1032
1033                if ((flags & (TRANSPORT_RECURSE_SUBMODULES_ON_DEMAND |
1034                              TRANSPORT_RECURSE_SUBMODULES_ONLY)) &&
1035                    !is_bare_repository()) {
1036                        struct ref *ref = remote_refs;
1037                        struct oid_array commits = OID_ARRAY_INIT;
1038
1039                        for (; ref; ref = ref->next)
1040                                if (!is_null_oid(&ref->new_oid))
1041                                        oid_array_append(&commits,
1042                                                          &ref->new_oid);
1043
1044                        if (!push_unpushed_submodules(&commits,
1045                                                      transport->remote,
1046                                                      refspec, refspec_nr,
1047                                                      transport->push_options,
1048                                                      pretend)) {
1049                                oid_array_clear(&commits);
1050                                die("Failed to push all needed submodules!");
1051                        }
1052                        oid_array_clear(&commits);
1053                }
1054
1055                if (((flags & TRANSPORT_RECURSE_SUBMODULES_CHECK) ||
1056                     ((flags & (TRANSPORT_RECURSE_SUBMODULES_ON_DEMAND |
1057                                TRANSPORT_RECURSE_SUBMODULES_ONLY)) &&
1058                      !pretend)) && !is_bare_repository()) {
1059                        struct ref *ref = remote_refs;
1060                        struct string_list needs_pushing = STRING_LIST_INIT_DUP;
1061                        struct oid_array commits = OID_ARRAY_INIT;
1062
1063                        for (; ref; ref = ref->next)
1064                                if (!is_null_oid(&ref->new_oid))
1065                                        oid_array_append(&commits,
1066                                                          &ref->new_oid);
1067
1068                        if (find_unpushed_submodules(&commits, transport->remote->name,
1069                                                &needs_pushing)) {
1070                                oid_array_clear(&commits);
1071                                die_with_unpushed_submodules(&needs_pushing);
1072                        }
1073                        string_list_clear(&needs_pushing, 0);
1074                        oid_array_clear(&commits);
1075                }
1076
1077                if (!(flags & TRANSPORT_RECURSE_SUBMODULES_ONLY))
1078                        push_ret = transport->push_refs(transport, remote_refs, flags);
1079                else
1080                        push_ret = 0;
1081                err = push_had_errors(remote_refs);
1082                ret = push_ret | err;
1083
1084                if (!quiet || err)
1085                        transport_print_push_status(transport->url, remote_refs,
1086                                        verbose | porcelain, porcelain,
1087                                        reject_reasons);
1088
1089                if (flags & TRANSPORT_PUSH_SET_UPSTREAM)
1090                        set_upstreams(transport, remote_refs, pretend);
1091
1092                if (!(flags & (TRANSPORT_PUSH_DRY_RUN |
1093                               TRANSPORT_RECURSE_SUBMODULES_ONLY))) {
1094                        struct ref *ref;
1095                        for (ref = remote_refs; ref; ref = ref->next)
1096                                transport_update_tracking_ref(transport->remote, ref, verbose);
1097                }
1098
1099                if (porcelain && !push_ret)
1100                        puts("Done");
1101                else if (!quiet && !ret && !transport_refs_pushed(remote_refs))
1102                        fprintf(stderr, "Everything up-to-date\n");
1103
1104                return ret;
1105        }
1106        return 1;
1107}
1108
1109const struct ref *transport_get_remote_refs(struct transport *transport)
1110{
1111        if (!transport->got_remote_refs) {
1112                transport->remote_refs = transport->get_refs_list(transport, 0);
1113                transport->got_remote_refs = 1;
1114        }
1115
1116        return transport->remote_refs;
1117}
1118
1119int transport_fetch_refs(struct transport *transport, struct ref *refs)
1120{
1121        int rc;
1122        int nr_heads = 0, nr_alloc = 0, nr_refs = 0;
1123        struct ref **heads = NULL;
1124        struct ref *rm;
1125
1126        for (rm = refs; rm; rm = rm->next) {
1127                nr_refs++;
1128                if (rm->peer_ref &&
1129                    !is_null_oid(&rm->old_oid) &&
1130                    !oidcmp(&rm->peer_ref->old_oid, &rm->old_oid))
1131                        continue;
1132                ALLOC_GROW(heads, nr_heads + 1, nr_alloc);
1133                heads[nr_heads++] = rm;
1134        }
1135
1136        if (!nr_heads) {
1137                /*
1138                 * When deepening of a shallow repository is requested,
1139                 * then local and remote refs are likely to still be equal.
1140                 * Just feed them all to the fetch method in that case.
1141                 * This condition shouldn't be met in a non-deepening fetch
1142                 * (see builtin/fetch.c:quickfetch()).
1143                 */
1144                ALLOC_ARRAY(heads, nr_refs);
1145                for (rm = refs; rm; rm = rm->next)
1146                        heads[nr_heads++] = rm;
1147        }
1148
1149        rc = transport->fetch(transport, nr_heads, heads);
1150
1151        free(heads);
1152        return rc;
1153}
1154
1155void transport_unlock_pack(struct transport *transport)
1156{
1157        if (transport->pack_lockfile) {
1158                unlink_or_warn(transport->pack_lockfile);
1159                FREE_AND_NULL(transport->pack_lockfile);
1160        }
1161}
1162
1163int transport_connect(struct transport *transport, const char *name,
1164                      const char *exec, int fd[2])
1165{
1166        if (transport->connect)
1167                return transport->connect(transport, name, exec, fd);
1168        else
1169                die("Operation not supported by protocol");
1170}
1171
1172int transport_disconnect(struct transport *transport)
1173{
1174        int ret = 0;
1175        if (transport->disconnect)
1176                ret = transport->disconnect(transport);
1177        free(transport);
1178        return ret;
1179}
1180
1181/*
1182 * Strip username (and password) from a URL and return
1183 * it in a newly allocated string.
1184 */
1185char *transport_anonymize_url(const char *url)
1186{
1187        char *scheme_prefix, *anon_part;
1188        size_t anon_len, prefix_len = 0;
1189
1190        anon_part = strchr(url, '@');
1191        if (url_is_local_not_ssh(url) || !anon_part)
1192                goto literal_copy;
1193
1194        anon_len = strlen(++anon_part);
1195        scheme_prefix = strstr(url, "://");
1196        if (!scheme_prefix) {
1197                if (!strchr(anon_part, ':'))
1198                        /* cannot be "me@there:/path/name" */
1199                        goto literal_copy;
1200        } else {
1201                const char *cp;
1202                /* make sure scheme is reasonable */
1203                for (cp = url; cp < scheme_prefix; cp++) {
1204                        switch (*cp) {
1205                                /* RFC 1738 2.1 */
1206                        case '+': case '.': case '-':
1207                                break; /* ok */
1208                        default:
1209                                if (isalnum(*cp))
1210                                        break;
1211                                /* it isn't */
1212                                goto literal_copy;
1213                        }
1214                }
1215                /* @ past the first slash does not count */
1216                cp = strchr(scheme_prefix + 3, '/');
1217                if (cp && cp < anon_part)
1218                        goto literal_copy;
1219                prefix_len = scheme_prefix - url + 3;
1220        }
1221        return xstrfmt("%.*s%.*s", (int)prefix_len, url,
1222                       (int)anon_len, anon_part);
1223literal_copy:
1224        return xstrdup(url);
1225}
1226
1227static void read_alternate_refs(const char *path,
1228                                alternate_ref_fn *cb,
1229                                void *data)
1230{
1231        struct child_process cmd = CHILD_PROCESS_INIT;
1232        struct strbuf line = STRBUF_INIT;
1233        FILE *fh;
1234
1235        cmd.git_cmd = 1;
1236        argv_array_pushf(&cmd.args, "--git-dir=%s", path);
1237        argv_array_push(&cmd.args, "for-each-ref");
1238        argv_array_push(&cmd.args, "--format=%(objectname) %(refname)");
1239        cmd.env = local_repo_env;
1240        cmd.out = -1;
1241
1242        if (start_command(&cmd))
1243                return;
1244
1245        fh = xfdopen(cmd.out, "r");
1246        while (strbuf_getline_lf(&line, fh) != EOF) {
1247                struct object_id oid;
1248
1249                if (get_oid_hex(line.buf, &oid) ||
1250                    line.buf[GIT_SHA1_HEXSZ] != ' ') {
1251                        warning("invalid line while parsing alternate refs: %s",
1252                                line.buf);
1253                        break;
1254                }
1255
1256                cb(line.buf + GIT_SHA1_HEXSZ + 1, &oid, data);
1257        }
1258
1259        fclose(fh);
1260        finish_command(&cmd);
1261}
1262
1263struct alternate_refs_data {
1264        alternate_ref_fn *fn;
1265        void *data;
1266};
1267
1268static int refs_from_alternate_cb(struct alternate_object_database *e,
1269                                  void *data)
1270{
1271        struct strbuf path = STRBUF_INIT;
1272        size_t base_len;
1273        struct alternate_refs_data *cb = data;
1274
1275        if (!strbuf_realpath(&path, e->path, 0))
1276                goto out;
1277        if (!strbuf_strip_suffix(&path, "/objects"))
1278                goto out;
1279        base_len = path.len;
1280
1281        /* Is this a git repository with refs? */
1282        strbuf_addstr(&path, "/refs");
1283        if (!is_directory(path.buf))
1284                goto out;
1285        strbuf_setlen(&path, base_len);
1286
1287        read_alternate_refs(path.buf, cb->fn, cb->data);
1288
1289out:
1290        strbuf_release(&path);
1291        return 0;
1292}
1293
1294void for_each_alternate_ref(alternate_ref_fn fn, void *data)
1295{
1296        struct alternate_refs_data cb;
1297        cb.fn = fn;
1298        cb.data = data;
1299        foreach_alt_odb(refs_from_alternate_cb, &cb);
1300}