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