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