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