Update partial HTTP transfers.
[git] / http-fetch.c
1 #include "cache.h"
2 #include "commit.h"
3 #include "pack.h"
4 #include "fetch.h"
5
6 #include <curl/curl.h>
7 #include <curl/easy.h>
8
9 #if LIBCURL_VERSION_NUM < 0x070704
10 #define curl_global_cleanup() do { /* nothing */ } while(0)
11 #endif
12 #if LIBCURL_VERSION_NUM < 0x070800
13 #define curl_global_init(a) do { /* nothing */ } while(0)
14 #endif
15
16 #define PREV_BUF_SIZE 4096
17 #define RANGE_HEADER_SIZE 30
18
19 static CURL *curl;
20 static struct curl_slist *no_pragma_header;
21 static struct curl_slist *no_range_header;
22 static char curl_errorstr[CURL_ERROR_SIZE];
23
24 static char *initial_base;
25
26 struct alt_base
27 {
28         char *base;
29         int got_indices;
30         struct packed_git *packs;
31         struct alt_base *next;
32 };
33
34 static struct alt_base *alt = NULL;
35
36 static SHA_CTX c;
37 static z_stream stream;
38
39 static int local;
40 static int zret;
41
42 static int curl_ssl_verify;
43 static char *ssl_cert;
44 static char *ssl_key;
45 static char *ssl_capath;
46 static char *ssl_cainfo;
47
48 struct buffer
49 {
50         size_t posn;
51         size_t size;
52         void *buffer;
53 };
54
55 static size_t fwrite_buffer(void *ptr, size_t eltsize, size_t nmemb,
56                             struct buffer *buffer)
57 {
58         size_t size = eltsize * nmemb;
59         if (size > buffer->size - buffer->posn)
60                 size = buffer->size - buffer->posn;
61         memcpy(buffer->buffer + buffer->posn, ptr, size);
62         buffer->posn += size;
63         return size;
64 }
65
66 static size_t fwrite_sha1_file(void *ptr, size_t eltsize, size_t nmemb,
67                                void *data)
68 {
69         unsigned char expn[4096];
70         size_t size = eltsize * nmemb;
71         int posn = 0;
72         do {
73                 ssize_t retval = write(local, ptr + posn, size - posn);
74                 if (retval < 0)
75                         return posn;
76                 posn += retval;
77         } while (posn < size);
78
79         stream.avail_in = size;
80         stream.next_in = ptr;
81         do {
82                 stream.next_out = expn;
83                 stream.avail_out = sizeof(expn);
84                 zret = inflate(&stream, Z_SYNC_FLUSH);
85                 SHA1_Update(&c, expn, sizeof(expn) - stream.avail_out);
86         } while (stream.avail_in && zret == Z_OK);
87         return size;
88 }
89
90 void prefetch(unsigned char *sha1)
91 {
92 }
93
94 int relink_or_rename(char *old, char *new) {
95         int ret;
96
97         ret = link(old, new);
98         if (ret < 0) {
99                 /* Same Coda hack as in write_sha1_file(sha1_file.c) */
100                 ret = errno;
101                 if (ret == EXDEV && !rename(old, new))
102                         return 0;
103         }
104         unlink(old);
105         if (ret) {
106                 if (ret != EEXIST)
107                         return ret;
108         }
109
110         return 0;
111 }
112
113 static int got_alternates = 0;
114
115 static int fetch_index(struct alt_base *repo, unsigned char *sha1)
116 {
117         char *filename;
118         char *url;
119         char tmpfile[PATH_MAX];
120         int ret;
121         long prev_posn = 0;
122         char range[RANGE_HEADER_SIZE];
123         struct curl_slist *range_header = NULL;
124         CURLcode curl_result;
125
126         FILE *indexfile;
127
128         if (has_pack_index(sha1))
129                 return 0;
130
131         if (get_verbosely)
132                 fprintf(stderr, "Getting index for pack %s\n",
133                         sha1_to_hex(sha1));
134         
135         url = xmalloc(strlen(repo->base) + 64);
136         sprintf(url, "%s/objects/pack/pack-%s.idx",
137                 repo->base, sha1_to_hex(sha1));
138         
139         filename = sha1_pack_index_name(sha1);
140         snprintf(tmpfile, sizeof(tmpfile), "%s.temp", filename);
141         indexfile = fopen(tmpfile, "a");
142         if (!indexfile)
143                 return error("Unable to open local file %s for pack index",
144                              filename);
145
146         curl_easy_setopt(curl, CURLOPT_FILE, indexfile);
147         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite);
148         curl_easy_setopt(curl, CURLOPT_URL, url);
149         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, no_pragma_header);
150         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_errorstr);
151         
152         /* If there is data present from a previous transfer attempt,
153            resume where it left off */
154         prev_posn = ftell(indexfile);
155         if (prev_posn>0) {
156                 if (get_verbosely)
157                         fprintf(stderr,
158                                 "Resuming fetch of index for pack %s at byte %ld\n",
159                                 sha1_to_hex(sha1), prev_posn);
160                 sprintf(range, "Range: bytes=%ld-", prev_posn);
161                 range_header = curl_slist_append(range_header, range);
162                 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, range_header);
163         }
164
165         /* Clear out the Range: header after performing the request, so
166            other curl requests don't inherit inappropriate header data */
167         curl_result = curl_easy_perform(curl);
168         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, no_range_header);
169         if (curl_result != 0) {
170                 fclose(indexfile);
171                 return error("Unable to get pack index %s\n%s", url,
172                              curl_errorstr);
173         }
174
175         fclose(indexfile);
176
177         ret = relink_or_rename(tmpfile, filename);
178         if (ret)
179                 return error("unable to write index filename %s: %s",
180                              filename, strerror(ret));
181
182         return 0;
183 }
184
185 static int setup_index(struct alt_base *repo, unsigned char *sha1)
186 {
187         struct packed_git *new_pack;
188         if (has_pack_file(sha1))
189                 return 0; // don't list this as something we can get
190
191         if (fetch_index(repo, sha1))
192                 return -1;
193
194         new_pack = parse_pack_index(sha1);
195         new_pack->next = repo->packs;
196         repo->packs = new_pack;
197         return 0;
198 }
199
200 static int fetch_alternates(char *base)
201 {
202         int ret = 0;
203         struct buffer buffer;
204         char *url;
205         char *data;
206         int i = 0;
207         int http_specific = 1;
208         if (got_alternates)
209                 return 0;
210         data = xmalloc(4096);
211         buffer.size = 4095;
212         buffer.posn = 0;
213         buffer.buffer = data;
214
215         if (get_verbosely)
216                 fprintf(stderr, "Getting alternates list\n");
217         
218         url = xmalloc(strlen(base) + 31);
219         sprintf(url, "%s/objects/info/http-alternates", base);
220
221         curl_easy_setopt(curl, CURLOPT_FILE, &buffer);
222         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
223         curl_easy_setopt(curl, CURLOPT_URL, url);
224
225         if (curl_easy_perform(curl) || !buffer.posn) {
226                 http_specific = 0;
227
228                 sprintf(url, "%s/objects/info/alternates", base);
229                 
230                 curl_easy_setopt(curl, CURLOPT_FILE, &buffer);
231                 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
232                 curl_easy_setopt(curl, CURLOPT_URL, url);
233                 
234                 if (curl_easy_perform(curl)) {
235                         return 0;
236                 }
237         }
238
239         data[buffer.posn] = '\0';
240
241         while (i < buffer.posn) {
242                 int posn = i;
243                 while (posn < buffer.posn && data[posn] != '\n')
244                         posn++;
245                 if (data[posn] == '\n') {
246                         int okay = 0;
247                         int serverlen = 0;
248                         struct alt_base *newalt;
249                         char *target = NULL;
250                         if (data[i] == '/') {
251                                 serverlen = strchr(base + 8, '/') - base;
252                                 okay = 1;
253                         } else if (!memcmp(data + i, "../", 3)) {
254                                 i += 3;
255                                 serverlen = strlen(base);
256                                 while (i + 2 < posn && 
257                                        !memcmp(data + i, "../", 3)) {
258                                         do {
259                                                 serverlen--;
260                                         } while (serverlen &&
261                                                  base[serverlen - 1] != '/');
262                                         i += 3;
263                                 }
264                                 // If the server got removed, give up.
265                                 okay = strchr(base, ':') - base + 3 < 
266                                         serverlen;
267                         } else if (http_specific) {
268                                 char *colon = strchr(data + i, ':');
269                                 char *slash = strchr(data + i, '/');
270                                 if (colon && slash && colon < data + posn &&
271                                     slash < data + posn && colon < slash) {
272                                         okay = 1;
273                                 }
274                         }
275                         // skip 'objects' at end
276                         if (okay) {
277                                 target = xmalloc(serverlen + posn - i - 6);
278                                 strncpy(target, base, serverlen);
279                                 strncpy(target + serverlen, data + i,
280                                         posn - i - 7);
281                                 target[serverlen + posn - i - 7] = '\0';
282                                 if (get_verbosely)
283                                         fprintf(stderr, 
284                                                 "Also look at %s\n", target);
285                                 newalt = xmalloc(sizeof(*newalt));
286                                 newalt->next = alt;
287                                 newalt->base = target;
288                                 newalt->got_indices = 0;
289                                 newalt->packs = NULL;
290                                 alt = newalt;
291                                 ret++;
292                         }
293                 }
294                 i = posn + 1;
295         }
296         got_alternates = 1;
297         
298         return ret;
299 }
300
301 static int fetch_indices(struct alt_base *repo)
302 {
303         unsigned char sha1[20];
304         char *url;
305         struct buffer buffer;
306         char *data;
307         int i = 0;
308
309         if (repo->got_indices)
310                 return 0;
311
312         data = xmalloc(4096);
313         buffer.size = 4096;
314         buffer.posn = 0;
315         buffer.buffer = data;
316
317         if (get_verbosely)
318                 fprintf(stderr, "Getting pack list\n");
319         
320         url = xmalloc(strlen(repo->base) + 21);
321         sprintf(url, "%s/objects/info/packs", repo->base);
322
323         curl_easy_setopt(curl, CURLOPT_FILE, &buffer);
324         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
325         curl_easy_setopt(curl, CURLOPT_URL, url);
326         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
327         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_errorstr);
328         
329         if (curl_easy_perform(curl))
330                 return error("%s", curl_errorstr);
331
332         while (i < buffer.posn) {
333                 switch (data[i]) {
334                 case 'P':
335                         i++;
336                         if (i + 52 < buffer.posn &&
337                             !strncmp(data + i, " pack-", 6) &&
338                             !strncmp(data + i + 46, ".pack\n", 6)) {
339                                 get_sha1_hex(data + i + 6, sha1);
340                                 setup_index(repo, sha1);
341                                 i += 51;
342                                 break;
343                         }
344                 default:
345                         while (data[i] != '\n')
346                                 i++;
347                 }
348                 i++;
349         }
350
351         repo->got_indices = 1;
352         return 0;
353 }
354
355 static int fetch_pack(struct alt_base *repo, unsigned char *sha1)
356 {
357         char *url;
358         struct packed_git *target;
359         struct packed_git **lst;
360         FILE *packfile;
361         char *filename;
362         char tmpfile[PATH_MAX];
363         int ret;
364         long prev_posn = 0;
365         char range[RANGE_HEADER_SIZE];
366         struct curl_slist *range_header = NULL;
367         CURLcode curl_result;
368
369         if (fetch_indices(repo))
370                 return -1;
371         target = find_sha1_pack(sha1, repo->packs);
372         if (!target)
373                 return -1;
374
375         if (get_verbosely) {
376                 fprintf(stderr, "Getting pack %s\n",
377                         sha1_to_hex(target->sha1));
378                 fprintf(stderr, " which contains %s\n",
379                         sha1_to_hex(sha1));
380         }
381
382         url = xmalloc(strlen(repo->base) + 65);
383         sprintf(url, "%s/objects/pack/pack-%s.pack",
384                 repo->base, sha1_to_hex(target->sha1));
385
386         filename = sha1_pack_name(target->sha1);
387         snprintf(tmpfile, sizeof(tmpfile), "%s.temp", filename);
388         packfile = fopen(tmpfile, "a");
389         if (!packfile)
390                 return error("Unable to open local file %s for pack",
391                              filename);
392
393         curl_easy_setopt(curl, CURLOPT_FILE, packfile);
394         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite);
395         curl_easy_setopt(curl, CURLOPT_URL, url);
396         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, no_pragma_header);
397         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_errorstr);
398
399         /* If there is data present from a previous transfer attempt,
400            resume where it left off */
401         prev_posn = ftell(packfile);
402         if (prev_posn>0) {
403                 if (get_verbosely)
404                         fprintf(stderr,
405                                 "Resuming fetch of pack %s at byte %ld\n",
406                                 sha1_to_hex(target->sha1), prev_posn);
407                 sprintf(range, "Range: bytes=%ld-", prev_posn);
408                 range_header = curl_slist_append(range_header, range);
409                 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, range_header);
410         }
411
412         /* Clear out the Range: header after performing the request, so
413            other curl requests don't inherit inappropriate header data */
414         curl_result = curl_easy_perform(curl);
415         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, no_range_header);
416         if (curl_result != 0) {
417                 fclose(packfile);
418                 return error("Unable to get pack file %s\n%s", url,
419                              curl_errorstr);
420         }
421
422         fclose(packfile);
423
424         ret = relink_or_rename(tmpfile, filename);
425         if (ret)
426                 return error("unable to write pack filename %s: %s",
427                              filename, strerror(ret));
428
429         lst = &repo->packs;
430         while (*lst != target)
431                 lst = &((*lst)->next);
432         *lst = (*lst)->next;
433
434         if (verify_pack(target, 0))
435                 return -1;
436         install_packed_git(target);
437
438         return 0;
439 }
440
441 static int fetch_object(struct alt_base *repo, unsigned char *sha1)
442 {
443         char *hex = sha1_to_hex(sha1);
444         char *filename = sha1_file_name(sha1);
445         unsigned char real_sha1[20];
446         char tmpfile[PATH_MAX];
447         char prevfile[PATH_MAX];
448         int ret;
449         char *url;
450         char *posn;
451         int prevlocal;
452         unsigned char prev_buf[PREV_BUF_SIZE];
453         ssize_t prev_read = 0;
454         long prev_posn = 0;
455         char range[RANGE_HEADER_SIZE];
456         struct curl_slist *range_header = NULL;
457         CURLcode curl_result;
458
459         snprintf(tmpfile, sizeof(tmpfile), "%s.temp", filename);
460         snprintf(prevfile, sizeof(prevfile), "%s.prev", filename);
461
462         if (unlink(prevfile) && (errno != ENOENT))
463                 return error("Failed to unlink %s (%s)",
464                              prevfile, strerror(errno));
465         if (rename(tmpfile, prevfile) && (errno != ENOENT))
466                 return error("Failed to rename %s to %s (%s)",
467                              tmpfile, prevfile, strerror(errno));
468
469         local = open(tmpfile, O_WRONLY | O_CREAT | O_EXCL, 0666);
470
471         /* Note: if another instance starts now, it will turn our new
472            tmpfile into its prevfile. */
473
474         if (local < 0)
475                 return error("Couldn't create temporary file %s for %s: %s\n",
476                              tmpfile, filename, strerror(errno));
477
478         memset(&stream, 0, sizeof(stream));
479
480         inflateInit(&stream);
481
482         SHA1_Init(&c);
483
484         curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
485         curl_easy_setopt(curl, CURLOPT_FILE, NULL);
486         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite_sha1_file);
487         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, no_pragma_header);
488         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_errorstr);
489
490         url = xmalloc(strlen(repo->base) + 50);
491         strcpy(url, repo->base);
492         posn = url + strlen(repo->base);
493         strcpy(posn, "objects/");
494         posn += 8;
495         memcpy(posn, hex, 2);
496         posn += 2;
497         *(posn++) = '/';
498         strcpy(posn, hex + 2);
499
500         curl_easy_setopt(curl, CURLOPT_URL, url);
501
502         /* If a previous temp file is present, process what was already
503            fetched. */
504         prevlocal = open(prevfile, O_RDONLY);
505         if (prevlocal != -1) {
506                 do {
507                         prev_read = read(prevlocal, prev_buf, PREV_BUF_SIZE);
508                         if (prev_read>0) {
509                                 if (fwrite_sha1_file(prev_buf,
510                                                      1,
511                                                      prev_read,
512                                                      NULL) == prev_read) {
513                                         prev_posn += prev_read;
514                                 } else {
515                                         prev_read = -1;
516                                 }
517                         }
518                 } while (prev_read > 0);
519                 close(prevlocal);
520         }
521         unlink(prevfile);
522
523         /* Reset inflate/SHA1 if there was an error reading the previous temp
524            file; also rewind to the beginning of the local file. */
525         if (prev_read == -1) {
526                 memset(&stream, 0, sizeof(stream));
527                 inflateInit(&stream);
528                 SHA1_Init(&c);
529                 if (prev_posn>0) {
530                         prev_posn = 0;
531                         lseek(local, SEEK_SET, 0);
532                         ftruncate(local, 0);
533                 }
534         }
535
536         /* If we have successfully processed data from a previous fetch
537            attempt, only fetch the data we don't already have. */
538         if (prev_posn>0) {
539                 if (get_verbosely)
540                         fprintf(stderr,
541                                 "Resuming fetch of object %s at byte %ld\n",
542                                 hex, prev_posn);
543                 sprintf(range, "Range: bytes=%ld-", prev_posn);
544                 range_header = curl_slist_append(range_header, range);
545                 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, range_header);
546         }
547
548         /* Clear out the Range: header after performing the request, so
549            other curl requests don't inherit inappropriate header data */
550         curl_result = curl_easy_perform(curl);
551         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, no_range_header);
552         if (curl_result != 0) {
553                 unlink(tmpfile);
554                 return error("%s", curl_errorstr);
555         }
556
557         fchmod(local, 0444);
558         close(local);
559         inflateEnd(&stream);
560         SHA1_Final(real_sha1, &c);
561         if (zret != Z_STREAM_END) {
562                 unlink(tmpfile);
563                 return error("File %s (%s) corrupt\n", hex, url);
564         }
565         if (memcmp(sha1, real_sha1, 20)) {
566                 unlink(tmpfile);
567                 return error("File %s has bad hash\n", hex);
568         }
569         ret = relink_or_rename(tmpfile, filename);
570         if (ret)
571                 return error("unable to write sha1 filename %s: %s",
572                              filename, strerror(ret));
573
574         pull_say("got %s\n", hex);
575         return 0;
576 }
577
578 int fetch(unsigned char *sha1)
579 {
580         struct alt_base *altbase = alt;
581         while (altbase) {
582                 if (!fetch_object(altbase, sha1))
583                         return 0;
584                 if (!fetch_pack(altbase, sha1))
585                         return 0;
586                 if (fetch_alternates(altbase->base) > 0) {
587                         altbase = alt;
588                         continue;
589                 }
590                 altbase = altbase->next;
591         }
592         return error("Unable to find %s under %s\n", sha1_to_hex(sha1), 
593                      initial_base);
594 }
595
596 int fetch_ref(char *ref, unsigned char *sha1)
597 {
598         char *url, *posn;
599         char hex[42];
600         struct buffer buffer;
601         char *base = initial_base;
602         buffer.size = 41;
603         buffer.posn = 0;
604         buffer.buffer = hex;
605         hex[41] = '\0';
606         
607         curl_easy_setopt(curl, CURLOPT_FILE, &buffer);
608         curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fwrite_buffer);
609         curl_easy_setopt(curl, CURLOPT_HTTPHEADER, NULL);
610         curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_errorstr);
611
612         url = xmalloc(strlen(base) + 6 + strlen(ref));
613         strcpy(url, base);
614         posn = url + strlen(base);
615         strcpy(posn, "refs/");
616         posn += 5;
617         strcpy(posn, ref);
618
619         curl_easy_setopt(curl, CURLOPT_URL, url);
620
621         if (curl_easy_perform(curl))
622                 return error("Couldn't get %s for %s\n%s",
623                              url, ref, curl_errorstr);
624
625         hex[40] = '\0';
626         get_sha1_hex(hex, sha1);
627         return 0;
628 }
629
630 int main(int argc, char **argv)
631 {
632         char *commit_id;
633         char *url;
634         int arg = 1;
635
636         while (arg < argc && argv[arg][0] == '-') {
637                 if (argv[arg][1] == 't') {
638                         get_tree = 1;
639                 } else if (argv[arg][1] == 'c') {
640                         get_history = 1;
641                 } else if (argv[arg][1] == 'a') {
642                         get_all = 1;
643                         get_tree = 1;
644                         get_history = 1;
645                 } else if (argv[arg][1] == 'v') {
646                         get_verbosely = 1;
647                 } else if (argv[arg][1] == 'w') {
648                         write_ref = argv[arg + 1];
649                         arg++;
650                 } else if (!strcmp(argv[arg], "--recover")) {
651                         get_recover = 1;
652                 }
653                 arg++;
654         }
655         if (argc < arg + 2) {
656                 usage("git-http-fetch [-c] [-t] [-a] [-d] [-v] [--recover] [-w ref] commit-id url");
657                 return 1;
658         }
659         commit_id = argv[arg];
660         url = argv[arg + 1];
661
662         curl_global_init(CURL_GLOBAL_ALL);
663
664         curl = curl_easy_init();
665         no_pragma_header = curl_slist_append(no_pragma_header, "Pragma:");
666         no_range_header = curl_slist_append(no_range_header, "Range:");
667
668         curl_ssl_verify = getenv("GIT_SSL_NO_VERIFY") ? 0 : 1;
669         curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, curl_ssl_verify);
670 #if LIBCURL_VERSION_NUM >= 0x070907
671         curl_easy_setopt(curl, CURLOPT_NETRC, CURL_NETRC_OPTIONAL);
672 #endif
673
674         if ((ssl_cert = getenv("GIT_SSL_CERT")) != NULL) {
675                 curl_easy_setopt(curl, CURLOPT_SSLCERT, ssl_cert);
676         }
677 #if LIBCURL_VERSION_NUM >= 0x070902
678         if ((ssl_key = getenv("GIT_SSL_KEY")) != NULL) {
679                 curl_easy_setopt(curl, CURLOPT_SSLKEY, ssl_key);
680         }
681 #endif
682 #if LIBCURL_VERSION_NUM >= 0x070908
683         if ((ssl_capath = getenv("GIT_SSL_CAPATH")) != NULL) {
684                 curl_easy_setopt(curl, CURLOPT_CAPATH, ssl_capath);
685         }
686 #endif
687         if ((ssl_cainfo = getenv("GIT_SSL_CAINFO")) != NULL) {
688                 curl_easy_setopt(curl, CURLOPT_CAINFO, ssl_cainfo);
689         }
690
691         alt = xmalloc(sizeof(*alt));
692         alt->base = url;
693         alt->got_indices = 0;
694         alt->packs = NULL;
695         alt->next = NULL;
696         initial_base = url;
697
698         if (pull(commit_id))
699                 return 1;
700
701         curl_slist_free_all(no_pragma_header);
702         curl_global_cleanup();
703         return 0;
704 }