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