Coverage Report

Created: 2026-03-31 06:24

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 "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 "oidtree.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 "tempfile.h"
31
#include "tmp-objdir.h"
32
33
/* The maximum size for an object header. */
34
#define MAX_HEADER_LEN 32
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 *source,
61
         struct strbuf *buf,
62
         const struct object_id *oid)
63
0
{
64
0
  strbuf_reset(buf);
65
0
  strbuf_addstr(buf, source->path);
66
0
  strbuf_addch(buf, '/');
67
0
  fill_loose_path(buf, oid, source->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)
73
0
{
74
0
  return !utime(fn, NULL);
75
0
}
76
77
/*
78
 * All of the check_and_freshen functions return 1 if the file exists and was
79
 * freshened (if freshening was requested), 0 otherwise. If they return
80
 * 0, you should not assume that it is safe to skip a write of the object (it
81
 * either does not exist on disk, or has a stale mtime and may be subject to
82
 * pruning).
83
 */
84
int check_and_freshen_file(const char *fn, int freshen)
85
0
{
86
0
  if (access(fn, F_OK))
87
0
    return 0;
88
0
  if (freshen && !freshen_file(fn))
89
0
    return 0;
90
0
  return 1;
91
0
}
92
93
static int check_and_freshen_source(struct odb_source *source,
94
            const struct object_id *oid,
95
            int freshen)
96
0
{
97
0
  static struct strbuf path = STRBUF_INIT;
98
0
  odb_loose_path(source, &path, oid);
99
0
  return check_and_freshen_file(path.buf, freshen);
100
0
}
101
102
int odb_source_loose_has_object(struct odb_source *source,
103
        const struct object_id *oid)
104
0
{
105
0
  return check_and_freshen_source(source, oid, 0);
106
0
}
107
108
int format_object_header(char *str, size_t size, enum object_type type,
109
       size_t objsize)
110
0
{
111
0
  const char *name = type_name(type);
112
113
0
  if (!name)
114
0
    BUG("could not get a type name for 'enum object_type' value %d", type);
115
116
0
  return xsnprintf(str, size, "%s %"PRIuMAX, name, (uintmax_t)objsize) + 1;
117
0
}
118
119
int check_object_signature(struct repository *r, const struct object_id *oid,
120
         void *buf, unsigned long size,
121
         enum object_type type)
122
0
{
123
0
  const struct git_hash_algo *algo =
124
0
    oid->algo ? &hash_algos[oid->algo] : r->hash_algo;
125
0
  struct object_id real_oid;
126
127
0
  hash_object_file(algo, buf, size, type, &real_oid);
128
129
0
  return !oideq(oid, &real_oid) ? -1 : 0;
130
0
}
131
132
int stream_object_signature(struct repository *r,
133
          struct odb_read_stream *st,
134
          const struct object_id *oid)
135
0
{
136
0
  struct object_id real_oid;
137
0
  struct git_hash_ctx c;
138
0
  char hdr[MAX_HEADER_LEN];
139
0
  int hdrlen;
140
141
  /* Generate the header */
142
0
  hdrlen = format_object_header(hdr, sizeof(hdr), st->type, st->size);
143
144
  /* Sha1.. */
145
0
  r->hash_algo->init_fn(&c);
146
0
  git_hash_update(&c, hdr, hdrlen);
147
0
  for (;;) {
148
0
    char buf[1024 * 16];
149
0
    ssize_t readlen = odb_read_stream_read(st, buf, sizeof(buf));
150
151
0
    if (readlen < 0) {
152
0
      odb_read_stream_close(st);
153
0
      return -1;
154
0
    }
155
0
    if (!readlen)
156
0
      break;
157
0
    git_hash_update(&c, buf, readlen);
158
0
  }
159
0
  git_hash_final_oid(&real_oid, &c);
160
0
  return !oideq(oid, &real_oid) ? -1 : 0;
161
0
}
162
163
/*
164
 * Find "oid" as a loose object in given source, open the object and return its
165
 * file descriptor. Returns the file descriptor on success, negative on failure.
166
 *
167
 * The "path" out-parameter will give the path of the object we found (if any).
168
 * Note that it may point to static storage and is only valid until another
169
 * call to stat_loose_object().
170
 */
171
static int open_loose_object(struct odb_source_loose *loose,
172
           const struct object_id *oid, const char **path)
173
0
{
174
0
  static struct strbuf buf = STRBUF_INIT;
175
0
  int fd;
176
177
0
  *path = odb_loose_path(loose->source, &buf, oid);
178
0
  fd = git_open(*path);
179
0
  if (fd >= 0)
180
0
    return fd;
181
182
0
  return -1;
183
0
}
184
185
static int quick_has_loose(struct odb_source_loose *loose,
186
         const struct object_id *oid)
187
0
{
188
0
  return !!oidtree_contains(odb_source_loose_cache(loose->source, oid), oid);
189
0
}
190
191
/*
192
 * Map and close the given loose object fd. The path argument is used for
193
 * error reporting.
194
 */
195
static void *map_fd(int fd, const char *path, unsigned long *size)
196
0
{
197
0
  void *map = NULL;
198
0
  struct stat st;
199
200
0
  if (!fstat(fd, &st)) {
201
0
    *size = xsize_t(st.st_size);
202
0
    if (!*size) {
203
      /* mmap() is forbidden on empty files */
204
0
      error(_("object file %s is empty"), path);
205
0
      close(fd);
206
0
      return NULL;
207
0
    }
208
0
    map = xmmap(NULL, *size, PROT_READ, MAP_PRIVATE, fd, 0);
209
0
  }
210
0
  close(fd);
211
0
  return map;
212
0
}
213
214
static void *odb_source_loose_map_object(struct odb_source *source,
215
           const struct object_id *oid,
216
           unsigned long *size)
217
0
{
218
0
  struct odb_source_files *files = odb_source_files_downcast(source);
219
0
  const char *p;
220
0
  int fd = open_loose_object(files->loose, oid, &p);
221
222
0
  if (fd < 0)
223
0
    return NULL;
224
0
  return map_fd(fd, p, size);
225
0
}
226
227
enum unpack_loose_header_result {
228
  ULHR_OK,
229
  ULHR_BAD,
230
  ULHR_TOO_LONG,
231
};
232
233
/**
234
 * unpack_loose_header() initializes the data stream needed to unpack
235
 * a loose object header.
236
 *
237
 * Returns:
238
 *
239
 * - ULHR_OK on success
240
 * - ULHR_BAD on error
241
 * - ULHR_TOO_LONG if the header was too long
242
 *
243
 * It will only parse up to MAX_HEADER_LEN bytes.
244
 */
245
static enum unpack_loose_header_result unpack_loose_header(git_zstream *stream,
246
                 unsigned char *map,
247
                 unsigned long mapsize,
248
                 void *buffer,
249
                 unsigned long bufsiz)
250
0
{
251
0
  int status;
252
253
  /* Get the data stream */
254
0
  memset(stream, 0, sizeof(*stream));
255
0
  stream->next_in = map;
256
0
  stream->avail_in = mapsize;
257
0
  stream->next_out = buffer;
258
0
  stream->avail_out = bufsiz;
259
260
0
  git_inflate_init(stream);
261
0
  obj_read_unlock();
262
0
  status = git_inflate(stream, 0);
263
0
  obj_read_lock();
264
0
  if (status != Z_OK && status != Z_STREAM_END)
265
0
    return ULHR_BAD;
266
267
  /*
268
   * Check if entire header is unpacked in the first iteration.
269
   */
270
0
  if (memchr(buffer, '\0', stream->next_out - (unsigned char *)buffer))
271
0
    return ULHR_OK;
272
273
  /*
274
   * We have a header longer than MAX_HEADER_LEN.
275
   */
276
0
  return ULHR_TOO_LONG;
277
0
}
278
279
static void *unpack_loose_rest(git_zstream *stream,
280
             void *buffer, unsigned long size,
281
             const struct object_id *oid)
282
0
{
283
0
  size_t bytes = strlen(buffer) + 1, n;
284
0
  unsigned char *buf = xmallocz(size);
285
0
  int status = Z_OK;
286
287
0
  n = stream->total_out - bytes;
288
0
  if (n > size)
289
0
    n = size;
290
0
  memcpy(buf, (char *) buffer + bytes, n);
291
0
  bytes = n;
292
0
  if (bytes <= size) {
293
    /*
294
     * The above condition must be (bytes <= size), not
295
     * (bytes < size).  In other words, even though we
296
     * expect no more output and set avail_out to zero,
297
     * the input zlib stream may have bytes that express
298
     * "this concludes the stream", and we *do* want to
299
     * eat that input.
300
     *
301
     * Otherwise we would not be able to test that we
302
     * consumed all the input to reach the expected size;
303
     * we also want to check that zlib tells us that all
304
     * went well with status == Z_STREAM_END at the end.
305
     */
306
0
    stream->next_out = buf + bytes;
307
0
    stream->avail_out = size - bytes;
308
0
    while (status == Z_OK) {
309
0
      obj_read_unlock();
310
0
      status = git_inflate(stream, Z_FINISH);
311
0
      obj_read_lock();
312
0
    }
313
0
  }
314
315
0
  if (status != Z_STREAM_END) {
316
0
    error(_("corrupt loose object '%s'"), oid_to_hex(oid));
317
0
    FREE_AND_NULL(buf);
318
0
  } else if (stream->avail_in) {
319
0
    error(_("garbage at end of loose object '%s'"),
320
0
          oid_to_hex(oid));
321
0
    FREE_AND_NULL(buf);
322
0
  }
323
324
0
  return buf;
325
0
}
326
327
/*
328
 * parse_loose_header() parses the starting "<type> <len>\0" of an
329
 * object. If it doesn't follow that format -1 is returned. To check
330
 * the validity of the <type> populate the "typep" in the "struct
331
 * object_info". It will be OBJ_BAD if the object type is unknown. The
332
 * parsed <len> can be retrieved via "oi->sizep", and from there
333
 * passed to unpack_loose_rest().
334
 *
335
 * We used to just use "sscanf()", but that's actually way
336
 * too permissive for what we want to check. So do an anal
337
 * object header parse by hand.
338
 */
339
static int parse_loose_header(const char *hdr, struct object_info *oi)
340
0
{
341
0
  const char *type_buf = hdr;
342
0
  size_t size;
343
0
  int type, type_len = 0;
344
345
  /*
346
   * The type can be of any size but is followed by
347
   * a space.
348
   */
349
0
  for (;;) {
350
0
    char c = *hdr++;
351
0
    if (!c)
352
0
      return -1;
353
0
    if (c == ' ')
354
0
      break;
355
0
    type_len++;
356
0
  }
357
358
0
  type = type_from_string_gently(type_buf, type_len, 1);
359
0
  if (oi->typep)
360
0
    *oi->typep = type;
361
362
  /*
363
   * The length must follow immediately, and be in canonical
364
   * decimal format (ie "010" is not valid).
365
   */
366
0
  size = *hdr++ - '0';
367
0
  if (size > 9)
368
0
    return -1;
369
0
  if (size) {
370
0
    for (;;) {
371
0
      unsigned long c = *hdr - '0';
372
0
      if (c > 9)
373
0
        break;
374
0
      hdr++;
375
0
      size = st_add(st_mult(size, 10), c);
376
0
    }
377
0
  }
378
379
0
  if (oi->sizep)
380
0
    *oi->sizep = cast_size_t_to_ulong(size);
381
382
  /*
383
   * The length must be followed by a zero byte
384
   */
385
0
  if (*hdr)
386
0
    return -1;
387
388
  /*
389
   * The format is valid, but the type may still be bogus. The
390
   * Caller needs to check its oi->typep.
391
   */
392
0
  return 0;
393
0
}
394
395
static int read_object_info_from_path(struct odb_source *source,
396
              const char *path,
397
              const struct object_id *oid,
398
              struct object_info *oi,
399
              enum object_info_flags flags)
400
0
{
401
0
  struct odb_source_files *files = odb_source_files_downcast(source);
402
0
  int ret;
403
0
  int fd;
404
0
  unsigned long mapsize;
405
0
  void *map = NULL;
406
0
  git_zstream stream, *stream_to_end = NULL;
407
0
  char hdr[MAX_HEADER_LEN];
408
0
  unsigned long size_scratch;
409
0
  enum object_type type_scratch;
410
0
  struct stat st;
411
412
  /*
413
   * If we don't care about type or size, then we don't
414
   * need to look inside the object at all. Note that we
415
   * do not optimize out the stat call, even if the
416
   * caller doesn't care about the disk-size, since our
417
   * return value implicitly indicates whether the
418
   * object even exists.
419
   */
420
0
  if (!oi || (!oi->typep && !oi->sizep && !oi->contentp)) {
421
0
    struct stat st;
422
423
0
    if ((!oi || (!oi->disk_sizep && !oi->mtimep)) && (flags & OBJECT_INFO_QUICK)) {
424
0
      ret = quick_has_loose(files->loose, oid) ? 0 : -1;
425
0
      goto out;
426
0
    }
427
428
0
    if (lstat(path, &st) < 0) {
429
0
      ret = -1;
430
0
      goto out;
431
0
    }
432
433
0
    if (oi) {
434
0
      if (oi->disk_sizep)
435
0
        *oi->disk_sizep = st.st_size;
436
0
      if (oi->mtimep)
437
0
        *oi->mtimep = st.st_mtime;
438
0
    }
439
440
0
    ret = 0;
441
0
    goto out;
442
0
  }
443
444
0
  fd = git_open(path);
445
0
  if (fd < 0) {
446
0
    if (errno != ENOENT)
447
0
      error_errno(_("unable to open loose object %s"), oid_to_hex(oid));
448
0
    ret = -1;
449
0
    goto out;
450
0
  }
451
452
0
  if (fstat(fd, &st)) {
453
0
    close(fd);
454
0
    ret = -1;
455
0
    goto out;
456
0
  }
457
458
0
  mapsize = xsize_t(st.st_size);
459
0
  if (!mapsize) {
460
0
    close(fd);
461
0
    ret = error(_("object file %s is empty"), path);
462
0
    goto out;
463
0
  }
464
465
0
  map = xmmap(NULL, mapsize, PROT_READ, MAP_PRIVATE, fd, 0);
466
0
  close(fd);
467
0
  if (!map) {
468
0
    ret = -1;
469
0
    goto out;
470
0
  }
471
472
0
  if (oi->disk_sizep)
473
0
    *oi->disk_sizep = mapsize;
474
0
  if (oi->mtimep)
475
0
    *oi->mtimep = st.st_mtime;
476
477
0
  stream_to_end = &stream;
478
479
0
  switch (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr))) {
480
0
  case ULHR_OK:
481
0
    if (!oi->sizep)
482
0
      oi->sizep = &size_scratch;
483
0
    if (!oi->typep)
484
0
      oi->typep = &type_scratch;
485
486
0
    if (parse_loose_header(hdr, oi) < 0) {
487
0
      ret = error(_("unable to parse %s header"), oid_to_hex(oid));
488
0
      goto corrupt;
489
0
    }
490
491
0
    if (*oi->typep < 0)
492
0
      die(_("invalid object type"));
493
494
0
    if (oi->contentp) {
495
0
      *oi->contentp = unpack_loose_rest(&stream, hdr, *oi->sizep, oid);
496
0
      if (!*oi->contentp) {
497
0
        ret = -1;
498
0
        goto corrupt;
499
0
      }
500
0
    }
501
502
0
    break;
503
0
  case ULHR_BAD:
504
0
    ret = error(_("unable to unpack %s header"),
505
0
          oid_to_hex(oid));
506
0
    goto corrupt;
507
0
  case ULHR_TOO_LONG:
508
0
    ret = error(_("header for %s too long, exceeds %d bytes"),
509
0
          oid_to_hex(oid), MAX_HEADER_LEN);
510
0
    goto corrupt;
511
0
  }
