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