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