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