ad874b98cb5c76ef81a99607dc3630baf7a7f62a
   1#include "cache.h"
   2#include "commit.h"
   3#include "pack.h"
   4#include "walker.h"
   5#include "http.h"
   6
   7#define PREV_BUF_SIZE 4096
   8#define RANGE_HEADER_SIZE 30
   9
  10struct alt_base
  11{
  12        char *base;
  13        int got_indices;
  14        struct packed_git *packs;
  15        struct alt_base *next;
  16};
  17
  18enum object_request_state {
  19        WAITING,
  20        ABORTED,
  21        ACTIVE,
  22        COMPLETE,
  23};
  24
  25struct object_request
  26{
  27        struct walker *walker;
  28        unsigned char sha1[20];
  29        struct alt_base *repo;
  30        char *url;
  31        char filename[PATH_MAX];
  32        char tmpfile[PATH_MAX];
  33        int local;
  34        enum object_request_state state;
  35        CURLcode curl_result;
  36        char errorstr[CURL_ERROR_SIZE];
  37        long http_code;
  38        unsigned char real_sha1[20];
  39        SHA_CTX c;
  40        z_stream stream;
  41        int zret;
  42        int rename;
  43        struct active_request_slot *slot;
  44        struct object_request *next;
  45};
  46
  47struct alternates_request {
  48        struct walker *walker;
  49        const char *base;
  50        char *url;
  51        struct buffer *buffer;
  52        struct active_request_slot *slot;
  53        int http_specific;
  54};
  55
  56struct walker_data {
  57        const char *url;
  58        int got_alternates;
  59        struct alt_base *alt;
  60        struct curl_slist *no_pragma_header;
  61};
  62
  63static struct object_request *object_queue_head;
  64
  65static size_t fwrite_sha1_file(void *ptr, size_t eltsize, size_t nmemb,
  66                               void *data)
  67{
  68        unsigned char expn[4096];
  69        size_t size = eltsize * nmemb;
  70        int posn = 0;
  71        struct object_request *obj_req = (struct object_request *)data;
  72        do {
  73                ssize_t retval = xwrite(obj_req->local,
  74                                       (char *) ptr + posn, size - posn);
  75                if (retval < 0)
  76                        return posn;
  77                posn += retval;
  78        } while (posn < size);
  79
  80        obj_req->stream.avail_in = size;
  81        obj_req->stream.next_in = ptr;
  82        do {
  83                obj_req->stream.next_out = expn;
  84                obj_req->stream.avail_out = sizeof(expn);
  85                obj_req->zret = inflate(&obj_req->stream, Z_SYNC_FLUSH);
  86                SHA1_Update(&obj_req->c, expn,
  87                            sizeof(expn) - obj_req->stream.avail_out);
  88        } while (obj_req->stream.avail_in && obj_req->zret == Z_OK);
  89        data_received++;
  90        return size;
  91}
  92
  93static void fetch_alternates(struct walker *walker, const char *base);
  94
  95static void process_object_response(void *callback_data);
  96
  97static void start_object_request(struct walker *walker,
  98                                 struct object_request *obj_req)
  99{
 100        char *hex = sha1_to_hex(obj_req->sha1);
 101        char prevfile[PATH_MAX];
 102        char *url;
 103        char *posn;
 104        int prevlocal;
 105        unsigned char prev_buf[PREV_BUF_SIZE];
 106        ssize_t prev_read = 0;
 107        long prev_posn = 0;
 108        char range[RANGE_HEADER_SIZE];
 109        struct curl_slist *range_header = NULL;
 110        struct active_request_slot *slot;
 111        struct walker_data *data = walker->data;
 112
 113        snprintf(prevfile, sizeof(prevfile), "%s.prev", obj_req->filename);
 114        unlink(prevfile);
 115        rename(obj_req->tmpfile, prevfile);
 116        unlink(obj_req->tmpfile);
 117
 118        if (obj_req->local != -1)
 119                error("fd leakage in start: %d", obj_req->local);
 120        obj_req->local = open(obj_req->tmpfile,
 121                              O_WRONLY | O_CREAT | O_EXCL, 0666);
 122        /* This could have failed due to the "lazy directory creation";
 123         * try to mkdir the last path component.
 124         */
 125        if (obj_req->local < 0 && errno == ENOENT) {
 126                char *dir = strrchr(obj_req->tmpfile, '/');
 127                if (dir) {
 128                        *dir = 0;
 129                        mkdir(obj_req->tmpfile, 0777);
 130                        *dir = '/';
 131                }
 132                obj_req->local = open(obj_req->tmpfile,
 133                                      O_WRONLY | O_CREAT | O_EXCL, 0666);
 134        }
 135
 136        if (obj_req->local < 0) {
 137                obj_req->state = ABORTED;
 138                error("Couldn't create temporary file %s for %s: %s",
 139                      obj_req->tmpfile, obj_req->filename, strerror(errno));
 140                return;
 141        }
 142
 143        memset(&obj_req->stream, 0, sizeof(obj_req->stream));
 144
 145        inflateInit(&obj_req->stream);
 146
 147        SHA1_Init(&obj_req->c);
 148
 149        url = xmalloc(strlen(obj_req->repo->base) + 51);
 150        obj_req->url = xmalloc(strlen(obj_req->repo->base) + 51);
 151        strcpy(url, obj_req->repo->base);
 152        posn = url + strlen(obj_req->repo->base);
 153        strcpy(posn, "/objects/");
 154        posn += 9;
 155        memcpy(posn, hex, 2);
 156        posn += 2;
 157        *(posn++) = '/';
 158        strcpy(posn, hex + 2);
 159        strcpy(obj_req->url, url);
 160
 161        /* If a previous temp file is present, process what was already
 162           fetched. */
 163        prevlocal = open(prevfile, O_RDONLY);
 164        if (prevlocal != -1) {
 165                do {
 166                        prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
 167                        if (prev_read>0) {
 168                                if (fwrite_sha1_file(prev_buf,
 169                                                     1,
 170                                                     prev_read,
 171                                                     obj_req) == prev_read) {
 172                                        prev_posn += prev_read;
 173                                } else {
 174                                        prev_read = -1;
 175                                }
 176                        }
 177                } while (prev_read > 0);
 178                close(prevlocal);
 179        }
 180        unlink(prevfile);
 181
 182        /* Reset inflate/SHA1 if there was an error reading the previous temp
 183           file; also rewind to the beginning of the local file. */
 184        if (prev_read == -1) {
 185                memset(&obj_req->stream, 0, sizeof(obj_req->stream));
 186                inflateInit(&obj_req->stream);
 187                SHA1_Init(&obj_req->c);
 188                if (prev_posn>0) {
 189                        prev_posn = 0;
 190                        lseek(obj_req->local, 0, SEEK_SET);
 191                        ftruncate(obj_req->local, 0);
 192                }
 193        }
 194
 195        slot = get_active_slot();
 196        slot->callback_func = process_object_response;
 197        slot->callback_data = obj_req;
 198        obj_req->slot = slot;
 199
 200        curl_easy_setopt(slot->curl, CURLOPT_FILE, obj_req);
 201        curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
 202        curl_easy_setopt(slot->curl, CURLOPT_ERRORBUFFER, obj_req->errorstr);
 203        curl_easy_setopt(slot->curl, CURLOPT_URL, url);
 204        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, data->no_pragma_header);
 205
 206        /* If we have successfully processed data from a previous fetch
 207           attempt, only fetch the data we don't already have. */
 208        if (prev_posn>0) {
 209                if (walker->get_verbosely)
 210                        fprintf(stderr,
 211                                "Resuming fetch of object %s at byte %ld\n",
 212                                hex, prev_posn);
 213                sprintf(range, "Range: bytes=%ld-", prev_posn);
 214                range_header = curl_slist_append(range_header, range);
 215                curl_easy_setopt(slot->curl,
 216                                 CURLOPT_HTTPHEADER, range_header);
 217        }
 218
 219        /* Try to get the request started, abort the request on error */
 220        obj_req->state = ACTIVE;
 221        if (!start_active_slot(slot)) {
 222                obj_req->state = ABORTED;
 223                obj_req->slot = NULL;
 224                close(obj_req->local); obj_req->local = -1;
 225                free(obj_req->url);
 226                return;
 227        }
 228}
 229
 230static void finish_object_request(struct object_request *obj_req)
 231{
 232        struct stat st;
 233
 234        fchmod(obj_req->local, 0444);
 235        close(obj_req->local); obj_req->local = -1;
 236
 237        if (obj_req->http_code == 416) {
 238                fprintf(stderr, "Warning: requested range invalid; we may already have all the data.\n");
 239        } else if (obj_req->curl_result != CURLE_OK) {
 240                if (stat(obj_req->tmpfile, &st) == 0)
 241                        if (st.st_size == 0)
 242                                unlink(obj_req->tmpfile);
 243                return;
 244        }
 245
 246        inflateEnd(&obj_req->stream);
 247        SHA1_Final(obj_req->real_sha1, &obj_req->c);
 248        if (obj_req->zret != Z_STREAM_END) {
 249                unlink(obj_req->tmpfile);
 250                return;
 251        }
 252        if (hashcmp(obj_req->sha1, obj_req->real_sha1)) {
 253                unlink(obj_req->tmpfile);
 254                return;
 255        }
 256        obj_req->rename =
 257                move_temp_to_file(obj_req->tmpfile, obj_req->filename);
 258
 259        if (obj_req->rename == 0)
 260                walker_say(obj_req->walker, "got %s\n", sha1_to_hex(obj_req->sha1));
 261}
 262
 263static void process_object_response(void *callback_data)
 264{
 265        struct object_request *obj_req =
 266                (struct object_request *)callback_data;
 267        struct walker *walker = obj_req->walker;
 268        struct walker_data *data = walker->data;
 269        struct alt_base *alt = data->alt;
 270
 271        obj_req->curl_result = obj_req->slot->curl_result;
 272        obj_req->http_code = obj_req->slot->http_code;
 273        obj_req->slot = NULL;
 274        obj_req->state = COMPLETE;
 275
 276        /* Use alternates if necessary */
 277        if (missing_target(obj_req)) {
 278                fetch_alternates(walker, alt->base);
 279                if (obj_req->repo->next != NULL) {
 280                        obj_req->repo =
 281                                obj_req->repo->next;
 282                        close(obj_req->local);
 283                        obj_req->local = -1;
 284                        start_object_request(walker, obj_req);
 285                        return;
 286                }
 287        }
 288
 289        finish_object_request(obj_req);
 290}
 291
 292static void release_object_request(struct object_request *obj_req)
 293{
 294        struct object_request *entry = object_queue_head;
 295
 296        if (obj_req->local != -1)
 297                error("fd leakage in release: %d", obj_req->local);
 298        if (obj_req == object_queue_head) {
 299                object_queue_head = obj_req->next;
 300        } else {
 301                while (entry->next != NULL && entry->next != obj_req)
 302                        entry = entry->next;
 303                if (entry->next == obj_req)
 304                        entry->next = entry->next->next;
 305        }
 306
 307        free(obj_req->url);
 308        free(obj_req);
 309}
 310
 311#ifdef USE_CURL_MULTI
 312static int fill_active_slot(struct walker *walker)
 313{
 314        struct object_request *obj_req;
 315
 316        for (obj_req = object_queue_head; obj_req; obj_req = obj_req->next) {
 317                if (obj_req->state == WAITING) {
 318                        if (has_sha1_file(obj_req->sha1))
 319                                obj_req->state = COMPLETE;
 320                        else {
 321                                start_object_request(walker, obj_req);
 322                                return 1;
 323                        }
 324                }
 325        }
 326        return 0;
 327}
 328#endif
 329
 330static void prefetch(struct walker *walker, unsigned char *sha1)
 331{
 332        struct object_request *newreq;
 333        struct object_request *tail;
 334        struct walker_data *data = walker->data;
 335        char *filename = sha1_file_name(sha1);
 336
 337        newreq = xmalloc(sizeof(*newreq));
 338        newreq->walker = walker;
 339        hashcpy(newreq->sha1, sha1);
 340        newreq->repo = data->alt;
 341        newreq->url = NULL;
 342        newreq->local = -1;
 343        newreq->state = WAITING;
 344        snprintf(newreq->filename, sizeof(newreq->filename), "%s", filename);
 345        snprintf(newreq->tmpfile, sizeof(newreq->tmpfile),
 346                 "%s.temp", filename);
 347        newreq->slot = NULL;
 348        newreq->next = NULL;
 349
 350        if (object_queue_head == NULL) {
 351                object_queue_head = newreq;
 352        } else {
 353                tail = object_queue_head;
 354                while (tail->next != NULL) {
 355                        tail = tail->next;
 356                }
 357                tail->next = newreq;
 358        }
 359
 360#ifdef USE_CURL_MULTI
 361        fill_active_slots();
 362        step_active_slots();
 363#endif
 364}
 365
 366static int fetch_index(struct walker *walker, struct alt_base *repo, unsigned char *sha1)
 367{
 368        char *hex = sha1_to_hex(sha1);
 369        char *filename;
 370        char *url;
 371        char tmpfile[PATH_MAX];
 372        long prev_posn = 0;
 373        char range[RANGE_HEADER_SIZE];
 374        struct curl_slist *range_header = NULL;
 375        struct walker_data *data = walker->data;
 376
 377        FILE *indexfile;
 378        struct active_request_slot *slot;
 379        struct slot_results results;
 380
 381        if (has_pack_index(sha1))
 382                return 0;
 383
 384        if (walker->get_verbosely)
 385                fprintf(stderr, "Getting index for pack %s\n", hex);
 386
 387        url = xmalloc(strlen(repo->base) + 64);
 388        sprintf(url, "%s/objects/pack/pack-%s.idx", repo->base, hex);
 389
 390        filename = sha1_pack_index_name(sha1);
 391        snprintf(tmpfile, sizeof(tmpfile), "%s.temp", filename);
 392        indexfile = fopen(tmpfile, "a");
 393        if (!indexfile)
 394                return error("Unable to open local file %s for pack index",
 395                             tmpfile);
 396
 397        slot = get_active_slot();
 398        slot->results = &results;
 399        curl_easy_setopt(slot->curl, CURLOPT_FILE, indexfile);
 400        curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
 401        curl_easy_setopt(slot->curl, CURLOPT_URL, url);
 402        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, data->no_pragma_header);
 403        slot->local = indexfile;
 404
 405        /* If there is data present from a previous transfer attempt,
 406           resume where it left off */
 407        prev_posn = ftell(indexfile);
 408        if (prev_posn>0) {
 409                if (walker->get_verbosely)
 410                        fprintf(stderr,
 411                                "Resuming fetch of index for pack %s at byte %ld\n",
 412                                hex, prev_posn);
 413                sprintf(range, "Range: bytes=%ld-", prev_posn);
 414                range_header = curl_slist_append(range_header, range);
 415                curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, range_header);
 416        }
 417
 418        if (start_active_slot(slot)) {
 419                run_active_slot(slot);
 420                if (results.curl_result != CURLE_OK) {
 421                        fclose(indexfile);
 422                        return error("Unable to get pack index %s\n%s", url,
 423                                     curl_errorstr);
 424                }
 425        } else {
 426                fclose(indexfile);
 427                return error("Unable to start request");
 428        }
 429
 430        fclose(indexfile);
 431
 432        return move_temp_to_file(tmpfile, filename);
 433}
 434
 435static int setup_index(struct walker *walker, struct alt_base *repo, unsigned char *sha1)
 436{
 437        struct packed_git *new_pack;
 438        if (has_pack_file(sha1))
 439                return 0; /* don't list this as something we can get */
 440
 441        if (fetch_index(walker, repo, sha1))
 442                return -1;
 443
 444        new_pack = parse_pack_index(sha1);
 445        new_pack->next = repo->packs;
 446        repo->packs = new_pack;
 447        return 0;
 448}
 449
 450static void process_alternates_response(void *callback_data)
 451{
 452        struct alternates_request *alt_req =
 453                (struct alternates_request *)callback_data;
 454        struct walker *walker = alt_req->walker;
 455        struct walker_data *cdata = walker->data;
 456        struct active_request_slot *slot = alt_req->slot;
 457        struct alt_base *tail = cdata->alt;
 458        const char *base = alt_req->base;
 459        static const char null_byte = '\0';
 460        char *data;
 461        int i = 0;
 462
 463        if (alt_req->http_specific) {
 464                if (slot->curl_result != CURLE_OK ||
 465                    !alt_req->buffer->posn) {
 466
 467                        /* Try reusing the slot to get non-http alternates */
 468                        alt_req->http_specific = 0;
 469                        sprintf(alt_req->url, "%s/objects/info/alternates",
 470                                base);
 471                        curl_easy_setopt(slot->curl, CURLOPT_URL,
 472                                         alt_req->url);
 473                        active_requests++;
 474                        slot->in_use = 1;
 475                        if (slot->finished != NULL)
 476                                (*slot->finished) = 0;
 477                        if (!start_active_slot(slot)) {
 478                                cdata->got_alternates = -1;
 479                                slot->in_use = 0;
 480                                if (slot->finished != NULL)
 481                                        (*slot->finished) = 1;
 482                        }
 483                        return;
 484                }
 485        } else if (slot->curl_result != CURLE_OK) {
 486                if (!missing_target(slot)) {
 487                        cdata->got_alternates = -1;
 488                        return;
 489                }
 490        }
 491
 492        fwrite_buffer(&null_byte, 1, 1, alt_req->buffer);
 493        alt_req->buffer->posn--;
 494        data = alt_req->buffer->buffer;
 495
 496        while (i < alt_req->buffer->posn) {
 497                int posn = i;
 498                while (posn < alt_req->buffer->posn && data[posn] != '\n')
 499                        posn++;
 500                if (data[posn] == '\n') {
 501                        int okay = 0;
 502                        int serverlen = 0;
 503                        struct alt_base *newalt;
 504                        char *target = NULL;
 505                        if (data[i] == '/') {
 506                                /* This counts
 507                                 * http://git.host/pub/scm/linux.git/
 508                                 * -----------here^
 509                                 * so memcpy(dst, base, serverlen) will
 510                                 * copy up to "...git.host".
 511                                 */
 512                                const char *colon_ss = strstr(base,"://");
 513                                if (colon_ss) {
 514                                        serverlen = (strchr(colon_ss + 3, '/')
 515                                                     - base);
 516                                        okay = 1;
 517                                }
 518                        } else if (!memcmp(data + i, "../", 3)) {
 519                                /* Relative URL; chop the corresponding
 520                                 * number of subpath from base (and ../
 521                                 * from data), and concatenate the result.
 522                                 *
 523                                 * The code first drops ../ from data, and
 524                                 * then drops one ../ from data and one path
 525                                 * from base.  IOW, one extra ../ is dropped
 526                                 * from data than path is dropped from base.
 527                                 *
 528                                 * This is not wrong.  The alternate in
 529                                 *     http://git.host/pub/scm/linux.git/
 530                                 * to borrow from
 531                                 *     http://git.host/pub/scm/linus.git/
 532                                 * is ../../linus.git/objects/.  You need
 533                                 * two ../../ to borrow from your direct
 534                                 * neighbour.
 535                                 */
 536                                i += 3;
 537                                serverlen = strlen(base);
 538                                while (i + 2 < posn &&
 539                                       !memcmp(data + i, "../", 3)) {
 540                                        do {
 541                                                serverlen--;
 542                                        } while (serverlen &&
 543                                                 base[serverlen - 1] != '/');
 544                                        i += 3;
 545                                }
 546                                /* If the server got removed, give up. */
 547                                okay = strchr(base, ':') - base + 3 <
 548                                        serverlen;
 549                        } else if (alt_req->http_specific) {
 550                                char *colon = strchr(data + i, ':');
 551                                char *slash = strchr(data + i, '/');
 552                                if (colon && slash && colon < data + posn &&
 553                                    slash < data + posn && colon < slash) {
 554                                        okay = 1;
 555                                }
 556                        }
 557                        /* skip "objects\n" at end */
 558                        if (okay) {
 559                                target = xmalloc(serverlen + posn - i - 6);
 560                                memcpy(target, base, serverlen);
 561                                memcpy(target + serverlen, data + i,
 562                                       posn - i - 7);
 563                                target[serverlen + posn - i - 7] = 0;
 564                                if (walker->get_verbosely)
 565                                        fprintf(stderr,
 566                                                "Also look at %s\n", target);
 567                                newalt = xmalloc(sizeof(*newalt));
 568                                newalt->next = NULL;
 569                                newalt->base = target;
 570                                newalt->got_indices = 0;
 571                                newalt->packs = NULL;
 572
 573                                while (tail->next != NULL)
 574                                        tail = tail->next;
 575                                tail->next = newalt;
 576                        }
 577                }
 578                i = posn + 1;
 579        }
 580
 581        cdata->got_alternates = 1;
 582}
 583
 584static void fetch_alternates(struct walker *walker, const char *base)
 585{
 586        struct buffer buffer;
 587        char *url;
 588        char *data;
 589        struct active_request_slot *slot;
 590        struct alternates_request alt_req;
 591        struct walker_data *cdata = walker->data;
 592
 593        /* If another request has already started fetching alternates,
 594           wait for them to arrive and return to processing this request's
 595           curl message */
 596#ifdef USE_CURL_MULTI
 597        while (cdata->got_alternates == 0) {
 598                step_active_slots();
 599        }
 600#endif
 601
 602        /* Nothing to do if they've already been fetched */
 603        if (cdata->got_alternates == 1)
 604                return;
 605
 606        /* Start the fetch */
 607        cdata->got_alternates = 0;
 608
 609        data = xmalloc(4096);
 610        buffer.size = 4096;
 611        buffer.posn = 0;
 612        buffer.buffer = data;
 613
 614        if (walker->get_verbosely)
 615                fprintf(stderr, "Getting alternates list for %s\n", base);
 616
 617        url = xmalloc(strlen(base) + 31);
 618        sprintf(url, "%s/objects/info/http-alternates", base);
 619
 620        /* Use a callback to process the result, since another request
 621           may fail and need to have alternates loaded before continuing */
 622        slot = get_active_slot();
 623        slot->callback_func = process_alternates_response;
 624        alt_req.walker = walker;
 625        slot->callback_data = &alt_req;
 626
 627        curl_easy_setopt(slot->curl, CURLOPT_FILE, &buffer);
 628        curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
 629        curl_easy_setopt(slot->curl, CURLOPT_URL, url);
 630
 631        alt_req.base = base;
 632        alt_req.url = url;
 633        alt_req.buffer = &buffer;
 634        alt_req.http_specific = 1;
 635        alt_req.slot = slot;
 636
 637        if (start_active_slot(slot))
 638                run_active_slot(slot);
 639        else
 640                cdata->got_alternates = -1;
 641
 642        free(data);
 643        free(url);
 644}
 645
 646static int fetch_indices(struct walker *walker, struct alt_base *repo)
 647{
 648        unsigned char sha1[20];
 649        char *url;
 650        struct buffer buffer;
 651        char *data;
 652        int i = 0;
 653
 654        struct active_request_slot *slot;
 655        struct slot_results results;
 656
 657        if (repo->got_indices)
 658                return 0;
 659
 660        data = xmalloc(4096);
 661        buffer.size = 4096;
 662        buffer.posn = 0;
 663        buffer.buffer = data;
 664
 665        if (walker->get_verbosely)
 666                fprintf(stderr, "Getting pack list for %s\n", repo->base);
 667
 668        url = xmalloc(strlen(repo->base) + 21);
 669        sprintf(url, "%s/objects/info/packs", repo->base);
 670
 671        slot = get_active_slot();
 672        slot->results = &results;
 673        curl_easy_setopt(slot->curl, CURLOPT_FILE, &buffer);
 674        curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
 675        curl_easy_setopt(slot->curl, CURLOPT_URL, url);
 676        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, NULL);
 677        if (start_active_slot(slot)) {
 678                run_active_slot(slot);
 679                if (results.curl_result != CURLE_OK) {
 680                        if (missing_target(&results)) {
 681                                repo->got_indices = 1;
 682                                free(buffer.buffer);
 683                                return 0;
 684                        } else {
 685                                repo->got_indices = 0;
 686                                free(buffer.buffer);
 687                                return error("%s", curl_errorstr);
 688                        }
 689                }
 690        } else {
 691                repo->got_indices = 0;
 692                free(buffer.buffer);
 693                return error("Unable to start request");
 694        }
 695
 696        data = buffer.buffer;
 697        while (i < buffer.posn) {
 698                switch (data[i]) {
 699                case 'P':
 700                        i++;
 701                        if (i + 52 <= buffer.posn &&
 702                            !prefixcmp(data + i, " pack-") &&
 703                            !prefixcmp(data + i + 46, ".pack\n")) {
 704                                get_sha1_hex(data + i + 6, sha1);
 705                                setup_index(walker, repo, sha1);
 706                                i += 51;
 707                                break;
 708                        }
 709                default:
 710                        while (i < buffer.posn && data[i] != '\n')
 711                                i++;
 712                }
 713                i++;
 714        }
 715
 716        free(buffer.buffer);
 717        repo->got_indices = 1;
 718        return 0;
 719}
 720
 721static int fetch_pack(struct walker *walker, struct alt_base *repo, unsigned char *sha1)
 722{
 723        char *url;
 724        struct packed_git *target;
 725        struct packed_git **lst;
 726        FILE *packfile;
 727        char *filename;
 728        char tmpfile[PATH_MAX];
 729        int ret;
 730        long prev_posn = 0;
 731        char range[RANGE_HEADER_SIZE];
 732        struct curl_slist *range_header = NULL;
 733        struct walker_data *data = walker->data;
 734
 735        struct active_request_slot *slot;
 736        struct slot_results results;
 737
 738        if (fetch_indices(walker, repo))
 739                return -1;
 740        target = find_sha1_pack(sha1, repo->packs);
 741        if (!target)
 742                return -1;
 743
 744        if (walker->get_verbosely) {
 745                fprintf(stderr, "Getting pack %s\n",
 746                        sha1_to_hex(target->sha1));
 747                fprintf(stderr, " which contains %s\n",
 748                        sha1_to_hex(sha1));
 749        }
 750
 751        url = xmalloc(strlen(repo->base) + 65);
 752        sprintf(url, "%s/objects/pack/pack-%s.pack",
 753                repo->base, sha1_to_hex(target->sha1));
 754
 755        filename = sha1_pack_name(target->sha1);
 756        snprintf(tmpfile, sizeof(tmpfile), "%s.temp", filename);
 757        packfile = fopen(tmpfile, "a");
 758        if (!packfile)
 759                return error("Unable to open local file %s for pack",
 760                             tmpfile);
 761
 762        slot = get_active_slot();
 763        slot->results = &results;
 764        curl_easy_setopt(slot->curl, CURLOPT_FILE, packfile);
 765        curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite);
 766        curl_easy_setopt(slot->curl, CURLOPT_URL, url);
 767        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, data->no_pragma_header);
 768        slot->local = packfile;
 769
 770        /* If there is data present from a previous transfer attempt,
 771           resume where it left off */
 772        prev_posn = ftell(packfile);
 773        if (prev_posn>0) {
 774                if (walker->get_verbosely)
 775                        fprintf(stderr,
 776                                "Resuming fetch of pack %s at byte %ld\n",
 777                                sha1_to_hex(target->sha1), prev_posn);
 778                sprintf(range, "Range: bytes=%ld-", prev_posn);
 779                range_header = curl_slist_append(range_header, range);
 780                curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, range_header);
 781        }
 782
 783        if (start_active_slot(slot)) {
 784                run_active_slot(slot);
 785                if (results.curl_result != CURLE_OK) {
 786                        fclose(packfile);
 787                        return error("Unable to get pack file %s\n%s", url,
 788                                     curl_errorstr);
 789                }
 790        } else {
 791                fclose(packfile);
 792                return error("Unable to start request");
 793        }
 794
 795        target->pack_size = ftell(packfile);
 796        fclose(packfile);
 797
 798        ret = move_temp_to_file(tmpfile, filename);
 799        if (ret)
 800                return ret;
 801
 802        lst = &repo->packs;
 803        while (*lst != target)
 804                lst = &((*lst)->next);
 805        *lst = (*lst)->next;
 806
 807        if (verify_pack(target, 0))
 808                return -1;
 809        install_packed_git(target);
 810
 811        return 0;
 812}
 813
 814static void abort_object_request(struct object_request *obj_req)
 815{
 816        if (obj_req->local >= 0) {
 817                close(obj_req->local);
 818                obj_req->local = -1;
 819        }
 820        unlink(obj_req->tmpfile);
 821        if (obj_req->slot) {
 822                release_active_slot(obj_req->slot);
 823                obj_req->slot = NULL;
 824        }
 825        release_object_request(obj_req);
 826}
 827
 828static int fetch_object(struct walker *walker, struct alt_base *repo, unsigned char *sha1)
 829{
 830        char *hex = sha1_to_hex(sha1);
 831        int ret = 0;
 832        struct object_request *obj_req = object_queue_head;
 833
 834        while (obj_req != NULL && hashcmp(obj_req->sha1, sha1))
 835                obj_req = obj_req->next;
 836        if (obj_req == NULL)
 837                return error("Couldn't find request for %s in the queue", hex);
 838
 839        if (has_sha1_file(obj_req->sha1)) {
 840                abort_object_request(obj_req);
 841                return 0;
 842        }
 843
 844#ifdef USE_CURL_MULTI
 845        while (obj_req->state == WAITING) {
 846                step_active_slots();
 847        }
 848#else
 849        start_object_request(walker, obj_req);
 850#endif
 851
 852        while (obj_req->state == ACTIVE) {
 853                run_active_slot(obj_req->slot);
 854        }
 855        if (obj_req->local != -1) {
 856                close(obj_req->local); obj_req->local = -1;
 857        }
 858
 859        if (obj_req->state == ABORTED) {
 860                ret = error("Request for %s aborted", hex);
 861        } else if (obj_req->curl_result != CURLE_OK &&
 862                   obj_req->http_code != 416) {
 863                if (missing_target(obj_req))
 864                        ret = -1; /* Be silent, it is probably in a pack. */
 865                else
 866                        ret = error("%s (curl_result = %d, http_code = %ld, sha1 = %s)",
 867                                    obj_req->errorstr, obj_req->curl_result,
 868                                    obj_req->http_code, hex);
 869        } else if (obj_req->zret != Z_STREAM_END) {
 870                walker->corrupt_object_found++;
 871                ret = error("File %s (%s) corrupt", hex, obj_req->url);
 872        } else if (hashcmp(obj_req->sha1, obj_req->real_sha1)) {
 873                ret = error("File %s has bad hash", hex);
 874        } else if (obj_req->rename < 0) {
 875                ret = error("unable to write sha1 filename %s",
 876                            obj_req->filename);
 877        }
 878
 879        release_object_request(obj_req);
 880        return ret;
 881}
 882
 883static int fetch(struct walker *walker, unsigned char *sha1)
 884{
 885        struct walker_data *data = walker->data;
 886        struct alt_base *altbase = data->alt;
 887
 888        if (!fetch_object(walker, altbase, sha1))
 889                return 0;
 890        while (altbase) {
 891                if (!fetch_pack(walker, altbase, sha1))
 892                        return 0;
 893                fetch_alternates(walker, data->alt->base);
 894                altbase = altbase->next;
 895        }
 896        return error("Unable to find %s under %s", sha1_to_hex(sha1),
 897                     data->alt->base);
 898}
 899
 900static inline int needs_quote(int ch)
 901{
 902        if (((ch >= 'A') && (ch <= 'Z'))
 903                        || ((ch >= 'a') && (ch <= 'z'))
 904                        || ((ch >= '0') && (ch <= '9'))
 905                        || (ch == '/')
 906                        || (ch == '-')
 907                        || (ch == '.'))
 908                return 0;
 909        return 1;
 910}
 911
 912static inline int hex(int v)
 913{
 914        if (v < 10) return '0' + v;
 915        else return 'A' + v - 10;
 916}
 917
 918static char *quote_ref_url(const char *base, const char *ref)
 919{
 920        const char *cp;
 921        char *dp, *qref;
 922        int len, baselen, ch;
 923
 924        baselen = strlen(base);
 925        len = baselen + 7; /* "/refs/" + NUL */
 926        for (cp = ref; (ch = *cp) != 0; cp++, len++)
 927                if (needs_quote(ch))
 928                        len += 2; /* extra two hex plus replacement % */
 929        qref = xmalloc(len);
 930        memcpy(qref, base, baselen);
 931        memcpy(qref + baselen, "/refs/", 6);
 932        for (cp = ref, dp = qref + baselen + 6; (ch = *cp) != 0; cp++) {
 933                if (needs_quote(ch)) {
 934                        *dp++ = '%';
 935                        *dp++ = hex((ch >> 4) & 0xF);
 936                        *dp++ = hex(ch & 0xF);
 937                }
 938                else
 939                        *dp++ = ch;
 940        }
 941        *dp = 0;
 942
 943        return qref;
 944}
 945
 946static int fetch_ref(struct walker *walker, char *ref, unsigned char *sha1)
 947{
 948        char *url;
 949        char hex[42];
 950        struct buffer buffer;
 951        struct walker_data *data = walker->data;
 952        const char *base = data->alt->base;
 953        struct active_request_slot *slot;
 954        struct slot_results results;
 955        buffer.size = 41;
 956        buffer.posn = 0;
 957        buffer.buffer = hex;
 958        hex[41] = '\0';
 959
 960        url = quote_ref_url(base, ref);
 961        slot = get_active_slot();
 962        slot->results = &results;
 963        curl_easy_setopt(slot->curl, CURLOPT_FILE, &buffer);
 964        curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
 965        curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, NULL);
 966        curl_easy_setopt(slot->curl, CURLOPT_URL, url);
 967        if (start_active_slot(slot)) {
 968                run_active_slot(slot);
 969                if (results.curl_result != CURLE_OK)
 970                        return error("Couldn't get %s for %s\n%s",
 971                                     url, ref, curl_errorstr);
 972        } else {
 973                return error("Unable to start request");
 974        }
 975
 976        if (buffer.posn != 41)
 977                return 1;
 978        hex[40] = '\0';
 979        return get_sha1_hex(hex, sha1);
 980}
 981
 982static void cleanup(struct walker *walker)
 983{
 984        struct walker_data *data = walker->data;
 985        http_cleanup();
 986
 987        curl_slist_free_all(data->no_pragma_header);
 988}
 989
 990struct walker *get_http_walker(const char *url)
 991{
 992        char *s;
 993        struct walker_data *data = xmalloc(sizeof(struct walker_data));
 994        struct walker *walker = xmalloc(sizeof(struct walker));
 995
 996        http_init();
 997
 998        data->no_pragma_header = curl_slist_append(NULL, "Pragma:");
 999
1000        data->alt = xmalloc(sizeof(*data->alt));
1001        data->alt->base = xmalloc(strlen(url) + 1);
1002        strcpy(data->alt->base, url);
1003        for (s = data->alt->base + strlen(data->alt->base) - 1; *s == '/'; --s)
1004                *s = 0;
1005
1006        data->alt->got_indices = 0;
1007        data->alt->packs = NULL;
1008        data->alt->next = NULL;
1009        data->got_alternates = -1;
1010
1011        walker->corrupt_object_found = 0;
1012        walker->fetch = fetch;
1013        walker->fetch_ref = fetch_ref;
1014        walker->prefetch = prefetch;
1015        walker->cleanup = cleanup;
1016        walker->data = data;
1017
1018#ifdef USE_CURL_MULTI
1019        add_fill_function(walker, (int (*)(void *)) fill_active_slot);
1020#endif
1021
1022        return walker;
1023}