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