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