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