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