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