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