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