512
513
0
  ret = 0;
514
515
0
corrupt:
516
0
  if (ret && (flags & OBJECT_INFO_DIE_IF_CORRUPT))
517
0
    die(_("loose object %s (stored in %s) is corrupt"),
518
0
        oid_to_hex(oid), path);
519
520
0
out:
521
0
  if (stream_to_end)
522
0
    git_inflate_end(stream_to_end);
523
0
  if (map)
524
0
    munmap(map, mapsize);
525
0
  if (oi) {
526
0
    if (oi->sizep == &size_scratch)
527
0
      oi->sizep = NULL;
528
0
    if (oi->typep == &type_scratch)
529
0
      oi->typep = NULL;
530
0
    if (oi->delta_base_oid)
531
0
      oidclr(oi->delta_base_oid, source->odb->repo->hash_algo);
532
0
    if (!ret)
533
0
      oi->whence = OI_LOOSE;
534
0
  }
535
536
0
  return ret;
537
0
}
538
539
int odb_source_loose_read_object_info(struct odb_source *source,
540
              const struct object_id *oid,
541
              struct object_info *oi,
542
              enum object_info_flags flags)
543
0
{
544
0
  static struct strbuf buf = STRBUF_INIT;
545
546
  /*
547
   * The second read shouldn't cause new loose objects to show up, unless
548
   * there was a race condition with a secondary process. We don't care
549
   * about this case though, so we simply skip reading loose objects a
550
   * second time.
551
   */
552
0
  if (flags & OBJECT_INFO_SECOND_READ)
553
0
    return -1;
554
555
0
  odb_loose_path(source, &buf, oid);
556
0
  return read_object_info_from_path(source, buf.buf, oid, oi, flags);
557
0
}
558
559
static void hash_object_body(const struct git_hash_algo *algo, struct git_hash_ctx *c,
560
           const void *buf, unsigned long len,
561
           struct object_id *oid,
562
           char *hdr, int *hdrlen)
563
0
{
564
0
  algo->init_fn(c);
565
0
  git_hash_update(c, hdr, *hdrlen);
566
0
  git_hash_update(c, buf, len);
567
0
  git_hash_final_oid(oid, c);
568
0
}
569
570
static void write_object_file_prepare(const struct git_hash_algo *algo,
571
              const void *buf, unsigned long len,
572
              enum object_type type, struct object_id *oid,
573
              char *hdr, int *hdrlen)
574
0
{
575
0
  struct git_hash_ctx c;
576
577
  /* Generate the header */
578
0
  *hdrlen = format_object_header(hdr, *hdrlen, type, len);
579
580
  /* Sha1.. */
581
0
  hash_object_body(algo, &c, buf, len, oid, hdr, hdrlen);
582
0
}
583
584
0
#define CHECK_COLLISION_DEST_VANISHED -2
585
586
static int check_collision(const char *source, const char *dest)
587
0
{
588
0
  char buf_source[4096], buf_dest[4096];
589
0
  int fd_source = -1, fd_dest = -1;
590
0
  int ret = 0;
591
592
0
  fd_source = open(source, O_RDONLY);
593
0
  if (fd_source < 0) {
594
0
    ret = error_errno(_("unable to open %s"), source);
595
0
    goto out;
596
0
  }
597
598
0
  fd_dest = open(dest, O_RDONLY);
599
0
  if (fd_dest < 0) {
600
0
    if (errno != ENOENT)
601
0
      ret = error_errno(_("unable to open %s"), dest);
602
0
    else
603
0
      ret = CHECK_COLLISION_DEST_VANISHED;
604
0
    goto out;
605
0
  }
606
607
0
  while (1) {
608
0
    ssize_t sz_a, sz_b;
609
610
0
    sz_a = read_in_full(fd_source, buf_source, sizeof(buf_source));
611
0
    if (sz_a < 0) {
612
0
      ret = error_errno(_("unable to read %s"), source);
613
0
      goto out;
614
0
    }
615
616
0
    sz_b = read_in_full(fd_dest, buf_dest, sizeof(buf_dest));
617
0
    if (sz_b < 0) {
618
0
      ret = error_errno(_("unable to read %s"), dest);
619
0
      goto out;
620
0
    }
621
622
0
    if (sz_a != sz_b || memcmp(buf_source, buf_dest, sz_a)) {
623
0
      ret = error(_("files '%s' and '%s' differ in contents"),
624
0
            source, dest);
625
0
      goto out;
626
0
    }
627
628
0
    if ((size_t) sz_a < sizeof(buf_source))
629
0
      break;
630
0
  }
631
632
0
out:
633
0
  if (fd_source > -1)
634
0
    close(fd_source);
635
0
  if (fd_dest > -1)
636
0
    close(fd_dest);
637
0
  return ret;
638
0
}
639
640
/*
641
 * Move the just written object into its final resting place.
642
 */
643
int finalize_object_file(struct repository *repo,
644
       const char *tmpfile, const char *filename)
645
0
{
646
0
  return finalize_object_file_flags(repo, tmpfile, filename, 0);
647
0
}
648
649
int finalize_object_file_flags(struct repository *repo,
650
             const char *tmpfile, const char *filename,
651
             enum finalize_object_file_flags flags)
652
0
{
653
0
  unsigned retries = 0;
654
0
  int ret;
655
656
0
retry:
657
0
  ret = 0;
658
659
0
  if (object_creation_mode == OBJECT_CREATION_USES_RENAMES)
660
0
    goto try_rename;
661
0
  else if (link(tmpfile, filename))
662
0
    ret = errno;
663
0
  else
664
0
    unlink_or_warn(tmpfile);
665
666
  /*
667
   * Coda hack - coda doesn't like cross-directory links,
668
   * so we fall back to a rename, which will mean that it
669
   * won't be able to check collisions, but that's not a
670
   * big deal.
671
   *
672
   * The same holds for FAT formatted media.
673
   *
674
   * When this succeeds, we just return.  We have nothing
675
   * left to unlink.
676
   */
677
0
  if (ret && ret != EEXIST) {
678
0
    struct stat st;
679
680
0
  try_rename:
681
0
    if (!stat(filename, &st))
682
0
      ret = EEXIST;
683
0
    else if (!rename(tmpfile, filename))
684
0
      goto out;
685
0
    else
686
0
      ret = errno;
687
0
  }
688
0
  if (ret) {
689
0
    if (ret != EEXIST) {
690
0
      int saved_errno = errno;
691
0
      unlink_or_warn(tmpfile);
692
0
      errno = saved_errno;
693
0
      return error_errno(_("unable to write file %s"), filename);
694
0
    }
695
0
    if (!(flags & FOF_SKIP_COLLISION_CHECK)) {
696
0
      ret = check_collision(tmpfile, filename);
697
0
      if (ret == CHECK_COLLISION_DEST_VANISHED) {
698
0
        if (retries++ > 5)
699
0
          return error(_("unable to write repeatedly vanishing file %s"),
700
0
                 filename);
701
0
        goto retry;
702
0
      }
703
0
      else if (ret)
704
0
        return -1;
705
0
    }
706
0
    unlink_or_warn(tmpfile);
707
0
  }
708
709
0
out:
710
0
  if (adjust_shared_perm(repo, filename))
711
0
    return error(_("unable to set permission to '%s'"), filename);
712
0
  return 0;
713
0
}
714
715
void hash_object_file(const struct git_hash_algo *algo, const void *buf,
716
          unsigned long len, enum object_type type,
717
          struct object_id *oid)
