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