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