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