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