Coverage Report

Created: 2026-12-01 06:58

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