Documentation for git-fmt-merge-msg
[git/dscho.git] / sha1_file.c
blob642f00d3d47c3d782c3dfe522d21819c1a67de30
1 /*
2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
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"
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
23 const unsigned char null_sha1[20] = { 0, };
25 static unsigned int sha1_file_open_flag = O_NOATIME;
27 static unsigned hexval(char c)
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;
38 int get_sha1_hex(const char *hex, unsigned char *sha1)
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;
48 return 0;
51 int safe_create_leading_directories(char *path)
53 char *pos = path;
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;
65 *pos++ = '/';
67 return 0;
70 char * sha1_to_hex(const unsigned char *sha1)
72 static char buffer[50];
73 static const char hex[] = "0123456789abcdef";
74 char *buf = buffer;
75 int i;
77 for (i = 0; i < 20; i++) {
78 unsigned int val = *sha1++;
79 *buf++ = hex[val >> 4];
80 *buf++ = hex[val & 0xf];
82 return buffer;
85 static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
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];
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.
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.
107 char *sha1_file_name(const unsigned char *sha1)
109 static char *name, *base;
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;
121 fill_sha1_path(name, sha1);
122 return base;
125 char *sha1_pack_name(const unsigned char *sha1)
127 static const char hex[] = "0123456789abcdef";
128 static char *name, *base, *buf;
129 int i;
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;
139 buf = name;
141 for (i = 0; i < 20; i++) {
142 unsigned int val = *sha1++;
143 *buf++ = hex[val >> 4];
144 *buf++ = hex[val & 0xf];
147 return base;
150 char *sha1_pack_index_name(const unsigned char *sha1)
152 static const char hex[] = "0123456789abcdef";
153 static char *name, *base, *buf;
154 int i;
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;
164 buf = name;
166 for (i = 0; i < 20; i++) {
167 unsigned int val = *sha1++;
168 *buf++ = hex[val >> 4];
169 *buf++ = hex[val & 0xf];
172 return base;
175 struct alternate_object_database *alt_odb_list;
176 static struct alternate_object_database **alt_odb_tail;
179 * Prepare alternate object database registry.
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.
193 static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
194 const char *relative_base)
196 const char *cp, *last;
197 struct alternate_object_database *ent;
198 int base_len = -1;
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;
209 for ( ; cp < ep && *cp != sep; cp++)
211 if (last != cp) {
212 /* 43 = 40-byte + 2 '/' + terminating NUL */
213 int pfxlen = cp - last;
214 int entlen = pfxlen + 43;
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;
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);
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;
239 while (cp < ep && *cp == sep)
240 cp++;
241 last = cp;
245 void prepare_alt_odb(void)
247 char path[PATH_MAX];
248 char *map;
249 int fd;
250 struct stat st;
251 char *alt;
253 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
254 if (!alt) alt = "";
256 if (alt_odb_tail)
257 return;
258 alt_odb_tail = &alt_odb_list;
259 link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL);
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;
269 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
270 close(fd);
271 if (map == MAP_FAILED)
272 return;
274 link_alt_odb_entries(map, map + st.st_size, '\n',
275 get_object_directory());
276 munmap(map, st.st_size);
279 static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
281 char *name = sha1_file_name(sha1);
282 struct alternate_object_database *alt;
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;
293 return NULL;
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;
301 static int check_packed_git_idx(const char *path, unsigned long *idx_size_,
302 void **idx_map_)
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;
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;
322 index = idx_map;
323 *idx_map_ = idx_map;
324 *idx_size_ = idx_size;
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;
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
344 if (idx_size != 4*256 + nr * 24 + 20 + 20)
345 return error("wrong index file size");
347 return 0;
350 static int unuse_one_packed_git(void)
352 struct packed_git *p, *lru = NULL;
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;
360 if (!lru)
361 return 0;
362 munmap(lru->pack_base, lru->pack_size);
363 lru->pack_base = NULL;
364 return 1;
367 void unuse_packed_git(struct packed_git *p)
369 p->pack_use_cnt--;
372 int use_packed_git(struct packed_git *p)
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;
382 if (!p->pack_base) {
383 int fd;
384 struct stat st;
385 void *map;
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);
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;
405 /* Check if the pack file matches with the index file.
406 * this is cheap.
408 if (memcmp((char*)(p->index_base) + p->index_size - 40,
409 p->pack_base + p->pack_size - 20, 20)) {
411 die("packfile %s does not match index.", p->pack_name);
414 p->pack_last_used = pack_used_ctr++;
415 p->pack_use_cnt++;
416 return 0;
419 struct packed_git *add_packed_git(char *path, int path_len, int local)
421 struct stat st;
422 struct packed_git *p;
423 unsigned long idx_size;
424 void *idx_map;
426 if (check_packed_git_idx(path, &idx_size, &idx_map))
427 return NULL;
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;
435 /* ok, it looks sane as far as we can check without
436 * actually mapping the pack file.
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;
451 struct packed_git *parse_pack_index(unsigned char *sha1)
453 char *path = sha1_pack_index_name(sha1);
454 return parse_pack_index_file(sha1, path);
457 struct packed_git *parse_pack_index_file(const unsigned char *sha1, char *idx_path)
459 struct packed_git *p;
460 unsigned long idx_size;
461 void *idx_map;
462 char *path;
464 if (check_packed_git_idx(idx_path, &idx_size, &idx_map))
465 return NULL;
467 path = sha1_pack_name(sha1);
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;
482 void install_packed_git(struct packed_git *pack)
484 pack->next = packed_git;
485 packed_git = pack;
488 static void prepare_packed_git_one(char *objdir, int local)
490 char path[PATH_MAX];
491 int len;
492 DIR *dir;
493 struct dirent *de;
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;
505 if (strcmp(de->d_name + namelen - 4, ".idx"))
506 continue;
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;
516 closedir(dir);
519 void prepare_packed_git(void)
521 static int run_once = 0;
522 struct alternate_object_database *alt;
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);
532 run_once = 1;
535 int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
537 char header[100];
538 unsigned char real_sha1[20];
539 SHA_CTX c;
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;
548 static void *map_sha1_file_internal(const unsigned char *sha1,
549 unsigned long *size)
551 struct stat st;
552 void *map;
553 int fd;
554 char *filename = find_sha1_file(sha1, &st);
556 if (!filename) {
557 return NULL;
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;
573 /* If it failed once, it will probably fail again.
574 * Stop using O_NOATIME
576 sha1_file_open_flag = 0;
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;
586 int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
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;
595 inflateInit(stream);
596 return inflate(stream, 0);
599 static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
601 int bytes = strlen(buffer) + 1;
602 unsigned char *buf = xmalloc(1+size);
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 */;
612 buf[size] = 0;
613 inflateEnd(stream);
614 return buf;
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.
622 int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
624 int i;
625 unsigned long size;
628 * The type can be at most ten bytes (including the
629 * terminating '\0' that we add), and is followed by
630 * a space.
632 i = 10;
633 for (;;) {
634 char c = *hdr++;
635 if (c == ' ')
636 break;
637 if (!--i)
638 return -1;
639 *type++ = c;
641 *type = 0;
644 * The length must follow immediately, and be in canonical
645 * decimal format (ie "010" is not valid).
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;
659 *sizep = size;
662 * The length must be followed by a zero byte
664 return *hdr ? -1 : 0;
667 void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
669 int ret;
670 z_stream stream;
671 char hdr[8192];
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;
677 return unpack_sha1_rest(&stream, hdr, *size);
680 /* forward declaration for a mutually recursive function */
681 static int packed_object_info(struct pack_entry *entry,
682 char *type, unsigned long *sizep);
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)
691 struct pack_entry base_ent;
693 if (left < 20)
694 die("truncated pack file");
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));
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.
707 if (packed_object_info(&base_ent, type, NULL))
708 die("cannot get info for delta-pack base");
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;
717 memset(&stream, 0, sizeof(stream));
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);
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");
731 /* Examine the initial part of the delta to figure out
732 * the result size.
734 data = delta_head;
735 get_delta_hdr_size(&data); /* ignore base size */
737 /* Read the result size */
738 result_size = get_delta_hdr_size(&data);
739 *sizep = result_size;
741 return 0;
744 static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
745 enum object_type *type, unsigned long *sizep)
747 unsigned shift;
748 unsigned char *pack, c;
749 unsigned long size;
751 if (offset >= p->pack_size)
752 die("object offset outside of pack file");
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;
768 *sizep = size;
769 return offset;
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)
779 struct packed_git *p = e->p;
780 unsigned long offset, left;
781 unsigned char *pack;
782 enum object_type kind;
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;
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;
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);
821 *store_size = 0; /* notyet */
824 static int packed_object_info(struct pack_entry *entry,
825 char *type, unsigned long *sizep)
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;
833 if (use_packed_git(p))
834 die("cannot map packed file");
836 offset = unpack_object_header(p, entry->offset, &kind, &size);
837 pack = p->pack_base + offset;
838 left = p->pack_size - offset;
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);
861 if (sizep)
862 *sizep = size;
863 unuse_packed_git(p);
864 return 0;
867 /* forward declaration for a mutually recursive function */
868 static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
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)
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;
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);
889 memset(&stream, 0, sizeof(stream));
891 stream.next_in = data;
892 stream.avail_in = data_size;
893 stream.next_out = delta_data;
894 stream.avail_out = delta_size;
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");
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;
921 static void *unpack_non_delta_entry(unsigned char *data,
922 unsigned long size,
923 unsigned long left)
925 int st;
926 z_stream stream;
927 unsigned char *buffer;
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;
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;
945 return buffer;
948 static void *unpack_entry(struct pack_entry *entry,
949 char *type, unsigned long *sizep)
951 struct packed_git *p = entry->p;
952 void *retval;
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;
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)
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;
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;
995 *sizep = size;
996 retval = unpack_non_delta_entry(pack, size, left);
997 return retval;
1000 int num_packed_objects(const struct packed_git *p)
1002 /* See check_packed_git_idx() */
1003 return (p->index_size - 20 - 20 - 4*256) / 24;
1006 int nth_packed_object_sha1(const struct packed_git *p, int n,
1007 unsigned char* sha1)
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;
1016 int find_pack_entry_one(const unsigned char *sha1,
1017 struct pack_entry *e, struct packed_git *p)
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;
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;
1033 if (cmp > 0)
1034 hi = mi;
1035 else
1036 lo = mi+1;
1037 } while (lo < hi);
1038 return 0;
1041 static int find_pack_entry(const unsigned char *sha1, struct pack_entry *e)
1043 struct packed_git *p;
1044 prepare_packed_git();
1046 for (p = packed_git; p; p = p->next) {
1047 if (find_pack_entry_one(sha1, e, p))
1048 return 1;
1050 return 0;
1053 struct packed_git *find_sha1_pack(const unsigned char *sha1,
1054 struct packed_git *packs)
1056 struct packed_git *p;
1057 struct pack_entry e;
1059 for (p = packs; p; p = p->next) {
1060 if (find_pack_entry_one(sha1, &e, p))
1061 return p;
1063 return NULL;
1067 int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
1069 int status;
1070 unsigned long mapsize, size;
1071 void *map;
1072 z_stream stream;
1073 char hdr[128];
1075 map = map_sha1_file_internal(sha1, &mapsize);
1076 if (!map) {
1077 struct pack_entry e;
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);
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;
1093 inflateEnd(&stream);
1094 munmap(map, mapsize);
1095 return status;
1098 static void *read_packed_sha1(const unsigned char *sha1, char *type, unsigned long *size)
1100 struct pack_entry e;
1102 if (!find_pack_entry(sha1, &e)) {
1103 error("cannot read sha1_file for %s", sha1_to_hex(sha1));
1104 return NULL;
1106 return unpack_entry(&e, type, size);
1109 void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1111 unsigned long mapsize;
1112 void *map, *buf;
1113 struct pack_entry e;
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;
1123 return NULL;
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)
1131 char type[20];
1132 void *buffer;
1133 unsigned long isize;
1134 unsigned char actual_sha1[20];
1136 memcpy(actual_sha1, sha1, 20);
1137 while (1) {
1138 int ref_length = -1;
1139 const char *ref_type = NULL;
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;
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;
1159 ref_length = strlen(ref_type);
1161 if (memcmp(buffer, ref_type, ref_length) ||
1162 get_sha1_hex(buffer + ref_length, actual_sha1)) {
1163 free(buffer);
1164 return NULL;
1166 free(buffer);
1167 /* Now we have the ID of the referred-to object in
1168 * actual_sha1. Check again. */
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)
1179 SHA_CTX c;
1181 /* Generate the header */
1182 *hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
1184 /* Sha1.. */
1185 SHA1_Init(&c);
1186 SHA1_Update(&c, hdr, *hdrlen);
1187 SHA1_Update(&c, buf, len);
1188 SHA1_Final(sha1, &c);
1190 return sha1_file_name(sha1);
1194 * Link the tempfile to the final place, possibly creating the
1195 * last directory level as you do so.
1197 * Returns the errno on failure, 0 on success.
1199 static int link_temp_to_file(const char *tmpfile, char *filename)
1201 int ret;
1203 if (!link(tmpfile, filename))
1204 return 0;
1207 * Try to mkdir the last path component if that failed
1208 * with an ENOENT.
1210 * Re-try the "link()" regardless of whether the mkdir
1211 * succeeds, since a race might mean that somebody
1212 * else succeeded.
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;
1226 return ret;
1230 * Move the just written object into its final resting place
1232 int move_temp_to_file(const char *tmpfile, char *filename)
1234 int ret = link_temp_to_file(tmpfile, filename);
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.
1242 * The same holds for FAT formatted media.
1244 * When this succeeds, we just return 0. We have nothing
1245 * left to unlink.
1247 if (ret && ret != EEXIST) {
1248 if (!rename(tmpfile, filename))
1249 return 0;
1250 ret = errno;
1252 unlink(tmpfile);
1253 if (ret) {
1254 if (ret != EEXIST) {
1255 fprintf(stderr, "unable to write sha1 filename %s: %s", filename, strerror(ret));
1256 return -1;
1258 /* FIXME!!! Collision check here ? */
1261 return 0;
1264 int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
1266 int size;
1267 unsigned char *compressed;
1268 z_stream stream;
1269 unsigned char sha1[20];
1270 char *filename;
1271 static char tmpfile[PATH_MAX];
1272 unsigned char hdr[50];
1273 int fd, hdrlen;
1275 /* Normally if we have it in the pack then we do not bother writing
1276 * it out into .git/objects/??/?{38} file.
1278 filename = write_sha1_file_prepare(buf, len, type, sha1, hdr, &hdrlen);
1279 if (returnsha1)
1280 memcpy(returnsha1, sha1, 20);
1281 if (has_sha1_file(sha1))
1282 return 0;
1283 fd = open(filename, O_RDONLY);
1284 if (fd >= 0) {
1286 * FIXME!!! We might do collision checking here, but we'd
1287 * need to uncompress the old file and check it. Later.
1289 close(fd);
1290 return 0;
1293 if (errno != ENOENT) {
1294 fprintf(stderr, "sha1 file %s: %s", filename, strerror(errno));
1295 return -1;
1298 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1300 fd = mkstemp(tmpfile);
1301 if (fd < 0) {
1302 fprintf(stderr, "unable to create temporary sha1 filename %s: %s", tmpfile, strerror(errno));
1303 return -1;
1306 /* Set it up */
1307 memset(&stream, 0, sizeof(stream));
1308 deflateInit(&stream, Z_BEST_COMPRESSION);
1309 size = deflateBound(&stream, len+hdrlen);
1310 compressed = xmalloc(size);
1312 /* Compress it */
1313 stream.next_out = compressed;
1314 stream.avail_out = size;
1316 /* First header.. */
1317 stream.next_in = hdr;
1318 stream.avail_in = hdrlen;
1319 while (deflate(&stream, 0) == Z_OK)
1320 /* nothing */;
1322 /* Then the data itself.. */
1323 stream.next_in = buf;
1324 stream.avail_in = len;
1325 while (deflate(&stream, Z_FINISH) == Z_OK)
1326 /* nothing */;
1327 deflateEnd(&stream);
1328 size = stream.total_out;
1330 if (write(fd, compressed, size) != size)
1331 die("unable to write file");
1332 fchmod(fd, 0444);
1333 close(fd);
1334 free(compressed);
1336 return move_temp_to_file(tmpfile, filename);
1339 int write_sha1_to_fd(int fd, const unsigned char *sha1)
1341 ssize_t size;
1342 unsigned long objsize;
1343 int posn = 0;
1344 void *map = map_sha1_file_internal(sha1, &objsize);
1345 void *buf = map;
1346 void *temp_obj = NULL;
1347 z_stream stream;
1349 if (!buf) {
1350 unsigned char *unpacked;
1351 unsigned long len;
1352 char type[20];
1353 char hdr[50];
1354 int hdrlen;
1355 // need to unpack and recompress it by itself
1356 unpacked = read_packed_sha1(sha1, type, &len);
1358 hdrlen = sprintf(hdr, "%s %lu", type, len) + 1;
1360 /* Set it up */
1361 memset(&stream, 0, sizeof(stream));
1362 deflateInit(&stream, Z_BEST_COMPRESSION);
1363 size = deflateBound(&stream, len + hdrlen);
1364 temp_obj = buf = xmalloc(size);
1366 /* Compress it */
1367 stream.next_out = buf;
1368 stream.avail_out = size;
1370 /* First header.. */
1371 stream.next_in = (void *)hdr;
1372 stream.avail_in = hdrlen;
1373 while (deflate(&stream, 0) == Z_OK)
1374 /* nothing */;
1376 /* Then the data itself.. */
1377 stream.next_in = unpacked;
1378 stream.avail_in = len;
1379 while (deflate(&stream, Z_FINISH) == Z_OK)
1380 /* nothing */;
1381 deflateEnd(&stream);
1382 free(unpacked);
1384 objsize = stream.total_out;
1387 do {
1388 size = write(fd, buf + posn, objsize - posn);
1389 if (size <= 0) {
1390 if (!size) {
1391 fprintf(stderr, "write closed");
1392 } else {
1393 perror("write ");
1395 return -1;
1397 posn += size;
1398 } while (posn < objsize);
1400 if (map)
1401 munmap(map, objsize);
1402 if (temp_obj)
1403 free(temp_obj);
1405 return 0;
1408 int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
1409 size_t bufsize, size_t *bufposn)
1411 char tmpfile[PATH_MAX];
1412 int local;
1413 z_stream stream;
1414 unsigned char real_sha1[20];
1415 unsigned char discard[4096];
1416 int ret;
1417 SHA_CTX c;
1419 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
1421 local = mkstemp(tmpfile);
1422 if (local < 0)
1423 return error("Couldn't open %s for %s\n", tmpfile, sha1_to_hex(sha1));
1425 memset(&stream, 0, sizeof(stream));
1427 inflateInit(&stream);
1429 SHA1_Init(&c);
1431 do {
1432 ssize_t size;
1433 if (*bufposn) {
1434 stream.avail_in = *bufposn;
1435 stream.next_in = (unsigned char *) buffer;
1436 do {
1437 stream.next_out = discard;
1438 stream.avail_out = sizeof(discard);
1439 ret = inflate(&stream, Z_SYNC_FLUSH);
1440 SHA1_Update(&c, discard, sizeof(discard) -
1441 stream.avail_out);
1442 } while (stream.avail_in && ret == Z_OK);
1443 write(local, buffer, *bufposn - stream.avail_in);
1444 memmove(buffer, buffer + *bufposn - stream.avail_in,
1445 stream.avail_in);
1446 *bufposn = stream.avail_in;
1447 if (ret != Z_OK)
1448 break;
1450 size = read(fd, buffer + *bufposn, bufsize - *bufposn);
1451 if (size <= 0) {
1452 close(local);
1453 unlink(tmpfile);
1454 if (!size)
1455 return error("Connection closed?");
1456 perror("Reading from connection");
1457 return -1;
1459 *bufposn += size;
1460 } while (1);
1461 inflateEnd(&stream);
1463 close(local);
1464 SHA1_Final(real_sha1, &c);
1465 if (ret != Z_STREAM_END) {
1466 unlink(tmpfile);
1467 return error("File %s corrupted", sha1_to_hex(sha1));
1469 if (memcmp(sha1, real_sha1, 20)) {
1470 unlink(tmpfile);
1471 return error("File %s has bad hash\n", sha1_to_hex(sha1));
1474 return move_temp_to_file(tmpfile, sha1_file_name(sha1));
1477 int has_pack_index(const unsigned char *sha1)
1479 struct stat st;
1480 if (stat(sha1_pack_index_name(sha1), &st))
1481 return 0;
1482 return 1;
1485 int has_pack_file(const unsigned char *sha1)
1487 struct stat st;
1488 if (stat(sha1_pack_name(sha1), &st))
1489 return 0;
1490 return 1;
1493 int has_sha1_pack(const unsigned char *sha1)
1495 struct pack_entry e;
1496 return find_pack_entry(sha1, &e);
1499 int has_sha1_file(const unsigned char *sha1)
1501 struct stat st;
1502 struct pack_entry e;
1504 if (find_pack_entry(sha1, &e))
1505 return 1;
1506 return find_sha1_file(sha1, &st) ? 1 : 0;
1509 int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
1511 unsigned long size = st->st_size;
1512 void *buf;
1513 int ret;
1514 unsigned char hdr[50];
1515 int hdrlen;
1517 buf = "";
1518 if (size)
1519 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1520 close(fd);
1521 if (buf == MAP_FAILED)
1522 return -1;
1524 if (!type)
1525 type = "blob";
1526 if (write_object)
1527 ret = write_sha1_file(buf, size, type, sha1);
1528 else {
1529 write_sha1_file_prepare(buf, size, type, sha1, hdr, &hdrlen);
1530 ret = 0;
1532 if (size)
1533 munmap(buf, size);
1534 return ret;
1537 int index_path(unsigned char *sha1, const char *path, struct stat *st, int write_object)
1539 int fd;
1540 char *target;
1542 switch (st->st_mode & S_IFMT) {
1543 case S_IFREG:
1544 fd = open(path, O_RDONLY);
1545 if (fd < 0)
1546 return error("open(\"%s\"): %s", path,
1547 strerror(errno));
1548 if (index_fd(sha1, fd, st, write_object, NULL) < 0)
1549 return error("%s: failed to insert into database",
1550 path);
1551 break;
1552 case S_IFLNK:
1553 target = xmalloc(st->st_size+1);
1554 if (readlink(path, target, st->st_size+1) != st->st_size) {
1555 char *errstr = strerror(errno);
1556 free(target);
1557 return error("readlink(\"%s\"): %s", path,
1558 errstr);
1560 if (!write_object) {
1561 unsigned char hdr[50];
1562 int hdrlen;
1563 write_sha1_file_prepare(target, st->st_size, "blob",
1564 sha1, hdr, &hdrlen);
1565 } else if (write_sha1_file(target, st->st_size, "blob", sha1))
1566 return error("%s: failed to insert into database",
1567 path);
1568 free(target);
1569 break;
1570 default:
1571 return error("%s: unsupported file type", path);
1573 return 0;