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