[PATCH] Enhance sha1_file_size() into sha1_object_info()
[git/git.git] / sha1_file.c
CommitLineData
0fcfd160
LT
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 */
0fcfd160
LT
9#include "cache.h"
10
144bde78
LT
11#ifndef O_NOATIME
12#if defined(__linux__) && (defined(__i386__) || defined(__PPC__))
13#define O_NOATIME 01000000
14#else
15#define O_NOATIME 0
16#endif
17#endif
18
19static unsigned int sha1_file_open_flag = O_NOATIME;
20
0fcfd160
LT
21static unsigned hexval(char c)
22{
23 if (c >= '0' && c <= '9')
24 return c - '0';
25 if (c >= 'a' && c <= 'f')
26 return c - 'a' + 10;
27 if (c >= 'A' && c <= 'F')
28 return c - 'A' + 10;
29 return ~0;
30}
31
32int get_sha1_hex(const char *hex, unsigned char *sha1)
33{
34 int i;
35 for (i = 0; i < 20; i++) {
36 unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
37 if (val & ~0xff)
38 return -1;
39 *sha1++ = val;
40 hex += 2;
41 }
42 return 0;
43}
44
e99d59ff 45static int get_sha1_file(const char *path, unsigned char *result)
3c249c95
LT
46{
47 char buffer[60];
48 int fd = open(path, O_RDONLY);
49 int len;
50
51 if (fd < 0)
52 return -1;
53 len = read(fd, buffer, sizeof(buffer));
54 close(fd);
55 if (len < 40)
56 return -1;
57 return get_sha1_hex(buffer, result);
58}
59
95fc7512 60static char *git_dir, *git_object_dir, *git_index_file, *git_refs_dir;
8ac069ac
JH
61static void setup_git_env(void)
62{
63 git_dir = gitenv(GIT_DIR_ENVIRONMENT);
64 if (!git_dir)
65 git_dir = DEFAULT_GIT_DIR_ENVIRONMENT;
66 git_object_dir = gitenv(DB_ENVIRONMENT);
67 if (!git_object_dir) {
68 git_object_dir = xmalloc(strlen(git_dir) + 9);
69 sprintf(git_object_dir, "%s/objects", git_dir);
70 }
95fc7512
DB
71 git_refs_dir = xmalloc(strlen(git_dir) + 6);
72 sprintf(git_refs_dir, "%s/refs", git_dir);
8ac069ac
JH
73 git_index_file = gitenv(INDEX_ENVIRONMENT);
74 if (!git_index_file) {
75 git_index_file = xmalloc(strlen(git_dir) + 7);
76 sprintf(git_index_file, "%s/index", git_dir);
77 }
78}
79
80char *get_object_directory(void)
81{
82 if (!git_object_dir)
83 setup_git_env();
84 return git_object_dir;
85}
86
95fc7512
DB
87char *get_refs_directory(void)
88{
89 if (!git_refs_dir)
90 setup_git_env();
91 return git_refs_dir;
92}
93
8ac069ac
JH
94char *get_index_file(void)
95{
96 if (!git_index_file)
97 setup_git_env();
98 return git_index_file;
99}
100
3c249c95
LT
101int get_sha1(const char *str, unsigned char *sha1)
102{
103 static char pathname[PATH_MAX];
35ad3382
LT
104 static const char *prefix[] = {
105 "",
106 "refs",
107 "refs/tags",
108 "refs/heads",
109 "refs/snap",
110 NULL
111 };
35ad3382 112 const char **p;
3c249c95
LT
113
114 if (!get_sha1_hex(str, sha1))
115 return 0;
35ad3382 116
8ac069ac
JH
117 if (!git_dir)
118 setup_git_env();
35ad3382 119 for (p = prefix; *p; p++) {
8ac069ac
JH
120 snprintf(pathname, sizeof(pathname), "%s/%s/%s",
121 git_dir, *p, str);
35ad3382
LT
122 if (!get_sha1_file(pathname, sha1))
123 return 0;
124 }
125
3c249c95
LT
126 return -1;
127}
128
0fcfd160
LT
129char * sha1_to_hex(const unsigned char *sha1)
130{
131 static char buffer[50];
132 static const char hex[] = "0123456789abcdef";
133 char *buf = buffer;
134 int i;
135
136 for (i = 0; i < 20; i++) {
137 unsigned int val = *sha1++;
138 *buf++ = hex[val >> 4];
139 *buf++ = hex[val & 0xf];
140 }
141 return buffer;
142}
143
ace1534d
JH
144static void fill_sha1_path(char *pathbuf, const unsigned char *sha1)
145{
146 int i;
147 for (i = 0; i < 20; i++) {
148 static char hex[] = "0123456789abcdef";
149 unsigned int val = sha1[i];
150 char *pos = pathbuf + i*2 + (i > 0);
151 *pos++ = hex[val >> 4];
152 *pos = hex[val & 0xf];
153 }
154}
155
0fcfd160
LT
156/*
157 * NOTE! This returns a statically allocated buffer, so you have to be
158 * careful about using it. Do a "strdup()" if you need to save the
159 * filename.
ace1534d
JH
160 *
161 * Also note that this returns the location for creating. Reading
162 * SHA1 file can happen from any alternate directory listed in the
d19938ab 163 * DB_ENVIRONMENT environment variable if it is not found in
ace1534d 164 * the primary object database.
0fcfd160
LT
165 */
166char *sha1_file_name(const unsigned char *sha1)
167{
0fcfd160
LT
168 static char *name, *base;
169
170 if (!base) {
d19938ab 171 const char *sha1_file_directory = get_object_directory();
0fcfd160 172 int len = strlen(sha1_file_directory);
812666c8 173 base = xmalloc(len + 60);
0fcfd160
LT
174 memcpy(base, sha1_file_directory, len);
175 memset(base+len, 0, 60);
176 base[len] = '/';
177 base[len+3] = '/';
178 name = base + len + 1;
179 }
ace1534d 180 fill_sha1_path(name, sha1);
0fcfd160
LT
181 return base;
182}
183
ddd5d056 184static struct alternate_object_database {
ace1534d
JH
185 char *base;
186 char *name;
187} *alt_odb;
188
ddd5d056
JH
189/*
190 * Prepare alternate object database registry.
191 * alt_odb points at an array of struct alternate_object_database.
192 * This array is terminated with an element that has both its base
193 * and name set to NULL. alt_odb[n] comes from n'th non-empty
d19938ab 194 * element from colon separated ALTERNATE_DB_ENVIRONMENT environment
ddd5d056
JH
195 * variable, and its base points at a statically allocated buffer
196 * that contains "/the/directory/corresponding/to/.git/objects/...",
197 * while its name points just after the slash at the end of
198 * ".git/objects/" in the example above, and has enough space to hold
199 * 40-byte hex SHA1, an extra slash for the first level indirection,
200 * and the terminating NUL.
201 * This function allocates the alt_odb array and all the strings
202 * pointed by base fields of the array elements with one xmalloc();
203 * the string pool immediately follows the array.
204 */
ace1534d
JH
205static void prepare_alt_odb(void)
206{
207 int pass, totlen, i;
ace1534d 208 const char *cp, *last;
e99d59ff 209 char *op = NULL;
d19938ab 210 const char *alt = gitenv(ALTERNATE_DB_ENVIRONMENT) ? : "";
ace1534d 211
ddd5d056
JH
212 /* The first pass counts how large an area to allocate to
213 * hold the entire alt_odb structure, including array of
214 * structs and path buffers for them. The second pass fills
215 * the structure and prepares the path buffers for use by
216 * fill_sha1_path().
217 */
ace1534d
JH
218 for (totlen = pass = 0; pass < 2; pass++) {
219 last = alt;
220 i = 0;
221 do {
222 cp = strchr(last, ':') ? : last + strlen(last);
223 if (last != cp) {
224 /* 43 = 40-byte + 2 '/' + terminating NUL */
225 int pfxlen = cp - last;
226 int entlen = pfxlen + 43;
227 if (pass == 0)
228 totlen += entlen;
229 else {
230 alt_odb[i].base = op;
231 alt_odb[i].name = op + pfxlen + 1;
232 memcpy(op, last, pfxlen);
233 op[pfxlen] = op[pfxlen + 3] = '/';
234 op[entlen-1] = 0;
235 op += entlen;
236 }
237 i++;
238 }
239 while (*cp && *cp == ':')
240 cp++;
241 last = cp;
242 } while (*cp);
243 if (pass)
244 break;
ddd5d056 245 alt_odb = xmalloc(sizeof(*alt_odb) * (i + 1) + totlen);
e99d59ff 246 alt_odb[i].base = alt_odb[i].name = NULL;
ace1534d
JH
247 op = (char*)(&alt_odb[i+1]);
248 }
249}
250
251static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
252{
253 int i;
254 char *name = sha1_file_name(sha1);
255
256 if (!stat(name, st))
257 return name;
258 if (!alt_odb)
259 prepare_alt_odb();
260 for (i = 0; (name = alt_odb[i].name) != NULL; i++) {
261 fill_sha1_path(name, sha1);
262 if (!stat(alt_odb[i].base, st))
263 return alt_odb[i].base;
264 }
265 return NULL;
266}
267
5d6ccf5c 268int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
0fcfd160 269{
d98b46f8 270 char header[100];
0fcfd160
LT
271 unsigned char real_sha1[20];
272 SHA_CTX c;
273
274 SHA1_Init(&c);
d98b46f8 275 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
0fcfd160
LT
276 SHA1_Update(&c, map, size);
277 SHA1_Final(real_sha1, &c);
278 return memcmp(sha1, real_sha1, 20) ? -1 : 0;
279}
280
281void *map_sha1_file(const unsigned char *sha1, unsigned long *size)
282{
0fcfd160
LT
283 struct stat st;
284 void *map;
144bde78 285 int fd;
ace1534d
JH
286 char *filename = find_sha1_file(sha1, &st);
287
288 if (!filename) {
289 error("cannot map sha1 file %s", sha1_to_hex(sha1));
290 return NULL;
291 }
0fcfd160 292
144bde78 293 fd = open(filename, O_RDONLY | sha1_file_open_flag);
0fcfd160 294 if (fd < 0) {
144bde78
LT
295 /* See if it works without O_NOATIME */
296 switch (sha1_file_open_flag) {
297 default:
298 fd = open(filename, O_RDONLY);
299 if (fd >= 0)
300 break;
301 /* Fallthrough */
302 case 0:
303 perror(filename);
304 return NULL;
305 }
306
307 /* If it failed once, it will probably fail again. Stop using O_NOATIME */
308 sha1_file_open_flag = 0;
0fcfd160 309 }
0fcfd160
LT
310 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
311 close(fd);
312 if (-1 == (int)(long)map)
313 return NULL;
314 *size = st.st_size;
315 return map;
316}
317
c4483576
LT
318int unpack_sha1_header(z_stream *stream, void *map, unsigned long mapsize, void *buffer, unsigned long size)
319{
320 /* Get the data stream */
321 memset(stream, 0, sizeof(*stream));
322 stream->next_in = map;
323 stream->avail_in = mapsize;
324 stream->next_out = buffer;
325 stream->avail_out = size;
326
327 inflateInit(stream);
328 return inflate(stream, 0);
329}
330
5180cacc
LT
331void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
332{
333 int bytes = strlen(buffer) + 1;
d565b341 334 unsigned char *buf = xmalloc(1+size);
5180cacc
LT
335
336 memcpy(buf, buffer + bytes, stream->total_out - bytes);
337 bytes = stream->total_out - bytes;
338 if (bytes < size) {
339 stream->next_out = buf + bytes;
340 stream->avail_out = size - bytes;
341 while (inflate(stream, Z_FINISH) == Z_OK)
342 /* nothing */;
343 }
344 buf[size] = 0;
345 inflateEnd(stream);
346 return buf;
347}
348
349/*
350 * We used to just use "sscanf()", but that's actually way
351 * too permissive for what we want to check. So do an anal
352 * object header parse by hand.
353 */
354int parse_sha1_header(char *hdr, char *type, unsigned long *sizep)
355{
356 int i;
357 unsigned long size;
358
359 /*
360 * The type can be at most ten bytes (including the
361 * terminating '\0' that we add), and is followed by
362 * a space.
363 */
364 i = 10;
365 for (;;) {
366 char c = *hdr++;
367 if (c == ' ')
368 break;
369 if (!--i)
370 return -1;
371 *type++ = c;
372 }
373 *type = 0;
374
375 /*
376 * The length must follow immediately, and be in canonical
377 * decimal format (ie "010" is not valid).
378 */
379 size = *hdr++ - '0';
380 if (size > 9)
381 return -1;
382 if (size) {
383 for (;;) {
384 unsigned long c = *hdr - '0';
385 if (c > 9)
386 break;
387 hdr++;
388 size = size * 10 + c;
389 }
390 }
391 *sizep = size;
392
393 /*
394 * The length must be followed by a zero byte
395 */
396 return *hdr ? -1 : 0;
397}
398
0fcfd160
LT
399void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
400{
5180cacc 401 int ret;
0fcfd160 402 z_stream stream;
5180cacc 403 char hdr[8192];
0fcfd160 404
5180cacc
LT
405 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
406 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
0fcfd160
LT
407 return NULL;
408
5180cacc 409 return unpack_sha1_rest(&stream, hdr, *size);
0fcfd160
LT
410}
411
36e4d74a 412int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
65c2e0c3 413{
36e4d74a 414 int status;
65c2e0c3
JH
415 unsigned long mapsize, size;
416 void *map;
417 z_stream stream;
36e4d74a 418 char hdr[128];
65c2e0c3
JH
419
420 map = map_sha1_file(sha1, &mapsize);
421 if (!map)
36e4d74a
JH
422 return error("unable to map %s", sha1_to_hex(sha1));
423 if (unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr)) < 0)
424 status = error("unable to unpack %s header",
425 sha1_to_hex(sha1));
426 if (parse_sha1_header(hdr, type, &size) < 0)
427 status = error("unable to parse %s header", sha1_to_hex(sha1));
c4584ae3 428 else {
65c2e0c3 429 status = 0;
c4584ae3 430 *sizep = size;
65c2e0c3 431 }
65c2e0c3
JH
432 inflateEnd(&stream);
433 munmap(map, mapsize);
434 return status;
435}
436
0fcfd160
LT
437void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
438{
439 unsigned long mapsize;
440 void *map, *buf;
441
442 map = map_sha1_file(sha1, &mapsize);
443 if (map) {
444 buf = unpack_sha1_file(map, mapsize, type, size);
445 munmap(map, mapsize);
446 return buf;
447 }
448 return NULL;
449}
450
40469ee9 451void *read_object_with_reference(const unsigned char *sha1,
bf0f910d 452 const char *required_type,
40469ee9
JH
453 unsigned long *size,
454 unsigned char *actual_sha1_return)
f4913f91
JH
455{
456 char type[20];
457 void *buffer;
458 unsigned long isize;
40469ee9 459 unsigned char actual_sha1[20];
f4913f91 460
40469ee9
JH
461 memcpy(actual_sha1, sha1, 20);
462 while (1) {
463 int ref_length = -1;
464 const char *ref_type = NULL;
f4913f91 465
40469ee9
JH
466 buffer = read_sha1_file(actual_sha1, type, &isize);
467 if (!buffer)
468 return NULL;
469 if (!strcmp(type, required_type)) {
470 *size = isize;
471 if (actual_sha1_return)
472 memcpy(actual_sha1_return, actual_sha1, 20);
473 return buffer;
474 }
475 /* Handle references */
476 else if (!strcmp(type, "commit"))
477 ref_type = "tree ";
478 else if (!strcmp(type, "tag"))
479 ref_type = "object ";
480 else {
481 free(buffer);
482 return NULL;
483 }
484 ref_length = strlen(ref_type);
f4913f91 485
40469ee9
JH
486 if (memcmp(buffer, ref_type, ref_length) ||
487 get_sha1_hex(buffer + ref_length, actual_sha1)) {
488 free(buffer);
489 return NULL;
490 }
491 /* Now we have the ID of the referred-to object in
492 * actual_sha1. Check again. */
f4913f91 493 }
f4913f91
JH
494}
495
bf0f910d 496int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
0fcfd160
LT
497{
498 int size;
bf0f910d 499 unsigned char *compressed;
0fcfd160
LT
500 z_stream stream;
501 unsigned char sha1[20];
502 SHA_CTX c;
706bc531 503 char *filename;
aac17941 504 static char tmpfile[PATH_MAX];
bf0f910d 505 unsigned char hdr[50];
aac17941 506 int fd, hdrlen, ret;
a44c9a5e
LT
507
508 /* Generate the header */
bf0f910d 509 hdrlen = sprintf((char *)hdr, "%s %lu", type, len)+1;
0fcfd160 510
d98b46f8
LT
511 /* Sha1.. */
512 SHA1_Init(&c);
a44c9a5e 513 SHA1_Update(&c, hdr, hdrlen);
d98b46f8
LT
514 SHA1_Update(&c, buf, len);
515 SHA1_Final(sha1, &c);
516
706bc531
LT
517 if (returnsha1)
518 memcpy(returnsha1, sha1, 20);
519
520 filename = sha1_file_name(sha1);
aac17941
LT
521 fd = open(filename, O_RDONLY);
522 if (fd >= 0) {
706bc531 523 /*
aac17941
LT
524 * FIXME!!! We might do collision checking here, but we'd
525 * need to uncompress the old file and check it. Later.
706bc531 526 */
aac17941 527 close(fd);
706bc531
LT
528 return 0;
529 }
530
aac17941
LT
531 if (errno != ENOENT) {
532 fprintf(stderr, "sha1 file %s: %s", filename, strerror(errno));
533 return -1;
534 }
535
536 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
ace1534d 537
aac17941
LT
538 fd = mkstemp(tmpfile);
539 if (fd < 0) {
540 fprintf(stderr, "unable to create temporary sha1 filename %s: %s", tmpfile, strerror(errno));
541 return -1;
542 }
543
0fcfd160
LT
544 /* Set it up */
545 memset(&stream, 0, sizeof(stream));
546 deflateInit(&stream, Z_BEST_COMPRESSION);
a44c9a5e 547 size = deflateBound(&stream, len+hdrlen);
812666c8 548 compressed = xmalloc(size);
0fcfd160
LT
549
550 /* Compress it */
0fcfd160
LT
551 stream.next_out = compressed;
552 stream.avail_out = size;
a44c9a5e
LT
553
554 /* First header.. */
555 stream.next_in = hdr;
556 stream.avail_in = hdrlen;
557 while (deflate(&stream, 0) == Z_OK)
6ffcee88 558 /* nothing */;
a44c9a5e
LT
559
560 /* Then the data itself.. */
561 stream.next_in = buf;
562 stream.avail_in = len;
0fcfd160
LT
563 while (deflate(&stream, Z_FINISH) == Z_OK)
564 /* nothing */;
565 deflateEnd(&stream);
566 size = stream.total_out;
567
706bc531
LT
568 if (write(fd, compressed, size) != size)
569 die("unable to write file");
aac17941 570 fchmod(fd, 0444);
706bc531 571 close(fd);
383f85b7 572 free(compressed);
0fcfd160 573
aac17941 574 ret = link(tmpfile, filename);
a31c6d02 575 if (ret < 0) {
aac17941 576 ret = errno;
a31c6d02
LT
577
578 /*
579 * Coda hack - coda doesn't like cross-directory links,
580 * so we fall back to a rename, which will mean that it
581 * won't be able to check collisions, but that's not a
582 * big deal.
583 *
584 * When this succeeds, we just return 0. We have nothing
585 * left to unlink.
586 */
587 if (ret == EXDEV && !rename(tmpfile, filename))
588 return 0;
589 }
aac17941
LT
590 unlink(tmpfile);
591 if (ret) {
592 if (ret != EEXIST) {
593 fprintf(stderr, "unable to write sha1 filename %s: %s", filename, strerror(ret));
0fcfd160 594 return -1;
aac17941
LT
595 }
596 /* FIXME!!! Collision check here ? */
0fcfd160 597 }
aac17941 598
0fcfd160
LT
599 return 0;
600}
8237b185
DB
601
602int write_sha1_from_fd(const unsigned char *sha1, int fd)
603{
604 char *filename = sha1_file_name(sha1);
605
606 int local;
607 z_stream stream;
608 unsigned char real_sha1[20];
bf0f910d
BG
609 unsigned char buf[4096];
610 unsigned char discard[4096];
8237b185
DB
611 int ret;
612 SHA_CTX c;
613
614 local = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0666);
615
616 if (local < 0)
617 return error("Couldn't open %s\n", filename);
618
619 memset(&stream, 0, sizeof(stream));
620
621 inflateInit(&stream);
622
623 SHA1_Init(&c);
624
625 do {
626 ssize_t size;
627 size = read(fd, buf, 4096);
628 if (size <= 0) {
629 close(local);
630 unlink(filename);
631 if (!size)
632 return error("Connection closed?");
633 perror("Reading from connection");
634 return -1;
635 }
636 write(local, buf, size);
637 stream.avail_in = size;
638 stream.next_in = buf;
639 do {
640 stream.next_out = discard;
641 stream.avail_out = sizeof(discard);
642 ret = inflate(&stream, Z_SYNC_FLUSH);
643 SHA1_Update(&c, discard, sizeof(discard) -
644 stream.avail_out);
645 } while (stream.avail_in && ret == Z_OK);
646
647 } while (ret == Z_OK);
648 inflateEnd(&stream);
649
650 close(local);
651 SHA1_Final(real_sha1, &c);
652 if (ret != Z_STREAM_END) {
653 unlink(filename);
654 return error("File %s corrupted", sha1_to_hex(sha1));
655 }
656 if (memcmp(sha1, real_sha1, 20)) {
657 unlink(filename);
658 return error("File %s has bad hash\n", sha1_to_hex(sha1));
659 }
660
661 return 0;
662}
663
664int has_sha1_file(const unsigned char *sha1)
665{
8237b185 666 struct stat st;
ace1534d 667 return !!find_sha1_file(sha1, &st);
8237b185 668}
74400e71
JH
669
670int index_fd(unsigned char *sha1, int fd, struct stat *st)
671{
74400e71 672 unsigned long size = st->st_size;
aac17941
LT
673 void *buf;
674 int ret;
74400e71 675
aac17941 676 buf = "";
74400e71 677 if (size)
aac17941 678 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
74400e71 679 close(fd);
aac17941 680 if ((int)(long)buf == -1)
74400e71
JH
681 return -1;
682
aac17941
LT
683 ret = write_sha1_file(buf, size, "blob", sha1);
684 if (size)
685 munmap(buf, size);
686 return ret;
74400e71 687}