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