Raw
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_read_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_read_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_blob_stream(struct odb_write_stream *stream,
706 const struct git_hash_algo *hash_algo,
707 struct object_id *result_oid, size_t size)
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 OBJ_BLOB, size);
716 git_hash_init(&ctx, hash_algo);
717 git_hash_update(&ctx, buf, header_len);
718
719 while (!stream->is_finished) {
720 ssize_t read_result = odb_write_stream_read(stream, buf,
721 sizeof(buf));
722
723 if (read_result < 0)
724 return -1;
725
726 git_hash_update(&ctx, buf, read_result);
727 bytes_hashed += read_result;
728 }
729
730 if (bytes_hashed != size)
731 return -1;
732
733 git_hash_final_oid(result_oid, &ctx);
734
735 return 0;
736 }
737
738 /*
739 * Read the contents from the stream provided, streaming it to the
740 * packfile in state while updating the hash in ctx.
741 */
742 static void stream_blob_to_pack(struct transaction_packfile *state,
743 struct git_hash_ctx *ctx, size_t size,
744 struct odb_write_stream *stream)
745 {
746 git_zstream s;
747 unsigned char ibuf[16384];
748 unsigned char obuf[16384];
749 unsigned hdrlen;
750 int status = Z_OK;
751 struct repo_config_values *cfg = repo_config_values(the_repository);
752 size_t bytes_read = 0;
753
754 git_deflate_init(&s, cfg->pack_compression_level);
755
756 hdrlen = encode_in_pack_object_header(obuf, sizeof(obuf), OBJ_BLOB, size);
757 s.next_out = obuf + hdrlen;
758 s.avail_out = sizeof(obuf) - hdrlen;
759
760 while (status != Z_STREAM_END) {
761 if (!stream->is_finished && !s.avail_in) {
762 ssize_t rsize = odb_write_stream_read(stream, ibuf,
763 sizeof(ibuf));
764
765 if (rsize < 0)
766 die("failed to read blob data");
767
768 git_hash_update(ctx, ibuf, rsize);
769
770 s.next_in = ibuf;
771 s.avail_in = rsize;
772 bytes_read += rsize;
773 }
774
775 status = git_deflate(&s, stream->is_finished ? Z_FINISH : 0);
776
777 if (!s.avail_out || status == Z_STREAM_END) {
778 size_t written = s.next_out - obuf;
779
780 hashwrite(state->f, obuf, written);
781 state->offset += written;
782 s.next_out = obuf;
783 s.avail_out = sizeof(obuf);
784 }
785
786 switch (status) {
787 case Z_OK:
788 case Z_BUF_ERROR:
789 case Z_STREAM_END:
790 continue;
791 default:
792 die("unexpected deflate failure: %d", status);
793 }
794 }
795
796 if (bytes_read != size)
797 die("read %" PRIuMAX " bytes of blob data, but expected %" PRIuMAX " bytes",
798 (uintmax_t)bytes_read, (uintmax_t)size);
799
800 git_deflate_end(&s);
801 }
802
803 static void flush_packfile_transaction(struct odb_transaction_files *transaction)
804 {
805 struct transaction_packfile *state = &transaction->packfile;
806 struct repository *repo = transaction->base.source->odb->repo;
807 unsigned char hash[GIT_MAX_RAWSZ];
808 struct strbuf packname = STRBUF_INIT;
809 char *idx_tmp_name = NULL;
810
811 if (!state->f)
812 return;
813
814 if (state->nr_written == 0) {
815 close(state->f->fd);
816 free_hashfile(state->f);
817 unlink(state->pack_tmp_name);
818 goto clear_exit;
819 } else if (state->nr_written == 1) {
820 finalize_hashfile(state->f, hash, FSYNC_COMPONENT_PACK,
821 CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
822 } else {
823 int fd = finalize_hashfile(state->f, hash, FSYNC_COMPONENT_PACK, 0);
824 fixup_pack_header_footer(repo->hash_algo, fd, hash, state->pack_tmp_name,
825 state->nr_written, hash,
826 state->offset);
827 close(fd);
828 }
829
830 strbuf_addf(&packname, "%s/pack/pack-%s.",
831 repo_get_object_directory(transaction->base.source->odb->repo),
832 hash_to_hex_algop(hash, repo->hash_algo));
833
834 stage_tmp_packfiles(repo, &packname, state->pack_tmp_name,
835 state->written, state->nr_written, NULL,
836 &state->pack_idx_opts, hash, &idx_tmp_name);
837 rename_tmp_packfile_idx(repo, &packname, &idx_tmp_name);
838
839 for (uint32_t i = 0; i < state->nr_written; i++)
840 free(state->written[i]);
841
842 clear_exit:
843 free(idx_tmp_name);
844 free(state->pack_tmp_name);
845 free(state->written);
846 memset(state, 0, sizeof(*state));
847
848 strbuf_release(&packname);
849 /* Make objects we just wrote available to ourselves */
850 odb_reprepare(repo->objects);
851 }
852
853 /*
854 * This writes the specified object to a packfile. Objects written here
855 * during the same transaction are written to the same packfile. The
856 * packfile is not flushed until the transaction is flushed. The caller
857 * is expected to ensure a valid transaction is setup for objects to be
858 * recorded to.
859 *
860 * This also bypasses the usual "convert-to-git" dance, and that is on
861 * purpose. We could write a streaming version of the converting
862 * functions and insert that before feeding the data to fast-import
863 * (or equivalent in-core API described above). However, that is
864 * somewhat complicated, as we do not know the size of the filter
865 * result, which we need to know beforehand when writing a git object.
866 * Since the primary motivation for trying to stream from the working
867 * tree file and to avoid mmaping it in core is to deal with large
868 * binary blobs, they generally do not want to get any conversion, and
869 * callers should avoid this code path when filters are requested.
870 */
871 static int odb_transaction_files_write_object_stream(struct odb_transaction *base,
872 struct odb_write_stream *stream,
873 size_t size,
874 struct object_id *result_oid)
875 {
876 struct odb_transaction_files *transaction = container_of(base,
877 struct odb_transaction_files,
878 base);
879 struct transaction_packfile *state = &transaction->packfile;
880 struct git_hash_ctx ctx;
881 unsigned char obuf[16384];
882 unsigned header_len;
883 struct hashfile_checkpoint checkpoint;
884 struct pack_idx_entry *idx;
885
886 header_len = format_object_header((char *)obuf, sizeof(obuf),
887 OBJ_BLOB, size);
888 git_hash_init(&ctx, transaction->base.source->odb->repo->hash_algo);
889 git_hash_update(&ctx, obuf, header_len);
890
891 /*
892 * If writing another object to the packfile could result in it
893 * exceeding the configured size limit, flush the current packfile
894 * transaction.
895 *
896 * Note that this uses the inflated object size as an approximation.
897 * Blob objects written in this manner are not delta-compressed, so
898 * the difference between the inflated and on-disk size is limited
899 * to zlib compression and is sufficient for this check.
900 */
901 if (state->nr_written && pack_size_limit_cfg &&
902 pack_size_limit_cfg < state->offset + size)
903 flush_packfile_transaction(transaction);
904
905 CALLOC_ARRAY(idx, 1);
906 prepare_packfile_transaction(transaction);
907 hashfile_checkpoint_init(state->f, &checkpoint);
908
909 hashfile_checkpoint(state->f, &checkpoint);
910 idx->offset = state->offset;
911 crc32_begin(state->f);
912 stream_blob_to_pack(state, &ctx, size, stream);
913 git_hash_final_oid(result_oid, &ctx);
914
915 idx->crc32 = crc32_end(state->f);
916 if (already_written(transaction, result_oid)) {
917 hashfile_truncate(state->f, &checkpoint);
918 state->offset = checkpoint.offset;
919 free(idx);
920 } else {
921 oidcpy(&idx->oid, result_oid);
922 ALLOC_GROW(state->written,
923 state->nr_written + 1,
924 state->alloc_written);
925 state->written[state->nr_written++] = idx;
926 }
927
928 hashfile_checkpoint_release(&checkpoint);
929 return 0;
930 }
931
932 int index_fd(struct index_state *istate, struct object_id *oid,
933 int fd, struct stat *st,
934 enum object_type type, const char *path, unsigned flags)
935 {
936 int ret;
937
938 /*
939 * Call xsize_t() only when needed to avoid potentially unnecessary
940 * die() for large files.
941 */
942 if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(istate, path)) {
943 ret = index_stream_convert_blob(istate, oid, fd, path, flags);
944 } else if (!S_ISREG(st->st_mode)) {
945 ret = index_pipe(istate, oid, fd, type, path, flags);
946 } else if ((st->st_size >= 0 &&
947 (size_t)st->st_size <= repo_settings_get_big_file_threshold(istate->repo)) ||
948 type != OBJ_BLOB ||
949 (path && would_convert_to_git(istate, path))) {
950 ret = index_core(istate, oid, fd, xsize_t(st->st_size),
951 type, path, flags);
952 } else {
953 struct odb_write_stream stream;
954 odb_write_stream_from_fd(&stream, fd, xsize_t(st->st_size));
955
956 if (flags & INDEX_WRITE_OBJECT) {
957 struct object_database *odb = the_repository->objects;
958 struct odb_transaction *transaction = odb->transaction;
959 int inflight = !!transaction;
960
961 if (!inflight)
962 odb_transaction_begin_or_die(odb, &transaction, 0);
963 ret = odb_transaction_write_object_stream(transaction,
964 &stream,
965 xsize_t(st->st_size),
966 oid);
967 if (!inflight)
968 odb_transaction_commit(transaction);
969 } else {
970 ret = hash_blob_stream(&stream,
971 the_repository->hash_algo, oid,
972 xsize_t(st->st_size));
973 }
974
975 odb_write_stream_release(&stream);
976 }
977
978 close(fd);
979 return ret;
980 }
981
982 int index_path(struct index_state *istate, struct object_id *oid,
983 const char *path, struct stat *st, unsigned flags)
984 {
985 int fd;
986 struct strbuf sb = STRBUF_INIT;
987 int rc = 0;
988
989 switch (st->st_mode & S_IFMT) {
990 case S_IFREG:
991 fd = open(path, O_RDONLY);
992 if (fd < 0)
993 return error_errno("open(\"%s\")", path);
994 if (index_fd(istate, oid, fd, st, OBJ_BLOB, path, flags) < 0)
995 return error(_("%s: failed to insert into database"),
996 path);
997 break;
998 case S_IFLNK:
999 if (strbuf_readlink(&sb, path, st->st_size))
1000 return error_errno("readlink(\"%s\")", path);
1001 if (!(flags & INDEX_WRITE_OBJECT))
1002 hash_object_file(istate->repo->hash_algo, sb.buf, sb.len,
1003 OBJ_BLOB, oid);
1004 else if (odb_write_object(istate->repo->objects, sb.buf, sb.len, OBJ_BLOB, oid))
1005 rc = error(_("%s: failed to insert into database"), path);
1006 strbuf_release(&sb);
1007 break;
1008 case S_IFDIR:
1009 if (repo_resolve_gitlink_ref(istate->repo, path, "HEAD", oid))
1010 return error(_("'%s' does not have a commit checked out"), path);
1011 if (&hash_algos[oid->algo] != istate->repo->hash_algo)
1012 return error(_("cannot add a submodule of a different hash algorithm"));
1013 break;
1014 default:
1015 return error(_("%s: unsupported file type"), path);
1016 }
1017 return rc;
1018 }
1019
1020 int read_pack_header(int fd, struct pack_header *header)
1021 {
1022 if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
1023 /* "eof before pack header was fully read" */
1024 return PH_ERROR_EOF;
1025
1026 if (header->hdr_signature != htonl(PACK_SIGNATURE))
1027 /* "protocol error (pack signature mismatch detected)" */
1028 return PH_ERROR_PACK_SIGNATURE;
1029 if (!pack_version_ok(header->hdr_version))
1030 /* "protocol error (pack version unsupported)" */
1031 return PH_ERROR_PROTOCOL;
1032 return 0;
1033 }
1034
1035 int for_each_file_in_obj_subdir(unsigned int subdir_nr,
1036 struct strbuf *path,
1037 const struct git_hash_algo *algop,
1038 each_loose_object_fn obj_cb,
1039 each_loose_cruft_fn cruft_cb,
1040 each_loose_subdir_fn subdir_cb,
1041 void *data)
1042 {
1043 size_t origlen, baselen;
1044 DIR *dir;
1045 struct dirent *de;
1046 int r = 0;
1047 struct object_id oid;
1048
1049 if (subdir_nr > 0xff)
1050 BUG("invalid loose object subdirectory: %x", subdir_nr);
1051
1052 origlen = path->len;
1053 strbuf_complete(path, '/');
1054 strbuf_addf(path, "%02x", subdir_nr);
1055
1056 dir = opendir(path->buf);
1057 if (!dir) {
1058 if (errno != ENOENT)
1059 r = error_errno(_("unable to open %s"), path->buf);
1060 strbuf_setlen(path, origlen);
1061 return r;
1062 }
1063
1064 oid.hash[0] = subdir_nr;
1065 strbuf_addch(path, '/');
1066 baselen = path->len;
1067
1068 while ((de = readdir_skip_dot_and_dotdot(dir))) {
1069 size_t namelen;
1070
1071 namelen = strlen(de->d_name);
1072 strbuf_setlen(path, baselen);
1073 strbuf_add(path, de->d_name, namelen);
1074 if (namelen == algop->hexsz - 2 &&
1075 !hex_to_bytes(oid.hash + 1, de->d_name,
1076 algop->rawsz - 1)) {
1077 oid_set_algo(&oid, algop);
1078 memset(oid.hash + algop->rawsz, 0,
1079 GIT_MAX_RAWSZ - algop->rawsz);
1080 if (obj_cb) {
1081 r = obj_cb(&oid, path->buf, data);
1082 if (r)
1083 break;
1084 }
1085 continue;
1086 }
1087
1088 if (cruft_cb) {
1089 r = cruft_cb(de->d_name, path->buf, data);
1090 if (r)
1091 break;
1092 }
1093 }
1094 closedir(dir);
1095
1096 strbuf_setlen(path, baselen - 1);
1097 if (!r && subdir_cb)
1098 r = subdir_cb(subdir_nr, path->buf, data);
1099
1100 strbuf_setlen(path, origlen);
1101
1102 return r;
1103 }
1104
1105 int for_each_loose_file_in_source(struct odb_source *source,
1106 each_loose_object_fn obj_cb,
1107 each_loose_cruft_fn cruft_cb,
1108 each_loose_subdir_fn subdir_cb,
1109 void *data)
1110 {
1111 struct strbuf buf = STRBUF_INIT;
1112 int r;
1113
1114 strbuf_addstr(&buf, source->path);
1115 for (int i = 0; i < 256; i++) {
1116 r = for_each_file_in_obj_subdir(i, &buf, source->odb->repo->hash_algo,
1117 obj_cb, cruft_cb, subdir_cb, data);
1118 if (r)
1119 break;
1120 }
1121
1122 strbuf_release(&buf);
1123 return r;
1124 }
1125
1126 static int check_stream_oid(git_zstream *stream,
1127 const char *hdr,
1128 unsigned long size,
1129 const char *path,
1130 const struct object_id *expected_oid,
1131 const struct git_hash_algo *algop)
1132 {
1133 struct git_hash_ctx c;
1134 struct object_id real_oid;
1135 unsigned char buf[4096];
1136 unsigned long total_read;
1137 int status = Z_OK;
1138
1139 git_hash_init(&c, algop);
1140 git_hash_update(&c, hdr, stream->total_out);
1141
1142 /*
1143 * We already read some bytes into hdr, but the ones up to the NUL
1144 * do not count against the object's content size.
1145 */
1146 total_read = stream->total_out - strlen(hdr) - 1;
1147
1148 /*
1149 * This size comparison must be "<=" to read the final zlib packets;
1150 * see the comment in unpack_loose_rest for details.
1151 */
1152 while (total_read <= size &&
1153 (status == Z_OK ||
1154 (status == Z_BUF_ERROR && !stream->avail_out))) {
1155 stream->next_out = buf;
1156 stream->avail_out = sizeof(buf);
1157 if (size - total_read < stream->avail_out)
1158 stream->avail_out = size - total_read;
1159 status = git_inflate(stream, Z_FINISH);
1160 git_hash_update(&c, buf, stream->next_out - buf);
1161 total_read += stream->next_out - buf;
1162 }
1163
1164 if (status != Z_STREAM_END) {
1165 error(_("corrupt loose object '%s'"), oid_to_hex(expected_oid));
1166 git_hash_discard(&c);
1167 return -1;
1168 }
1169 if (stream->avail_in) {
1170 error(_("garbage at end of loose object '%s'"),
1171 oid_to_hex(expected_oid));
1172 git_hash_discard(&c);
1173 return -1;
1174 }
1175
1176 git_hash_final_oid(&real_oid, &c);
1177 if (!oideq(expected_oid, &real_oid)) {
1178 error(_("hash mismatch for %s (expected %s)"), path,
1179 oid_to_hex(expected_oid));
1180 return -1;
1181 }
1182
1183 return 0;
1184 }
1185
1186 int read_loose_object(struct repository *repo,
1187 const char *path,
1188 const struct object_id *expected_oid,
1189 struct object_id *real_oid,
1190 void **contents,
1191 struct object_info *oi)
1192 {
1193 int ret = -1;
1194 int fd;
1195 void *map = NULL;
1196 unsigned long mapsize;
1197 git_zstream stream;
1198 char hdr[MAX_HEADER_LEN];
1199 size_t *size = oi->sizep;
1200
1201 fd = git_open(path);
1202 if (fd >= 0)
1203 map = map_fd(fd, path, &mapsize);
1204 if (!map) {
1205 error_errno(_("unable to mmap %s"), path);
1206 goto out;
1207 }
1208
1209 if (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr)) != ULHR_OK) {
1210 error(_("unable to unpack header of %s"), path);
1211 goto out_inflate;
1212 }
1213
1214 if (parse_loose_header(hdr, oi) < 0) {
1215 error(_("unable to parse header of %s"), path);
1216 goto out_inflate;
1217 }
1218
1219 if (*oi->typep < 0) {
1220 error(_("unable to parse type from header '%s' of %s"),
1221 hdr, path);
1222 goto out_inflate;
1223 }
1224
1225 if (*oi->typep == OBJ_BLOB &&
1226 *size > repo_settings_get_big_file_threshold(repo)) {
1227 if (check_stream_oid(&stream, hdr, *size, path, expected_oid,
1228 repo->hash_algo) < 0)
1229 goto out_inflate;
1230 } else {
1231 *contents = unpack_loose_rest(&stream, hdr, *size, expected_oid);
1232 if (!*contents) {
1233 error(_("unable to unpack contents of %s"), path);
1234 goto out_inflate;
1235 }
1236 hash_object_file(repo->hash_algo,
1237 *contents, *size,
1238 *oi->typep, real_oid);
1239 if (!oideq(expected_oid, real_oid))
1240 goto out_inflate;
1241 }
1242
1243 ret = 0; /* everything checks out */
1244
1245 out_inflate:
1246 git_inflate_end(&stream);
1247 out:
1248 if (map)
1249 munmap(map, mapsize);
1250 return ret;
1251 }
1252
1253 static int odb_transaction_files_commit(struct odb_transaction *base)
1254 {
1255 struct odb_transaction_files *transaction =
1256 container_of(base, struct odb_transaction_files, base);
1257
1258 if (transaction->objdir) {
1259 struct strbuf temp_path = STRBUF_INIT;
1260 struct tempfile *temp;
1261
1262 /*
1263 * Issue a full hardware flush against a temporary file to ensure
1264 * that all objects are durable before any renames occur. The code in
1265 * odb_transaction_files_fsync has already issued a writeout
1266 * request, but it has not flushed any writeback cache in the storage
1267 * hardware or any filesystem logs. This fsync call acts as a barrier
1268 * to ensure that the data in each new object file is durable before
1269 * the final name is visible.
1270 */
1271 strbuf_addf(&temp_path, "%s/bulk_fsync_XXXXXX",
1272 repo_get_object_directory(transaction->base.source->odb->repo));
1273 temp = xmks_tempfile(temp_path.buf);
1274 fsync_or_die(get_tempfile_fd(temp), get_tempfile_path(temp));
1275 delete_tempfile(&temp);
1276 strbuf_release(&temp_path);
1277
1278 /*
1279 * Make the object files visible in the primary ODB after their data is
1280 * fully durable.
1281 */
1282 if (tmp_objdir_migrate(transaction->objdir))
1283 return error(_("unable to migrate temporary objects"));
1284
1285 transaction->objdir = NULL;
1286 }
1287
1288 flush_packfile_transaction(transaction);
1289
1290 return 0;
1291 }
1292
1293 static int odb_transaction_files_env(struct odb_transaction *base,
1294 struct strvec *env)
1295 {
1296 struct odb_transaction_files *transaction =
1297 container_of(base, struct odb_transaction_files, base);
1298 int ret;
1299
1300 ret = odb_transaction_files_prepare(&transaction->base);
1301 if (!ret)
1302 strvec_pushv(env, tmp_objdir_env(transaction->objdir));
1303
1304 return ret;
1305 }
1306
1307 int odb_transaction_files_begin(struct odb_source *source,
1308 struct odb_transaction **out,
1309 enum odb_transaction_flags flags)
1310 {
1311 struct odb_transaction_files *transaction;
1312
1313 transaction = xcalloc(1, sizeof(*transaction));
1314 transaction->base.source = source;
1315 transaction->base.commit = odb_transaction_files_commit;
1316 transaction->base.write_object_stream = odb_transaction_files_write_object_stream;
1317 transaction->base.env = odb_transaction_files_env;
1318
1319 transaction->prefix = "bulk-fsync";
1320 if (flags & ODB_TRANSACTION_RECEIVE) {
1321 /*
1322 * ODB transactions for git-receive-pack(1) eagerly create a
1323 * temporary directory and use a different temporary directory
1324 * prefix.
1325 *
1326 * NEEDSWORK: This transaction flag is only used by the "files"
1327 * backend to special case temporary directory set up and
1328 * handling. Ideally transaction users should not have to care
1329 * though. To avoid this, we could eagerly create the temporary
1330 * directory and use the same prefix name for all transactions.
1331 */
1332 transaction->prefix = "incoming";
1333 if (odb_transaction_files_prepare(&transaction->base)) {
1334 free(transaction);
1335 return -1;
1336 }
1337 }
1338
1339 *out = &transaction->base;
1340
1341 return 0;
1342 }
1343
1344 void free_object_info_contents(struct object_info *object_info)
1345 {
1346 if (!object_info)
1347 return;
1348 free(object_info->typep);
1349 free(object_info->sizep);
1350 free(object_info->disk_sizep);
1351 free(object_info->delta_base_oid);
1352 }