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