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