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