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