718
0
{
719
0
  char hdr[MAX_HEADER_LEN];
720
0
  int hdrlen = sizeof(hdr);
721
722
0
  write_object_file_prepare(algo, buf, len, type, oid, hdr, &hdrlen);
723
0
}
724
725
struct transaction_packfile {
726
  char *pack_tmp_name;
727
  struct hashfile *f;
728
  off_t offset;
729
  struct pack_idx_option pack_idx_opts;
730
731
  struct pack_idx_entry **written;
732
  uint32_t alloc_written;
733
  uint32_t nr_written;
734
};
735
736
struct odb_transaction_files {
737
  struct odb_transaction base;
738
739
  struct tmp_objdir *objdir;
740
  struct transaction_packfile packfile;
741
};
742
743
static void prepare_loose_object_transaction(struct odb_transaction *base)
744
0
{
745
0
  struct odb_transaction_files *transaction =
746
0
    container_of_or_null(base, struct odb_transaction_files, base);
747
748
  /*
749
   * We lazily create the temporary object directory
750
   * the first time an object might be added, since
751
   * callers may not know whether any objects will be
752
   * added at the time they call odb_transaction_files_begin.
753
   */
754
0
  if (!transaction || transaction->objdir)
755
0
    return;
756
757
0
  transaction->objdir = tmp_objdir_create(base->source->odb->repo, "bulk-fsync");
758
0
  if (transaction->objdir)
759
0
    tmp_objdir_replace_primary_odb(transaction->objdir, 0);
760
0
}
761
762
static void fsync_loose_object_transaction(struct odb_transaction *base,
763
             int fd, const char *filename)
764
0
{
765
0
  struct odb_transaction_files *transaction =
766
0
    container_of_or_null(base, struct odb_transaction_files, base);
767
768
  /*
769
   * If we have an active ODB transaction, we issue a call that
770
   * cleans the filesystem page cache but avoids a hardware flush
771
   * command. Later on we will issue a single hardware flush
772
   * before renaming the objects to their final names as part of
773
   * flush_batch_fsync.
774
   */
775
0
  if (!transaction || !transaction->objdir ||
776
0
      git_fsync(fd, FSYNC_WRITEOUT_ONLY) < 0) {
777
0
    if (errno == ENOSYS)
778
0
      warning(_("core.fsyncMethod = batch is unsupported on this platform"));
779
0
    fsync_or_die(fd, filename);
780
0
  }
781
0
}
782
783
/*
784
 * Cleanup after batch-mode fsync_object_files.
785
 */
786
static void flush_loose_object_transaction(struct odb_transaction_files *transaction)
787
0
{
788
0
  struct strbuf temp_path = STRBUF_INIT;
789
0
  struct tempfile *temp;
790
791
0
  if (!transaction->objdir)
792
0
    return;
793
794
  /*
795
   * Issue a full hardware flush against a temporary file to ensure
796
   * that all objects are durable before any renames occur. The code in
797
   * fsync_loose_object_transaction has already issued a writeout
798
   * request, but it has not flushed any writeback cache in the storage
799
   * hardware or any filesystem logs. This fsync call acts as a barrier
800
   * to ensure that the data in each new object file is durable before
801
   * the final name is visible.
802
   */
803
0
  strbuf_addf(&temp_path, "%s/bulk_fsync_XXXXXX",
804
0
        repo_get_object_directory(transaction->base.source->odb->repo));
805
0
  temp = xmks_tempfile(temp_path.buf);
806
0
  fsync_or_die(get_tempfile_fd(temp), get_tempfile_path(temp));
807
0
  delete_tempfile(&temp);
808
0
  strbuf_release(&temp_path);
809
810
  /*
811
   * Make the object files visible in the primary ODB after their data is
812
   * fully durable.
813
   */
814
0
  tmp_objdir_migrate(transaction->objdir);
815
0
  transaction->objdir = NULL;
816
0
}
817
818
/* Finalize a file on disk, and close it. */
819
static void close_loose_object(struct odb_source *source,
820
             int fd, const char *filename)
821
0
{
822
0
  if (source->will_destroy)
823
0
    goto out;
824
825
0
  if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
826
0
    fsync_loose_object_transaction(source->odb->transaction, fd, filename);
827
0
  else if (fsync_object_files > 0)
828
0
    fsync_or_die(fd, filename);
829
0
  else
830
0
    fsync_component_or_die(FSYNC_COMPONENT_LOOSE_OBJECT, fd,
831
0
               filename);
832
833
0
out:
834
0
  if (close(fd) != 0)
835
0
    die_errno(_("error when closing loose object file"));
836
0
}
837
838
/* Size of directory component, including the ending '/' */
839
static inline int directory_size(const char *filename)
840
0
{
841
0
  const char *s = strrchr(filename, '/');
842
0
  if (!s)
843
0
    return 0;
844
0
  return s - filename + 1;
845
0
}
846
847
/*
848
 * This creates a temporary file in the same directory as the final
849
 * 'filename'
850
 *
851
 * We want to avoid cross-directory filename renames, because those
852
 * can have problems on various filesystems (FAT, NFS, Coda).
853
 */
854
static int create_tmpfile(struct repository *repo,
855
        struct strbuf *tmp, const char *filename)
856
0
{
857
0
  int fd, dirlen = directory_size(filename);
858
859
0
  strbuf_reset(tmp);
860
0
  strbuf_add(tmp, filename, dirlen);
861
0
  strbuf_addstr(tmp, "tmp_obj_XXXXXX");
862
0
  fd = git_mkstemp_mode(tmp->buf, 0444);
863
0
  if (fd < 0 && dirlen && errno == ENOENT) {
864
    /*
865
     * Make sure the directory exists; note that the contents
866
     * of the buffer are undefined after mkstemp returns an
867
     * error, so we have to rewrite the whole buffer from
868
     * scratch.
869
     */
870
0
    strbuf_reset(tmp);
871
0
    strbuf_add(tmp, filename, dirlen - 1);
872
0
    if (mkdir(tmp->buf, 0777) && errno != EEXIST)
873
0
      return -1;
874
0
    if (adjust_shared_perm(repo, tmp->buf))
875
0
      return -1;
876
877
    /* Try again */
878
0
    strbuf_addstr(tmp, "/tmp_obj_XXXXXX");
879
0
    fd = git_mkstemp_mode(tmp->buf, 0444);
880
0
  }
881
0
  return fd;
882
0
}
883
884
/**
885
 * Common steps for loose object writers to start writing loose
886
 * objects:
887
 *
888
 * - Create tmpfile for the loose object.
889
 * - Setup zlib stream for compression.
890
 * - Start to feed header to zlib stream.
891
 *
892
 * Returns a "fd", which should later be provided to
893
 * end_loose_object_common().
894
 */
895
static int start_loose_object_common(struct odb_source *source,
896
             struct strbuf *tmp_file,
897
             const char *filename, unsigned flags,
898
             git_zstream *stream,
899
             unsigned char *buf, size_t buflen,
900
             struct git_hash_ctx *c, struct git_hash_ctx *compat_c,
901
             char *hdr, int hdrlen)
902
0
{
903
0
  const struct git_hash_algo *algo = source->odb->repo->hash_algo;
904
0
  const struct git_hash_algo *compat = source->odb->repo->compat_hash_algo;
905
0
  int fd;
906
907
0
  fd = create_tmpfile(source->odb->repo, tmp_file, filename);
908
0
  if (fd < 0) {
909
0
    if (flags & WRITE_OBJECT_SILENT)
910
0
      return -1;
911
0
    else if (errno == EACCES)
912
0
      return error(_("insufficient permission for adding "
913
0
               "an object to repository database %s"),
914
0
             source->path);
915
0
    else
916
0
      return error_errno(
917
0
        _("unable to create temporary file"));
918
0
  }
919
920
  /*  Setup zlib stream for compression */
921
0
  git_deflate_init(stream, zlib_compression_level);
922
0
  stream->next_out = buf;
923
0
  stream->avail_out = buflen;
924
0
  algo->init_fn(c);
925
0
  if (compat && compat_c)
926
0
    compat->init_fn(compat_c);
927
928
  /*  Start to feed header to zlib stream */
929
0
  stream->next_in = (unsigned char *)hdr;
930
0
  stream->avail_in = hdrlen;
931
0
  while (git_deflate(stream, 0) == Z_OK)
932
0
    ; /* nothing */
933
0
  git_hash_update(c, hdr, hdrlen);
934
0
  if (compat && compat_c)
935
0
    git_hash_update(compat_c, hdr, hdrlen);
936
937
0
  return fd;
938
0
}
939
940
/**
941
 * Common steps for the inner git_deflate() loop for writing loose
942
 * objects. Returns what git_deflate() returns.
943
 */
944
static int write_loose_object_common(struct odb_source *source,
945
             struct git_hash_ctx *c, struct git_hash_ctx *compat_c,
946
             git_zstream *stream, const int flush,
947
             unsigned char *in0, const int fd,
948
             unsigned char *compressed,
949
             const size_t compressed_len)
950
0
{
951
0
  const struct git_hash_algo *compat = source->odb->repo->compat_hash_algo;
952
0
  int ret;
953
954
0
  ret = git_deflate(stream, flush ? Z_FINISH : 0);
955
0
  git_hash_update(c, in0, stream->next_in - in0);
956
0
  if (compat && compat_c)
957
0
    git_hash_update(compat_c, in0, stream->next_in - in0);
958
0
  if (write_in_full(fd, compressed, stream->next_out - compressed) < 0)
959
0
    die_errno(_("unable to write loose object file"));
960
0
  stream->next_out = compressed;
961
0
  stream->avail_out = compressed_len;
962
963
0
  return ret;
964
0
}
965
966
/**
967
 * Common steps for loose object writers to end writing loose objects:
968
 *
969
 * - End the compression of zlib stream.
970
 * - Get the calculated oid to "oid".
971
 */
972
static int end_loose_object_common(struct odb_source *source,
973
           struct git_hash_ctx *c, struct git_hash_ctx *compat_c,
974
           git_zstream *stream, struct object_id *oid,
975
           struct object_id *compat_oid)
