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