aefafd33de6ecac03540c99e5e2b6c7eb3a5fcbc
   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        int err, large_request = 0;
 417
 418        /* Try to load the entire request, if we can fit it into the
 419         * allocated buffer space we can use HTTP/1.0 and avoid the
 420         * chunked encoding mess.
 421         */
 422        while (1) {
 423                size_t left = rpc->alloc - rpc->len;
 424                char *buf = rpc->buf + rpc->len;
 425                int n;
 426
 427                if (left < LARGE_PACKET_MAX) {
 428                        large_request = 1;
 429                        use_gzip = 0;
 430                        break;
 431                }
 432
 433                n = packet_read_line(rpc->out, buf, left);
 434                if (!n)
 435                        break;
 436                rpc->len += n;
 437        }
 438
 439        if (large_request) {
 440                do {
 441                        err = probe_rpc(rpc);
 442                } while (err == HTTP_REAUTH);
 443                if (err != HTTP_OK)
 444                        return -1;
 445        }
 446
 447        headers = curl_slist_append(headers, rpc->hdr_content_type);
 448        headers = curl_slist_append(headers, rpc->hdr_accept);
 449        headers = curl_slist_append(headers, "Expect:");
 450
 451retry:
 452        slot = get_active_slot();
 453
 454        curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
 455        curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
 456        curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
 457        curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
 458
 459        if (large_request) {
 460                /* The request body is large and the size cannot be predicted.
 461                 * We must use chunked encoding to send it.
 462                 */
 463                headers = curl_slist_append(headers, "Transfer-Encoding: chunked");
 464                rpc->initial_buffer = 1;
 465                curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, rpc_out);
 466                curl_easy_setopt(slot->curl, CURLOPT_INFILE, rpc);
 467#ifndef NO_CURL_IOCTL
 468                curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, rpc_ioctl);
 469                curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, rpc);
 470#endif
 471                if (options.verbosity > 1) {
 472                        fprintf(stderr, "POST %s (chunked)\n", rpc->service_name);
 473                        fflush(stderr);
 474                }
 475
 476        } else if (use_gzip && 1024 < rpc->len) {
 477                /* The client backend isn't giving us compressed data so
 478                 * we can try to deflate it ourselves, this may save on.
 479                 * the transfer time.
 480                 */
 481                size_t size;
 482                git_zstream stream;
 483                int ret;
 484
 485                memset(&stream, 0, sizeof(stream));
 486                git_deflate_init_gzip(&stream, Z_BEST_COMPRESSION);
 487                size = git_deflate_bound(&stream, rpc->len);
 488                gzip_body = xmalloc(size);
 489
 490                stream.next_in = (unsigned char *)rpc->buf;
 491                stream.avail_in = rpc->len;
 492                stream.next_out = (unsigned char *)gzip_body;
 493                stream.avail_out = size;
 494
 495                ret = git_deflate(&stream, Z_FINISH);
 496                if (ret != Z_STREAM_END)
 497                        die("cannot deflate request; zlib deflate error %d", ret);
 498
 499                ret = git_deflate_end_gently(&stream);
 500                if (ret != Z_OK)
 501                        die("cannot deflate request; zlib end error %d", ret);
 502
 503                size = stream.total_out;
 504
 505                headers = curl_slist_append(headers, "Content-Encoding: gzip");
 506                curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
 507                curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, size);
 508
 509                if (options.verbosity > 1) {
 510                        fprintf(stderr, "POST %s (gzip %lu to %lu bytes)\n",
 511                                rpc->service_name,
 512                                (unsigned long)rpc->len, (unsigned long)size);
 513                        fflush(stderr);
 514                }
 515        } else {
 516                /* We know the complete request size in advance, use the
 517                 * more normal Content-Length approach.
 518                 */
 519                curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, rpc->buf);
 520                curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, rpc->len);
 521                if (options.verbosity > 1) {
 522                        fprintf(stderr, "POST %s (%lu bytes)\n",
 523                                rpc->service_name, (unsigned long)rpc->len);
 524                        fflush(stderr);
 525                }
 526        }
 527
 528        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
 529        curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, rpc_in);
 530        curl_easy_setopt(slot->curl, CURLOPT_FILE, rpc);
 531
 532        err = run_slot(slot);
 533        if (err == HTTP_REAUTH && !large_request && !use_gzip)
 534                goto retry;
 535        if (err != HTTP_OK)
 536                err = -1;
 537
 538        curl_slist_free_all(headers);
 539        free(gzip_body);
 540        return err;
 541}
 542
 543static int rpc_service(struct rpc_state *rpc, struct discovery *heads)
 544{
 545        const char *svc = rpc->service_name;
 546        struct strbuf buf = STRBUF_INIT;
 547        struct strbuf *preamble = rpc->stdin_preamble;
 548        struct child_process client;
 549        int err = 0;
 550
 551        memset(&client, 0, sizeof(client));
 552        client.in = -1;
 553        client.out = -1;
 554        client.git_cmd = 1;
 555        client.argv = rpc->argv;
 556        if (start_command(&client))
 557                exit(1);
 558        if (preamble)
 559                write_or_die(client.in, preamble->buf, preamble->len);
 560        if (heads)
 561                write_or_die(client.in, heads->buf, heads->len);
 562
 563        rpc->alloc = http_post_buffer;
 564        rpc->buf = xmalloc(rpc->alloc);
 565        rpc->in = client.in;
 566        rpc->out = client.out;
 567        strbuf_init(&rpc->result, 0);
 568
 569        strbuf_addf(&buf, "%s%s", url, svc);
 570        rpc->service_url = strbuf_detach(&buf, NULL);
 571
 572        strbuf_addf(&buf, "Content-Type: application/x-%s-request", svc);
 573        rpc->hdr_content_type = strbuf_detach(&buf, NULL);
 574
 575        strbuf_addf(&buf, "Accept: application/x-%s-result", svc);
 576        rpc->hdr_accept = strbuf_detach(&buf, NULL);
 577
 578        while (!err) {
 579                int n = packet_read_line(rpc->out, rpc->buf, rpc->alloc);
 580                if (!n)
 581                        break;
 582                rpc->pos = 0;
 583                rpc->len = n;
 584                err |= post_rpc(rpc);
 585        }
 586
 587        close(client.in);
 588        client.in = -1;
 589        if (!err) {
 590                strbuf_read(&rpc->result, client.out, 0);
 591        } else {
 592                char buf[4096];
 593                for (;;)
 594                        if (xread(client.out, buf, sizeof(buf)) <= 0)
 595                                break;
 596        }
 597
 598        close(client.out);
 599        client.out = -1;
 600
 601        err |= finish_command(&client);
 602        free(rpc->service_url);
 603        free(rpc->hdr_content_type);
 604        free(rpc->hdr_accept);
 605        free(rpc->buf);
 606        strbuf_release(&buf);
 607        return err;
 608}
 609
 610static int fetch_dumb(int nr_heads, struct ref **to_fetch)
 611{
 612        struct walker *walker;
 613        char **targets = xmalloc(nr_heads * sizeof(char*));
 614        int ret, i;
 615
 616        if (options.depth)
 617                die("dumb http transport does not support --depth");
 618        for (i = 0; i < nr_heads; i++)
 619                targets[i] = xstrdup(sha1_to_hex(to_fetch[i]->old_sha1));
 620
 621        walker = get_http_walker(url);
 622        walker->get_all = 1;
 623        walker->get_tree = 1;
 624        walker->get_history = 1;
 625        walker->get_verbosely = options.verbosity >= 3;
 626        walker->get_recover = 0;
 627        ret = walker_fetch(walker, nr_heads, targets, NULL, NULL);
 628        walker_free(walker);
 629
 630        for (i = 0; i < nr_heads; i++)
 631                free(targets[i]);
 632        free(targets);
 633
 634        return ret ? error("Fetch failed.") : 0;
 635}
 636
 637static int fetch_git(struct discovery *heads,
 638        int nr_heads, struct ref **to_fetch)
 639{
 640        struct rpc_state rpc;
 641        struct strbuf preamble = STRBUF_INIT;
 642        char *depth_arg = NULL;
 643        int argc = 0, i, err;
 644        const char *argv[15];
 645
 646        argv[argc++] = "fetch-pack";
 647        argv[argc++] = "--stateless-rpc";
 648        argv[argc++] = "--stdin";
 649        argv[argc++] = "--lock-pack";
 650        if (options.followtags)
 651                argv[argc++] = "--include-tag";
 652        if (options.thin)
 653                argv[argc++] = "--thin";
 654        if (options.verbosity >= 3) {
 655                argv[argc++] = "-v";
 656                argv[argc++] = "-v";
 657        }
 658        if (!options.progress)
 659                argv[argc++] = "--no-progress";
 660        if (options.depth) {
 661                struct strbuf buf = STRBUF_INIT;
 662                strbuf_addf(&buf, "--depth=%lu", options.depth);
 663                depth_arg = strbuf_detach(&buf, NULL);
 664                argv[argc++] = depth_arg;
 665        }
 666        argv[argc++] = url;
 667        argv[argc++] = NULL;
 668
 669        for (i = 0; i < nr_heads; i++) {
 670                struct ref *ref = to_fetch[i];
 671                if (!ref->name || !*ref->name)
 672                        die("cannot fetch by sha1 over smart http");
 673                packet_buf_write(&preamble, "%s\n", ref->name);
 674        }
 675        packet_buf_flush(&preamble);
 676
 677        memset(&rpc, 0, sizeof(rpc));
 678        rpc.service_name = "git-upload-pack",
 679        rpc.argv = argv;
 680        rpc.stdin_preamble = &preamble;
 681        rpc.gzip_request = 1;
 682
 683        err = rpc_service(&rpc, heads);
 684        if (rpc.result.len)
 685                safe_write(1, rpc.result.buf, rpc.result.len);
 686        strbuf_release(&rpc.result);
 687        strbuf_release(&preamble);
 688        free(depth_arg);
 689        return err;
 690}
 691
 692static int fetch(int nr_heads, struct ref **to_fetch)
 693{
 694        struct discovery *d = discover_refs("git-upload-pack");
 695        if (d->proto_git)
 696                return fetch_git(d, nr_heads, to_fetch);
 697        else
 698                return fetch_dumb(nr_heads, to_fetch);
 699}
 700
 701static void parse_fetch(struct strbuf *buf)
 702{
 703        struct ref **to_fetch = NULL;
 704        struct ref *list_head = NULL;
 705        struct ref **list = &list_head;
 706        int alloc_heads = 0, nr_heads = 0;
 707
 708        do {
 709                if (!prefixcmp(buf->buf, "fetch ")) {
 710                        char *p = buf->buf + strlen("fetch ");
 711                        char *name;
 712                        struct ref *ref;
 713                        unsigned char old_sha1[20];
 714
 715                        if (strlen(p) < 40 || get_sha1_hex(p, old_sha1))
 716                                die("protocol error: expected sha/ref, got %s'", p);
 717                        if (p[40] == ' ')
 718                                name = p + 41;
 719                        else if (!p[40])
 720                                name = "";
 721                        else
 722                                die("protocol error: expected sha/ref, got %s'", p);
 723
 724                        ref = alloc_ref(name);
 725                        hashcpy(ref->old_sha1, old_sha1);
 726
 727                        *list = ref;
 728                        list = &ref->next;
 729
 730                        ALLOC_GROW(to_fetch, nr_heads + 1, alloc_heads);
 731                        to_fetch[nr_heads++] = ref;
 732                }
 733                else
 734                        die("http transport does not support %s", buf->buf);
 735
 736                strbuf_reset(buf);
 737                if (strbuf_getline(buf, stdin, '\n') == EOF)
 738                        return;
 739                if (!*buf->buf)
 740                        break;
 741        } while (1);
 742
 743        if (fetch(nr_heads, to_fetch))
 744                exit(128); /* error already reported */
 745        free_refs(list_head);
 746        free(to_fetch);
 747
 748        printf("\n");
 749        fflush(stdout);
 750        strbuf_reset(buf);
 751}
 752
 753static int push_dav(int nr_spec, char **specs)
 754{
 755        const char **argv = xmalloc((10 + nr_spec) * sizeof(char*));
 756        int argc = 0, i;
 757
 758        argv[argc++] = "http-push";
 759        argv[argc++] = "--helper-status";
 760        if (options.dry_run)
 761                argv[argc++] = "--dry-run";
 762        if (options.verbosity > 1)
 763                argv[argc++] = "--verbose";
 764        argv[argc++] = url;
 765        for (i = 0; i < nr_spec; i++)
 766                argv[argc++] = specs[i];
 767        argv[argc++] = NULL;
 768
 769        if (run_command_v_opt(argv, RUN_GIT_CMD))
 770                die("git-%s failed", argv[0]);
 771        free(argv);
 772        return 0;
 773}
 774
 775static int push_git(struct discovery *heads, int nr_spec, char **specs)
 776{
 777        struct rpc_state rpc;
 778        const char **argv;
 779        int argc = 0, i, err;
 780
 781        argv = xmalloc((10 + nr_spec) * sizeof(char*));
 782        argv[argc++] = "send-pack";
 783        argv[argc++] = "--stateless-rpc";
 784        argv[argc++] = "--helper-status";
 785        if (options.thin)
 786                argv[argc++] = "--thin";
 787        if (options.dry_run)
 788                argv[argc++] = "--dry-run";
 789        if (options.verbosity == 0)
 790                argv[argc++] = "--quiet";
 791        else if (options.verbosity > 1)
 792                argv[argc++] = "--verbose";
 793        argv[argc++] = options.progress ? "--progress" : "--no-progress";
 794        argv[argc++] = url;
 795        for (i = 0; i < nr_spec; i++)
 796                argv[argc++] = specs[i];
 797        argv[argc++] = NULL;
 798
 799        memset(&rpc, 0, sizeof(rpc));
 800        rpc.service_name = "git-receive-pack",
 801        rpc.argv = argv;
 802
 803        err = rpc_service(&rpc, heads);
 804        if (rpc.result.len)
 805                safe_write(1, rpc.result.buf, rpc.result.len);
 806        strbuf_release(&rpc.result);
 807        free(argv);
 808        return err;
 809}
 810
 811static int push(int nr_spec, char **specs)
 812{
 813        struct discovery *heads = discover_refs("git-receive-pack");
 814        int ret;
 815
 816        if (heads->proto_git)
 817                ret = push_git(heads, nr_spec, specs);
 818        else
 819                ret = push_dav(nr_spec, specs);
 820        free_discovery(heads);
 821        return ret;
 822}
 823
 824static void parse_push(struct strbuf *buf)
 825{
 826        char **specs = NULL;
 827        int alloc_spec = 0, nr_spec = 0, i, ret;
 828
 829        do {
 830                if (!prefixcmp(buf->buf, "push ")) {
 831                        ALLOC_GROW(specs, nr_spec + 1, alloc_spec);
 832                        specs[nr_spec++] = xstrdup(buf->buf + 5);
 833                }
 834                else
 835                        die("http transport does not support %s", buf->buf);
 836
 837                strbuf_reset(buf);
 838                if (strbuf_getline(buf, stdin, '\n') == EOF)
 839                        goto free_specs;
 840                if (!*buf->buf)
 841                        break;
 842        } while (1);
 843
 844        ret = push(nr_spec, specs);
 845        printf("\n");
 846        fflush(stdout);
 847
 848        if (ret)
 849                exit(128); /* error already reported */
 850
 851 free_specs:
 852        for (i = 0; i < nr_spec; i++)
 853                free(specs[i]);
 854        free(specs);
 855}
 856
 857int main(int argc, const char **argv)
 858{
 859        struct strbuf buf = STRBUF_INIT;
 860        int nongit;
 861
 862        git_extract_argv0_path(argv[0]);
 863        setup_git_directory_gently(&nongit);
 864        if (argc < 2) {
 865                fprintf(stderr, "Remote needed\n");
 866                return 1;
 867        }
 868
 869        options.verbosity = 1;
 870        options.progress = !!isatty(2);
 871        options.thin = 1;
 872
 873        remote = remote_get(argv[1]);
 874
 875        if (argc > 2) {
 876                end_url_with_slash(&buf, argv[2]);
 877        } else {
 878                end_url_with_slash(&buf, remote->url[0]);
 879        }
 880
 881        url = strbuf_detach(&buf, NULL);
 882
 883        http_init(remote, url, 0);
 884
 885        do {
 886                if (strbuf_getline(&buf, stdin, '\n') == EOF) {
 887                        if (ferror(stdin))
 888                                fprintf(stderr, "Error reading command stream\n");
 889                        else
 890                                fprintf(stderr, "Unexpected end of command stream\n");
 891                        return 1;
 892                }
 893                if (buf.len == 0)
 894                        break;
 895                if (!prefixcmp(buf.buf, "fetch ")) {
 896                        if (nongit)
 897                                die("Fetch attempted without a local repo");
 898                        parse_fetch(&buf);
 899
 900                } else if (!strcmp(buf.buf, "list") || !prefixcmp(buf.buf, "list ")) {
 901                        int for_push = !!strstr(buf.buf + 4, "for-push");
 902                        output_refs(get_refs(for_push));
 903
 904                } else if (!prefixcmp(buf.buf, "push ")) {
 905                        parse_push(&buf);
 906
 907                } else if (!prefixcmp(buf.buf, "option ")) {
 908                        char *name = buf.buf + strlen("option ");
 909                        char *value = strchr(name, ' ');
 910                        int result;
 911
 912                        if (value)
 913                                *value++ = '\0';
 914                        else
 915                                value = "true";
 916
 917                        result = set_option(name, value);
 918                        if (!result)
 919                                printf("ok\n");
 920                        else if (result < 0)
 921                                printf("error invalid value\n");
 922                        else
 923                                printf("unsupported\n");
 924                        fflush(stdout);
 925
 926                } else if (!strcmp(buf.buf, "capabilities")) {
 927                        printf("fetch\n");
 928                        printf("option\n");
 929                        printf("push\n");
 930                        printf("\n");
 931                        fflush(stdout);
 932                } else {
 933                        fprintf(stderr, "Unknown command '%s'\n", buf.buf);
 934                        return 1;
 935                }
 936                strbuf_reset(&buf);
 937        } while (1);
 938
 939        http_cleanup();
 940
 941        return 0;
 942}