4b89b984c4c55f231801930c998afbd49ca8efe8
   1#include "git-compat-util.h"
   2#include "cache.h"
   3#include "config.h"
   4#include "pkt-line.h"
   5#include "quote.h"
   6#include "refs.h"
   7#include "run-command.h"
   8#include "remote.h"
   9#include "connect.h"
  10#include "url.h"
  11#include "string-list.h"
  12#include "sha1-array.h"
  13#include "transport.h"
  14#include "strbuf.h"
  15#include "protocol.h"
  16
  17static char *server_capabilities;
  18static const char *parse_feature_value(const char *, const char *, int *);
  19
  20static int check_ref(const char *name, unsigned int flags)
  21{
  22        if (!flags)
  23                return 1;
  24
  25        if (!skip_prefix(name, "refs/", &name))
  26                return 0;
  27
  28        /* REF_NORMAL means that we don't want the magic fake tag refs */
  29        if ((flags & REF_NORMAL) && check_refname_format(name, 0))
  30                return 0;
  31
  32        /* REF_HEADS means that we want regular branch heads */
  33        if ((flags & REF_HEADS) && starts_with(name, "heads/"))
  34                return 1;
  35
  36        /* REF_TAGS means that we want tags */
  37        if ((flags & REF_TAGS) && starts_with(name, "tags/"))
  38                return 1;
  39
  40        /* All type bits clear means that we are ok with anything */
  41        return !(flags & ~REF_NORMAL);
  42}
  43
  44int check_ref_type(const struct ref *ref, int flags)
  45{
  46        return check_ref(ref->name, flags);
  47}
  48
  49static void die_initial_contact(int unexpected)
  50{
  51        /*
  52         * A hang-up after seeing some response from the other end
  53         * means that it is unexpected, as we know the other end is
  54         * willing to talk to us.  A hang-up before seeing any
  55         * response does not necessarily mean an ACL problem, though.
  56         */
  57        if (unexpected)
  58                die(_("The remote end hung up upon initial contact"));
  59        else
  60                die(_("Could not read from remote repository.\n\n"
  61                      "Please make sure you have the correct access rights\n"
  62                      "and the repository exists."));
  63}
  64
  65enum protocol_version discover_version(struct packet_reader *reader)
  66{
  67        enum protocol_version version = protocol_unknown_version;
  68
  69        /*
  70         * Peek the first line of the server's response to
  71         * determine the protocol version the server is speaking.
  72         */
  73        switch (packet_reader_peek(reader)) {
  74        case PACKET_READ_EOF:
  75                die_initial_contact(0);
  76        case PACKET_READ_FLUSH:
  77        case PACKET_READ_DELIM:
  78                version = protocol_v0;
  79                break;
  80        case PACKET_READ_NORMAL:
  81                version = determine_protocol_version_client(reader->line);
  82                break;
  83        }
  84
  85        switch (version) {
  86        case protocol_v2:
  87                die("support for protocol v2 not implemented yet");
  88                break;
  89        case protocol_v1:
  90                /* Read the peeked version line */
  91                packet_reader_read(reader);
  92                break;
  93        case protocol_v0:
  94                break;
  95        case protocol_unknown_version:
  96                BUG("unknown protocol version");
  97        }
  98
  99        return version;
 100}
 101
 102static void parse_one_symref_info(struct string_list *symref, const char *val, int len)
 103{
 104        char *sym, *target;
 105        struct string_list_item *item;
 106
 107        if (!len)
 108                return; /* just "symref" */
 109        /* e.g. "symref=HEAD:refs/heads/master" */
 110        sym = xmemdupz(val, len);
 111        target = strchr(sym, ':');
 112        if (!target)
 113                /* just "symref=something" */
 114                goto reject;
 115        *(target++) = '\0';
 116        if (check_refname_format(sym, REFNAME_ALLOW_ONELEVEL) ||
 117            check_refname_format(target, REFNAME_ALLOW_ONELEVEL))
 118                /* "symref=bogus:pair */
 119                goto reject;
 120        item = string_list_append_nodup(symref, sym);
 121        item->util = target;
 122        return;
 123reject:
 124        free(sym);
 125        return;
 126}
 127
 128static void annotate_refs_with_symref_info(struct ref *ref)
 129{
 130        struct string_list symref = STRING_LIST_INIT_DUP;
 131        const char *feature_list = server_capabilities;
 132
 133        while (feature_list) {
 134                int len;
 135                const char *val;
 136
 137                val = parse_feature_value(feature_list, "symref", &len);
 138                if (!val)
 139                        break;
 140                parse_one_symref_info(&symref, val, len);
 141                feature_list = val + 1;
 142        }
 143        string_list_sort(&symref);
 144
 145        for (; ref; ref = ref->next) {
 146                struct string_list_item *item;
 147                item = string_list_lookup(&symref, ref->name);
 148                if (!item)
 149                        continue;
 150                ref->symref = xstrdup((char *)item->util);
 151        }
 152        string_list_clear(&symref, 0);
 153}
 154
 155static void process_capabilities(const char *line, int *len)
 156{
 157        int nul_location = strlen(line);
 158        if (nul_location == *len)
 159                return;
 160        server_capabilities = xstrdup(line + nul_location + 1);
 161        *len = nul_location;
 162}
 163
 164static int process_dummy_ref(const char *line)
 165{
 166        struct object_id oid;
 167        const char *name;
 168
 169        if (parse_oid_hex(line, &oid, &name))
 170                return 0;
 171        if (*name != ' ')
 172                return 0;
 173        name++;
 174
 175        return !oidcmp(&null_oid, &oid) && !strcmp(name, "capabilities^{}");
 176}
 177
 178static void check_no_capabilities(const char *line, int len)
 179{
 180        if (strlen(line) != len)
 181                warning("Ignoring capabilities after first line '%s'",
 182                        line + strlen(line));
 183}
 184
 185static int process_ref(const char *line, int len, struct ref ***list,
 186                       unsigned int flags, struct oid_array *extra_have)
 187{
 188        struct object_id old_oid;
 189        const char *name;
 190
 191        if (parse_oid_hex(line, &old_oid, &name))
 192                return 0;
 193        if (*name != ' ')
 194                return 0;
 195        name++;
 196
 197        if (extra_have && !strcmp(name, ".have")) {
 198                oid_array_append(extra_have, &old_oid);
 199        } else if (!strcmp(name, "capabilities^{}")) {
 200                die("protocol error: unexpected capabilities^{}");
 201        } else if (check_ref(name, flags)) {
 202                struct ref *ref = alloc_ref(name);
 203                oidcpy(&ref->old_oid, &old_oid);
 204                **list = ref;
 205                *list = &ref->next;
 206        }
 207        check_no_capabilities(line, len);
 208        return 1;
 209}
 210
 211static int process_shallow(const char *line, int len,
 212                           struct oid_array *shallow_points)
 213{
 214        const char *arg;
 215        struct object_id old_oid;
 216
 217        if (!skip_prefix(line, "shallow ", &arg))
 218                return 0;
 219
 220        if (get_oid_hex(arg, &old_oid))
 221                die("protocol error: expected shallow sha-1, got '%s'", arg);
 222        if (!shallow_points)
 223                die("repository on the other end cannot be shallow");
 224        oid_array_append(shallow_points, &old_oid);
 225        check_no_capabilities(line, len);
 226        return 1;
 227}
 228
 229enum get_remote_heads_state {
 230        EXPECTING_FIRST_REF = 0,
 231        EXPECTING_REF,
 232        EXPECTING_SHALLOW,
 233        EXPECTING_DONE,
 234};
 235
 236/*
 237 * Read all the refs from the other end
 238 */
 239struct ref **get_remote_heads(struct packet_reader *reader,
 240                              struct ref **list, unsigned int flags,
 241                              struct oid_array *extra_have,
 242                              struct oid_array *shallow_points)
 243{
 244        struct ref **orig_list = list;
 245        int len = 0;
 246        enum get_remote_heads_state state = EXPECTING_FIRST_REF;
 247        const char *arg;
 248
 249        *list = NULL;
 250
 251        while (state != EXPECTING_DONE) {
 252                switch (packet_reader_read(reader)) {
 253                case PACKET_READ_EOF:
 254                        die_initial_contact(1);
 255                case PACKET_READ_NORMAL:
 256                        len = reader->pktlen;
 257                        if (len > 4 && skip_prefix(reader->line, "ERR ", &arg))
 258                                die("remote error: %s", arg);
 259                        break;
 260                case PACKET_READ_FLUSH:
 261                        state = EXPECTING_DONE;
 262                        break;
 263                case PACKET_READ_DELIM:
 264                        die("invalid packet");
 265                }
 266
 267                switch (state) {
 268                case EXPECTING_FIRST_REF:
 269                        process_capabilities(reader->line, &len);
 270                        if (process_dummy_ref(reader->line)) {
 271                                state = EXPECTING_SHALLOW;
 272                                break;
 273                        }
 274                        state = EXPECTING_REF;
 275                        /* fallthrough */
 276                case EXPECTING_REF:
 277                        if (process_ref(reader->line, len, &list, flags, extra_have))
 278                                break;
 279                        state = EXPECTING_SHALLOW;
 280                        /* fallthrough */
 281                case EXPECTING_SHALLOW:
 282                        if (process_shallow(reader->line, len, shallow_points))
 283                                break;
 284                        die("protocol error: unexpected '%s'", reader->line);
 285                case EXPECTING_DONE:
 286                        break;
 287                }
 288        }
 289
 290        annotate_refs_with_symref_info(*orig_list);
 291
 292        return list;
 293}
 294
 295static const char *parse_feature_value(const char *feature_list, const char *feature, int *lenp)
 296{
 297        int len;
 298
 299        if (!feature_list)
 300                return NULL;
 301
 302        len = strlen(feature);
 303        while (*feature_list) {
 304                const char *found = strstr(feature_list, feature);
 305                if (!found)
 306                        return NULL;
 307                if (feature_list == found || isspace(found[-1])) {
 308                        const char *value = found + len;
 309                        /* feature with no value (e.g., "thin-pack") */
 310                        if (!*value || isspace(*value)) {
 311                                if (lenp)
 312                                        *lenp = 0;
 313                                return value;
 314                        }
 315                        /* feature with a value (e.g., "agent=git/1.2.3") */
 316                        else if (*value == '=') {
 317                                value++;
 318                                if (lenp)
 319                                        *lenp = strcspn(value, " \t\n");
 320                                return value;
 321                        }
 322                        /*
 323                         * otherwise we matched a substring of another feature;
 324                         * keep looking
 325                         */
 326                }
 327                feature_list = found + 1;
 328        }
 329        return NULL;
 330}
 331
 332int parse_feature_request(const char *feature_list, const char *feature)
 333{
 334        return !!parse_feature_value(feature_list, feature, NULL);
 335}
 336
 337const char *server_feature_value(const char *feature, int *len)
 338{
 339        return parse_feature_value(server_capabilities, feature, len);
 340}
 341
 342int server_supports(const char *feature)
 343{
 344        return !!server_feature_value(feature, NULL);
 345}
 346
 347enum protocol {
 348        PROTO_LOCAL = 1,
 349        PROTO_FILE,
 350        PROTO_SSH,
 351        PROTO_GIT
 352};
 353
 354int url_is_local_not_ssh(const char *url)
 355{
 356        const char *colon = strchr(url, ':');
 357        const char *slash = strchr(url, '/');
 358        return !colon || (slash && slash < colon) ||
 359                has_dos_drive_prefix(url);
 360}
 361
 362static const char *prot_name(enum protocol protocol)
 363{
 364        switch (protocol) {
 365                case PROTO_LOCAL:
 366                case PROTO_FILE:
 367                        return "file";
 368                case PROTO_SSH:
 369                        return "ssh";
 370                case PROTO_GIT:
 371                        return "git";
 372                default:
 373                        return "unknown protocol";
 374        }
 375}
 376
 377static enum protocol get_protocol(const char *name)
 378{
 379        if (!strcmp(name, "ssh"))
 380                return PROTO_SSH;
 381        if (!strcmp(name, "git"))
 382                return PROTO_GIT;
 383        if (!strcmp(name, "git+ssh")) /* deprecated - do not use */
 384                return PROTO_SSH;
 385        if (!strcmp(name, "ssh+git")) /* deprecated - do not use */
 386                return PROTO_SSH;
 387        if (!strcmp(name, "file"))
 388                return PROTO_FILE;
 389        die("I don't handle protocol '%s'", name);
 390}
 391
 392static char *host_end(char **hoststart, int removebrackets)
 393{
 394        char *host = *hoststart;
 395        char *end;
 396        char *start = strstr(host, "@[");
 397        if (start)
 398                start++; /* Jump over '@' */
 399        else
 400                start = host;
 401        if (start[0] == '[') {
 402                end = strchr(start + 1, ']');
 403                if (end) {
 404                        if (removebrackets) {
 405                                *end = 0;
 406                                memmove(start, start + 1, end - start);
 407                                end++;
 408                        }
 409                } else
 410                        end = host;
 411        } else
 412                end = host;
 413        return end;
 414}
 415
 416#define STR_(s) # s
 417#define STR(s)  STR_(s)
 418
 419static void get_host_and_port(char **host, const char **port)
 420{
 421        char *colon, *end;
 422        end = host_end(host, 1);
 423        colon = strchr(end, ':');
 424        if (colon) {
 425                long portnr = strtol(colon + 1, &end, 10);
 426                if (end != colon + 1 && *end == '\0' && 0 <= portnr && portnr < 65536) {
 427                        *colon = 0;
 428                        *port = colon + 1;
 429                } else if (!colon[1]) {
 430                        *colon = 0;
 431                }
 432        }
 433}
 434
 435static void enable_keepalive(int sockfd)
 436{
 437        int ka = 1;
 438
 439        if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &ka, sizeof(ka)) < 0)
 440                fprintf(stderr, "unable to set SO_KEEPALIVE on socket: %s\n",
 441                        strerror(errno));
 442}
 443
 444#ifndef NO_IPV6
 445
 446static const char *ai_name(const struct addrinfo *ai)
 447{
 448        static char addr[NI_MAXHOST];
 449        if (getnameinfo(ai->ai_addr, ai->ai_addrlen, addr, sizeof(addr), NULL, 0,
 450                        NI_NUMERICHOST) != 0)
 451                xsnprintf(addr, sizeof(addr), "(unknown)");
 452
 453        return addr;
 454}
 455
 456/*
 457 * Returns a connected socket() fd, or else die()s.
 458 */
 459static int git_tcp_connect_sock(char *host, int flags)
 460{
 461        struct strbuf error_message = STRBUF_INIT;
 462        int sockfd = -1;
 463        const char *port = STR(DEFAULT_GIT_PORT);
 464        struct addrinfo hints, *ai0, *ai;
 465        int gai;
 466        int cnt = 0;
 467
 468        get_host_and_port(&host, &port);
 469        if (!*port)
 470                port = "<none>";
 471
 472        memset(&hints, 0, sizeof(hints));
 473        if (flags & CONNECT_IPV4)
 474                hints.ai_family = AF_INET;
 475        else if (flags & CONNECT_IPV6)
 476                hints.ai_family = AF_INET6;
 477        hints.ai_socktype = SOCK_STREAM;
 478        hints.ai_protocol = IPPROTO_TCP;
 479
 480        if (flags & CONNECT_VERBOSE)
 481                fprintf(stderr, "Looking up %s ... ", host);
 482
 483        gai = getaddrinfo(host, port, &hints, &ai);
 484        if (gai)
 485                die("Unable to look up %s (port %s) (%s)", host, port, gai_strerror(gai));
 486
 487        if (flags & CONNECT_VERBOSE)
 488                fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);
 489
 490        for (ai0 = ai; ai; ai = ai->ai_next, cnt++) {
 491                sockfd = socket(ai->ai_family,
 492                                ai->ai_socktype, ai->ai_protocol);
 493                if ((sockfd < 0) ||
 494                    (connect(sockfd, ai->ai_addr, ai->ai_addrlen) < 0)) {
 495                        strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
 496                                    host, cnt, ai_name(ai), strerror(errno));
 497                        if (0 <= sockfd)
 498                                close(sockfd);
 499                        sockfd = -1;
 500                        continue;
 501                }
 502                if (flags & CONNECT_VERBOSE)
 503                        fprintf(stderr, "%s ", ai_name(ai));
 504                break;
 505        }
 506
 507        freeaddrinfo(ai0);
 508
 509        if (sockfd < 0)
 510                die("unable to connect to %s:\n%s", host, error_message.buf);
 511
 512        enable_keepalive(sockfd);
 513
 514        if (flags & CONNECT_VERBOSE)
 515                fprintf(stderr, "done.\n");
 516
 517        strbuf_release(&error_message);
 518
 519        return sockfd;
 520}
 521
 522#else /* NO_IPV6 */
 523
 524/*
 525 * Returns a connected socket() fd, or else die()s.
 526 */
 527static int git_tcp_connect_sock(char *host, int flags)
 528{
 529        struct strbuf error_message = STRBUF_INIT;
 530        int sockfd = -1;
 531        const char *port = STR(DEFAULT_GIT_PORT);
 532        char *ep;
 533        struct hostent *he;
 534        struct sockaddr_in sa;
 535        char **ap;
 536        unsigned int nport;
 537        int cnt;
 538
 539        get_host_and_port(&host, &port);
 540
 541        if (flags & CONNECT_VERBOSE)
 542                fprintf(stderr, "Looking up %s ... ", host);
 543
 544        he = gethostbyname(host);
 545        if (!he)
 546                die("Unable to look up %s (%s)", host, hstrerror(h_errno));
 547        nport = strtoul(port, &ep, 10);
 548        if ( ep == port || *ep ) {
 549                /* Not numeric */
 550                struct servent *se = getservbyname(port,"tcp");
 551                if ( !se )
 552                        die("Unknown port %s", port);
 553                nport = se->s_port;
 554        }
 555
 556        if (flags & CONNECT_VERBOSE)
 557                fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);
 558
 559        for (cnt = 0, ap = he->h_addr_list; *ap; ap++, cnt++) {
 560                memset(&sa, 0, sizeof sa);
 561                sa.sin_family = he->h_addrtype;
 562                sa.sin_port = htons(nport);
 563                memcpy(&sa.sin_addr, *ap, he->h_length);
 564
 565                sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
 566                if ((sockfd < 0) ||
 567                    connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
 568                        strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
 569                                host,
 570                                cnt,
 571                                inet_ntoa(*(struct in_addr *)&sa.sin_addr),
 572                                strerror(errno));
 573                        if (0 <= sockfd)
 574                                close(sockfd);
 575                        sockfd = -1;
 576                        continue;
 577                }
 578                if (flags & CONNECT_VERBOSE)
 579                        fprintf(stderr, "%s ",
 580                                inet_ntoa(*(struct in_addr *)&sa.sin_addr));
 581                break;
 582        }
 583
 584        if (sockfd < 0)
 585                die("unable to connect to %s:\n%s", host, error_message.buf);
 586
 587        enable_keepalive(sockfd);
 588
 589        if (flags & CONNECT_VERBOSE)
 590                fprintf(stderr, "done.\n");
 591
 592        return sockfd;
 593}
 594
 595#endif /* NO_IPV6 */
 596
 597
 598/*
 599 * Dummy child_process returned by git_connect() if the transport protocol
 600 * does not need fork(2).
 601 */
 602static struct child_process no_fork = CHILD_PROCESS_INIT;
 603
 604int git_connection_is_socket(struct child_process *conn)
 605{
 606        return conn == &no_fork;
 607}
 608
 609static struct child_process *git_tcp_connect(int fd[2], char *host, int flags)
 610{
 611        int sockfd = git_tcp_connect_sock(host, flags);
 612
 613        fd[0] = sockfd;
 614        fd[1] = dup(sockfd);
 615
 616        return &no_fork;
 617}
 618
 619
 620static char *git_proxy_command;
 621
 622static int git_proxy_command_options(const char *var, const char *value,
 623                void *cb)
 624{
 625        if (!strcmp(var, "core.gitproxy")) {
 626                const char *for_pos;
 627                int matchlen = -1;
 628                int hostlen;
 629                const char *rhost_name = cb;
 630                int rhost_len = strlen(rhost_name);
 631
 632                if (git_proxy_command)
 633                        return 0;
 634                if (!value)
 635                        return config_error_nonbool(var);
 636                /* [core]
 637                 * ;# matches www.kernel.org as well
 638                 * gitproxy = netcatter-1 for kernel.org
 639                 * gitproxy = netcatter-2 for sample.xz
 640                 * gitproxy = netcatter-default
 641                 */
 642                for_pos = strstr(value, " for ");
 643                if (!for_pos)
 644                        /* matches everybody */
 645                        matchlen = strlen(value);
 646                else {
 647                        hostlen = strlen(for_pos + 5);
 648                        if (rhost_len < hostlen)
 649                                matchlen = -1;
 650                        else if (!strncmp(for_pos + 5,
 651                                          rhost_name + rhost_len - hostlen,
 652                                          hostlen) &&
 653                                 ((rhost_len == hostlen) ||
 654                                  rhost_name[rhost_len - hostlen -1] == '.'))
 655                                matchlen = for_pos - value;
 656                        else
 657                                matchlen = -1;
 658                }
 659                if (0 <= matchlen) {
 660                        /* core.gitproxy = none for kernel.org */
 661                        if (matchlen == 4 &&
 662                            !memcmp(value, "none", 4))
 663                                matchlen = 0;
 664                        git_proxy_command = xmemdupz(value, matchlen);
 665                }
 666                return 0;
 667        }
 668
 669        return git_default_config(var, value, cb);
 670}
 671
 672static int git_use_proxy(const char *host)
 673{
 674        git_proxy_command = getenv("GIT_PROXY_COMMAND");
 675        git_config(git_proxy_command_options, (void*)host);
 676        return (git_proxy_command && *git_proxy_command);
 677}
 678
 679static struct child_process *git_proxy_connect(int fd[2], char *host)
 680{
 681        const char *port = STR(DEFAULT_GIT_PORT);
 682        struct child_process *proxy;
 683
 684        get_host_and_port(&host, &port);
 685
 686        if (looks_like_command_line_option(host))
 687                die("strange hostname '%s' blocked", host);
 688        if (looks_like_command_line_option(port))
 689                die("strange port '%s' blocked", port);
 690
 691        proxy = xmalloc(sizeof(*proxy));
 692        child_process_init(proxy);
 693        argv_array_push(&proxy->args, git_proxy_command);
 694        argv_array_push(&proxy->args, host);
 695        argv_array_push(&proxy->args, port);
 696        proxy->in = -1;
 697        proxy->out = -1;
 698        if (start_command(proxy))
 699                die("cannot start proxy %s", git_proxy_command);
 700        fd[0] = proxy->out; /* read from proxy stdout */
 701        fd[1] = proxy->in;  /* write to proxy stdin */
 702        return proxy;
 703}
 704
 705static char *get_port(char *host)
 706{
 707        char *end;
 708        char *p = strchr(host, ':');
 709
 710        if (p) {
 711                long port = strtol(p + 1, &end, 10);
 712                if (end != p + 1 && *end == '\0' && 0 <= port && port < 65536) {
 713                        *p = '\0';
 714                        return p+1;
 715                }
 716        }
 717
 718        return NULL;
 719}
 720
 721/*
 722 * Extract protocol and relevant parts from the specified connection URL.
 723 * The caller must free() the returned strings.
 724 */
 725static enum protocol parse_connect_url(const char *url_orig, char **ret_host,
 726                                       char **ret_path)
 727{
 728        char *url;
 729        char *host, *path;
 730        char *end;
 731        int separator = '/';
 732        enum protocol protocol = PROTO_LOCAL;
 733
 734        if (is_url(url_orig))
 735                url = url_decode(url_orig);
 736        else
 737                url = xstrdup(url_orig);
 738
 739        host = strstr(url, "://");
 740        if (host) {
 741                *host = '\0';
 742                protocol = get_protocol(url);
 743                host += 3;
 744        } else {
 745                host = url;
 746                if (!url_is_local_not_ssh(url)) {
 747                        protocol = PROTO_SSH;
 748                        separator = ':';
 749                }
 750        }
 751
 752        /*
 753         * Don't do destructive transforms as protocol code does
 754         * '[]' unwrapping in get_host_and_port()
 755         */
 756        end = host_end(&host, 0);
 757
 758        if (protocol == PROTO_LOCAL)
 759                path = end;
 760        else if (protocol == PROTO_FILE && has_dos_drive_prefix(end))
 761                path = end; /* "file://$(pwd)" may be "file://C:/projects/repo" */
 762        else
 763                path = strchr(end, separator);
 764
 765        if (!path || !*path)
 766                die("No path specified. See 'man git-pull' for valid url syntax");
 767
 768        /*
 769         * null-terminate hostname and point path to ~ for URL's like this:
 770         *    ssh://host.xz/~user/repo
 771         */
 772
 773        end = path; /* Need to \0 terminate host here */
 774        if (separator == ':')
 775                path++; /* path starts after ':' */
 776        if (protocol == PROTO_GIT || protocol == PROTO_SSH) {
 777                if (path[1] == '~')
 778                        path++;
 779        }
 780
 781        path = xstrdup(path);
 782        *end = '\0';
 783
 784        *ret_host = xstrdup(host);
 785        *ret_path = path;
 786        free(url);
 787        return protocol;
 788}
 789
 790static const char *get_ssh_command(void)
 791{
 792        const char *ssh;
 793
 794        if ((ssh = getenv("GIT_SSH_COMMAND")))
 795                return ssh;
 796
 797        if (!git_config_get_string_const("core.sshcommand", &ssh))
 798                return ssh;
 799
 800        return NULL;
 801}
 802
 803enum ssh_variant {
 804        VARIANT_AUTO,
 805        VARIANT_SIMPLE,
 806        VARIANT_SSH,
 807        VARIANT_PLINK,
 808        VARIANT_PUTTY,
 809        VARIANT_TORTOISEPLINK,
 810};
 811
 812static void override_ssh_variant(enum ssh_variant *ssh_variant)
 813{
 814        const char *variant = getenv("GIT_SSH_VARIANT");
 815
 816        if (!variant && git_config_get_string_const("ssh.variant", &variant))
 817                return;
 818
 819        if (!strcmp(variant, "auto"))
 820                *ssh_variant = VARIANT_AUTO;
 821        else if (!strcmp(variant, "plink"))
 822                *ssh_variant = VARIANT_PLINK;
 823        else if (!strcmp(variant, "putty"))
 824                *ssh_variant = VARIANT_PUTTY;
 825        else if (!strcmp(variant, "tortoiseplink"))
 826                *ssh_variant = VARIANT_TORTOISEPLINK;
 827        else if (!strcmp(variant, "simple"))
 828                *ssh_variant = VARIANT_SIMPLE;
 829        else
 830                *ssh_variant = VARIANT_SSH;
 831}
 832
 833static enum ssh_variant determine_ssh_variant(const char *ssh_command,
 834                                              int is_cmdline)
 835{
 836        enum ssh_variant ssh_variant = VARIANT_AUTO;
 837        const char *variant;
 838        char *p = NULL;
 839
 840        override_ssh_variant(&ssh_variant);
 841
 842        if (ssh_variant != VARIANT_AUTO)
 843                return ssh_variant;
 844
 845        if (!is_cmdline) {
 846                p = xstrdup(ssh_command);
 847                variant = basename(p);
 848        } else {
 849                const char **ssh_argv;
 850
 851                p = xstrdup(ssh_command);
 852                if (split_cmdline(p, &ssh_argv) > 0) {
 853                        variant = basename((char *)ssh_argv[0]);
 854                        /*
 855                         * At this point, variant points into the buffer
 856                         * referenced by p, hence we do not need ssh_argv
 857                         * any longer.
 858                         */
 859                        free(ssh_argv);
 860                } else {
 861                        free(p);
 862                        return ssh_variant;
 863                }
 864        }
 865
 866        if (!strcasecmp(variant, "ssh") ||
 867            !strcasecmp(variant, "ssh.exe"))
 868                ssh_variant = VARIANT_SSH;
 869        else if (!strcasecmp(variant, "plink") ||
 870                 !strcasecmp(variant, "plink.exe"))
 871                ssh_variant = VARIANT_PLINK;
 872        else if (!strcasecmp(variant, "tortoiseplink") ||
 873                 !strcasecmp(variant, "tortoiseplink.exe"))
 874                ssh_variant = VARIANT_TORTOISEPLINK;
 875
 876        free(p);
 877        return ssh_variant;
 878}
 879
 880/*
 881 * Open a connection using Git's native protocol.
 882 *
 883 * The caller is responsible for freeing hostandport, but this function may
 884 * modify it (for example, to truncate it to remove the port part).
 885 */
 886static struct child_process *git_connect_git(int fd[2], char *hostandport,
 887                                             const char *path, const char *prog,
 888                                             int flags)
 889{
 890        struct child_process *conn;
 891        struct strbuf request = STRBUF_INIT;
 892        /*
 893         * Set up virtual host information based on where we will
 894         * connect, unless the user has overridden us in
 895         * the environment.
 896         */
 897        char *target_host = getenv("GIT_OVERRIDE_VIRTUAL_HOST");
 898        if (target_host)
 899                target_host = xstrdup(target_host);
 900        else
 901                target_host = xstrdup(hostandport);
 902
 903        transport_check_allowed("git");
 904
 905        /*
 906         * These underlying connection commands die() if they
 907         * cannot connect.
 908         */
 909        if (git_use_proxy(hostandport))
 910                conn = git_proxy_connect(fd, hostandport);
 911        else
 912                conn = git_tcp_connect(fd, hostandport, flags);
 913        /*
 914         * Separate original protocol components prog and path
 915         * from extended host header with a NUL byte.
 916         *
 917         * Note: Do not add any other headers here!  Doing so
 918         * will cause older git-daemon servers to crash.
 919         */
 920        strbuf_addf(&request,
 921                    "%s %s%chost=%s%c",
 922                    prog, path, 0,
 923                    target_host, 0);
 924
 925        /* If using a new version put that stuff here after a second null byte */
 926        if (get_protocol_version_config() > 0) {
 927                strbuf_addch(&request, '\0');
 928                strbuf_addf(&request, "version=%d%c",
 929                            get_protocol_version_config(), '\0');
 930        }
 931
 932        packet_write(fd[1], request.buf, request.len);
 933
 934        free(target_host);
 935        strbuf_release(&request);
 936        return conn;
 937}
 938
 939/*
 940 * Append the appropriate environment variables to `env` and options to
 941 * `args` for running ssh in Git's SSH-tunneled transport.
 942 */
 943static void push_ssh_options(struct argv_array *args, struct argv_array *env,
 944                             enum ssh_variant variant, const char *port,
 945                             int flags)
 946{
 947        if (variant == VARIANT_SSH &&
 948            get_protocol_version_config() > 0) {
 949                argv_array_push(args, "-o");
 950                argv_array_push(args, "SendEnv=" GIT_PROTOCOL_ENVIRONMENT);
 951                argv_array_pushf(env, GIT_PROTOCOL_ENVIRONMENT "=version=%d",
 952                                 get_protocol_version_config());
 953        }
 954
 955        if (flags & CONNECT_IPV4) {
 956                switch (variant) {
 957                case VARIANT_AUTO:
 958                        BUG("VARIANT_AUTO passed to push_ssh_options");
 959                case VARIANT_SIMPLE:
 960                        die("ssh variant 'simple' does not support -4");
 961                case VARIANT_SSH:
 962                case VARIANT_PLINK:
 963                case VARIANT_PUTTY:
 964                case VARIANT_TORTOISEPLINK:
 965                        argv_array_push(args, "-4");
 966                }
 967        } else if (flags & CONNECT_IPV6) {
 968                switch (variant) {
 969                case VARIANT_AUTO:
 970                        BUG("VARIANT_AUTO passed to push_ssh_options");
 971                case VARIANT_SIMPLE:
 972                        die("ssh variant 'simple' does not support -6");
 973                case VARIANT_SSH:
 974                case VARIANT_PLINK:
 975                case VARIANT_PUTTY:
 976                case VARIANT_TORTOISEPLINK:
 977                        argv_array_push(args, "-6");
 978                }
 979        }
 980
 981        if (variant == VARIANT_TORTOISEPLINK)
 982                argv_array_push(args, "-batch");
 983
 984        if (port) {
 985                switch (variant) {
 986                case VARIANT_AUTO:
 987                        BUG("VARIANT_AUTO passed to push_ssh_options");
 988                case VARIANT_SIMPLE:
 989                        die("ssh variant 'simple' does not support setting port");
 990                case VARIANT_SSH:
 991                        argv_array_push(args, "-p");
 992                        break;
 993                case VARIANT_PLINK:
 994                case VARIANT_PUTTY:
 995                case VARIANT_TORTOISEPLINK:
 996                        argv_array_push(args, "-P");
 997                }
 998
 999                argv_array_push(args, port);
1000        }
1001}
1002
1003/* Prepare a child_process for use by Git's SSH-tunneled transport. */
1004static void fill_ssh_args(struct child_process *conn, const char *ssh_host,
1005                          const char *port, int flags)
1006{
1007        const char *ssh;
1008        enum ssh_variant variant;
1009
1010        if (looks_like_command_line_option(ssh_host))
1011                die("strange hostname '%s' blocked", ssh_host);
1012
1013        ssh = get_ssh_command();
1014        if (ssh) {
1015                variant = determine_ssh_variant(ssh, 1);
1016        } else {
1017                /*
1018                 * GIT_SSH is the no-shell version of
1019                 * GIT_SSH_COMMAND (and must remain so for
1020                 * historical compatibility).
1021                 */
1022                conn->use_shell = 0;
1023
1024                ssh = getenv("GIT_SSH");
1025                if (!ssh)
1026                        ssh = "ssh";
1027                variant = determine_ssh_variant(ssh, 0);
1028        }
1029
1030        if (variant == VARIANT_AUTO) {
1031                struct child_process detect = CHILD_PROCESS_INIT;
1032
1033                detect.use_shell = conn->use_shell;
1034                detect.no_stdin = detect.no_stdout = detect.no_stderr = 1;
1035
1036                argv_array_push(&detect.args, ssh);
1037                argv_array_push(&detect.args, "-G");
1038                push_ssh_options(&detect.args, &detect.env_array,
1039                                 VARIANT_SSH, port, flags);
1040                argv_array_push(&detect.args, ssh_host);
1041
1042                variant = run_command(&detect) ? VARIANT_SIMPLE : VARIANT_SSH;
1043        }
1044
1045        argv_array_push(&conn->args, ssh);
1046        push_ssh_options(&conn->args, &conn->env_array, variant, port, flags);
1047        argv_array_push(&conn->args, ssh_host);
1048}
1049
1050/*
1051 * This returns the dummy child_process `no_fork` if the transport protocol
1052 * does not need fork(2), or a struct child_process object if it does.  Once
1053 * done, finish the connection with finish_connect() with the value returned
1054 * from this function (it is safe to call finish_connect() with NULL to
1055 * support the former case).
1056 *
1057 * If it returns, the connect is successful; it just dies on errors (this
1058 * will hopefully be changed in a libification effort, to return NULL when
1059 * the connection failed).
1060 */
1061struct child_process *git_connect(int fd[2], const char *url,
1062                                  const char *prog, int flags)
1063{
1064        char *hostandport, *path;
1065        struct child_process *conn;
1066        enum protocol protocol;
1067
1068        /* Without this we cannot rely on waitpid() to tell
1069         * what happened to our children.
1070         */
1071        signal(SIGCHLD, SIG_DFL);
1072
1073        protocol = parse_connect_url(url, &hostandport, &path);
1074        if ((flags & CONNECT_DIAG_URL) && (protocol != PROTO_SSH)) {
1075                printf("Diag: url=%s\n", url ? url : "NULL");
1076                printf("Diag: protocol=%s\n", prot_name(protocol));
1077                printf("Diag: hostandport=%s\n", hostandport ? hostandport : "NULL");
1078                printf("Diag: path=%s\n", path ? path : "NULL");
1079                conn = NULL;
1080        } else if (protocol == PROTO_GIT) {
1081                conn = git_connect_git(fd, hostandport, path, prog, flags);
1082        } else {
1083                struct strbuf cmd = STRBUF_INIT;
1084                const char *const *var;
1085
1086                conn = xmalloc(sizeof(*conn));
1087                child_process_init(conn);
1088
1089                if (looks_like_command_line_option(path))
1090                        die("strange pathname '%s' blocked", path);
1091
1092                strbuf_addstr(&cmd, prog);
1093                strbuf_addch(&cmd, ' ');
1094                sq_quote_buf(&cmd, path);
1095
1096                /* remove repo-local variables from the environment */
1097                for (var = local_repo_env; *var; var++)
1098                        argv_array_push(&conn->env_array, *var);
1099
1100                conn->use_shell = 1;
1101                conn->in = conn->out = -1;
1102                if (protocol == PROTO_SSH) {
1103                        char *ssh_host = hostandport;
1104                        const char *port = NULL;
1105                        transport_check_allowed("ssh");
1106                        get_host_and_port(&ssh_host, &port);
1107
1108                        if (!port)
1109                                port = get_port(ssh_host);
1110
1111                        if (flags & CONNECT_DIAG_URL) {
1112                                printf("Diag: url=%s\n", url ? url : "NULL");
1113                                printf("Diag: protocol=%s\n", prot_name(protocol));
1114                                printf("Diag: userandhost=%s\n", ssh_host ? ssh_host : "NULL");
1115                                printf("Diag: port=%s\n", port ? port : "NONE");
1116                                printf("Diag: path=%s\n", path ? path : "NULL");
1117
1118                                free(hostandport);
1119                                free(path);
1120                                free(conn);
1121                                strbuf_release(&cmd);
1122                                return NULL;
1123                        }
1124                        fill_ssh_args(conn, ssh_host, port, flags);
1125                } else {
1126                        transport_check_allowed("file");
1127                        if (get_protocol_version_config() > 0) {
1128                                argv_array_pushf(&conn->env_array, GIT_PROTOCOL_ENVIRONMENT "=version=%d",
1129                                                 get_protocol_version_config());
1130                        }
1131                }
1132                argv_array_push(&conn->args, cmd.buf);
1133
1134                if (start_command(conn))
1135                        die("unable to fork");
1136
1137                fd[0] = conn->out; /* read from child's stdout */
1138                fd[1] = conn->in;  /* write to child's stdin */
1139                strbuf_release(&cmd);
1140        }
1141        free(hostandport);
1142        free(path);
1143        return conn;
1144}
1145
1146int finish_connect(struct child_process *conn)
1147{
1148        int code;
1149        if (!conn || git_connection_is_socket(conn))
1150                return 0;
1151
1152        code = finish_command(conn);
1153        free(conn);
1154        return code;
1155}