http.con commit Merge branch 'pw/add-p-select' into next (eae69f5)
   1#include "git-compat-util.h"
   2#include "http.h"
   3#include "config.h"
   4#include "pack.h"
   5#include "sideband.h"
   6#include "run-command.h"
   7#include "url.h"
   8#include "urlmatch.h"
   9#include "credential.h"
  10#include "version.h"
  11#include "pkt-line.h"
  12#include "gettext.h"
  13#include "transport.h"
  14#include "packfile.h"
  15#include "protocol.h"
  16#include "string-list.h"
  17
  18static struct trace_key trace_curl = TRACE_KEY_INIT(CURL);
  19static int trace_curl_data = 1;
  20static struct string_list cookies_to_redact = STRING_LIST_INIT_DUP;
  21#if LIBCURL_VERSION_NUM >= 0x070a08
  22long int git_curl_ipresolve = CURL_IPRESOLVE_WHATEVER;
  23#else
  24long int git_curl_ipresolve;
  25#endif
  26int active_requests;
  27int http_is_verbose;
  28ssize_t http_post_buffer = 16 * LARGE_PACKET_MAX;
  29
  30#if LIBCURL_VERSION_NUM >= 0x070a06
  31#define LIBCURL_CAN_HANDLE_AUTH_ANY
  32#endif
  33
  34static int min_curl_sessions = 1;
  35static int curl_session_count;
  36#ifdef USE_CURL_MULTI
  37static int max_requests = -1;
  38static CURLM *curlm;
  39#endif
  40#ifndef NO_CURL_EASY_DUPHANDLE
  41static CURL *curl_default;
  42#endif
  43
  44#define PREV_BUF_SIZE 4096
  45
  46char curl_errorstr[CURL_ERROR_SIZE];
  47
  48static int curl_ssl_verify = -1;
  49static int curl_ssl_try;
  50static const char *ssl_cert;
  51static const char *ssl_cipherlist;
  52static const char *ssl_version;
  53static struct {
  54        const char *name;
  55        long ssl_version;
  56} sslversions[] = {
  57        { "sslv2", CURL_SSLVERSION_SSLv2 },
  58        { "sslv3", CURL_SSLVERSION_SSLv3 },
  59        { "tlsv1", CURL_SSLVERSION_TLSv1 },
  60#if LIBCURL_VERSION_NUM >= 0x072200
  61        { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
  62        { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
  63        { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
  64#endif
  65#if LIBCURL_VERSION_NUM >= 0x073400
  66        { "tlsv1.3", CURL_SSLVERSION_TLSv1_3 },
  67#endif
  68};
  69#if LIBCURL_VERSION_NUM >= 0x070903
  70static const char *ssl_key;
  71#endif
  72#if LIBCURL_VERSION_NUM >= 0x070908
  73static const char *ssl_capath;
  74#endif
  75#if LIBCURL_VERSION_NUM >= 0x071304
  76static const char *curl_no_proxy;
  77#endif
  78#if LIBCURL_VERSION_NUM >= 0x072c00
  79static const char *ssl_pinnedkey;
  80#endif
  81static const char *ssl_cainfo;
  82static long curl_low_speed_limit = -1;
  83static long curl_low_speed_time = -1;
  84static int curl_ftp_no_epsv;
  85static const char *curl_http_proxy;
  86static const char *http_proxy_authmethod;
  87static struct {
  88        const char *name;
  89        long curlauth_param;
  90} proxy_authmethods[] = {
  91        { "basic", CURLAUTH_BASIC },
  92        { "digest", CURLAUTH_DIGEST },
  93        { "negotiate", CURLAUTH_GSSNEGOTIATE },
  94        { "ntlm", CURLAUTH_NTLM },
  95#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
  96        { "anyauth", CURLAUTH_ANY },
  97#endif
  98        /*
  99         * CURLAUTH_DIGEST_IE has no corresponding command-line option in
 100         * curl(1) and is not included in CURLAUTH_ANY, so we leave it out
 101         * here, too
 102         */
 103};
 104#ifdef CURLGSSAPI_DELEGATION_FLAG
 105static const char *curl_deleg;
 106static struct {
 107        const char *name;
 108        long curl_deleg_param;
 109} curl_deleg_levels[] = {
 110        { "none", CURLGSSAPI_DELEGATION_NONE },
 111        { "policy", CURLGSSAPI_DELEGATION_POLICY_FLAG },
 112        { "always", CURLGSSAPI_DELEGATION_FLAG },
 113};
 114#endif
 115
 116static struct credential proxy_auth = CREDENTIAL_INIT;
 117static const char *curl_proxyuserpwd;
 118static const char *curl_cookie_file;
 119static int curl_save_cookies;
 120struct credential http_auth = CREDENTIAL_INIT;
 121static int http_proactive_auth;
 122static const char *user_agent;
 123static int curl_empty_auth = -1;
 124
 125enum http_follow_config http_follow_config = HTTP_FOLLOW_INITIAL;
 126
 127#if LIBCURL_VERSION_NUM >= 0x071700
 128/* Use CURLOPT_KEYPASSWD as is */
 129#elif LIBCURL_VERSION_NUM >= 0x070903
 130#define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
 131#else
 132#define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
 133#endif
 134
 135static struct credential cert_auth = CREDENTIAL_INIT;
 136static int ssl_cert_password_required;
 137#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
 138static unsigned long http_auth_methods = CURLAUTH_ANY;
 139static int http_auth_methods_restricted;
 140/* Modes for which empty_auth cannot actually help us. */
 141static unsigned long empty_auth_useless =
 142        CURLAUTH_BASIC
 143#ifdef CURLAUTH_DIGEST_IE
 144        | CURLAUTH_DIGEST_IE
 145#endif
 146        | CURLAUTH_DIGEST;
 147#endif
 148
 149static struct curl_slist *pragma_header;
 150static struct curl_slist *no_pragma_header;
 151static struct curl_slist *extra_http_headers;
 152
 153static struct active_request_slot *active_queue_head;
 154
 155static char *cached_accept_language;
 156
 157size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
 158{
 159        size_t size = eltsize * nmemb;
 160        struct buffer *buffer = buffer_;
 161
 162        if (size > buffer->buf.len - buffer->posn)
 163                size = buffer->buf.len - buffer->posn;
 164        memcpy(ptr, buffer->buf.buf + buffer->posn, size);
 165        buffer->posn += size;
 166
 167        return size;
 168}
 169
 170#ifndef NO_CURL_IOCTL
 171curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
 172{
 173        struct buffer *buffer = clientp;
 174
 175        switch (cmd) {
 176        case CURLIOCMD_NOP:
 177                return CURLIOE_OK;
 178
 179        case CURLIOCMD_RESTARTREAD:
 180                buffer->posn = 0;
 181                return CURLIOE_OK;
 182
 183        default:
 184                return CURLIOE_UNKNOWNCMD;
 185        }
 186}
 187#endif
 188
 189size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
 190{
 191        size_t size = eltsize * nmemb;
 192        struct strbuf *buffer = buffer_;
 193
 194        strbuf_add(buffer, ptr, size);
 195        return size;
 196}
 197
 198size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
 199{
 200        return eltsize * nmemb;
 201}
 202
 203static void closedown_active_slot(struct active_request_slot *slot)
 204{
 205        active_requests--;
 206        slot->in_use = 0;
 207}
 208
 209static void finish_active_slot(struct active_request_slot *slot)
 210{
 211        closedown_active_slot(slot);
 212        curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
 213
 214        if (slot->finished != NULL)
 215                (*slot->finished) = 1;
 216
 217        /* Store slot results so they can be read after the slot is reused */
 218        if (slot->results != NULL) {
 219                slot->results->curl_result = slot->curl_result;
 220                slot->results->http_code = slot->http_code;
 221#if LIBCURL_VERSION_NUM >= 0x070a08
 222                curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
 223                                  &slot->results->auth_avail);
 224#else
 225                slot->results->auth_avail = 0;
 226#endif
 227
 228                curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CONNECTCODE,
 229                        &slot->results->http_connectcode);
 230        }
 231
 232        /* Run callback if appropriate */
 233        if (slot->callback_func != NULL)
 234                slot->callback_func(slot->callback_data);
 235}
 236
 237static void xmulti_remove_handle(struct active_request_slot *slot)
 238{
 239#ifdef USE_CURL_MULTI
 240        curl_multi_remove_handle(curlm, slot->curl);
 241#endif
 242}
 243
 244#ifdef USE_CURL_MULTI
 245static void process_curl_messages(void)
 246{
 247        int num_messages;
 248        struct active_request_slot *slot;
 249        CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
 250
 251        while (curl_message != NULL) {
 252                if (curl_message->msg == CURLMSG_DONE) {
 253                        int curl_result = curl_message->data.result;
 254                        slot = active_queue_head;
 255                        while (slot != NULL &&
 256                               slot->curl != curl_message->easy_handle)
 257                                slot = slot->next;
 258                        if (slot != NULL) {
 259                                xmulti_remove_handle(slot);
 260                                slot->curl_result = curl_result;
 261                                finish_active_slot(slot);
 262                        } else {
 263                                fprintf(stderr, "Received DONE message for unknown request!\n");
 264                        }
 265                } else {
 266                        fprintf(stderr, "Unknown CURL message received: %d\n",
 267                                (int)curl_message->msg);
 268                }
 269                curl_message = curl_multi_info_read(curlm, &num_messages);
 270        }
 271}
 272#endif
 273
 274static int http_options(const char *var, const char *value, void *cb)
 275{
 276        if (!strcmp("http.sslverify", var)) {
 277                curl_ssl_verify = git_config_bool(var, value);
 278                return 0;
 279        }
 280        if (!strcmp("http.sslcipherlist", var))
 281                return git_config_string(&ssl_cipherlist, var, value);
 282        if (!strcmp("http.sslversion", var))
 283                return git_config_string(&ssl_version, var, value);
 284        if (!strcmp("http.sslcert", var))
 285                return git_config_pathname(&ssl_cert, var, value);
 286#if LIBCURL_VERSION_NUM >= 0x070903
 287        if (!strcmp("http.sslkey", var))
 288                return git_config_pathname(&ssl_key, var, value);
 289#endif
 290#if LIBCURL_VERSION_NUM >= 0x070908
 291        if (!strcmp("http.sslcapath", var))
 292                return git_config_pathname(&ssl_capath, var, value);
 293#endif
 294        if (!strcmp("http.sslcainfo", var))
 295                return git_config_pathname(&ssl_cainfo, var, value);
 296        if (!strcmp("http.sslcertpasswordprotected", var)) {
 297                ssl_cert_password_required = git_config_bool(var, value);
 298                return 0;
 299        }
 300        if (!strcmp("http.ssltry", var)) {
 301                curl_ssl_try = git_config_bool(var, value);
 302                return 0;
 303        }
 304        if (!strcmp("http.minsessions", var)) {
 305                min_curl_sessions = git_config_int(var, value);
 306#ifndef USE_CURL_MULTI
 307                if (min_curl_sessions > 1)
 308                        min_curl_sessions = 1;
 309#endif
 310                return 0;
 311        }
 312#ifdef USE_CURL_MULTI
 313        if (!strcmp("http.maxrequests", var)) {
 314                max_requests = git_config_int(var, value);
 315                return 0;
 316        }
 317#endif
 318        if (!strcmp("http.lowspeedlimit", var)) {
 319                curl_low_speed_limit = (long)git_config_int(var, value);
 320                return 0;
 321        }
 322        if (!strcmp("http.lowspeedtime", var)) {
 323                curl_low_speed_time = (long)git_config_int(var, value);
 324                return 0;
 325        }
 326
 327        if (!strcmp("http.noepsv", var)) {
 328                curl_ftp_no_epsv = git_config_bool(var, value);
 329                return 0;
 330        }
 331        if (!strcmp("http.proxy", var))
 332                return git_config_string(&curl_http_proxy, var, value);
 333
 334        if (!strcmp("http.proxyauthmethod", var))
 335                return git_config_string(&http_proxy_authmethod, var, value);
 336
 337        if (!strcmp("http.cookiefile", var))
 338                return git_config_pathname(&curl_cookie_file, var, value);
 339        if (!strcmp("http.savecookies", var)) {
 340                curl_save_cookies = git_config_bool(var, value);
 341                return 0;
 342        }
 343
 344        if (!strcmp("http.postbuffer", var)) {
 345                http_post_buffer = git_config_ssize_t(var, value);
 346                if (http_post_buffer < 0)
 347                        warning(_("negative value for http.postbuffer; defaulting to %d"), LARGE_PACKET_MAX);
 348                if (http_post_buffer < LARGE_PACKET_MAX)
 349                        http_post_buffer = LARGE_PACKET_MAX;
 350                return 0;
 351        }
 352
 353        if (!strcmp("http.useragent", var))
 354                return git_config_string(&user_agent, var, value);
 355
 356        if (!strcmp("http.emptyauth", var)) {
 357                if (value && !strcmp("auto", value))
 358                        curl_empty_auth = -1;
 359                else
 360                        curl_empty_auth = git_config_bool(var, value);
 361                return 0;
 362        }
 363
 364        if (!strcmp("http.delegation", var)) {
 365#ifdef CURLGSSAPI_DELEGATION_FLAG
 366                return git_config_string(&curl_deleg, var, value);
 367#else
 368                warning(_("Delegation control is not supported with cURL < 7.22.0"));
 369                return 0;
 370#endif
 371        }
 372
 373        if (!strcmp("http.pinnedpubkey", var)) {
 374#if LIBCURL_VERSION_NUM >= 0x072c00
 375                return git_config_pathname(&ssl_pinnedkey, var, value);
 376#else
 377                warning(_("Public key pinning not supported with cURL < 7.44.0"));
 378                return 0;
 379#endif
 380        }
 381
 382        if (!strcmp("http.extraheader", var)) {
 383                if (!value) {
 384                        return config_error_nonbool(var);
 385                } else if (!*value) {
 386                        curl_slist_free_all(extra_http_headers);
 387                        extra_http_headers = NULL;
 388                } else {
 389                        extra_http_headers =
 390                                curl_slist_append(extra_http_headers, value);
 391                }
 392                return 0;
 393        }
 394
 395        if (!strcmp("http.followredirects", var)) {
 396                if (value && !strcmp(value, "initial"))
 397                        http_follow_config = HTTP_FOLLOW_INITIAL;
 398                else if (git_config_bool(var, value))
 399                        http_follow_config = HTTP_FOLLOW_ALWAYS;
 400                else
 401                        http_follow_config = HTTP_FOLLOW_NONE;
 402                return 0;
 403        }
 404
 405        /* Fall back on the default ones */
 406        return git_default_config(var, value, cb);
 407}
 408
 409static int curl_empty_auth_enabled(void)
 410{
 411        if (curl_empty_auth >= 0)
 412                return curl_empty_auth;
 413
 414#ifndef LIBCURL_CAN_HANDLE_AUTH_ANY
 415        /*
 416         * Our libcurl is too old to do AUTH_ANY in the first place;
 417         * just default to turning the feature off.
 418         */
 419#else
 420        /*
 421         * In the automatic case, kick in the empty-auth
 422         * hack as long as we would potentially try some
 423         * method more exotic than "Basic" or "Digest".
 424         *
 425         * But only do this when this is our second or
 426         * subsequent request, as by then we know what
 427         * methods are available.
 428         */
 429        if (http_auth_methods_restricted &&
 430            (http_auth_methods & ~empty_auth_useless))
 431                return 1;
 432#endif
 433        return 0;
 434}
 435
 436static void init_curl_http_auth(CURL *result)
 437{
 438        if (!http_auth.username || !*http_auth.username) {
 439                if (curl_empty_auth_enabled())
 440                        curl_easy_setopt(result, CURLOPT_USERPWD, ":");
 441                return;
 442        }
 443
 444        credential_fill(&http_auth);
 445
 446#if LIBCURL_VERSION_NUM >= 0x071301
 447        curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
 448        curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
 449#else
 450        {
 451                static struct strbuf up = STRBUF_INIT;
 452                /*
 453                 * Note that we assume we only ever have a single set of
 454                 * credentials in a given program run, so we do not have
 455                 * to worry about updating this buffer, only setting its
 456                 * initial value.
 457                 */
 458                if (!up.len)
 459                        strbuf_addf(&up, "%s:%s",
 460                                http_auth.username, http_auth.password);
 461                curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
 462        }
 463#endif
 464}
 465
 466/* *var must be free-able */
 467static void var_override(const char **var, char *value)
 468{
 469        if (value) {
 470                free((void *)*var);
 471                *var = xstrdup(value);
 472        }
 473}
 474
 475static void set_proxyauth_name_password(CURL *result)
 476{
 477#if LIBCURL_VERSION_NUM >= 0x071301
 478                curl_easy_setopt(result, CURLOPT_PROXYUSERNAME,
 479                        proxy_auth.username);
 480                curl_easy_setopt(result, CURLOPT_PROXYPASSWORD,
 481                        proxy_auth.password);
 482#else
 483                struct strbuf s = STRBUF_INIT;
 484
 485                strbuf_addstr_urlencode(&s, proxy_auth.username, 1);
 486                strbuf_addch(&s, ':');
 487                strbuf_addstr_urlencode(&s, proxy_auth.password, 1);
 488                curl_proxyuserpwd = strbuf_detach(&s, NULL);
 489                curl_easy_setopt(result, CURLOPT_PROXYUSERPWD, curl_proxyuserpwd);
 490#endif
 491}
 492
 493static void init_curl_proxy_auth(CURL *result)
 494{
 495        if (proxy_auth.username) {
 496                if (!proxy_auth.password)
 497                        credential_fill(&proxy_auth);
 498                set_proxyauth_name_password(result);
 499        }
 500
 501        var_override(&http_proxy_authmethod, getenv("GIT_HTTP_PROXY_AUTHMETHOD"));
 502
 503#if LIBCURL_VERSION_NUM >= 0x070a07 /* CURLOPT_PROXYAUTH and CURLAUTH_ANY */
 504        if (http_proxy_authmethod) {
 505                int i;
 506                for (i = 0; i < ARRAY_SIZE(proxy_authmethods); i++) {
 507                        if (!strcmp(http_proxy_authmethod, proxy_authmethods[i].name)) {
 508                                curl_easy_setopt(result, CURLOPT_PROXYAUTH,
 509                                                proxy_authmethods[i].curlauth_param);
 510                                break;
 511                        }
 512                }
 513                if (i == ARRAY_SIZE(proxy_authmethods)) {
 514                        warning("unsupported proxy authentication method %s: using anyauth",
 515                                        http_proxy_authmethod);
 516                        curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
 517                }
 518        }
 519        else
 520                curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
 521#endif
 522}
 523
 524static int has_cert_password(void)
 525{
 526        if (ssl_cert == NULL || ssl_cert_password_required != 1)
 527                return 0;
 528        if (!cert_auth.password) {
 529                cert_auth.protocol = xstrdup("cert");
 530                cert_auth.username = xstrdup("");
 531                cert_auth.path = xstrdup(ssl_cert);
 532                credential_fill(&cert_auth);
 533        }
 534        return 1;
 535}
 536
 537#if LIBCURL_VERSION_NUM >= 0x071900
 538static void set_curl_keepalive(CURL *c)
 539{
 540        curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
 541}
 542
 543#elif LIBCURL_VERSION_NUM >= 0x071000
 544static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
 545{
 546        int ka = 1;
 547        int rc;
 548        socklen_t len = (socklen_t)sizeof(ka);
 549
 550        if (type != CURLSOCKTYPE_IPCXN)
 551                return 0;
 552
 553        rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
 554        if (rc < 0)
 555                warning_errno("unable to set SO_KEEPALIVE on socket");
 556
 557        return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
 558}
 559
 560static void set_curl_keepalive(CURL *c)
 561{
 562        curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
 563}
 564
 565#else
 566static void set_curl_keepalive(CURL *c)
 567{
 568        /* not supported on older curl versions */
 569}
 570#endif
 571
 572static void redact_sensitive_header(struct strbuf *header)
 573{
 574        const char *sensitive_header;
 575
 576        if (skip_prefix(header->buf, "Authorization:", &sensitive_header) ||
 577            skip_prefix(header->buf, "Proxy-Authorization:", &sensitive_header)) {
 578                /* The first token is the type, which is OK to log */
 579                while (isspace(*sensitive_header))
 580                        sensitive_header++;
 581                while (*sensitive_header && !isspace(*sensitive_header))
 582                        sensitive_header++;
 583                /* Everything else is opaque and possibly sensitive */
 584                strbuf_setlen(header,  sensitive_header - header->buf);
 585                strbuf_addstr(header, " <redacted>");
 586        } else if (cookies_to_redact.nr &&
 587                   skip_prefix(header->buf, "Cookie:", &sensitive_header)) {
 588                struct strbuf redacted_header = STRBUF_INIT;
 589                char *cookie;
 590
 591                while (isspace(*sensitive_header))
 592                        sensitive_header++;
 593
 594                /*
 595                 * The contents of header starting from sensitive_header will
 596                 * subsequently be overridden, so it is fine to mutate this
 597                 * string (hence the assignment to "char *").
 598                 */
 599                cookie = (char *) sensitive_header;
 600
 601                while (cookie) {
 602                        char *equals;
 603                        char *semicolon = strstr(cookie, "; ");
 604                        if (semicolon)
 605                                *semicolon = 0;
 606                        equals = strchrnul(cookie, '=');
 607                        if (!equals) {
 608                                /* invalid cookie, just append and continue */
 609                                strbuf_addstr(&redacted_header, cookie);
 610                                continue;
 611                        }
 612                        *equals = 0; /* temporarily set to NUL for lookup */
 613                        if (string_list_lookup(&cookies_to_redact, cookie)) {
 614                                strbuf_addstr(&redacted_header, cookie);
 615                                strbuf_addstr(&redacted_header, "=<redacted>");
 616                        } else {
 617                                *equals = '=';
 618                                strbuf_addstr(&redacted_header, cookie);
 619                        }
 620                        if (semicolon) {
 621                                /*
 622                                 * There are more cookies. (Or, for some
 623                                 * reason, the input string ends in "; ".)
 624                                 */
 625                                strbuf_addstr(&redacted_header, "; ");
 626                                cookie = semicolon + strlen("; ");
 627                        } else {
 628                                cookie = NULL;
 629                        }
 630                }
 631
 632                strbuf_setlen(header, sensitive_header - header->buf);
 633                strbuf_addbuf(header, &redacted_header);
 634        }
 635}
 636
 637static void curl_dump_header(const char *text, unsigned char *ptr, size_t size, int hide_sensitive_header)
 638{
 639        struct strbuf out = STRBUF_INIT;
 640        struct strbuf **headers, **header;
 641
 642        strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
 643                text, (long)size, (long)size);
 644        trace_strbuf(&trace_curl, &out);
 645        strbuf_reset(&out);
 646        strbuf_add(&out, ptr, size);
 647        headers = strbuf_split_max(&out, '\n', 0);
 648
 649        for (header = headers; *header; header++) {
 650                if (hide_sensitive_header)
 651                        redact_sensitive_header(*header);
 652                strbuf_insert((*header), 0, text, strlen(text));
 653                strbuf_insert((*header), strlen(text), ": ", 2);
 654                strbuf_rtrim((*header));
 655                strbuf_addch((*header), '\n');
 656                trace_strbuf(&trace_curl, (*header));
 657        }
 658        strbuf_list_free(headers);
 659        strbuf_release(&out);
 660}
 661
 662static void curl_dump_data(const char *text, unsigned char *ptr, size_t size)
 663{
 664        size_t i;
 665        struct strbuf out = STRBUF_INIT;
 666        unsigned int width = 60;
 667
 668        strbuf_addf(&out, "%s, %10.10ld bytes (0x%8.8lx)\n",
 669                text, (long)size, (long)size);
 670        trace_strbuf(&trace_curl, &out);
 671
 672        for (i = 0; i < size; i += width) {
 673                size_t w;
 674
 675                strbuf_reset(&out);
 676                strbuf_addf(&out, "%s: ", text);
 677                for (w = 0; (w < width) && (i + w < size); w++) {
 678                        unsigned char ch = ptr[i + w];
 679
 680                        strbuf_addch(&out,
 681                                       (ch >= 0x20) && (ch < 0x80)
 682                                       ? ch : '.');
 683                }
 684                strbuf_addch(&out, '\n');
 685                trace_strbuf(&trace_curl, &out);
 686        }
 687        strbuf_release(&out);
 688}
 689
 690static int curl_trace(CURL *handle, curl_infotype type, char *data, size_t size, void *userp)
 691{
 692        const char *text;
 693        enum { NO_FILTER = 0, DO_FILTER = 1 };
 694
 695        switch (type) {
 696        case CURLINFO_TEXT:
 697                trace_printf_key(&trace_curl, "== Info: %s", data);
 698                break;
 699        case CURLINFO_HEADER_OUT:
 700                text = "=> Send header";
 701                curl_dump_header(text, (unsigned char *)data, size, DO_FILTER);
 702                break;
 703        case CURLINFO_DATA_OUT:
 704                if (trace_curl_data) {
 705                        text = "=> Send data";
 706                        curl_dump_data(text, (unsigned char *)data, size);
 707                }
 708                break;
 709        case CURLINFO_SSL_DATA_OUT:
 710                if (trace_curl_data) {
 711                        text = "=> Send SSL data";
 712                        curl_dump_data(text, (unsigned char *)data, size);
 713                }
 714                break;
 715        case CURLINFO_HEADER_IN:
 716                text = "<= Recv header";
 717                curl_dump_header(text, (unsigned char *)data, size, NO_FILTER);
 718                break;
 719        case CURLINFO_DATA_IN:
 720                if (trace_curl_data) {
 721                        text = "<= Recv data";
 722                        curl_dump_data(text, (unsigned char *)data, size);
 723                }
 724                break;
 725        case CURLINFO_SSL_DATA_IN:
 726                if (trace_curl_data) {
 727                        text = "<= Recv SSL data";
 728                        curl_dump_data(text, (unsigned char *)data, size);
 729                }
 730                break;
 731
 732        default:                /* we ignore unknown types by default */
 733                return 0;
 734        }
 735        return 0;
 736}
 737
 738void setup_curl_trace(CURL *handle)
 739{
 740        if (!trace_want(&trace_curl))
 741                return;
 742        curl_easy_setopt(handle, CURLOPT_VERBOSE, 1L);
 743        curl_easy_setopt(handle, CURLOPT_DEBUGFUNCTION, curl_trace);
 744        curl_easy_setopt(handle, CURLOPT_DEBUGDATA, NULL);
 745}
 746
 747#ifdef CURLPROTO_HTTP
 748static long get_curl_allowed_protocols(int from_user)
 749{
 750        long allowed_protocols = 0;
 751
 752        if (is_transport_allowed("http", from_user))
 753                allowed_protocols |= CURLPROTO_HTTP;
 754        if (is_transport_allowed("https", from_user))
 755                allowed_protocols |= CURLPROTO_HTTPS;
 756        if (is_transport_allowed("ftp", from_user))
 757                allowed_protocols |= CURLPROTO_FTP;
 758        if (is_transport_allowed("ftps", from_user))
 759                allowed_protocols |= CURLPROTO_FTPS;
 760
 761        return allowed_protocols;
 762}
 763#endif
 764
 765static CURL *get_curl_handle(void)
 766{
 767        CURL *result = curl_easy_init();
 768
 769        if (!result)
 770                die("curl_easy_init failed");
 771
 772        if (!curl_ssl_verify) {
 773                curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
 774                curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
 775        } else {
 776                /* Verify authenticity of the peer's certificate */
 777                curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
 778                /* The name in the cert must match whom we tried to connect */
 779                curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
 780        }
 781
 782#if LIBCURL_VERSION_NUM >= 0x070907
 783        curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
 784#endif
 785#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
 786        curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
 787#endif
 788
 789#ifdef CURLGSSAPI_DELEGATION_FLAG
 790        if (curl_deleg) {
 791                int i;
 792                for (i = 0; i < ARRAY_SIZE(curl_deleg_levels); i++) {
 793                        if (!strcmp(curl_deleg, curl_deleg_levels[i].name)) {
 794                                curl_easy_setopt(result, CURLOPT_GSSAPI_DELEGATION,
 795                                                curl_deleg_levels[i].curl_deleg_param);
 796                                break;
 797                        }
 798                }
 799                if (i == ARRAY_SIZE(curl_deleg_levels))
 800                        warning("Unknown delegation method '%s': using default",
 801                                curl_deleg);
 802        }
 803#endif
 804
 805        if (http_proactive_auth)
 806                init_curl_http_auth(result);
 807
 808        if (getenv("GIT_SSL_VERSION"))
 809                ssl_version = getenv("GIT_SSL_VERSION");
 810        if (ssl_version && *ssl_version) {
 811                int i;
 812                for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
 813                        if (!strcmp(ssl_version, sslversions[i].name)) {
 814                                curl_easy_setopt(result, CURLOPT_SSLVERSION,
 815                                                 sslversions[i].ssl_version);
 816                                break;
 817                        }
 818                }
 819                if (i == ARRAY_SIZE(sslversions))
 820                        warning("unsupported ssl version %s: using default",
 821                                ssl_version);
 822        }
 823
 824        if (getenv("GIT_SSL_CIPHER_LIST"))
 825                ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
 826        if (ssl_cipherlist != NULL && *ssl_cipherlist)
 827                curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
 828                                ssl_cipherlist);
 829
 830        if (ssl_cert != NULL)
 831                curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
 832        if (has_cert_password())
 833                curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
 834#if LIBCURL_VERSION_NUM >= 0x070903
 835        if (ssl_key != NULL)
 836                curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
 837#endif
 838#if LIBCURL_VERSION_NUM >= 0x070908
 839        if (ssl_capath != NULL)
 840                curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
 841#endif
 842#if LIBCURL_VERSION_NUM >= 0x072c00
 843        if (ssl_pinnedkey != NULL)
 844                curl_easy_setopt(result, CURLOPT_PINNEDPUBLICKEY, ssl_pinnedkey);
 845#endif
 846        if (ssl_cainfo != NULL)
 847                curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
 848
 849        if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
 850                curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
 851                                 curl_low_speed_limit);
 852                curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
 853                                 curl_low_speed_time);
 854        }
 855
 856        curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
 857#if LIBCURL_VERSION_NUM >= 0x071301
 858        curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
 859#elif LIBCURL_VERSION_NUM >= 0x071101
 860        curl_easy_setopt(result, CURLOPT_POST301, 1);
 861#endif
 862#ifdef CURLPROTO_HTTP
 863        curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS,
 864                         get_curl_allowed_protocols(0));
 865        curl_easy_setopt(result, CURLOPT_PROTOCOLS,
 866                         get_curl_allowed_protocols(-1));
 867#else
 868        warning("protocol restrictions not applied to curl redirects because\n"
 869                "your curl version is too old (>= 7.19.4)");
 870#endif
 871        if (getenv("GIT_CURL_VERBOSE"))
 872                curl_easy_setopt(result, CURLOPT_VERBOSE, 1L);
 873        setup_curl_trace(result);
 874        if (getenv("GIT_TRACE_CURL_NO_DATA"))
 875                trace_curl_data = 0;
 876        if (getenv("GIT_REDACT_COOKIES")) {
 877                string_list_split(&cookies_to_redact,
 878                                  getenv("GIT_REDACT_COOKIES"), ',', -1);
 879                string_list_sort(&cookies_to_redact);
 880        }
 881
 882        curl_easy_setopt(result, CURLOPT_USERAGENT,
 883                user_agent ? user_agent : git_user_agent());
 884
 885        if (curl_ftp_no_epsv)
 886                curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
 887
 888#ifdef CURLOPT_USE_SSL
 889        if (curl_ssl_try)
 890                curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
 891#endif
 892
 893        /*
 894         * CURL also examines these variables as a fallback; but we need to query
 895         * them here in order to decide whether to prompt for missing password (cf.
 896         * init_curl_proxy_auth()).
 897         *
 898         * Unlike many other common environment variables, these are historically
 899         * lowercase only. It appears that CURL did not know this and implemented
 900         * only uppercase variants, which was later corrected to take both - with
 901         * the exception of http_proxy, which is lowercase only also in CURL. As
 902         * the lowercase versions are the historical quasi-standard, they take
 903         * precedence here, as in CURL.
 904         */
 905        if (!curl_http_proxy) {
 906                if (http_auth.protocol && !strcmp(http_auth.protocol, "https")) {
 907                        var_override(&curl_http_proxy, getenv("HTTPS_PROXY"));
 908                        var_override(&curl_http_proxy, getenv("https_proxy"));
 909                } else {
 910                        var_override(&curl_http_proxy, getenv("http_proxy"));
 911                }
 912                if (!curl_http_proxy) {
 913                        var_override(&curl_http_proxy, getenv("ALL_PROXY"));
 914                        var_override(&curl_http_proxy, getenv("all_proxy"));
 915                }
 916        }
 917
 918        if (curl_http_proxy && curl_http_proxy[0] == '\0') {
 919                /*
 920                 * Handle case with the empty http.proxy value here to keep
 921                 * common code clean.
 922                 * NB: empty option disables proxying at all.
 923                 */
 924                curl_easy_setopt(result, CURLOPT_PROXY, "");
 925        } else if (curl_http_proxy) {
 926#if LIBCURL_VERSION_NUM >= 0x071800
 927                if (starts_with(curl_http_proxy, "socks5h"))
 928                        curl_easy_setopt(result,
 929                                CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME);
 930                else if (starts_with(curl_http_proxy, "socks5"))
 931                        curl_easy_setopt(result,
 932                                CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
 933                else if (starts_with(curl_http_proxy, "socks4a"))
 934                        curl_easy_setopt(result,
 935                                CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
 936                else if (starts_with(curl_http_proxy, "socks"))
 937                        curl_easy_setopt(result,
 938                                CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
 939#endif
 940#if LIBCURL_VERSION_NUM >= 0x073400
 941                else if (starts_with(curl_http_proxy, "https"))
 942                        curl_easy_setopt(result,
 943                                CURLOPT_PROXYTYPE, CURLPROXY_HTTPS);
 944#endif
 945                if (strstr(curl_http_proxy, "://"))
 946                        credential_from_url(&proxy_auth, curl_http_proxy);
 947                else {
 948                        struct strbuf url = STRBUF_INIT;
 949                        strbuf_addf(&url, "http://%s", curl_http_proxy);
 950                        credential_from_url(&proxy_auth, url.buf);
 951                        strbuf_release(&url);
 952                }
 953
 954                if (!proxy_auth.host)
 955                        die("Invalid proxy URL '%s'", curl_http_proxy);
 956
 957                curl_easy_setopt(result, CURLOPT_PROXY, proxy_auth.host);
 958#if LIBCURL_VERSION_NUM >= 0x071304
 959                var_override(&curl_no_proxy, getenv("NO_PROXY"));
 960                var_override(&curl_no_proxy, getenv("no_proxy"));
 961                curl_easy_setopt(result, CURLOPT_NOPROXY, curl_no_proxy);
 962#endif
 963        }
 964        init_curl_proxy_auth(result);
 965
 966        set_curl_keepalive(result);
 967
 968        return result;
 969}
 970
 971static void set_from_env(const char **var, const char *envname)
 972{
 973        const char *val = getenv(envname);
 974        if (val)
 975                *var = val;
 976}
 977
 978void http_init(struct remote *remote, const char *url, int proactive_auth)
 979{
 980        char *low_speed_limit;
 981        char *low_speed_time;
 982        char *normalized_url;
 983        struct urlmatch_config config = { STRING_LIST_INIT_DUP };
 984
 985        config.section = "http";
 986        config.key = NULL;
 987        config.collect_fn = http_options;
 988        config.cascade_fn = git_default_config;
 989        config.cb = NULL;
 990
 991        http_is_verbose = 0;
 992        normalized_url = url_normalize(url, &config.url);
 993
 994        git_config(urlmatch_config_entry, &config);
 995        free(normalized_url);
 996
 997        if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
 998                die("curl_global_init failed");
 999
1000        http_proactive_auth = proactive_auth;
1001
1002        if (remote && remote->http_proxy)
1003                curl_http_proxy = xstrdup(remote->http_proxy);
1004
1005        if (remote)
1006                var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
1007
1008        pragma_header = curl_slist_append(http_copy_default_headers(),
1009                "Pragma: no-cache");
1010        no_pragma_header = curl_slist_append(http_copy_default_headers(),
1011                "Pragma:");
1012
1013#ifdef USE_CURL_MULTI
1014        {
1015                char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
1016                if (http_max_requests != NULL)
1017                        max_requests = atoi(http_max_requests);
1018        }
1019
1020        curlm = curl_multi_init();
1021        if (!curlm)
1022                die("curl_multi_init failed");
1023#endif
1024
1025        if (getenv("GIT_SSL_NO_VERIFY"))
1026                curl_ssl_verify = 0;
1027
1028        set_from_env(&ssl_cert, "GIT_SSL_CERT");
1029#if LIBCURL_VERSION_NUM >= 0x070903
1030        set_from_env(&ssl_key, "GIT_SSL_KEY");
1031#endif
1032#if LIBCURL_VERSION_NUM >= 0x070908
1033        set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
1034#endif
1035        set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
1036
1037        set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
1038
1039        low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
1040        if (low_speed_limit != NULL)
1041                curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
1042        low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
1043        if (low_speed_time != NULL)
1044                curl_low_speed_time = strtol(low_speed_time, NULL, 10);
1045
1046        if (curl_ssl_verify == -1)
1047                curl_ssl_verify = 1;
1048
1049        curl_session_count = 0;
1050#ifdef USE_CURL_MULTI
1051        if (max_requests < 1)
1052                max_requests = DEFAULT_MAX_REQUESTS;
1053#endif
1054
1055        if (getenv("GIT_CURL_FTP_NO_EPSV"))
1056                curl_ftp_no_epsv = 1;
1057
1058        if (url) {
1059                credential_from_url(&http_auth, url);
1060                if (!ssl_cert_password_required &&
1061                    getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
1062                    starts_with(url, "https://"))
1063                        ssl_cert_password_required = 1;
1064        }
1065
1066#ifndef NO_CURL_EASY_DUPHANDLE
1067        curl_default = get_curl_handle();
1068#endif
1069}
1070
1071void http_cleanup(void)
1072{
1073        struct active_request_slot *slot = active_queue_head;
1074
1075        while (slot != NULL) {
1076                struct active_request_slot *next = slot->next;
1077                if (slot->curl != NULL) {
1078                        xmulti_remove_handle(slot);
1079                        curl_easy_cleanup(slot->curl);
1080                }
1081                free(slot);
1082                slot = next;
1083        }
1084        active_queue_head = NULL;
1085
1086#ifndef NO_CURL_EASY_DUPHANDLE
1087        curl_easy_cleanup(curl_default);
1088#endif
1089
1090#ifdef USE_CURL_MULTI
1091        curl_multi_cleanup(curlm);
1092#endif
1093        curl_global_cleanup();
1094
1095        curl_slist_free_all(extra_http_headers);
1096        extra_http_headers = NULL;
1097
1098        curl_slist_free_all(pragma_header);
1099        pragma_header = NULL;
1100
1101        curl_slist_free_all(no_pragma_header);
1102        no_pragma_header = NULL;
1103
1104        if (curl_http_proxy) {
1105                free((void *)curl_http_proxy);
1106                curl_http_proxy = NULL;
1107        }
1108
1109        if (proxy_auth.password) {
1110                memset(proxy_auth.password, 0, strlen(proxy_auth.password));
1111                FREE_AND_NULL(proxy_auth.password);
1112        }
1113
1114        free((void *)curl_proxyuserpwd);
1115        curl_proxyuserpwd = NULL;
1116
1117        free((void *)http_proxy_authmethod);
1118        http_proxy_authmethod = NULL;
1119
1120        if (cert_auth.password != NULL) {
1121                memset(cert_auth.password, 0, strlen(cert_auth.password));
1122                FREE_AND_NULL(cert_auth.password);
1123        }
1124        ssl_cert_password_required = 0;
1125
1126        FREE_AND_NULL(cached_accept_language);
1127}
1128
1129struct active_request_slot *get_active_slot(void)
1130{
1131        struct active_request_slot *slot = active_queue_head;
1132        struct active_request_slot *newslot;
1133
1134#ifdef USE_CURL_MULTI
1135        int num_transfers;
1136
1137        /* Wait for a slot to open up if the queue is full */
1138        while (active_requests >= max_requests) {
1139                curl_multi_perform(curlm, &num_transfers);
1140                if (num_transfers < active_requests)
1141                        process_curl_messages();
1142        }
1143#endif
1144
1145        while (slot != NULL && slot->in_use)
1146                slot = slot->next;
1147
1148        if (slot == NULL) {
1149                newslot = xmalloc(sizeof(*newslot));
1150                newslot->curl = NULL;
1151                newslot->in_use = 0;
1152                newslot->next = NULL;
1153
1154                slot = active_queue_head;
1155                if (slot == NULL) {
1156                        active_queue_head = newslot;
1157                } else {
1158                        while (slot->next != NULL)
1159                                slot = slot->next;
1160                        slot->next = newslot;
1161                }
1162                slot = newslot;
1163        }
1164
1165        if (slot->curl == NULL) {
1166#ifdef NO_CURL_EASY_DUPHANDLE
1167                slot->curl = get_curl_handle();
1168#else
1169                slot->curl = curl_easy_duphandle(curl_default);
1170#endif
1171                curl_session_count++;
1172        }
1173
1174        active_requests++;
1175        slot->in_use = 1;
1176        slot->results = NULL;
1177        slot->finished = NULL;
1178        slot->callback_data = NULL;
1179        slot->callback_func = NULL;
1180        curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
1181        if (curl_save_cookies)
1182                curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
1183        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
1184        curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
1185        curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
1186        curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
1187        curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
1188        curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
1189        curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
1190        curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1191        curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
1192        curl_easy_setopt(slot->curl, CURLOPT_RANGE, NULL);
1193
1194        /*
1195         * Default following to off unless "ALWAYS" is configured; this gives
1196         * callers a sane starting point, and they can tweak for individual
1197         * HTTP_FOLLOW_* cases themselves.
1198         */
1199        if (http_follow_config == HTTP_FOLLOW_ALWAYS)
1200                curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1201        else
1202                curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 0);
1203
1204#if LIBCURL_VERSION_NUM >= 0x070a08
1205        curl_easy_setopt(slot->curl, CURLOPT_IPRESOLVE, git_curl_ipresolve);
1206#endif
1207#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1208        curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
1209#endif
1210        if (http_auth.password || curl_empty_auth_enabled())
1211                init_curl_http_auth(slot->curl);
1212
1213        return slot;
1214}
1215
1216int start_active_slot(struct active_request_slot *slot)
1217{
1218#ifdef USE_CURL_MULTI
1219        CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
1220        int num_transfers;
1221
1222        if (curlm_result != CURLM_OK &&
1223            curlm_result != CURLM_CALL_MULTI_PERFORM) {
1224                warning("curl_multi_add_handle failed: %s",
1225                        curl_multi_strerror(curlm_result));
1226                active_requests--;
1227                slot->in_use = 0;
1228                return 0;
1229        }
1230
1231        /*
1232         * We know there must be something to do, since we just added
1233         * something.
1234         */
1235        curl_multi_perform(curlm, &num_transfers);
1236#endif
1237        return 1;
1238}
1239
1240#ifdef USE_CURL_MULTI
1241struct fill_chain {
1242        void *data;
1243        int (*fill)(void *);
1244        struct fill_chain *next;
1245};
1246
1247static struct fill_chain *fill_cfg;
1248
1249void add_fill_function(void *data, int (*fill)(void *))
1250{
1251        struct fill_chain *new_fill = xmalloc(sizeof(*new_fill));
1252        struct fill_chain **linkp = &fill_cfg;
1253        new_fill->data = data;
1254        new_fill->fill = fill;
1255        new_fill->next = NULL;
1256        while (*linkp)
1257                linkp = &(*linkp)->next;
1258        *linkp = new_fill;
1259}
1260
1261void fill_active_slots(void)
1262{
1263        struct active_request_slot *slot = active_queue_head;
1264
1265        while (active_requests < max_requests) {
1266                struct fill_chain *fill;
1267                for (fill = fill_cfg; fill; fill = fill->next)
1268                        if (fill->fill(fill->data))
1269                                break;
1270
1271                if (!fill)
1272                        break;
1273        }
1274
1275        while (slot != NULL) {
1276                if (!slot->in_use && slot->curl != NULL
1277                        && curl_session_count > min_curl_sessions) {
1278                        curl_easy_cleanup(slot->curl);
1279                        slot->curl = NULL;
1280                        curl_session_count--;
1281                }
1282                slot = slot->next;
1283        }
1284}
1285
1286void step_active_slots(void)
1287{
1288        int num_transfers;
1289        CURLMcode curlm_result;
1290
1291        do {
1292                curlm_result = curl_multi_perform(curlm, &num_transfers);
1293        } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
1294        if (num_transfers < active_requests) {
1295                process_curl_messages();
1296                fill_active_slots();
1297        }
1298}
1299#endif
1300
1301void run_active_slot(struct active_request_slot *slot)
1302{
1303#ifdef USE_CURL_MULTI
1304        fd_set readfds;
1305        fd_set writefds;
1306        fd_set excfds;
1307        int max_fd;
1308        struct timeval select_timeout;
1309        int finished = 0;
1310
1311        slot->finished = &finished;
1312        while (!finished) {
1313                step_active_slots();
1314
1315                if (slot->in_use) {
1316#if LIBCURL_VERSION_NUM >= 0x070f04
1317                        long curl_timeout;
1318                        curl_multi_timeout(curlm, &curl_timeout);
1319                        if (curl_timeout == 0) {
1320                                continue;
1321                        } else if (curl_timeout == -1) {
1322                                select_timeout.tv_sec  = 0;
1323                                select_timeout.tv_usec = 50000;
1324                        } else {
1325                                select_timeout.tv_sec  =  curl_timeout / 1000;
1326                                select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
1327                        }
1328#else
1329                        select_timeout.tv_sec  = 0;
1330                        select_timeout.tv_usec = 50000;
1331#endif
1332
1333                        max_fd = -1;
1334                        FD_ZERO(&readfds);
1335                        FD_ZERO(&writefds);
1336                        FD_ZERO(&excfds);
1337                        curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
1338
1339                        /*
1340                         * It can happen that curl_multi_timeout returns a pathologically
1341                         * long timeout when curl_multi_fdset returns no file descriptors
1342                         * to read.  See commit message for more details.
1343                         */
1344                        if (max_fd < 0 &&
1345                            (select_timeout.tv_sec > 0 ||
1346                             select_timeout.tv_usec > 50000)) {
1347                                select_timeout.tv_sec  = 0;
1348                                select_timeout.tv_usec = 50000;
1349                        }
1350
1351                        select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
1352                }
1353        }
1354#else
1355        while (slot->in_use) {
1356                slot->curl_result = curl_easy_perform(slot->curl);
1357                finish_active_slot(slot);
1358        }
1359#endif
1360}
1361
1362static void release_active_slot(struct active_request_slot *slot)
1363{
1364        closedown_active_slot(slot);
1365        if (slot->curl) {
1366                xmulti_remove_handle(slot);
1367                if (curl_session_count > min_curl_sessions) {
1368                        curl_easy_cleanup(slot->curl);
1369                        slot->curl = NULL;
1370                        curl_session_count--;
1371                }
1372        }
1373#ifdef USE_CURL_MULTI
1374        fill_active_slots();
1375#endif
1376}
1377
1378void finish_all_active_slots(void)
1379{
1380        struct active_request_slot *slot = active_queue_head;
1381
1382        while (slot != NULL)
1383                if (slot->in_use) {
1384                        run_active_slot(slot);
1385                        slot = active_queue_head;
1386                } else {
1387                        slot = slot->next;
1388                }
1389}
1390
1391/* Helpers for modifying and creating URLs */
1392static inline int needs_quote(int ch)
1393{
1394        if (((ch >= 'A') && (ch <= 'Z'))
1395                        || ((ch >= 'a') && (ch <= 'z'))
1396                        || ((ch >= '0') && (ch <= '9'))
1397                        || (ch == '/')
1398                        || (ch == '-')
1399                        || (ch == '.'))
1400                return 0;
1401        return 1;
1402}
1403
1404static char *quote_ref_url(const char *base, const char *ref)
1405{
1406        struct strbuf buf = STRBUF_INIT;
1407        const char *cp;
1408        int ch;
1409
1410        end_url_with_slash(&buf, base);
1411
1412        for (cp = ref; (ch = *cp) != 0; cp++)
1413                if (needs_quote(ch))
1414                        strbuf_addf(&buf, "%%%02x", ch);
1415                else
1416                        strbuf_addch(&buf, *cp);
1417
1418        return strbuf_detach(&buf, NULL);
1419}
1420
1421void append_remote_object_url(struct strbuf *buf, const char *url,
1422                              const char *hex,
1423                              int only_two_digit_prefix)
1424{
1425        end_url_with_slash(buf, url);
1426
1427        strbuf_addf(buf, "objects/%.*s/", 2, hex);
1428        if (!only_two_digit_prefix)
1429                strbuf_addstr(buf, hex + 2);
1430}
1431
1432char *get_remote_object_url(const char *url, const char *hex,
1433                            int only_two_digit_prefix)
1434{
1435        struct strbuf buf = STRBUF_INIT;
1436        append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
1437        return strbuf_detach(&buf, NULL);
1438}
1439
1440static int handle_curl_result(struct slot_results *results)
1441{
1442        /*
1443         * If we see a failing http code with CURLE_OK, we have turned off
1444         * FAILONERROR (to keep the server's custom error response), and should
1445         * translate the code into failure here.
1446         *
1447         * Likewise, if we see a redirect (30x code), that means we turned off
1448         * redirect-following, and we should treat the result as an error.
1449         */
1450        if (results->curl_result == CURLE_OK &&
1451            results->http_code >= 300) {
1452                results->curl_result = CURLE_HTTP_RETURNED_ERROR;
1453                /*
1454                 * Normally curl will already have put the "reason phrase"
1455                 * from the server into curl_errorstr; unfortunately without
1456                 * FAILONERROR it is lost, so we can give only the numeric
1457                 * status code.
1458                 */
1459                xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1460                          "The requested URL returned error: %ld",
1461                          results->http_code);
1462        }
1463
1464        if (results->curl_result == CURLE_OK) {
1465                credential_approve(&http_auth);
1466                if (proxy_auth.password)
1467                        credential_approve(&proxy_auth);
1468                return HTTP_OK;
1469        } else if (missing_target(results))
1470                return HTTP_MISSING_TARGET;
1471        else if (results->http_code == 401) {
1472                if (http_auth.username && http_auth.password) {
1473                        credential_reject(&http_auth);
1474                        return HTTP_NOAUTH;
1475                } else {
1476#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
1477                        http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
1478                        if (results->auth_avail) {
1479                                http_auth_methods &= results->auth_avail;
1480                                http_auth_methods_restricted = 1;
1481                        }
1482#endif
1483                        return HTTP_REAUTH;
1484                }
1485        } else {
1486                if (results->http_connectcode == 407)
1487                        credential_reject(&proxy_auth);
1488#if LIBCURL_VERSION_NUM >= 0x070c00
1489                if (!curl_errorstr[0])
1490                        strlcpy(curl_errorstr,
1491                                curl_easy_strerror(results->curl_result),
1492                                sizeof(curl_errorstr));
1493#endif
1494                return HTTP_ERROR;
1495        }
1496}
1497
1498int run_one_slot(struct active_request_slot *slot,
1499                 struct slot_results *results)
1500{
1501        slot->results = results;
1502        if (!start_active_slot(slot)) {
1503                xsnprintf(curl_errorstr, sizeof(curl_errorstr),
1504                          "failed to start HTTP request");
1505                return HTTP_START_FAILED;
1506        }
1507
1508        run_active_slot(slot);
1509        return handle_curl_result(results);
1510}
1511
1512struct curl_slist *http_copy_default_headers(void)
1513{
1514        struct curl_slist *headers = NULL, *h;
1515
1516        for (h = extra_http_headers; h; h = h->next)
1517                headers = curl_slist_append(headers, h->data);
1518
1519        return headers;
1520}
1521
1522static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
1523{
1524        char *ptr;
1525        CURLcode ret;
1526
1527        strbuf_reset(buf);
1528        ret = curl_easy_getinfo(curl, info, &ptr);
1529        if (!ret && ptr)
1530                strbuf_addstr(buf, ptr);
1531        return ret;
1532}
1533
1534/*
1535 * Check for and extract a content-type parameter. "raw"
1536 * should be positioned at the start of the potential
1537 * parameter, with any whitespace already removed.
1538 *
1539 * "name" is the name of the parameter. The value is appended
1540 * to "out".
1541 */
1542static int extract_param(const char *raw, const char *name,
1543                         struct strbuf *out)
1544{
1545        size_t len = strlen(name);
1546
1547        if (strncasecmp(raw, name, len))
1548                return -1;
1549        raw += len;
1550
1551        if (*raw != '=')
1552                return -1;
1553        raw++;
1554
1555        while (*raw && !isspace(*raw) && *raw != ';')
1556                strbuf_addch(out, *raw++);
1557        return 0;
1558}
1559
1560/*
1561 * Extract a normalized version of the content type, with any
1562 * spaces suppressed, all letters lowercased, and no trailing ";"
1563 * or parameters.
1564 *
1565 * Note that we will silently remove even invalid whitespace. For
1566 * example, "text / plain" is specifically forbidden by RFC 2616,
1567 * but "text/plain" is the only reasonable output, and this keeps
1568 * our code simple.
1569 *
1570 * If the "charset" argument is not NULL, store the value of any
1571 * charset parameter there.
1572 *
1573 * Example:
1574 *   "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1575 *   "text / plain" -> "text/plain"
1576 */
1577static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1578                                 struct strbuf *charset)
1579{
1580        const char *p;
1581
1582        strbuf_reset(type);
1583        strbuf_grow(type, raw->len);
1584        for (p = raw->buf; *p; p++) {
1585                if (isspace(*p))
1586                        continue;
1587                if (*p == ';') {
1588                        p++;
1589                        break;
1590                }
1591                strbuf_addch(type, tolower(*p));
1592        }
1593
1594        if (!charset)
1595                return;
1596
1597        strbuf_reset(charset);
1598        while (*p) {
1599                while (isspace(*p) || *p == ';')
1600                        p++;
1601                if (!extract_param(p, "charset", charset))
1602                        return;
1603                while (*p && !isspace(*p))
1604                        p++;
1605        }
1606
1607        if (!charset->len && starts_with(type->buf, "text/"))
1608                strbuf_addstr(charset, "ISO-8859-1");
1609}
1610
1611static void write_accept_language(struct strbuf *buf)
1612{
1613        /*
1614         * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1615         * that, q-value will be smaller than 0.001, the minimum q-value the
1616         * HTTP specification allows. See
1617         * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1618         */
1619        const int MAX_DECIMAL_PLACES = 3;
1620        const int MAX_LANGUAGE_TAGS = 1000;
1621        const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1622        char **language_tags = NULL;
1623        int num_langs = 0;
1624        const char *s = get_preferred_languages();
1625        int i;
1626        struct strbuf tag = STRBUF_INIT;
1627
1628        /* Don't add Accept-Language header if no language is preferred. */
1629        if (!s)
1630                return;
1631
1632        /*
1633         * Split the colon-separated string of preferred languages into
1634         * language_tags array.
1635         */
1636        do {
1637                /* collect language tag */
1638                for (; *s && (isalnum(*s) || *s == '_'); s++)
1639                        strbuf_addch(&tag, *s == '_' ? '-' : *s);
1640
1641                /* skip .codeset, @modifier and any other unnecessary parts */
1642                while (*s && *s != ':')
1643                        s++;
1644
1645                if (tag.len) {
1646                        num_langs++;
1647                        REALLOC_ARRAY(language_tags, num_langs);
1648                        language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1649                        if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1650                                break;
1651                }
1652        } while (*s++);
1653
1654        /* write Accept-Language header into buf */
1655        if (num_langs) {
1656                int last_buf_len = 0;
1657                int max_q;
1658                int decimal_places;
1659                char q_format[32];
1660
1661                /* add '*' */
1662                REALLOC_ARRAY(language_tags, num_langs + 1);
1663                language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1664
1665                /* compute decimal_places */
1666                for (max_q = 1, decimal_places = 0;
1667                     max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1668                     decimal_places++, max_q *= 10)
1669                        ;
1670
1671                xsnprintf(q_format, sizeof(q_format), ";q=0.%%0%dd", decimal_places);
1672
1673                strbuf_addstr(buf, "Accept-Language: ");
1674
1675                for (i = 0; i < num_langs; i++) {
1676                        if (i > 0)
1677                                strbuf_addstr(buf, ", ");
1678
1679                        strbuf_addstr(buf, language_tags[i]);
1680
1681                        if (i > 0)
1682                                strbuf_addf(buf, q_format, max_q - i);
1683
1684                        if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1685                                strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1686                                break;
1687                        }
1688
1689                        last_buf_len = buf->len;
1690                }
1691        }
1692
1693        /* free language tags -- last one is a static '*' */
1694        for (i = 0; i < num_langs - 1; i++)
1695                free(language_tags[i]);
1696        free(language_tags);
1697}
1698
1699/*
1700 * Get an Accept-Language header which indicates user's preferred languages.
1701 *
1702 * Examples:
1703 *   LANGUAGE= -> ""
1704 *   LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1705 *   LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1706 *   LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1707 *   LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1708 *   LANGUAGE= LANG=C -> ""
1709 */
1710static const char *get_accept_language(void)
1711{
1712        if (!cached_accept_language) {
1713                struct strbuf buf = STRBUF_INIT;
1714                write_accept_language(&buf);
1715                if (buf.len > 0)
1716                        cached_accept_language = strbuf_detach(&buf, NULL);
1717        }
1718
1719        return cached_accept_language;
1720}
1721
1722static void http_opt_request_remainder(CURL *curl, off_t pos)
1723{
1724        char buf[128];
1725        xsnprintf(buf, sizeof(buf), "%"PRIuMAX"-", (uintmax_t)pos);
1726        curl_easy_setopt(curl, CURLOPT_RANGE, buf);
1727}
1728
1729/* http_request() targets */
1730#define HTTP_REQUEST_STRBUF     0
1731#define HTTP_REQUEST_FILE       1
1732
1733static int http_request(const char *url,
1734                        void *result, int target,
1735                        const struct http_get_options *options)
1736{
1737        struct active_request_slot *slot;
1738        struct slot_results results;
1739        struct curl_slist *headers = http_copy_default_headers();
1740        struct strbuf buf = STRBUF_INIT;
1741        const char *accept_language;
1742        int ret;
1743
1744        slot = get_active_slot();
1745        curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1746
1747        if (result == NULL) {
1748                curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1749        } else {
1750                curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1751                curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1752
1753                if (target == HTTP_REQUEST_FILE) {
1754                        off_t posn = ftello(result);
1755                        curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1756                                         fwrite);
1757                        if (posn > 0)
1758                                http_opt_request_remainder(slot->curl, posn);
1759                } else
1760                        curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1761                                         fwrite_buffer);
1762        }
1763
1764        accept_language = get_accept_language();
1765
1766        if (accept_language)
1767                headers = curl_slist_append(headers, accept_language);
1768
1769        strbuf_addstr(&buf, "Pragma:");
1770        if (options && options->no_cache)
1771                strbuf_addstr(&buf, " no-cache");
1772        if (options && options->keep_error)
1773                curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1774        if (options && options->initial_request &&
1775            http_follow_config == HTTP_FOLLOW_INITIAL)
1776                curl_easy_setopt(slot->curl, CURLOPT_FOLLOWLOCATION, 1);
1777
1778        headers = curl_slist_append(headers, buf.buf);
1779
1780        /* Add additional headers here */
1781        if (options && options->extra_headers) {
1782                const struct string_list_item *item;
1783                for_each_string_list_item(item, options->extra_headers) {
1784                        headers = curl_slist_append(headers, item->string);
1785                }
1786        }
1787
1788        curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1789        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1790        curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1791
1792        ret = run_one_slot(slot, &results);
1793
1794        if (options && options->content_type) {
1795                struct strbuf raw = STRBUF_INIT;
1796                curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1797                extract_content_type(&raw, options->content_type,
1798                                     options->charset);
1799                strbuf_release(&raw);
1800        }
1801
1802        if (options && options->effective_url)
1803                curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1804                                options->effective_url);
1805
1806        curl_slist_free_all(headers);
1807        strbuf_release(&buf);
1808
1809        return ret;
1810}
1811
1812/*
1813 * Update the "base" url to a more appropriate value, as deduced by
1814 * redirects seen when requesting a URL starting with "url".
1815 *
1816 * The "asked" parameter is a URL that we asked curl to access, and must begin
1817 * with "base".
1818 *
1819 * The "got" parameter is the URL that curl reported to us as where we ended
1820 * up.
1821 *
1822 * Returns 1 if we updated the base url, 0 otherwise.
1823 *
1824 * Our basic strategy is to compare "base" and "asked" to find the bits
1825 * specific to our request. We then strip those bits off of "got" to yield the
1826 * new base. So for example, if our base is "http://example.com/foo.git",
1827 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1828 * with "https://other.example.com/foo.git/info/refs". We would want the
1829 * new URL to become "https://other.example.com/foo.git".
1830 *
1831 * Note that this assumes a sane redirect scheme. It's entirely possible
1832 * in the example above to end up at a URL that does not even end in
1833 * "info/refs".  In such a case we die. There's not much we can do, such a
1834 * scheme is unlikely to represent a real git repository, and failing to
1835 * rewrite the base opens options for malicious redirects to do funny things.
1836 */
1837static int update_url_from_redirect(struct strbuf *base,
1838                                    const char *asked,
1839                                    const struct strbuf *got)
1840{
1841        const char *tail;
1842        size_t new_len;
1843
1844        if (!strcmp(asked, got->buf))
1845                return 0;
1846
1847        if (!skip_prefix(asked, base->buf, &tail))
1848                die("BUG: update_url_from_redirect: %s is not a superset of %s",
1849                    asked, base->buf);
1850
1851        new_len = got->len;
1852        if (!strip_suffix_mem(got->buf, &new_len, tail))
1853                die(_("unable to update url base from redirection:\n"
1854                      "  asked for: %s\n"
1855                      "   redirect: %s"),
1856                    asked, got->buf);
1857
1858        strbuf_reset(base);
1859        strbuf_add(base, got->buf, new_len);
1860
1861        return 1;
1862}
1863
1864static int http_request_reauth(const char *url,
1865                               void *result, int target,
1866                               struct http_get_options *options)
1867{
1868        int ret = http_request(url, result, target, options);
1869
1870        if (ret != HTTP_OK && ret != HTTP_REAUTH)
1871                return ret;
1872
1873        if (options && options->effective_url && options->base_url) {
1874                if (update_url_from_redirect(options->base_url,
1875                                             url, options->effective_url)) {
1876                        credential_from_url(&http_auth, options->base_url->buf);
1877                        url = options->effective_url->buf;
1878                }
1879        }
1880
1881        if (ret != HTTP_REAUTH)
1882                return ret;
1883
1884        /*
1885         * If we are using KEEP_ERROR, the previous request may have
1886         * put cruft into our output stream; we should clear it out before
1887         * making our next request. We only know how to do this for
1888         * the strbuf case, but that is enough to satisfy current callers.
1889         */
1890        if (options && options->keep_error) {
1891                switch (target) {
1892                case HTTP_REQUEST_STRBUF:
1893                        strbuf_reset(result);
1894                        break;
1895                default:
1896                        die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1897                }
1898        }
1899
1900        credential_fill(&http_auth);
1901
1902        return http_request(url, result, target, options);
1903}
1904
1905int http_get_strbuf(const char *url,
1906                    struct strbuf *result,
1907                    struct http_get_options *options)
1908{
1909        return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1910}
1911
1912/*
1913 * Downloads a URL and stores the result in the given file.
1914 *
1915 * If a previous interrupted download is detected (i.e. a previous temporary
1916 * file is still around) the download is resumed.
1917 */
1918static int http_get_file(const char *url, const char *filename,
1919                         struct http_get_options *options)
1920{
1921        int ret;
1922        struct strbuf tmpfile = STRBUF_INIT;
1923        FILE *result;
1924
1925        strbuf_addf(&tmpfile, "%s.temp", filename);
1926        result = fopen(tmpfile.buf, "a");
1927        if (!result) {
1928                error("Unable to open local file %s", tmpfile.buf);
1929                ret = HTTP_ERROR;
1930                goto cleanup;
1931        }
1932
1933        ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1934        fclose(result);
1935
1936        if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1937                ret = HTTP_ERROR;
1938cleanup:
1939        strbuf_release(&tmpfile);
1940        return ret;
1941}
1942
1943int http_fetch_ref(const char *base, struct ref *ref)
1944{
1945        struct http_get_options options = {0};
1946        char *url;
1947        struct strbuf buffer = STRBUF_INIT;
1948        int ret = -1;
1949
1950        options.no_cache = 1;
1951
1952        url = quote_ref_url(base, ref->name);
1953        if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1954                strbuf_rtrim(&buffer);
1955                if (buffer.len == 40)
1956                        ret = get_oid_hex(buffer.buf, &ref->old_oid);
1957                else if (starts_with(buffer.buf, "ref: ")) {
1958                        ref->symref = xstrdup(buffer.buf + 5);
1959                        ret = 0;
1960                }
1961        }
1962
1963        strbuf_release(&buffer);
1964        free(url);
1965        return ret;
1966}
1967
1968/* Helpers for fetching packs */
1969static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1970{
1971        char *url, *tmp;
1972        struct strbuf buf = STRBUF_INIT;
1973
1974        if (http_is_verbose)
1975                fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1976
1977        end_url_with_slash(&buf, base_url);
1978        strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1979        url = strbuf_detach(&buf, NULL);
1980
1981        strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1982        tmp = strbuf_detach(&buf, NULL);
1983
1984        if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1985                error("Unable to get pack index %s", url);
1986                FREE_AND_NULL(tmp);
1987        }
1988
1989        free(url);
1990        return tmp;
1991}
1992
1993static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1994        unsigned char *sha1, const char *base_url)
1995{
1996        struct packed_git *new_pack;
1997        char *tmp_idx = NULL;
1998        int ret;
1999
2000        if (has_pack_index(sha1)) {
2001                new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
2002                if (!new_pack)
2003                        return -1; /* parse_pack_index() already issued error message */
2004                goto add_pack;
2005        }
2006
2007        tmp_idx = fetch_pack_index(sha1, base_url);
2008        if (!tmp_idx)
2009                return -1;
2010
2011        new_pack = parse_pack_index(sha1, tmp_idx);
2012        if (!new_pack) {
2013                unlink(tmp_idx);
2014                free(tmp_idx);
2015
2016                return -1; /* parse_pack_index() already issued error message */
2017        }
2018
2019        ret = verify_pack_index(new_pack);
2020        if (!ret) {
2021                close_pack_index(new_pack);
2022                ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
2023        }
2024        free(tmp_idx);
2025        if (ret)
2026                return -1;
2027
2028add_pack:
2029        new_pack->next = *packs_head;
2030        *packs_head = new_pack;
2031        return 0;
2032}
2033
2034int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
2035{
2036        struct http_get_options options = {0};
2037        int ret = 0, i = 0;
2038        char *url, *data;
2039        struct strbuf buf = STRBUF_INIT;
2040        unsigned char sha1[20];
2041
2042        end_url_with_slash(&buf, base_url);
2043        strbuf_addstr(&buf, "objects/info/packs");
2044        url = strbuf_detach(&buf, NULL);
2045
2046        options.no_cache = 1;
2047        ret = http_get_strbuf(url, &buf, &options);
2048        if (ret != HTTP_OK)
2049                goto cleanup;
2050
2051        data = buf.buf;
2052        while (i < buf.len) {
2053                switch (data[i]) {
2054                case 'P':
2055                        i++;
2056                        if (i + 52 <= buf.len &&
2057                            starts_with(data + i, " pack-") &&
2058                            starts_with(data + i + 46, ".pack\n")) {
2059                                get_sha1_hex(data + i + 6, sha1);
2060                                fetch_and_setup_pack_index(packs_head, sha1,
2061                                                      base_url);
2062                                i += 51;
2063                                break;
2064                        }
2065                default:
2066                        while (i < buf.len && data[i] != '\n')
2067                                i++;
2068                }
2069                i++;
2070        }
2071
2072cleanup:
2073        free(url);
2074        return ret;
2075}
2076
2077void release_http_pack_request(struct http_pack_request *preq)
2078{
2079        if (preq->packfile != NULL) {
2080                fclose(preq->packfile);
2081                preq->packfile = NULL;
2082        }
2083        preq->slot = NULL;
2084        free(preq->url);
2085        free(preq);
2086}
2087
2088int finish_http_pack_request(struct http_pack_request *preq)
2089{
2090        struct packed_git **lst;
2091        struct packed_git *p = preq->target;
2092        char *tmp_idx;
2093        size_t len;
2094        struct child_process ip = CHILD_PROCESS_INIT;
2095
2096        close_pack_index(p);
2097
2098        fclose(preq->packfile);
2099        preq->packfile = NULL;
2100
2101        lst = preq->lst;
2102        while (*lst != p)
2103                lst = &((*lst)->next);
2104        *lst = (*lst)->next;
2105
2106        if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
2107                die("BUG: pack tmpfile does not end in .pack.temp?");
2108        tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
2109
2110        argv_array_push(&ip.args, "index-pack");
2111        argv_array_pushl(&ip.args, "-o", tmp_idx, NULL);
2112        argv_array_push(&ip.args, preq->tmpfile);
2113        ip.git_cmd = 1;
2114        ip.no_stdin = 1;
2115        ip.no_stdout = 1;
2116
2117        if (run_command(&ip)) {
2118                unlink(preq->tmpfile);
2119                unlink(tmp_idx);
2120                free(tmp_idx);
2121                return -1;
2122        }
2123
2124        unlink(sha1_pack_index_name(p->sha1));
2125
2126        if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
2127         || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
2128                free(tmp_idx);
2129                return -1;
2130        }
2131
2132        install_packed_git(p);
2133        free(tmp_idx);
2134        return 0;
2135}
2136
2137struct http_pack_request *new_http_pack_request(
2138        struct packed_git *target, const char *base_url)
2139{
2140        off_t prev_posn = 0;
2141        struct strbuf buf = STRBUF_INIT;
2142        struct http_pack_request *preq;
2143
2144        preq = xcalloc(1, sizeof(*preq));
2145        preq->target = target;
2146
2147        end_url_with_slash(&buf, base_url);
2148        strbuf_addf(&buf, "objects/pack/pack-%s.pack",
2149                sha1_to_hex(target->sha1));
2150        preq->url = strbuf_detach(&buf, NULL);
2151
2152        snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
2153                sha1_pack_name(target->sha1));
2154        preq->packfile = fopen(preq->tmpfile, "a");
2155        if (!preq->packfile) {
2156                error("Unable to open local file %s for pack",
2157                      preq->tmpfile);
2158                goto abort;
2159        }
2160
2161        preq->slot = get_active_slot();
2162        curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
2163        curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
2164        curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
2165        curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
2166                no_pragma_header);
2167
2168        /*
2169         * If there is data present from a previous transfer attempt,
2170         * resume where it left off
2171         */
2172        prev_posn = ftello(preq->packfile);
2173        if (prev_posn>0) {
2174                if (http_is_verbose)
2175                        fprintf(stderr,
2176                                "Resuming fetch of pack %s at byte %"PRIuMAX"\n",
2177                                sha1_to_hex(target->sha1), (uintmax_t)prev_posn);
2178                http_opt_request_remainder(preq->slot->curl, prev_posn);
2179        }
2180
2181        return preq;
2182
2183abort:
2184        free(preq->url);
2185        free(preq);
2186        return NULL;
2187}
2188
2189/* Helpers for fetching objects (loose) */
2190static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
2191                               void *data)
2192{
2193        unsigned char expn[4096];
2194        size_t size = eltsize * nmemb;
2195        int posn = 0;
2196        struct http_object_request *freq = data;
2197        struct active_request_slot *slot = freq->slot;
2198
2199        if (slot) {
2200                CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
2201                                                &slot->http_code);
2202                if (c != CURLE_OK)
2203                        die("BUG: curl_easy_getinfo for HTTP code failed: %s",
2204                                curl_easy_strerror(c));
2205                if (slot->http_code >= 300)
2206                        return size;
2207        }
2208
2209        do {
2210                ssize_t retval = xwrite(freq->localfile,
2211                                        (char *) ptr + posn, size - posn);
2212                if (retval < 0)
2213                        return posn;
2214                posn += retval;
2215        } while (posn < size);
2216
2217        freq->stream.avail_in = size;
2218        freq->stream.next_in = (void *)ptr;
2219        do {
2220                freq->stream.next_out = expn;
2221                freq->stream.avail_out = sizeof(expn);
2222                freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
2223                git_SHA1_Update(&freq->c, expn,
2224                                sizeof(expn) - freq->stream.avail_out);
2225        } while (freq->stream.avail_in && freq->zret == Z_OK);
2226        return size;
2227}
2228
2229struct http_object_request *new_http_object_request(const char *base_url,
2230        unsigned char *sha1)
2231{
2232        char *hex = sha1_to_hex(sha1);
2233        struct strbuf filename = STRBUF_INIT;
2234        char prevfile[PATH_MAX];
2235        int prevlocal;
2236        char prev_buf[PREV_BUF_SIZE];
2237        ssize_t prev_read = 0;
2238        off_t prev_posn = 0;
2239        struct http_object_request *freq;
2240
2241        freq = xcalloc(1, sizeof(*freq));
2242        hashcpy(freq->sha1, sha1);
2243        freq->localfile = -1;
2244
2245        sha1_file_name(&filename, sha1);
2246        snprintf(freq->tmpfile, sizeof(freq->tmpfile),
2247                 "%s.temp", filename.buf);
2248
2249        snprintf(prevfile, sizeof(prevfile), "%s.prev", filename.buf);
2250        unlink_or_warn(prevfile);
2251        rename(freq->tmpfile, prevfile);
2252        unlink_or_warn(freq->tmpfile);
2253        strbuf_release(&filename);
2254
2255        if (freq->localfile != -1)
2256                error("fd leakage in start: %d", freq->localfile);
2257        freq->localfile = open(freq->tmpfile,
2258                               O_WRONLY | O_CREAT | O_EXCL, 0666);
2259        /*
2260         * This could have failed due to the "lazy directory creation";
2261         * try to mkdir the last path component.
2262         */
2263        if (freq->localfile < 0 && errno == ENOENT) {
2264                char *dir = strrchr(freq->tmpfile, '/');
2265                if (dir) {
2266                        *dir = 0;
2267                        mkdir(freq->tmpfile, 0777);
2268                        *dir = '/';
2269                }
2270                freq->localfile = open(freq->tmpfile,
2271                                       O_WRONLY | O_CREAT | O_EXCL, 0666);
2272        }
2273
2274        if (freq->localfile < 0) {
2275                error_errno("Couldn't create temporary file %s", freq->tmpfile);
2276                goto abort;
2277        }
2278
2279        git_inflate_init(&freq->stream);
2280
2281        git_SHA1_Init(&freq->c);
2282
2283        freq->url = get_remote_object_url(base_url, hex, 0);
2284
2285        /*
2286         * If a previous temp file is present, process what was already
2287         * fetched.
2288         */
2289        prevlocal = open(prevfile, O_RDONLY);
2290        if (prevlocal != -1) {
2291                do {
2292                        prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
2293                        if (prev_read>0) {
2294                                if (fwrite_sha1_file(prev_buf,
2295                                                     1,
2296                                                     prev_read,
2297                                                     freq) == prev_read) {
2298                                        prev_posn += prev_read;
2299                                } else {
2300                                        prev_read = -1;
2301                                }
2302                        }
2303                } while (prev_read > 0);
2304                close(prevlocal);
2305        }
2306        unlink_or_warn(prevfile);
2307
2308        /*
2309         * Reset inflate/SHA1 if there was an error reading the previous temp
2310         * file; also rewind to the beginning of the local file.
2311         */
2312        if (prev_read == -1) {
2313                memset(&freq->stream, 0, sizeof(freq->stream));
2314                git_inflate_init(&freq->stream);
2315                git_SHA1_Init(&freq->c);
2316                if (prev_posn>0) {
2317                        prev_posn = 0;
2318                        lseek(freq->localfile, 0, SEEK_SET);
2319                        if (ftruncate(freq->localfile, 0) < 0) {
2320                                error_errno("Couldn't truncate temporary file %s",
2321                                            freq->tmpfile);
2322                                goto abort;
2323                        }
2324                }
2325        }
2326
2327        freq->slot = get_active_slot();
2328
2329        curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
2330        curl_easy_setopt(freq->slot->curl, CURLOPT_FAILONERROR, 0);
2331        curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
2332        curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
2333        curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
2334        curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
2335
2336        /*
2337         * If we have successfully processed data from a previous fetch
2338         * attempt, only fetch the data we don't already have.
2339         */
2340        if (prev_posn>0) {
2341                if (http_is_verbose)
2342                        fprintf(stderr,
2343                                "Resuming fetch of object %s at byte %"PRIuMAX"\n",
2344                                hex, (uintmax_t)prev_posn);
2345                http_opt_request_remainder(freq->slot->curl, prev_posn);
2346        }
2347
2348        return freq;
2349
2350abort:
2351        free(freq->url);
2352        free(freq);
2353        return NULL;
2354}
2355
2356void process_http_object_request(struct http_object_request *freq)
2357{
2358        if (freq->slot == NULL)
2359                return;
2360        freq->curl_result = freq->slot->curl_result;
2361        freq->http_code = freq->slot->http_code;
2362        freq->slot = NULL;
2363}
2364
2365int finish_http_object_request(struct http_object_request *freq)
2366{
2367        struct stat st;
2368        struct strbuf filename = STRBUF_INIT;
2369
2370        close(freq->localfile);
2371        freq->localfile = -1;
2372
2373        process_http_object_request(freq);
2374
2375        if (freq->http_code == 416) {
2376                warning("requested range invalid; we may already have all the data.");
2377        } else if (freq->curl_result != CURLE_OK) {
2378                if (stat(freq->tmpfile, &st) == 0)
2379                        if (st.st_size == 0)
2380                                unlink_or_warn(freq->tmpfile);
2381                return -1;
2382        }
2383
2384        git_inflate_end(&freq->stream);
2385        git_SHA1_Final(freq->real_sha1, &freq->c);
2386        if (freq->zret != Z_STREAM_END) {
2387                unlink_or_warn(freq->tmpfile);
2388                return -1;
2389        }
2390        if (hashcmp(freq->sha1, freq->real_sha1)) {
2391                unlink_or_warn(freq->tmpfile);
2392                return -1;
2393        }
2394
2395        sha1_file_name(&filename, freq->sha1);
2396        freq->rename = finalize_object_file(freq->tmpfile, filename.buf);
2397        strbuf_release(&filename);
2398
2399        return freq->rename;
2400}
2401
2402void abort_http_object_request(struct http_object_request *freq)
2403{
2404        unlink_or_warn(freq->tmpfile);
2405
2406        release_http_object_request(freq);
2407}
2408
2409void release_http_object_request(struct http_object_request *freq)
2410{
2411        if (freq->localfile != -1) {
2412                close(freq->localfile);
2413                freq->localfile = -1;
2414        }
2415        if (freq->url != NULL) {
2416                FREE_AND_NULL(freq->url);
2417        }
2418        if (freq->slot != NULL) {
2419                freq->slot->callback_func = NULL;
2420                freq->slot->callback_data = NULL;
2421                release_active_slot(freq->slot);
2422                freq->slot = NULL;
2423        }
2424}