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