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