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