976
0
{
977
0
  const struct git_hash_algo *compat = source->odb->repo->compat_hash_algo;
978
0
  int ret;
979
980
0
  ret = git_deflate_end_gently(stream);
981
0
  if (ret != Z_OK)
982
0
    return ret;
983
0
  git_hash_final_oid(oid, c);
984
0
  if (compat && compat_c)
985
0
    git_hash_final_oid(compat_oid, compat_c);
986
987
0
  return Z_OK;
988
0
}
989
990
static int write_loose_object(struct odb_source *source,
991
            const struct object_id *oid, char *hdr,
992
            int hdrlen, const void *buf, unsigned long len,
993
            time_t mtime, unsigned flags)
994
0
{
995
0
  int fd, ret;
996
0
  unsigned char compressed[4096];
997
0
  git_zstream stream;
998
0
  struct git_hash_ctx c;
999
0
  struct object_id parano_oid;
1000
0
  static struct strbuf tmp_file = STRBUF_INIT;
1001
0
  static struct strbuf filename = STRBUF_INIT;
1002
1003
0
  if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
1004
0
    prepare_loose_object_transaction(source->odb->transaction);
1005
1006
0
  odb_loose_path(source, &filename, oid);
1007
1008
0
  fd = start_loose_object_common(source, &tmp_file, filename.buf, flags,
1009
0
               &stream, compressed, sizeof(compressed),
1010
0
               &c, NULL, hdr, hdrlen);
1011
0
  if (fd < 0)
1012
0
    return -1;
1013
1014
  /* Then the data itself.. */
1015
0
  stream.next_in = (void *)buf;
1016
0
  stream.avail_in = len;
1017
0
  do {
1018
0
    unsigned char *in0 = stream.next_in;
1019
1020
0
    ret = write_loose_object_common(source, &c, NULL, &stream, 1, in0, fd,
1021
0
            compressed, sizeof(compressed));
1022
0
  } while (ret == Z_OK);
1023
1024
0
  if (ret != Z_STREAM_END)
1025
0
    die(_("unable to deflate new object %s (%d)"), oid_to_hex(oid),
1026
0
        ret);
1027
0
  ret = end_loose_object_common(source, &c, NULL, &stream, &parano_oid, NULL);
1028
0
  if (ret != Z_OK)
1029
0
    die(_("deflateEnd on object %s failed (%d)"), oid_to_hex(oid),
1030
0
        ret);
1031
0
  if (!oideq(oid, &parano_oid))
1032
0
    die(_("confused by unstable object source data for %s"),
1033
0
        oid_to_hex(oid));
1034
1035
0
  close_loose_object(source, fd, tmp_file.buf);
1036
1037
0
  if (mtime) {
1038
0
    struct utimbuf utb;
1039
0
    utb.actime = mtime;
1040
0
    utb.modtime = mtime;
1041
0
    if (utime(tmp_file.buf, &utb) < 0 &&
1042
0
        !(flags & WRITE_OBJECT_SILENT))
1043
0
      warning_errno(_("failed utime() on %s"), tmp_file.buf);
1044
0
  }
1045
1046
0
  return finalize_object_file_flags(source->odb->repo, tmp_file.buf, filename.buf,
1047
0
            FOF_SKIP_COLLISION_CHECK);
1048
0
}
1049
1050
int odb_source_loose_freshen_object(struct odb_source *source,
1051
            const struct object_id *oid)
1052
0
{
1053
0
  return !!check_and_freshen_source(source, oid, 1);
1054
0
}
1055
1056
int odb_source_loose_write_stream(struct odb_source *source,
1057
          struct odb_write_stream *in_stream, size_t len,
1058
          struct object_id *oid)
1059
0
{
1060
0
  const struct git_hash_algo *compat = source->odb->repo->compat_hash_algo;
1061
0
  struct object_id compat_oid;
1062
0
  int fd, ret, err = 0, flush = 0;
1063
0
  unsigned char compressed[4096];
1064
0
  git_zstream stream;
1065
0
  struct git_hash_ctx c, compat_c;
1066
0
  struct strbuf tmp_file = STRBUF_INIT;
1067
0
  struct strbuf filename = STRBUF_INIT;
1068
0
  int dirlen;
1069
0
  char hdr[MAX_HEADER_LEN];
1070
0
  int hdrlen;
1071
1072
0
  if (batch_fsync_enabled(FSYNC_COMPONENT_LOOSE_OBJECT))
1073
0
    prepare_loose_object_transaction(source->odb->transaction);
1074
1075
  /* Since oid is not determined, save tmp file to odb path. */
1076
0
  strbuf_addf(&filename, "%s/", source->path);
1077
0
  hdrlen = format_object_header(hdr, sizeof(hdr), OBJ_BLOB, len);
1078
1079
  /*
1080
   * Common steps for write_loose_object and stream_loose_object to
1081
   * start writing loose objects:
1082
   *
1083
   *  - Create tmpfile for the loose object.
1084
   *  - Setup zlib stream for compression.
1085
   *  - Start to feed header to zlib stream.
1086
   */
1087
0
  fd = start_loose_object_common(source, &tmp_file, filename.buf, 0,
1088
0
               &stream, compressed, sizeof(compressed),
1089
0
               &c, &compat_c, hdr, hdrlen);
1090
0
  if (fd < 0) {
1091
0
    err = -1;
1092
0
    goto cleanup;
1093
0
  }
1094
1095
  /* Then the data itself.. */
1096
0
  do {
1097
0
    unsigned char *in0 = stream.next_in;
1098
1099
0
    if (!stream.avail_in && !in_stream->is_finished) {
1100
0
      const void *in = in_stream->read(in_stream, &stream.avail_in);
1101
0
      stream.next_in = (void *)in;
1102
0
      in0 = (unsigned char *)in;
1103
      /* All data has been read. */
1104
0
      if (in_stream->is_finished)
1105
0
        flush = 1;
1106
0
    }
1107
0
    ret = write_loose_object_common(source, &c, &compat_c, &stream, flush, in0, fd,
1108
0
            compressed, sizeof(compressed));
1109
    /*
1110
     * Unlike write_loose_object(), we do not have the entire
1111
     * buffer. If we get Z_BUF_ERROR due to too few input bytes,
1112
     * then we'll replenish them in the next input_stream->read()
1113
     * call when we loop.
1114
     */
1115
0
  } while (ret == Z_OK || ret == Z_BUF_ERROR);
1116
1117
0
  if (stream.total_in != len + hdrlen)
1118
0
    die(_("write stream object %ld != %"PRIuMAX), stream.total_in,
1119
0
        (uintmax_t)len + hdrlen);
1120
1121
  /*
1122
   * Common steps for write_loose_object and stream_loose_object to
1123
   * end writing loose object:
1124
   *
1125
   *  - End the compression of zlib stream.
1126
   *  - Get the calculated oid.
1127
   */
1128
0
  if (ret != Z_STREAM_END)
1129
0
    die(_("unable to stream deflate new object (%d)"), ret);
1130
0
  ret = end_loose_object_common(source, &c, &compat_c, &stream, oid, &compat_oid);
1131
0
  if (ret != Z_OK)
1132
0
    die(_("deflateEnd on stream object failed (%d)"), ret);
1133
0
  close_loose_object(source, fd, tmp_file.buf);
1134
1135
0
  if (odb_freshen_object(source->odb, oid)) {
1136
0
    unlink_or_warn(tmp_file.buf);
1137
0
    goto cleanup;
1138
0
  }
1139
0
  odb_loose_path(source, &filename, oid);
1140
1141
  /* We finally know the object path, and create the missing dir. */
1142
0
  dirlen = directory_size(filename.buf);
1143
0
  if (dirlen) {
1144
0
    struct strbuf dir = STRBUF_INIT;
1145
0
    strbuf_add(&dir, filename.buf, dirlen);
1146
1147
0
    if (safe_create_dir_in_gitdir(source->odb->repo, dir.buf) &&
1148
0
        errno != EEXIST) {
1149
0
      err = error_errno(_("unable to create directory %s"), dir.buf);
1150
0
      strbuf_release(&dir);
1151
0
      goto cleanup;
1152
0
    }
1153
0
    strbuf_release(&dir);
1154
0
  }
1155
1156
0
  err = finalize_object_file_flags(source->odb->repo, tmp_file.buf, filename.buf,
1157
0
           FOF_SKIP_COLLISION_CHECK);
1158
0
  if (!err && compat)
1159
0
    err = repo_add_loose_object_map(source, oid, &compat_oid);
1160
0
cleanup:
1161
0
  strbuf_release(&tmp_file);
1162
0
  strbuf_release(&filename);
1163
0
  return err;
1164
0
}
1165
1166
int odb_source_loose_write_object(struct odb_source *source,
1167
          const void *buf, unsigned long len,
1168
          enum object_type type, struct object_id *oid,
1169
          struct object_id *compat_oid_in, unsigned flags)
1170
0
{
1171
0
  const struct git_hash_algo *algo = source->odb->repo->hash_algo;
1172
0
  const struct git_hash_algo *compat = source->odb->repo->compat_hash_algo;
1173
0
  struct object_id compat_oid;
1174
0
  char hdr[MAX_HEADER_LEN];
1175
0
  int hdrlen = sizeof(hdr);
1176
1177
  /* Generate compat_oid */
1178
0
  if (compat) {
1179
0
    if (compat_oid_in)
1180
0
      oidcpy(&compat_oid, compat_oid_in);
1181
0
    else if (type == OBJ_BLOB)
1182
0
      hash_object_file(compat, buf, len, type, &compat_oid);
1183
0
    else {
1184
0
      struct strbuf converted = STRBUF_INIT;
1185
0
      convert_object_file(source->odb->repo, &converted, algo, compat,
1186
0
              buf, len, type, 0);
1187
0
      hash_object_file(compat, converted.buf, converted.len,
1188
0
           type, &compat_oid);
1189
0
      strbuf_release(&converted);
1190
0
    }
1191
0
  }
1192
1193
  /* Normally if we have it in the pack then we do not bother writing
1194
   * it out into .git/objects/??/?{38} file.
1195
   */
1196
0
  write_object_file_prepare(algo, buf, len, type, oid, hdr, &hdrlen);
1197
0
  if (odb_freshen_object(source->odb, oid))
1198
0
    return 0;
1199
0
  if (write_loose_object(source, oid, hdr, hdrlen, buf, len, 0, flags))
1200
0
    return -1;
1201
0
  if (compat)
1202
0
    return repo_add_loose_object_map(source, oid, &compat_oid);
1203
0
  return 0;
1204
0
}
1205
1206
int force_object_loose(struct odb_source *source,
1207
           const struct object_id *oid, time_t mtime)
