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