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