1208
0
{
1209
0
  const struct git_hash_algo *compat = source->odb->repo->compat_hash_algo;
1210
0
  void *buf;
1211
0
  unsigned long len;
1212
0
  struct object_info oi = OBJECT_INFO_INIT;
1213
0
  struct object_id compat_oid;
1214
0
  enum object_type type;
1215
0
  char hdr[MAX_HEADER_LEN];
1216
0
  int hdrlen;
1217
0
  int ret;
1218
1219
0
  for (struct odb_source *s = source->odb->sources; s; s = s->next)
1220
0
    if (odb_source_loose_has_object(s, oid))
1221
0
      return 0;
1222
1223
0
  oi.typep = &type;
1224
0
  oi.sizep = &len;
1225
0
  oi.contentp = &buf;
1226
0
  if (odb_read_object_info_extended(source->odb, oid, &oi, 0))
1227
0
    return error(_("cannot read object for %s"), oid_to_hex(oid));
1228
0
  if (compat) {
1229
0
    if (repo_oid_to_algop(source->odb->repo, oid, compat, &compat_oid))
1230
0
      return error(_("cannot map object %s to %s"),
1231
0
             oid_to_hex(oid), compat->name);
1232
0
  }
1233
0
  hdrlen = format_object_header(hdr, sizeof(hdr), type, len);
1234
0
  ret = write_loose_object(source, oid, hdr, hdrlen, buf, len, mtime, 0);
1235
0
  if (!ret && compat)
1236
0
    ret = repo_add_loose_object_map(source, oid, &compat_oid);
1237
0
  free(buf);
1238
1239
0
  return ret;
1240
0
}
1241
1242
/*
1243
 * We can't use the normal fsck_error_function() for index_mem(),
1244
 * because we don't yet have a valid oid for it to report. Instead,
1245
 * report the minimal fsck error here, and rely on the caller to
1246
 * give more context.
1247
 */
1248
static int hash_format_check_report(struct fsck_options *opts UNUSED,
1249
            void *fsck_report UNUSED,
1250
            enum fsck_msg_type msg_type UNUSED,
1251
            enum fsck_msg_id msg_id UNUSED,
1252
            const char *message)
1253
0
{
1254
0
  error(_("object fails fsck: %s"), message);
1255
0
  return 1;
1256
0
}
1257
1258
static int index_mem(struct index_state *istate,
1259
         struct object_id *oid,
1260
         const void *buf, size_t size,
1261
         enum object_type type,
1262
         const char *path, unsigned flags)
1263
0
{
1264
0
  struct strbuf nbuf = STRBUF_INIT;
1265
0
  int ret = 0;
1266
0
  int write_object = flags & INDEX_WRITE_OBJECT;
1267
1268
0
  if (!type)
1269
0
    type = OBJ_BLOB;
1270
1271
  /*
1272
   * Convert blobs to git internal format
1273
   */
1274
0
  if ((type == OBJ_BLOB) && path) {
1275
0
    if (convert_to_git(istate, path, buf, size, &nbuf,
1276
0
           get_conv_flags(flags))) {
1277
0
      buf = nbuf.buf;
1278
0
      size = nbuf.len;
1279
0
    }
1280
0
  }
1281
0
  if (flags & INDEX_FORMAT_CHECK) {
1282
0
    struct fsck_options opts = FSCK_OPTIONS_DEFAULT;
1283
1284
0
    opts.strict = 1;
1285
0
    opts.error_func = hash_format_check_report;
1286
0
    if (fsck_buffer(null_oid(istate->repo->hash_algo), type, buf, size, &opts))
1287
0
      die(_("refusing to create malformed object"));
1288
0
    fsck_finish(&opts);
1289
0
  }
1290
1291
0
  if (write_object)
1292
0
    ret = odb_write_object(istate->repo->objects, buf, size, type, oid);
1293
0
  else
1294
0
    hash_object_file(istate->repo->hash_algo, buf, size, type, oid);
1295
1296
0
  strbuf_release(&nbuf);
1297
0
  return ret;
1298
0
}
1299
1300
static int index_stream_convert_blob(struct index_state *istate,
1301
             struct object_id *oid,
1302
             int fd,
1303
             const char *path,
1304
             unsigned flags)
1305
0
{
1306
0
  int ret = 0;
1307
0
  const int write_object = flags & INDEX_WRITE_OBJECT;
1308
0
  struct strbuf sbuf = STRBUF_INIT;
1309
1310
0
  assert(path);
1311
0
  ASSERT(would_convert_to_git_filter_fd(istate, path));
1312
1313
0
  convert_to_git_filter_fd(istate, path, fd, &sbuf,
1314
0
         get_conv_flags(flags));
1315
1316
0
  if (write_object)
1317
0
    ret = odb_write_object(istate->repo->objects, sbuf.buf, sbuf.len, OBJ_BLOB,
1318
0
               oid);
1319
0
  else
1320
0
    hash_object_file(istate->repo->hash_algo, sbuf.buf, sbuf.len, OBJ_BLOB,
1321
0
         oid);
1322
0
  strbuf_release(&sbuf);
1323
0
  return ret;
1324
0
}
1325
1326
static int index_pipe(struct index_state *istate, struct object_id *oid,
1327
          int fd, enum object_type type,
1328
          const char *path, unsigned flags)
1329
0
{
1330
0
  struct strbuf sbuf = STRBUF_INIT;
1331
0
  int ret;
1332
1333
0
  if (strbuf_read(&sbuf, fd, 4096) >= 0)
1334
0
    ret = index_mem(istate, oid, sbuf.buf, sbuf.len, type, path, flags);
1335
0
  else
1336
0
    ret = -1;
1337
0
  strbuf_release(&sbuf);
1338
0
  return ret;
1339
0
}
1340
1341
0
#define SMALL_FILE_SIZE (32*1024)
1342
1343
static int index_core(struct index_state *istate,
1344
          struct object_id *oid, int fd, size_t size,
1345
          enum object_type type, const char *path,
1346
          unsigned flags)
1347
0
{
1348
0
  int ret;
1349
1350
0
  if (!size) {
1351
0
    ret = index_mem(istate, oid, "", size, type, path, flags);
1352
0
  } else if (size <= SMALL_FILE_SIZE) {
1353
0
    char *buf = xmalloc(size);
1354
0
    ssize_t read_result = read_in_full(fd, buf, size);
1355
0
    if (read_result < 0)
1356
0
      ret = error_errno(_("read error while indexing %s"),
1357
0
            path ? path : "<unknown>");
1358
0
    else if ((size_t) read_result != size)
1359
0
      ret = error(_("short read while indexing %s"),
1360
0
            path ? path : "<unknown>");
1361
0
    else
1362
0
      ret = index_mem(istate, oid, buf, size, type, path, flags);
1363
0
    free(buf);
1364
0
  } else {
1365
0
    void *buf = xmmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
1366
0
    ret = index_mem(istate, oid, buf, size, type, path, flags);
1367
0
    munmap(buf, size);
1368
0
  }
1369
0
  return ret;
1370
0
}
1371
1372
static int already_written(struct odb_transaction_files *transaction,
1373
         struct object_id *oid)
1374
0
{
1375
  /* The object may already exist in the repository */
1376
0
  if (odb_has_object(transaction->base.source->odb, oid,
1377
0
         HAS_OBJECT_RECHECK_PACKED | HAS_OBJECT_FETCH_PROMISOR))
1378
0
    return 1;
1379
1380
  /* Might want to keep the list sorted */
1381
0
  for (uint32_t i = 0; i < transaction->packfile.nr_written; i++)
1382
0
    if (oideq(&transaction->packfile.written[i]->oid, oid))
1383
0
      return 1;
1384
1385
  /* This is a new object we need to keep */
1386
0
  return 0;
1387
0
}
1388
1389
/* Lazily create backing packfile for the state */
1390
static void prepare_packfile_transaction(struct odb_transaction_files *transaction,
1391
           unsigned flags)
1392
0
{
1393
0
  struct transaction_packfile *state = &transaction->packfile;
1394
0
  if (!(flags & INDEX_WRITE_OBJECT) || state->f)
1395
0
    return;
1396
1397
0
  state->f = create_tmp_packfile(transaction->base.source->odb->repo,
1398
0
               &state->pack_tmp_name);
1399
0
  reset_pack_idx_option(&state->pack_idx_opts);
1400
1401
  /* Pretend we are going to write only one object */
1402
0
  state->offset = write_pack_header(state->f, 1);
1403
0
  if (!state->offset)
1404
0
    die_errno("unable to write pack header");
1405
0
}
1406
1407
/*
1408
 * Read the contents from fd for size bytes, streaming it to the
1409
 * packfile in state while updating the hash in ctx. Signal a failure
1410
 * by returning a negative value when the resulting pack would exceed
1411
 * the pack size limit and this is not the first object in the pack,
1412
 * so that the caller can discard what we wrote from the current pack
1413
 * by truncating it and opening a new one. The caller will then call
1414
 * us again after rewinding the input fd.
1415
 *
1416
 * The already_hashed_to pointer is kept untouched by the caller to
1417
 * make sure we do not hash the same byte when we are called
1418
 * again. This way, the caller does not have to checkpoint its hash
1419
 * status before calling us just in case we ask it to call us again
1420
 * with a new pack.
1421
 */
1422
static int stream_blob_to_pack(struct transaction_packfile *state,
1423
             struct git_hash_ctx *ctx, off_t *already_hashed_to,
1424
             int fd, size_t size, const char *path,
1425
             unsigned flags)
