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