[PATCH] delta read
[git.git] / sha1_file.c
1 /*
2  * GIT - The information manager from hell
3  *
4  * Copyright (C) Linus Torvalds, 2005
5  *
6  * This handles basic git sha1 object files - packing, unpacking,
7  * creation etc.
8  */
9 #include <stdarg.h>
10 #include <limits.h>
11 #include "cache.h"
12 #include "delta.h"
13
14 #ifndef O_NOATIME
15 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
16 #define O_NOATIME 01000000
17 #else
18 #define O_NOATIME 0
19 #endif
20 #endif
21
22 static unsigned int sha1_file_open_flag = O_NOATIME;
23
24 static unsigned hexval(char c)
25 {
26         if (c >= '0' && c <= '9')
27                 return c - '0';
28         if (c >= 'a' && c <= 'f')
29                 return c - 'a' + 10;
30         if (c >= 'A' && c <= 'F')
31                 return c - 'A' + 10;
32         return ~0;
33 }
34
35 int get_sha1_hex(const char *hex, unsigned char *sha1)
36 {
37         int i;
38         for (i = 0; i < 20; i++) {
39                 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
40                 if (val & ~0xff)
41                         return -1;
42                 *sha1++ = val;
43                 hex += 2;
44         }
45         return 0;
46 }
47
48 static int get_sha1_file(const char *path, unsigned char *result)
49 {
50         char buffer[60];
51         int fd = open(path, O_RDONLY);
52         int len;
53
54         if (fd < 0)
55                 return -1;
56         len = read(fd, buffer, sizeof(buffer));
57         close(fd);
58         if (len < 40)
59                 return -1;
60         return get_sha1_hex(buffer, result);
61 }
62
63 static char *git_dir, *git_object_dir, *git_index_file;
64 static void setup_git_env(void)
65 {
66         git_dir = gitenv(GIT_DIR_ENVIRONMENT);
67         if (!git_dir)
68                 git_dir = DEFAULT_GIT_DIR_ENVIRONMENT;
69         git_object_dir = gitenv(DB_ENVIRONMENT);
70         if (!git_object_dir) {
71                 git_object_dir = xmalloc(strlen(git_dir) + 9);
72                 sprintf(git_object_dir, "%s/objects", git_dir);
73         }
74         git_index_file = gitenv(INDEX_ENVIRONMENT);
75         if (!git_index_file) {
76                 git_index_file = xmalloc(strlen(git_dir) + 7);
77                 sprintf(git_index_file, "%s/index", git_dir);
78         }
79 }
80
81 char *get_object_directory(void)
82 {
83         if (!git_object_dir)
84                 setup_git_env();
85         return git_object_dir;
86 }
87
88 char *get_index_file(void)
89 {
90         if (!git_index_file)
91                 setup_git_env();
92         return git_index_file;
93 }
94
95 int get_sha1(const char *str, unsigned char *sha1)
96 {
97         static char pathname[PATH_MAX];
98         static const char *prefix[] = {
99                 "",
100                 "refs",
101                 "refs/tags",
102                 "refs/heads",
103                 "refs/snap",
104                 NULL
105         };
106         const char **p;
107
108         if (!get_sha1_hex(str, sha1))
109                 return 0;
110
111         if (!git_dir)
112                 setup_git_env();
113         for (p = prefix; *p; p++) {
114                 snprintf(pathname, sizeof(pathname), "%s/%s/%s",
115                          git_dir, *p, str);
116                 if (!get_sha1_file(pathname, sha1))
117                         return 0;
118         }
119
120         return -1;
121 }
122
123 char * sha1_to_hex(const unsigned char *sha1)
124 {
125         static char buffer[50];
126         static const char hex[] = "0123456789abcdef";
127         char *buf = buffer;
128         int i;
129
130         for (i = 0; i < 20; i++) {
131                 unsigned int val = *sha1++;
132                 *buf++ = hex[val >> 4];
133                 *buf++ = hex[val & 0xf];
134         }
135         return buffer;
136 }
137
138 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
139 {
140         int i;
141         for (i = 0; i < 20; i++) {
142                 static char hex[] = "0123456789abcdef";
143                 unsigned int val = sha1[i];
144                 char *pos = pathbuf + i*2 + (i > 0);
145                 *pos++ = hex[val >> 4];
146                 *pos = hex[val & 0xf];
147         }
148 }
149
150 /*
151  * NOTE! This returns a statically allocated buffer, so you have to be
152  * careful about using it. Do a "strdup()" if you need to save the
153  * filename.
154  *
155  * Also note that this returns the location for creating.  Reading
156  * SHA1 file can happen from any alternate directory listed in the
157  * DB_ENVIRONMENT environment variable if it is not found in
158  * the primary object database.
159  */
160 char *sha1_file_name(const unsigned char *sha1)
161 {
162         static char *name, *base;
163
164         if (!base) {
165                 const char *sha1_file_directory = get_object_directory();
166                 int len = strlen(sha1_file_directory);
167                 base = xmalloc(len + 60);
168                 memcpy(base, sha1_file_directory, len);
169                 memset(base+len, 0, 60);
170                 base[len] = '/';
171                 base[len+3] = '/';
172                 name = base + len + 1;
173         }
174         fill_sha1_path(name, sha1);
175         return base;
176 }
177
178 static struct alternate_object_database {
179         char *base;
180         char *name;
181 } *alt_odb;
182
183 /*
184  * Prepare alternate object database registry.
185  * alt_odb points at an array of struct alternate_object_database.
186  * This array is terminated with an element that has both its base
187  * and name set to NULL.  alt_odb[n] comes from n'th non-empty
188  * element from colon separated ALTERNATE_DB_ENVIRONMENT environment
189  * variable, and its base points at a statically allocated buffer
190  * that contains "/the/directory/corresponding/to/.git/objects/...",
191  * while its name points just after the slash at the end of
192  * ".git/objects/" in the example above, and has enough space to hold
193  * 40-byte hex SHA1, an extra slash for the first level indirection,
194  * and the terminating NUL.
195  * This function allocates the alt_odb array and all the strings
196  * pointed by base fields of the array elements with one xmalloc();
197  * the string pool immediately follows the array.
198  */
199 static void prepare_alt_odb(void)
200 {
201         int pass, totlen, i;
202         const char *cp, *last;
203         char *op = NULL;
204         const char *alt = gitenv(ALTERNATE_DB_ENVIRONMENT) ? : "";
205
206         /* The first pass counts how large an area to allocate to
207          * hold the entire alt_odb structure, including array of
208          * structs and path buffers for them.  The second pass fills
209          * the structure and prepares the path buffers for use by
210          * fill_sha1_path().
211          */
212         for (totlen = pass = 0; pass < 2; pass++) {
213                 last = alt;
214                 i = 0;
215                 do {
216                         cp = strchr(last, ':') ? : last + strlen(last);
217                         if (last != cp) {
218                                 /* 43 = 40-byte + 2 '/' + terminating NUL */
219                                 int pfxlen = cp - last;
220                                 int entlen = pfxlen + 43;
221                                 if (pass == 0)
222                                         totlen += entlen;
223                                 else {
224                                         alt_odb[i].base = op;
225                                         alt_odb[i].name = op + pfxlen + 1;
226                                         memcpy(op, last, pfxlen);
227                                         op[pfxlen] = op[pfxlen + 3] = '/';
228                                         op[entlen-1] = 0;
229                                         op += entlen;
230                                 }
231                                 i++;
232                         }
233                         while (*cp && *cp == ':')
234                                 cp++;
235                         last = cp;
236                 } while (*cp);
237                 if (pass)
238                         break;
239                 alt_odb = xmalloc(sizeof(*alt_odb) * (i + 1) + totlen);
240                 alt_odb[i].base = alt_odb[i].name = NULL;
241                 op = (char*)(&alt_odb[i+1]);
242         }
243 }
244
245 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
246 {
247         int i;
248         char *name = sha1_file_name(sha1);
249
250         if (!stat(name, st))
251                 return name;
252         if (!alt_odb)
253                 prepare_alt_odb();
254         for (i = 0; (name = alt_odb[i].name) != NULL; i++) {
255                 fill_sha1_path(name, sha1);
256                 if (!stat(alt_odb[i].base, st))
257                         return alt_odb[i].base;
258         }
259         return NULL;
260 }
261
262 int check_sha1_signature(unsigned char *sha1, void *map, unsigned long size, const char *type)
263 {
264         char header[100];
265         unsigned char real_sha1[20];
266         SHA_CTX c;
267
268         SHA1_Init(&c);
269         SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
270         SHA1_Update(&c, map, size);
271         SHA1_Final(real_sha1, &c);
272         return memcmp(sha1, real_sha1, 20) ? -1 : 0;
273 }
274
275 void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
276 {
277         struct stat st;
278         void *map;
279         int fd;
280         char *filename = find_sha1_file(sha1, &st);
281
282         if (!filename) {
283                 error("cannot map sha1 file %s", sha1_to_hex(sha1));
284                 return NULL;
285         }
286
287         fd = open(filename, O_RDONLY | sha1_file_open_flag);
288         if (fd < 0) {
289                 /* See if it works without O_NOATIME */
290                 switch (sha1_file_open_flag) {
291                 default:
292                         fd = open(filename, O_RDONLY);
293                         if (fd >= 0)
294                                 break;
295                 /* Fallthrough */
296                 case 0:
297                         perror(filename);
298                         return NULL;
299                 }
300
301                 /* If it failed once, it will probably fail again. Stop using O_NOATIME */
302                 sha1_file_open_flag = 0;
303         }
304         map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
305         close(fd);
306         if (-1 == (int)(long)map)
307                 return NULL;
308         *size = st.st_size;
309         return map;
310 }
311
312 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
313 {
314         int ret, bytes;
315         z_stream stream;
316         char buffer[8192];
317         unsigned char *buf;
318
319         /* Get the data stream */
320         memset(&stream, 0, sizeof(stream));
321         stream.next_in = map;
322         stream.avail_in = mapsize;
323         stream.next_out = (unsigned char *)buffer;
324         stream.avail_out = sizeof(buffer);
325
326         inflateInit(&stream);
327         ret = inflate(&stream, 0);
328         if (ret < Z_OK)
329                 return NULL;
330         if (sscanf(buffer, "%10s %lu", type, size) != 2)
331                 return NULL;
332
333         bytes = strlen(buffer) + 1;
334         buf = xmalloc(*size);
335
336         memcpy(buf, buffer + bytes, stream.total_out - bytes);
337         bytes = stream.total_out - bytes;
338         if (bytes < *size && ret == Z_OK) {
339                 stream.next_out = buf + bytes;
340                 stream.avail_out = *size - bytes;
341                 while (inflate(&stream, Z_FINISH) == Z_OK)
342                         /* nothing */;
343         }
344         inflateEnd(&stream);
345         return buf;
346 }
347
348 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
349 {
350         unsigned long mapsize;
351         void *map, *buf;
352
353         map = map_sha1_file(sha1, &mapsize);
354         if (map) {
355                 buf = unpack_sha1_file(map, mapsize, type, size);
356                 munmap(map, mapsize);
357                 if (buf && !strcmp(type, "delta")) {
358                         void *ref = NULL, *delta = buf;
359                         unsigned long ref_size, delta_size = *size;
360                         buf = NULL;
361                         if (delta_size > 20)
362                                 ref = read_sha1_file(delta, type, &ref_size);
363                         if (ref)
364                                 buf = patch_delta(ref, ref_size,
365                                                   delta+20, delta_size-20, 
366                                                   size);
367                         free(delta);
368                         free(ref);
369                 }
370                 return buf;
371         }
372         return NULL;
373 }
374
375 void *read_object_with_reference(const unsigned char *sha1,
376                                  const char *required_type,
377                                  unsigned long *size,
378                                  unsigned char *actual_sha1_return)
379 {
380         char type[20];
381         void *buffer;
382         unsigned long isize;
383         unsigned char actual_sha1[20];
384
385         memcpy(actual_sha1, sha1, 20);
386         while (1) {
387                 int ref_length = -1;
388                 const char *ref_type = NULL;
389
390                 buffer = read_sha1_file(actual_sha1, type, &isize);
391                 if (!buffer)
392                         return NULL;
393                 if (!strcmp(type, required_type)) {
394                         *size = isize;
395                         if (actual_sha1_return)
396                                 memcpy(actual_sha1_return, actual_sha1, 20);
397                         return buffer;
398                 }
399                 /* Handle references */
400                 else if (!strcmp(type, "commit"))
401                         ref_type = "tree ";
402                 else if (!strcmp(type, "tag"))
403                         ref_type = "object ";
404                 else {
405                         free(buffer);
406                         return NULL;
407                 }
408                 ref_length = strlen(ref_type);
409
410                 if (memcmp(buffer, ref_type, ref_length) ||
411                     get_sha1_hex(buffer + ref_length, actual_sha1)) {
412                         free(buffer);
413                         return NULL;
414                 }
415                 /* Now we have the ID of the referred-to object in
416                  * actual_sha1.  Check again. */
417         }
418 }
419
420 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
421 {
422         int size;
423         unsigned char *compressed;
424         z_stream stream;
425         unsigned char sha1[20];
426         SHA_CTX c;
427         char *filename;
428         static char tmpfile[PATH_MAX];
429         unsigned char hdr[50];
430         int fd, hdrlen, ret;
431
432         /* Generate the header */
433         hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
434
435         /* Sha1.. */
436         SHA1_Init(&c);
437         SHA1_Update(&c, hdr, hdrlen);
438         SHA1_Update(&c, buf, len);
439         SHA1_Final(sha1, &c);
440
441         if (returnsha1)
442                 memcpy(returnsha1, sha1, 20);
443
444         filename = sha1_file_name(sha1);
445         fd = open(filename, O_RDONLY);
446         if (fd >= 0) {
447                 /*
448                  * FIXME!!! We might do collision checking here, but we'd
449                  * need to uncompress the old file and check it. Later.
450                  */
451                 close(fd);
452                 return 0;
453         }
454
455         if (errno != ENOENT) {
456                 fprintf(stderr, "sha1 file %s: %s", filename, strerror(errno));
457                 return -1;
458         }
459
460         snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
461
462         fd = mkstemp(tmpfile);
463         if (fd < 0) {
464                 fprintf(stderr, "unable to create temporary sha1 filename %s: %s", tmpfile, strerror(errno));
465                 return -1;
466         }
467
468         /* Set it up */
469         memset(&stream, 0, sizeof(stream));
470         deflateInit(&stream, Z_BEST_COMPRESSION);
471         size = deflateBound(&stream, len+hdrlen);
472         compressed = xmalloc(size);
473
474         /* Compress it */
475         stream.next_out = compressed;
476         stream.avail_out = size;
477
478         /* First header.. */
479         stream.next_in = hdr;
480         stream.avail_in = hdrlen;
481         while (deflate(&stream, 0) == Z_OK)
482                 /* nothing */;
483
484         /* Then the data itself.. */
485         stream.next_in = buf;
486         stream.avail_in = len;
487         while (deflate(&stream, Z_FINISH) == Z_OK)
488                 /* nothing */;
489         deflateEnd(&stream);
490         size = stream.total_out;
491
492         if (write(fd, compressed, size) != size)
493                 die("unable to write file");
494         fchmod(fd, 0444);
495         close(fd);
496         free(compressed);
497
498         ret = link(tmpfile, filename);
499         if (ret < 0) {
500                 ret = errno;
501
502                 /*
503                  * Coda hack - coda doesn't like cross-directory links,
504                  * so we fall back to a rename, which will mean that it
505                  * won't be able to check collisions, but that's not a
506                  * big deal.
507                  *
508                  * When this succeeds, we just return 0. We have nothing
509                  * left to unlink.
510                  */
511                 if (ret == EXDEV && !rename(tmpfile, filename))
512                         return 0;
513         }
514         unlink(tmpfile);
515         if (ret) {
516                 if (ret != EEXIST) {
517                         fprintf(stderr, "unable to write sha1 filename %s: %s", filename, strerror(ret));
518                         return -1;
519                 }
520                 /* FIXME!!! Collision check here ? */
521         }
522
523         return 0;
524 }
525
526 int write_sha1_from_fd(const unsigned char *sha1, int fd)
527 {
528         char *filename = sha1_file_name(sha1);
529
530         int local;
531         z_stream stream;
532         unsigned char real_sha1[20];
533         unsigned char buf[4096];
534         unsigned char discard[4096];
535         int ret;
536         SHA_CTX c;
537
538         local = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0666);
539
540         if (local < 0)
541                 return error("Couldn't open %s\n", filename);
542
543         memset(&stream, 0, sizeof(stream));
544
545         inflateInit(&stream);
546
547         SHA1_Init(&c);
548
549         do {
550                 ssize_t size;
551                 size = read(fd, buf, 4096);
552                 if (size <= 0) {
553                         close(local);
554                         unlink(filename);
555                         if (!size)
556                                 return error("Connection closed?");
557                         perror("Reading from connection");
558                         return -1;
559                 }
560                 write(local, buf, size);
561                 stream.avail_in = size;
562                 stream.next_in = buf;
563                 do {
564                         stream.next_out = discard;
565                         stream.avail_out = sizeof(discard);
566                         ret = inflate(&stream, Z_SYNC_FLUSH);
567                         SHA1_Update(&c, discard, sizeof(discard) -
568                                     stream.avail_out);
569                 } while (stream.avail_in && ret == Z_OK);
570                 
571         } while (ret == Z_OK);
572         inflateEnd(&stream);
573
574         close(local);
575         SHA1_Final(real_sha1, &c);
576         if (ret != Z_STREAM_END) {
577                 unlink(filename);
578                 return error("File %s corrupted", sha1_to_hex(sha1));
579         }
580         if (memcmp(sha1, real_sha1, 20)) {
581                 unlink(filename);
582                 return error("File %s has bad hash\n", sha1_to_hex(sha1));
583         }
584         
585         return 0;
586 }
587
588 int has_sha1_file(const unsigned char *sha1)
589 {
590         struct stat st;
591         return !!find_sha1_file(sha1, &st);
592 }
593
594 int index_fd(unsigned char *sha1, int fd, struct stat *st)
595 {
596         unsigned long size = st->st_size;
597         void *buf;
598         int ret;
599
600         buf = "";
601         if (size)
602                 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
603         close(fd);
604         if ((int)(long)buf == -1)
605                 return -1;
606
607         ret = write_sha1_file(buf, size, "blob", sha1);
608         if (size)
609                 munmap(buf, size);
610         return ret;
611 }