1426
0
{
1427
0
  git_zstream s;
1428
0
  unsigned char ibuf[16384];
1429
0
  unsigned char obuf[16384];
1430
0
  unsigned hdrlen;
1431
0
  int status = Z_OK;
1432
0
  int write_object = (flags & INDEX_WRITE_OBJECT);
1433
0
  off_t offset = 0;
1434
1435
0
  git_deflate_init(&s, pack_compression_level);
1436
1437
0
  hdrlen = encode_in_pack_object_header(obuf, sizeof(obuf), OBJ_BLOB, size);
1438
0
  s.next_out = obuf + hdrlen;
1439
0
  s.avail_out = sizeof(obuf) - hdrlen;
1440
1441
0
  while (status != Z_STREAM_END) {
1442
0
    if (size && !s.avail_in) {
1443
0
      size_t rsize = size < sizeof(ibuf) ? size : sizeof(ibuf);
1444
0
      ssize_t read_result = read_in_full(fd, ibuf, rsize);
1445
0
      if (read_result < 0)
1446
0
        die_errno("failed to read from '%s'", path);
1447
0
      if ((size_t)read_result != rsize)
1448
0
        die("failed to read %u bytes from '%s'",
1449
0
            (unsigned)rsize, path);
1450
0
      offset += rsize;
1451
0
      if (*already_hashed_to < offset) {
1452
0
        size_t hsize = offset - *already_hashed_to;
1453
0
        if (rsize < hsize)
1454
0
          hsize = rsize;
1455
0
        if (hsize)
1456
0
          git_hash_update(ctx, ibuf, hsize);
1457
0
        *already_hashed_to = offset;
1458
0
      }
1459
0
      s.next_in = ibuf;
1460
0
      s.avail_in = rsize;
1461
0
      size -= rsize;
1462
0
    }
1463
1464
0
    status = git_deflate(&s, size ? 0 : Z_FINISH);
1465
1466
0
    if (!s.avail_out || status == Z_STREAM_END) {
1467
0
      if (write_object) {
1468
0
        size_t written = s.next_out - obuf;
1469
1470
        /* would we bust the size limit? */
1471
0
        if (state->nr_written &&
1472
0
            pack_size_limit_cfg &&
1473
0
            pack_size_limit_cfg < state->offset + written) {
1474
0
          git_deflate_abort(&s);
1475
0
          return -1;
1476
0
        }
1477
1478
0
        hashwrite(state->f, obuf, written);
1479
0
        state->offset += written;
1480
0
      }
1481
0
      s.next_out = obuf;
1482
0
      s.avail_out = sizeof(obuf);
1483
0
    }
1484
1485
0
    switch (status) {
1486
0
    case Z_OK:
1487
0
    case Z_BUF_ERROR:
1488
0
    case Z_STREAM_END:
1489
0
      continue;
1490
0
    default:
1491
0
      die("unexpected deflate failure: %d", status);
1492
0
    }
1493
0
  }
1494
0
  git_deflate_end(&s);
1495
0
  return 0;
1496
0
}
1497
1498
static void flush_packfile_transaction(struct odb_transaction_files *transaction)
1499
0
{
1500
0
  struct transaction_packfile *state = &transaction->packfile;
1501
0
  struct repository *repo = transaction->base.source->odb->repo;
1502
0
  unsigned char hash[GIT_MAX_RAWSZ];
1503
0
  struct strbuf packname = STRBUF_INIT;
1504
0
  char *idx_tmp_name = NULL;
1505
1506
0
  if (!state->f)
1507
0
    return;
1508
1509
0
  if (state->nr_written == 0) {
1510
0
    close(state->f->fd);
1511
0
    free_hashfile(state->f);
1512
0
    unlink(state->pack_tmp_name);
1513
0
    goto clear_exit;
1514
0
  } else if (state->nr_written == 1) {
1515
0
    finalize_hashfile(state->f, hash, FSYNC_COMPONENT_PACK,
1516
0
          CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
1517
0
  } else {
1518
0
    int fd = finalize_hashfile(state->f, hash, FSYNC_COMPONENT_PACK, 0);
1519
0
    fixup_pack_header_footer(repo->hash_algo, fd, hash, state->pack_tmp_name,
1520
0
           state->nr_written, hash,
1521
0
           state->offset);
1522
0
    close(fd);
1523
0
  }
1524
1525
0
  strbuf_addf(&packname, "%s/pack/pack-%s.",
1526
0
        repo_get_object_directory(transaction->base.source->odb->repo),
1527
0
        hash_to_hex_algop(hash, repo->hash_algo));
1528
1529
0
  stage_tmp_packfiles(repo, &packname, state->pack_tmp_name,
1530
0
          state->written, state->nr_written, NULL,
1531
0
          &state->pack_idx_opts, hash, &idx_tmp_name);
1532
0
  rename_tmp_packfile_idx(repo, &packname, &idx_tmp_name);
1533
1534
0
  for (uint32_t i = 0; i < state->nr_written; i++)
1535
0
    free(state->written[i]);
1536
1537
0
clear_exit:
1538
0
  free(idx_tmp_name);
1539
0
  free(state->pack_tmp_name);
1540
0
  free(state->written);
1541
0
  memset(state, 0, sizeof(*state));
1542
1543
0
  strbuf_release(&packname);
1544
  /* Make objects we just wrote available to ourselves */
1545
0
  odb_reprepare(repo->objects);
1546
0
}
1547
1548
/*
1549
 * This writes the specified object to a packfile. Objects written here
1550
 * during the same transaction are written to the same packfile. The
1551
 * packfile is not flushed until the transaction is flushed. The caller
1552
 * is expected to ensure a valid transaction is setup for objects to be
1553
 * recorded to.
1554
 *
1555
 * This also bypasses the usual "convert-to-git" dance, and that is on
1556
 * purpose. We could write a streaming version of the converting
1557
 * functions and insert that before feeding the data to fast-import
1558
 * (or equivalent in-core API described above). However, that is
1559
 * somewhat complicated, as we do not know the size of the filter
1560
 * result, which we need to know beforehand when writing a git object.
1561
 * Since the primary motivation for trying to stream from the working
1562
 * tree file and to avoid mmaping it in core is to deal with large
1563
 * binary blobs, they generally do not want to get any conversion, and
1564
 * callers should avoid this code path when filters are requested.
1565
 */
1566
static int index_blob_packfile_transaction(struct odb_transaction_files *transaction,
1567
             struct object_id *result_oid, int fd,
1568
             size_t size, const char *path,
1569
             unsigned flags)
1570
0
{
1571
0
  struct transaction_packfile *state = &transaction->packfile;
1572
0
  off_t seekback, already_hashed_to;
1573
0
  struct git_hash_ctx ctx;
1574
0
  unsigned char obuf[16384];
1575
0
  unsigned header_len;
1576
0
  struct hashfile_checkpoint checkpoint;
1577
0
  struct pack_idx_entry *idx = NULL;
1578
1579
0
  seekback = lseek(fd, 0, SEEK_CUR);
1580
0
  if (seekback == (off_t)-1)
1581
0
    return error("cannot find the current offset");
1582
1583
0
  header_len = format_object_header((char *)obuf, sizeof(obuf),
1584
0
            OBJ_BLOB, size);
1585
0
  transaction->base.source->odb->repo->hash_algo->init_fn(&ctx);
1586
0
  git_hash_update(&ctx, obuf, header_len);
1587
1588
  /* Note: idx is non-NULL when we are writing */
1589
0
  if ((flags & INDEX_WRITE_OBJECT) != 0) {
1590
0
    CALLOC_ARRAY(idx, 1);
1591
1592
0
    prepare_packfile_transaction(transaction, flags);
1593
0
    hashfile_checkpoint_init(state->f, &checkpoint);
1594
0
  }
1595
1596
0
  already_hashed_to = 0;
1597
1598
0
  while (1) {
1599
0
    prepare_packfile_transaction(transaction, flags);
1600
0
    if (idx) {
1601
0
      hashfile_checkpoint(state->f, &checkpoint);
1602
0
      idx->offset = state->offset;
1603
0
      crc32_begin(state->f);
1604
0
    }
1605
0
    if (!stream_blob_to_pack(state, &ctx, &already_hashed_to,
1606
0
           fd, size, path, flags))
1607
0
      break;
1608
    /*
1609
     * Writing this object to the current pack will make
1610
     * it too big; we need to truncate it, start a new
1611
     * pack, and write into it.
1612
     */
1613
0
    if (!idx)
1614
0
      BUG("should not happen");
1615
0
    hashfile_truncate(state->f, &checkpoint);
1616
0
    state->offset = checkpoint.offset;
1617
0
    flush_packfile_transaction(transaction);
1618
0
    if (lseek(fd, seekback, SEEK_SET) == (off_t)-1)
1619
0
      return error("cannot seek back");
1620
0
  }
1621
0
  git_hash_final_oid(result_oid, &ctx);
1622
0
  if (!idx)
1623
0
    return 0;
1624
1625
0
  idx->crc32 = crc32_end(state->f);
1626
0
  if (already_written(transaction, result_oid)) {
1627
0
    hashfile_truncate(state->f, &checkpoint);
1628
0
    state->offset = checkpoint.offset;
1629
0
    free(idx);
1630
0
  } else {
1631
0
    oidcpy(&idx->oid, result_oid);
1632
0
    ALLOC_GROW(state->written,
1633
0
         state->nr_written + 1,
1634
0
         state->alloc_written);
1635
0
    state->written[state->nr_written++] = idx;
1636
0
  }
1637
0
  return 0;
1638
0
}
1639
1640
int index_fd(struct index_state *istate, struct object_id *oid,
1641
       int fd, struct stat *st,
1642
       enum object_type type, const char *path, unsigned flags)
1643
0
{
1644
0
  int ret;
1645
1646
  /*
1647
   * Call xsize_t() only when needed to avoid potentially unnecessary
1648
   * die() for large files.
1649
   */
1650
0
  if (type == OBJ_BLOB && path && would_convert_to_git_filter_fd(istate, path)) {
1651
0
    ret = index_stream_convert_blob(istate, oid, fd, path, flags);
1652
0
  } else if (!S_ISREG(st->st_mode)) {
1653
0
    ret = index_pipe(istate, oid, fd, type, path, flags);
1654
0
  } else if ((st->st_size >= 0 &&
1655
0
        (size_t)st->st_size <= repo_settings_get_big_file_threshold(istate->repo)) ||
1656
0
       type != OBJ_BLOB ||
1657
0
       (path && would_convert_to_git(istate, path))) {
1658
0
    ret = index_core(istate, oid, fd, xsize_t(st->st_size),
1659
0
         type, path, flags);
1660
0
  } else {
1661
0
    struct object_database *odb = the_repository->objects;
1662
0
    struct odb_transaction_files *files_transaction;
1663
0
    struct odb_transaction *transaction;
1664
1665
0
    transaction = odb_transaction_begin(odb);
1666
0
    files_transaction = container_of(odb->transaction,
1667
0
             struct odb_transaction_files,
1668
0
             base);
1669
0
    ret = index_blob_packfile_transaction(files_transaction, oid, fd,
1670
0
                  xsize_t(st->st_size),
1671
0
                  path, flags);
1672
0
    odb_transaction_commit(transaction);
1673
0
  }
1674
1675
0
  close(fd);
1676
0
  return ret;
1677
0
}
1678
1679
int index_path(struct index_state *istate, struct object_id *oid,
1680
         const char *path, struct stat *st, unsigned flags)
1681
0
{
1682
0
  int fd;
1683
0
  struct strbuf sb = STRBUF_INIT;
1684
0
  int rc = 0;
1685
1686
0
  switch (st->st_mode & S_IFMT) {
1687
0
  case S_IFREG:
1688
0
    fd = open(path, O_RDONLY);
1689
0
    if (fd < 0)
1690
0
      return error_errno("open(\"%s\")", path);
1691
0
    if (index_fd(istate, oid, fd, st, OBJ_BLOB, path, flags) < 0)
1692
0
      return error(_("%s: failed to insert into database"),
1693
0
             path);
1694
0
    break;
1695
0
  case S_IFLNK:
1696
0
    if (strbuf_readlink(&sb, path, st->st_size))
1697
0
      return error_errno("readlink(\"%s\")", path);
1698
0
    if (!(flags & INDEX_WRITE_OBJECT))
1699
0
      hash_object_file(istate->repo->hash_algo, sb.buf, sb.len,
1700
0
           OBJ_BLOB, oid);
1701
0
    else if (odb_write_object(istate->repo->objects, sb.buf, sb.len, OBJ_BLOB, oid))
1702
0
      rc = error(_("%s: failed to insert into database"), path);
1703
0
    strbuf_release(&sb);
1704
0
    break;
1705
0
  case S_IFDIR:
1706
0
    if (repo_resolve_gitlink_ref(istate->repo, path, "HEAD", oid))
1707
0
      return error(_("'%s' does not have a commit checked out"), path);
1708
0
    if (&hash_algos[oid->algo] != istate->repo->hash_algo)
1709
0
      return error(_("cannot add a submodule of a different hash algorithm"));
1710
0
    break;
1711
0
  default:
1712
0
    return error(_("%s: unsupported file type"), path);
1713
0
  }
1714
0
  return rc;
1715
0
}
1716
1717
int read_pack_header(int fd, struct pack_header *header)
1718
0
{
1719
0
  if (read_in_full(fd, header, sizeof(*header)) != sizeof(*header))
1720
    /* "eof before pack header was fully read" */
1721
0
    return PH_ERROR_EOF;
1722
1723
0
  if (header->hdr_signature != htonl(PACK_SIGNATURE))
1724
    /* "protocol error (pack signature mismatch detected)" */
1725
0
    return PH_ERROR_PACK_SIGNATURE;
1726
0
  if (!pack_version_ok(header->hdr_version))
1727
    /* "protocol error (pack version unsupported)" */
1728
0
    return PH_ERROR_PROTOCOL;
1729
0
  return 0;
1730
0
}
1731
1732
static int for_each_file_in_obj_subdir(unsigned int subdir_nr,
1733
               struct strbuf *path,
1734
               const struct git_hash_algo *algop,
1735
               each_loose_object_fn obj_cb,
1736
               each_loose_cruft_fn cruft_cb,
1737
               each_loose_subdir_fn subdir_cb,
1738
               void *data)
1739
0
{
1740
0
  size_t origlen, baselen;
1741
0
  DIR *dir;
1742
0
  struct dirent *de;
1743
0
  int r = 0;
1744
0
  struct object_id oid;
1745
1746
0
  if (subdir_nr > 0xff)
1747
0
    BUG("invalid loose object subdirectory: %x", subdir_nr);
1748
1749
0
  origlen = path->len;
1750
0
  strbuf_complete(path, '/');
1751
0
  strbuf_addf(path, "%02x", subdir_nr);
1752
1753
0
  dir = opendir(path->buf);
1754
0
  if (!dir) {
1755
0
    if (errno != ENOENT)
1756
0
      r = error_errno(_("unable to open %s"), path->buf);
1757
0
    strbuf_setlen(path, origlen);
1758
0
    return r;
1759
0
  }
1760
1761
0
  oid.hash[0] = subdir_nr;
1762
0
  strbuf_addch(path, '/');
1763
0
  baselen = path->len;
1764
1765
0
  while ((de = readdir_skip_dot_and_dotdot(dir))) {
1766
0
    size_t namelen;
1767
1768
0
    namelen = strlen(de->d_name);
1769
0
    strbuf_setlen(path, baselen);
1770
0
    strbuf_add(path, de->d_name, namelen);
1771
0
    if (namelen == algop->hexsz - 2 &&
1772
0
        !hex_to_bytes(oid.hash + 1, de->d_name,
1773
0
          algop->rawsz - 1)) {
1774
0
      oid_set_algo(&oid, algop);
1775
0
      memset(oid.hash + algop->rawsz, 0,
1776
0
             GIT_MAX_RAWSZ - algop->rawsz);
1777
0
      if (obj_cb) {
1778
0
        r = obj_cb(&oid, path->buf, data);
1779
0
        if (r)
1780
0
          break;
1781
0
      }
1782
0
      continue;
1783
0
    }
1784
1785
0
    if (cruft_cb) {
1786
0
      r = cruft_cb(de->d_name, path->buf, data);
1787
0
      if (r)
1788
0
        break;
1789
0
    }
1790
0
  }
1791
0
  closedir(dir);
1792
1793
0
  strbuf_setlen(path, baselen - 1);
1794
0
  if (!r && subdir_cb)
1795
0
    r = subdir_cb(subdir_nr, path->buf, data);
1796
1797
0
  strbuf_setlen(path, origlen);
1798
1799
0
  return r;
1800
0
}
1801
1802
int for_each_loose_file_in_source(struct odb_source *source,
1803
          each_loose_object_fn obj_cb,
1804
          each_loose_cruft_fn cruft_cb,
1805
          each_loose_subdir_fn subdir_cb,
1806
          void *data)
1807
0
{
1808
0
  struct strbuf buf = STRBUF_INIT;
1809
0
  int r;
1810
1811
0
  strbuf_addstr(&buf, source->path);
1812
0
  for (int i = 0; i < 256; i++) {
1813
0
    r = for_each_file_in_obj_subdir(i, &buf, source->odb->repo->hash_algo,
1814
0
            obj_cb, cruft_cb, subdir_cb, data);
1815
0
    if (r)
1816
0
      break;
1817
0
  }
1818
1819
0
  strbuf_release(&buf);
1820
0
  return r;
1821
0
}
1822
1823
struct for_each_object_wrapper_data {
1824
  struct odb_source *source;
1825
  const struct object_info *request;
1826
  odb_for_each_object_cb cb;
1827
  void *cb_data;
1828
};
1829
1830
static int for_each_object_wrapper_cb(const struct object_id *oid,
1831
              const char *path,
1832
              void *cb_data)
1833
0
{
1834
0
  struct for_each_object_wrapper_data *data = cb_data;
1835
1836
0
  if (data->request) {
1837
0
    struct object_info oi = *data->request;
1838
1839
0
    if (read_object_info_from_path(data->source, path, oid, &oi, 0) < 0)
1840
0
      return -1;
1841
1842
0
    return data->cb(oid, &oi, data->cb_data);
1843
0
  } else {
1844
0
    return data->cb(oid, NULL, data->cb_data);
1845
0
  }
1846
0
}
1847
1848
int odb_source_loose_for_each_object(struct odb_source *source,
1849
             const struct object_info *request,
1850
             odb_for_each_object_cb cb,
1851
             void *cb_data,
1852
             unsigned flags)
1853
0
{
1854
0
  struct for_each_object_wrapper_data data = {
1855
0
    .source = source,
1856
0
    .request = request,
1857
0
    .cb = cb,
1858
0
    .cb_data = cb_data,
1859
0
  };
1860
1861
  /* There are no loose promisor objects, so we can return immediately. */
1862
0
  if ((flags & ODB_FOR_EACH_OBJECT_PROMISOR_ONLY))
1863
0
    return 0;
1864
0
  if ((flags & ODB_FOR_EACH_OBJECT_LOCAL_ONLY) && !source->local)
1865
0
    return 0;
1866
1867
0
  return for_each_loose_file_in_source(source, for_each_object_wrapper_cb,
1868
0
               NULL, NULL, &data);
1869
0
}
1870
1871
static int count_loose_object(const struct object_id *oid UNUSED,
1872
            struct object_info *oi UNUSED,
1873
            void *payload)
1874
0
{
1875
0
  unsigned long *count = payload;
1876
0
  (*count)++;
1877
0
  return 0;
1878
0
}
1879
1880
int odb_source_loose_count_objects(struct odb_source *source,
1881
           enum odb_count_objects_flags flags,
1882
           unsigned long *out)
1883
0
{
1884
0
  const unsigned hexsz = source->odb->repo->hash_algo->hexsz - 2;
1885
0
  char *path = NULL;
1886
0
  DIR *dir = NULL;
1887
0
  int ret;
1888
1889
0
  if (flags & ODB_COUNT_OBJECTS_APPROXIMATE) {
1890
0
    unsigned long count = 0;
1891
0
    struct dirent *ent;
1892
1893
0
    path = xstrfmt("%s/17", source->path);
1894
1895
0
    dir = opendir(path);
1896
0
    if (!dir) {
1897
0
      if (errno == ENOENT) {
1898
0
        *out = 0;
1899
0
        ret = 0;
1900
0
        goto out;
1901
0
      }
1902
1903
0
      ret = error_errno("cannot open object shard '%s'", path);
1904
0
      goto out;
1905
0
    }
1906
1907
0
    while ((ent = readdir(dir)) != NULL) {
1908
0
      if (strspn(ent->d_name, "0123456789abcdef") != hexsz ||
1909
0
          ent->d_name[hexsz] != '\0')
1910
0
        continue;
1911
0
      count++;
1912
0
    }
1913
1914
0
    *out = count * 256;
1915
0
    ret = 0;
1916
0
  } else {
1917
0
    *out = 0;
1918
0
    ret = odb_source_loose_for_each_object(source, NULL, count_loose_object,
1919
0
                   out, 0);
1920
0
  }
1921
1922
0
out:
1923
0
  if (dir)
1924
0
    closedir(dir);
1925
0
  free(path);
1926
0
  return ret;
1927
0
}
1928
1929
static int append_loose_object(const struct object_id *oid,
1930
             const char *path UNUSED,
1931
             void *data)
1932
0
{
1933
0
  oidtree_insert(data, oid);
1934
0
  return 0;
1935
0
}
1936
1937
struct oidtree *odb_source_loose_cache(struct odb_source *source,
1938
               const struct object_id *oid)
1939
0
{
1940
0
  struct odb_source_files *files = odb_source_files_downcast(source);
1941
0
  int subdir_nr = oid->hash[0];
1942
0
  struct strbuf buf = STRBUF_INIT;
1943
0
  size_t word_bits = bitsizeof(files->loose->subdir_seen[0]);
1944
0
  size_t word_index = subdir_nr / word_bits;
1945
0
  size_t mask = (size_t)1u << (subdir_nr % word_bits);
1946
0
  uint32_t *bitmap;
1947
1948
0
  if (subdir_nr < 0 ||
1949
0
      (size_t) subdir_nr >= bitsizeof(files->loose->subdir_seen))
1950
0
    BUG("subdir_nr out of range");
1951
1952
0
  bitmap = &files->loose->subdir_seen[word_index];
1953
0
  if (*bitmap & mask)
1954
0
    return files->loose->cache;
1955
0
  if (!files->loose->cache) {
1956
0
    ALLOC_ARRAY(files->loose->cache, 1);
1957
0
    oidtree_init(files->loose->cache);
1958
0
  }
1959
0
  strbuf_addstr(&buf, source->path);
1960
0
  for_each_file_in_obj_subdir(subdir_nr, &buf,
1961
0
            source->odb->repo->hash_algo,
1962
0
            append_loose_object,
1963
0
            NULL, NULL,
1964
0
            files->loose->cache);
1965
0
  *bitmap |= mask;
1966
0
  strbuf_release(&buf);
1967
0
  return files->loose->cache;
1968
0
}
1969
1970
static void odb_source_loose_clear_cache(struct odb_source_loose *loose)
1971
0
{
1972
0
  oidtree_clear(loose->cache);
1973
0
  FREE_AND_NULL(loose->cache);
1974
0
  memset(&loose->subdir_seen, 0,
1975
0
         sizeof(loose->subdir_seen));
1976
0
}
1977
1978
void odb_source_loose_reprepare(struct odb_source *source)
1979
0
{
1980
0
  struct odb_source_files *files = odb_source_files_downcast(source);
1981
0
  odb_source_loose_clear_cache(files->loose);
1982
0
}
1983
1984
static int check_stream_oid(git_zstream *stream,
1985
          const char *hdr,
1986
          unsigned long size,
1987
          const char *path,
1988
          const struct object_id *expected_oid,
1989
          const struct git_hash_algo *algop)
1990
0
{
1991
0
  struct git_hash_ctx c;
1992
0
  struct object_id real_oid;
1993
0
  unsigned char buf[4096];
1994
0
  unsigned long total_read;
1995
0
  int status = Z_OK;
1996
1997
0
  algop->init_fn(&c);
1998
0
  git_hash_update(&c, hdr, stream->total_out);
1999
2000
  /*
2001
   * We already read some bytes into hdr, but the ones up to the NUL
2002
   * do not count against the object's content size.
2003
   */
2004
0
  total_read = stream->total_out - strlen(hdr) - 1;
2005
2006
  /*
2007
   * This size comparison must be "<=" to read the final zlib packets;
2008
   * see the comment in unpack_loose_rest for details.
2009
   */
2010
0
  while (total_read <= size &&
2011
0
         (status == Z_OK ||
2012
0
    (status == Z_BUF_ERROR && !stream->avail_out))) {
2013
0
    stream->next_out = buf;
2014
0
    stream->avail_out = sizeof(buf);
2015
0
    if (size - total_read < stream->avail_out)
2016
0
      stream->avail_out = size - total_read;
2017
0
    status = git_inflate(stream, Z_FINISH);
2018
0
    git_hash_update(&c, buf, stream->next_out - buf);
2019
0
    total_read += stream->next_out - buf;
2020
0
  }
2021
2022
0
  if (status != Z_STREAM_END) {
2023
0
    error(_("corrupt loose object '%s'"), oid_to_hex(expected_oid));
2024
0
    return -1;
2025
0
  }
2026
0
  if (stream->avail_in) {
2027
0
    error(_("garbage at end of loose object '%s'"),
2028
0
          oid_to_hex(expected_oid));
2029
0
    return -1;
2030
0
  }
2031
2032
0
  git_hash_final_oid(&real_oid, &c);
2033
0
  if (!oideq(expected_oid, &real_oid)) {
2034
0
    error(_("hash mismatch for %s (expected %s)"), path,
2035
0
          oid_to_hex(expected_oid));
2036
0
    return -1;
2037
0
  }
2038
2039
0
  return 0;
2040
0
}
2041
2042
int read_loose_object(struct repository *repo,
2043
          const char *path,
2044
          const struct object_id *expected_oid,
2045
          struct object_id *real_oid,
2046
          void **contents,
2047
          struct object_info *oi)
2048
0
{
2049
0
  int ret = -1;
2050
0
  int fd;
2051
0
  void *map = NULL;
2052
0
  unsigned long mapsize;
2053
0
  git_zstream stream;
2054
0
  char hdr[MAX_HEADER_LEN];
2055
0
  unsigned long *size = oi->sizep;
2056
2057
0
  fd = git_open(path);
2058
0
  if (fd >= 0)
2059
0
    map = map_fd(fd, path, &mapsize);
2060
0
  if (!map) {
2061
0
    error_errno(_("unable to mmap %s"), path);
2062
0
    goto out;
2063
0
  }
2064
2065
0
  if (unpack_loose_header(&stream, map, mapsize, hdr, sizeof(hdr)) != ULHR_OK) {
2066
0
    error(_("unable to unpack header of %s"), path);
2067
0
    goto out_inflate;
2068
0
  }
2069
2070
0
  if (parse_loose_header(hdr, oi) < 0) {
2071
0
    error(_("unable to parse header of %s"), path);
2072
0
    goto out_inflate;
2073
0
  }
2074
2075
0
  if (*oi->typep < 0) {
2076
0
    error(_("unable to parse type from header '%s' of %s"),
2077
0
          hdr, path);
2078
0
    goto out_inflate;
2079
0
  }
2080
2081
0
  if (*oi->typep == OBJ_BLOB &&
2082
0
      *size > repo_settings_get_big_file_threshold(repo)) {
2083
0
    if (check_stream_oid(&stream, hdr, *size, path, expected_oid,
2084
0
             repo->hash_algo) < 0)
2085
0
      goto out_inflate;
2086
0
  } else {
2087
0
    *contents = unpack_loose_rest(&stream, hdr, *size, expected_oid);
2088
0
    if (!*contents) {
2089
0
      error(_("unable to unpack contents of %s"), path);
2090
0
      goto out_inflate;
2091
0
    }
2092
0
    hash_object_file(repo->hash_algo,
2093
0
         *contents, *size,
2094
0
         *oi->typep, real_oid);
2095
0
    if (!oideq(expected_oid, real_oid))
2096
0
      goto out_inflate;
2097
0
  }
2098
2099
0
  ret = 0; /* everything checks out */
2100
2101
0
out_inflate:
2102
0
  git_inflate_end(&stream);
2103
0
out:
2104
0
  if (map)
2105
0
    munmap(map, mapsize);
2106
0
  return ret;
2107
0
}
2108
2109
static void odb_transaction_files_commit(struct odb_transaction *base)
2110
0
{
2111
0
  struct odb_transaction_files *transaction =
2112
0
    container_of(base, struct odb_transaction_files, base);
2113
2114
0
  flush_loose_object_transaction(transaction);
2115
0
  flush_packfile_transaction(transaction);
2116
0
}
2117
2118
struct odb_transaction *odb_transaction_files_begin(struct odb_source *source)
2119
0
{
2120
0
  struct odb_transaction_files *transaction;
2121
0
  struct object_database *odb = source->odb;
2122
2123
0
  if (odb->transaction)
2124
0
    return NULL;
2125
2126
0
  transaction = xcalloc(1, sizeof(*transaction));
2127
0
  transaction->base.source = source;
2128
0
  transaction->base.commit = odb_transaction_files_commit;
2129
2130
0
  return &transaction->base;
2131
0
}
2132
2133
struct odb_source_loose *odb_source_loose_new(struct odb_source *source)
2134
0
{
2135
0
  struct odb_source_loose *loose;
2136
0
  CALLOC_ARRAY(loose, 1);
2137
0
  loose->source = source;
2138
0
  return loose;
2139
0
}
2140
2141
void odb_source_loose_free(struct odb_source_loose *loose)
2142
0
{
2143
0
  if (!loose)
2144
0
    return;
2145
0
  odb_source_loose_clear_cache(loose);
2146
0
  loose_object_map_clear(&loose->map);
2147
0
  free(loose);
2148
0
}
2149
2150
struct odb_loose_read_stream {
2151
  struct odb_read_stream base;
2152
  git_zstream z;
2153
  enum {
2154
    ODB_LOOSE_READ_STREAM_INUSE,
2155
    ODB_LOOSE_READ_STREAM_DONE,
2156
    ODB_LOOSE_READ_STREAM_ERROR,
2157
  } z_state;
2158
  void *mapped;
2159
  unsigned long mapsize;
2160
  char hdr[32];
2161
  int hdr_avail;
2162
  int hdr_used;
2163
};
2164
2165
static ssize_t read_istream_loose(struct odb_read_stream *_st, char *buf, size_t sz)
2166
0
{
2167
0
  struct odb_loose_read_stream *st =
2168
0
    container_of(_st, struct odb_loose_read_stream, base);
2169
0
  size_t total_read = 0;
2170
2171
0
  switch (st->z_state) {
2172
0
  case ODB_LOOSE_READ_STREAM_DONE:
2173
0
    return 0;
2174
0
  case ODB_LOOSE_READ_STREAM_ERROR:
2175
0
    return -1;
2176
0
  default:
2177
0
    break;
2178
0
  }
2179
2180
0
  if (st->hdr_used < st->hdr_avail) {
2181
0
    size_t to_copy = st->hdr_avail - st->hdr_used;
2182
0
    if (sz < to_copy)
2183
0
      to_copy = sz;
2184
0
    memcpy(buf, st->hdr + st->hdr_used, to_copy);
2185
0
    st->hdr_used += to_copy;
2186
0
    total_read += to_copy;
2187
0
  }
2188
2189
0
  while (total_read < sz) {
2190
0
    int status;
2191
2192
0
    st->z.next_out = (unsigned char *)buf + total_read;
2193
0
    st->z.avail_out = sz - total_read;
2194
0
    status = git_inflate(&st->z, Z_FINISH);
2195
2196
0
    total_read = st->z.next_out - (unsigned char *)buf;
2197
2198
0
    if (status == Z_STREAM_END) {
2199
0
      git_inflate_end(&st->z);
2200
0
      st->z_state = ODB_LOOSE_READ_STREAM_DONE;
2201
0
      break;
2202
0
    }
2203
0
    if (status != Z_OK && (status != Z_BUF_ERROR || total_read < sz)) {
2204
0
      git_inflate_end(&st->z);
2205
0
      st->z_state = ODB_LOOSE_READ_STREAM_ERROR;
2206
0
      return -1;
2207
0
    }
2208
0
  }
2209
0
  return total_read;
2210
0
}
2211
2212
static int close_istream_loose(struct odb_read_stream *_st)
2213
0
{
2214
0
  struct odb_loose_read_stream *st =
2215
0
    container_of(_st, struct odb_loose_read_stream, base);
2216
2217
0
  if (st->z_state == ODB_LOOSE_READ_STREAM_INUSE)
2218
0
    git_inflate_end(&st->z);
2219
0
  munmap(st->mapped, st->mapsize);
2220
0
  return 0;
2221
0
}
2222
2223
int odb_source_loose_read_object_stream(struct odb_read_stream **out,
2224
          struct odb_source *source,
2225
          const struct object_id *oid)
2226
0
{
2227
0
  struct object_info oi = OBJECT_INFO_INIT;
2228
0
  struct odb_loose_read_stream *st;
2229
0
  unsigned long mapsize;
2230
0
  void *mapped;
2231
2232
0
  mapped = odb_source_loose_map_object(source, oid, &mapsize);
2233
0
  if (!mapped)
2234
0
    return -1;
2235
2236
  /*
2237
   * Note: we must allocate this structure early even though we may still
2238
   * fail. This is because we need to initialize the zlib stream, and it
2239
   * is not possible to copy the stream around after the fact because it
2240
   * has self-referencing pointers.
2241
   */
2242
0
  CALLOC_ARRAY(st, 1);
2243
2244
0
  switch (unpack_loose_header(&st->z, mapped, mapsize, st->hdr,
2245
0
            sizeof(st->hdr))) {
2246
0
  case ULHR_OK:
2247
0
    break;
2248
0
  case ULHR_BAD:
2249
0
  case ULHR_TOO_LONG:
2250
0
    goto error;
2251
0
  }
2252
2253
0
  oi.sizep = &st->base.size;
2254
0
  oi.typep = &st->base.type;
2255
2256
0
  if (parse_loose_header(st->hdr, &oi) < 0 || st->base.type < 0)
2257
0
    goto error;
2258
2259
0
  st->mapped = mapped;
2260
0
  st->mapsize = mapsize;
2261
0
  st->hdr_used = strlen(st->hdr) + 1;
2262
0
  st->hdr_avail = st->z.total_out;
2263
0
  st->z_state = ODB_LOOSE_READ_STREAM_INUSE;
2264
0
  st->base.close = close_istream_loose;
2265
0
  st->base.read = read_istream_loose;
2266
2267
0
  *out = &st->base;
2268
2269
0
  return 0;
2270
0
error:
2271
0
  git_inflate_end(&st->z);
2272
0
  munmap(mapped, mapsize);
2273
0
  free(st);
2274
0
  return -1;
2275
0
}