a24f0d132d30aadd82eff6a02dc6d86fca48ff63
   1#include "git-compat-util.h"
   2#include "http.h"
   3#include "pack.h"
   4#include "sideband.h"
   5#include "run-command.h"
   6#include "url.h"
   7#include "urlmatch.h"
   8#include "credential.h"
   9#include "version.h"
  10#include "pkt-line.h"
  11#include "gettext.h"
  12#include "transport.h"
  13
  14int active_requests;
  15int http_is_verbose;
  16size_t http_post_buffer = 16 * LARGE_PACKET_MAX;
  17
  18#if LIBCURL_VERSION_NUM >= 0x070a06
  19#define LIBCURL_CAN_HANDLE_AUTH_ANY
  20#endif
  21
  22static int min_curl_sessions = 1;
  23static int curl_session_count;
  24#ifdef USE_CURL_MULTI
  25static int max_requests = -1;
  26static CURLM *curlm;
  27#endif
  28#ifndef NO_CURL_EASY_DUPHANDLE
  29static CURL *curl_default;
  30#endif
  31
  32#define PREV_BUF_SIZE 4096
  33#define RANGE_HEADER_SIZE 30
  34
  35char curl_errorstr[CURL_ERROR_SIZE];
  36
  37static int curl_ssl_verify = -1;
  38static int curl_ssl_try;
  39static const char *ssl_cert;
  40static const char *ssl_cipherlist;
  41static const char *ssl_version;
  42static struct {
  43        const char *name;
  44        long ssl_version;
  45} sslversions[] = {
  46        { "sslv2", CURL_SSLVERSION_SSLv2 },
  47        { "sslv3", CURL_SSLVERSION_SSLv3 },
  48        { "tlsv1", CURL_SSLVERSION_TLSv1 },
  49#if LIBCURL_VERSION_NUM >= 0x072200
  50        { "tlsv1.0", CURL_SSLVERSION_TLSv1_0 },
  51        { "tlsv1.1", CURL_SSLVERSION_TLSv1_1 },
  52        { "tlsv1.2", CURL_SSLVERSION_TLSv1_2 },
  53#endif
  54};
  55#if LIBCURL_VERSION_NUM >= 0x070903
  56static const char *ssl_key;
  57#endif
  58#if LIBCURL_VERSION_NUM >= 0x070908
  59static const char *ssl_capath;
  60#endif
  61static const char *ssl_cainfo;
  62static long curl_low_speed_limit = -1;
  63static long curl_low_speed_time = -1;
  64static int curl_ftp_no_epsv;
  65static const char *curl_http_proxy;
  66static const char *curl_cookie_file;
  67static int curl_save_cookies;
  68struct credential http_auth = CREDENTIAL_INIT;
  69static int http_proactive_auth;
  70static const char *user_agent;
  71
  72#if LIBCURL_VERSION_NUM >= 0x071700
  73/* Use CURLOPT_KEYPASSWD as is */
  74#elif LIBCURL_VERSION_NUM >= 0x070903
  75#define CURLOPT_KEYPASSWD CURLOPT_SSLKEYPASSWD
  76#else
  77#define CURLOPT_KEYPASSWD CURLOPT_SSLCERTPASSWD
  78#endif
  79
  80static struct credential cert_auth = CREDENTIAL_INIT;
  81static int ssl_cert_password_required;
  82#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
  83static unsigned long http_auth_methods = CURLAUTH_ANY;
  84#endif
  85
  86static struct curl_slist *pragma_header;
  87static struct curl_slist *no_pragma_header;
  88
  89static struct active_request_slot *active_queue_head;
  90
  91static char *cached_accept_language;
  92
  93size_t fread_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
  94{
  95        size_t size = eltsize * nmemb;
  96        struct buffer *buffer = buffer_;
  97
  98        if (size > buffer->buf.len - buffer->posn)
  99                size = buffer->buf.len - buffer->posn;
 100        memcpy(ptr, buffer->buf.buf + buffer->posn, size);
 101        buffer->posn += size;
 102
 103        return size;
 104}
 105
 106#ifndef NO_CURL_IOCTL
 107curlioerr ioctl_buffer(CURL *handle, int cmd, void *clientp)
 108{
 109        struct buffer *buffer = clientp;
 110
 111        switch (cmd) {
 112        case CURLIOCMD_NOP:
 113                return CURLIOE_OK;
 114
 115        case CURLIOCMD_RESTARTREAD:
 116                buffer->posn = 0;
 117                return CURLIOE_OK;
 118
 119        default:
 120                return CURLIOE_UNKNOWNCMD;
 121        }
 122}
 123#endif
 124
 125size_t fwrite_buffer(char *ptr, size_t eltsize, size_t nmemb, void *buffer_)
 126{
 127        size_t size = eltsize * nmemb;
 128        struct strbuf *buffer = buffer_;
 129
 130        strbuf_add(buffer, ptr, size);
 131        return size;
 132}
 133
 134size_t fwrite_null(char *ptr, size_t eltsize, size_t nmemb, void *strbuf)
 135{
 136        return eltsize * nmemb;
 137}
 138
 139static void closedown_active_slot(struct active_request_slot *slot)
 140{
 141        active_requests--;
 142        slot->in_use = 0;
 143}
 144
 145static void finish_active_slot(struct active_request_slot *slot)
 146{
 147        closedown_active_slot(slot);
 148        curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE, &slot->http_code);
 149
 150        if (slot->finished != NULL)
 151                (*slot->finished) = 1;
 152
 153        /* Store slot results so they can be read after the slot is reused */
 154        if (slot->results != NULL) {
 155                slot->results->curl_result = slot->curl_result;
 156                slot->results->http_code = slot->http_code;
 157#if LIBCURL_VERSION_NUM >= 0x070a08
 158                curl_easy_getinfo(slot->curl, CURLINFO_HTTPAUTH_AVAIL,
 159                                  &slot->results->auth_avail);
 160#else
 161                slot->results->auth_avail = 0;
 162#endif
 163        }
 164
 165        /* Run callback if appropriate */
 166        if (slot->callback_func != NULL)
 167                slot->callback_func(slot->callback_data);
 168}
 169
 170static void xmulti_remove_handle(struct active_request_slot *slot)
 171{
 172#ifdef USE_CURL_MULTI
 173        curl_multi_remove_handle(curlm, slot->curl);
 174#endif
 175}
 176
 177#ifdef USE_CURL_MULTI
 178static void process_curl_messages(void)
 179{
 180        int num_messages;
 181        struct active_request_slot *slot;
 182        CURLMsg *curl_message = curl_multi_info_read(curlm, &num_messages);
 183
 184        while (curl_message != NULL) {
 185                if (curl_message->msg == CURLMSG_DONE) {
 186                        int curl_result = curl_message->data.result;
 187                        slot = active_queue_head;
 188                        while (slot != NULL &&
 189                               slot->curl != curl_message->easy_handle)
 190                                slot = slot->next;
 191                        if (slot != NULL) {
 192                                xmulti_remove_handle(slot);
 193                                slot->curl_result = curl_result;
 194                                finish_active_slot(slot);
 195                        } else {
 196                                fprintf(stderr, "Received DONE message for unknown request!\n");
 197                        }
 198                } else {
 199                        fprintf(stderr, "Unknown CURL message received: %d\n",
 200                                (int)curl_message->msg);
 201                }
 202                curl_message = curl_multi_info_read(curlm, &num_messages);
 203        }
 204}
 205#endif
 206
 207static int http_options(const char *var, const char *value, void *cb)
 208{
 209        if (!strcmp("http.sslverify", var)) {
 210                curl_ssl_verify = git_config_bool(var, value);
 211                return 0;
 212        }
 213        if (!strcmp("http.sslcipherlist", var))
 214                return git_config_string(&ssl_cipherlist, var, value);
 215        if (!strcmp("http.sslversion", var))
 216                return git_config_string(&ssl_version, var, value);
 217        if (!strcmp("http.sslcert", var))
 218                return git_config_string(&ssl_cert, var, value);
 219#if LIBCURL_VERSION_NUM >= 0x070903
 220        if (!strcmp("http.sslkey", var))
 221                return git_config_string(&ssl_key, var, value);
 222#endif
 223#if LIBCURL_VERSION_NUM >= 0x070908
 224        if (!strcmp("http.sslcapath", var))
 225                return git_config_pathname(&ssl_capath, var, value);
 226#endif
 227        if (!strcmp("http.sslcainfo", var))
 228                return git_config_pathname(&ssl_cainfo, var, value);
 229        if (!strcmp("http.sslcertpasswordprotected", var)) {
 230                ssl_cert_password_required = git_config_bool(var, value);
 231                return 0;
 232        }
 233        if (!strcmp("http.ssltry", var)) {
 234                curl_ssl_try = git_config_bool(var, value);
 235                return 0;
 236        }
 237        if (!strcmp("http.minsessions", var)) {
 238                min_curl_sessions = git_config_int(var, value);
 239#ifndef USE_CURL_MULTI
 240                if (min_curl_sessions > 1)
 241                        min_curl_sessions = 1;
 242#endif
 243                return 0;
 244        }
 245#ifdef USE_CURL_MULTI
 246        if (!strcmp("http.maxrequests", var)) {
 247                max_requests = git_config_int(var, value);
 248                return 0;
 249        }
 250#endif
 251        if (!strcmp("http.lowspeedlimit", var)) {
 252                curl_low_speed_limit = (long)git_config_int(var, value);
 253                return 0;
 254        }
 255        if (!strcmp("http.lowspeedtime", var)) {
 256                curl_low_speed_time = (long)git_config_int(var, value);
 257                return 0;
 258        }
 259
 260        if (!strcmp("http.noepsv", var)) {
 261                curl_ftp_no_epsv = git_config_bool(var, value);
 262                return 0;
 263        }
 264        if (!strcmp("http.proxy", var))
 265                return git_config_string(&curl_http_proxy, var, value);
 266
 267        if (!strcmp("http.cookiefile", var))
 268                return git_config_string(&curl_cookie_file, var, value);
 269        if (!strcmp("http.savecookies", var)) {
 270                curl_save_cookies = git_config_bool(var, value);
 271                return 0;
 272        }
 273
 274        if (!strcmp("http.postbuffer", var)) {
 275                http_post_buffer = git_config_int(var, value);
 276                if (http_post_buffer < LARGE_PACKET_MAX)
 277                        http_post_buffer = LARGE_PACKET_MAX;
 278                return 0;
 279        }
 280
 281        if (!strcmp("http.useragent", var))
 282                return git_config_string(&user_agent, var, value);
 283
 284        /* Fall back on the default ones */
 285        return git_default_config(var, value, cb);
 286}
 287
 288static void init_curl_http_auth(CURL *result)
 289{
 290        if (!http_auth.username)
 291                return;
 292
 293        credential_fill(&http_auth);
 294
 295#if LIBCURL_VERSION_NUM >= 0x071301
 296        curl_easy_setopt(result, CURLOPT_USERNAME, http_auth.username);
 297        curl_easy_setopt(result, CURLOPT_PASSWORD, http_auth.password);
 298#else
 299        {
 300                static struct strbuf up = STRBUF_INIT;
 301                /*
 302                 * Note that we assume we only ever have a single set of
 303                 * credentials in a given program run, so we do not have
 304                 * to worry about updating this buffer, only setting its
 305                 * initial value.
 306                 */
 307                if (!up.len)
 308                        strbuf_addf(&up, "%s:%s",
 309                                http_auth.username, http_auth.password);
 310                curl_easy_setopt(result, CURLOPT_USERPWD, up.buf);
 311        }
 312#endif
 313}
 314
 315static int has_cert_password(void)
 316{
 317        if (ssl_cert == NULL || ssl_cert_password_required != 1)
 318                return 0;
 319        if (!cert_auth.password) {
 320                cert_auth.protocol = xstrdup("cert");
 321                cert_auth.username = xstrdup("");
 322                cert_auth.path = xstrdup(ssl_cert);
 323                credential_fill(&cert_auth);
 324        }
 325        return 1;
 326}
 327
 328#if LIBCURL_VERSION_NUM >= 0x071900
 329static void set_curl_keepalive(CURL *c)
 330{
 331        curl_easy_setopt(c, CURLOPT_TCP_KEEPALIVE, 1);
 332}
 333
 334#elif LIBCURL_VERSION_NUM >= 0x071000
 335static int sockopt_callback(void *client, curl_socket_t fd, curlsocktype type)
 336{
 337        int ka = 1;
 338        int rc;
 339        socklen_t len = (socklen_t)sizeof(ka);
 340
 341        if (type != CURLSOCKTYPE_IPCXN)
 342                return 0;
 343
 344        rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&ka, len);
 345        if (rc < 0)
 346                warning("unable to set SO_KEEPALIVE on socket %s",
 347                        strerror(errno));
 348
 349        return 0; /* CURL_SOCKOPT_OK only exists since curl 7.21.5 */
 350}
 351
 352static void set_curl_keepalive(CURL *c)
 353{
 354        curl_easy_setopt(c, CURLOPT_SOCKOPTFUNCTION, sockopt_callback);
 355}
 356
 357#else
 358static void set_curl_keepalive(CURL *c)
 359{
 360        /* not supported on older curl versions */
 361}
 362#endif
 363
 364static CURL *get_curl_handle(void)
 365{
 366        CURL *result = curl_easy_init();
 367        long allowed_protocols = 0;
 368
 369        if (!result)
 370                die("curl_easy_init failed");
 371
 372        if (!curl_ssl_verify) {
 373                curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0);
 374                curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0);
 375        } else {
 376                /* Verify authenticity of the peer's certificate */
 377                curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1);
 378                /* The name in the cert must match whom we tried to connect */
 379                curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2);
 380        }
 381
 382#if LIBCURL_VERSION_NUM >= 0x070907
 383        curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
 384#endif
 385#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
 386        curl_easy_setopt(result, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
 387#endif
 388
 389        if (http_proactive_auth)
 390                init_curl_http_auth(result);
 391
 392        if (getenv("GIT_SSL_VERSION"))
 393                ssl_version = getenv("GIT_SSL_VERSION");
 394        if (ssl_version && *ssl_version) {
 395                int i;
 396                for (i = 0; i < ARRAY_SIZE(sslversions); i++) {
 397                        if (!strcmp(ssl_version, sslversions[i].name)) {
 398                                curl_easy_setopt(result, CURLOPT_SSLVERSION,
 399                                                 sslversions[i].ssl_version);
 400                                break;
 401                        }
 402                }
 403                if (i == ARRAY_SIZE(sslversions))
 404                        warning("unsupported ssl version %s: using default",
 405                                ssl_version);
 406        }
 407
 408        if (getenv("GIT_SSL_CIPHER_LIST"))
 409                ssl_cipherlist = getenv("GIT_SSL_CIPHER_LIST");
 410        if (ssl_cipherlist != NULL && *ssl_cipherlist)
 411                curl_easy_setopt(result, CURLOPT_SSL_CIPHER_LIST,
 412                                ssl_cipherlist);
 413
 414        if (ssl_cert != NULL)
 415                curl_easy_setopt(result, CURLOPT_SSLCERT, ssl_cert);
 416        if (has_cert_password())
 417                curl_easy_setopt(result, CURLOPT_KEYPASSWD, cert_auth.password);
 418#if LIBCURL_VERSION_NUM >= 0x070903
 419        if (ssl_key != NULL)
 420                curl_easy_setopt(result, CURLOPT_SSLKEY, ssl_key);
 421#endif
 422#if LIBCURL_VERSION_NUM >= 0x070908
 423        if (ssl_capath != NULL)
 424                curl_easy_setopt(result, CURLOPT_CAPATH, ssl_capath);
 425#endif
 426        if (ssl_cainfo != NULL)
 427                curl_easy_setopt(result, CURLOPT_CAINFO, ssl_cainfo);
 428
 429        if (curl_low_speed_limit > 0 && curl_low_speed_time > 0) {
 430                curl_easy_setopt(result, CURLOPT_LOW_SPEED_LIMIT,
 431                                 curl_low_speed_limit);
 432                curl_easy_setopt(result, CURLOPT_LOW_SPEED_TIME,
 433                                 curl_low_speed_time);
 434        }
 435
 436        curl_easy_setopt(result, CURLOPT_FOLLOWLOCATION, 1);
 437        curl_easy_setopt(result, CURLOPT_MAXREDIRS, 20);
 438#if LIBCURL_VERSION_NUM >= 0x071301
 439        curl_easy_setopt(result, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
 440#elif LIBCURL_VERSION_NUM >= 0x071101
 441        curl_easy_setopt(result, CURLOPT_POST301, 1);
 442#endif
 443#if LIBCURL_VERSION_NUM >= 0x071304
 444        if (is_transport_allowed("http"))
 445                allowed_protocols |= CURLPROTO_HTTP;
 446        if (is_transport_allowed("https"))
 447                allowed_protocols |= CURLPROTO_HTTPS;
 448        if (is_transport_allowed("ftp"))
 449                allowed_protocols |= CURLPROTO_FTP;
 450        if (is_transport_allowed("ftps"))
 451                allowed_protocols |= CURLPROTO_FTPS;
 452        curl_easy_setopt(result, CURLOPT_REDIR_PROTOCOLS, allowed_protocols);
 453#else
 454        if (transport_restrict_protocols())
 455                warning("protocol restrictions not applied to curl redirects because\n"
 456                        "your curl version is too old (>= 7.19.4)");
 457#endif
 458
 459        if (getenv("GIT_CURL_VERBOSE"))
 460                curl_easy_setopt(result, CURLOPT_VERBOSE, 1);
 461
 462        curl_easy_setopt(result, CURLOPT_USERAGENT,
 463                user_agent ? user_agent : git_user_agent());
 464
 465        if (curl_ftp_no_epsv)
 466                curl_easy_setopt(result, CURLOPT_FTP_USE_EPSV, 0);
 467
 468#ifdef CURLOPT_USE_SSL
 469        if (curl_ssl_try)
 470                curl_easy_setopt(result, CURLOPT_USE_SSL, CURLUSESSL_TRY);
 471#endif
 472
 473        if (curl_http_proxy) {
 474                curl_easy_setopt(result, CURLOPT_PROXY, curl_http_proxy);
 475#if LIBCURL_VERSION_NUM >= 0x071800
 476                if (starts_with(curl_http_proxy, "socks5"))
 477                        curl_easy_setopt(result,
 478                                CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
 479                else if (starts_with(curl_http_proxy, "socks4a"))
 480                        curl_easy_setopt(result,
 481                                CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A);
 482                else if (starts_with(curl_http_proxy, "socks"))
 483                        curl_easy_setopt(result,
 484                                CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
 485#endif
 486        }
 487#if LIBCURL_VERSION_NUM >= 0x070a07
 488        curl_easy_setopt(result, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
 489#endif
 490
 491        set_curl_keepalive(result);
 492
 493        return result;
 494}
 495
 496static void set_from_env(const char **var, const char *envname)
 497{
 498        const char *val = getenv(envname);
 499        if (val)
 500                *var = val;
 501}
 502
 503void http_init(struct remote *remote, const char *url, int proactive_auth)
 504{
 505        char *low_speed_limit;
 506        char *low_speed_time;
 507        char *normalized_url;
 508        struct urlmatch_config config = { STRING_LIST_INIT_DUP };
 509
 510        config.section = "http";
 511        config.key = NULL;
 512        config.collect_fn = http_options;
 513        config.cascade_fn = git_default_config;
 514        config.cb = NULL;
 515
 516        http_is_verbose = 0;
 517        normalized_url = url_normalize(url, &config.url);
 518
 519        git_config(urlmatch_config_entry, &config);
 520        free(normalized_url);
 521
 522        if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
 523                die("curl_global_init failed");
 524
 525        http_proactive_auth = proactive_auth;
 526
 527        if (remote && remote->http_proxy)
 528                curl_http_proxy = xstrdup(remote->http_proxy);
 529
 530        pragma_header = curl_slist_append(pragma_header, "Pragma: no-cache");
 531        no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
 532
 533#ifdef USE_CURL_MULTI
 534        {
 535                char *http_max_requests = getenv("GIT_HTTP_MAX_REQUESTS");
 536                if (http_max_requests != NULL)
 537                        max_requests = atoi(http_max_requests);
 538        }
 539
 540        curlm = curl_multi_init();
 541        if (!curlm)
 542                die("curl_multi_init failed");
 543#endif
 544
 545        if (getenv("GIT_SSL_NO_VERIFY"))
 546                curl_ssl_verify = 0;
 547
 548        set_from_env(&ssl_cert, "GIT_SSL_CERT");
 549#if LIBCURL_VERSION_NUM >= 0x070903
 550        set_from_env(&ssl_key, "GIT_SSL_KEY");
 551#endif
 552#if LIBCURL_VERSION_NUM >= 0x070908
 553        set_from_env(&ssl_capath, "GIT_SSL_CAPATH");
 554#endif
 555        set_from_env(&ssl_cainfo, "GIT_SSL_CAINFO");
 556
 557        set_from_env(&user_agent, "GIT_HTTP_USER_AGENT");
 558
 559        low_speed_limit = getenv("GIT_HTTP_LOW_SPEED_LIMIT");
 560        if (low_speed_limit != NULL)
 561                curl_low_speed_limit = strtol(low_speed_limit, NULL, 10);
 562        low_speed_time = getenv("GIT_HTTP_LOW_SPEED_TIME");
 563        if (low_speed_time != NULL)
 564                curl_low_speed_time = strtol(low_speed_time, NULL, 10);
 565
 566        if (curl_ssl_verify == -1)
 567                curl_ssl_verify = 1;
 568
 569        curl_session_count = 0;
 570#ifdef USE_CURL_MULTI
 571        if (max_requests < 1)
 572                max_requests = DEFAULT_MAX_REQUESTS;
 573#endif
 574
 575        if (getenv("GIT_CURL_FTP_NO_EPSV"))
 576                curl_ftp_no_epsv = 1;
 577
 578        if (url) {
 579                credential_from_url(&http_auth, url);
 580                if (!ssl_cert_password_required &&
 581                    getenv("GIT_SSL_CERT_PASSWORD_PROTECTED") &&
 582                    starts_with(url, "https://"))
 583                        ssl_cert_password_required = 1;
 584        }
 585
 586#ifndef NO_CURL_EASY_DUPHANDLE
 587        curl_default = get_curl_handle();
 588#endif
 589}
 590
 591void http_cleanup(void)
 592{
 593        struct active_request_slot *slot = active_queue_head;
 594
 595        while (slot != NULL) {
 596                struct active_request_slot *next = slot->next;
 597                if (slot->curl != NULL) {
 598                        xmulti_remove_handle(slot);
 599                        curl_easy_cleanup(slot->curl);
 600                }
 601                free(slot);
 602                slot = next;
 603        }
 604        active_queue_head = NULL;
 605
 606#ifndef NO_CURL_EASY_DUPHANDLE
 607        curl_easy_cleanup(curl_default);
 608#endif
 609
 610#ifdef USE_CURL_MULTI
 611        curl_multi_cleanup(curlm);
 612#endif
 613        curl_global_cleanup();
 614
 615        curl_slist_free_all(pragma_header);
 616        pragma_header = NULL;
 617
 618        curl_slist_free_all(no_pragma_header);
 619        no_pragma_header = NULL;
 620
 621        if (curl_http_proxy) {
 622                free((void *)curl_http_proxy);
 623                curl_http_proxy = NULL;
 624        }
 625
 626        if (cert_auth.password != NULL) {
 627                memset(cert_auth.password, 0, strlen(cert_auth.password));
 628                free(cert_auth.password);
 629                cert_auth.password = NULL;
 630        }
 631        ssl_cert_password_required = 0;
 632
 633        free(cached_accept_language);
 634        cached_accept_language = NULL;
 635}
 636
 637struct active_request_slot *get_active_slot(void)
 638{
 639        struct active_request_slot *slot = active_queue_head;
 640        struct active_request_slot *newslot;
 641
 642#ifdef USE_CURL_MULTI
 643        int num_transfers;
 644
 645        /* Wait for a slot to open up if the queue is full */
 646        while (active_requests >= max_requests) {
 647                curl_multi_perform(curlm, &num_transfers);
 648                if (num_transfers < active_requests)
 649                        process_curl_messages();
 650        }
 651#endif
 652
 653        while (slot != NULL && slot->in_use)
 654                slot = slot->next;
 655
 656        if (slot == NULL) {
 657                newslot = xmalloc(sizeof(*newslot));
 658                newslot->curl = NULL;
 659                newslot->in_use = 0;
 660                newslot->next = NULL;
 661
 662                slot = active_queue_head;
 663                if (slot == NULL) {
 664                        active_queue_head = newslot;
 665                } else {
 666                        while (slot->next != NULL)
 667                                slot = slot->next;
 668                        slot->next = newslot;
 669                }
 670                slot = newslot;
 671        }
 672
 673        if (slot->curl == NULL) {
 674#ifdef NO_CURL_EASY_DUPHANDLE
 675                slot->curl = get_curl_handle();
 676#else
 677                slot->curl = curl_easy_duphandle(curl_default);
 678#endif
 679                curl_session_count++;
 680        }
 681
 682        active_requests++;
 683        slot->in_use = 1;
 684        slot->results = NULL;
 685        slot->finished = NULL;
 686        slot->callback_data = NULL;
 687        slot->callback_func = NULL;
 688        curl_easy_setopt(slot->curl, CURLOPT_COOKIEFILE, curl_cookie_file);
 689        if (curl_save_cookies)
 690                curl_easy_setopt(slot->curl, CURLOPT_COOKIEJAR, curl_cookie_file);
 691        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, pragma_header);
 692        curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, curl_errorstr);
 693        curl_easy_setopt(slot->curl, CURLOPT_CUSTOMREQUEST, NULL);
 694        curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, NULL);
 695        curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, NULL);
 696        curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, NULL);
 697        curl_easy_setopt(slot->curl, CURLOPT_UPLOAD, 0);
 698        curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
 699        curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 1);
 700#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
 701        curl_easy_setopt(slot->curl, CURLOPT_HTTPAUTH, http_auth_methods);
 702#endif
 703        if (http_auth.password)
 704                init_curl_http_auth(slot->curl);
 705
 706        return slot;
 707}
 708
 709int start_active_slot(struct active_request_slot *slot)
 710{
 711#ifdef USE_CURL_MULTI
 712        CURLMcode curlm_result = curl_multi_add_handle(curlm, slot->curl);
 713        int num_transfers;
 714
 715        if (curlm_result != CURLM_OK &&
 716            curlm_result != CURLM_CALL_MULTI_PERFORM) {
 717                warning("curl_multi_add_handle failed: %s",
 718                        curl_multi_strerror(curlm_result));
 719                active_requests--;
 720                slot->in_use = 0;
 721                return 0;
 722        }
 723
 724        /*
 725         * We know there must be something to do, since we just added
 726         * something.
 727         */
 728        curl_multi_perform(curlm, &num_transfers);
 729#endif
 730        return 1;
 731}
 732
 733#ifdef USE_CURL_MULTI
 734struct fill_chain {
 735        void *data;
 736        int (*fill)(void *);
 737        struct fill_chain *next;
 738};
 739
 740static struct fill_chain *fill_cfg;
 741
 742void add_fill_function(void *data, int (*fill)(void *))
 743{
 744        struct fill_chain *new = xmalloc(sizeof(*new));
 745        struct fill_chain **linkp = &fill_cfg;
 746        new->data = data;
 747        new->fill = fill;
 748        new->next = NULL;
 749        while (*linkp)
 750                linkp = &(*linkp)->next;
 751        *linkp = new;
 752}
 753
 754void fill_active_slots(void)
 755{
 756        struct active_request_slot *slot = active_queue_head;
 757
 758        while (active_requests < max_requests) {
 759                struct fill_chain *fill;
 760                for (fill = fill_cfg; fill; fill = fill->next)
 761                        if (fill->fill(fill->data))
 762                                break;
 763
 764                if (!fill)
 765                        break;
 766        }
 767
 768        while (slot != NULL) {
 769                if (!slot->in_use && slot->curl != NULL
 770                        && curl_session_count > min_curl_sessions) {
 771                        curl_easy_cleanup(slot->curl);
 772                        slot->curl = NULL;
 773                        curl_session_count--;
 774                }
 775                slot = slot->next;
 776        }
 777}
 778
 779void step_active_slots(void)
 780{
 781        int num_transfers;
 782        CURLMcode curlm_result;
 783
 784        do {
 785                curlm_result = curl_multi_perform(curlm, &num_transfers);
 786        } while (curlm_result == CURLM_CALL_MULTI_PERFORM);
 787        if (num_transfers < active_requests) {
 788                process_curl_messages();
 789                fill_active_slots();
 790        }
 791}
 792#endif
 793
 794void run_active_slot(struct active_request_slot *slot)
 795{
 796#ifdef USE_CURL_MULTI
 797        fd_set readfds;
 798        fd_set writefds;
 799        fd_set excfds;
 800        int max_fd;
 801        struct timeval select_timeout;
 802        int finished = 0;
 803
 804        slot->finished = &finished;
 805        while (!finished) {
 806                step_active_slots();
 807
 808                if (slot->in_use) {
 809#if LIBCURL_VERSION_NUM >= 0x070f04
 810                        long curl_timeout;
 811                        curl_multi_timeout(curlm, &curl_timeout);
 812                        if (curl_timeout == 0) {
 813                                continue;
 814                        } else if (curl_timeout == -1) {
 815                                select_timeout.tv_sec  = 0;
 816                                select_timeout.tv_usec = 50000;
 817                        } else {
 818                                select_timeout.tv_sec  =  curl_timeout / 1000;
 819                                select_timeout.tv_usec = (curl_timeout % 1000) * 1000;
 820                        }
 821#else
 822                        select_timeout.tv_sec  = 0;
 823                        select_timeout.tv_usec = 50000;
 824#endif
 825
 826                        max_fd = -1;
 827                        FD_ZERO(&readfds);
 828                        FD_ZERO(&writefds);
 829                        FD_ZERO(&excfds);
 830                        curl_multi_fdset(curlm, &readfds, &writefds, &excfds, &max_fd);
 831
 832                        /*
 833                         * It can happen that curl_multi_timeout returns a pathologically
 834                         * long timeout when curl_multi_fdset returns no file descriptors
 835                         * to read.  See commit message for more details.
 836                         */
 837                        if (max_fd < 0 &&
 838                            (select_timeout.tv_sec > 0 ||
 839                             select_timeout.tv_usec > 50000)) {
 840                                select_timeout.tv_sec  = 0;
 841                                select_timeout.tv_usec = 50000;
 842                        }
 843
 844                        select(max_fd+1, &readfds, &writefds, &excfds, &select_timeout);
 845                }
 846        }
 847#else
 848        while (slot->in_use) {
 849                slot->curl_result = curl_easy_perform(slot->curl);
 850                finish_active_slot(slot);
 851        }
 852#endif
 853}
 854
 855static void release_active_slot(struct active_request_slot *slot)
 856{
 857        closedown_active_slot(slot);
 858        if (slot->curl && curl_session_count > min_curl_sessions) {
 859                xmulti_remove_handle(slot);
 860                curl_easy_cleanup(slot->curl);
 861                slot->curl = NULL;
 862                curl_session_count--;
 863        }
 864#ifdef USE_CURL_MULTI
 865        fill_active_slots();
 866#endif
 867}
 868
 869void finish_all_active_slots(void)
 870{
 871        struct active_request_slot *slot = active_queue_head;
 872
 873        while (slot != NULL)
 874                if (slot->in_use) {
 875                        run_active_slot(slot);
 876                        slot = active_queue_head;
 877                } else {
 878                        slot = slot->next;
 879                }
 880}
 881
 882/* Helpers for modifying and creating URLs */
 883static inline int needs_quote(int ch)
 884{
 885        if (((ch >= 'A') && (ch <= 'Z'))
 886                        || ((ch >= 'a') && (ch <= 'z'))
 887                        || ((ch >= '0') && (ch <= '9'))
 888                        || (ch == '/')
 889                        || (ch == '-')
 890                        || (ch == '.'))
 891                return 0;
 892        return 1;
 893}
 894
 895static char *quote_ref_url(const char *base, const char *ref)
 896{
 897        struct strbuf buf = STRBUF_INIT;
 898        const char *cp;
 899        int ch;
 900
 901        end_url_with_slash(&buf, base);
 902
 903        for (cp = ref; (ch = *cp) != 0; cp++)
 904                if (needs_quote(ch))
 905                        strbuf_addf(&buf, "%%%02x", ch);
 906                else
 907                        strbuf_addch(&buf, *cp);
 908
 909        return strbuf_detach(&buf, NULL);
 910}
 911
 912void append_remote_object_url(struct strbuf *buf, const char *url,
 913                              const char *hex,
 914                              int only_two_digit_prefix)
 915{
 916        end_url_with_slash(buf, url);
 917
 918        strbuf_addf(buf, "objects/%.*s/", 2, hex);
 919        if (!only_two_digit_prefix)
 920                strbuf_addf(buf, "%s", hex+2);
 921}
 922
 923char *get_remote_object_url(const char *url, const char *hex,
 924                            int only_two_digit_prefix)
 925{
 926        struct strbuf buf = STRBUF_INIT;
 927        append_remote_object_url(&buf, url, hex, only_two_digit_prefix);
 928        return strbuf_detach(&buf, NULL);
 929}
 930
 931static int handle_curl_result(struct slot_results *results)
 932{
 933        /*
 934         * If we see a failing http code with CURLE_OK, we have turned off
 935         * FAILONERROR (to keep the server's custom error response), and should
 936         * translate the code into failure here.
 937         */
 938        if (results->curl_result == CURLE_OK &&
 939            results->http_code >= 400) {
 940                results->curl_result = CURLE_HTTP_RETURNED_ERROR;
 941                /*
 942                 * Normally curl will already have put the "reason phrase"
 943                 * from the server into curl_errorstr; unfortunately without
 944                 * FAILONERROR it is lost, so we can give only the numeric
 945                 * status code.
 946                 */
 947                snprintf(curl_errorstr, sizeof(curl_errorstr),
 948                         "The requested URL returned error: %ld",
 949                         results->http_code);
 950        }
 951
 952        if (results->curl_result == CURLE_OK) {
 953                credential_approve(&http_auth);
 954                return HTTP_OK;
 955        } else if (missing_target(results))
 956                return HTTP_MISSING_TARGET;
 957        else if (results->http_code == 401) {
 958                if (http_auth.username && http_auth.password) {
 959                        credential_reject(&http_auth);
 960                        return HTTP_NOAUTH;
 961                } else {
 962#ifdef LIBCURL_CAN_HANDLE_AUTH_ANY
 963                        http_auth_methods &= ~CURLAUTH_GSSNEGOTIATE;
 964#endif
 965                        return HTTP_REAUTH;
 966                }
 967        } else {
 968#if LIBCURL_VERSION_NUM >= 0x070c00
 969                if (!curl_errorstr[0])
 970                        strlcpy(curl_errorstr,
 971                                curl_easy_strerror(results->curl_result),
 972                                sizeof(curl_errorstr));
 973#endif
 974                return HTTP_ERROR;
 975        }
 976}
 977
 978int run_one_slot(struct active_request_slot *slot,
 979                 struct slot_results *results)
 980{
 981        slot->results = results;
 982        if (!start_active_slot(slot)) {
 983                snprintf(curl_errorstr, sizeof(curl_errorstr),
 984                         "failed to start HTTP request");
 985                return HTTP_START_FAILED;
 986        }
 987
 988        run_active_slot(slot);
 989        return handle_curl_result(results);
 990}
 991
 992static CURLcode curlinfo_strbuf(CURL *curl, CURLINFO info, struct strbuf *buf)
 993{
 994        char *ptr;
 995        CURLcode ret;
 996
 997        strbuf_reset(buf);
 998        ret = curl_easy_getinfo(curl, info, &ptr);
 999        if (!ret && ptr)
1000                strbuf_addstr(buf, ptr);
1001        return ret;
1002}
1003
1004/*
1005 * Check for and extract a content-type parameter. "raw"
1006 * should be positioned at the start of the potential
1007 * parameter, with any whitespace already removed.
1008 *
1009 * "name" is the name of the parameter. The value is appended
1010 * to "out".
1011 */
1012static int extract_param(const char *raw, const char *name,
1013                         struct strbuf *out)
1014{
1015        size_t len = strlen(name);
1016
1017        if (strncasecmp(raw, name, len))
1018                return -1;
1019        raw += len;
1020
1021        if (*raw != '=')
1022                return -1;
1023        raw++;
1024
1025        while (*raw && !isspace(*raw) && *raw != ';')
1026                strbuf_addch(out, *raw++);
1027        return 0;
1028}
1029
1030/*
1031 * Extract a normalized version of the content type, with any
1032 * spaces suppressed, all letters lowercased, and no trailing ";"
1033 * or parameters.
1034 *
1035 * Note that we will silently remove even invalid whitespace. For
1036 * example, "text / plain" is specifically forbidden by RFC 2616,
1037 * but "text/plain" is the only reasonable output, and this keeps
1038 * our code simple.
1039 *
1040 * If the "charset" argument is not NULL, store the value of any
1041 * charset parameter there.
1042 *
1043 * Example:
1044 *   "TEXT/PLAIN; charset=utf-8" -> "text/plain", "utf-8"
1045 *   "text / plain" -> "text/plain"
1046 */
1047static void extract_content_type(struct strbuf *raw, struct strbuf *type,
1048                                 struct strbuf *charset)
1049{
1050        const char *p;
1051
1052        strbuf_reset(type);
1053        strbuf_grow(type, raw->len);
1054        for (p = raw->buf; *p; p++) {
1055                if (isspace(*p))
1056                        continue;
1057                if (*p == ';') {
1058                        p++;
1059                        break;
1060                }
1061                strbuf_addch(type, tolower(*p));
1062        }
1063
1064        if (!charset)
1065                return;
1066
1067        strbuf_reset(charset);
1068        while (*p) {
1069                while (isspace(*p) || *p == ';')
1070                        p++;
1071                if (!extract_param(p, "charset", charset))
1072                        return;
1073                while (*p && !isspace(*p))
1074                        p++;
1075        }
1076
1077        if (!charset->len && starts_with(type->buf, "text/"))
1078                strbuf_addstr(charset, "ISO-8859-1");
1079}
1080
1081static void write_accept_language(struct strbuf *buf)
1082{
1083        /*
1084         * MAX_DECIMAL_PLACES must not be larger than 3. If it is larger than
1085         * that, q-value will be smaller than 0.001, the minimum q-value the
1086         * HTTP specification allows. See
1087         * http://tools.ietf.org/html/rfc7231#section-5.3.1 for q-value.
1088         */
1089        const int MAX_DECIMAL_PLACES = 3;
1090        const int MAX_LANGUAGE_TAGS = 1000;
1091        const int MAX_ACCEPT_LANGUAGE_HEADER_SIZE = 4000;
1092        char **language_tags = NULL;
1093        int num_langs = 0;
1094        const char *s = get_preferred_languages();
1095        int i;
1096        struct strbuf tag = STRBUF_INIT;
1097
1098        /* Don't add Accept-Language header if no language is preferred. */
1099        if (!s)
1100                return;
1101
1102        /*
1103         * Split the colon-separated string of preferred languages into
1104         * language_tags array.
1105         */
1106        do {
1107                /* collect language tag */
1108                for (; *s && (isalnum(*s) || *s == '_'); s++)
1109                        strbuf_addch(&tag, *s == '_' ? '-' : *s);
1110
1111                /* skip .codeset, @modifier and any other unnecessary parts */
1112                while (*s && *s != ':')
1113                        s++;
1114
1115                if (tag.len) {
1116                        num_langs++;
1117                        REALLOC_ARRAY(language_tags, num_langs);
1118                        language_tags[num_langs - 1] = strbuf_detach(&tag, NULL);
1119                        if (num_langs >= MAX_LANGUAGE_TAGS - 1) /* -1 for '*' */
1120                                break;
1121                }
1122        } while (*s++);
1123
1124        /* write Accept-Language header into buf */
1125        if (num_langs) {
1126                int last_buf_len = 0;
1127                int max_q;
1128                int decimal_places;
1129                char q_format[32];
1130
1131                /* add '*' */
1132                REALLOC_ARRAY(language_tags, num_langs + 1);
1133                language_tags[num_langs++] = "*"; /* it's OK; this won't be freed */
1134
1135                /* compute decimal_places */
1136                for (max_q = 1, decimal_places = 0;
1137                     max_q < num_langs && decimal_places <= MAX_DECIMAL_PLACES;
1138                     decimal_places++, max_q *= 10)
1139                        ;
1140
1141                sprintf(q_format, ";q=0.%%0%dd", decimal_places);
1142
1143                strbuf_addstr(buf, "Accept-Language: ");
1144
1145                for (i = 0; i < num_langs; i++) {
1146                        if (i > 0)
1147                                strbuf_addstr(buf, ", ");
1148
1149                        strbuf_addstr(buf, language_tags[i]);
1150
1151                        if (i > 0)
1152                                strbuf_addf(buf, q_format, max_q - i);
1153
1154                        if (buf->len > MAX_ACCEPT_LANGUAGE_HEADER_SIZE) {
1155                                strbuf_remove(buf, last_buf_len, buf->len - last_buf_len);
1156                                break;
1157                        }
1158
1159                        last_buf_len = buf->len;
1160                }
1161        }
1162
1163        /* free language tags -- last one is a static '*' */
1164        for (i = 0; i < num_langs - 1; i++)
1165                free(language_tags[i]);
1166        free(language_tags);
1167}
1168
1169/*
1170 * Get an Accept-Language header which indicates user's preferred languages.
1171 *
1172 * Examples:
1173 *   LANGUAGE= -> ""
1174 *   LANGUAGE=ko:en -> "Accept-Language: ko, en; q=0.9, *; q=0.1"
1175 *   LANGUAGE=ko_KR.UTF-8:sr@latin -> "Accept-Language: ko-KR, sr; q=0.9, *; q=0.1"
1176 *   LANGUAGE=ko LANG=en_US.UTF-8 -> "Accept-Language: ko, *; q=0.1"
1177 *   LANGUAGE= LANG=en_US.UTF-8 -> "Accept-Language: en-US, *; q=0.1"
1178 *   LANGUAGE= LANG=C -> ""
1179 */
1180static const char *get_accept_language(void)
1181{
1182        if (!cached_accept_language) {
1183                struct strbuf buf = STRBUF_INIT;
1184                write_accept_language(&buf);
1185                if (buf.len > 0)
1186                        cached_accept_language = strbuf_detach(&buf, NULL);
1187        }
1188
1189        return cached_accept_language;
1190}
1191
1192/* http_request() targets */
1193#define HTTP_REQUEST_STRBUF     0
1194#define HTTP_REQUEST_FILE       1
1195
1196static int http_request(const char *url,
1197                        void *result, int target,
1198                        const struct http_get_options *options)
1199{
1200        struct active_request_slot *slot;
1201        struct slot_results results;
1202        struct curl_slist *headers = NULL;
1203        struct strbuf buf = STRBUF_INIT;
1204        const char *accept_language;
1205        int ret;
1206
1207        slot = get_active_slot();
1208        curl_easy_setopt(slot->curl, CURLOPT_HTTPGET, 1);
1209
1210        if (result == NULL) {
1211                curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 1);
1212        } else {
1213                curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
1214                curl_easy_setopt(slot->curl, CURLOPT_FILE, result);
1215
1216                if (target == HTTP_REQUEST_FILE) {
1217                        long posn = ftell(result);
1218                        curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1219                                         fwrite);
1220                        if (posn > 0) {
1221                                strbuf_addf(&buf, "Range: bytes=%ld-", posn);
1222                                headers = curl_slist_append(headers, buf.buf);
1223                                strbuf_reset(&buf);
1224                        }
1225                } else
1226                        curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION,
1227                                         fwrite_buffer);
1228        }
1229
1230        accept_language = get_accept_language();
1231
1232        if (accept_language)
1233                headers = curl_slist_append(headers, accept_language);
1234
1235        strbuf_addstr(&buf, "Pragma:");
1236        if (options && options->no_cache)
1237                strbuf_addstr(&buf, " no-cache");
1238        if (options && options->keep_error)
1239                curl_easy_setopt(slot->curl, CURLOPT_FAILONERROR, 0);
1240
1241        headers = curl_slist_append(headers, buf.buf);
1242
1243        curl_easy_setopt(slot->curl, CURLOPT_URL, url);
1244        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
1245        curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
1246
1247        ret = run_one_slot(slot, &results);
1248
1249        if (options && options->content_type) {
1250                struct strbuf raw = STRBUF_INIT;
1251                curlinfo_strbuf(slot->curl, CURLINFO_CONTENT_TYPE, &raw);
1252                extract_content_type(&raw, options->content_type,
1253                                     options->charset);
1254                strbuf_release(&raw);
1255        }
1256
1257        if (options && options->effective_url)
1258                curlinfo_strbuf(slot->curl, CURLINFO_EFFECTIVE_URL,
1259                                options->effective_url);
1260
1261        curl_slist_free_all(headers);
1262        strbuf_release(&buf);
1263
1264        return ret;
1265}
1266
1267/*
1268 * Update the "base" url to a more appropriate value, as deduced by
1269 * redirects seen when requesting a URL starting with "url".
1270 *
1271 * The "asked" parameter is a URL that we asked curl to access, and must begin
1272 * with "base".
1273 *
1274 * The "got" parameter is the URL that curl reported to us as where we ended
1275 * up.
1276 *
1277 * Returns 1 if we updated the base url, 0 otherwise.
1278 *
1279 * Our basic strategy is to compare "base" and "asked" to find the bits
1280 * specific to our request. We then strip those bits off of "got" to yield the
1281 * new base. So for example, if our base is "http://example.com/foo.git",
1282 * and we ask for "http://example.com/foo.git/info/refs", we might end up
1283 * with "https://other.example.com/foo.git/info/refs". We would want the
1284 * new URL to become "https://other.example.com/foo.git".
1285 *
1286 * Note that this assumes a sane redirect scheme. It's entirely possible
1287 * in the example above to end up at a URL that does not even end in
1288 * "info/refs".  In such a case we simply punt, as there is not much we can
1289 * do (and such a scheme is unlikely to represent a real git repository,
1290 * which means we are likely about to abort anyway).
1291 */
1292static int update_url_from_redirect(struct strbuf *base,
1293                                    const char *asked,
1294                                    const struct strbuf *got)
1295{
1296        const char *tail;
1297        size_t tail_len;
1298
1299        if (!strcmp(asked, got->buf))
1300                return 0;
1301
1302        if (!skip_prefix(asked, base->buf, &tail))
1303                die("BUG: update_url_from_redirect: %s is not a superset of %s",
1304                    asked, base->buf);
1305
1306        tail_len = strlen(tail);
1307
1308        if (got->len < tail_len ||
1309            strcmp(tail, got->buf + got->len - tail_len))
1310                return 0; /* insane redirect scheme */
1311
1312        strbuf_reset(base);
1313        strbuf_add(base, got->buf, got->len - tail_len);
1314        return 1;
1315}
1316
1317static int http_request_reauth(const char *url,
1318                               void *result, int target,
1319                               struct http_get_options *options)
1320{
1321        int ret = http_request(url, result, target, options);
1322
1323        if (options && options->effective_url && options->base_url) {
1324                if (update_url_from_redirect(options->base_url,
1325                                             url, options->effective_url)) {
1326                        credential_from_url(&http_auth, options->base_url->buf);
1327                        url = options->effective_url->buf;
1328                }
1329        }
1330
1331        if (ret != HTTP_REAUTH)
1332                return ret;
1333
1334        /*
1335         * If we are using KEEP_ERROR, the previous request may have
1336         * put cruft into our output stream; we should clear it out before
1337         * making our next request. We only know how to do this for
1338         * the strbuf case, but that is enough to satisfy current callers.
1339         */
1340        if (options && options->keep_error) {
1341                switch (target) {
1342                case HTTP_REQUEST_STRBUF:
1343                        strbuf_reset(result);
1344                        break;
1345                default:
1346                        die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
1347                }
1348        }
1349
1350        credential_fill(&http_auth);
1351
1352        return http_request(url, result, target, options);
1353}
1354
1355int http_get_strbuf(const char *url,
1356                    struct strbuf *result,
1357                    struct http_get_options *options)
1358{
1359        return http_request_reauth(url, result, HTTP_REQUEST_STRBUF, options);
1360}
1361
1362/*
1363 * Downloads a URL and stores the result in the given file.
1364 *
1365 * If a previous interrupted download is detected (i.e. a previous temporary
1366 * file is still around) the download is resumed.
1367 */
1368static int http_get_file(const char *url, const char *filename,
1369                         struct http_get_options *options)
1370{
1371        int ret;
1372        struct strbuf tmpfile = STRBUF_INIT;
1373        FILE *result;
1374
1375        strbuf_addf(&tmpfile, "%s.temp", filename);
1376        result = fopen(tmpfile.buf, "a");
1377        if (!result) {
1378                error("Unable to open local file %s", tmpfile.buf);
1379                ret = HTTP_ERROR;
1380                goto cleanup;
1381        }
1382
1383        ret = http_request_reauth(url, result, HTTP_REQUEST_FILE, options);
1384        fclose(result);
1385
1386        if (ret == HTTP_OK && finalize_object_file(tmpfile.buf, filename))
1387                ret = HTTP_ERROR;
1388cleanup:
1389        strbuf_release(&tmpfile);
1390        return ret;
1391}
1392
1393int http_fetch_ref(const char *base, struct ref *ref)
1394{
1395        struct http_get_options options = {0};
1396        char *url;
1397        struct strbuf buffer = STRBUF_INIT;
1398        int ret = -1;
1399
1400        options.no_cache = 1;
1401
1402        url = quote_ref_url(base, ref->name);
1403        if (http_get_strbuf(url, &buffer, &options) == HTTP_OK) {
1404                strbuf_rtrim(&buffer);
1405                if (buffer.len == 40)
1406                        ret = get_sha1_hex(buffer.buf, ref->old_sha1);
1407                else if (starts_with(buffer.buf, "ref: ")) {
1408                        ref->symref = xstrdup(buffer.buf + 5);
1409                        ret = 0;
1410                }
1411        }
1412
1413        strbuf_release(&buffer);
1414        free(url);
1415        return ret;
1416}
1417
1418/* Helpers for fetching packs */
1419static char *fetch_pack_index(unsigned char *sha1, const char *base_url)
1420{
1421        char *url, *tmp;
1422        struct strbuf buf = STRBUF_INIT;
1423
1424        if (http_is_verbose)
1425                fprintf(stderr, "Getting index for pack %s\n", sha1_to_hex(sha1));
1426
1427        end_url_with_slash(&buf, base_url);
1428        strbuf_addf(&buf, "objects/pack/pack-%s.idx", sha1_to_hex(sha1));
1429        url = strbuf_detach(&buf, NULL);
1430
1431        strbuf_addf(&buf, "%s.temp", sha1_pack_index_name(sha1));
1432        tmp = strbuf_detach(&buf, NULL);
1433
1434        if (http_get_file(url, tmp, NULL) != HTTP_OK) {
1435                error("Unable to get pack index %s", url);
1436                free(tmp);
1437                tmp = NULL;
1438        }
1439
1440        free(url);
1441        return tmp;
1442}
1443
1444static int fetch_and_setup_pack_index(struct packed_git **packs_head,
1445        unsigned char *sha1, const char *base_url)
1446{
1447        struct packed_git *new_pack;
1448        char *tmp_idx = NULL;
1449        int ret;
1450
1451        if (has_pack_index(sha1)) {
1452                new_pack = parse_pack_index(sha1, sha1_pack_index_name(sha1));
1453                if (!new_pack)
1454                        return -1; /* parse_pack_index() already issued error message */
1455                goto add_pack;
1456        }
1457
1458        tmp_idx = fetch_pack_index(sha1, base_url);
1459        if (!tmp_idx)
1460                return -1;
1461
1462        new_pack = parse_pack_index(sha1, tmp_idx);
1463        if (!new_pack) {
1464                unlink(tmp_idx);
1465                free(tmp_idx);
1466
1467                return -1; /* parse_pack_index() already issued error message */
1468        }
1469
1470        ret = verify_pack_index(new_pack);
1471        if (!ret) {
1472                close_pack_index(new_pack);
1473                ret = finalize_object_file(tmp_idx, sha1_pack_index_name(sha1));
1474        }
1475        free(tmp_idx);
1476        if (ret)
1477                return -1;
1478
1479add_pack:
1480        new_pack->next = *packs_head;
1481        *packs_head = new_pack;
1482        return 0;
1483}
1484
1485int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
1486{
1487        struct http_get_options options = {0};
1488        int ret = 0, i = 0;
1489        char *url, *data;
1490        struct strbuf buf = STRBUF_INIT;
1491        unsigned char sha1[20];
1492
1493        end_url_with_slash(&buf, base_url);
1494        strbuf_addstr(&buf, "objects/info/packs");
1495        url = strbuf_detach(&buf, NULL);
1496
1497        options.no_cache = 1;
1498        ret = http_get_strbuf(url, &buf, &options);
1499        if (ret != HTTP_OK)
1500                goto cleanup;
1501
1502        data = buf.buf;
1503        while (i < buf.len) {
1504                switch (data[i]) {
1505                case 'P':
1506                        i++;
1507                        if (i + 52 <= buf.len &&
1508                            starts_with(data + i, " pack-") &&
1509                            starts_with(data + i + 46, ".pack\n")) {
1510                                get_sha1_hex(data + i + 6, sha1);
1511                                fetch_and_setup_pack_index(packs_head, sha1,
1512                                                      base_url);
1513                                i += 51;
1514                                break;
1515                        }
1516                default:
1517                        while (i < buf.len && data[i] != '\n')
1518                                i++;
1519                }
1520                i++;
1521        }
1522
1523cleanup:
1524        free(url);
1525        return ret;
1526}
1527
1528void release_http_pack_request(struct http_pack_request *preq)
1529{
1530        if (preq->packfile != NULL) {
1531                fclose(preq->packfile);
1532                preq->packfile = NULL;
1533        }
1534        if (preq->range_header != NULL) {
1535                curl_slist_free_all(preq->range_header);
1536                preq->range_header = NULL;
1537        }
1538        preq->slot = NULL;
1539        free(preq->url);
1540        free(preq);
1541}
1542
1543int finish_http_pack_request(struct http_pack_request *preq)
1544{
1545        struct packed_git **lst;
1546        struct packed_git *p = preq->target;
1547        char *tmp_idx;
1548        struct child_process ip = CHILD_PROCESS_INIT;
1549        const char *ip_argv[8];
1550
1551        close_pack_index(p);
1552
1553        fclose(preq->packfile);
1554        preq->packfile = NULL;
1555
1556        lst = preq->lst;
1557        while (*lst != p)
1558                lst = &((*lst)->next);
1559        *lst = (*lst)->next;
1560
1561        tmp_idx = xstrdup(preq->tmpfile);
1562        strcpy(tmp_idx + strlen(tmp_idx) - strlen(".pack.temp"),
1563               ".idx.temp");
1564
1565        ip_argv[0] = "index-pack";
1566        ip_argv[1] = "-o";
1567        ip_argv[2] = tmp_idx;
1568        ip_argv[3] = preq->tmpfile;
1569        ip_argv[4] = NULL;
1570
1571        ip.argv = ip_argv;
1572        ip.git_cmd = 1;
1573        ip.no_stdin = 1;
1574        ip.no_stdout = 1;
1575
1576        if (run_command(&ip)) {
1577                unlink(preq->tmpfile);
1578                unlink(tmp_idx);
1579                free(tmp_idx);
1580                return -1;
1581        }
1582
1583        unlink(sha1_pack_index_name(p->sha1));
1584
1585        if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
1586         || finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
1587                free(tmp_idx);
1588                return -1;
1589        }
1590
1591        install_packed_git(p);
1592        free(tmp_idx);
1593        return 0;
1594}
1595
1596struct http_pack_request *new_http_pack_request(
1597        struct packed_git *target, const char *base_url)
1598{
1599        long prev_posn = 0;
1600        char range[RANGE_HEADER_SIZE];
1601        struct strbuf buf = STRBUF_INIT;
1602        struct http_pack_request *preq;
1603
1604        preq = xcalloc(1, sizeof(*preq));
1605        preq->target = target;
1606
1607        end_url_with_slash(&buf, base_url);
1608        strbuf_addf(&buf, "objects/pack/pack-%s.pack",
1609                sha1_to_hex(target->sha1));
1610        preq->url = strbuf_detach(&buf, NULL);
1611
1612        snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
1613                sha1_pack_name(target->sha1));
1614        preq->packfile = fopen(preq->tmpfile, "a");
1615        if (!preq->packfile) {
1616                error("Unable to open local file %s for pack",
1617                      preq->tmpfile);
1618                goto abort;
1619        }
1620
1621        preq->slot = get_active_slot();
1622        curl_easy_setopt(preq->slot->curl, CURLOPT_FILE, preq->packfile);
1623        curl_easy_setopt(preq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
1624        curl_easy_setopt(preq->slot->curl, CURLOPT_URL, preq->url);
1625        curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1626                no_pragma_header);
1627
1628        /*
1629         * If there is data present from a previous transfer attempt,
1630         * resume where it left off
1631         */
1632        prev_posn = ftell(preq->packfile);
1633        if (prev_posn>0) {
1634                if (http_is_verbose)
1635                        fprintf(stderr,
1636                                "Resuming fetch of pack %s at byte %ld\n",
1637                                sha1_to_hex(target->sha1), prev_posn);
1638                sprintf(range, "Range: bytes=%ld-", prev_posn);
1639                preq->range_header = curl_slist_append(NULL, range);
1640                curl_easy_setopt(preq->slot->curl, CURLOPT_HTTPHEADER,
1641                        preq->range_header);
1642        }
1643
1644        return preq;
1645
1646abort:
1647        free(preq->url);
1648        free(preq);
1649        return NULL;
1650}
1651
1652/* Helpers for fetching objects (loose) */
1653static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
1654                               void *data)
1655{
1656        unsigned char expn[4096];
1657        size_t size = eltsize * nmemb;
1658        int posn = 0;
1659        struct http_object_request *freq =
1660                (struct http_object_request *)data;
1661        do {
1662                ssize_t retval = xwrite(freq->localfile,
1663                                        (char *) ptr + posn, size - posn);
1664                if (retval < 0)
1665                        return posn;
1666                posn += retval;
1667        } while (posn < size);
1668
1669        freq->stream.avail_in = size;
1670        freq->stream.next_in = (void *)ptr;
1671        do {
1672                freq->stream.next_out = expn;
1673                freq->stream.avail_out = sizeof(expn);
1674                freq->zret = git_inflate(&freq->stream, Z_SYNC_FLUSH);
1675                git_SHA1_Update(&freq->c, expn,
1676                                sizeof(expn) - freq->stream.avail_out);
1677        } while (freq->stream.avail_in && freq->zret == Z_OK);
1678        return size;
1679}
1680
1681struct http_object_request *new_http_object_request(const char *base_url,
1682        unsigned char *sha1)
1683{
1684        char *hex = sha1_to_hex(sha1);
1685        const char *filename;
1686        char prevfile[PATH_MAX];
1687        int prevlocal;
1688        char prev_buf[PREV_BUF_SIZE];
1689        ssize_t prev_read = 0;
1690        long prev_posn = 0;
1691        char range[RANGE_HEADER_SIZE];
1692        struct curl_slist *range_header = NULL;
1693        struct http_object_request *freq;
1694
1695        freq = xcalloc(1, sizeof(*freq));
1696        hashcpy(freq->sha1, sha1);
1697        freq->localfile = -1;
1698
1699        filename = sha1_file_name(sha1);
1700        snprintf(freq->tmpfile, sizeof(freq->tmpfile),
1701                 "%s.temp", filename);
1702
1703        snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
1704        unlink_or_warn(prevfile);
1705        rename(freq->tmpfile, prevfile);
1706        unlink_or_warn(freq->tmpfile);
1707
1708        if (freq->localfile != -1)
1709                error("fd leakage in start: %d", freq->localfile);
1710        freq->localfile = open(freq->tmpfile,
1711                               O_WRONLY | O_CREAT | O_EXCL, 0666);
1712        /*
1713         * This could have failed due to the "lazy directory creation";
1714         * try to mkdir the last path component.
1715         */
1716        if (freq->localfile < 0 && errno == ENOENT) {
1717                char *dir = strrchr(freq->tmpfile, '/');
1718                if (dir) {
1719                        *dir = 0;
1720                        mkdir(freq->tmpfile, 0777);
1721                        *dir = '/';
1722                }
1723                freq->localfile = open(freq->tmpfile,
1724                                       O_WRONLY | O_CREAT | O_EXCL, 0666);
1725        }
1726
1727        if (freq->localfile < 0) {
1728                error("Couldn't create temporary file %s: %s",
1729                      freq->tmpfile, strerror(errno));
1730                goto abort;
1731        }
1732
1733        git_inflate_init(&freq->stream);
1734
1735        git_SHA1_Init(&freq->c);
1736
1737        freq->url = get_remote_object_url(base_url, hex, 0);
1738
1739        /*
1740         * If a previous temp file is present, process what was already
1741         * fetched.
1742         */
1743        prevlocal = open(prevfile, O_RDONLY);
1744        if (prevlocal != -1) {
1745                do {
1746                        prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
1747                        if (prev_read>0) {
1748                                if (fwrite_sha1_file(prev_buf,
1749                                                     1,
1750                                                     prev_read,
1751                                                     freq) == prev_read) {
1752                                        prev_posn += prev_read;
1753                                } else {
1754                                        prev_read = -1;
1755                                }
1756                        }
1757                } while (prev_read > 0);
1758                close(prevlocal);
1759        }
1760        unlink_or_warn(prevfile);
1761
1762        /*
1763         * Reset inflate/SHA1 if there was an error reading the previous temp
1764         * file; also rewind to the beginning of the local file.
1765         */
1766        if (prev_read == -1) {
1767                memset(&freq->stream, 0, sizeof(freq->stream));
1768                git_inflate_init(&freq->stream);
1769                git_SHA1_Init(&freq->c);
1770                if (prev_posn>0) {
1771                        prev_posn = 0;
1772                        lseek(freq->localfile, 0, SEEK_SET);
1773                        if (ftruncate(freq->localfile, 0) < 0) {
1774                                error("Couldn't truncate temporary file %s: %s",
1775                                          freq->tmpfile, strerror(errno));
1776                                goto abort;
1777                        }
1778                }
1779        }
1780
1781        freq->slot = get_active_slot();
1782
1783        curl_easy_setopt(freq->slot->curl, CURLOPT_FILE, freq);
1784        curl_easy_setopt(freq->slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
1785        curl_easy_setopt(freq->slot->curl, CURLOPT_ERRORBUFFER, freq->errorstr);
1786        curl_easy_setopt(freq->slot->curl, CURLOPT_URL, freq->url);
1787        curl_easy_setopt(freq->slot->curl, CURLOPT_HTTPHEADER, no_pragma_header);
1788
1789        /*
1790         * If we have successfully processed data from a previous fetch
1791         * attempt, only fetch the data we don't already have.
1792         */
1793        if (prev_posn>0) {
1794                if (http_is_verbose)
1795                        fprintf(stderr,
1796                                "Resuming fetch of object %s at byte %ld\n",
1797                                hex, prev_posn);
1798                sprintf(range, "Range: bytes=%ld-", prev_posn);
1799                range_header = curl_slist_append(range_header, range);
1800                curl_easy_setopt(freq->slot->curl,
1801                                 CURLOPT_HTTPHEADER, range_header);
1802        }
1803
1804        return freq;
1805
1806abort:
1807        free(freq->url);
1808        free(freq);
1809        return NULL;
1810}
1811
1812void process_http_object_request(struct http_object_request *freq)
1813{
1814        if (freq->slot == NULL)
1815                return;
1816        freq->curl_result = freq->slot->curl_result;
1817        freq->http_code = freq->slot->http_code;
1818        freq->slot = NULL;
1819}
1820
1821int finish_http_object_request(struct http_object_request *freq)
1822{
1823        struct stat st;
1824
1825        close(freq->localfile);
1826        freq->localfile = -1;
1827
1828        process_http_object_request(freq);
1829
1830        if (freq->http_code == 416) {
1831                warning("requested range invalid; we may already have all the data.");
1832        } else if (freq->curl_result != CURLE_OK) {
1833                if (stat(freq->tmpfile, &st) == 0)
1834                        if (st.st_size == 0)
1835                                unlink_or_warn(freq->tmpfile);
1836                return -1;
1837        }
1838
1839        git_inflate_end(&freq->stream);
1840        git_SHA1_Final(freq->real_sha1, &freq->c);
1841        if (freq->zret != Z_STREAM_END) {
1842                unlink_or_warn(freq->tmpfile);
1843                return -1;
1844        }
1845        if (hashcmp(freq->sha1, freq->real_sha1)) {
1846                unlink_or_warn(freq->tmpfile);
1847                return -1;
1848        }
1849        freq->rename =
1850                finalize_object_file(freq->tmpfile, sha1_file_name(freq->sha1));
1851
1852        return freq->rename;
1853}
1854
1855void abort_http_object_request(struct http_object_request *freq)
1856{
1857        unlink_or_warn(freq->tmpfile);
1858
1859        release_http_object_request(freq);
1860}
1861
1862void release_http_object_request(struct http_object_request *freq)
1863{
1864        if (freq->localfile != -1) {
1865                close(freq->localfile);
1866                freq->localfile = -1;
1867        }
1868        if (freq->url != NULL) {
1869                free(freq->url);
1870                freq->url = NULL;
1871        }
1872        if (freq->slot != NULL) {
1873                freq->slot->callback_func = NULL;
1874                freq->slot->callback_data = NULL;
1875                release_active_slot(freq->slot);
1876                freq->slot = NULL;
1877        }
1878}