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