at commit aae63be1

1 /*
2 * GIT - The information manager from hell
3 *
4 * Copyright (C) Linus Torvalds, 2005
5 *
6 * This handles basic git object files - packing, unpacking,
7 * creation etc.
8 */
9
10 #define USE_THE_REPOSITORY_VARIABLE
11
12 #include "git-compat-util.h"
13 #include "convert.h"
14 #include "dir.h"
15 #include "environment.h"
16 #include "fsck.h"
17 #include "gettext.h"
18 #include "hex.h"
19 #include "loose.h"
20 #include "object-file-convert.h"
21 #include "object-file.h"
22 #include "odb.h"
23 #include "odb/streaming.h"
24 #include "odb/transaction.h"
25 #include "pack.h"
26 #include "packfile.h"
27 #include "path.h"
28 #include "read-cache-ll.h"
29 #include "setup.h"
30 #include "strvec.h"
31 #include "tempfile.h"
32 #include "tmp-objdir.h"
33
34 static int get_conv_flags(unsigned flags)
35 {
36 if (flags & INDEX_RENORMALIZE)
37 return CONV_EOL_RENORMALIZE;
38 else if (flags & INDEX_WRITE_OBJECT)
39 return global_conv_flags_eol | CONV_WRITE_OBJECT;
40 else
41 return 0;
42 }
43
44 static void fill_loose_path(struct strbuf *buf,
45 const struct object_id *oid,
46 const struct git_hash_algo *algop)
47 {
48 for (size_t i = 0; i < algop->rawsz; i++) {
49 static char hex[] = "0123456789abcdef";
50 unsigned int val = oid->hash[i];
51 strbuf_addch(buf, hex[val >> 4]);
52 strbuf_addch(buf, hex[val & 0xf]);
53 if (!i)
54 strbuf_addch(buf, '/');
55 }
56 }
57
58 const char *odb_loose_path(struct odb_source_loose *loose,
59 struct strbuf *buf,
60 const struct object_id *oid)
61 {
62 strbuf_reset(buf);
63 strbuf_addstr(buf, loose->base.path);
64 strbuf_addch(buf, '/');
65 fill_loose_path(buf, oid, loose->base.odb->repo->hash_algo);
66 return buf->buf;
67 }
68
69 /* Returns 1 if we have successfully freshened the file, 0 otherwise. */
70 static int freshen_file(const char *fn, const time_t *mtime)
71 {
72 struct utimbuf times, *timesp = NULL;
73
74 if (mtime) {
75 times.actime = *mtime;
76 times.modtime = *mtime;
77 timesp = &times;
78 }
79
80 return !utime(fn, timesp);
81 }
82
83 /*
84 * All of the check_and_freshen functions return 1 if the file exists and was
85 * freshened (if freshening was requested), 0 otherwise. If they return
86 * 0, you should not assume that it is safe to skip a write of the object (it
87 * either does not exist on disk, or has a stale mtime and may be subject to
88 * pruning).
89 */
90 int check_and_freshen_file(const char *fn, int freshen,
91 const time_t *mtime)
92 {
93 if (access(fn, F_OK))
94 return 0;
95 if (freshen && !freshen_file(fn, mtime))
96 return 0;
97 return 1;
98 }
99
100 int format_object_header(char *str, size_t size, enum object_type type,
101 size_t objsize)
102 {
103 const char *name = type_name(type);
104
105 if (!name)
106 BUG("could not get a type name for 'enum object_type' value %d", type);
107
108 return xsnprintf(str, size, "%s %"PRIuMAX, name, (uintmax_t)objsize) + 1;
109 }
110
111 int check_object_signature(struct repository *r, const struct object_id *oid,
112 void *buf, unsigned long size,
113 enum object_type type)
114 {
115 const struct git_hash_algo *algo =
116 oid->algo ? &hash_algos[oid->algo] : r->hash_algo;
117 struct object_id real_oid;
118
119 hash_object_file(algo, buf, size, type, &real_oid);
120
121 return !oideq(oid, &real_oid) ? -1 : 0;
122 }
123
124 int stream_object_signature(struct repository *r,
125 struct odb_stream *st,
126 const struct object_id *oid)
127 {
128 struct object_id real_oid;
129 struct git_hash_ctx c;
130 char hdr[MAX_HEADER_LEN];
131 int hdrlen;
132
133 /* Generate the header */
134 hdrlen = format_object_header(hdr, sizeof(hdr), st->type, st->size);
135
136 /* Sha1.. */
137 git_hash_init(&c, r->hash_algo);
138 git_hash_update(&c, hdr, hdrlen);
139 for (;;) {
140 char buf[1024 * 16];
141 ssize_t readlen = odb_stream_read(st, buf, sizeof(buf));
142 if (readlen < 0)
143 return -1;
144 if (!readlen)
145 break;
146 git_hash_update(&c, buf, readlen);
147 }
148 git_hash_final_oid(&real_oid, &c);
149 return !oideq(oid, &real_oid) ? -1 : 0;
150 }
151
152 /*
153 * Map and close the given loose object fd. The path argument is used for
154 * error reporting.
155 */
156 static void *map_fd(int fd, const char *path, unsigned long *size)
157 {
158 void *map = NULL;
159 struct stat st;
160
161 if (!fstat(fd, &st)) {
162 *size = xsize_t(st.st_size);
163 if (!*size) {
164 /* mmap() is forbidden on empty files */
165 error(_("object file %s is empty"), path);
166 close(fd);
167 return NULL;
168 }
169 map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
170 }
171 close(fd);
172 return map;
173 }
174
175 enum unpack_loose_header_result unpack_loose_header(git_zstream *stream,
176 unsigned char *map,
177 unsigned long mapsize,
178 void *buffer,
179 unsigned long bufsiz)
180 {
181 int status;
182
183 /* Get the data stream */
184 memset(stream, 0, sizeof(*stream));
185 stream->next_in = map;
186 stream->avail_in = mapsize;
187 stream->next_out = buffer;
188 stream->avail_out = bufsiz;
189
190 git_inflate_init(stream);
191 obj_read_unlock();
192 status = git_inflate(stream, 0);
193 obj_read_lock();
194 if (status != Z_OK && status != Z_STREAM_END)
195 return ULHR_BAD;
196
197 /*
198 * Check if entire header is unpacked in the first iteration.
199 */
200 if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
201 return ULHR_OK;
202
203 /*
204 * We have a header longer than MAX_HEADER_LEN.
205 */
206 return ULHR_TOO_LONG;
207 }
208
209 void *unpack_loose_rest(git_zstream *stream,
210 void *buffer, unsigned long size,
211 const struct object_id *oid)
212 {
213 size_t bytes = strlen(buffer) + 1, n;
214 unsigned char *buf = xmallocz(size);
215 int status = Z_OK;
216
217 n = stream->total_out - bytes;
218 if (n > size)
219 n = size;
220 memcpy(buf, (char *) buffer + bytes, n);
221 bytes = n;
222 if (bytes <= size) {
223 /*
224 * The above condition must be (bytes <= size), not
225 * (bytes < size). In other words, even though we
226 * expect no more output and set avail_out to zero,
227 * the input zlib stream may have bytes that express
228 * "this concludes the stream", and we *do* want to
229 * eat that input.
230 *
231 * Otherwise we would not be able to test that we
232 * consumed all the input to reach the expected size;
233 * we also want to check that zlib tells us that all
234 * went well with status == Z_STREAM_END at the end.
235 */
236 stream->next_out = buf + bytes;
237 stream->avail_out = size - bytes;
238 while (status == Z_OK) {
239 obj_read_unlock();
240 status = git_inflate(stream, Z_FINISH);
241 obj_read_lock();
242 }
243 }
244
245 if (status != Z_STREAM_END) {
246 error(_("corrupt loose object '%s'"), oid_to_hex(oid));
247 FREE_AND_NULL(buf);
248 } else if (stream->avail_in) {
249 error(_("garbage at end of loose object '%s'"),
250 oid_to_hex(oid));
251 FREE_AND_NULL(buf);
252 }
253
254 return buf;
255 }
256
257 /*
258 * parse_loose_header() parses the starting "<type> <len>\0" of an
259 * object. If it doesn't follow that format -1 is returned. To check
260 * the validity of the <type> populate the "typep" in the "struct
261 * object_info". It will be OBJ_BAD if the object type is unknown. The
262 * parsed <len> can be retrieved via "oi->sizep", and from there
263 * passed to unpack_loose_rest().
264 *
265 * We used to just use "sscanf()", but that's actually way
266 * too permissive for what we want to check. So do an anal
267 * object header parse by hand.
268 */
269 int parse_loose_header(const char *hdr, struct object_info *oi)
270 {
271 const char *type_buf = hdr;
272 size_t size;
273 int type, type_len = 0;
274
275 /*
276 * The type can be of any size but is followed by
277 * a space.
278 */
279 for (;;) {
280 char c = *hdr++;
281 if (!c)
282 return -1;
283 if (c == ' ')
284 break;
285 type_len++;
286 }
287
288 type = type_from_string_gently(type_buf, type_len, 1);
289 if (oi->typep)
290 *oi->typep = type;
291
292 /*
293 * The length must follow immediately, and be in canonical
294 * decimal format (ie "010" is not valid).
295 */
296 size = *hdr++ - '0';
297 if (size > 9)
298 return -1;
299 if (size) {
300 for (;;) {
301 unsigned long c = *hdr - '0';
302 if (c > 9)
303 break;
304 hdr++;
305 size = st_add(st_mult(size, 10), c);
306 }
307 }
308
309 if (oi->sizep)
310 *oi->sizep = size;
311
312 /*
313 * The length must be followed by a zero byte
314 */
315 if (*hdr)
316 return -1;
317
318 /*
319 * The format is valid, but the type may still be bogus. The
320 * Caller needs to check its oi->typep.
321 */
322 return 0;
323 }
324
325 #define CHECK_COLLISION_DEST_VANISHED -2
326
327 static int check_collision(const char *source, const char *dest)
328 {
329 char buf_source[4096], buf_dest[4096];
330 int fd_source = -1, fd_dest = -1;
331 int ret = 0;
332
333 fd_source = open(source, O_RDONLY);
334 if (fd_source < 0) {
335 ret = error_errno(_("unable to open %s"), source);
336 goto out;
337 }
338
339 fd_dest = open(dest, O_RDONLY);
340 if (fd_dest < 0) {
341 if (errno != ENOENT)
342 ret = error_errno(_("unable to open %s"), dest);
343 else
344 ret = CHECK_COLLISION_DEST_VANISHED;
345 goto out;
346 }
347
348 while (1) {
349 ssize_t sz_a, sz_b;
350
351 sz_a = read_in_full(fd_source, buf_source, sizeof(buf_source));
352 if (sz_a < 0) {
353 ret = error_errno(_("unable to read %s"), source);
354 goto out;
355 }
356
357 sz_b = read_in_full(fd_dest, buf_dest, sizeof(buf_dest));
358 if (sz_b < 0) {
359 ret = error_errno(_("unable to read %s"), dest);
360 goto out;
361 }
362
363 if (sz_a != sz_b || memcmp(buf_source, buf_dest, sz_a)) {
364 ret = error(_("files '%s' and '%s' differ in contents"),
365 source, dest);
366 goto out;
367 }
368
369 if ((size_t) sz_a < sizeof(buf_source))
370 break;
371 }
372
373 out:
374 if (fd_source > -1)
375 close(fd_source);
376 if (fd_dest > -1)
377 close(fd_dest);
378 return ret;
379 }
380
381 /*
382 * Move the just written object into its final resting place.
383 */
384 int finalize_object_file(struct repository *repo,
385 const char *tmpfile, const char *filename)
386 {
387 return finalize_object_file_flags(repo, tmpfile, filename, 0);
388 }
389
390 int finalize_object_file_flags(struct repository *repo,
391 const char *tmpfile, const char *filename,
392 enum finalize_object_file_flags flags)
393 {
394 unsigned retries = 0;
395 int ret;
396 struct repo_config_values *cfg = repo_config_values(repo);
397
398 retry:
399 ret = 0;
400
401 if (cfg->object_creation_mode == OBJECT_CREATION_USES_RENAMES)
402 goto try_rename;
403 else if (link(tmpfile, filename))
404 ret = errno;
405 else
406 unlink_or_warn(tmpfile);
407
408 /*
409 * Coda hack - coda doesn't like cross-directory links,
410 * so we fall back to a rename, which will mean that it
411 * won't be able to check collisions, but that's not a
412 * big deal.
413 *
414 * The same holds for FAT formatted media.
415 *
416 * When this succeeds, we just return. We have nothing
417 * left to unlink.
418 */
419 if (ret && ret != EEXIST) {
420 struct stat st;
421
422 try_rename:
423 if (!stat(filename, &st))
424 ret = EEXIST;
425 else if (!rename(tmpfile, filename))
426 goto out;
427 else
428 ret = errno;
429 }
430 if (ret) {
431 if (ret != EEXIST) {
432 int saved_errno = errno;
433 unlink_or_warn(tmpfile);
434 errno = saved_errno;
435 return error_errno(_("unable to write file %s"), filename);
436 }
437 if (!(flags & FOF_SKIP_COLLISION_CHECK)) {
438 ret = check_collision(tmpfile, filename);
439 if (ret == CHECK_COLLISION_DEST_VANISHED) {
440 if (retries++ > 5)
441 return error(_("unable to write repeatedly vanishing file %s"),
442 filename);
443 goto retry;
444 }
445 else if (ret)
446 return -1;
447 }
448 unlink_or_warn(tmpfile);
449 }
450
451 out:
452 if (adjust_shared_perm(repo, filename))
453 return error(_("unable to set permission to '%s'"), filename);
454 return 0;
455 }
456
457 void hash_object_file(const struct git_hash_algo *algo, const void *buf,
458 size_t len, enum object_type type,
459 struct object_id *oid)
460 {
461 struct git_hash_ctx c;
462 char hdr[MAX_HEADER_LEN];
463 int hdrlen;
464
465 hdrlen = format_object_header(hdr, sizeof(hdr), type, len);
466
467 git_hash_init(&c, algo);
468 git_hash_update(&c, hdr, hdrlen);
469 git_hash_update(&c, buf, len);
470 git_hash_final_oid(oid, &c);
471 }
472
473 struct transaction_packfile {
474 char *pack_tmp_name;
475 struct hashfile *f;
476 off_t offset;
477 struct pack_idx_option pack_idx_opts;
478
479 struct pack_idx_entry **written;
480 uint32_t alloc_written;
481 uint32_t nr_written;
482 };
483
484 struct odb_transaction_files {
485 struct odb_transaction base;
486
487 struct tmp_objdir *objdir;
488 struct transaction_packfile packfile;
489 const char *prefix;
490 };
491
492 int odb_transaction_files_prepare(struct odb_transaction *base)
493 {
494 struct odb_transaction_files *transaction =
495 container_of_or_null(base, struct odb_transaction_files, base);
496
497 /*
498 * We lazily create the temporary object directory
499 * the first time an object might be added, since
500 * callers may not know whether any objects will be
501 * added at the time they call odb_transaction_files_begin.
502 */
503 if (!transaction || transaction->objdir)
504 return 0;
505
506 transaction->objdir = tmp_objdir_create(base->source->odb->repo, transaction->prefix);
507 if (!transaction->objdir)
508 return error(_("unable to create temporary object directory"));
509
510 tmp_objdir_replace_primary_odb(transaction->objdir, 0);
511
512 return 0;
513 }
514
515 void odb_transaction_files_fsync(struct odb_transaction *base,
516 int fd, const char *filename)
517 {
518 struct odb_transaction_files *transaction =
519 container_of_or_null(base, struct odb_transaction_files, base);
520
521 if (!transaction || !transaction->objdir) {
522 fsync_or_die(fd, filename);
523 return;
524 }
525
526 /*
527 * If we have an active ODB transaction, we issue a call that
528 * cleans the filesystem page cache but avoids a hardware flush
529 * command. Later on we will issue a single hardware flush
530 * before renaming the objects to their final names as part of
531 * flush_batch_fsync.
532 */
533 if (git_fsync(fd, FSYNC_WRITEOUT_ONLY) < 0) {
534 if (errno == ENOSYS)
535 warning(_("core.fsyncMethod = batch is unsupported on this platform"));
536 fsync_or_die(fd, filename);
537 }
538 }
539
540 /*
541 * We can't use the normal fsck_error_function() for index_mem(),
542 * because we don't yet have a valid oid for it to report. Instead,
543 * report the minimal fsck error here, and rely on the caller to
544 * give more context.
545 */
546 static int hash_format_check_report(struct fsck_options *opts UNUSED,
547 void *fsck_report UNUSED,
548 enum fsck_msg_type msg_type UNUSED,
549 enum fsck_msg_id msg_id UNUSED,
550 const char *message)
551 {
552 error(_("object fails fsck: %s"), message);
553 return 1;
554 }
555
556 static int index_mem(struct index_state *istate,
557 struct object_id *oid,
558 const void *buf, size_t size,
559 enum object_type type,
560 const char *path, unsigned flags)
561 {
562 struct strbuf nbuf = STRBUF_INIT;
563 int ret = 0;
564 int write_object = flags & INDEX_WRITE_OBJECT;
565
566 if (!type)
567 type = OBJ_BLOB;
568
569 /*
570 * Convert blobs to git internal format
571 */
572 if ((type == OBJ_BLOB) && path) {
573 if (convert_to_git(istate, path, buf, size, &nbuf,
574 get_conv_flags(flags))) {
575 buf = nbuf.buf;
576 size = nbuf.len;
577 }
578 }
579 if (flags & INDEX_FORMAT_CHECK) {
580 struct fsck_options opts;
581
582 fsck_options_init(&opts, the_repository, FSCK_OPTIONS_DEFAULT);
583 opts.strict = 1;
584 opts.error_func = hash_format_check_report;
585 if (fsck_buffer(null_oid(istate->repo->hash_algo), type, buf, size, &opts))
586 die(_("refusing to create malformed object"));
587 fsck_finish(&opts);
588 }
589
590 if (write_object)
591 ret = odb_write_object(istate->repo->objects, buf, size, type, oid);
592 else
593 hash_object_file(istate->repo->hash_algo, buf, size, type, oid);
594
595 strbuf_release(&nbuf);
596 return ret;
597 }
598
599 static int index_stream_convert_blob(struct index_state *istate,
600 struct object_id *oid,
601 int fd,
602 const char *path,
603 unsigned flags)
604 {
605 int ret = 0;
606 const int write_object = flags & INDEX_WRITE_OBJECT;
607 struct strbuf sbuf = STRBUF_INIT;
608
609 assert(path);
610 ASSERT(would_convert_to_git_filter_fd(istate, path));
611
612 convert_to_git_filter_fd(istate, path, fd, &sbuf,
613 get_conv_flags(flags));
614
615 if (write_object)
616 ret = odb_write_object(istate->repo->objects, sbuf.buf, sbuf.len, OBJ_BLOB,
617 oid);
618 else
619 hash_object_file(istate->repo->hash_algo, sbuf.buf, sbuf.len, OBJ_BLOB,
620 oid);
621 strbuf_release(&sbuf);
622 return ret;
623 }
624
625 static int index_pipe(struct index_state *istate, struct object_id *oid,
626 int fd, enum object_type type,
627 const char *path, unsigned flags)
628 {
629 struct strbuf sbuf = STRBUF_INIT;
630 int ret;
631
632 if (strbuf_read(&sbuf, fd, 4096) >= 0)
633 ret = index_mem(istate, oid, sbuf.buf, sbuf.len, type, path, flags);
634 else
635 ret = -1;
636 strbuf_release(&sbuf);
637 return ret;
638 }
639
640 #define SMALL_FILE_SIZE (32*1024)
641
642 static int index_core(struct index_state *istate,
643 struct object_id *oid, int fd, size_t size,
644 enum object_type type, const char *path,
645 unsigned flags)
646 {
647 int ret;
648
649 if (!size) {
650 ret = index_mem(istate, oid, "", size, type, path, flags);
651 } else if (size <= SMALL_FILE_SIZE) {
652 char *buf = xmalloc(size);
653 ssize_t read_result = read_in_full(fd, buf, size);
654 if (read_result < 0)
655 ret = error_errno(_("read error while indexing %s"),
656 path ? path : "<unknown>");
657 else if ((size_t) read_result != size)
658 ret = error(_("short read while indexing %s"),
659 path ? path : "<unknown>");
660 else
661 ret = index_mem(istate, oid, buf, size, type, path, flags);
662 free(buf);
663 } else {
664 void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
665 ret = index_mem(istate, oid, buf, size, type, path, flags);
666 munmap(buf, size);
667 }
668 return ret;
669 }
670
671 static int already_written(struct odb_transaction_files *transaction,
672 struct object_id *oid)
673 {
674 /* The object may already exist in the repository */
675 if (odb_has_object(transaction->base.source->odb, oid,
676 ODB_HAS_OBJECT_RECHECK_PACKED | ODB_HAS_OBJECT_FETCH_PROMISOR))
677 return 1;
678
679 /* Might want to keep the list sorted */
680 for (uint32_t i = 0; i < transaction->packfile.nr_written; i++)
681 if (oideq(&transaction->packfile.written[i]->oid, oid))
682 return 1;
683
684 /* This is a new object we need to keep */
685 return 0;
686 }
687
688 /* Lazily create backing packfile for the state */
689 static void prepare_packfile_transaction(struct odb_transaction_files *transaction)
690 {
691 struct transaction_packfile *state = &transaction->packfile;
692 if (state->f)
693 return;
694
695 state->f = create_tmp_packfile(transaction->base.source->odb->repo,
696 &state->pack_tmp_name);
697 reset_pack_idx_option(&state->pack_idx_opts);
698
699 /* Pretend we are going to write only one object */
700 state->offset = write_pack_header(state->f, 1);
701 if (!state->offset)
702 die_errno("unable to write pack header");
703 }
704
705 static int hash_stream(struct odb_stream *stream,
706 const struct git_hash_algo *hash_algo,
707 struct object_id *result_oid)
708 {
709 unsigned char buf[16384];
710 struct git_hash_ctx ctx;
711 unsigned header_len;
712 size_t bytes_hashed = 0;
713
714 header_len = format_object_header((char *)buf, sizeof(buf),
715 stream->type, stream->size);
716 git_hash_init(&ctx, hash_algo);
717 git_hash_update(&ctx, buf, header_len);
718
719 while (1) {
720 ssize_t read_result = odb_stream_read(stream, buf,
721 sizeof(buf));
722 if (read_result < 0)
723 return -1;
724 if (!read_result)
725 break;
726
727 git_hash_update(&ctx, buf, read_result);
728 bytes_hashed += read_result;
729 }
730
731 if (bytes_hashed != stream->size)
732 return -1;
733
734 git_hash_final_oid(result_oid, &ctx);
735
736 return 0;
737 }
738
739 /*
740 * Read the contents from the stream provided, streaming it to the
741 * packfile in state while updating the hash in ctx.
742 */
743 static void stream_to_pack(struct transaction_packfile *state,
744 struct git_hash_ctx *ctx,
745 struct odb_stream *stream)
746 {
747 git_zstream s;
748 unsigned char ibuf[16384];
749 unsigned char obuf[16384];
750 unsigned hdrlen;
751 int status = Z_OK;
752 struct repo_config_values *cfg = repo_config_values(the_repository);
753 bool is_finished = false;
754 size_t bytes_read = 0;
755
756 git_deflate_init(&s, cfg->pack_compression_level);
757
758 hdrlen = encode_in_pack_object_header(obuf, sizeof(obuf), stream->type, stream->size);
759 s.next_out = obuf + hdrlen;
760 s.avail_out = sizeof(obuf) - hdrlen;
761
762 while (status != Z_STREAM_END) {
763 if (!is_finished && !s.avail_in) {
764 ssize_t rsize = odb_stream_read(stream, ibuf,
765 sizeof(ibuf));
766 if (rsize < 0)
767 die("failed to read object data");
768 if (!rsize)
769 is_finished = true;
770
771 git_hash_update(ctx, ibuf, rsize);
772
773 s.next_in = ibuf;
774 s.avail_in = rsize;
775 bytes_read += rsize;
776 }
777
778 status = git_deflate(&s, is_finished ? Z_FINISH : 0);
779
780 if (!s.avail_out || status == Z_STREAM_END) {
781 size_t written = s.next_out - obuf;
782
783 hashwrite(state->f, obuf, written);
784 state->offset += written;
785 s.next_out = obuf;
786 s.avail_out = sizeof(obuf);
787 }
788
789 switch (status) {
790 case Z_OK:
791 case Z_BUF_ERROR:
792 case Z_STREAM_END:
793 continue;
794 default:
795 die("unexpected deflate failure: %d", status);
796 }
797 }
798
799 if (bytes_read != stream->size)
800 die("read %" PRIuMAX " bytes of object data, but expected %" PRIuMAX " bytes",
801 (uintmax_t)bytes_read, (uintmax_t)stream->size);
802
803 git_deflate_end(&s);
804 }
805
806 static void flush_packfile_transaction(struct odb_transaction_files *transaction)
807 {
808 struct transaction_packfile *state = &transaction->packfile;
809 struct repository *repo = transaction->base.source->odb->repo;
810 unsigned char hash[GIT_MAX_RAWSZ];
811 struct strbuf packname = STRBUF_INIT;
812 char *idx_tmp_name = NULL;
813
814 if (!state->f)
815 return;
816
817 if (state->nr_written == 0) {
818 close(state->f->fd);
819 free_hashfile(state->f);
820 unlink(state->pack_tmp_name);
821 goto clear_exit;
822 } else if (state->nr_written == 1) {
823 finalize_hashfile(state->f, hash, FSYNC_COMPONENT_PACK,
824 CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
825 } else {
826 int fd = finalize_hashfile(state->f, hash, FSYNC_COMPONENT_PACK, 0);
827 fixup_pack_header_footer(repo->hash_algo, fd, hash, state->pack_tmp_name,
828 state->nr_written, hash,
829 state->offset);
830 close(fd);
831 }
832
833 strbuf_addf(&packname, "%s/pack/pack-%s.",
834 repo_get_object_directory(transaction->base.source->odb->repo),
835 hash_to_hex_algop(hash, repo->hash_algo));
836
837 stage_tmp_packfiles(repo, &packname, state->pack_tmp_name,
838 state->written, state->nr_written, NULL,
839 &state->pack_idx_opts, hash, &idx_tmp_name);
840 rename_tmp_packfile_idx(repo, &packname, &idx_tmp_name);
841
842 for (uint32_t i = 0; i < state->nr_written; i++)
843 free(state->written[i]);
844
845 clear_exit:
846 free(idx_tmp_name);
847 free(state->pack_tmp_name);
848 free(state->written);
849 memset(state, 0, sizeof(*state));
850
851 strbuf_release(&packname);
852 /* Make objects we just wrote available to ourselves */
853 odb_reprepare(repo->objects);
854 }
855
856 /*
857 * This writes the specified object to a packfile. Objects written here
858 * during the same transaction are written to the same packfile. The
859 * packfile is not flushed until the transaction is flushed. The caller
860 * is expected to ensure a valid transaction is setup for objects to be
861 * recorded to.
862 *
863 * This also bypasses the usual "convert-to-git" dance, and that is on
864 * purpose. We could write a streaming version of the converting
865 * functions and insert that before feeding the data to fast-import
866 * (or equivalent in-core API described above). However, that is
867 * somewhat complicated, as we do not know the size of the filter
868 * result, which we need to know beforehand when writing a git object.
869 * Since the primary motivation for trying to stream from the working
870 * tree file and to avoid mmaping it in core is to deal with large
871 * objects, they generally do not want to get any conversion, and
872 * callers should avoid this code path when filters are requested.
873 */
874 static int odb_transaction_files_write_object_stream(struct odb_transaction *base,
875 struct odb_stream *stream,
876 struct object_id *result_oid)
877 {
878 struct odb_transaction_files *transaction = container_of(base,
879 struct odb_transaction_files,
880 base);
881 struct transaction_packfile *state = &transaction->packfile;
882 struct git_hash_ctx ctx;
883 unsigned char obuf[16384];
884 unsigned header_len;
885 struct hashfile_checkpoint checkpoint;
886 struct pack_idx_entry *idx;
887
888 header_len = format_object_header((char *)obuf, sizeof(obuf),
889 stream->type, stream->size);
890 git_hash_init(&ctx, transaction->base.source->odb->repo->hash_algo);
891 git_hash_update(&ctx, obuf, header_len);
892
893 /*
894 * If writing another object to the packfile could result in it
895 * exceeding the configured size limit, flush the current packfile
896 * transaction.
897 *
898 * Note that this uses the inflated object size as an approximation.
899 * Blob objects written in this manner are not delta-compressed, so
900 * the difference between the inflated and on-disk size is limited
901 * to zlib compression and is sufficient for this check.
902 */
903 if (state->nr_written && pack_size_limit_cfg &&
904 pack_size_limit_cfg < state->offset + stream->size)
905 flush_packfile_transaction(transaction);
906
907 CALLOC_ARRAY(idx, 1);
908 prepare_packfile_transaction(transaction);
909 hashfile_checkpoint_init(state->f, &checkpoint);
910
911 hashfile_checkpoint(state->f, &checkpoint);
912 idx->offset = state->offset;
913 crc32_begin(state->f);
914 stream_to_pack(state, &ctx, stream);
915 git_hash_final_oid(result_oid, &ctx);
916
917 idx->crc32 = crc32_end(state->f);
918 if (already_written(transaction, result_oid)) {
919 hashfile_truncate(state->f, &checkpoint);
920 state->offset = checkpoint.offset;
921 free(idx);
922 } else {
923 oidcpy(&idx->oid, result_oid);
924 ALLOC_GROW(state->written,
925 state->nr_written + 1,
926 state->alloc_written);
927 state->written[state->nr_written++] = idx;
928 }
929
930 hashfile_checkpoint_release(&checkpoint);
931 return 0;
932 }
933
934 int index_fd(struct index_state *istate, struct object_id *oid,
935 int fd, struct stat *st,
936 enum object_type type, const char *path, unsigned flags)
937 {
938 int ret;
939
940 /*
941 * Call xsize_t() only when needed to avoid potentially unnecessary
942 * die() for large files.
943 */
944 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(istate, path)) {
945 ret = index_stream_convert_blob(istate, oid, fd, path, flags);
946 } else if (!S_ISREG(st->st_mode)) {
947 ret = index_pipe(istate, oid, fd, type, path, flags);
948 } else if ((st->st_size >= 0 &&
949 (size_t)st->st_size <= repo_settings_get_big_file_threshold(istate->repo)) ||
950 type != OBJ_BLOB ||
951 (path && would_convert_to_git(istate, path))) {
952 ret = index_core(istate, oid, fd, xsize_t(st->st_size),
953 type, path, flags);
954 } else {
955 struct odb_stream *stream = odb_stream_from_fd(fd, xsize_t(st->st_size),
956 OBJ_BLOB);
957
958 if (flags & INDEX_WRITE_OBJECT) {
959 struct object_database *odb = the_repository->objects;
960 struct odb_transaction *transaction = odb->transaction;
961 int inflight = !!transaction;
962
963 if (!inflight)
964 odb_transaction_begin_or_die(odb, &transaction, 0);
965 ret = odb_transaction_write_object_stream(transaction,
966 stream, oid);
967 if (!inflight)
968 odb_transaction_commit(transaction);
969 } else {
970 ret = hash_stream(stream, the_repository->hash_algo, oid);
971 }
972
973 odb_stream_close(stream);
974 }
975
976 close(fd);
977 return ret;
978 }
979
980 int index_path(struct index_state *istate, struct object_id *oid,
981 const char *path, struct stat *st, unsigned flags)
982 {
983 int fd;
984 struct strbuf sb = STRBUF_INIT;
985 int rc = 0;
986
987 switch (st->st_mode & S_IFMT) {
988 case S_IFREG:
989 fd = open(path, O_RDONLY);
990 if (fd < 0)
991 return error_errno("open(\"%s\")", path);
992 if (index_fd(istate, oid, fd, st, OBJ_BLOB, path, flags) < 0)
993 return error(_("%s: failed to insert into database"),
994 path);
995 break;
996 case S_IFLNK:
997 if (strbuf_readlink(&sb, path, st->st_size))
998 return error_errno("readlink(\"%s\")", path);
999 if (!(flags & INDEX_WRITE_OBJECT))
1000 hash_object_file(istate->repo->hash_algo, sb.buf, sb.len,
1001 OBJ_BLOB, oid);
1002 else if (odb_write_object(istate->repo->objects, sb.buf, sb.len, OBJ_BLOB, oid))
1003 rc = error(_("%s: failed to insert into database"), path);
1004 strbuf_release(&sb);
1005 break;
1006 case S_IFDIR:
1007 if (repo_resolve_gitlink_ref(istate->repo, path, "HEAD", oid))
1008 return error(_("'%s' does not have a commit checked out"), path);
1009 if (&hash_algos[oid->algo] != istate->repo->hash_algo)
1010 return error(_("cannot add a submodule of a different hash algorithm"));
1011 break;
1012 default:
1013 return error(_("%s: unsupported file type"), path);
1014 }
1015 return rc;
1016 }
1017
1018 int read_pack_header(int fd, struct pack_header *header)
1019 {
1020 if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
1021 /* "eof before pack header was fully read" */
1022 return PH_ERROR_EOF;
1023
1024 if (header->hdr_signature != htonl(PACK_SIGNATURE))
1025 /* "protocol error (pack signature mismatch detected)" */
1026 return PH_ERROR_PACK_SIGNATURE;
1027 if (!pack_version_ok(header->hdr_version))
1028 /* "protocol error (pack version unsupported)" */
1029 return PH_ERROR_PROTOCOL;
1030 return 0;
1031 }
1032
1033 int for_each_file_in_obj_subdir(unsigned int subdir_nr,
1034 struct strbuf *path,
1035 const struct git_hash_algo *algop,
1036 each_loose_object_fn obj_cb,
1037 each_loose_cruft_fn cruft_cb,
1038 each_loose_subdir_fn subdir_cb,
1039 void *data)
1040 {
1041 size_t origlen, baselen;
1042 DIR *dir;
1043 struct dirent *de;
1044 int r = 0;
1045 struct object_id oid;
1046
1047 if (subdir_nr > 0xff)
1048 BUG("invalid loose object subdirectory: %x", subdir_nr);
1049
1050 origlen = path->len;
1051 strbuf_complete(path, '/');
1052 strbuf_addf(path, "%02x", subdir_nr);
1053
1054 dir = opendir(path->buf);
1055 if (!dir) {
1056 if (errno != ENOENT)
1057 r = error_errno(_("unable to open %s"), path->buf);
1058 strbuf_setlen(path, origlen);
1059 return r;
1060 }
1061
1062 oid.hash[0] = subdir_nr;
1063 strbuf_addch(path, '/');
1064 baselen = path->len;
1065
1066 while ((de = readdir_skip_dot_and_dotdot(dir))) {
1067 size_t namelen;
1068
1069 namelen = strlen(de->d_name);
1070 strbuf_setlen(path, baselen);
1071 strbuf_add(path, de->d_name, namelen);
1072 if (namelen == algop->hexsz - 2 &&
1073 !hex_to_bytes(oid.hash + 1, de->d_name,
1074 algop->rawsz - 1)) {
1075 oid_set_algo(&oid, algop);
1076 memset(oid.hash + algop->rawsz, 0,
1077 GIT_MAX_RAWSZ - algop->rawsz);
1078 if (obj_cb) {
1079 r = obj_cb(&oid, path->buf, data);
1080 if (r)
1081 break;
1082 }
1083 continue;
1084 }
1085
1086 if (cruft_cb) {
1087 r = cruft_cb(de->d_name, path->buf, data);
1088 if (r)
1089 break;
1090 }
1091 }
1092 closedir(dir);
1093
1094 strbuf_setlen(path, baselen - 1);
1095 if (!r && subdir_cb)
1096 r = subdir_cb(subdir_nr, path->buf, data);
1097
1098 strbuf_setlen(path, origlen);
1099
1100 return r;
1101 }
1102
1103 int for_each_loose_file_in_source(struct odb_source *source,
1104 each_loose_object_fn obj_cb,
1105 each_loose_cruft_fn cruft_cb,
1106 each_loose_subdir_fn subdir_cb,
1107 void *data)
1108 {
1109 struct strbuf buf = STRBUF_INIT;
1110 int r;
1111
1112 strbuf_addstr(&buf, source->path);
1113 for (int i = 0; i < 256; i++) {
1114 r = for_each_file_in_obj_subdir(i, &buf, source->odb->repo->hash_algo,
1115 obj_cb, cruft_cb, subdir_cb, data);
1116 if (r)
1117 break;
1118 }
1119
1120 strbuf_release(&buf);
1121 return r;
1122 }
1123
1124 static int check_stream_oid(git_zstream *stream,
1125 const char *hdr,
1126 unsigned long size,
1127 const char *path,
1128 const struct object_id *expected_oid,
1129 const struct git_hash_algo *algop)
1130 {
1131 struct git_hash_ctx c;
1132 struct object_id real_oid;
1133 unsigned char buf[4096];
1134 unsigned long total_read;
1135 int status = Z_OK;
1136
1137 git_hash_init(&c, algop);
1138 git_hash_update(&c, hdr, stream->total_out);
1139
1140 /*
1141 * We already read some bytes into hdr, but the ones up to the NUL
1142 * do not count against the object's content size.
1143 */
1144 total_read = stream->total_out - strlen(hdr) - 1;
1145
1146 /*
1147 * This size comparison must be "<=" to read the final zlib packets;
1148 * see the comment in unpack_loose_rest for details.
1149 */
1150 while (total_read <= size &&
1151 (status == Z_OK ||
1152 (status == Z_BUF_ERROR && !stream->avail_out))) {
1153 stream->next_out = buf;
1154 stream->avail_out = sizeof(buf);
1155 if (size - total_read < stream->avail_out)
1156 stream->avail_out = size - total_read;
1157 status = git_inflate(stream, Z_FINISH);
1158 git_hash_update(&c, buf, stream->next_out - buf);
1159 total_read += stream->next_out - buf;
1160 }
1161
1162 if (status != Z_STREAM_END) {
1163 error(_("corrupt loose object '%s'"), oid_to_hex(expected_oid));
1164 git_hash_discard(&c);
1165 return -1;
1166 }
1167 if (stream->avail_in) {
1168 error(_("garbage at end of loose object '%s'"),
1169 oid_to_hex(expected_oid));
1170 git_hash_discard(&c);
1171 return -1;
1172 }
1173
1174 git_hash_final_oid(&real_oid, &c);
1175 if (!oideq(expected_oid, &real_oid)) {
1176 error(_("hash mismatch for %s (expected %s)"), path,
1177 oid_to_hex(expected_oid));
1178 return -1;
1179 }
1180
1181 return 0;
1182 }
1183
1184 int read_loose_object(struct repository *repo,
1185 const char *path,
1186 const struct object_id *expected_oid,
1187 struct object_id *real_oid,
1188 void **contents,
1189 struct object_info *oi)
1190 {
1191 int ret = -1;
1192 int fd;
1193 void *map = NULL;
1194 unsigned long mapsize;
1195 git_zstream stream;
1196 char hdr[MAX_HEADER_LEN];
1197 size_t *size = oi->sizep;
1198
1199 fd = git_open(path);
1200 if (fd >= 0)
1201 map = map_fd(fd, path, &mapsize);
1202 if (!map) {
1203 error_errno(_("unable to mmap %s"), path);
1204 goto out;
1205 }
1206
1207 if (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr)) != ULHR_OK) {
1208 error(_("unable to unpack header of %s"), path);
1209 goto out_inflate;
1210 }
1211
1212 if (parse_loose_header(hdr, oi) < 0) {
1213 error(_("unable to parse header of %s"), path);
1214 goto out_inflate;
1215 }
1216
1217 if (*oi->typep < 0) {
1218 error(_("unable to parse type from header '%s' of %s"),
1219 hdr, path);
1220 goto out_inflate;
1221 }
1222
1223 if (*oi->typep == OBJ_BLOB &&
1224 *size > repo_settings_get_big_file_threshold(repo)) {
1225 if (check_stream_oid(&stream, hdr, *size, path, expected_oid,
1226 repo->hash_algo) < 0)
1227 goto out_inflate;
1228 } else {
1229 *contents = unpack_loose_rest(&stream, hdr, *size, expected_oid);
1230 if (!*contents) {
1231 error(_("unable to unpack contents of %s"), path);
1232 goto out_inflate;
1233 }
1234 hash_object_file(repo->hash_algo,
1235 *contents, *size,
1236 *oi->typep, real_oid);
1237 if (!oideq(expected_oid, real_oid))
1238 goto out_inflate;
1239 }
1240
1241 ret = 0; /* everything checks out */
1242
1243 out_inflate:
1244 git_inflate_end(&stream);
1245 out:
1246 if (map)
1247 munmap(map, mapsize);
1248 return ret;
1249 }
1250
1251 static int odb_transaction_files_commit(struct odb_transaction *base)
1252 {
1253 struct odb_transaction_files *transaction =
1254 container_of(base, struct odb_transaction_files, base);
1255
1256 if (transaction->objdir) {
1257 struct strbuf temp_path = STRBUF_INIT;
1258 struct tempfile *temp;
1259
1260 /*
1261 * Issue a full hardware flush against a temporary file to ensure
1262 * that all objects are durable before any renames occur. The code in
1263 * odb_transaction_files_fsync has already issued a writeout
1264 * request, but it has not flushed any writeback cache in the storage
1265 * hardware or any filesystem logs. This fsync call acts as a barrier
1266 * to ensure that the data in each new object file is durable before
1267 * the final name is visible.
1268 */
1269 strbuf_addf(&temp_path, "%s/bulk_fsync_XXXXXX",
1270 repo_get_object_directory(transaction->base.source->odb->repo));
1271 temp = xmks_tempfile(temp_path.buf);
1272 fsync_or_die(get_tempfile_fd(temp), get_tempfile_path(temp));
1273 delete_tempfile(&temp);
1274 strbuf_release(&temp_path);
1275
1276 /*
1277 * Make the object files visible in the primary ODB after their data is
1278 * fully durable.
1279 */
1280 if (tmp_objdir_migrate(transaction->objdir))
1281 return error(_("unable to migrate temporary objects"));
1282
1283 transaction->objdir = NULL;
1284 }
1285
1286 flush_packfile_transaction(transaction);
1287
1288 return 0;
1289 }
1290
1291 static int odb_transaction_files_env(struct odb_transaction *base,
1292 struct strvec *env)
1293 {
1294 struct odb_transaction_files *transaction =
1295 container_of(base, struct odb_transaction_files, base);
1296 int ret;
1297
1298 ret = odb_transaction_files_prepare(&transaction->base);
1299 if (!ret)
1300 strvec_pushv(env, tmp_objdir_env(transaction->objdir));
1301
1302 return ret;
1303 }
1304
1305 int odb_transaction_files_begin(struct odb_source *source,
1306 struct odb_transaction **out,
1307 enum odb_transaction_flags flags)
1308 {
1309 struct odb_transaction_files *transaction;
1310
1311 transaction = xcalloc(1, sizeof(*transaction));
1312 transaction->base.source = source;
1313 transaction->base.commit = odb_transaction_files_commit;
1314 transaction->base.write_object_stream = odb_transaction_files_write_object_stream;
1315 transaction->base.env = odb_transaction_files_env;
1316
1317 transaction->prefix = "bulk-fsync";
1318 if (flags & ODB_TRANSACTION_RECEIVE) {
1319 /*
1320 * ODB transactions for git-receive-pack(1) eagerly create a
1321 * temporary directory and use a different temporary directory
1322 * prefix.
1323 *
1324 * NEEDSWORK: This transaction flag is only used by the "files"
1325 * backend to special case temporary directory set up and
1326 * handling. Ideally transaction users should not have to care
1327 * though. To avoid this, we could eagerly create the temporary
1328 * directory and use the same prefix name for all transactions.
1329 */
1330 transaction->prefix = "incoming";
1331 if (odb_transaction_files_prepare(&transaction->base)) {
1332 free(transaction);
1333 return -1;
1334 }
1335 }
1336
1337 *out = &transaction->base;
1338
1339 return 0;
1340 }