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