Work around missing hard links on FAT formatted media
[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 */
1f688557
JH
9#include <sys/types.h>
10#include <dirent.h>
0fcfd160 11#include "cache.h"
1f688557 12#include "delta.h"
a733cb60 13#include "pack.h"
0fcfd160 14
144bde78
LT
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
88cd621d
JH
23const unsigned char null_sha1[20] = { 0, };
24
144bde78
LT
25static unsigned int sha1_file_open_flag = O_NOATIME;
26
0fcfd160
LT
27static 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
38int 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
b2cb9425
JH
51int 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}
723c31fe 69
0fcfd160
LT
70char * 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
ace1534d
JH
85static 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
0fcfd160
LT
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.
ace1534d
JH
101 *
102 * Also note that this returns the location for creating. Reading
103 * SHA1 file can happen from any alternate directory listed in the
d19938ab 104 * DB_ENVIRONMENT environment variable if it is not found in
ace1534d 105 * the primary object database.
0fcfd160
LT
106 */
107char *sha1_file_name(const unsigned char *sha1)
108{
0fcfd160
LT
109 static char *name, *base;
110
111 if (!base) {
d19938ab 112 const char *sha1_file_directory = get_object_directory();
0fcfd160 113 int len = strlen(sha1_file_directory);
812666c8 114 base = xmalloc(len + 60);
0fcfd160
LT
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 }
ace1534d 121 fill_sha1_path(name, sha1);
0fcfd160
LT
122 return base;
123}
124
bf592c50
DB
125char *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
150char *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
d5a63b99
JH
175struct alternate_object_database *alt_odb_list;
176static struct alternate_object_database **alt_odb_tail;
ace1534d 177
ddd5d056
JH
178/*
179 * Prepare alternate object database registry.
d5a63b99
JH
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.
ddd5d056 192 */
ccfd3e99
JH
193static void link_alt_odb_entries(const char *alt, const char *ep, int sep,
194 const char *relative_base)
ace1534d 195{
ace1534d 196 const char *cp, *last;
d5a63b99 197 struct alternate_object_database *ent;
ccfd3e99 198 int base_len = -1;
d5a63b99
JH
199
200 last = alt;
9577e7e3
JH
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++)
d5a63b99
JH
210 ;
211 if (last != cp) {
212 /* 43 = 40-byte + 2 '/' + terminating NUL */
213 int pfxlen = cp - last;
214 int entlen = pfxlen + 43;
215
ccfd3e99
JH
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 }
d5a63b99
JH
223 ent = xmalloc(sizeof(*ent) + entlen);
224 *alt_odb_tail = ent;
225 alt_odb_tail = &(ent->next);
226 ent->next = NULL;
ccfd3e99
JH
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);
d5a63b99
JH
235 ent->name = ent->base + pfxlen + 1;
236 ent->base[pfxlen] = ent->base[pfxlen + 3] = '/';
237 ent->base[entlen-1] = 0;
238 }
9577e7e3 239 while (cp < ep && *cp == sep)
d5a63b99
JH
240 cp++;
241 last = cp;
9577e7e3 242 }
d5a63b99
JH
243}
244
245void prepare_alt_odb(void)
246{
247 char path[PATH_MAX];
9577e7e3 248 char *map;
d5a63b99
JH
249 int fd;
250 struct stat st;
c7c81b3a
JR
251 char *alt;
252
a9ab586a 253 alt = getenv(ALTERNATE_DB_ENVIRONMENT);
c7c81b3a 254 if (!alt) alt = "";
ace1534d 255
d5a63b99
JH
256 if (alt_odb_tail)
257 return;
258 alt_odb_tail = &alt_odb_list;
ccfd3e99 259 link_alt_odb_entries(alt, alt + strlen(alt), ':', NULL);
d5a63b99 260
ccfd3e99 261 sprintf(path, "%s/info/alternates", get_object_directory());
d5a63b99
JH
262 fd = open(path, O_RDONLY);
263 if (fd < 0)
264 return;
265 if (fstat(fd, &st) || (st.st_size == 0)) {
266 close(fd);
9a217f2a 267 return;
ace1534d 268 }
d5a63b99
JH
269 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
270 close(fd);
271 if (map == MAP_FAILED)
272 return;
273
ccfd3e99
JH
274 link_alt_odb_entries(map, map + st.st_size, '\n',
275 get_object_directory());
d5a63b99 276 munmap(map, st.st_size);
ace1534d
JH
277}
278
279static char *find_sha1_file(const unsigned char *sha1, struct stat *st)
280{
ace1534d 281 char *name = sha1_file_name(sha1);
d5a63b99 282 struct alternate_object_database *alt;
ace1534d
JH
283
284 if (!stat(name, st))
285 return name;
9a217f2a 286 prepare_alt_odb();
d5a63b99
JH
287 for (alt = alt_odb_list; alt; alt = alt->next) {
288 name = alt->name;
ace1534d 289 fill_sha1_path(name, sha1);
d5a63b99
JH
290 if (!stat(alt->base, st))
291 return alt->base;
ace1534d
JH
292 }
293 return NULL;
294}
295
1f688557
JH
296#define PACK_MAX_SZ (1<<26)
297static int pack_used_ctr;
298static unsigned long pack_mapped;
9a217f2a 299struct packed_git *packed_git;
1f688557 300
1f688557
JH
301static 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;
4d235c80
LT
323 *idx_map_ = idx_map;
324 *idx_size_ = idx_size;
1f688557
JH
325
326 /* check index map */
f9253394 327 if (idx_size < 4*256 + 20 + 20)
1f688557
JH
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
1f688557
JH
347 return 0;
348}
349
f9253394 350static int unuse_one_packed_git(void)
1f688557 351{
f9253394
JH
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
367void unuse_packed_git(struct packed_git *p)
368{
369 p->pack_use_cnt--;
1f688557
JH
370}
371
f9253394 372int use_packed_git(struct packed_git *p)
1f688557 373{
bf592c50
DB
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 }
1f688557
JH
382 if (!p->pack_base) {
383 int fd;
384 struct stat st;
385 void *map;
386
387 pack_mapped += p->pack_size;
f9253394
JH
388 while (PACK_MAX_SZ < pack_mapped && unuse_one_packed_git())
389 ; /* nothing */
1f688557
JH
390 fd = open(p->pack_name, O_RDONLY);
391 if (fd < 0)
f9253394 392 die("packfile %s cannot be opened", p->pack_name);
1f688557
JH
393 if (fstat(fd, &st)) {
394 close(fd);
f9253394 395 die("packfile %s cannot be opened", p->pack_name);
1f688557
JH
396 }
397 if (st.st_size != p->pack_size)
f9253394 398 die("packfile %s size mismatch.", p->pack_name);
1f688557
JH
399 map = mmap(NULL, p->pack_size, PROT_READ, MAP_PRIVATE, fd, 0);
400 close(fd);
401 if (map == MAP_FAILED)
f9253394 402 die("packfile %s cannot be mapped.", p->pack_name);
1f688557 403 p->pack_base = map;
f9253394
JH
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,
bf592c50
DB
409 p->pack_base + p->pack_size - 20, 20)) {
410
f9253394 411 die("packfile %s does not match index.", p->pack_name);
bf592c50 412 }
1f688557
JH
413 }
414 p->pack_last_used = pack_used_ctr++;
f9253394 415 p->pack_use_cnt++;
1f688557
JH
416 return 0;
417}
418
9d835df2 419struct packed_git *add_packed_git(char *path, int path_len, int local)
1f688557
JH
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;
d85a4fee 444 p->pack_base = NULL;
1f688557 445 p->pack_last_used = 0;
f9253394 446 p->pack_use_cnt = 0;
9d835df2 447 p->pack_local = local;
1f688557
JH
448 return p;
449}
450
bf592c50 451struct packed_git *parse_pack_index(unsigned char *sha1)
c508df5e
DB
452{
453 char *path = sha1_pack_index_name(sha1);
454 return parse_pack_index_file(sha1, path);
455}
456
2ab141a2 457struct packed_git *parse_pack_index_file(const unsigned char *sha1, char *idx_path)
bf592c50
DB
458{
459 struct packed_git *p;
460 unsigned long idx_size;
461 void *idx_map;
c508df5e 462 char *path;
bf592c50 463
c508df5e 464 if (check_packed_git_idx(idx_path, &idx_size, &idx_map))
bf592c50
DB
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
482void install_packed_git(struct packed_git *pack)
483{
484 pack->next = packed_git;
485 packed_git = pack;
486}
487
9d835df2 488static void prepare_packed_git_one(char *objdir, int local)
1f688557
JH
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);
9d835df2 510 p = add_packed_git(path, len + namelen, local);
1f688557
JH
511 if (!p)
512 continue;
513 p->next = packed_git;
514 packed_git = p;
515 }
5b35bcd5 516 closedir(dir);
1f688557
JH
517}
518
9a217f2a 519void prepare_packed_git(void)
1f688557 520{
1f688557 521 static int run_once = 0;
d5a63b99 522 struct alternate_object_database *alt;
1f688557 523
d5a63b99 524 if (run_once)
1f688557 525 return;
9d835df2 526 prepare_packed_git_one(get_object_directory(), 1);
9a217f2a 527 prepare_alt_odb();
d5a63b99
JH
528 for (alt = alt_odb_list; alt; alt = alt->next) {
529 alt->name[0] = 0;
9d835df2 530 prepare_packed_git_one(alt->base, 0);
1f688557 531 }
d5a63b99 532 run_once = 1;
1f688557
JH
533}
534
5d6ccf5c 535int check_sha1_signature(const unsigned char *sha1, void *map, unsigned long size, const char *type)
0fcfd160 536{
d98b46f8 537 char header[100];
0fcfd160
LT
538 unsigned char real_sha1[20];
539 SHA_CTX c;
540
541 SHA1_Init(&c);
d98b46f8 542 SHA1_Update(&c, header, 1+sprintf(header, "%s %lu", type, size));
0fcfd160
LT
543 SHA1_Update(&c, map, size);
544 SHA1_Final(real_sha1, &c);
545 return memcmp(sha1, real_sha1, 20) ? -1 : 0;
546}
547
1f688557 548static void *map_sha1_file_internal(const unsigned char *sha1,
d5f1befc 549 unsigned long *size)
0fcfd160 550{
0fcfd160
LT
551 struct stat st;
552 void *map;
144bde78 553 int fd;
ace1534d
JH
554 char *filename = find_sha1_file(sha1, &st);
555
556 if (!filename) {
ace1534d
JH
557 return NULL;
558 }
0fcfd160 559
144bde78 560 fd = open(filename, O_RDONLY | sha1_file_open_flag);
0fcfd160 561 if (fd < 0) {
144bde78
LT
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:
144bde78
LT
570 return NULL;
571 }
572
1f688557
JH
573 /* If it failed once, it will probably fail again.
574 * Stop using O_NOATIME
575 */
144bde78 576 sha1_file_open_flag = 0;
0fcfd160 577 }
0fcfd160
LT
578 map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
579 close(fd);
e35f9824 580 if (map == MAP_FAILED)
0fcfd160
LT
581 return NULL;
582 *size = st.st_size;
583 return map;
584}
585
c4483576
LT
586int 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
6da4016a 599static void *unpack_sha1_rest(z_stream *stream, void *buffer, unsigned long size)
5180cacc
LT
600{
601 int bytes = strlen(buffer) + 1;
d565b341 602 unsigned char *buf = xmalloc(1+size);
5180cacc
LT
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 */
622int 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
0fcfd160
LT
667void * unpack_sha1_file(void *map, unsigned long mapsize, char *type, unsigned long *size)
668{
5180cacc 669 int ret;
0fcfd160 670 z_stream stream;
5180cacc 671 char hdr[8192];
0fcfd160 672
5180cacc
LT
673 ret = unpack_sha1_header(&stream, map, mapsize, hdr, sizeof(hdr));
674 if (ret < Z_OK || parse_sha1_header(hdr, type, size) < 0)
0fcfd160
LT
675 return NULL;
676
5180cacc 677 return unpack_sha1_rest(&stream, hdr, *size);
0fcfd160
LT
678}
679
f3bf9224
JH
680/* forward declaration for a mutually recursive function */
681static int packed_object_info(struct pack_entry *entry,
682 char *type, unsigned long *sizep);
683
5db47c2b
JH
684static int packed_delta_info(unsigned char *base_sha1,
685 unsigned long delta_size,
686 unsigned long left,
687 char *type,
f3bf9224
JH
688 unsigned long *sizep,
689 struct packed_git *p)
5db47c2b 690{
f3bf9224
JH
691 struct pack_entry base_ent;
692
5db47c2b
JH
693 if (left < 20)
694 die("truncated pack file");
5db47c2b 695
f3bf9224
JH
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
c62266f3
JH
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 */
5db47c2b 706
f3bf9224 707 if (packed_object_info(&base_ent, type, NULL))
c62266f3 708 die("cannot get info for delta-pack base");
5db47c2b 709
c62266f3
JH
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 */
5db47c2b 736
c62266f3
JH
737 /* Read the result size */
738 result_size = get_delta_hdr_size(&data);
739 *sizep = result_size;
740 }
5db47c2b
JH
741 return 0;
742}
743
a733cb60
LT
744static unsigned long unpack_object_header(struct packed_git *p, unsigned long offset,
745 enum object_type *type, unsigned long *sizep)
746{
01247d87 747 unsigned shift;
a733cb60
LT
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;
01247d87 759 shift = 4;
a733cb60
LT
760 while (c & 0x80) {
761 if (offset >= p->pack_size)
762 die("object offset outside of pack file");
763 c = *pack++;
764 offset++;
01247d87
LT
765 size += (c & 0x7f) << shift;
766 shift += 7;
a733cb60
LT
767 }
768 *sizep = size;
769 return offset;
770}
771
ad8c80a5
JH
772void 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:
264b16b6
JH
818 die("corrupted pack file %s containing object of kind %d",
819 p->pack_name, kind);
ad8c80a5
JH
820 }
821 *store_size = 0; /* notyet */
822}
823
1f688557
JH
824static 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;
a733cb60 830 enum object_type kind;
f9253394 831 int retval;
5db47c2b
JH
832
833 if (use_packed_git(p))
834 die("cannot map packed file");
835
a733cb60 836 offset = unpack_object_header(p, entry->offset, &kind, &size);
1f688557 837 pack = p->pack_base + offset;
a733cb60
LT
838 left = p->pack_size - offset;
839
840 switch (kind) {
841 case OBJ_DELTA:
f3bf9224 842 retval = packed_delta_info(pack, size, left, type, sizep, p);
f9253394
JH
843 unuse_packed_git(p);
844 return retval;
a733cb60 845 case OBJ_COMMIT:
1f688557
JH
846 strcpy(type, "commit");
847 break;
a733cb60 848 case OBJ_TREE:
1f688557
JH
849 strcpy(type, "tree");
850 break;
a733cb60 851 case OBJ_BLOB:
1f688557
JH
852 strcpy(type, "blob");
853 break;
a733cb60 854 case OBJ_TAG:
a69d0943
LT
855 strcpy(type, "tag");
856 break;
1f688557 857 default:
264b16b6
JH
858 die("corrupted pack file %s containing object of kind %d",
859 p->pack_name, kind);
1f688557 860 }
c62266f3
JH
861 if (sizep)
862 *sizep = size;
f9253394 863 unuse_packed_git(p);
1f688557
JH
864 return 0;
865}
866
867/* forward declaration for a mutually recursive function */
868static void *unpack_entry(struct pack_entry *, char *, unsigned long *);
869
870static void *unpack_delta_entry(unsigned char *base_sha1,
871 unsigned long delta_size,
872 unsigned long left,
873 char *type,
f3bf9224
JH
874 unsigned long *sizep,
875 struct packed_git *p)
1f688557 876{
f3bf9224 877 struct pack_entry base_ent;
1f688557
JH
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
f3bf9224
JH
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);
1f688557
JH
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
921static void *unpack_non_delta_entry(unsigned char *data,
922 unsigned long size,
923 unsigned long left)
924{
925 int st;
926 z_stream stream;
4d235c80 927 unsigned char *buffer;
1f688557
JH
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
948static void *unpack_entry(struct pack_entry *entry,
949 char *type, unsigned long *sizep)
950{
951 struct packed_git *p = entry->p;
f9253394 952 void *retval;
1f688557
JH
953
954 if (use_packed_git(p))
955 die("cannot map packed file");
f3bf9224
JH
956 retval = unpack_entry_gently(entry, type, sizep);
957 unuse_packed_git(p);
958 if (!retval)
264b16b6 959 die("corrupted pack file %s", p->pack_name);
f3bf9224
JH
960 return retval;
961}
962
963/* The caller is responsible for use_packed_git()/unuse_packed_git() pair */
964void *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;
1f688557 972
a733cb60 973 offset = unpack_object_header(p, entry->offset, &kind, &size);
1f688557 974 pack = p->pack_base + offset;
a733cb60
LT
975 left = p->pack_size - offset;
976 switch (kind) {
977 case OBJ_DELTA:
f3bf9224 978 retval = unpack_delta_entry(pack, size, left, type, sizep, p);
f9253394 979 return retval;
a733cb60 980 case OBJ_COMMIT:
1f688557
JH
981 strcpy(type, "commit");
982 break;
a733cb60 983 case OBJ_TREE:
1f688557
JH
984 strcpy(type, "tree");
985 break;
a733cb60 986 case OBJ_BLOB:
1f688557
JH
987 strcpy(type, "blob");
988 break;
a733cb60 989 case OBJ_TAG:
a69d0943
LT
990 strcpy(type, "tag");
991 break;
1f688557 992 default:
f3bf9224 993 return NULL;
1f688557
JH
994 }
995 *sizep = size;
f9253394 996 retval = unpack_non_delta_entry(pack, size, left);
f9253394 997 return retval;
1f688557
JH
998}
999
9a217f2a
JH
1000int num_packed_objects(const struct packed_git *p)
1001{
f9253394 1002 /* See check_packed_git_idx() */
9a217f2a
JH
1003 return (p->index_size - 20 - 20 - 4*256) / 24;
1004}
1005
1006int 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
f3bf9224
JH
1016int find_pack_entry_one(const unsigned char *sha1,
1017 struct pack_entry *e, struct packed_git *p)
1f688557 1018{
4d235c80 1019 unsigned int *level1_ofs = p->index_base;
1f688557
JH
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
1041static 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) {
f3bf9224 1047 if (find_pack_entry_one(sha1, e, p))
1f688557
JH
1048 return 1;
1049 }
1050 return 0;
1051}
1052
bf592c50
DB
1053struct 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
36e4d74a 1067int sha1_object_info(const unsigned char *sha1, char *type, unsigned long *sizep)
65c2e0c3 1068{
36e4d74a 1069 int status;
65c2e0c3
JH
1070 unsigned long mapsize, size;
1071 void *map;
1072 z_stream stream;
36e4d74a 1073 char hdr[128];
65c2e0c3 1074
d5f1befc 1075 map = map_sha1_file_internal(sha1, &mapsize);
1f688557
JH
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));
c62266f3 1081 return packed_object_info(&e, type, sizep);
1f688557 1082 }
36e4d74a
JH
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));
c4584ae3 1088 else {
65c2e0c3 1089 status = 0;
c62266f3
JH
1090 if (sizep)
1091 *sizep = size;
65c2e0c3 1092 }
65c2e0c3
JH
1093 inflateEnd(&stream);
1094 munmap(map, mapsize);
1095 return status;
1096}
1097
1f688557
JH
1098static 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
0fcfd160
LT
1109void * read_sha1_file(const unsigned char *sha1, char *type, unsigned long *size)
1110{
1111 unsigned long mapsize;
1112 void *map, *buf;
ab90ea5d 1113 struct pack_entry e;
0fcfd160 1114
ab90ea5d
JH
1115 if (find_pack_entry(sha1, &e))
1116 return read_packed_sha1(sha1, type, size);
d5f1befc 1117 map = map_sha1_file_internal(sha1, &mapsize);
0fcfd160
LT
1118 if (map) {
1119 buf = unpack_sha1_file(map, mapsize, type, size);
1120 munmap(map, mapsize);
1121 return buf;
1122 }
ab90ea5d 1123 return NULL;
0fcfd160
LT
1124}
1125
40469ee9 1126void *read_object_with_reference(const unsigned char *sha1,
bf0f910d 1127 const char *required_type,
40469ee9
JH
1128 unsigned long *size,
1129 unsigned char *actual_sha1_return)
f4913f91
JH
1130{
1131 char type[20];
1132 void *buffer;
1133 unsigned long isize;
40469ee9 1134 unsigned char actual_sha1[20];
f4913f91 1135
40469ee9
JH
1136 memcpy(actual_sha1, sha1, 20);
1137 while (1) {
1138 int ref_length = -1;
1139 const char *ref_type = NULL;
f4913f91 1140
40469ee9
JH
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);
f4913f91 1160
40469ee9
JH
1161 if (memcmp(buffer, ref_type, ref_length) ||
1162 get_sha1_hex(buffer + ref_length, actual_sha1)) {
1163 free(buffer);
1164 return NULL;
1165 }
1cf58e72 1166 free(buffer);
40469ee9
JH
1167 /* Now we have the ID of the referred-to object in
1168 * actual_sha1. Check again. */
f4913f91 1169 }
f4913f91
JH
1170}
1171
7672db20
BL
1172char *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)
d410c0f5
JH
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
230f1322
LT
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 */
1199static 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 */
b721e01f 1232int move_temp_to_file(const char *tmpfile, char *filename)
230f1322
LT
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 *
9e48b389
JS
1242 * The same holds for FAT formatted media.
1243 *
230f1322
LT
1244 * When this succeeds, we just return 0. We have nothing
1245 * left to unlink.
1246 */
9e48b389 1247 if ((ret == EXDEV || ret == ENOTSUP) && !rename(tmpfile, filename))
230f1322 1248 return 0;
9e48b389 1249 ret = errno;
230f1322
LT
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
bf0f910d 1263int write_sha1_file(void *buf, unsigned long len, const char *type, unsigned char *returnsha1)
0fcfd160
LT
1264{
1265 int size;
bf0f910d 1266 unsigned char *compressed;
0fcfd160
LT
1267 z_stream stream;
1268 unsigned char sha1[20];
706bc531 1269 char *filename;
aac17941 1270 static char tmpfile[PATH_MAX];
bf0f910d 1271 unsigned char hdr[50];
230f1322 1272 int fd, hdrlen;
a44c9a5e 1273
d410c0f5
JH
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);
706bc531
LT
1278 if (returnsha1)
1279 memcpy(returnsha1, sha1, 20);
d410c0f5
JH
1280 if (has_sha1_file(sha1))
1281 return 0;
aac17941
LT
1282 fd = open(filename, O_RDONLY);
1283 if (fd >= 0) {
706bc531 1284 /*
aac17941
LT
1285 * FIXME!!! We might do collision checking here, but we'd
1286 * need to uncompress the old file and check it. Later.
706bc531 1287 */
aac17941 1288 close(fd);
706bc531
LT
1289 return 0;
1290 }
1291
aac17941
LT
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());
ace1534d 1298
aac17941
LT
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
0fcfd160
LT
1305 /* Set it up */
1306 memset(&stream, 0, sizeof(stream));
1307 deflateInit(&stream, Z_BEST_COMPRESSION);
a44c9a5e 1308 size = deflateBound(&stream, len+hdrlen);
812666c8 1309 compressed = xmalloc(size);
0fcfd160
LT
1310
1311 /* Compress it */
0fcfd160
LT
1312 stream.next_out = compressed;
1313 stream.avail_out = size;
a44c9a5e
LT
1314
1315 /* First header.. */
1316 stream.next_in = hdr;
1317 stream.avail_in = hdrlen;
1318 while (deflate(&stream, 0) == Z_OK)
6ffcee88 1319 /* nothing */;
a44c9a5e
LT
1320
1321 /* Then the data itself.. */
1322 stream.next_in = buf;
1323 stream.avail_in = len;
0fcfd160
LT
1324 while (deflate(&stream, Z_FINISH) == Z_OK)
1325 /* nothing */;
1326 deflateEnd(&stream);
1327 size = stream.total_out;
1328
706bc531
LT
1329 if (write(fd, compressed, size) != size)
1330 die("unable to write file");
aac17941 1331 fchmod(fd, 0444);
706bc531 1332 close(fd);
383f85b7 1333 free(compressed);
0fcfd160 1334
230f1322 1335 return move_temp_to_file(tmpfile, filename);
0fcfd160 1336}
8237b185 1337
a5eda52b
DB
1338int write_sha1_to_fd(int fd, const unsigned char *sha1)
1339{
1340 ssize_t size;
1341 unsigned long objsize;
1342 int posn = 0;
bfc66daf
SV
1343 void *map = map_sha1_file_internal(sha1, &objsize);
1344 void *buf = map;
1345 void *temp_obj = NULL;
a5eda52b 1346 z_stream stream;
bfc66daf 1347
a5eda52b
DB
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);
bfc66daf 1363 temp_obj = buf = xmalloc(size);
a5eda52b
DB
1364
1365 /* Compress it */
1366 stream.next_out = buf;
1367 stream.avail_out = size;
1368
1369 /* First header.. */
0ee19dce 1370 stream.next_in = (void *)hdr;
a5eda52b
DB
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);
bfc66daf 1381 free(unpacked);
a5eda52b
DB
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);
bfc66daf
SV
1398
1399 if (map)
1400 munmap(map, objsize);
1401 if (temp_obj)
1402 free(temp_obj);
1403
a5eda52b
DB
1404 return 0;
1405}
1406
70b9829e
DB
1407int write_sha1_from_fd(const unsigned char *sha1, int fd, char *buffer,
1408 size_t bufsize, size_t *bufposn)
8237b185 1409{
230f1322 1410 char tmpfile[PATH_MAX];
8237b185
DB
1411 int local;
1412 z_stream stream;
1413 unsigned char real_sha1[20];
bf0f910d 1414 unsigned char discard[4096];
8237b185
DB
1415 int ret;
1416 SHA_CTX c;
1417
230f1322 1418 snprintf(tmpfile, sizeof(tmpfile), "%s/obj_XXXXXX", get_object_directory());
8237b185 1419
230f1322 1420 local = mkstemp(tmpfile);
8237b185 1421 if (local < 0)
230f1322 1422 return error("Couldn't open %s for %s\n", tmpfile, sha1_to_hex(sha1));
8237b185
DB
1423
1424 memset(&stream, 0, sizeof(stream));
1425
1426 inflateInit(&stream);
1427
1428 SHA1_Init(&c);
1429
1430 do {
1431 ssize_t size;
70b9829e
DB
1432 if (*bufposn) {
1433 stream.avail_in = *bufposn;
96ad15ae 1434 stream.next_in = (unsigned char *) buffer;
70b9829e
DB
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);
8237b185
DB
1450 if (size <= 0) {
1451 close(local);
230f1322 1452 unlink(tmpfile);
8237b185
DB
1453 if (!size)
1454 return error("Connection closed?");
1455 perror("Reading from connection");
1456 return -1;
1457 }
70b9829e
DB
1458 *bufposn += size;
1459 } while (1);
8237b185
DB
1460 inflateEnd(&stream);
1461
1462 close(local);
1463 SHA1_Final(real_sha1, &c);
1464 if (ret != Z_STREAM_END) {
230f1322 1465 unlink(tmpfile);
8237b185
DB
1466 return error("File %s corrupted", sha1_to_hex(sha1));
1467 }
1468 if (memcmp(sha1, real_sha1, 20)) {
230f1322 1469 unlink(tmpfile);
8237b185
DB
1470 return error("File %s has bad hash\n", sha1_to_hex(sha1));
1471 }
230f1322
LT
1472
1473 return move_temp_to_file(tmpfile, sha1_file_name(sha1));
8237b185
DB
1474}
1475
bf592c50
DB
1476int 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
1484int 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
dade09c2
LT
1492int has_sha1_pack(const unsigned char *sha1)
1493{
1494 struct pack_entry e;
1495 return find_pack_entry(sha1, &e);
1496}
1497
8237b185
DB
1498int has_sha1_file(const unsigned char *sha1)
1499{
8237b185 1500 struct stat st;
1f688557
JH
1501 struct pack_entry e;
1502
ab90ea5d 1503 if (find_pack_entry(sha1, &e))
1f688557 1504 return 1;
ab90ea5d 1505 return find_sha1_file(sha1, &st) ? 1 : 0;
8237b185 1506}
74400e71 1507
7672db20 1508int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, const char *type)
74400e71 1509{
74400e71 1510 unsigned long size = st->st_size;
aac17941
LT
1511 void *buf;
1512 int ret;
7672db20
BL
1513 unsigned char hdr[50];
1514 int hdrlen;
74400e71 1515
aac17941 1516 buf = "";
74400e71 1517 if (size)
aac17941 1518 buf = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
74400e71 1519 close(fd);
e35f9824 1520 if (buf == MAP_FAILED)
74400e71
JH
1521 return -1;
1522
7672db20
BL
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 }
aac17941
LT
1531 if (size)
1532 munmap(buf, size);
1533 return ret;
74400e71 1534}
ec1fcc16
JH
1535
1536int 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}