Merge branch 'jc/bindiff' into next
[git] / sha1_file.c
1 /*
2  * GIT - The information manager from hell
3  *
4  * Copyright (C) Linus Torvalds, 2005
5  *
6  * This handles basic git sha1 object files - packing, unpacking,
7  * creation etc.
8  */
9 #include "cache.h"
10 #include "delta.h"
11 #include "pack.h"
12 #include "blob.h"
13 #include "commit.h"
14 #include "tag.h"
15 #include "tree.h"
16
17 #ifndef O_NOATIME
18 #if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
19 #define O_NOATIME 01000000
20 #else
21 #define O_NOATIME 0
22 #endif
23 #endif
24
25 const unsigned char null_sha1[20] = { 0, };
26
27 static unsigned int sha1_file_open_flag = O_NOATIME;
28
29 static unsigned hexval(char c)
30 {
31         if (c >= '0' && c <= '9')
32                 return c - '0';
33         if (c >= 'a' && c <= 'f')
34                 return c - 'a' + 10;
35         if (c >= 'A' && c <= 'F')
36                 return c - 'A' + 10;
37         return ~0;
38 }
39
40 int get_sha1_hex(const char *hex, unsigned char *sha1)
41 {
42         int i;
43         for (i = 0; i < 20; i++) {
44                 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
45                 if (val & ~0xff)
46                         return -1;
47                 *sha1++ = val;
48                 hex += 2;
49         }
50         return 0;
51 }
52
53 int adjust_shared_perm(const char *path)
54 {
55         struct stat st;
56         int mode;
57
58         if (!shared_repository)
59                 return 0;
60         if (lstat(path, &st) < 0)
61                 return -1;
62         mode = st.st_mode;
63         if (mode & S_IRUSR)
64                 mode |= S_IRGRP;
65         if (mode & S_IWUSR)
66                 mode |= S_IWGRP;
67         if (mode & S_IXUSR)
68                 mode |= S_IXGRP;
69         if (S_ISDIR(mode))
70                 mode |= S_ISGID;
71         if (chmod(path, mode) < 0)
72                 return -2;
73         return 0;
74 }
75
76 int safe_create_leading_directories(char *path)
77 {
78         char *pos = path;
79         struct stat st;
80
81         if (*pos == '/')
82                 pos++;
83
84         while (pos) {
85                 pos = strchr(pos, '/');
86                 if (!pos)
87                         break;
88                 *pos = 0;
89                 if (!stat(path, &st)) {
90                         /* path exists */
91                         if (!S_ISDIR(st.st_mode)) {
92                                 *pos = '/';
93                                 return -3;
94                         }
95                 }
96                 else if (mkdir(path, 0777)) {
97                         *pos = '/';
98                         return -1;
99                 }
100                 else if (adjust_shared_perm(path)) {
101                         *pos = '/';
102                         return -2;
103                 }
104                 *pos++ = '/';
105         }
106         return 0;
107 }
108
109 char * sha1_to_hex(const unsigned char *sha1)
110 {
111         static int bufno;
112         static char hexbuffer[4][50];
113         static const char hex[] = "0123456789abcdef";
114         char *buffer = hexbuffer[3 & ++bufno], *buf = buffer;
115         int i;
116
117         for (i = 0; i < 20; i++) {
118                 unsigned int val = *sha1++;
119                 *buf++ = hex[val >> 4];
120                 *buf++ = hex[val & 0xf];
121         }
122         *buf = '\0';
123
124         return buffer;
125 }
126
127 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
128 {
129         int i;
130         for (i = 0; i < 20; i++) {
131                 static char hex[] = "0123456789abcdef";
132                 unsigned int val = sha1[i];
133                 char *pos = pathbuf + i*2 + (i > 0);
134                 *pos++ = hex[val >> 4];
135                 *pos = hex[val & 0xf];
136         }
137 }
138
139 /*
140  * NOTE! This returns a statically allocated buffer, so you have to be
141  * careful about using it. Do a "strdup()" if you need to save the
142  * filename.
143  *
144  * Also note that this returns the location for creating.  Reading
145  * SHA1 file can happen from any alternate directory listed in the
146  * DB_ENVIRONMENT environment variable if it is not found in
147  * the primary object database.
148  */
149 char *sha1_file_name(const unsigned char *sha1)
150 {
151         static char *name, *base;
152
153         if (!base) {
154                 const char *sha1_file_directory = get_object_directory();
155                 int len = strlen(sha1_file_directory);
156                 base = xmalloc(len + 60);
157                 memcpy(base, sha1_file_directory, len);
158                 memset(base+len, 0, 60);
159                 base[len] = '/';
160                 base[len+3] = '/';
161                 name = base + len + 1;
162         }
163         fill_sha1_path(name, sha1);
164         return base;
165 }
166
167 char *sha1_pack_name(const unsigned char *sha1)
168 {
169         static const char hex[] = "0123456789abcdef";
170         static char *name, *base, *buf;
171         int i;
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                 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.pack", sha1_file_directory);
178                 name = base + len + 11;
179         }
180
181         buf = name;
182
183         for (i = 0; i < 20; i++) {
184                 unsigned int val = *sha1++;
185                 *buf++ = hex[val >> 4];
186                 *buf++ = hex[val & 0xf];
187         }
188         
189         return base;
190 }
191
192 char *sha1_pack_index_name(const unsigned char *sha1)
193 {
194         static const char hex[] = "0123456789abcdef";
195         static char *name, *base, *buf;
196         int i;
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                 sprintf(base, "%s/pack/pack-1234567890123456789012345678901234567890.idx", sha1_file_directory);
203                 name = base + len + 11;
204         }
205
206         buf = name;
207
208         for (i = 0; i < 20; i++) {
209                 unsigned int val = *sha1++;
210                 *buf++ = hex[val >> 4];
211                 *buf++ = hex[val & 0xf];
212         }
213         
214         return base;
215 }
216
217 struct alternate_object_database *alt_odb_list;
218 static struct alternate_object_database **alt_odb_tail;
219
220 /*
221  * Prepare alternate object database registry.
222  *
223  * The variable alt_odb_list points at the list of struct
224  * alternate_object_database.  The elements on this list come from
225  * non-empty elements from colon separated ALTERNATE_DB_ENVIRONMENT
226  * environment variable, and $GIT_OBJECT_DIRECTORY/info/alternates,
227  * whose contents is similar to that environment variable but can be
228  * LF separated.  Its base points at a statically allocated buffer that
229  * contains "/the/directory/corresponding/to/.git/objects/...", while
230  * its name points just after the slash at the end of ".git/objects/"
231  * in the example above, and has enough space to hold 40-byte hex
232  * SHA1, an extra slash for the first level indirection, and the
233  * terminating NUL.
234  */
235 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
236                                  const char *relative_base)
237 {
238         const char *cp, *last;
239         struct alternate_object_database *ent;
240         const char *objdir = get_object_directory();
241         int base_len = -1;
242
243         last = alt;
244         while (last < ep) {
245                 cp = last;
246                 if (cp < ep && *cp == '#') {
247                         while (cp < ep && *cp != sep)
248                                 cp++;
249                         last = cp + 1;
250                         continue;
251                 }
252                 for ( ; cp < ep && *cp != sep; cp++)
253                         ;
254                 if (last != cp) {
255                         struct stat st;
256                         struct alternate_object_database *alt;
257                         /* 43 = 40-byte + 2 '/' + terminating NUL */
258                         int pfxlen = cp - last;
259                         int entlen = pfxlen + 43;
260
261                         if (*last != '/' && relative_base) {
262                                 /* Relative alt-odb */
263                                 if (base_len < 0)
264                                         base_len = strlen(relative_base) + 1;
265                                 entlen += base_len;
266                                 pfxlen += base_len;
267                         }
268                         ent = xmalloc(sizeof(*ent) + entlen);
269
270                         if (*last != '/' && relative_base) {
271                                 memcpy(ent->base, relative_base, base_len - 1);
272                                 ent->base[base_len - 1] = '/';
273                                 memcpy(ent->base + base_len,
274                                        last, cp - last);
275                         }
276                         else
277                                 memcpy(ent->base, last, pfxlen);
278
279                         ent->name = ent->base + pfxlen + 1;
280                         ent->base[pfxlen + 3] = '/';
281                         ent->base[pfxlen] = ent->base[entlen-1] = 0;
282
283                         /* Detect cases where alternate disappeared */
284                         if (stat(ent->base, &st) || !S_ISDIR(st.st_mode)) {
285                                 error("object directory %s does not exist; "
286                                       "check .git/objects/info/alternates.",
287                                       ent->base);
288                                 goto bad;
289                         }
290                         ent->base[pfxlen] = '/';
291
292                         /* Prevent the common mistake of listing the same
293                          * thing twice, or object directory itself.
294                          */
295                         for (alt = alt_odb_list; alt; alt = alt->next)
296                                 if (!memcmp(ent->base, alt->base, pfxlen))
297                                         goto bad;
298                         if (!memcmp(ent->base, objdir, pfxlen)) {
299                         bad:
300                                 free(ent);
301                         }
302                         else {
303                                 *alt_odb_tail = ent;
304                                 alt_odb_tail = &(ent->next);
305                                 ent->next = NULL;
306                         }
307                 }
308                 while (cp < ep && *cp == sep)
309                         cp++;
310                 last = cp;
311         }
312 }
313
314 void prepare_alt_odb(void)
315 {
316         char path[PATH_MAX];
317         char *map;
318         int fd;
319         struct stat st;
320         char *alt;
321
322         alt = getenv(ALTERNATE_DB_ENVIRONMENT);
323         if (!alt) alt = "";
324
325         if (alt_odb_tail)
326                 return;
327         alt_odb_tail = &alt_odb_list;
328         link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL);
329
330         sprintf(path, "%s/info/alternates", get_object_directory());
331         fd = open(path, O_RDONLY);
332         if (fd < 0)
333                 return;
334         if (fstat(fd, &st) || (st.st_size == 0)) {
335                 close(fd);
336                 return;
337         }
338         map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
339         close(fd);
340         if (map == MAP_FAILED)
341                 return;
342
343         link_alt_odb_entries(map, map + st.st_size, '\n',
344                              get_object_directory());
345         munmap(map, st.st_size);
346 }
347
348 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
349 {
350         char *name = sha1_file_name(sha1);
351         struct alternate_object_database *alt;
352
353         if (!stat(name, st))
354                 return name;
355         prepare_alt_odb();
356         for (alt = alt_odb_list; alt; alt = alt->next) {
357                 name = alt->name;
358                 fill_sha1_path(name, sha1);
359                 if (!stat(alt->base, st))
360                         return alt->base;
361         }
362         return NULL;
363 }
364
365 #define PACK_MAX_SZ (1<<26)
366 static int pack_used_ctr;
367 static unsigned long pack_mapped;
368 struct packed_git *packed_git;
369
370 static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
371                                 void **idx_map_)
372 {
373         void *idx_map;
374         unsigned int *index;
375         unsigned long idx_size;
376         int nr, i;
377         int fd = open(path, O_RDONLY);
378         struct stat st;
379         if (fd < 0)
380                 return -1;
381         if (fstat(fd, &st)) {
382                 close(fd);
383                 return -1;
384         }
385         idx_size = st.st_size;
386         idx_map = mmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
387         close(fd);
388         if (idx_map == MAP_FAILED)
389                 return -1;
390
391         index = idx_map;
392         *idx_map_ = idx_map;
393         *idx_size_ = idx_size;
394
395         /* check index map */
396         if (idx_size < 4*256 + 20 + 20)
397                 return error("index file too small");
398         nr = 0;
399         for (i = 0; i < 256; i++) {
400                 unsigned int n = ntohl(index[i]);
401                 if (n < nr)
402                         return error("non-monotonic index");
403                 nr = n;
404         }
405
406         /*
407          * Total size:
408          *  - 256 index entries 4 bytes each
409          *  - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
410          *  - 20-byte SHA1 of the packfile
411          *  - 20-byte SHA1 file checksum
412          */
413         if (idx_size != 4*256 + nr * 24 + 20 + 20)
414                 return error("wrong index file size");
415
416         return 0;
417 }
418
419 static int unuse_one_packed_git(void)
420 {
421         struct packed_git *p, *lru = NULL;
422
423         for (p = packed_git; p; p = p->next) {
424                 if (p->pack_use_cnt || !p->pack_base)
425                         continue;
426                 if (!lru || p->pack_last_used < lru->pack_last_used)
427                         lru = p;
428         }
429         if (!lru)
430                 return 0;
431         munmap(lru->pack_base, lru->pack_size);
432         lru->pack_base = NULL;
433         return 1;
434 }
435
436 void unuse_packed_git(struct packed_git *p)
437 {
438         p->pack_use_cnt--;
439 }
440
441 int use_packed_git(struct packed_git *p)
442 {
443         if (!p->pack_size) {
444                 struct stat st;
445                 // We created the struct before we had the pack
446                 stat(p->pack_name, &st);
447                 if (!S_ISREG(st.st_mode))
448                         die("packfile %s not a regular file", p->pack_name);
449                 p->pack_size = st.st_size;
450         }
451         if (!p->pack_base) {
452                 int fd;
453                 struct stat st;
454                 void *map;
455
456                 pack_mapped += p->pack_size;
457                 while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
458                         ; /* nothing */
459                 fd = open(p->pack_name, O_RDONLY);
460                 if (fd < 0)
461                         die("packfile %s cannot be opened", p->pack_name);
462                 if (fstat(fd, &st)) {
463                         close(fd);
464                         die("packfile %s cannot be opened", p->pack_name);
465                 }
466                 if (st.st_size != p->pack_size)
467                         die("packfile %s size mismatch.", p->pack_name);
468                 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
469                 close(fd);
470                 if (map == MAP_FAILED)
471                         die("packfile %s cannot be mapped.", p->pack_name);
472                 p->pack_base = map;
473
474                 /* Check if the pack file matches with the index file.
475                  * this is cheap.
476                  */
477                 if (memcmp((char*)(p->index_base) + p->index_size - 40,
478                            p->pack_base + p->pack_size - 20, 20)) {
479                               
480                         die("packfile %s does not match index.", p->pack_name);
481                 }
482         }
483         p->pack_last_used = pack_used_ctr++;
484         p->pack_use_cnt++;
485         return 0;
486 }
487
488 struct packed_git *add_packed_git(char *path, int path_len, int local)
489 {
490         struct stat st;
491         struct packed_git *p;
492         unsigned long idx_size;
493         void *idx_map;
494         unsigned char sha1[20];
495
496         if (check_packed_git_idx(path, &idx_size, &idx_map))
497                 return NULL;
498
499         /* do we have a corresponding .pack file? */
500         strcpy(path + path_len - 4, ".pack");
501         if (stat(path, &st) || !S_ISREG(st.st_mode)) {
502                 munmap(idx_map, idx_size);
503                 return NULL;
504         }
505         /* ok, it looks sane as far as we can check without
506          * actually mapping the pack file.
507          */
508         p = xmalloc(sizeof(*p) + path_len + 2);
509         strcpy(p->pack_name, path);
510         p->index_size = idx_size;
511         p->pack_size = st.st_size;
512         p->index_base = idx_map;
513         p->next = NULL;
514         p->pack_base = NULL;
515         p->pack_last_used = 0;
516         p->pack_use_cnt = 0;
517         p->pack_local = local;
518         if ((path_len > 44) && !get_sha1_hex(path + path_len - 44, sha1))
519                 memcpy(p->sha1, sha1, 20);
520         return p;
521 }
522
523 struct packed_git *parse_pack_index(unsigned char *sha1)
524 {
525         char *path = sha1_pack_index_name(sha1);
526         return parse_pack_index_file(sha1, path);
527 }
528
529 struct packed_git *parse_pack_index_file(const unsigned char *sha1, char *idx_path)
530 {
531         struct packed_git *p;
532         unsigned long idx_size;
533         void *idx_map;
534         char *path;
535
536         if (check_packed_git_idx(idx_path, &idx_size, &idx_map))
537                 return NULL;
538
539         path = sha1_pack_name(sha1);
540
541         p = xmalloc(sizeof(*p) + strlen(path) + 2);
542         strcpy(p->pack_name, path);
543         p->index_size = idx_size;
544         p->pack_size = 0;
545         p->index_base = idx_map;
546         p->next = NULL;
547         p->pack_base = NULL;
548         p->pack_last_used = 0;
549         p->pack_use_cnt = 0;
550         memcpy(p->sha1, sha1, 20);
551         return p;
552 }
553
554 void install_packed_git(struct packed_git *pack)
555 {
556         pack->next = packed_git;
557         packed_git = pack;
558 }
559
560 static void prepare_packed_git_one(char *objdir, int local)
561 {
562         char path[PATH_MAX];
563         int len;
564         DIR *dir;
565         struct dirent *de;
566
567         sprintf(path, "%s/pack", objdir);
568         len = strlen(path);
569         dir = opendir(path);
570         if (!dir) {
571                 if (errno != ENOENT)
572                         error("unable to open object pack directory: %s: %s",
573                               path, strerror(errno));
574                 return;
575         }
576         path[len++] = '/';
577         while ((de = readdir(dir)) != NULL) {
578                 int namelen = strlen(de->d_name);
579                 struct packed_git *p;
580
581                 if (strcmp(de->d_name + namelen - 4, ".idx"))
582                         continue;
583
584                 /* we have .idx.  Is it a file we can map? */
585                 strcpy(path + len, de->d_name);
586                 p = add_packed_git(path, len + namelen, local);
587                 if (!p)
588                         continue;
589                 p->next = packed_git;
590                 packed_git = p;
591         }
592         closedir(dir);
593 }
594
595 void prepare_packed_git(void)
596 {
597         static int run_once = 0;
598         struct alternate_object_database *alt;
599
600         if (run_once)
601                 return;
602         prepare_packed_git_one(get_object_directory(), 1);
603         prepare_alt_odb();
604         for (alt = alt_odb_list; alt; alt = alt->next) {
605                 alt->name[-1] = 0;
606                 prepare_packed_git_one(alt->base, 0);
607                 alt->name[-1] = '/';
608         }
609         run_once = 1;
610 }
611
612 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
613 {
614         char header[100];
615         unsigned char real_sha1[20];
616         SHA_CTX c;
617
618         SHA1_Init(&c);
619         SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
620         SHA1_Update(&c, map, size);
621         SHA1_Final(real_sha1, &c);
622         return memcmp(sha1, real_sha1, 20) ? -1 : 0;
623 }
624
625 static void *map_sha1_file_internal(const unsigned char *sha1,
626                                     unsigned long *size)
627 {
628         struct stat st;
629         void *map;
630         int fd;
631         char *filename = find_sha1_file(sha1, &st);
632
633         if (!filename) {
634                 return NULL;
635         }
636
637         fd = open(filename, O_RDONLY | sha1_file_open_flag);
638         if (fd < 0) {
639                 /* See if it works without O_NOATIME */
640                 switch (sha1_file_open_flag) {
641                 default:
642                         fd = open(filename, O_RDONLY);
643                         if (fd >= 0)
644                                 break;
645                 /* Fallthrough */
646                 case 0:
647                         return NULL;
648                 }
649
650                 /* If it failed once, it will probably fail again.
651                  * Stop using O_NOATIME
652                  */
653                 sha1_file_open_flag = 0;
654         }
655         map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
656         close(fd);
657         if (map == MAP_FAILED)
658                 return NULL;
659         *size = st.st_size;
660         return map;
661 }
662
663 int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
664 {
665         /* Get the data stream */
666         memset(stream, 0, sizeof(*stream));
667         stream->next_in = map;
668         stream->avail_in = mapsize;
669         stream->next_out = buffer;
670         stream->avail_out = size;
671
672         inflateInit(stream);
673         return inflate(stream, 0);
674 }
675
676 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
677 {
678         int bytes = strlen(buffer) + 1;
679         unsigned char *buf = xmalloc(1+size);
680
681         memcpy(buf, buffer + bytes, stream->total_out - bytes);
682         bytes = stream->total_out - bytes;
683         if (bytes < size) {
684                 stream->next_out = buf + bytes;
685                 stream->avail_out = size - bytes;
686                 while (inflate(stream, Z_FINISH) == Z_OK)
687                         /* nothing */;
688         }
689         buf[size] = 0;
690         inflateEnd(stream);
691         return buf;
692 }
693
694 /*
695  * We used to just use "sscanf()", but that's actually way
696  * too permissive for what we want to check. So do an anal
697  * object header parse by hand.
698  */
699 int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
700 {
701         int i;
702         unsigned long size;
703
704         /*
705          * The type can be at most ten bytes (including the 
706          * terminating '\0' that we add), and is followed by
707          * a space. 
708          */
709         i = 10;
710         for (;;) {
711                 char c = *hdr++;
712                 if (c == ' ')
713                         break;
714                 if (!--i)
715                         return -1;
716                 *type++ = c;
717         }
718         *type = 0;
719
720         /*
721          * The length must follow immediately, and be in canonical
722          * decimal format (ie "010" is not valid).
723          */
724         size = *hdr++ - '0';
725         if (size > 9)
726                 return -1;
727         if (size) {
728                 for (;;) {
729                         unsigned long c = *hdr - '0';
730                         if (c > 9)
731                                 break;
732                         hdr++;
733                         size = size * 10 + c;
734                 }
735         }
736         *sizep = size;
737
738         /*
739          * The length must be followed by a zero byte
740          */
741         return *hdr ? -1 : 0;
742 }
743
744 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
745 {
746         int ret;
747         z_stream stream;
748         char hdr[8192];
749
750         ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
751         if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
752                 return NULL;
753
754         return unpack_sha1_rest(&stream, hdr, *size);
755 }
756
757 /* forward declaration for a mutually recursive function */
758 static int packed_object_info(struct pack_entry *entry,
759                               char *type, unsigned long *sizep);
760
761 static int packed_delta_info(unsigned char *base_sha1,
762                              unsigned long delta_size,
763                              unsigned long left,
764                              char *type,
765                              unsigned long *sizep,
766                              struct packed_git *p)
767 {
768         struct pack_entry base_ent;
769
770         if (left < 20)
771                 die("truncated pack file");
772
773         /* The base entry _must_ be in the same pack */
774         if (!find_pack_entry_one(base_sha1, &base_ent, p))
775                 die("failed to find delta-pack base object %s",
776                     sha1_to_hex(base_sha1));
777
778         /* We choose to only get the type of the base object and
779          * ignore potentially corrupt pack file that expects the delta
780          * based on a base with a wrong size.  This saves tons of
781          * inflate() calls.
782          */
783
784         if (packed_object_info(&base_ent, type, NULL))
785                 die("cannot get info for delta-pack base");
786
787         if (sizep) {
788                 const unsigned char *data;
789                 unsigned char delta_head[64];
790                 unsigned long result_size;
791                 z_stream stream;
792                 int st;
793
794                 memset(&stream, 0, sizeof(stream));
795
796                 data = stream.next_in = base_sha1 + 20;
797                 stream.avail_in = left - 20;
798                 stream.next_out = delta_head;
799                 stream.avail_out = sizeof(delta_head);
800
801                 inflateInit(&stream);
802                 st = inflate(&stream, Z_FINISH);
803                 inflateEnd(&stream);
804                 if ((st != Z_STREAM_END) &&
805                     stream.total_out != sizeof(delta_head))
806                         die("delta data unpack-initial failed");
807
808                 /* Examine the initial part of the delta to figure out
809                  * the result size.
810                  */
811                 data = delta_head;
812
813                 /* ignore base size */
814                 get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
815
816                 /* Read the result size */
817                 result_size = get_delta_hdr_size(&data, delta_head+sizeof(delta_head));
818                 *sizep = result_size;
819         }
820         return 0;
821 }
822
823 static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
824         enum object_type *type, unsigned long *sizep)
825 {
826         unsigned shift;
827         unsigned char *pack, c;
828         unsigned long size;
829
830         if (offset >= p->pack_size)
831                 die("object offset outside of pack file");
832
833         pack =  p->pack_base + offset;
834         c = *pack++;
835         offset++;
836         *type = (c >> 4) & 7;
837         size = c & 15;
838         shift = 4;
839         while (c & 0x80) {
840                 if (offset >= p->pack_size)
841                         die("object offset outside of pack file");
842                 c = *pack++;
843                 offset++;
844                 size += (c & 0x7f) << shift;
845                 shift += 7;
846         }
847         *sizep = size;
848         return offset;
849 }
850
851 int check_reuse_pack_delta(struct packed_git *p, unsigned long offset,
852                            unsigned char *base, unsigned long *sizep,
853                            enum object_type *kindp)
854 {
855         unsigned long ptr;
856         int status = -1;
857
858         use_packed_git(p);
859         ptr = offset;
860         ptr = unpack_object_header(p, ptr, kindp, sizep);
861         if (*kindp != OBJ_DELTA)
862                 goto done;
863         memcpy(base, p->pack_base + ptr, 20);
864         status = 0;
865  done:
866         unuse_packed_git(p);
867         return status;
868 }
869
870 void packed_object_info_detail(struct pack_entry *e,
871                                char *type,
872                                unsigned long *size,
873                                unsigned long *store_size,
874                                unsigned int *delta_chain_length,
875                                unsigned char *base_sha1)
876 {
877         struct packed_git *p = e->p;
878         unsigned long offset;
879         unsigned char *pack;
880         enum object_type kind;
881
882         offset = unpack_object_header(p, e->offset, &kind, size);
883         pack = p->pack_base + offset;
884         if (kind != OBJ_DELTA)
885                 *delta_chain_length = 0;
886         else {
887                 unsigned int chain_length = 0;
888                 if (p->pack_size <= offset + 20)
889                         die("pack file %s records an incomplete delta base",
890                             p->pack_name);
891                 memcpy(base_sha1, pack, 20);
892                 do {
893                         struct pack_entry base_ent;
894                         unsigned long junk;
895
896                         find_pack_entry_one(pack, &base_ent, p);
897                         offset = unpack_object_header(p, base_ent.offset,
898                                                       &kind, &junk);
899                         pack = p->pack_base + offset;
900                         chain_length++;
901                 } while (kind == OBJ_DELTA);
902                 *delta_chain_length = chain_length;
903         }
904         switch (kind) {
905         case OBJ_COMMIT:
906                 strcpy(type, commit_type);
907                 break;
908         case OBJ_TREE:
909                 strcpy(type, tree_type);
910                 break;
911         case OBJ_BLOB:
912                 strcpy(type, blob_type);
913                 break;
914         case OBJ_TAG:
915                 strcpy(type, tag_type);
916                 break;
917         default:
918                 die("corrupted pack file %s containing object of kind %d",
919                     p->pack_name, kind);
920         }
921         *store_size = 0; /* notyet */
922 }
923
924 static int packed_object_info(struct pack_entry *entry,
925                               char *type, unsigned long *sizep)
926 {
927         struct packed_git *p = entry->p;
928         unsigned long offset, size, left;
929         unsigned char *pack;
930         enum object_type kind;
931         int retval;
932
933         if (use_packed_git(p))
934                 die("cannot map packed file");
935
936         offset = unpack_object_header(p, entry->offset, &kind, &size);
937         pack = p->pack_base + offset;
938         left = p->pack_size - offset;
939
940         switch (kind) {
941         case OBJ_DELTA:
942                 retval = packed_delta_info(pack, size, left, type, sizep, p);
943                 unuse_packed_git(p);
944                 return retval;
945         case OBJ_COMMIT:
946                 strcpy(type, commit_type);
947                 break;
948         case OBJ_TREE:
949                 strcpy(type, tree_type);
950                 break;
951         case OBJ_BLOB:
952                 strcpy(type, blob_type);
953                 break;
954         case OBJ_TAG:
955                 strcpy(type, tag_type);
956                 break;
957         default:
958                 die("corrupted pack file %s containing object of kind %d",
959                     p->pack_name, kind);
960         }
961         if (sizep)
962                 *sizep = size;
963         unuse_packed_git(p);
964         return 0;
965 }
966
967 /* forward declaration for a mutually recursive function */
968 static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
969
970 static void *unpack_delta_entry(unsigned char *base_sha1,
971                                 unsigned long delta_size,
972                                 unsigned long left,
973                                 char *type,
974                                 unsigned long *sizep,
975                                 struct packed_git *p)
976 {
977         struct pack_entry base_ent;
978         void *data, *delta_data, *result, *base;
979         unsigned long data_size, result_size, base_size;
980         z_stream stream;
981         int st;
982
983         if (left < 20)
984                 die("truncated pack file");
985
986         /* The base entry _must_ be in the same pack */
987         if (!find_pack_entry_one(base_sha1, &base_ent, p))
988                 die("failed to find delta-pack base object %s",
989                     sha1_to_hex(base_sha1));
990         base = unpack_entry_gently(&base_ent, type, &base_size);
991         if (!base)
992                 die("failed to read delta-pack base object %s",
993                     sha1_to_hex(base_sha1));
994
995         data = base_sha1 + 20;
996         data_size = left - 20;
997         delta_data = xmalloc(delta_size);
998
999         memset(&stream, 0, sizeof(stream));
1000
1001         stream.next_in = data;
1002         stream.avail_in = data_size;
1003         stream.next_out = delta_data;
1004         stream.avail_out = delta_size;
1005
1006         inflateInit(&stream);
1007         st = inflate(&stream, Z_FINISH);
1008         inflateEnd(&stream);
1009         if ((st != Z_STREAM_END) || stream.total_out != delta_size)
1010                 die("delta data unpack failed");
1011
1012         result = patch_delta(base, base_size,
1013                              delta_data, delta_size,
1014                              &result_size);
1015         if (!result)
1016                 die("failed to apply delta");
1017         free(delta_data);
1018         free(base);
1019         *sizep = result_size;
1020         return result;
1021 }
1022
1023 static void *unpack_non_delta_entry(unsigned char *data,
1024                                     unsigned long size,
1025                                     unsigned long left)
1026 {
1027         int st;
1028         z_stream stream;
1029         unsigned char *buffer;
1030
1031         buffer = xmalloc(size + 1);
1032         buffer[size] = 0;
1033         memset(&stream, 0, sizeof(stream));
1034         stream.next_in = data;
1035         stream.avail_in = left;
1036         stream.next_out = buffer;
1037         stream.avail_out = size;
1038
1039         inflateInit(&stream);
1040         st = inflate(&stream, Z_FINISH);
1041         inflateEnd(&stream);
1042         if ((st != Z_STREAM_END) || stream.total_out != size) {
1043                 free(buffer);
1044                 return NULL;
1045         }
1046
1047         return buffer;
1048 }
1049
1050 static void *unpack_entry(struct pack_entry *entry,
1051                           char *type, unsigned long *sizep)
1052 {
1053         struct packed_git *p = entry->p;
1054         void *retval;
1055
1056         if (use_packed_git(p))
1057                 die("cannot map packed file");
1058         retval = unpack_entry_gently(entry, type, sizep);
1059         unuse_packed_git(p);
1060         if (!retval)
1061                 die("corrupted pack file %s", p->pack_name);
1062         return retval;
1063 }
1064
1065 /* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
1066 void *unpack_entry_gently(struct pack_entry *entry,
1067                           char *type, unsigned long *sizep)
1068 {
1069         struct packed_git *p = entry->p;
1070         unsigned long offset, size, left;
1071         unsigned char *pack;
1072         enum object_type kind;
1073         void *retval;
1074
1075         offset = unpack_object_header(p, entry->offset, &kind, &size);
1076         pack = p->pack_base + offset;
1077         left = p->pack_size - offset;
1078         switch (kind) {
1079         case OBJ_DELTA:
1080                 retval = unpack_delta_entry(pack, size, left, type, sizep, p);
1081                 return retval;
1082         case OBJ_COMMIT:
1083                 strcpy(type, commit_type);
1084                 break;
1085         case OBJ_TREE:
1086                 strcpy(type, tree_type);
1087                 break;
1088         case OBJ_BLOB:
1089                 strcpy(type, blob_type);
1090                 break;
1091         case OBJ_TAG:
1092                 strcpy(type, tag_type);
1093                 break;
1094         default:
1095                 return NULL;
1096         }
1097         *sizep = size;
1098         retval = unpack_non_delta_entry(pack, size, left);
1099         return retval;
1100 }
1101
1102 int num_packed_objects(const struct packed_git *p)
1103 {
1104         /* See check_packed_git_idx() */
1105         return (p->index_size - 20 - 20 - 4*256) / 24;
1106 }
1107
1108 int nth_packed_object_sha1(const struct packed_git *p, int n,
1109                            unsigned char* sha1)
1110 {
1111         void *index = p->index_base + 256;
1112         if (n < 0 || num_packed_objects(p) <= n)
1113                 return -1;
1114         memcpy(sha1, (index + 24 * n + 4), 20);
1115         return 0;
1116 }
1117
1118 int find_pack_entry_one(const unsigned char *sha1,
1119                         struct pack_entry *e, struct packed_git *p)
1120 {
1121         unsigned int *level1_ofs = p->index_base;
1122         int hi = ntohl(level1_ofs[*sha1]);
1123         int lo = ((*sha1 == 0x0) ? 0 : ntohl(level1_ofs[*sha1 - 1]));
1124         void *index = p->index_base + 256;
1125
1126         do {
1127                 int mi = (lo + hi) / 2;
1128                 int cmp = memcmp(index + 24 * mi + 4, sha1, 20);
1129                 if (!cmp) {
1130                         e->offset = ntohl(*((int*)(index + 24 * mi)));
1131                         memcpy(e->sha1, sha1, 20);
1132                         e->p = p;
1133                         return 1;
1134                 }
1135                 if (cmp > 0)
1136                         hi = mi;
1137                 else
1138                         lo = mi+1;
1139         } while (lo < hi);
1140         return 0;
1141 }
1142
1143 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1144 {
1145         struct packed_git *p;
1146         prepare_packed_git();
1147
1148         for (p = packed_git; p; p = p->next) {
1149                 if (find_pack_entry_one(sha1, e, p))
1150                         return 1;
1151         }
1152         return 0;
1153 }
1154
1155 struct packed_git *find_sha1_pack(const unsigned char *sha1, 
1156                                   struct packed_git *packs)
1157 {
1158         struct packed_git *p;
1159         struct pack_entry e;
1160
1161         for (p = packs; p; p = p->next) {
1162                 if (find_pack_entry_one(sha1, &e, p))
1163                         return p;
1164         }
1165         return NULL;
1166         
1167 }
1168
1169 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1170 {
1171         int status;
1172         unsigned long mapsize, size;
1173         void *map;
1174         z_stream stream;
1175         char hdr[128];
1176
1177         map = map_sha1_file_internal(sha1, &mapsize);
1178         if (!map) {
1179                 struct pack_entry e;
1180
1181                 if (!find_pack_entry(sha1, &e))
1182                         return error("unable to find %s", sha1_to_hex(sha1));
1183                 return packed_object_info(&e, type, sizep);
1184         }
1185         if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
1186                 status = error("unable to unpack %s header",
1187                                sha1_to_hex(sha1));
1188         if (parse_sha1_header(hdr, type, &size) < 0)
1189                 status = error("unable to parse %s header", sha1_to_hex(sha1));
1190         else {
1191                 status = 0;
1192                 if (sizep)
1193                         *sizep = size;
1194         }
1195         inflateEnd(&stream);
1196         munmap(map, mapsize);
1197         return status;
1198 }
1199
1200 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1201 {
1202         struct pack_entry e;
1203
1204         if (!find_pack_entry(sha1, &e)) {
1205                 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1206                 return NULL;
1207         }
1208         return unpack_entry(&e, type, size);
1209 }
1210
1211 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1212 {
1213         unsigned long mapsize;
1214         void *map, *buf;
1215         struct pack_entry e;
1216
1217         if (find_pack_entry(sha1, &e))
1218                 return read_packed_sha1(sha1, type, size);
1219         map = map_sha1_file_internal(sha1, &mapsize);
1220         if (map) {
1221                 buf = unpack_sha1_file(map, mapsize, type, size);
1222                 munmap(map, mapsize);
1223                 return buf;
1224         }
1225         return NULL;
1226 }
1227
1228 void *read_object_with_reference(const unsigned char *sha1,
1229                                  const char *required_type,
1230                                  unsigned long *size,
1231                                  unsigned char *actual_sha1_return)
1232 {
1233         char type[20];
1234         void *buffer;
1235         unsigned long isize;
1236         unsigned char actual_sha1[20];
1237
1238         memcpy(actual_sha1, sha1, 20);
1239         while (1) {
1240                 int ref_length = -1;
1241                 const char *ref_type = NULL;
1242
1243                 buffer = read_sha1_file(actual_sha1, type, &isize);
1244                 if (!buffer)
1245                         return NULL;
1246                 if (!strcmp(type, required_type)) {
1247                         *size = isize;
1248                         if (actual_sha1_return)
1249                                 memcpy(actual_sha1_return, actual_sha1, 20);
1250                         return buffer;
1251                 }
1252                 /* Handle references */
1253                 else if (!strcmp(type, commit_type))
1254                         ref_type = "tree ";
1255                 else if (!strcmp(type, tag_type))
1256                         ref_type = "object ";
1257                 else {
1258                         free(buffer);
1259                         return NULL;
1260                 }
1261                 ref_length = strlen(ref_type);
1262
1263                 if (memcmp(buffer, ref_type, ref_length) ||
1264                     get_sha1_hex(buffer + ref_length, actual_sha1)) {
1265                         free(buffer);
1266                         return NULL;
1267                 }
1268                 free(buffer);
1269                 /* Now we have the ID of the referred-to object in
1270                  * actual_sha1.  Check again. */
1271         }
1272 }
1273
1274 char *write_sha1_file_prepare(void *buf,
1275                               unsigned long len,
1276                               const char *type,
1277                               unsigned char *sha1,
1278                               unsigned char *hdr,
1279                               int *hdrlen)
1280 {
1281         SHA_CTX c;
1282
1283         /* Generate the header */
1284         *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1285
1286         /* Sha1.. */
1287         SHA1_Init(&c);
1288         SHA1_Update(&c, hdr, *hdrlen);
1289         SHA1_Update(&c, buf, len);
1290         SHA1_Final(sha1, &c);
1291
1292         return sha1_file_name(sha1);
1293 }
1294
1295 /*
1296  * Link the tempfile to the final place, possibly creating the
1297  * last directory level as you do so.
1298  *
1299  * Returns the errno on failure, 0 on success.
1300  */
1301 static int link_temp_to_file(const char *tmpfile, char *filename)
1302 {
1303         int ret;
1304
1305         if (!link(tmpfile, filename))
1306                 return 0;
1307
1308         /*
1309          * Try to mkdir the last path component if that failed
1310          * with an ENOENT.
1311          *
1312          * Re-try the "link()" regardless of whether the mkdir
1313          * succeeds, since a race might mean that somebody
1314          * else succeeded.
1315          */
1316         ret = errno;
1317         if (ret == ENOENT) {
1318                 char *dir = strrchr(filename, '/');
1319                 if (dir) {
1320                         *dir = 0;
1321                         mkdir(filename, 0777);
1322                         if (adjust_shared_perm(filename))
1323                                 return -2;
1324                         *dir = '/';
1325                         if (!link(tmpfile, filename))
1326                                 return 0;
1327                         ret = errno;
1328                 }
1329         }
1330         return ret;
1331 }
1332
1333 /*
1334  * Move the just written object into its final resting place
1335  */
1336 int move_temp_to_file(const char *tmpfile, char *filename)
1337 {
1338         int ret = link_temp_to_file(tmpfile, filename);
1339
1340         /*
1341          * Coda hack - coda doesn't like cross-directory links,
1342          * so we fall back to a rename, which will mean that it
1343          * won't be able to check collisions, but that's not a
1344          * big deal.
1345          *
1346          * The same holds for FAT formatted media.
1347          *
1348          * When this succeeds, we just return 0. We have nothing
1349          * left to unlink.
1350          */
1351         if (ret && ret != EEXIST) {
1352                 if (!rename(tmpfile, filename))
1353                         return 0;
1354                 ret = errno;
1355         }
1356         unlink(tmpfile);
1357         if (ret) {
1358                 if (ret != EEXIST) {
1359                         fprintf(stderr, "unable to write sha1 filename %s: %s\n", filename, strerror(ret));
1360                         return -1;
1361                 }
1362                 /* FIXME!!! Collision check here ? */
1363         }
1364
1365         return 0;
1366 }
1367
1368 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1369 {
1370         int size;
1371         unsigned char *compressed;
1372         z_stream stream;
1373         unsigned char sha1[20];
1374         char *filename;
1375         static char tmpfile[PATH_MAX];
1376         unsigned char hdr[50];
1377         int fd, hdrlen;
1378
1379         /* Normally if we have it in the pack then we do not bother writing
1380          * it out into .git/objects/??/?{38} file.
1381          */
1382         filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1383         if (returnsha1)
1384                 memcpy(returnsha1, sha1, 20);
1385         if (has_sha1_file(sha1))
1386                 return 0;
1387         fd = open(filename, O_RDONLY);
1388         if (fd >= 0) {
1389                 /*
1390                  * FIXME!!! We might do collision checking here, but we'd
1391                  * need to uncompress the old file and check it. Later.
1392                  */
1393                 close(fd);
1394                 return 0;
1395         }
1396
1397         if (errno != ENOENT) {
1398                 fprintf(stderr, "sha1 file %s: %s\n", filename, strerror(errno));
1399                 return -1;
1400         }
1401
1402         snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1403
1404         fd = mkstemp(tmpfile);
1405         if (fd < 0) {
1406                 fprintf(stderr, "unable to create temporary sha1 filename %s: %s\n", tmpfile, strerror(errno));
1407                 return -1;
1408         }
1409
1410         /* Set it up */
1411         memset(&stream, 0, sizeof(stream));
1412         deflateInit(&stream, Z_BEST_COMPRESSION);
1413         size = deflateBound(&stream, len+hdrlen);
1414         compressed = xmalloc(size);
1415
1416         /* Compress it */
1417         stream.next_out = compressed;
1418         stream.avail_out = size;
1419
1420         /* First header.. */
1421         stream.next_in = hdr;
1422         stream.avail_in = hdrlen;
1423         while (deflate(&stream, 0) == Z_OK)
1424                 /* nothing */;
1425
1426         /* Then the data itself.. */
1427         stream.next_in = buf;
1428         stream.avail_in = len;
1429         while (deflate(&stream, Z_FINISH) == Z_OK)
1430                 /* nothing */;
1431         deflateEnd(&stream);
1432         size = stream.total_out;
1433
1434         if (write(fd, compressed, size) != size)
1435                 die("unable to write file");
1436         fchmod(fd, 0444);
1437         close(fd);
1438         free(compressed);
1439
1440         return move_temp_to_file(tmpfile, filename);
1441 }
1442
1443 int write_sha1_to_fd(int fd, const unsigned char *sha1)
1444 {
1445         ssize_t size;
1446         unsigned long objsize;
1447         int posn = 0;
1448         void *map = map_sha1_file_internal(sha1, &objsize);
1449         void *buf = map;
1450         void *temp_obj = NULL;
1451         z_stream stream;
1452
1453         if (!buf) {
1454                 unsigned char *unpacked;
1455                 unsigned long len;
1456                 char type[20];
1457                 char hdr[50];
1458                 int hdrlen;
1459                 // need to unpack and recompress it by itself
1460                 unpacked = read_packed_sha1(sha1, type, &len);
1461
1462                 hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
1463
1464                 /* Set it up */
1465                 memset(&stream, 0, sizeof(stream));
1466                 deflateInit(&stream, Z_BEST_COMPRESSION);
1467                 size = deflateBound(&stream, len + hdrlen);
1468                 temp_obj = buf = xmalloc(size);
1469
1470                 /* Compress it */
1471                 stream.next_out = buf;
1472                 stream.avail_out = size;
1473                 
1474                 /* First header.. */
1475                 stream.next_in = (void *)hdr;
1476                 stream.avail_in = hdrlen;
1477                 while (deflate(&stream, 0) == Z_OK)
1478                         /* nothing */;
1479
1480                 /* Then the data itself.. */
1481                 stream.next_in = unpacked;
1482                 stream.avail_in = len;
1483                 while (deflate(&stream, Z_FINISH) == Z_OK)
1484                         /* nothing */;
1485                 deflateEnd(&stream);
1486                 free(unpacked);
1487                 
1488                 objsize = stream.total_out;
1489         }
1490
1491         do {
1492                 size = write(fd, buf + posn, objsize - posn);
1493                 if (size <= 0) {
1494                         if (!size) {
1495                                 fprintf(stderr, "write closed\n");
1496                         } else {
1497                                 perror("write ");
1498                         }
1499                         return -1;
1500                 }
1501                 posn += size;
1502         } while (posn < objsize);
1503
1504         if (map)
1505                 munmap(map, objsize);
1506         if (temp_obj)
1507                 free(temp_obj);
1508
1509         return 0;
1510 }
1511
1512 int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
1513                        size_t bufsize, size_t *bufposn)
1514 {
1515         char tmpfile[PATH_MAX];
1516         int local;
1517         z_stream stream;
1518         unsigned char real_sha1[20];
1519         unsigned char discard[4096];
1520         int ret;
1521         SHA_CTX c;
1522
1523         snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1524
1525         local = mkstemp(tmpfile);
1526         if (local < 0)
1527                 return error("Couldn't open %s for %s",
1528                              tmpfile, sha1_to_hex(sha1));
1529
1530         memset(&stream, 0, sizeof(stream));
1531
1532         inflateInit(&stream);
1533
1534         SHA1_Init(&c);
1535
1536         do {
1537                 ssize_t size;
1538                 if (*bufposn) {
1539                         stream.avail_in = *bufposn;
1540                         stream.next_in = (unsigned char *) buffer;
1541                         do {
1542                                 stream.next_out = discard;
1543                                 stream.avail_out = sizeof(discard);
1544                                 ret = inflate(&stream, Z_SYNC_FLUSH);
1545                                 SHA1_Update(&c, discard, sizeof(discard) -
1546                                             stream.avail_out);
1547                         } while (stream.avail_in && ret == Z_OK);
1548                         write(local, buffer, *bufposn - stream.avail_in);
1549                         memmove(buffer, buffer + *bufposn - stream.avail_in,
1550                                 stream.avail_in);
1551                         *bufposn = stream.avail_in;
1552                         if (ret != Z_OK)
1553                                 break;
1554                 }
1555                 size = read(fd, buffer + *bufposn, bufsize - *bufposn);
1556                 if (size <= 0) {
1557                         close(local);
1558                         unlink(tmpfile);
1559                         if (!size)
1560                                 return error("Connection closed?");
1561                         perror("Reading from connection");
1562                         return -1;
1563                 }
1564                 *bufposn += size;
1565         } while (1);
1566         inflateEnd(&stream);
1567
1568         close(local);
1569         SHA1_Final(real_sha1, &c);
1570         if (ret != Z_STREAM_END) {
1571                 unlink(tmpfile);
1572                 return error("File %s corrupted", sha1_to_hex(sha1));
1573         }
1574         if (memcmp(sha1, real_sha1, 20)) {
1575                 unlink(tmpfile);
1576                 return error("File %s has bad hash", sha1_to_hex(sha1));
1577         }
1578
1579         return move_temp_to_file(tmpfile, sha1_file_name(sha1));
1580 }
1581
1582 int has_pack_index(const unsigned char *sha1)
1583 {
1584         struct stat st;
1585         if (stat(sha1_pack_index_name(sha1), &st))
1586                 return 0;
1587         return 1;
1588 }
1589
1590 int has_pack_file(const unsigned char *sha1)
1591 {
1592         struct stat st;
1593         if (stat(sha1_pack_name(sha1), &st))
1594                 return 0;
1595         return 1;
1596 }
1597
1598 int has_sha1_pack(const unsigned char *sha1)
1599 {
1600         struct pack_entry e;
1601         return find_pack_entry(sha1, &e);
1602 }
1603
1604 int has_sha1_file(const unsigned char *sha1)
1605 {
1606         struct stat st;
1607         struct pack_entry e;
1608
1609         if (find_pack_entry(sha1, &e))
1610                 return 1;
1611         return find_sha1_file(sha1, &st) ? 1 : 0;
1612 }
1613
1614 int index_pipe(unsigned char *sha1, int fd, const char *type, int write_object)
1615 {
1616         unsigned long size = 4096;
1617         char *buf = malloc(size);
1618         int iret, ret;
1619         unsigned long off = 0;
1620         unsigned char hdr[50];
1621         int hdrlen;
1622         do {
1623                 iret = read(fd, buf + off, size - off);
1624                 if (iret > 0) {
1625                         off += iret;
1626                         if (off == size) {
1627                                 size *= 2;
1628                                 buf = realloc(buf, size);
1629                         }
1630                 }
1631         } while (iret > 0);
1632         if (iret < 0) {
1633                 free(buf);
1634                 return -1;
1635         }
1636         if (!type)
1637                 type = blob_type;
1638         if (write_object)
1639                 ret = write_sha1_file(buf, off, type, sha1);
1640         else {
1641                 write_sha1_file_prepare(buf, off, type, sha1, hdr, &hdrlen);
1642                 ret = 0;
1643         }
1644         free(buf);
1645         return ret;
1646 }
1647
1648 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
1649 {
1650         unsigned long size = st->st_size;
1651         void *buf;
1652         int ret;
1653         unsigned char hdr[50];
1654         int hdrlen;
1655
1656         buf = "";
1657         if (size)
1658                 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1659         close(fd);
1660         if (buf == MAP_FAILED)
1661                 return -1;
1662
1663         if (!type)
1664                 type = blob_type;
1665         if (write_object)
1666                 ret = write_sha1_file(buf, size, type, sha1);
1667         else {
1668                 write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1669                 ret = 0;
1670         }
1671         if (size)
1672                 munmap(buf, size);
1673         return ret;
1674 }
1675
1676 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
1677 {
1678         int fd;
1679         char *target;
1680
1681         switch (st->st_mode & S_IFMT) {
1682         case S_IFREG:
1683                 fd = open(path, O_RDONLY);
1684                 if (fd < 0)
1685                         return error("open(\"%s\"): %s", path,
1686                                      strerror(errno));
1687                 if (index_fd(sha1, fd, st, write_object, NULL) < 0)
1688                         return error("%s: failed to insert into database",
1689                                      path);
1690                 break;
1691         case S_IFLNK:
1692                 target = xmalloc(st->st_size+1);
1693                 if (readlink(path, target, st->st_size+1) != st->st_size) {
1694                         char *errstr = strerror(errno);
1695                         free(target);
1696                         return error("readlink(\"%s\"): %s", path,
1697                                      errstr);
1698                 }
1699                 if (!write_object) {
1700                         unsigned char hdr[50];
1701                         int hdrlen;
1702                         write_sha1_file_prepare(target, st->st_size, blob_type,
1703                                                 sha1, hdr, &hdrlen);
1704                 } else if (write_sha1_file(target, st->st_size, blob_type, sha1))
1705                         return error("%s: failed to insert into database",
1706                                      path);
1707                 free(target);
1708                 break;
1709         default:
1710                 return error("%s: unsupported file type", path);
1711         }
1712         return 0;
1713 }