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