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