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