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