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