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