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