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