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