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