remote-curl.con commit smart http: use the same connectivity check on cloning (9ba3804)
   1#include "cache.h"
   2#include "remote.h"
   3#include "strbuf.h"
   4#include "walker.h"
   5#include "http.h"
   6#include "exec_cmd.h"
   7#include "run-command.h"
   8#include "pkt-line.h"
   9#include "sideband.h"
  10
  11static struct remote *remote;
  12static const char *url; /* always ends with a trailing slash */
  13
  14struct options {
  15        int verbosity;
  16        unsigned long depth;
  17        unsigned progress : 1,
  18                check_self_contained_and_connected : 1,
  19                followtags : 1,
  20                dry_run : 1,
  21                thin : 1;
  22};
  23static struct options options;
  24
  25static int set_option(const char *name, const char *value)
  26{
  27        if (!strcmp(name, "verbosity")) {
  28                char *end;
  29                int v = strtol(value, &end, 10);
  30                if (value == end || *end)
  31                        return -1;
  32                options.verbosity = v;
  33                return 0;
  34        }
  35        else if (!strcmp(name, "progress")) {
  36                if (!strcmp(value, "true"))
  37                        options.progress = 1;
  38                else if (!strcmp(value, "false"))
  39                        options.progress = 0;
  40                else
  41                        return -1;
  42                return 0;
  43        }
  44        else if (!strcmp(name, "depth")) {
  45                char *end;
  46                unsigned long v = strtoul(value, &end, 10);
  47                if (value == end || *end)
  48                        return -1;
  49                options.depth = v;
  50                return 0;
  51        }
  52        else if (!strcmp(name, "followtags")) {
  53                if (!strcmp(value, "true"))
  54                        options.followtags = 1;
  55                else if (!strcmp(value, "false"))
  56                        options.followtags = 0;
  57                else
  58                        return -1;
  59                return 0;
  60        }
  61        else if (!strcmp(name, "dry-run")) {
  62                if (!strcmp(value, "true"))
  63                        options.dry_run = 1;
  64                else if (!strcmp(value, "false"))
  65                        options.dry_run = 0;
  66                else
  67                        return -1;
  68                return 0;
  69        }
  70        else if (!strcmp(name, "check-connectivity")) {
  71                if (!strcmp(value, "true"))
  72                        options.check_self_contained_and_connected = 1;
  73                else if (!strcmp(value, "false"))
  74                        options.check_self_contained_and_connected = 0;
  75                else
  76                        return -1;
  77                return 0;
  78        }
  79        else {
  80                return 1 /* unsupported */;
  81        }
  82}
  83
  84struct discovery {
  85        const char *service;
  86        char *buf_alloc;
  87        char *buf;
  88        size_t len;
  89        struct ref *refs;
  90        unsigned proto_git : 1;
  91};
  92static struct discovery *last_discovery;
  93
  94static struct ref *parse_git_refs(struct discovery *heads, int for_push)
  95{
  96        struct ref *list = NULL;
  97        get_remote_heads(-1, heads->buf, heads->len, &list,
  98                         for_push ? REF_NORMAL : 0, NULL);
  99        return list;
 100}
 101
 102static struct ref *parse_info_refs(struct discovery *heads)
 103{
 104        char *data, *start, *mid;
 105        char *ref_name;
 106        int i = 0;
 107
 108        struct ref *refs = NULL;
 109        struct ref *ref = NULL;
 110        struct ref *last_ref = NULL;
 111
 112        data = heads->buf;
 113        start = NULL;
 114        mid = data;
 115        while (i < heads->len) {
 116                if (!start) {
 117                        start = &data[i];
 118                }
 119                if (data[i] == '\t')
 120                        mid = &data[i];
 121                if (data[i] == '\n') {
 122                        if (mid - start != 40)
 123                                die("%sinfo/refs not valid: is this a git repository?", url);
 124                        data[i] = 0;
 125                        ref_name = mid + 1;
 126                        ref = xmalloc(sizeof(struct ref) +
 127                                      strlen(ref_name) + 1);
 128                        memset(ref, 0, sizeof(struct ref));
 129                        strcpy(ref->name, ref_name);
 130                        get_sha1_hex(start, ref->old_sha1);
 131                        if (!refs)
 132                                refs = ref;
 133                        if (last_ref)
 134                                last_ref->next = ref;
 135                        last_ref = ref;
 136                        start = NULL;
 137                }
 138                i++;
 139        }
 140
 141        ref = alloc_ref("HEAD");
 142        if (!http_fetch_ref(url, ref) &&
 143            !resolve_remote_symref(ref, refs)) {
 144                ref->next = refs;
 145                refs = ref;
 146        } else {
 147                free(ref);
 148        }
 149
 150        return refs;
 151}
 152
 153static void free_discovery(struct discovery *d)
 154{
 155        if (d) {
 156                if (d == last_discovery)
 157                        last_discovery = NULL;
 158                free(d->buf_alloc);
 159                free_refs(d->refs);
 160                free(d);
 161        }
 162}
 163
 164static int show_http_message(struct strbuf *type, struct strbuf *msg)
 165{
 166        const char *p, *eol;
 167
 168        /*
 169         * We only show text/plain parts, as other types are likely
 170         * to be ugly to look at on the user's terminal.
 171         *
 172         * TODO should handle "; charset=XXX", and re-encode into
 173         * logoutputencoding
 174         */
 175        if (strcasecmp(type->buf, "text/plain"))
 176                return -1;
 177
 178        strbuf_trim(msg);
 179        if (!msg->len)
 180                return -1;
 181
 182        p = msg->buf;
 183        do {
 184                eol = strchrnul(p, '\n');
 185                fprintf(stderr, "remote: %.*s\n", (int)(eol - p), p);
 186                p = eol + 1;
 187        } while(*eol);
 188        return 0;
 189}
 190
 191static struct discovery* discover_refs(const char *service, int for_push)
 192{
 193        struct strbuf exp = STRBUF_INIT;
 194        struct strbuf type = STRBUF_INIT;
 195        struct strbuf buffer = STRBUF_INIT;
 196        struct discovery *last = last_discovery;
 197        char *refs_url;
 198        int http_ret, maybe_smart = 0;
 199
 200        if (last && !strcmp(service, last->service))
 201                return last;
 202        free_discovery(last);
 203
 204        strbuf_addf(&buffer, "%sinfo/refs", url);
 205        if ((!prefixcmp(url, "http://") || !prefixcmp(url, "https://")) &&
 206             git_env_bool("GIT_SMART_HTTP", 1)) {
 207                maybe_smart = 1;
 208                if (!strchr(url, '?'))
 209                        strbuf_addch(&buffer, '?');
 210                else
 211                        strbuf_addch(&buffer, '&');
 212                strbuf_addf(&buffer, "service=%s", service);
 213        }
 214        refs_url = strbuf_detach(&buffer, NULL);
 215
 216        http_ret = http_get_strbuf(refs_url, &type, &buffer,
 217                                   HTTP_NO_CACHE | HTTP_KEEP_ERROR);
 218        switch (http_ret) {
 219        case HTTP_OK:
 220                break;
 221        case HTTP_MISSING_TARGET:
 222                show_http_message(&type, &buffer);
 223                die("repository '%s' not found", url);
 224        case HTTP_NOAUTH:
 225                show_http_message(&type, &buffer);
 226                die("Authentication failed for '%s'", url);
 227        default:
 228                show_http_message(&type, &buffer);
 229                die("unable to access '%s': %s", url, curl_errorstr);
 230        }
 231
 232        last= xcalloc(1, sizeof(*last_discovery));
 233        last->service = service;
 234        last->buf_alloc = strbuf_detach(&buffer, &last->len);
 235        last->buf = last->buf_alloc;
 236
 237        strbuf_addf(&exp, "application/x-%s-advertisement", service);
 238        if (maybe_smart &&
 239            (5 <= last->len && last->buf[4] == '#') &&
 240            !strbuf_cmp(&exp, &type)) {
 241                char *line;
 242
 243                /*
 244                 * smart HTTP response; validate that the service
 245                 * pkt-line matches our request.
 246                 */
 247                line = packet_read_line_buf(&last->buf, &last->len, NULL);
 248
 249                strbuf_reset(&exp);
 250                strbuf_addf(&exp, "# service=%s", service);
 251                if (strcmp(line, exp.buf))
 252                        die("invalid server response; got '%s'", line);
 253                strbuf_release(&exp);
 254
 255                /* The header can include additional metadata lines, up
 256                 * until a packet flush marker.  Ignore these now, but
 257                 * in the future we might start to scan them.
 258                 */
 259                while (packet_read_line_buf(&last->buf, &last->len, NULL))
 260                        ;
 261
 262                last->proto_git = 1;
 263        }
 264
 265        if (last->proto_git)
 266                last->refs = parse_git_refs(last, for_push);
 267        else
 268                last->refs = parse_info_refs(last);
 269
 270        free(refs_url);
 271        strbuf_release(&exp);
 272        strbuf_release(&type);
 273        strbuf_release(&buffer);
 274        last_discovery = last;
 275        return last;
 276}
 277
 278static struct ref *get_refs(int for_push)
 279{
 280        struct discovery *heads;
 281
 282        if (for_push)
 283                heads = discover_refs("git-receive-pack", for_push);
 284        else
 285                heads = discover_refs("git-upload-pack", for_push);
 286
 287        return heads->refs;
 288}
 289
 290static void output_refs(struct ref *refs)
 291{
 292        struct ref *posn;
 293        for (posn = refs; posn; posn = posn->next) {
 294                if (posn->symref)
 295                        printf("@%s %s\n", posn->symref, posn->name);
 296                else
 297                        printf("%s %s\n", sha1_to_hex(posn->old_sha1), posn->name);
 298        }
 299        printf("\n");
 300        fflush(stdout);
 301}
 302
 303struct rpc_state {
 304        const char *service_name;
 305        const char **argv;
 306        struct strbuf *stdin_preamble;
 307        char *service_url;
 308        char *hdr_content_type;
 309        char *hdr_accept;
 310        char *buf;
 311        size_t alloc;
 312        size_t len;
 313        size_t pos;
 314        int in;
 315        int out;
 316        struct strbuf result;
 317        unsigned gzip_request : 1;
 318        unsigned initial_buffer : 1;
 319};
 320
 321static size_t rpc_out(void *ptr, size_t eltsize,
 322                size_t nmemb, void *buffer_)
 323{
 324        size_t max = eltsize * nmemb;
 325        struct rpc_state *rpc = buffer_;
 326        size_t avail = rpc->len - rpc->pos;
 327
 328        if (!avail) {
 329                rpc->initial_buffer = 0;
 330                avail = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
 331                if (!avail)
 332                        return 0;
 333                rpc->pos = 0;
 334                rpc->len = avail;
 335        }
 336
 337        if (max < avail)
 338                avail = max;
 339        memcpy(ptr, rpc->buf + rpc->pos, avail);
 340        rpc->pos += avail;
 341        return avail;
 342}
 343
 344#ifndef NO_CURL_IOCTL
 345static curlioerr rpc_ioctl(CURL *handle, int cmd, void *clientp)
 346{
 347        struct rpc_state *rpc = clientp;
 348
 349        switch (cmd) {
 350        case CURLIOCMD_NOP:
 351                return CURLIOE_OK;
 352
 353        case CURLIOCMD_RESTARTREAD:
 354                if (rpc->initial_buffer) {
 355                        rpc->pos = 0;
 356                        return CURLIOE_OK;
 357                }
 358                fprintf(stderr, "Unable to rewind rpc post data - try increasing http.postBuffer\n");
 359                return CURLIOE_FAILRESTART;
 360
 361        default:
 362                return CURLIOE_UNKNOWNCMD;
 363        }
 364}
 365#endif
 366
 367static size_t rpc_in(char *ptr, size_t eltsize,
 368                size_t nmemb, void *buffer_)
 369{
 370        size_t size = eltsize * nmemb;
 371        struct rpc_state *rpc = buffer_;
 372        write_or_die(rpc->in, ptr, size);
 373        return size;
 374}
 375
 376static int run_slot(struct active_request_slot *slot)
 377{
 378        int err;
 379        struct slot_results results;
 380
 381        slot->results = &results;
 382        slot->curl_result = curl_easy_perform(slot->curl);
 383        finish_active_slot(slot);
 384
 385        err = handle_curl_result(&results);
 386        if (err != HTTP_OK && err != HTTP_REAUTH) {
 387                error("RPC failed; result=%d, HTTP code = %ld",
 388                      results.curl_result, results.http_code);
 389        }
 390
 391        return err;
 392}
 393
 394static int probe_rpc(struct rpc_state *rpc)
 395{
 396        struct active_request_slot *slot;
 397        struct curl_slist *headers = NULL;
 398        struct strbuf buf = STRBUF_INIT;
 399        int err;
 400
 401        slot = get_active_slot();
 402
 403        headers = curl_slist_append(headers, rpc->hdr_content_type);
 404        headers = curl_slist_append(headers, rpc->hdr_accept);
 405
 406        curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
 407        curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
 408        curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
 409        curl_easy_setopt(slot->curl, CURLOPT_ENCODING, NULL);
 410        curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, "0000");
 411        curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, 4);
 412        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
 413        curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
 414        curl_easy_setopt(slot->curl, CURLOPT_FILE, &buf);
 415
 416        err = run_slot(slot);
 417
 418        curl_slist_free_all(headers);
 419        strbuf_release(&buf);
 420        return err;
 421}
 422
 423static int post_rpc(struct rpc_state *rpc)
 424{
 425        struct active_request_slot *slot;
 426        struct curl_slist *headers = NULL;
 427        int use_gzip = rpc->gzip_request;
 428        char *gzip_body = NULL;
 429        size_t gzip_size = 0;
 430        int err, large_request = 0;
 431
 432        /* Try to load the entire request, if we can fit it into the
 433         * allocated buffer space we can use HTTP/1.0 and avoid the
 434         * chunked encoding mess.
 435         */
 436        while (1) {
 437                size_t left = rpc->alloc - rpc->len;
 438                char *buf = rpc->buf + rpc->len;
 439                int n;
 440
 441                if (left < LARGE_PACKET_MAX) {
 442                        large_request = 1;
 443                        use_gzip = 0;
 444                        break;
 445                }
 446
 447                n = packet_read(rpc->out, NULL, NULL, buf, left, 0);
 448                if (!n)
 449                        break;
 450                rpc->len += n;
 451        }
 452
 453        if (large_request) {
 454                do {
 455                        err = probe_rpc(rpc);
 456                } while (err == HTTP_REAUTH);
 457                if (err != HTTP_OK)
 458                        return -1;
 459        }
 460
 461        headers = curl_slist_append(headers, rpc->hdr_content_type);
 462        headers = curl_slist_append(headers, rpc->hdr_accept);
 463        headers = curl_slist_append(headers, "Expect:");
 464
 465retry:
 466        slot = get_active_slot();
 467
 468        curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
 469        curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
 470        curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
 471        curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
 472
 473        if (large_request) {
 474                /* The request body is large and the size cannot be predicted.
 475                 * We must use chunked encoding to send it.
 476                 */
 477                headers = curl_slist_append(headers, "Transfer-Encoding: chunked");
 478                rpc->initial_buffer = 1;
 479                curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, rpc_out);
 480                curl_easy_setopt(slot->curl, CURLOPT_INFILE, rpc);
 481#ifndef NO_CURL_IOCTL
 482                curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, rpc_ioctl);
 483                curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, rpc);
 484#endif
 485                if (options.verbosity > 1) {
 486                        fprintf(stderr, "POST %s (chunked)\n", rpc->service_name);
 487                        fflush(stderr);
 488                }
 489
 490        } else if (gzip_body) {
 491                /*
 492                 * If we are looping to retry authentication, then the previous
 493                 * run will have set up the headers and gzip buffer already,
 494                 * and we just need to send it.
 495                 */
 496                curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
 497                curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, gzip_size);
 498
 499        } else if (use_gzip && 1024 < rpc->len) {
 500                /* The client backend isn't giving us compressed data so
 501                 * we can try to deflate it ourselves, this may save on.
 502                 * the transfer time.
 503                 */
 504                git_zstream stream;
 505                int ret;
 506
 507                memset(&stream, 0, sizeof(stream));
 508                git_deflate_init_gzip(&stream, Z_BEST_COMPRESSION);
 509                gzip_size = git_deflate_bound(&stream, rpc->len);
 510                gzip_body = xmalloc(gzip_size);
 511
 512                stream.next_in = (unsigned char *)rpc->buf;
 513                stream.avail_in = rpc->len;
 514                stream.next_out = (unsigned char *)gzip_body;
 515                stream.avail_out = gzip_size;
 516
 517                ret = git_deflate(&stream, Z_FINISH);
 518                if (ret != Z_STREAM_END)
 519                        die("cannot deflate request; zlib deflate error %d", ret);
 520
 521                ret = git_deflate_end_gently(&stream);
 522                if (ret != Z_OK)
 523                        die("cannot deflate request; zlib end error %d", ret);
 524
 525                gzip_size = stream.total_out;
 526
 527                headers = curl_slist_append(headers, "Content-Encoding: gzip");
 528                curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
 529                curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, gzip_size);
 530
 531                if (options.verbosity > 1) {
 532                        fprintf(stderr, "POST %s (gzip %lu to %lu bytes)\n",
 533                                rpc->service_name,
 534                                (unsigned long)rpc->len, (unsigned long)gzip_size);
 535                        fflush(stderr);
 536                }
 537        } else {
 538                /* We know the complete request size in advance, use the
 539                 * more normal Content-Length approach.
 540                 */
 541                curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, rpc->buf);
 542                curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, rpc->len);
 543                if (options.verbosity > 1) {
 544                        fprintf(stderr, "POST %s (%lu bytes)\n",
 545                                rpc->service_name, (unsigned long)rpc->len);
 546                        fflush(stderr);
 547                }
 548        }
 549
 550        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
 551        curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, rpc_in);
 552        curl_easy_setopt(slot->curl, CURLOPT_FILE, rpc);
 553
 554        err = run_slot(slot);
 555        if (err == HTTP_REAUTH && !large_request)
 556                goto retry;
 557        if (err != HTTP_OK)
 558                err = -1;
 559
 560        curl_slist_free_all(headers);
 561        free(gzip_body);
 562        return err;
 563}
 564
 565static int rpc_service(struct rpc_state *rpc, struct discovery *heads)
 566{
 567        const char *svc = rpc->service_name;
 568        struct strbuf buf = STRBUF_INIT;
 569        struct strbuf *preamble = rpc->stdin_preamble;
 570        struct child_process client;
 571        int err = 0;
 572
 573        memset(&client, 0, sizeof(client));
 574        client.in = -1;
 575        client.out = -1;
 576        client.git_cmd = 1;
 577        client.argv = rpc->argv;
 578        if (start_command(&client))
 579                exit(1);
 580        if (preamble)
 581                write_or_die(client.in, preamble->buf, preamble->len);
 582        if (heads)
 583                write_or_die(client.in, heads->buf, heads->len);
 584
 585        rpc->alloc = http_post_buffer;
 586        rpc->buf = xmalloc(rpc->alloc);
 587        rpc->in = client.in;
 588        rpc->out = client.out;
 589        strbuf_init(&rpc->result, 0);
 590
 591        strbuf_addf(&buf, "%s%s", url, svc);
 592        rpc->service_url = strbuf_detach(&buf, NULL);
 593
 594        strbuf_addf(&buf, "Content-Type: application/x-%s-request", svc);
 595        rpc->hdr_content_type = strbuf_detach(&buf, NULL);
 596
 597        strbuf_addf(&buf, "Accept: application/x-%s-result", svc);
 598        rpc->hdr_accept = strbuf_detach(&buf, NULL);
 599
 600        while (!err) {
 601                int n = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
 602                if (!n)
 603                        break;
 604                rpc->pos = 0;
 605                rpc->len = n;
 606                err |= post_rpc(rpc);
 607        }
 608
 609        close(client.in);
 610        client.in = -1;
 611        if (!err) {
 612                strbuf_read(&rpc->result, client.out, 0);
 613        } else {
 614                char buf[4096];
 615                for (;;)
 616                        if (xread(client.out, buf, sizeof(buf)) <= 0)
 617                                break;
 618        }
 619
 620        close(client.out);
 621        client.out = -1;
 622
 623        err |= finish_command(&client);
 624        free(rpc->service_url);
 625        free(rpc->hdr_content_type);
 626        free(rpc->hdr_accept);
 627        free(rpc->buf);
 628        strbuf_release(&buf);
 629        return err;
 630}
 631
 632static int fetch_dumb(int nr_heads, struct ref **to_fetch)
 633{
 634        struct walker *walker;
 635        char **targets = xmalloc(nr_heads * sizeof(char*));
 636        int ret, i;
 637
 638        if (options.depth)
 639                die("dumb http transport does not support --depth");
 640        for (i = 0; i < nr_heads; i++)
 641                targets[i] = xstrdup(sha1_to_hex(to_fetch[i]->old_sha1));
 642
 643        walker = get_http_walker(url);
 644        walker->get_all = 1;
 645        walker->get_tree = 1;
 646        walker->get_history = 1;
 647        walker->get_verbosely = options.verbosity >= 3;
 648        walker->get_recover = 0;
 649        ret = walker_fetch(walker, nr_heads, targets, NULL, NULL);
 650        walker_free(walker);
 651
 652        for (i = 0; i < nr_heads; i++)
 653                free(targets[i]);
 654        free(targets);
 655
 656        return ret ? error("Fetch failed.") : 0;
 657}
 658
 659static int fetch_git(struct discovery *heads,
 660        int nr_heads, struct ref **to_fetch)
 661{
 662        struct rpc_state rpc;
 663        struct strbuf preamble = STRBUF_INIT;
 664        char *depth_arg = NULL;
 665        int argc = 0, i, err;
 666        const char *argv[16];
 667
 668        argv[argc++] = "fetch-pack";
 669        argv[argc++] = "--stateless-rpc";
 670        argv[argc++] = "--stdin";
 671        argv[argc++] = "--lock-pack";
 672        if (options.followtags)
 673                argv[argc++] = "--include-tag";
 674        if (options.thin)
 675                argv[argc++] = "--thin";
 676        if (options.verbosity >= 3) {
 677                argv[argc++] = "-v";
 678                argv[argc++] = "-v";
 679        }
 680        if (options.check_self_contained_and_connected)
 681                argv[argc++] = "--check-self-contained-and-connected";
 682        if (!options.progress)
 683                argv[argc++] = "--no-progress";
 684        if (options.depth) {
 685                struct strbuf buf = STRBUF_INIT;
 686                strbuf_addf(&buf, "--depth=%lu", options.depth);
 687                depth_arg = strbuf_detach(&buf, NULL);
 688                argv[argc++] = depth_arg;
 689        }
 690        argv[argc++] = url;
 691        argv[argc++] = NULL;
 692
 693        for (i = 0; i < nr_heads; i++) {
 694                struct ref *ref = to_fetch[i];
 695                if (!ref->name || !*ref->name)
 696                        die("cannot fetch by sha1 over smart http");
 697                packet_buf_write(&preamble, "%s\n", ref->name);
 698        }
 699        packet_buf_flush(&preamble);
 700
 701        memset(&rpc, 0, sizeof(rpc));
 702        rpc.service_name = "git-upload-pack",
 703        rpc.argv = argv;
 704        rpc.stdin_preamble = &preamble;
 705        rpc.gzip_request = 1;
 706
 707        err = rpc_service(&rpc, heads);
 708        if (rpc.result.len)
 709                write_or_die(1, rpc.result.buf, rpc.result.len);
 710        strbuf_release(&rpc.result);
 711        strbuf_release(&preamble);
 712        free(depth_arg);
 713        return err;
 714}
 715
 716static int fetch(int nr_heads, struct ref **to_fetch)
 717{
 718        struct discovery *d = discover_refs("git-upload-pack", 0);
 719        if (d->proto_git)
 720                return fetch_git(d, nr_heads, to_fetch);
 721        else
 722                return fetch_dumb(nr_heads, to_fetch);
 723}
 724
 725static void parse_fetch(struct strbuf *buf)
 726{
 727        struct ref **to_fetch = NULL;
 728        struct ref *list_head = NULL;
 729        struct ref **list = &list_head;
 730        int alloc_heads = 0, nr_heads = 0;
 731
 732        do {
 733                if (!prefixcmp(buf->buf, "fetch ")) {
 734                        char *p = buf->buf + strlen("fetch ");
 735                        char *name;
 736                        struct ref *ref;
 737                        unsigned char old_sha1[20];
 738
 739                        if (strlen(p) < 40 || get_sha1_hex(p, old_sha1))
 740                                die("protocol error: expected sha/ref, got %s'", p);
 741                        if (p[40] == ' ')
 742                                name = p + 41;
 743                        else if (!p[40])
 744                                name = "";
 745                        else
 746                                die("protocol error: expected sha/ref, got %s'", p);
 747
 748                        ref = alloc_ref(name);
 749                        hashcpy(ref->old_sha1, old_sha1);
 750
 751                        *list = ref;
 752                        list = &ref->next;
 753
 754                        ALLOC_GROW(to_fetch, nr_heads + 1, alloc_heads);
 755                        to_fetch[nr_heads++] = ref;
 756                }
 757                else
 758                        die("http transport does not support %s", buf->buf);
 759
 760                strbuf_reset(buf);
 761                if (strbuf_getline(buf, stdin, '\n') == EOF)
 762                        return;
 763                if (!*buf->buf)
 764                        break;
 765        } while (1);
 766
 767        if (fetch(nr_heads, to_fetch))
 768                exit(128); /* error already reported */
 769        free_refs(list_head);
 770        free(to_fetch);
 771
 772        printf("\n");
 773        fflush(stdout);
 774        strbuf_reset(buf);
 775}
 776
 777static int push_dav(int nr_spec, char **specs)
 778{
 779        const char **argv = xmalloc((10 + nr_spec) * sizeof(char*));
 780        int argc = 0, i;
 781
 782        argv[argc++] = "http-push";
 783        argv[argc++] = "--helper-status";
 784        if (options.dry_run)
 785                argv[argc++] = "--dry-run";
 786        if (options.verbosity > 1)
 787                argv[argc++] = "--verbose";
 788        argv[argc++] = url;
 789        for (i = 0; i < nr_spec; i++)
 790                argv[argc++] = specs[i];
 791        argv[argc++] = NULL;
 792
 793        if (run_command_v_opt(argv, RUN_GIT_CMD))
 794                die("git-%s failed", argv[0]);
 795        free(argv);
 796        return 0;
 797}
 798
 799static int push_git(struct discovery *heads, int nr_spec, char **specs)
 800{
 801        struct rpc_state rpc;
 802        const char **argv;
 803        int argc = 0, i, err;
 804
 805        argv = xmalloc((10 + nr_spec) * sizeof(char*));
 806        argv[argc++] = "send-pack";
 807        argv[argc++] = "--stateless-rpc";
 808        argv[argc++] = "--helper-status";
 809        if (options.thin)
 810                argv[argc++] = "--thin";
 811        if (options.dry_run)
 812                argv[argc++] = "--dry-run";
 813        if (options.verbosity == 0)
 814                argv[argc++] = "--quiet";
 815        else if (options.verbosity > 1)
 816                argv[argc++] = "--verbose";
 817        argv[argc++] = options.progress ? "--progress" : "--no-progress";
 818        argv[argc++] = url;
 819        for (i = 0; i < nr_spec; i++)
 820                argv[argc++] = specs[i];
 821        argv[argc++] = NULL;
 822
 823        memset(&rpc, 0, sizeof(rpc));
 824        rpc.service_name = "git-receive-pack",
 825        rpc.argv = argv;
 826
 827        err = rpc_service(&rpc, heads);
 828        if (rpc.result.len)
 829                write_or_die(1, rpc.result.buf, rpc.result.len);
 830        strbuf_release(&rpc.result);
 831        free(argv);
 832        return err;
 833}
 834
 835static int push(int nr_spec, char **specs)
 836{
 837        struct discovery *heads = discover_refs("git-receive-pack", 1);
 838        int ret;
 839
 840        if (heads->proto_git)
 841                ret = push_git(heads, nr_spec, specs);
 842        else
 843                ret = push_dav(nr_spec, specs);
 844        free_discovery(heads);
 845        return ret;
 846}
 847
 848static void parse_push(struct strbuf *buf)
 849{
 850        char **specs = NULL;
 851        int alloc_spec = 0, nr_spec = 0, i, ret;
 852
 853        do {
 854                if (!prefixcmp(buf->buf, "push ")) {
 855                        ALLOC_GROW(specs, nr_spec + 1, alloc_spec);
 856                        specs[nr_spec++] = xstrdup(buf->buf + 5);
 857                }
 858                else
 859                        die("http transport does not support %s", buf->buf);
 860
 861                strbuf_reset(buf);
 862                if (strbuf_getline(buf, stdin, '\n') == EOF)
 863                        goto free_specs;
 864                if (!*buf->buf)
 865                        break;
 866        } while (1);
 867
 868        ret = push(nr_spec, specs);
 869        printf("\n");
 870        fflush(stdout);
 871
 872        if (ret)
 873                exit(128); /* error already reported */
 874
 875 free_specs:
 876        for (i = 0; i < nr_spec; i++)
 877                free(specs[i]);
 878        free(specs);
 879}
 880
 881int main(int argc, const char **argv)
 882{
 883        struct strbuf buf = STRBUF_INIT;
 884        int nongit;
 885
 886        git_extract_argv0_path(argv[0]);
 887        setup_git_directory_gently(&nongit);
 888        if (argc < 2) {
 889                fprintf(stderr, "Remote needed\n");
 890                return 1;
 891        }
 892
 893        options.verbosity = 1;
 894        options.progress = !!isatty(2);
 895        options.thin = 1;
 896
 897        remote = remote_get(argv[1]);
 898
 899        if (argc > 2) {
 900                end_url_with_slash(&buf, argv[2]);
 901        } else {
 902                end_url_with_slash(&buf, remote->url[0]);
 903        }
 904
 905        url = strbuf_detach(&buf, NULL);
 906
 907        http_init(remote, url, 0);
 908
 909        do {
 910                if (strbuf_getline(&buf, stdin, '\n') == EOF) {
 911                        if (ferror(stdin))
 912                                fprintf(stderr, "Error reading command stream\n");
 913                        else
 914                                fprintf(stderr, "Unexpected end of command stream\n");
 915                        return 1;
 916                }
 917                if (buf.len == 0)
 918                        break;
 919                if (!prefixcmp(buf.buf, "fetch ")) {
 920                        if (nongit)
 921                                die("Fetch attempted without a local repo");
 922                        parse_fetch(&buf);
 923
 924                } else if (!strcmp(buf.buf, "list") || !prefixcmp(buf.buf, "list ")) {
 925                        int for_push = !!strstr(buf.buf + 4, "for-push");
 926                        output_refs(get_refs(for_push));
 927
 928                } else if (!prefixcmp(buf.buf, "push ")) {
 929                        parse_push(&buf);
 930
 931                } else if (!prefixcmp(buf.buf, "option ")) {
 932                        char *name = buf.buf + strlen("option ");
 933                        char *value = strchr(name, ' ');
 934                        int result;
 935
 936                        if (value)
 937                                *value++ = '\0';
 938                        else
 939                                value = "true";
 940
 941                        result = set_option(name, value);
 942                        if (!result)
 943                                printf("ok\n");
 944                        else if (result < 0)
 945                                printf("error invalid value\n");
 946                        else
 947                                printf("unsupported\n");
 948                        fflush(stdout);
 949
 950                } else if (!strcmp(buf.buf, "capabilities")) {
 951                        printf("fetch\n");
 952                        printf("option\n");
 953                        printf("push\n");
 954                        printf("check-connectivity\n");
 955                        printf("\n");
 956                        fflush(stdout);
 957                } else {
 958                        fprintf(stderr, "Unknown command '%s'\n", buf.buf);
 959                        return 1;
 960                }
 961                strbuf_reset(&buf);
 962        } while (1);
 963
 964        http_cleanup();
 965
 966        return 0;
 967}