e27affb2885717974b5612d4a41a91ed390d7ff7
[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 <sys/types.h>
10 #include <dirent.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, *git_refs_dir;
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_refs_dir = xmalloc(strlen(git_dir) + 6);
75         sprintf(git_refs_dir, "%s/refs", git_dir);
76         git_index_file = gitenv(INDEX_ENVIRONMENT);
77         if (!git_index_file) {
78                 git_index_file = xmalloc(strlen(git_dir) + 7);
79                 sprintf(git_index_file, "%s/index", git_dir);
80         }
81 }
82
83 char *get_object_directory(void)
84 {
85         if (!git_object_dir)
86                 setup_git_env();
87         return git_object_dir;
88 }
89
90 char *get_refs_directory(void)
91 {
92         if (!git_refs_dir)
93                 setup_git_env();
94         return git_refs_dir;
95 }
96
97 char *get_index_file(void)
98 {
99         if (!git_index_file)
100                 setup_git_env();
101         return git_index_file;
102 }
103
104 int get_sha1(const char *str, unsigned char *sha1)
105 {
106         static char pathname[PATH_MAX];
107         static const char *prefix[] = {
108                 "",
109                 "refs",
110                 "refs/tags",
111                 "refs/heads",
112                 "refs/snap",
113                 NULL
114         };
115         const char **p;
116
117         if (!get_sha1_hex(str, sha1))
118                 return 0;
119
120         if (!git_dir)
121                 setup_git_env();
122         for (p = prefix; *p; p++) {
123                 snprintf(pathname, sizeof(pathname), "%s/%s/%s",
124                          git_dir, *p, str);
125                 if (!get_sha1_file(pathname, sha1))
126                         return 0;
127         }
128
129         return -1;
130 }
131
132 char * sha1_to_hex(const unsigned char *sha1)
133 {
134         static char buffer[50];
135         static const char hex[] = "0123456789abcdef";
136         char *buf = buffer;
137         int i;
138
139         for (i = 0; i < 20; i++) {
140                 unsigned int val = *sha1++;
141                 *buf++ = hex[val >> 4];
142                 *buf++ = hex[val & 0xf];
143         }
144         return buffer;
145 }
146
147 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
148 {
149         int i;
150         for (i = 0; i < 20; i++) {
151                 static char hex[] = "0123456789abcdef";
152                 unsigned int val = sha1[i];
153                 char *pos = pathbuf + i*2 + (i > 0);
154                 *pos++ = hex[val >> 4];
155                 *pos = hex[val & 0xf];
156         }
157 }
158
159 /*
160  * NOTE! This returns a statically allocated buffer, so you have to be
161  * careful about using it. Do a "strdup()" if you need to save the
162  * filename.
163  *
164  * Also note that this returns the location for creating.  Reading
165  * SHA1 file can happen from any alternate directory listed in the
166  * DB_ENVIRONMENT environment variable if it is not found in
167  * the primary object database.
168  */
169 char *sha1_file_name(const unsigned char *sha1)
170 {
171         static char *name, *base;
172
173         if (!base) {
174                 const char *sha1_file_directory = get_object_directory();
175                 int len = strlen(sha1_file_directory);
176                 base = xmalloc(len + 60);
177                 memcpy(base, sha1_file_directory, len);
178                 memset(base+len, 0, 60);
179                 base[len] = '/';
180                 base[len+3] = '/';
181                 name = base + len + 1;
182         }
183         fill_sha1_path(name, sha1);
184         return base;
185 }
186
187 static struct alternate_object_database {
188         char *base;
189         char *name;
190 } *alt_odb;
191
192 /*
193  * Prepare alternate object database registry.
194  * alt_odb points at an array of struct alternate_object_database.
195  * This array is terminated with an element that has both its base
196  * and name set to NULL.  alt_odb[n] comes from n'th non-empty
197  * element from colon separated ALTERNATE_DB_ENVIRONMENT environment
198  * variable, and its base points at a statically allocated buffer
199  * that contains "/the/directory/corresponding/to/.git/objects/...",
200  * while its name points just after the slash at the end of
201  * ".git/objects/" in the example above, and has enough space to hold
202  * 40-byte hex SHA1, an extra slash for the first level indirection,
203  * and the terminating NUL.
204  * This function allocates the alt_odb array and all the strings
205  * pointed by base fields of the array elements with one xmalloc();
206  * the string pool immediately follows the array.
207  */
208 static void prepare_alt_odb(void)
209 {
210         int pass, totlen, i;
211         const char *cp, *last;
212         char *op = NULL;
213         const char *alt = gitenv(ALTERNATE_DB_ENVIRONMENT) ? : "";
214
215         /* The first pass counts how large an area to allocate to
216          * hold the entire alt_odb structure, including array of
217          * structs and path buffers for them.  The second pass fills
218          * the structure and prepares the path buffers for use by
219          * fill_sha1_path().
220          */
221         for (totlen = pass = 0; pass < 2; pass++) {
222                 last = alt;
223                 i = 0;
224                 do {
225                         cp = strchr(last, ':') ? : last + strlen(last);
226                         if (last != cp) {
227                                 /* 43 = 40-byte + 2 '/' + terminating NUL */
228                                 int pfxlen = cp - last;
229                                 int entlen = pfxlen + 43;
230                                 if (pass == 0)
231                                         totlen += entlen;
232                                 else {
233                                         alt_odb[i].base = op;
234                                         alt_odb[i].name = op + pfxlen + 1;
235                                         memcpy(op, last, pfxlen);
236                                         op[pfxlen] = op[pfxlen + 3] = '/';
237                                         op[entlen-1] = 0;
238                                         op += entlen;
239                                 }
240                                 i++;
241                         }
242                         while (*cp && *cp == ':')
243                                 cp++;
244                         last = cp;
245                 } while (*cp);
246                 if (pass)
247                         break;
248                 alt_odb = xmalloc(sizeof(*alt_odb) * (i + 1) + totlen);
249                 alt_odb[i].base = alt_odb[i].name = NULL;
250                 op = (char*)(&alt_odb[i+1]);
251         }
252 }
253
254 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
255 {
256         int i;
257         char *name = sha1_file_name(sha1);
258
259         if (!stat(name, st))
260                 return name;
261         if (!alt_odb)
262                 prepare_alt_odb();
263         for (i = 0; (name = alt_odb[i].name) != NULL; i++) {
264                 fill_sha1_path(name, sha1);
265                 if (!stat(alt_odb[i].base, st))
266                         return alt_odb[i].base;
267         }
268         return NULL;
269 }
270
271 #define PACK_MAX_SZ (1<<26)
272 static int pack_used_ctr;
273 static unsigned long pack_mapped;
274 static struct packed_git {
275         struct packed_git *next;
276         unsigned long index_size;
277         unsigned long pack_size;
278         unsigned int *index_base;
279         void *pack_base;
280         unsigned int pack_last_used;
281         char pack_name[0]; /* something like ".git/objects/pack/xxxxx.pack" */
282 } *packed_git;
283
284 struct pack_entry {
285         unsigned int offset;
286         unsigned char sha1[20];
287         struct packed_git *p;
288 };
289
290 static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
291                                 void **idx_map_)
292 {
293         void *idx_map;
294         unsigned int *index;
295         unsigned long idx_size;
296         int nr, i;
297         int fd = open(path, O_RDONLY);
298         struct stat st;
299         if (fd < 0)
300                 return -1;
301         if (fstat(fd, &st)) {
302                 close(fd);
303                 return -1;
304         }
305         idx_size = st.st_size;
306         idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
307         close(fd);
308         if (idx_map == MAP_FAILED)
309                 return -1;
310
311         index = idx_map;
312
313         /* check index map */
314         if (idx_size < 4*256 + 20)
315                 return error("index file too small");
316         nr = 0;
317         for (i = 0; i < 256; i++) {
318                 unsigned int n = ntohl(index[i]);
319                 if (n < nr)
320                         return error("non-monotonic index");
321                 nr = n;
322         }
323
324         /*
325          * Total size:
326          *  - 256 index entries 4 bytes each
327          *  - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
328          *  - 20-byte SHA1 of the packfile
329          *  - 20-byte SHA1 file checksum
330          */
331         if (idx_size != 4*256 + nr * 24 + 20 + 20)
332                 return error("wrong index file size");
333
334         *idx_map_ = idx_map;
335         *idx_size_ = idx_size;
336         return 0;
337 }
338
339 static void unuse_one_packed_git(void)
340 {
341         /* NOTYET */
342 }
343
344 static int use_packed_git(struct packed_git *p)
345 {
346         if (!p->pack_base) {
347                 int fd;
348                 struct stat st;
349                 void *map;
350
351                 pack_mapped += p->pack_size;
352                 while (PACK_MAX_SZ < pack_mapped)
353                         unuse_one_packed_git();
354                 fd = open(p->pack_name, O_RDONLY);
355                 if (fd < 0)
356                         return -1;
357                 if (fstat(fd, &st)) {
358                         close(fd);
359                         return -1;
360                 }
361                 if (st.st_size != p->pack_size)
362                         return -1;
363                 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
364                 close(fd);
365                 if (map == MAP_FAILED)
366                         return -1;
367                 p->pack_base = map;
368         }
369         p->pack_last_used = pack_used_ctr++;
370         return 0;
371 }
372
373 static struct packed_git *add_packed_git(char *path, int path_len)
374 {
375         struct stat st;
376         struct packed_git *p;
377         unsigned long idx_size;
378         void *idx_map;
379
380         if (check_packed_git_idx(path, &idx_size, &idx_map))
381                 return NULL;
382
383         /* do we have a corresponding .pack file? */
384         strcpy(path + path_len - 4, ".pack");
385         if (stat(path, &st) || !S_ISREG(st.st_mode)) {
386                 munmap(idx_map, idx_size);
387                 return NULL;
388         }
389         /* ok, it looks sane as far as we can check without
390          * actually mapping the pack file.
391          */
392         p = xmalloc(sizeof(*p) + path_len + 2);
393         strcpy(p->pack_name, path);
394         p->index_size = idx_size;
395         p->pack_size = st.st_size;
396         p->index_base = idx_map;
397         p->next = NULL;
398         p->pack_last_used = 0;
399         return p;
400 }
401
402 static void prepare_packed_git_one(char *objdir)
403 {
404         char path[PATH_MAX];
405         int len;
406         DIR *dir;
407         struct dirent *de;
408
409         sprintf(path, "%s/pack", objdir);
410         len = strlen(path);
411         dir = opendir(path);
412         if (!dir)
413                 return;
414         path[len++] = '/';
415         while ((de = readdir(dir)) != NULL) {
416                 int namelen = strlen(de->d_name);
417                 struct packed_git *p;
418
419                 if (strcmp(de->d_name + namelen - 4, ".idx"))
420                         continue;
421
422                 /* we have .idx.  Is it a file we can map? */
423                 strcpy(path + len, de->d_name);
424                 p = add_packed_git(path, len + namelen);
425                 if (!p)
426                         continue;
427                 p->next = packed_git;
428                 packed_git = p;
429         }
430 }
431
432 static void prepare_packed_git(void)
433 {
434         int i;
435         static int run_once = 0;
436
437         if (run_once++)
438                 return;
439
440         prepare_packed_git_one(get_object_directory());
441         if (!alt_odb)
442                 prepare_alt_odb();
443         for (i = 0; alt_odb[i].base != NULL; i++) {
444                 alt_odb[i].name[0] = 0;
445                 prepare_packed_git_one(alt_odb[i].base);
446         }
447 }
448
449 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
450 {
451         char header[100];
452         unsigned char real_sha1[20];
453         SHA_CTX c;
454
455         SHA1_Init(&c);
456         SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
457         SHA1_Update(&c, map, size);
458         SHA1_Final(real_sha1, &c);
459         return memcmp(sha1, real_sha1, 20) ? -1 : 0;
460 }
461
462 static void *map_sha1_file_internal(const unsigned char *sha1,
463                                     unsigned long *size,
464                                     int say_error)
465 {
466         struct stat st;
467         void *map;
468         int fd;
469         char *filename = find_sha1_file(sha1, &st);
470
471         if (!filename) {
472                 if (say_error)
473                         error("cannot map sha1 file %s", sha1_to_hex(sha1));
474                 return NULL;
475         }
476
477         fd = open(filename, O_RDONLY | sha1_file_open_flag);
478         if (fd < 0) {
479                 /* See if it works without O_NOATIME */
480                 switch (sha1_file_open_flag) {
481                 default:
482                         fd = open(filename, O_RDONLY);
483                         if (fd >= 0)
484                                 break;
485                 /* Fallthrough */
486                 case 0:
487                         if (say_error)
488                                 perror(filename);
489                         return NULL;
490                 }
491
492                 /* If it failed once, it will probably fail again.
493                  * Stop using O_NOATIME
494                  */
495                 sha1_file_open_flag = 0;
496         }
497         map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
498         close(fd);
499         if (-1 == (int)(long)map)
500                 return NULL;
501         *size = st.st_size;
502         return map;
503 }
504
505 void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
506 {
507         return map_sha1_file_internal(sha1, size, 1);
508 }
509
510 int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
511 {
512         /* Get the data stream */
513         memset(stream, 0, sizeof(*stream));
514         stream->next_in = map;
515         stream->avail_in = mapsize;
516         stream->next_out = buffer;
517         stream->avail_out = size;
518
519         inflateInit(stream);
520         return inflate(stream, 0);
521 }
522
523 void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
524 {
525         int bytes = strlen(buffer) + 1;
526         unsigned char *buf = xmalloc(1+size);
527
528         memcpy(buf, buffer + bytes, stream->total_out - bytes);
529         bytes = stream->total_out - bytes;
530         if (bytes < size) {
531                 stream->next_out = buf + bytes;
532                 stream->avail_out = size - bytes;
533                 while (inflate(stream, Z_FINISH) == Z_OK)
534                         /* nothing */;
535         }
536         buf[size] = 0;
537         inflateEnd(stream);
538         return buf;
539 }
540
541 /*
542  * We used to just use "sscanf()", but that's actually way
543  * too permissive for what we want to check. So do an anal
544  * object header parse by hand.
545  */
546 int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
547 {
548         int i;
549         unsigned long size;
550
551         /*
552          * The type can be at most ten bytes (including the 
553          * terminating '\0' that we add), and is followed by
554          * a space. 
555          */
556         i = 10;
557         for (;;) {
558                 char c = *hdr++;
559                 if (c == ' ')
560                         break;
561                 if (!--i)
562                         return -1;
563                 *type++ = c;
564         }
565         *type = 0;
566
567         /*
568          * The length must follow immediately, and be in canonical
569          * decimal format (ie "010" is not valid).
570          */
571         size = *hdr++ - '0';
572         if (size > 9)
573                 return -1;
574         if (size) {
575                 for (;;) {
576                         unsigned long c = *hdr - '0';
577                         if (c > 9)
578                                 break;
579                         hdr++;
580                         size = size * 10 + c;
581                 }
582         }
583         *sizep = size;
584
585         /*
586          * The length must be followed by a zero byte
587          */
588         return *hdr ? -1 : 0;
589 }
590
591 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
592 {
593         int ret;
594         z_stream stream;
595         char hdr[8192];
596
597         ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
598         if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
599                 return NULL;
600
601         return unpack_sha1_rest(&stream, hdr, *size);
602 }
603
604 static int packed_delta_info(unsigned char *base_sha1,
605                              unsigned long delta_size,
606                              unsigned long left,
607                              char *type,
608                              unsigned long *sizep)
609 {
610         unsigned char *data;
611         unsigned char delta_head[64];
612         int i;
613         unsigned char cmd;
614         unsigned long data_size, result_size, base_size, verify_base_size;
615         z_stream stream;
616         int st;
617
618         if (left < 20)
619                 die("truncated pack file");
620         if (sha1_object_info(base_sha1, type, &base_size))
621                 die("cannot get info for delta-pack base");
622
623         data = base_sha1 + 20;
624         data_size = left - 20;
625
626         memset(&stream, 0, sizeof(stream));
627
628         stream.next_in = data;
629         stream.avail_in = data_size;
630         stream.next_out = delta_head;
631         stream.avail_out = sizeof(delta_head);
632
633         inflateInit(&stream);
634         st = inflate(&stream, Z_FINISH);
635         inflateEnd(&stream);
636         if ((st != Z_STREAM_END) && stream.total_out != sizeof(delta_head))
637                 die("delta data unpack-initial failed");
638
639         /* Examine the initial part of the delta to figure out
640          * the result size.  Verify the base size while we are at it.
641          */
642         data = delta_head;
643         verify_base_size = i = 0;
644         cmd = *data++;
645         while (cmd) {
646                 if (cmd & 1)
647                         verify_base_size |= *data++ << i;
648                 i += 8;
649                 cmd >>= 1;
650         }
651
652         /* Read the result size */
653         result_size = i = 0;
654         cmd = *data++;
655         while (cmd) {
656                 if (cmd & 1)
657                         result_size |= *data++ << i;
658                 i += 8;
659                 cmd >>= 1;
660         }
661         if (verify_base_size != base_size)
662                 die("delta base size mismatch");
663
664         *sizep = result_size;
665         return 0;
666 }
667
668 static int packed_object_info(struct pack_entry *entry,
669                               char *type, unsigned long *sizep)
670 {
671         struct packed_git *p = entry->p;
672         unsigned long offset, size, left;
673         unsigned char *pack;
674
675         offset = entry->offset;
676         if (p->pack_size - 5 < offset)
677                 die("object offset outside of pack file");
678
679         if (use_packed_git(p))
680                 die("cannot map packed file");
681
682         pack = p->pack_base + offset;
683         size = (pack[1] << 24) + (pack[2] << 16) + (pack[3] << 8) + pack[4];
684         left = p->pack_size - offset - 5;
685         switch (*pack) {
686         case 'D':
687                 return packed_delta_info(pack+5, size, left, type, sizep);
688                 break;
689         case 'C':
690                 strcpy(type, "commit");
691                 break;
692         case 'T':
693                 strcpy(type, "tree");
694                 break;
695         case 'B':
696                 strcpy(type, "blob");
697                 break;
698         case 'G':
699                 strcpy(type, "tag");
700                 break;
701         default:
702                 die("corrupted pack file");
703         }
704         *sizep = size;
705         return 0;
706 }
707
708 /* forward declaration for a mutually recursive function */
709 static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
710
711 static void *unpack_delta_entry(unsigned char *base_sha1,
712                                 unsigned long delta_size,
713                                 unsigned long left,
714                                 char *type,
715                                 unsigned long *sizep)
716 {
717         void *data, *delta_data, *result, *base;
718         unsigned long data_size, result_size, base_size;
719         z_stream stream;
720         int st;
721
722         if (left < 20)
723                 die("truncated pack file");
724         data = base_sha1 + 20;
725         data_size = left - 20;
726         delta_data = xmalloc(delta_size);
727
728         memset(&stream, 0, sizeof(stream));
729
730         stream.next_in = data;
731         stream.avail_in = data_size;
732         stream.next_out = delta_data;
733         stream.avail_out = delta_size;
734
735         inflateInit(&stream);
736         st = inflate(&stream, Z_FINISH);
737         inflateEnd(&stream);
738         if ((st != Z_STREAM_END) || stream.total_out != delta_size)
739                 die("delta data unpack failed");
740
741         /* This may recursively unpack the base, which is what we want */
742         base = read_sha1_file(base_sha1, type, &base_size);
743         if (!base)
744                 die("failed to read delta-pack base object %s",
745                     sha1_to_hex(base_sha1));
746         result = patch_delta(base, base_size,
747                              delta_data, delta_size,
748                              &result_size);
749         if (!result)
750                 die("failed to apply delta");
751         free(delta_data);
752         free(base);
753         *sizep = result_size;
754         return result;
755 }
756
757 static void *unpack_non_delta_entry(unsigned char *data,
758                                     unsigned long size,
759                                     unsigned long left)
760 {
761         int st;
762         z_stream stream;
763         char *buffer;
764
765         buffer = xmalloc(size + 1);
766         buffer[size] = 0;
767         memset(&stream, 0, sizeof(stream));
768         stream.next_in = data;
769         stream.avail_in = left;
770         stream.next_out = buffer;
771         stream.avail_out = size;
772
773         inflateInit(&stream);
774         st = inflate(&stream, Z_FINISH);
775         inflateEnd(&stream);
776         if ((st != Z_STREAM_END) || stream.total_out != size) {
777                 free(buffer);
778                 return NULL;
779         }
780
781         return buffer;
782 }
783
784 static void *unpack_entry(struct pack_entry *entry,
785                           char *type, unsigned long *sizep)
786 {
787         struct packed_git *p = entry->p;
788         unsigned long offset, size, left;
789         unsigned char *pack;
790
791         offset = entry->offset;
792         if (p->pack_size - 5 < offset)
793                 die("object offset outside of pack file");
794
795         if (use_packed_git(p))
796                 die("cannot map packed file");
797
798         pack = p->pack_base + offset;
799         size = (pack[1] << 24) + (pack[2] << 16) + (pack[3] << 8) + pack[4];
800         left = p->pack_size - offset - 5;
801         switch (*pack) {
802         case 'D':
803                 return unpack_delta_entry(pack+5, size, left, type, sizep);
804         case 'C':
805                 strcpy(type, "commit");
806                 break;
807         case 'T':
808                 strcpy(type, "tree");
809                 break;
810         case 'B':
811                 strcpy(type, "blob");
812                 break;
813         case 'G':
814                 strcpy(type, "tag");
815                 break;
816         default:
817                 die("corrupted pack file");
818         }
819         *sizep = size;
820         return unpack_non_delta_entry(pack+5, size, left);
821 }
822
823 static int find_pack_entry_1(const unsigned char *sha1,
824                              struct pack_entry *e, struct packed_git *p)
825 {
826         int *level1_ofs = p->index_base;
827         int hi = ntohl(level1_ofs[*sha1]);
828         int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
829         void *index = p->index_base + 256;
830
831         do {
832                 int mi = (lo + hi) / 2;
833                 int cmp = memcmp(index + 24 * mi + 4, sha1, 20);
834                 if (!cmp) {
835                         e->offset = ntohl(*((int*)(index + 24 * mi)));
836                         memcpy(e->sha1, sha1, 20);
837                         e->p = p;
838                         return 1;
839                 }
840                 if (cmp > 0)
841                         hi = mi;
842                 else
843                         lo = mi+1;
844         } while (lo < hi);
845         return 0;
846 }
847
848 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
849 {
850         struct packed_git *p;
851         prepare_packed_git();
852
853         for (p = packed_git; p; p = p->next) {
854                 if (find_pack_entry_1(sha1, e, p))
855                         return 1;
856         }
857         return 0;
858 }
859
860 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
861 {
862         int status;
863         unsigned long mapsize, size;
864         void *map;
865         z_stream stream;
866         char hdr[128];
867
868         map = map_sha1_file_internal(sha1, &mapsize, 0);
869         if (!map) {
870                 struct pack_entry e;
871
872                 if (!find_pack_entry(sha1, &e))
873                         return error("unable to find %s", sha1_to_hex(sha1));
874                 if (!packed_object_info(&e, type, sizep))
875                         return 0;
876                 /* sheesh */
877                 map = unpack_entry(&e, type, sizep);
878                 free(map);
879                 return (map == NULL) ? 0 : -1;
880         }
881         if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
882                 status = error("unable to unpack %s header",
883                                sha1_to_hex(sha1));
884         if (parse_sha1_header(hdr, type, &size) < 0)
885                 status = error("unable to parse %s header", sha1_to_hex(sha1));
886         else {
887                 status = 0;
888                 *sizep = size;
889         }
890         inflateEnd(&stream);
891         munmap(map, mapsize);
892         return status;
893 }
894
895 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
896 {
897         struct pack_entry e;
898
899         if (!find_pack_entry(sha1, &e)) {
900                 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
901                 return NULL;
902         }
903         return unpack_entry(&e, type, size);
904 }
905
906 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
907 {
908         unsigned long mapsize;
909         void *map, *buf;
910
911         map = map_sha1_file_internal(sha1, &mapsize, 0);
912         if (map) {
913                 buf = unpack_sha1_file(map, mapsize, type, size);
914                 munmap(map, mapsize);
915                 return buf;
916         }
917         return read_packed_sha1(sha1, type, size);
918 }
919
920 void *read_object_with_reference(const unsigned char *sha1,
921                                  const char *required_type,
922                                  unsigned long *size,
923                                  unsigned char *actual_sha1_return)
924 {
925         char type[20];
926         void *buffer;
927         unsigned long isize;
928         unsigned char actual_sha1[20];
929
930         memcpy(actual_sha1, sha1, 20);
931         while (1) {
932                 int ref_length = -1;
933                 const char *ref_type = NULL;
934
935                 buffer = read_sha1_file(actual_sha1, type, &isize);
936                 if (!buffer)
937                         return NULL;
938                 if (!strcmp(type, required_type)) {
939                         *size = isize;
940                         if (actual_sha1_return)
941                                 memcpy(actual_sha1_return, actual_sha1, 20);
942                         return buffer;
943                 }
944                 /* Handle references */
945                 else if (!strcmp(type, "commit"))
946                         ref_type = "tree ";
947                 else if (!strcmp(type, "tag"))
948                         ref_type = "object ";
949                 else {
950                         free(buffer);
951                         return NULL;
952                 }
953                 ref_length = strlen(ref_type);
954
955                 if (memcmp(buffer, ref_type, ref_length) ||
956                     get_sha1_hex(buffer + ref_length, actual_sha1)) {
957                         free(buffer);
958                         return NULL;
959                 }
960                 /* Now we have the ID of the referred-to object in
961                  * actual_sha1.  Check again. */
962         }
963 }
964
965 static char *write_sha1_file_prepare(void *buf,
966                                      unsigned long len,
967                                      const char *type,
968                                      unsigned char *sha1,
969                                      unsigned char *hdr,
970                                      int *hdrlen)
971 {
972         SHA_CTX c;
973
974         /* Generate the header */
975         *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
976
977         /* Sha1.. */
978         SHA1_Init(&c);
979         SHA1_Update(&c, hdr, *hdrlen);
980         SHA1_Update(&c, buf, len);
981         SHA1_Final(sha1, &c);
982
983         return sha1_file_name(sha1);
984 }
985
986 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
987 {
988         int size;
989         unsigned char *compressed;
990         z_stream stream;
991         unsigned char sha1[20];
992         char *filename;
993         static char tmpfile[PATH_MAX];
994         unsigned char hdr[50];
995         int fd, hdrlen, ret;
996
997         /* Normally if we have it in the pack then we do not bother writing
998          * it out into .git/objects/??/?{38} file.
999          */
1000         filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1001         if (returnsha1)
1002                 memcpy(returnsha1, sha1, 20);
1003         if (has_sha1_file(sha1))
1004                 return 0;
1005         fd = open(filename, O_RDONLY);
1006         if (fd >= 0) {
1007                 /*
1008                  * FIXME!!! We might do collision checking here, but we'd
1009                  * need to uncompress the old file and check it. Later.
1010                  */
1011                 close(fd);
1012                 return 0;
1013         }
1014
1015         if (errno != ENOENT) {
1016                 fprintf(stderr, "sha1 file %s: %s", filename, strerror(errno));
1017                 return -1;
1018         }
1019
1020         snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1021
1022         fd = mkstemp(tmpfile);
1023         if (fd < 0) {
1024                 fprintf(stderr, "unable to create temporary sha1 filename %s: %s", tmpfile, strerror(errno));
1025                 return -1;
1026         }
1027
1028         /* Set it up */
1029         memset(&stream, 0, sizeof(stream));
1030         deflateInit(&stream, Z_BEST_COMPRESSION);
1031         size = deflateBound(&stream, len+hdrlen);
1032         compressed = xmalloc(size);
1033
1034         /* Compress it */
1035         stream.next_out = compressed;
1036         stream.avail_out = size;
1037
1038         /* First header.. */
1039         stream.next_in = hdr;
1040         stream.avail_in = hdrlen;
1041         while (deflate(&stream, 0) == Z_OK)
1042                 /* nothing */;
1043
1044         /* Then the data itself.. */
1045         stream.next_in = buf;
1046         stream.avail_in = len;
1047         while (deflate(&stream, Z_FINISH) == Z_OK)
1048                 /* nothing */;
1049         deflateEnd(&stream);
1050         size = stream.total_out;
1051
1052         if (write(fd, compressed, size) != size)
1053                 die("unable to write file");
1054         fchmod(fd, 0444);
1055         close(fd);
1056         free(compressed);
1057
1058         ret = link(tmpfile, filename);
1059         if (ret < 0) {
1060                 ret = errno;
1061
1062                 /*
1063                  * Coda hack - coda doesn't like cross-directory links,
1064                  * so we fall back to a rename, which will mean that it
1065                  * won't be able to check collisions, but that's not a
1066                  * big deal.
1067                  *
1068                  * When this succeeds, we just return 0. We have nothing
1069                  * left to unlink.
1070                  */
1071                 if (ret == EXDEV && !rename(tmpfile, filename))
1072                         return 0;
1073         }
1074         unlink(tmpfile);
1075         if (ret) {
1076                 if (ret != EEXIST) {
1077                         fprintf(stderr, "unable to write sha1 filename %s: %s", filename, strerror(ret));
1078                         return -1;
1079                 }
1080                 /* FIXME!!! Collision check here ? */
1081         }
1082
1083         return 0;
1084 }
1085
1086 int write_sha1_from_fd(const unsigned char *sha1, int fd)
1087 {
1088         char *filename = sha1_file_name(sha1);
1089
1090         int local;
1091         z_stream stream;
1092         unsigned char real_sha1[20];
1093         unsigned char buf[4096];
1094         unsigned char discard[4096];
1095         int ret;
1096         SHA_CTX c;
1097
1098         local = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0666);
1099
1100         if (local < 0)
1101                 return error("Couldn't open %s\n", filename);
1102
1103         memset(&stream, 0, sizeof(stream));
1104
1105         inflateInit(&stream);
1106
1107         SHA1_Init(&c);
1108
1109         do {
1110                 ssize_t size;
1111                 size = read(fd, buf, 4096);
1112                 if (size <= 0) {
1113                         close(local);
1114                         unlink(filename);
1115                         if (!size)
1116                                 return error("Connection closed?");
1117                         perror("Reading from connection");
1118                         return -1;
1119                 }
1120                 write(local, buf, size);
1121                 stream.avail_in = size;
1122                 stream.next_in = buf;
1123                 do {
1124                         stream.next_out = discard;
1125                         stream.avail_out = sizeof(discard);
1126                         ret = inflate(&stream, Z_SYNC_FLUSH);
1127                         SHA1_Update(&c, discard, sizeof(discard) -
1128                                     stream.avail_out);
1129                 } while (stream.avail_in && ret == Z_OK);
1130                 
1131         } while (ret == Z_OK);
1132         inflateEnd(&stream);
1133
1134         close(local);
1135         SHA1_Final(real_sha1, &c);
1136         if (ret != Z_STREAM_END) {
1137                 unlink(filename);
1138                 return error("File %s corrupted", sha1_to_hex(sha1));
1139         }
1140         if (memcmp(sha1, real_sha1, 20)) {
1141                 unlink(filename);
1142                 return error("File %s has bad hash\n", sha1_to_hex(sha1));
1143         }
1144         
1145         return 0;
1146 }
1147
1148 int has_sha1_file(const unsigned char *sha1)
1149 {
1150         struct stat st;
1151         struct pack_entry e;
1152
1153         if (find_sha1_file(sha1, &st))
1154                 return 1;
1155         return find_pack_entry(sha1, &e);
1156 }
1157
1158 int index_fd(unsigned char *sha1, int fd, struct stat *st)
1159 {
1160         unsigned long size = st->st_size;
1161         void *buf;
1162         int ret;
1163
1164         buf = "";
1165         if (size)
1166                 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1167         close(fd);
1168         if ((int)(long)buf == -1)
1169                 return -1;
1170
1171         ret = write_sha1_file(buf, size, "blob", sha1);
1172         if (size)
1173                 munmap(buf, size);
1174         return ret;
1175 }