remote-curl.con commit remote-curl: reduce scope of rpc_state.result (b359030)
   1#include "cache.h"
   2#include "config.h"
   3#include "remote.h"
   4#include "connect.h"
   5#include "strbuf.h"
   6#include "walker.h"
   7#include "http.h"
   8#include "exec-cmd.h"
   9#include "run-command.h"
  10#include "pkt-line.h"
  11#include "string-list.h"
  12#include "sideband.h"
  13#include "argv-array.h"
  14#include "credential.h"
  15#include "sha1-array.h"
  16#include "send-pack.h"
  17#include "protocol.h"
  18#include "quote.h"
  19
  20static struct remote *remote;
  21/* always ends with a trailing slash */
  22static struct strbuf url = STRBUF_INIT;
  23
  24struct options {
  25        int verbosity;
  26        unsigned long depth;
  27        char *deepen_since;
  28        struct string_list deepen_not;
  29        struct string_list push_options;
  30        char *filter;
  31        unsigned progress : 1,
  32                check_self_contained_and_connected : 1,
  33                cloning : 1,
  34                update_shallow : 1,
  35                followtags : 1,
  36                dry_run : 1,
  37                thin : 1,
  38                /* One of the SEND_PACK_PUSH_CERT_* constants. */
  39                push_cert : 2,
  40                deepen_relative : 1,
  41                from_promisor : 1,
  42                no_dependents : 1;
  43};
  44static struct options options;
  45static struct string_list cas_options = STRING_LIST_INIT_DUP;
  46
  47static int set_option(const char *name, const char *value)
  48{
  49        if (!strcmp(name, "verbosity")) {
  50                char *end;
  51                int v = strtol(value, &end, 10);
  52                if (value == end || *end)
  53                        return -1;
  54                options.verbosity = v;
  55                return 0;
  56        }
  57        else if (!strcmp(name, "progress")) {
  58                if (!strcmp(value, "true"))
  59                        options.progress = 1;
  60                else if (!strcmp(value, "false"))
  61                        options.progress = 0;
  62                else
  63                        return -1;
  64                return 0;
  65        }
  66        else if (!strcmp(name, "depth")) {
  67                char *end;
  68                unsigned long v = strtoul(value, &end, 10);
  69                if (value == end || *end)
  70                        return -1;
  71                options.depth = v;
  72                return 0;
  73        }
  74        else if (!strcmp(name, "deepen-since")) {
  75                options.deepen_since = xstrdup(value);
  76                return 0;
  77        }
  78        else if (!strcmp(name, "deepen-not")) {
  79                string_list_append(&options.deepen_not, value);
  80                return 0;
  81        }
  82        else if (!strcmp(name, "deepen-relative")) {
  83                if (!strcmp(value, "true"))
  84                        options.deepen_relative = 1;
  85                else if (!strcmp(value, "false"))
  86                        options.deepen_relative = 0;
  87                else
  88                        return -1;
  89                return 0;
  90        }
  91        else if (!strcmp(name, "followtags")) {
  92                if (!strcmp(value, "true"))
  93                        options.followtags = 1;
  94                else if (!strcmp(value, "false"))
  95                        options.followtags = 0;
  96                else
  97                        return -1;
  98                return 0;
  99        }
 100        else if (!strcmp(name, "dry-run")) {
 101                if (!strcmp(value, "true"))
 102                        options.dry_run = 1;
 103                else if (!strcmp(value, "false"))
 104                        options.dry_run = 0;
 105                else
 106                        return -1;
 107                return 0;
 108        }
 109        else if (!strcmp(name, "check-connectivity")) {
 110                if (!strcmp(value, "true"))
 111                        options.check_self_contained_and_connected = 1;
 112                else if (!strcmp(value, "false"))
 113                        options.check_self_contained_and_connected = 0;
 114                else
 115                        return -1;
 116                return 0;
 117        }
 118        else if (!strcmp(name, "cas")) {
 119                struct strbuf val = STRBUF_INIT;
 120                strbuf_addf(&val, "--" CAS_OPT_NAME "=%s", value);
 121                string_list_append(&cas_options, val.buf);
 122                strbuf_release(&val);
 123                return 0;
 124        } else if (!strcmp(name, "cloning")) {
 125                if (!strcmp(value, "true"))
 126                        options.cloning = 1;
 127                else if (!strcmp(value, "false"))
 128                        options.cloning = 0;
 129                else
 130                        return -1;
 131                return 0;
 132        } else if (!strcmp(name, "update-shallow")) {
 133                if (!strcmp(value, "true"))
 134                        options.update_shallow = 1;
 135                else if (!strcmp(value, "false"))
 136                        options.update_shallow = 0;
 137                else
 138                        return -1;
 139                return 0;
 140        } else if (!strcmp(name, "pushcert")) {
 141                if (!strcmp(value, "true"))
 142                        options.push_cert = SEND_PACK_PUSH_CERT_ALWAYS;
 143                else if (!strcmp(value, "false"))
 144                        options.push_cert = SEND_PACK_PUSH_CERT_NEVER;
 145                else if (!strcmp(value, "if-asked"))
 146                        options.push_cert = SEND_PACK_PUSH_CERT_IF_ASKED;
 147                else
 148                        return -1;
 149                return 0;
 150        } else if (!strcmp(name, "push-option")) {
 151                if (*value != '"')
 152                        string_list_append(&options.push_options, value);
 153                else {
 154                        struct strbuf unquoted = STRBUF_INIT;
 155                        if (unquote_c_style(&unquoted, value, NULL) < 0)
 156                                die("invalid quoting in push-option value");
 157                        string_list_append_nodup(&options.push_options,
 158                                                 strbuf_detach(&unquoted, NULL));
 159                }
 160                return 0;
 161
 162#if LIBCURL_VERSION_NUM >= 0x070a08
 163        } else if (!strcmp(name, "family")) {
 164                if (!strcmp(value, "ipv4"))
 165                        git_curl_ipresolve = CURL_IPRESOLVE_V4;
 166                else if (!strcmp(value, "ipv6"))
 167                        git_curl_ipresolve = CURL_IPRESOLVE_V6;
 168                else if (!strcmp(value, "all"))
 169                        git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
 170                else
 171                        return -1;
 172                return 0;
 173#endif /* LIBCURL_VERSION_NUM >= 0x070a08 */
 174        } else if (!strcmp(name, "from-promisor")) {
 175                options.from_promisor = 1;
 176                return 0;
 177        } else if (!strcmp(name, "no-dependents")) {
 178                options.no_dependents = 1;
 179                return 0;
 180        } else if (!strcmp(name, "filter")) {
 181                options.filter = xstrdup(value);
 182                return 0;
 183        } else {
 184                return 1 /* unsupported */;
 185        }
 186}
 187
 188struct discovery {
 189        char *service;
 190        char *buf_alloc;
 191        char *buf;
 192        size_t len;
 193        struct ref *refs;
 194        struct oid_array shallow;
 195        enum protocol_version version;
 196        unsigned proto_git : 1;
 197};
 198static struct discovery *last_discovery;
 199
 200static struct ref *parse_git_refs(struct discovery *heads, int for_push)
 201{
 202        struct ref *list = NULL;
 203        struct packet_reader reader;
 204
 205        packet_reader_init(&reader, -1, heads->buf, heads->len,
 206                           PACKET_READ_CHOMP_NEWLINE |
 207                           PACKET_READ_GENTLE_ON_EOF |
 208                           PACKET_READ_DIE_ON_ERR_PACKET);
 209
 210        heads->version = discover_version(&reader);
 211        switch (heads->version) {
 212        case protocol_v2:
 213                /*
 214                 * Do nothing.  This isn't a list of refs but rather a
 215                 * capability advertisement.  Client would have run
 216                 * 'stateless-connect' so we'll dump this capability listing
 217                 * and let them request the refs themselves.
 218                 */
 219                break;
 220        case protocol_v1:
 221        case protocol_v0:
 222                get_remote_heads(&reader, &list, for_push ? REF_NORMAL : 0,
 223                                 NULL, &heads->shallow);
 224                break;
 225        case protocol_unknown_version:
 226                BUG("unknown protocol version");
 227        }
 228
 229        return list;
 230}
 231
 232static struct ref *parse_info_refs(struct discovery *heads)
 233{
 234        char *data, *start, *mid;
 235        char *ref_name;
 236        int i = 0;
 237
 238        struct ref *refs = NULL;
 239        struct ref *ref = NULL;
 240        struct ref *last_ref = NULL;
 241
 242        data = heads->buf;
 243        start = NULL;
 244        mid = data;
 245        while (i < heads->len) {
 246                if (!start) {
 247                        start = &data[i];
 248                }
 249                if (data[i] == '\t')
 250                        mid = &data[i];
 251                if (data[i] == '\n') {
 252                        if (mid - start != 40)
 253                                die("%sinfo/refs not valid: is this a git repository?",
 254                                    url.buf);
 255                        data[i] = 0;
 256                        ref_name = mid + 1;
 257                        ref = alloc_ref(ref_name);
 258                        get_oid_hex(start, &ref->old_oid);
 259                        if (!refs)
 260                                refs = ref;
 261                        if (last_ref)
 262                                last_ref->next = ref;
 263                        last_ref = ref;
 264                        start = NULL;
 265                }
 266                i++;
 267        }
 268
 269        ref = alloc_ref("HEAD");
 270        if (!http_fetch_ref(url.buf, ref) &&
 271            !resolve_remote_symref(ref, refs)) {
 272                ref->next = refs;
 273                refs = ref;
 274        } else {
 275                free(ref);
 276        }
 277
 278        return refs;
 279}
 280
 281static void free_discovery(struct discovery *d)
 282{
 283        if (d) {
 284                if (d == last_discovery)
 285                        last_discovery = NULL;
 286                free(d->shallow.oid);
 287                free(d->buf_alloc);
 288                free_refs(d->refs);
 289                free(d->service);
 290                free(d);
 291        }
 292}
 293
 294static int show_http_message(struct strbuf *type, struct strbuf *charset,
 295                             struct strbuf *msg)
 296{
 297        const char *p, *eol;
 298
 299        /*
 300         * We only show text/plain parts, as other types are likely
 301         * to be ugly to look at on the user's terminal.
 302         */
 303        if (strcmp(type->buf, "text/plain"))
 304                return -1;
 305        if (charset->len)
 306                strbuf_reencode(msg, charset->buf, get_log_output_encoding());
 307
 308        strbuf_trim(msg);
 309        if (!msg->len)
 310                return -1;
 311
 312        p = msg->buf;
 313        do {
 314                eol = strchrnul(p, '\n');
 315                fprintf(stderr, "remote: %.*s\n", (int)(eol - p), p);
 316                p = eol + 1;
 317        } while(*eol);
 318        return 0;
 319}
 320
 321static int get_protocol_http_header(enum protocol_version version,
 322                                    struct strbuf *header)
 323{
 324        if (version > 0) {
 325                strbuf_addf(header, GIT_PROTOCOL_HEADER ": version=%d",
 326                            version);
 327
 328                return 1;
 329        }
 330
 331        return 0;
 332}
 333
 334static void check_smart_http(struct discovery *d, const char *service,
 335                             struct strbuf *type)
 336{
 337        const char *p;
 338        struct packet_reader reader;
 339
 340        /*
 341         * If we don't see x-$service-advertisement, then it's not smart-http.
 342         * But once we do, we commit to it and assume any other protocol
 343         * violations are hard errors.
 344         */
 345        if (!skip_prefix(type->buf, "application/x-", &p) ||
 346            !skip_prefix(p, service, &p) ||
 347            strcmp(p, "-advertisement"))
 348                return;
 349
 350        packet_reader_init(&reader, -1, d->buf, d->len,
 351                           PACKET_READ_CHOMP_NEWLINE |
 352                           PACKET_READ_DIE_ON_ERR_PACKET);
 353        if (packet_reader_read(&reader) != PACKET_READ_NORMAL)
 354                die("invalid server response; expected service, got flush packet");
 355
 356        if (skip_prefix(reader.line, "# service=", &p) && !strcmp(p, service)) {
 357                /*
 358                 * The header can include additional metadata lines, up
 359                 * until a packet flush marker.  Ignore these now, but
 360                 * in the future we might start to scan them.
 361                 */
 362                for (;;) {
 363                        packet_reader_read(&reader);
 364                        if (reader.pktlen <= 0) {
 365                                break;
 366                        }
 367                }
 368
 369                /*
 370                 * v0 smart http; callers expect us to soak up the
 371                 * service and header packets
 372                 */
 373                d->buf = reader.src_buffer;
 374                d->len = reader.src_len;
 375                d->proto_git = 1;
 376
 377        } else if (!strcmp(reader.line, "version 2")) {
 378                /*
 379                 * v2 smart http; do not consume version packet, which will
 380                 * be handled elsewhere.
 381                 */
 382                d->proto_git = 1;
 383
 384        } else {
 385                die("invalid server response; got '%s'", reader.line);
 386        }
 387}
 388
 389static struct discovery *discover_refs(const char *service, int for_push)
 390{
 391        struct strbuf type = STRBUF_INIT;
 392        struct strbuf charset = STRBUF_INIT;
 393        struct strbuf buffer = STRBUF_INIT;
 394        struct strbuf refs_url = STRBUF_INIT;
 395        struct strbuf effective_url = STRBUF_INIT;
 396        struct strbuf protocol_header = STRBUF_INIT;
 397        struct string_list extra_headers = STRING_LIST_INIT_DUP;
 398        struct discovery *last = last_discovery;
 399        int http_ret, maybe_smart = 0;
 400        struct http_get_options http_options;
 401        enum protocol_version version = get_protocol_version_config();
 402
 403        if (last && !strcmp(service, last->service))
 404                return last;
 405        free_discovery(last);
 406
 407        strbuf_addf(&refs_url, "%sinfo/refs", url.buf);
 408        if ((starts_with(url.buf, "http://") || starts_with(url.buf, "https://")) &&
 409             git_env_bool("GIT_SMART_HTTP", 1)) {
 410                maybe_smart = 1;
 411                if (!strchr(url.buf, '?'))
 412                        strbuf_addch(&refs_url, '?');
 413                else
 414                        strbuf_addch(&refs_url, '&');
 415                strbuf_addf(&refs_url, "service=%s", service);
 416        }
 417
 418        /*
 419         * NEEDSWORK: If we are trying to use protocol v2 and we are planning
 420         * to perform a push, then fallback to v0 since the client doesn't know
 421         * how to push yet using v2.
 422         */
 423        if (version == protocol_v2 && !strcmp("git-receive-pack", service))
 424                version = protocol_v0;
 425
 426        /* Add the extra Git-Protocol header */
 427        if (get_protocol_http_header(version, &protocol_header))
 428                string_list_append(&extra_headers, protocol_header.buf);
 429
 430        memset(&http_options, 0, sizeof(http_options));
 431        http_options.content_type = &type;
 432        http_options.charset = &charset;
 433        http_options.effective_url = &effective_url;
 434        http_options.base_url = &url;
 435        http_options.extra_headers = &extra_headers;
 436        http_options.initial_request = 1;
 437        http_options.no_cache = 1;
 438
 439        http_ret = http_get_strbuf(refs_url.buf, &buffer, &http_options);
 440        switch (http_ret) {
 441        case HTTP_OK:
 442                break;
 443        case HTTP_MISSING_TARGET:
 444                show_http_message(&type, &charset, &buffer);
 445                die("repository '%s' not found", url.buf);
 446        case HTTP_NOAUTH:
 447                show_http_message(&type, &charset, &buffer);
 448                die("Authentication failed for '%s'", url.buf);
 449        default:
 450                show_http_message(&type, &charset, &buffer);
 451                die("unable to access '%s': %s", url.buf, curl_errorstr);
 452        }
 453
 454        if (options.verbosity && !starts_with(refs_url.buf, url.buf))
 455                warning(_("redirecting to %s"), url.buf);
 456
 457        last= xcalloc(1, sizeof(*last_discovery));
 458        last->service = xstrdup(service);
 459        last->buf_alloc = strbuf_detach(&buffer, &last->len);
 460        last->buf = last->buf_alloc;
 461
 462        if (maybe_smart)
 463                check_smart_http(last, service, &type);
 464
 465        if (last->proto_git)
 466                last->refs = parse_git_refs(last, for_push);
 467        else
 468                last->refs = parse_info_refs(last);
 469
 470        strbuf_release(&refs_url);
 471        strbuf_release(&type);
 472        strbuf_release(&charset);
 473        strbuf_release(&effective_url);
 474        strbuf_release(&buffer);
 475        strbuf_release(&protocol_header);
 476        string_list_clear(&extra_headers, 0);
 477        last_discovery = last;
 478        return last;
 479}
 480
 481static struct ref *get_refs(int for_push)
 482{
 483        struct discovery *heads;
 484
 485        if (for_push)
 486                heads = discover_refs("git-receive-pack", for_push);
 487        else
 488                heads = discover_refs("git-upload-pack", for_push);
 489
 490        return heads->refs;
 491}
 492
 493static void output_refs(struct ref *refs)
 494{
 495        struct ref *posn;
 496        for (posn = refs; posn; posn = posn->next) {
 497                if (posn->symref)
 498                        printf("@%s %s\n", posn->symref, posn->name);
 499                else
 500                        printf("%s %s\n", oid_to_hex(&posn->old_oid), posn->name);
 501        }
 502        printf("\n");
 503        fflush(stdout);
 504}
 505
 506struct rpc_state {
 507        const char *service_name;
 508        char *service_url;
 509        char *hdr_content_type;
 510        char *hdr_accept;
 511        char *protocol_header;
 512        char *buf;
 513        size_t alloc;
 514        size_t len;
 515        size_t pos;
 516        int in;
 517        int out;
 518        int any_written;
 519        unsigned gzip_request : 1;
 520        unsigned initial_buffer : 1;
 521};
 522
 523static size_t rpc_out(void *ptr, size_t eltsize,
 524                size_t nmemb, void *buffer_)
 525{
 526        size_t max = eltsize * nmemb;
 527        struct rpc_state *rpc = buffer_;
 528        size_t avail = rpc->len - rpc->pos;
 529
 530        if (!avail) {
 531                rpc->initial_buffer = 0;
 532                avail = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
 533                if (!avail)
 534                        return 0;
 535                rpc->pos = 0;
 536                rpc->len = avail;
 537        }
 538
 539        if (max < avail)
 540                avail = max;
 541        memcpy(ptr, rpc->buf + rpc->pos, avail);
 542        rpc->pos += avail;
 543        return avail;
 544}
 545
 546#ifndef NO_CURL_IOCTL
 547static curlioerr rpc_ioctl(CURL *handle, int cmd, void *clientp)
 548{
 549        struct rpc_state *rpc = clientp;
 550
 551        switch (cmd) {
 552        case CURLIOCMD_NOP:
 553                return CURLIOE_OK;
 554
 555        case CURLIOCMD_RESTARTREAD:
 556                if (rpc->initial_buffer) {
 557                        rpc->pos = 0;
 558                        return CURLIOE_OK;
 559                }
 560                error("unable to rewind rpc post data - try increasing http.postBuffer");
 561                return CURLIOE_FAILRESTART;
 562
 563        default:
 564                return CURLIOE_UNKNOWNCMD;
 565        }
 566}
 567#endif
 568
 569struct rpc_in_data {
 570        struct rpc_state *rpc;
 571        struct active_request_slot *slot;
 572};
 573
 574/*
 575 * A callback for CURLOPT_WRITEFUNCTION. The return value is the bytes consumed
 576 * from ptr.
 577 */
 578static size_t rpc_in(char *ptr, size_t eltsize,
 579                size_t nmemb, void *buffer_)
 580{
 581        size_t size = eltsize * nmemb;
 582        struct rpc_in_data *data = buffer_;
 583        long response_code;
 584
 585        if (curl_easy_getinfo(data->slot->curl, CURLINFO_RESPONSE_CODE,
 586                              &response_code) != CURLE_OK)
 587                return size;
 588        if (response_code >= 300)
 589                return size;
 590        if (size)
 591                data->rpc->any_written = 1;
 592        write_or_die(data->rpc->in, ptr, size);
 593        return size;
 594}
 595
 596static int run_slot(struct active_request_slot *slot,
 597                    struct slot_results *results)
 598{
 599        int err;
 600        struct slot_results results_buf;
 601
 602        if (!results)
 603                results = &results_buf;
 604
 605        err = run_one_slot(slot, results);
 606
 607        if (err != HTTP_OK && err != HTTP_REAUTH) {
 608                struct strbuf msg = STRBUF_INIT;
 609                if (results->http_code && results->http_code != 200)
 610                        strbuf_addf(&msg, "HTTP %ld", results->http_code);
 611                if (results->curl_result != CURLE_OK) {
 612                        if (msg.len)
 613                                strbuf_addch(&msg, ' ');
 614                        strbuf_addf(&msg, "curl %d", results->curl_result);
 615                        if (curl_errorstr[0]) {
 616                                strbuf_addch(&msg, ' ');
 617                                strbuf_addstr(&msg, curl_errorstr);
 618                        }
 619                }
 620                error("RPC failed; %s", msg.buf);
 621                strbuf_release(&msg);
 622        }
 623
 624        return err;
 625}
 626
 627static int probe_rpc(struct rpc_state *rpc, struct slot_results *results)
 628{
 629        struct active_request_slot *slot;
 630        struct curl_slist *headers = http_copy_default_headers();
 631        struct strbuf buf = STRBUF_INIT;
 632        int err;
 633
 634        slot = get_active_slot();
 635
 636        headers = curl_slist_append(headers, rpc->hdr_content_type);
 637        headers = curl_slist_append(headers, rpc->hdr_accept);
 638
 639        curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
 640        curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
 641        curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
 642        curl_easy_setopt(slot->curl, CURLOPT_ENCODING, NULL);
 643        curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, "0000");
 644        curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, 4);
 645        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
 646        curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
 647        curl_easy_setopt(slot->curl, CURLOPT_FILE, &buf);
 648
 649        err = run_slot(slot, results);
 650
 651        curl_slist_free_all(headers);
 652        strbuf_release(&buf);
 653        return err;
 654}
 655
 656static curl_off_t xcurl_off_t(size_t len)
 657{
 658        uintmax_t size = len;
 659        if (size > maximum_signed_value_of_type(curl_off_t))
 660                die("cannot handle pushes this big");
 661        return (curl_off_t)size;
 662}
 663
 664static int post_rpc(struct rpc_state *rpc)
 665{
 666        struct active_request_slot *slot;
 667        struct curl_slist *headers = http_copy_default_headers();
 668        int use_gzip = rpc->gzip_request;
 669        char *gzip_body = NULL;
 670        size_t gzip_size = 0;
 671        int err, large_request = 0;
 672        int needs_100_continue = 0;
 673        struct rpc_in_data rpc_in_data;
 674
 675        /* Try to load the entire request, if we can fit it into the
 676         * allocated buffer space we can use HTTP/1.0 and avoid the
 677         * chunked encoding mess.
 678         */
 679        while (1) {
 680                size_t left = rpc->alloc - rpc->len;
 681                char *buf = rpc->buf + rpc->len;
 682                int n;
 683
 684                if (left < LARGE_PACKET_MAX) {
 685                        large_request = 1;
 686                        use_gzip = 0;
 687                        break;
 688                }
 689
 690                n = packet_read(rpc->out, NULL, NULL, buf, left, 0);
 691                if (!n)
 692                        break;
 693                rpc->len += n;
 694        }
 695
 696        if (large_request) {
 697                struct slot_results results;
 698
 699                do {
 700                        err = probe_rpc(rpc, &results);
 701                        if (err == HTTP_REAUTH)
 702                                credential_fill(&http_auth);
 703                } while (err == HTTP_REAUTH);
 704                if (err != HTTP_OK)
 705                        return -1;
 706
 707                if (results.auth_avail & CURLAUTH_GSSNEGOTIATE)
 708                        needs_100_continue = 1;
 709        }
 710
 711        headers = curl_slist_append(headers, rpc->hdr_content_type);
 712        headers = curl_slist_append(headers, rpc->hdr_accept);
 713        headers = curl_slist_append(headers, needs_100_continue ?
 714                "Expect: 100-continue" : "Expect:");
 715
 716        /* Add the extra Git-Protocol header */
 717        if (rpc->protocol_header)
 718                headers = curl_slist_append(headers, rpc->protocol_header);
 719
 720retry:
 721        slot = get_active_slot();
 722
 723        curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
 724        curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
 725        curl_easy_setopt(slot->curl, CURLOPT_URL, rpc->service_url);
 726        curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
 727
 728        if (large_request) {
 729                /* The request body is large and the size cannot be predicted.
 730                 * We must use chunked encoding to send it.
 731                 */
 732                headers = curl_slist_append(headers, "Transfer-Encoding: chunked");
 733                rpc->initial_buffer = 1;
 734                curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, rpc_out);
 735                curl_easy_setopt(slot->curl, CURLOPT_INFILE, rpc);
 736#ifndef NO_CURL_IOCTL
 737                curl_easy_setopt(slot->curl, CURLOPT_IOCTLFUNCTION, rpc_ioctl);
 738                curl_easy_setopt(slot->curl, CURLOPT_IOCTLDATA, rpc);
 739#endif
 740                if (options.verbosity > 1) {
 741                        fprintf(stderr, "POST %s (chunked)\n", rpc->service_name);
 742                        fflush(stderr);
 743                }
 744
 745        } else if (gzip_body) {
 746                /*
 747                 * If we are looping to retry authentication, then the previous
 748                 * run will have set up the headers and gzip buffer already,
 749                 * and we just need to send it.
 750                 */
 751                curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
 752                curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(gzip_size));
 753
 754        } else if (use_gzip && 1024 < rpc->len) {
 755                /* The client backend isn't giving us compressed data so
 756                 * we can try to deflate it ourselves, this may save on
 757                 * the transfer time.
 758                 */
 759                git_zstream stream;
 760                int ret;
 761
 762                git_deflate_init_gzip(&stream, Z_BEST_COMPRESSION);
 763                gzip_size = git_deflate_bound(&stream, rpc->len);
 764                gzip_body = xmalloc(gzip_size);
 765
 766                stream.next_in = (unsigned char *)rpc->buf;
 767                stream.avail_in = rpc->len;
 768                stream.next_out = (unsigned char *)gzip_body;
 769                stream.avail_out = gzip_size;
 770
 771                ret = git_deflate(&stream, Z_FINISH);
 772                if (ret != Z_STREAM_END)
 773                        die("cannot deflate request; zlib deflate error %d", ret);
 774
 775                ret = git_deflate_end_gently(&stream);
 776                if (ret != Z_OK)
 777                        die("cannot deflate request; zlib end error %d", ret);
 778
 779                gzip_size = stream.total_out;
 780
 781                headers = curl_slist_append(headers, "Content-Encoding: gzip");
 782                curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
 783                curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(gzip_size));
 784
 785                if (options.verbosity > 1) {
 786                        fprintf(stderr, "POST %s (gzip %lu to %lu bytes)\n",
 787                                rpc->service_name,
 788                                (unsigned long)rpc->len, (unsigned long)gzip_size);
 789                        fflush(stderr);
 790                }
 791        } else {
 792                /* We know the complete request size in advance, use the
 793                 * more normal Content-Length approach.
 794                 */
 795                curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, rpc->buf);
 796                curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE_LARGE, xcurl_off_t(rpc->len));
 797                if (options.verbosity > 1) {
 798                        fprintf(stderr, "POST %s (%lu bytes)\n",
 799                                rpc->service_name, (unsigned long)rpc->len);
 800                        fflush(stderr);
 801                }
 802        }
 803
 804        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
 805        curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, rpc_in);
 806        rpc_in_data.rpc = rpc;
 807        rpc_in_data.slot = slot;
 808        curl_easy_setopt(slot->curl, CURLOPT_FILE, &rpc_in_data);
 809        curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
 810
 811
 812        rpc->any_written = 0;
 813        err = run_slot(slot, NULL);
 814        if (err == HTTP_REAUTH && !large_request) {
 815                credential_fill(&http_auth);
 816                goto retry;
 817        }
 818        if (err != HTTP_OK)
 819                err = -1;
 820
 821        if (!rpc->any_written)
 822                err = -1;
 823
 824        curl_slist_free_all(headers);
 825        free(gzip_body);
 826        return err;
 827}
 828
 829static int rpc_service(struct rpc_state *rpc, struct discovery *heads,
 830                       const char **client_argv, const struct strbuf *preamble,
 831                       struct strbuf *rpc_result)
 832{
 833        const char *svc = rpc->service_name;
 834        struct strbuf buf = STRBUF_INIT;
 835        struct child_process client = CHILD_PROCESS_INIT;
 836        int err = 0;
 837
 838        client.in = -1;
 839        client.out = -1;
 840        client.git_cmd = 1;
 841        client.argv = client_argv;
 842        if (start_command(&client))
 843                exit(1);
 844        write_or_die(client.in, preamble->buf, preamble->len);
 845        if (heads)
 846                write_or_die(client.in, heads->buf, heads->len);
 847
 848        rpc->alloc = http_post_buffer;
 849        rpc->buf = xmalloc(rpc->alloc);
 850        rpc->in = client.in;
 851        rpc->out = client.out;
 852
 853        strbuf_addf(&buf, "%s%s", url.buf, svc);
 854        rpc->service_url = strbuf_detach(&buf, NULL);
 855
 856        strbuf_addf(&buf, "Content-Type: application/x-%s-request", svc);
 857        rpc->hdr_content_type = strbuf_detach(&buf, NULL);
 858
 859        strbuf_addf(&buf, "Accept: application/x-%s-result", svc);
 860        rpc->hdr_accept = strbuf_detach(&buf, NULL);
 861
 862        if (get_protocol_http_header(heads->version, &buf))
 863                rpc->protocol_header = strbuf_detach(&buf, NULL);
 864        else
 865                rpc->protocol_header = NULL;
 866
 867        while (!err) {
 868                int n = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
 869                if (!n)
 870                        break;
 871                rpc->pos = 0;
 872                rpc->len = n;
 873                err |= post_rpc(rpc);
 874        }
 875
 876        close(client.in);
 877        client.in = -1;
 878        if (!err) {
 879                strbuf_read(rpc_result, client.out, 0);
 880        } else {
 881                char buf[4096];
 882                for (;;)
 883                        if (xread(client.out, buf, sizeof(buf)) <= 0)
 884                                break;
 885        }
 886
 887        close(client.out);
 888        client.out = -1;
 889
 890        err |= finish_command(&client);
 891        free(rpc->service_url);
 892        free(rpc->hdr_content_type);
 893        free(rpc->hdr_accept);
 894        free(rpc->protocol_header);
 895        free(rpc->buf);
 896        strbuf_release(&buf);
 897        return err;
 898}
 899
 900static int fetch_dumb(int nr_heads, struct ref **to_fetch)
 901{
 902        struct walker *walker;
 903        char **targets;
 904        int ret, i;
 905
 906        ALLOC_ARRAY(targets, nr_heads);
 907        if (options.depth || options.deepen_since)
 908                die("dumb http transport does not support shallow capabilities");
 909        for (i = 0; i < nr_heads; i++)
 910                targets[i] = xstrdup(oid_to_hex(&to_fetch[i]->old_oid));
 911
 912        walker = get_http_walker(url.buf);
 913        walker->get_verbosely = options.verbosity >= 3;
 914        walker->get_recover = 0;
 915        ret = walker_fetch(walker, nr_heads, targets, NULL, NULL);
 916        walker_free(walker);
 917
 918        for (i = 0; i < nr_heads; i++)
 919                free(targets[i]);
 920        free(targets);
 921
 922        return ret ? error("fetch failed.") : 0;
 923}
 924
 925static int fetch_git(struct discovery *heads,
 926        int nr_heads, struct ref **to_fetch)
 927{
 928        struct rpc_state rpc;
 929        struct strbuf preamble = STRBUF_INIT;
 930        int i, err;
 931        struct argv_array args = ARGV_ARRAY_INIT;
 932        struct strbuf rpc_result = STRBUF_INIT;
 933
 934        argv_array_pushl(&args, "fetch-pack", "--stateless-rpc",
 935                         "--stdin", "--lock-pack", NULL);
 936        if (options.followtags)
 937                argv_array_push(&args, "--include-tag");
 938        if (options.thin)
 939                argv_array_push(&args, "--thin");
 940        if (options.verbosity >= 3)
 941                argv_array_pushl(&args, "-v", "-v", NULL);
 942        if (options.check_self_contained_and_connected)
 943                argv_array_push(&args, "--check-self-contained-and-connected");
 944        if (options.cloning)
 945                argv_array_push(&args, "--cloning");
 946        if (options.update_shallow)
 947                argv_array_push(&args, "--update-shallow");
 948        if (!options.progress)
 949                argv_array_push(&args, "--no-progress");
 950        if (options.depth)
 951                argv_array_pushf(&args, "--depth=%lu", options.depth);
 952        if (options.deepen_since)
 953                argv_array_pushf(&args, "--shallow-since=%s", options.deepen_since);
 954        for (i = 0; i < options.deepen_not.nr; i++)
 955                argv_array_pushf(&args, "--shallow-exclude=%s",
 956                                 options.deepen_not.items[i].string);
 957        if (options.deepen_relative && options.depth)
 958                argv_array_push(&args, "--deepen-relative");
 959        if (options.from_promisor)
 960                argv_array_push(&args, "--from-promisor");
 961        if (options.no_dependents)
 962                argv_array_push(&args, "--no-dependents");
 963        if (options.filter)
 964                argv_array_pushf(&args, "--filter=%s", options.filter);
 965        argv_array_push(&args, url.buf);
 966
 967        for (i = 0; i < nr_heads; i++) {
 968                struct ref *ref = to_fetch[i];
 969                if (!*ref->name)
 970                        die("cannot fetch by sha1 over smart http");
 971                packet_buf_write(&preamble, "%s %s\n",
 972                                 oid_to_hex(&ref->old_oid), ref->name);
 973        }
 974        packet_buf_flush(&preamble);
 975
 976        memset(&rpc, 0, sizeof(rpc));
 977        rpc.service_name = "git-upload-pack",
 978        rpc.gzip_request = 1;
 979
 980        err = rpc_service(&rpc, heads, args.argv, &preamble, &rpc_result);
 981        if (rpc_result.len)
 982                write_or_die(1, rpc_result.buf, rpc_result.len);
 983        strbuf_release(&rpc_result);
 984        strbuf_release(&preamble);
 985        argv_array_clear(&args);
 986        return err;
 987}
 988
 989static int fetch(int nr_heads, struct ref **to_fetch)
 990{
 991        struct discovery *d = discover_refs("git-upload-pack", 0);
 992        if (d->proto_git)
 993                return fetch_git(d, nr_heads, to_fetch);
 994        else
 995                return fetch_dumb(nr_heads, to_fetch);
 996}
 997
 998static void parse_fetch(struct strbuf *buf)
 999{
1000        struct ref **to_fetch = NULL;
1001        struct ref *list_head = NULL;
1002        struct ref **list = &list_head;
1003        int alloc_heads = 0, nr_heads = 0;
1004
1005        do {
1006                const char *p;
1007                if (skip_prefix(buf->buf, "fetch ", &p)) {
1008                        const char *name;
1009                        struct ref *ref;
1010                        struct object_id old_oid;
1011
1012                        if (get_oid_hex(p, &old_oid))
1013                                die("protocol error: expected sha/ref, got %s'", p);
1014                        if (p[GIT_SHA1_HEXSZ] == ' ')
1015                                name = p + GIT_SHA1_HEXSZ + 1;
1016                        else if (!p[GIT_SHA1_HEXSZ])
1017                                name = "";
1018                        else
1019                                die("protocol error: expected sha/ref, got %s'", p);
1020
1021                        ref = alloc_ref(name);
1022                        oidcpy(&ref->old_oid, &old_oid);
1023
1024                        *list = ref;
1025                        list = &ref->next;
1026
1027                        ALLOC_GROW(to_fetch, nr_heads + 1, alloc_heads);
1028                        to_fetch[nr_heads++] = ref;
1029                }
1030                else
1031                        die("http transport does not support %s", buf->buf);
1032
1033                strbuf_reset(buf);
1034                if (strbuf_getline_lf(buf, stdin) == EOF)
1035                        return;
1036                if (!*buf->buf)
1037                        break;
1038        } while (1);
1039
1040        if (fetch(nr_heads, to_fetch))
1041                exit(128); /* error already reported */
1042        free_refs(list_head);
1043        free(to_fetch);
1044
1045        printf("\n");
1046        fflush(stdout);
1047        strbuf_reset(buf);
1048}
1049
1050static int push_dav(int nr_spec, char **specs)
1051{
1052        struct child_process child = CHILD_PROCESS_INIT;
1053        size_t i;
1054
1055        child.git_cmd = 1;
1056        argv_array_push(&child.args, "http-push");
1057        argv_array_push(&child.args, "--helper-status");
1058        if (options.dry_run)
1059                argv_array_push(&child.args, "--dry-run");
1060        if (options.verbosity > 1)
1061                argv_array_push(&child.args, "--verbose");
1062        argv_array_push(&child.args, url.buf);
1063        for (i = 0; i < nr_spec; i++)
1064                argv_array_push(&child.args, specs[i]);
1065
1066        if (run_command(&child))
1067                die("git-http-push failed");
1068        return 0;
1069}
1070
1071static int push_git(struct discovery *heads, int nr_spec, char **specs)
1072{
1073        struct rpc_state rpc;
1074        int i, err;
1075        struct argv_array args;
1076        struct string_list_item *cas_option;
1077        struct strbuf preamble = STRBUF_INIT;
1078        struct strbuf rpc_result = STRBUF_INIT;
1079
1080        argv_array_init(&args);
1081        argv_array_pushl(&args, "send-pack", "--stateless-rpc", "--helper-status",
1082                         NULL);
1083
1084        if (options.thin)
1085                argv_array_push(&args, "--thin");
1086        if (options.dry_run)
1087                argv_array_push(&args, "--dry-run");
1088        if (options.push_cert == SEND_PACK_PUSH_CERT_ALWAYS)
1089                argv_array_push(&args, "--signed=yes");
1090        else if (options.push_cert == SEND_PACK_PUSH_CERT_IF_ASKED)
1091                argv_array_push(&args, "--signed=if-asked");
1092        if (options.verbosity == 0)
1093                argv_array_push(&args, "--quiet");
1094        else if (options.verbosity > 1)
1095                argv_array_push(&args, "--verbose");
1096        for (i = 0; i < options.push_options.nr; i++)
1097                argv_array_pushf(&args, "--push-option=%s",
1098                                 options.push_options.items[i].string);
1099        argv_array_push(&args, options.progress ? "--progress" : "--no-progress");
1100        for_each_string_list_item(cas_option, &cas_options)
1101                argv_array_push(&args, cas_option->string);
1102        argv_array_push(&args, url.buf);
1103
1104        argv_array_push(&args, "--stdin");
1105        for (i = 0; i < nr_spec; i++)
1106                packet_buf_write(&preamble, "%s\n", specs[i]);
1107        packet_buf_flush(&preamble);
1108
1109        memset(&rpc, 0, sizeof(rpc));
1110        rpc.service_name = "git-receive-pack",
1111
1112        err = rpc_service(&rpc, heads, args.argv, &preamble, &rpc_result);
1113        if (rpc_result.len)
1114                write_or_die(1, rpc_result.buf, rpc_result.len);
1115        strbuf_release(&rpc_result);
1116        strbuf_release(&preamble);
1117        argv_array_clear(&args);
1118        return err;
1119}
1120
1121static int push(int nr_spec, char **specs)
1122{
1123        struct discovery *heads = discover_refs("git-receive-pack", 1);
1124        int ret;
1125
1126        if (heads->proto_git)
1127                ret = push_git(heads, nr_spec, specs);
1128        else
1129                ret = push_dav(nr_spec, specs);
1130        free_discovery(heads);
1131        return ret;
1132}
1133
1134static void parse_push(struct strbuf *buf)
1135{
1136        char **specs = NULL;
1137        int alloc_spec = 0, nr_spec = 0, i, ret;
1138
1139        do {
1140                if (starts_with(buf->buf, "push ")) {
1141                        ALLOC_GROW(specs, nr_spec + 1, alloc_spec);
1142                        specs[nr_spec++] = xstrdup(buf->buf + 5);
1143                }
1144                else
1145                        die("http transport does not support %s", buf->buf);
1146
1147                strbuf_reset(buf);
1148                if (strbuf_getline_lf(buf, stdin) == EOF)
1149                        goto free_specs;
1150                if (!*buf->buf)
1151                        break;
1152        } while (1);
1153
1154        ret = push(nr_spec, specs);
1155        printf("\n");
1156        fflush(stdout);
1157
1158        if (ret)
1159                exit(128); /* error already reported */
1160
1161 free_specs:
1162        for (i = 0; i < nr_spec; i++)
1163                free(specs[i]);
1164        free(specs);
1165}
1166
1167/*
1168 * Used to represent the state of a connection to an HTTP server when
1169 * communicating using git's wire-protocol version 2.
1170 */
1171struct proxy_state {
1172        char *service_name;
1173        char *service_url;
1174        struct curl_slist *headers;
1175        struct strbuf request_buffer;
1176        int in;
1177        int out;
1178        struct packet_reader reader;
1179        size_t pos;
1180        int seen_flush;
1181};
1182
1183static void proxy_state_init(struct proxy_state *p, const char *service_name,
1184                             enum protocol_version version)
1185{
1186        struct strbuf buf = STRBUF_INIT;
1187
1188        memset(p, 0, sizeof(*p));
1189        p->service_name = xstrdup(service_name);
1190
1191        p->in = 0;
1192        p->out = 1;
1193        strbuf_init(&p->request_buffer, 0);
1194
1195        strbuf_addf(&buf, "%s%s", url.buf, p->service_name);
1196        p->service_url = strbuf_detach(&buf, NULL);
1197
1198        p->headers = http_copy_default_headers();
1199
1200        strbuf_addf(&buf, "Content-Type: application/x-%s-request", p->service_name);
1201        p->headers = curl_slist_append(p->headers, buf.buf);
1202        strbuf_reset(&buf);
1203
1204        strbuf_addf(&buf, "Accept: application/x-%s-result", p->service_name);
1205        p->headers = curl_slist_append(p->headers, buf.buf);
1206        strbuf_reset(&buf);
1207
1208        p->headers = curl_slist_append(p->headers, "Transfer-Encoding: chunked");
1209
1210        /* Add the Git-Protocol header */
1211        if (get_protocol_http_header(version, &buf))
1212                p->headers = curl_slist_append(p->headers, buf.buf);
1213
1214        packet_reader_init(&p->reader, p->in, NULL, 0,
1215                           PACKET_READ_GENTLE_ON_EOF |
1216                           PACKET_READ_DIE_ON_ERR_PACKET);
1217
1218        strbuf_release(&buf);
1219}
1220
1221static void proxy_state_clear(struct proxy_state *p)
1222{
1223        free(p->service_name);
1224        free(p->service_url);
1225        curl_slist_free_all(p->headers);
1226        strbuf_release(&p->request_buffer);
1227}
1228
1229/*
1230 * CURLOPT_READFUNCTION callback function.
1231 * Attempts to copy over a single packet-line at a time into the
1232 * curl provided buffer.
1233 */
1234static size_t proxy_in(char *buffer, size_t eltsize,
1235                       size_t nmemb, void *userdata)
1236{
1237        size_t max;
1238        struct proxy_state *p = userdata;
1239        size_t avail = p->request_buffer.len - p->pos;
1240
1241
1242        if (eltsize != 1)
1243                BUG("curl read callback called with size = %"PRIuMAX" != 1",
1244                    (uintmax_t)eltsize);
1245        max = nmemb;
1246
1247        if (!avail) {
1248                if (p->seen_flush) {
1249                        p->seen_flush = 0;
1250                        return 0;
1251                }
1252
1253                strbuf_reset(&p->request_buffer);
1254                switch (packet_reader_read(&p->reader)) {
1255                case PACKET_READ_EOF:
1256                        die("unexpected EOF when reading from parent process");
1257                case PACKET_READ_NORMAL:
1258                        packet_buf_write_len(&p->request_buffer, p->reader.line,
1259                                             p->reader.pktlen);
1260                        break;
1261                case PACKET_READ_DELIM:
1262                        packet_buf_delim(&p->request_buffer);
1263                        break;
1264                case PACKET_READ_FLUSH:
1265                        packet_buf_flush(&p->request_buffer);
1266                        p->seen_flush = 1;
1267                        break;
1268                }
1269                p->pos = 0;
1270                avail = p->request_buffer.len;
1271        }
1272
1273        if (max < avail)
1274                avail = max;
1275        memcpy(buffer, p->request_buffer.buf + p->pos, avail);
1276        p->pos += avail;
1277        return avail;
1278}
1279
1280static size_t proxy_out(char *buffer, size_t eltsize,
1281                        size_t nmemb, void *userdata)
1282{
1283        size_t size;
1284        struct proxy_state *p = userdata;
1285
1286        if (eltsize != 1)
1287                BUG("curl read callback called with size = %"PRIuMAX" != 1",
1288                    (uintmax_t)eltsize);
1289        size = nmemb;
1290
1291        write_or_die(p->out, buffer, size);
1292        return size;
1293}
1294
1295/* Issues a request to the HTTP server configured in `p` */
1296static int proxy_request(struct proxy_state *p)
1297{
1298        struct active_request_slot *slot;
1299
1300        slot = get_active_slot();
1301
1302        curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "");
1303        curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1304        curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
1305        curl_easy_setopt(slot->curl, CURLOPT_URL, p->service_url);
1306        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, p->headers);
1307
1308        /* Setup function to read request from client */
1309        curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, proxy_in);
1310        curl_easy_setopt(slot->curl, CURLOPT_READDATA, p);
1311
1312        /* Setup function to write server response to client */
1313        curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, proxy_out);
1314        curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, p);
1315
1316        if (run_slot(slot, NULL) != HTTP_OK)
1317                return -1;
1318
1319        return 0;
1320}
1321
1322static int stateless_connect(const char *service_name)
1323{
1324        struct discovery *discover;
1325        struct proxy_state p;
1326
1327        /*
1328         * Run the info/refs request and see if the server supports protocol
1329         * v2.  If and only if the server supports v2 can we successfully
1330         * establish a stateless connection, otherwise we need to tell the
1331         * client to fallback to using other transport helper functions to
1332         * complete their request.
1333         */
1334        discover = discover_refs(service_name, 0);
1335        if (discover->version != protocol_v2) {
1336                printf("fallback\n");
1337                fflush(stdout);
1338                return -1;
1339        } else {
1340                /* Stateless Connection established */
1341                printf("\n");
1342                fflush(stdout);
1343        }
1344
1345        proxy_state_init(&p, service_name, discover->version);
1346
1347        /*
1348         * Dump the capability listing that we got from the server earlier
1349         * during the info/refs request.
1350         */
1351        write_or_die(p.out, discover->buf, discover->len);
1352
1353        /* Peek the next packet line.  Until we see EOF keep sending POSTs */
1354        while (packet_reader_peek(&p.reader) != PACKET_READ_EOF) {
1355                if (proxy_request(&p)) {
1356                        /* We would have an err here */
1357                        break;
1358                }
1359        }
1360
1361        proxy_state_clear(&p);
1362        return 0;
1363}
1364
1365int cmd_main(int argc, const char **argv)
1366{
1367        struct strbuf buf = STRBUF_INIT;
1368        int nongit;
1369
1370        setup_git_directory_gently(&nongit);
1371        if (argc < 2) {
1372                error("remote-curl: usage: git remote-curl <remote> [<url>]");
1373                return 1;
1374        }
1375
1376        options.verbosity = 1;
1377        options.progress = !!isatty(2);
1378        options.thin = 1;
1379        string_list_init(&options.deepen_not, 1);
1380        string_list_init(&options.push_options, 1);
1381
1382        remote = remote_get(argv[1]);
1383
1384        if (argc > 2) {
1385                end_url_with_slash(&url, argv[2]);
1386        } else {
1387                end_url_with_slash(&url, remote->url[0]);
1388        }
1389
1390        http_init(remote, url.buf, 0);
1391
1392        do {
1393                const char *arg;
1394
1395                if (strbuf_getline_lf(&buf, stdin) == EOF) {
1396                        if (ferror(stdin))
1397                                error("remote-curl: error reading command stream from git");
1398                        return 1;
1399                }
1400                if (buf.len == 0)
1401                        break;
1402                if (starts_with(buf.buf, "fetch ")) {
1403                        if (nongit)
1404                                die("remote-curl: fetch attempted without a local repo");
1405                        parse_fetch(&buf);
1406
1407                } else if (!strcmp(buf.buf, "list") || starts_with(buf.buf, "list ")) {
1408                        int for_push = !!strstr(buf.buf + 4, "for-push");
1409                        output_refs(get_refs(for_push));
1410
1411                } else if (starts_with(buf.buf, "push ")) {
1412                        parse_push(&buf);
1413
1414                } else if (skip_prefix(buf.buf, "option ", &arg)) {
1415                        char *value = strchr(arg, ' ');
1416                        int result;
1417
1418                        if (value)
1419                                *value++ = '\0';
1420                        else
1421                                value = "true";
1422
1423                        result = set_option(arg, value);
1424                        if (!result)
1425                                printf("ok\n");
1426                        else if (result < 0)
1427                                printf("error invalid value\n");
1428                        else
1429                                printf("unsupported\n");
1430                        fflush(stdout);
1431
1432                } else if (!strcmp(buf.buf, "capabilities")) {
1433                        printf("stateless-connect\n");
1434                        printf("fetch\n");
1435                        printf("option\n");
1436                        printf("push\n");
1437                        printf("check-connectivity\n");
1438                        printf("\n");
1439                        fflush(stdout);
1440                } else if (skip_prefix(buf.buf, "stateless-connect ", &arg)) {
1441                        if (!stateless_connect(arg))
1442                                break;
1443                } else {
1444                        error("remote-curl: unknown command '%s' from git", buf.buf);
1445                        return 1;
1446                }
1447                strbuf_reset(&buf);
1448        } while (1);
1449
1450        http_cleanup();
1451
1452        return 0;
1453}