connect.con commit remove the impression of unexpectedness when access is denied (46284dd)
   1#include "git-compat-util.h"
   2#include "cache.h"
   3#include "pkt-line.h"
   4#include "quote.h"
   5#include "refs.h"
   6#include "run-command.h"
   7#include "remote.h"
   8#include "url.h"
   9
  10static char *server_capabilities;
  11
  12static int check_ref(const char *name, int len, unsigned int flags)
  13{
  14        if (!flags)
  15                return 1;
  16
  17        if (len < 5 || memcmp(name, "refs/", 5))
  18                return 0;
  19
  20        /* Skip the "refs/" part */
  21        name += 5;
  22        len -= 5;
  23
  24        /* REF_NORMAL means that we don't want the magic fake tag refs */
  25        if ((flags & REF_NORMAL) && check_ref_format(name) < 0)
  26                return 0;
  27
  28        /* REF_HEADS means that we want regular branch heads */
  29        if ((flags & REF_HEADS) && !memcmp(name, "heads/", 6))
  30                return 1;
  31
  32        /* REF_TAGS means that we want tags */
  33        if ((flags & REF_TAGS) && !memcmp(name, "tags/", 5))
  34                return 1;
  35
  36        /* All type bits clear means that we are ok with anything */
  37        return !(flags & ~REF_NORMAL);
  38}
  39
  40int check_ref_type(const struct ref *ref, int flags)
  41{
  42        return check_ref(ref->name, strlen(ref->name), flags);
  43}
  44
  45static void add_extra_have(struct extra_have_objects *extra, unsigned char *sha1)
  46{
  47        ALLOC_GROW(extra->array, extra->nr + 1, extra->alloc);
  48        hashcpy(&(extra->array[extra->nr][0]), sha1);
  49        extra->nr++;
  50}
  51
  52static void die_initial_contact(int got_at_least_one_head)
  53{
  54        if (got_at_least_one_head)
  55                die("The remote end hung up upon initial contact");
  56        else
  57                die("Could not read from remote repository.\n\n"
  58                    "Please make sure you have the correct access rights\n"
  59                    "and the repository exists.");
  60}
  61
  62/*
  63 * Read all the refs from the other end
  64 */
  65struct ref **get_remote_heads(int in, struct ref **list,
  66                              int nr_match, char **match,
  67                              unsigned int flags,
  68                              struct extra_have_objects *extra_have)
  69{
  70        int got_at_least_one_head = 0;
  71
  72        *list = NULL;
  73        for (;;) {
  74                struct ref *ref;
  75                unsigned char old_sha1[20];
  76                static char buffer[1000];
  77                char *name;
  78                int len, name_len;
  79
  80                len = packet_read(in, buffer, sizeof(buffer));
  81                if (len < 0)
  82                        die_initial_contact(got_at_least_one_head);
  83
  84                if (!len)
  85                        break;
  86                if (buffer[len-1] == '\n')
  87                        buffer[--len] = 0;
  88
  89                if (len > 4 && !prefixcmp(buffer, "ERR "))
  90                        die("remote error: %s", buffer + 4);
  91
  92                if (len < 42 || get_sha1_hex(buffer, old_sha1) || buffer[40] != ' ')
  93                        die("protocol error: expected sha/ref, got '%s'", buffer);
  94                name = buffer + 41;
  95
  96                name_len = strlen(name);
  97                if (len != name_len + 41) {
  98                        free(server_capabilities);
  99                        server_capabilities = xstrdup(name + name_len + 1);
 100                }
 101
 102                if (extra_have &&
 103                    name_len == 5 && !memcmp(".have", name, 5)) {
 104                        add_extra_have(extra_have, old_sha1);
 105                        continue;
 106                }
 107
 108                if (!check_ref(name, name_len, flags))
 109                        continue;
 110                if (nr_match && !path_match(name, nr_match, match))
 111                        continue;
 112                ref = alloc_ref(buffer + 41);
 113                hashcpy(ref->old_sha1, old_sha1);
 114                *list = ref;
 115                list = &ref->next;
 116                got_at_least_one_head = 1;
 117        }
 118        return list;
 119}
 120
 121int server_supports(const char *feature)
 122{
 123        return server_capabilities &&
 124                strstr(server_capabilities, feature) != NULL;
 125}
 126
 127int path_match(const char *path, int nr, char **match)
 128{
 129        int i;
 130        int pathlen = strlen(path);
 131
 132        for (i = 0; i < nr; i++) {
 133                char *s = match[i];
 134                int len = strlen(s);
 135
 136                if (!len || len > pathlen)
 137                        continue;
 138                if (memcmp(path + pathlen - len, s, len))
 139                        continue;
 140                if (pathlen > len && path[pathlen - len - 1] != '/')
 141                        continue;
 142                *s = 0;
 143                return (i + 1);
 144        }
 145        return 0;
 146}
 147
 148enum protocol {
 149        PROTO_LOCAL = 1,
 150        PROTO_SSH,
 151        PROTO_GIT
 152};
 153
 154static enum protocol get_protocol(const char *name)
 155{
 156        if (!strcmp(name, "ssh"))
 157                return PROTO_SSH;
 158        if (!strcmp(name, "git"))
 159                return PROTO_GIT;
 160        if (!strcmp(name, "git+ssh"))
 161                return PROTO_SSH;
 162        if (!strcmp(name, "ssh+git"))
 163                return PROTO_SSH;
 164        if (!strcmp(name, "file"))
 165                return PROTO_LOCAL;
 166        die("I don't handle protocol '%s'", name);
 167}
 168
 169#define STR_(s) # s
 170#define STR(s)  STR_(s)
 171
 172static void get_host_and_port(char **host, const char **port)
 173{
 174        char *colon, *end;
 175
 176        if (*host[0] == '[') {
 177                end = strchr(*host + 1, ']');
 178                if (end) {
 179                        *end = 0;
 180                        end++;
 181                        (*host)++;
 182                } else
 183                        end = *host;
 184        } else
 185                end = *host;
 186        colon = strchr(end, ':');
 187
 188        if (colon) {
 189                *colon = 0;
 190                *port = colon + 1;
 191        }
 192}
 193
 194#ifndef NO_IPV6
 195
 196static const char *ai_name(const struct addrinfo *ai)
 197{
 198        static char addr[NI_MAXHOST];
 199        if (getnameinfo(ai->ai_addr, ai->ai_addrlen, addr, sizeof(addr), NULL, 0,
 200                        NI_NUMERICHOST) != 0)
 201                strcpy(addr, "(unknown)");
 202
 203        return addr;
 204}
 205
 206/*
 207 * Returns a connected socket() fd, or else die()s.
 208 */
 209static int git_tcp_connect_sock(char *host, int flags)
 210{
 211        struct strbuf error_message = STRBUF_INIT;
 212        int sockfd = -1;
 213        const char *port = STR(DEFAULT_GIT_PORT);
 214        struct addrinfo hints, *ai0, *ai;
 215        int gai;
 216        int cnt = 0;
 217
 218        get_host_and_port(&host, &port);
 219        if (!*port)
 220                port = "<none>";
 221
 222        memset(&hints, 0, sizeof(hints));
 223        hints.ai_socktype = SOCK_STREAM;
 224        hints.ai_protocol = IPPROTO_TCP;
 225
 226        if (flags & CONNECT_VERBOSE)
 227                fprintf(stderr, "Looking up %s ... ", host);
 228
 229        gai = getaddrinfo(host, port, &hints, &ai);
 230        if (gai)
 231                die("Unable to look up %s (port %s) (%s)", host, port, gai_strerror(gai));
 232
 233        if (flags & CONNECT_VERBOSE)
 234                fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);
 235
 236        for (ai0 = ai; ai; ai = ai->ai_next, cnt++) {
 237                sockfd = socket(ai->ai_family,
 238                                ai->ai_socktype, ai->ai_protocol);
 239                if ((sockfd < 0) ||
 240                    (connect(sockfd, ai->ai_addr, ai->ai_addrlen) < 0)) {
 241                        strbuf_addf(&error_message, "%s[%d: %s]: errno=%s\n",
 242                                    host, cnt, ai_name(ai), strerror(errno));
 243                        if (0 <= sockfd)
 244                                close(sockfd);
 245                        sockfd = -1;
 246                        continue;
 247                }
 248                if (flags & CONNECT_VERBOSE)
 249                        fprintf(stderr, "%s ", ai_name(ai));
 250                break;
 251        }
 252
 253        freeaddrinfo(ai0);
 254
 255        if (sockfd < 0)
 256                die("unable to connect to %s:\n%s", host, error_message.buf);
 257
 258        if (flags & CONNECT_VERBOSE)
 259                fprintf(stderr, "done.\n");
 260
 261        strbuf_release(&error_message);
 262
 263        return sockfd;
 264}
 265
 266#else /* NO_IPV6 */
 267
 268/*
 269 * Returns a connected socket() fd, or else die()s.
 270 */
 271static int git_tcp_connect_sock(char *host, int flags)
 272{
 273        int sockfd = -1, saved_errno = 0;
 274        const char *port = STR(DEFAULT_GIT_PORT);
 275        char *ep;
 276        struct hostent *he;
 277        struct sockaddr_in sa;
 278        char **ap;
 279        unsigned int nport;
 280        int cnt;
 281
 282        get_host_and_port(&host, &port);
 283
 284        if (flags & CONNECT_VERBOSE)
 285                fprintf(stderr, "Looking up %s ... ", host);
 286
 287        he = gethostbyname(host);
 288        if (!he)
 289                die("Unable to look up %s (%s)", host, hstrerror(h_errno));
 290        nport = strtoul(port, &ep, 10);
 291        if ( ep == port || *ep ) {
 292                /* Not numeric */
 293                struct servent *se = getservbyname(port,"tcp");
 294                if ( !se )
 295                        die("Unknown port %s", port);
 296                nport = se->s_port;
 297        }
 298
 299        if (flags & CONNECT_VERBOSE)
 300                fprintf(stderr, "done.\nConnecting to %s (port %s) ... ", host, port);
 301
 302        for (cnt = 0, ap = he->h_addr_list; *ap; ap++, cnt++) {
 303                sockfd = socket(he->h_addrtype, SOCK_STREAM, 0);
 304                if (sockfd < 0) {
 305                        saved_errno = errno;
 306                        continue;
 307                }
 308
 309                memset(&sa, 0, sizeof sa);
 310                sa.sin_family = he->h_addrtype;
 311                sa.sin_port = htons(nport);
 312                memcpy(&sa.sin_addr, *ap, he->h_length);
 313
 314                if (connect(sockfd, (struct sockaddr *)&sa, sizeof sa) < 0) {
 315                        saved_errno = errno;
 316                        fprintf(stderr, "%s[%d: %s]: errno=%s\n",
 317                                host,
 318                                cnt,
 319                                inet_ntoa(*(struct in_addr *)&sa.sin_addr),
 320                                strerror(saved_errno));
 321                        close(sockfd);
 322                        sockfd = -1;
 323                        continue;
 324                }
 325                if (flags & CONNECT_VERBOSE)
 326                        fprintf(stderr, "%s ",
 327                                inet_ntoa(*(struct in_addr *)&sa.sin_addr));
 328                break;
 329        }
 330
 331        if (sockfd < 0)
 332                die("unable to connect a socket (%s)", strerror(saved_errno));
 333
 334        if (flags & CONNECT_VERBOSE)
 335                fprintf(stderr, "done.\n");
 336
 337        return sockfd;
 338}
 339
 340#endif /* NO_IPV6 */
 341
 342
 343static void git_tcp_connect(int fd[2], char *host, int flags)
 344{
 345        int sockfd = git_tcp_connect_sock(host, flags);
 346
 347        fd[0] = sockfd;
 348        fd[1] = dup(sockfd);
 349}
 350
 351
 352static char *git_proxy_command;
 353
 354static int git_proxy_command_options(const char *var, const char *value,
 355                void *cb)
 356{
 357        if (!strcmp(var, "core.gitproxy")) {
 358                const char *for_pos;
 359                int matchlen = -1;
 360                int hostlen;
 361                const char *rhost_name = cb;
 362                int rhost_len = strlen(rhost_name);
 363
 364                if (git_proxy_command)
 365                        return 0;
 366                if (!value)
 367                        return config_error_nonbool(var);
 368                /* [core]
 369                 * ;# matches www.kernel.org as well
 370                 * gitproxy = netcatter-1 for kernel.org
 371                 * gitproxy = netcatter-2 for sample.xz
 372                 * gitproxy = netcatter-default
 373                 */
 374                for_pos = strstr(value, " for ");
 375                if (!for_pos)
 376                        /* matches everybody */
 377                        matchlen = strlen(value);
 378                else {
 379                        hostlen = strlen(for_pos + 5);
 380                        if (rhost_len < hostlen)
 381                                matchlen = -1;
 382                        else if (!strncmp(for_pos + 5,
 383                                          rhost_name + rhost_len - hostlen,
 384                                          hostlen) &&
 385                                 ((rhost_len == hostlen) ||
 386                                  rhost_name[rhost_len - hostlen -1] == '.'))
 387                                matchlen = for_pos - value;
 388                        else
 389                                matchlen = -1;
 390                }
 391                if (0 <= matchlen) {
 392                        /* core.gitproxy = none for kernel.org */
 393                        if (matchlen == 4 &&
 394                            !memcmp(value, "none", 4))
 395                                matchlen = 0;
 396                        git_proxy_command = xmemdupz(value, matchlen);
 397                }
 398                return 0;
 399        }
 400
 401        return git_default_config(var, value, cb);
 402}
 403
 404static int git_use_proxy(const char *host)
 405{
 406        git_proxy_command = getenv("GIT_PROXY_COMMAND");
 407        git_config(git_proxy_command_options, (void*)host);
 408        return (git_proxy_command && *git_proxy_command);
 409}
 410
 411static struct child_process *git_proxy_connect(int fd[2], char *host)
 412{
 413        const char *port = STR(DEFAULT_GIT_PORT);
 414        const char **argv;
 415        struct child_process *proxy;
 416
 417        get_host_and_port(&host, &port);
 418
 419        argv = xmalloc(sizeof(*argv) * 4);
 420        argv[0] = git_proxy_command;
 421        argv[1] = host;
 422        argv[2] = port;
 423        argv[3] = NULL;
 424        proxy = xcalloc(1, sizeof(*proxy));
 425        proxy->argv = argv;
 426        proxy->in = -1;
 427        proxy->out = -1;
 428        if (start_command(proxy))
 429                die("cannot start proxy %s", argv[0]);
 430        fd[0] = proxy->out; /* read from proxy stdout */
 431        fd[1] = proxy->in;  /* write to proxy stdin */
 432        return proxy;
 433}
 434
 435#define MAX_CMD_LEN 1024
 436
 437static char *get_port(char *host)
 438{
 439        char *end;
 440        char *p = strchr(host, ':');
 441
 442        if (p) {
 443                long port = strtol(p + 1, &end, 10);
 444                if (end != p + 1 && *end == '\0' && 0 <= port && port < 65536) {
 445                        *p = '\0';
 446                        return p+1;
 447                }
 448        }
 449
 450        return NULL;
 451}
 452
 453static struct child_process no_fork;
 454
 455/*
 456 * This returns a dummy child_process if the transport protocol does not
 457 * need fork(2), or a struct child_process object if it does.  Once done,
 458 * finish the connection with finish_connect() with the value returned from
 459 * this function (it is safe to call finish_connect() with NULL to support
 460 * the former case).
 461 *
 462 * If it returns, the connect is successful; it just dies on errors (this
 463 * will hopefully be changed in a libification effort, to return NULL when
 464 * the connection failed).
 465 */
 466struct child_process *git_connect(int fd[2], const char *url_orig,
 467                                  const char *prog, int flags)
 468{
 469        char *url;
 470        char *host, *path;
 471        char *end;
 472        int c;
 473        struct child_process *conn = &no_fork;
 474        enum protocol protocol = PROTO_LOCAL;
 475        int free_path = 0;
 476        char *port = NULL;
 477        const char **arg;
 478        struct strbuf cmd;
 479
 480        /* Without this we cannot rely on waitpid() to tell
 481         * what happened to our children.
 482         */
 483        signal(SIGCHLD, SIG_DFL);
 484
 485        if (is_url(url_orig))
 486                url = url_decode(url_orig);
 487        else
 488                url = xstrdup(url_orig);
 489
 490        host = strstr(url, "://");
 491        if (host) {
 492                *host = '\0';
 493                protocol = get_protocol(url);
 494                host += 3;
 495                c = '/';
 496        } else {
 497                host = url;
 498                c = ':';
 499        }
 500
 501        /*
 502         * Don't do destructive transforms with git:// as that
 503         * protocol code does '[]' unwrapping of its own.
 504         */
 505        if (host[0] == '[') {
 506                end = strchr(host + 1, ']');
 507                if (end) {
 508                        if (protocol != PROTO_GIT) {
 509                                *end = 0;
 510                                host++;
 511                        }
 512                        end++;
 513                } else
 514                        end = host;
 515        } else
 516                end = host;
 517
 518        path = strchr(end, c);
 519        if (path && !has_dos_drive_prefix(end)) {
 520                if (c == ':') {
 521                        protocol = PROTO_SSH;
 522                        *path++ = '\0';
 523                }
 524        } else
 525                path = end;
 526
 527        if (!path || !*path)
 528                die("No path specified. See 'man git-pull' for valid url syntax");
 529
 530        /*
 531         * null-terminate hostname and point path to ~ for URL's like this:
 532         *    ssh://host.xz/~user/repo
 533         */
 534        if (protocol != PROTO_LOCAL && host != url) {
 535                char *ptr = path;
 536                if (path[1] == '~')
 537                        path++;
 538                else {
 539                        path = xstrdup(ptr);
 540                        free_path = 1;
 541                }
 542
 543                *ptr = '\0';
 544        }
 545
 546        /*
 547         * Add support for ssh port: ssh://host.xy:<port>/...
 548         */
 549        if (protocol == PROTO_SSH && host != url)
 550                port = get_port(host);
 551
 552        if (protocol == PROTO_GIT) {
 553                /* These underlying connection commands die() if they
 554                 * cannot connect.
 555                 */
 556                char *target_host = xstrdup(host);
 557                if (git_use_proxy(host))
 558                        conn = git_proxy_connect(fd, host);
 559                else
 560                        git_tcp_connect(fd, host, flags);
 561                /*
 562                 * Separate original protocol components prog and path
 563                 * from extended host header with a NUL byte.
 564                 *
 565                 * Note: Do not add any other headers here!  Doing so
 566                 * will cause older git-daemon servers to crash.
 567                 */
 568                packet_write(fd[1],
 569                             "%s %s%chost=%s%c",
 570                             prog, path, 0,
 571                             target_host, 0);
 572                free(target_host);
 573                free(url);
 574                if (free_path)
 575                        free(path);
 576                return conn;
 577        }
 578
 579        conn = xcalloc(1, sizeof(*conn));
 580
 581        strbuf_init(&cmd, MAX_CMD_LEN);
 582        strbuf_addstr(&cmd, prog);
 583        strbuf_addch(&cmd, ' ');
 584        sq_quote_buf(&cmd, path);
 585        if (cmd.len >= MAX_CMD_LEN)
 586                die("command line too long");
 587
 588        conn->in = conn->out = -1;
 589        conn->argv = arg = xcalloc(7, sizeof(*arg));
 590        if (protocol == PROTO_SSH) {
 591                const char *ssh = getenv("GIT_SSH");
 592                int putty = ssh && strcasestr(ssh, "plink");
 593                if (!ssh) ssh = "ssh";
 594
 595                *arg++ = ssh;
 596                if (putty && !strcasestr(ssh, "tortoiseplink"))
 597                        *arg++ = "-batch";
 598                if (port) {
 599                        /* P is for PuTTY, p is for OpenSSH */
 600                        *arg++ = putty ? "-P" : "-p";
 601                        *arg++ = port;
 602                }
 603                *arg++ = host;
 604        }
 605        else {
 606                /* remove repo-local variables from the environment */
 607                conn->env = local_repo_env;
 608                conn->use_shell = 1;
 609        }
 610        *arg++ = cmd.buf;
 611        *arg = NULL;
 612
 613        if (start_command(conn))
 614                die("unable to fork");
 615
 616        fd[0] = conn->out; /* read from child's stdout */
 617        fd[1] = conn->in;  /* write to child's stdin */
 618        strbuf_release(&cmd);
 619        free(url);
 620        if (free_path)
 621                free(path);
 622        return conn;
 623}
 624
 625int git_connection_is_socket(struct child_process *conn)
 626{
 627        return conn == &no_fork;
 628}
 629
 630int finish_connect(struct child_process *conn)
 631{
 632        int code;
 633        if (!conn || git_connection_is_socket(conn))
 634                return 0;
 635
 636        code = finish_command(conn);
 637        free(conn->argv);
 638        free(conn);
 639        return code;
 640}
 641
 642char *git_getpass(const char *prompt)
 643{
 644        const char *askpass;
 645        struct child_process pass;
 646        const char *args[3];
 647        static struct strbuf buffer = STRBUF_INIT;
 648
 649        askpass = getenv("GIT_ASKPASS");
 650        if (!askpass)
 651                askpass = askpass_program;
 652        if (!askpass)
 653                askpass = getenv("SSH_ASKPASS");
 654        if (!askpass || !(*askpass)) {
 655                char *result = getpass(prompt);
 656                if (!result)
 657                        die_errno("Could not read password");
 658                return result;
 659        }
 660
 661        args[0] = askpass;
 662        args[1] = prompt;
 663        args[2] = NULL;
 664
 665        memset(&pass, 0, sizeof(pass));
 666        pass.argv = args;
 667        pass.out = -1;
 668
 669        if (start_command(&pass))
 670                exit(1);
 671
 672        strbuf_reset(&buffer);
 673        if (strbuf_read(&buffer, pass.out, 20) < 0)
 674                die("failed to read password from %s\n", askpass);
 675
 676        close(pass.out);
 677
 678        if (finish_command(&pass))
 679                exit(1);
 680
 681        strbuf_setlen(&buffer, strcspn(buffer.buf, "\r\n"));
 682
 683        return buffer.buf;
 684}