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