Coverage Report

Created: 2023-11-27 07:10

/src/libgit2/src/util/futils.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (C) the libgit2 contributors. All rights reserved.
3
 *
4
 * This file is part of libgit2, distributed under the GNU GPL v2 with
5
 * a Linking Exception. For full terms see the included COPYING file.
6
 */
7
8
#include "futils.h"
9
10
#include "runtime.h"
11
#include "strmap.h"
12
#include "hash.h"
13
#include "rand.h"
14
15
#include <ctype.h>
16
17
0
#define GIT_FILEMODE_DEFAULT 0100666
18
19
int git_futils_mkpath2file(const char *file_path, const mode_t mode)
20
0
{
21
0
  return git_futils_mkdir(
22
0
    file_path, mode,
23
0
    GIT_MKDIR_PATH | GIT_MKDIR_SKIP_LAST | GIT_MKDIR_VERIFY_DIR);
24
0
}
25
26
int git_futils_mktmp(git_str *path_out, const char *filename, mode_t mode)
27
6.01k
{
28
6.01k
  const int open_flags = O_RDWR | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC;
29
6.01k
  unsigned int tries = 32;
30
6.01k
  int fd;
31
32
6.01k
  while (tries--) {
33
6.01k
    uint64_t rand = git_rand_next();
34
35
6.01k
    git_str_sets(path_out, filename);
36
6.01k
    git_str_puts(path_out, "_git2_");
37
6.01k
    git_str_encode_hexstr(path_out, (void *)&rand, sizeof(uint64_t));
38
39
6.01k
    if (git_str_oom(path_out))
40
0
      return -1;
41
42
    /* Note that we open with O_CREAT | O_EXCL */
43
6.01k
    if ((fd = p_open(path_out->ptr, open_flags, mode)) >= 0)
44
6.01k
      return fd;
45
6.01k
  }
46
47
0
  git_error_set(GIT_ERROR_OS,
48
0
    "failed to create temporary file '%s'", path_out->ptr);
49
0
  git_str_dispose(path_out);
50
0
  return -1;
51
6.01k
}
52
53
int git_futils_creat_withpath(const char *path, const mode_t dirmode, const mode_t mode)
54
0
{
55
0
  int fd;
56
57
0
  if (git_futils_mkpath2file(path, dirmode) < 0)
58
0
    return -1;
59
60
0
  fd = p_creat(path, mode);
61
0
  if (fd < 0) {
62
0
    git_error_set(GIT_ERROR_OS, "failed to create file '%s'", path);
63
0
    return -1;
64
0
  }
65
66
0
  return fd;
67
0
}
68
69
int git_futils_creat_locked(const char *path, const mode_t mode)
70
8
{
71
8
  int fd = p_open(path, O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC,
72
8
    mode);
73
74
8
  if (fd < 0) {
75
0
    int error = errno;
76
0
    git_error_set(GIT_ERROR_OS, "failed to create locked file '%s'", path);
77
0
    switch (error) {
78
0
    case EEXIST:
79
0
      return GIT_ELOCKED;
80
0
    case ENOENT:
81
0
      return GIT_ENOTFOUND;
82
0
    default:
83
0
      return -1;
84
0
    }
85
0
  }
86
87
8
  return fd;
88
8
}
89
90
int git_futils_creat_locked_withpath(const char *path, const mode_t dirmode, const mode_t mode)
91
0
{
92
0
  if (git_futils_mkpath2file(path, dirmode) < 0)
93
0
    return -1;
94
95
0
  return git_futils_creat_locked(path, mode);
96
0
}
97
98
int git_futils_open_ro(const char *path)
99
3.11k
{
100
3.11k
  int fd = p_open(path, O_RDONLY);
101
3.11k
  if (fd < 0)
102
3.10k
    return git_fs_path_set_error(errno, path, "open");
103
10
  return fd;
104
3.11k
}
105
106
int git_futils_truncate(const char *path, int mode)
107
0
{
108
0
  int fd = p_open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, mode);
109
0
  if (fd < 0)
110
0
    return git_fs_path_set_error(errno, path, "open");
111
112
0
  close(fd);
113
0
  return 0;
114
0
}
115
116
int git_futils_filesize(uint64_t *out, git_file fd)
117
0
{
118
0
  struct stat sb;
119
120
0
  if (p_fstat(fd, &sb)) {
121
0
    git_error_set(GIT_ERROR_OS, "failed to stat file descriptor");
122
0
    return -1;
123
0
  }
124
125
0
  if (sb.st_size < 0) {
126
0
    git_error_set(GIT_ERROR_INVALID, "invalid file size");
127
0
    return -1;
128
0
  }
129
130
0
  *out = sb.st_size;
131
0
  return 0;
132
0
}
133
134
mode_t git_futils_canonical_mode(mode_t raw_mode)
135
0
{
136
0
  if (S_ISREG(raw_mode))
137
0
    return S_IFREG | GIT_PERMS_CANONICAL(raw_mode);
138
0
  else if (S_ISLNK(raw_mode))
139
0
    return S_IFLNK;
140
0
  else if (S_ISGITLINK(raw_mode))
141
0
    return S_IFGITLINK;
142
0
  else if (S_ISDIR(raw_mode))
143
0
    return S_IFDIR;
144
0
  else
145
0
    return 0;
146
0
}
147
148
int git_futils_readbuffer_fd(git_str *buf, git_file fd, size_t len)
149
10
{
150
10
  ssize_t read_size = 0;
151
10
  size_t alloc_len;
152
153
10
  git_str_clear(buf);
154
155
10
  if (!git__is_ssizet(len)) {
156
0
    git_error_set(GIT_ERROR_INVALID, "read too large");
157
0
    return -1;
158
0
  }
159
160
10
  GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, len, 1);
161
10
  if (git_str_grow(buf, alloc_len) < 0)
162
0
    return -1;
163
164
  /* p_read loops internally to read len bytes */
165
10
  read_size = p_read(fd, buf->ptr, len);
166
167
10
  if (read_size < 0) {
168
0
    git_error_set(GIT_ERROR_OS, "failed to read descriptor");
169
0
    git_str_dispose(buf);
170
0
    return -1;
171
0
  }
172
173
10
  if ((size_t)read_size != len) {
174
0
    git_error_set(GIT_ERROR_FILESYSTEM, "could not read (expected %" PRIuZ " bytes, read %" PRIuZ ")", len, (size_t)read_size);
175
0
    git_str_dispose(buf);
176
0
    return -1;
177
0
  }
178
179
10
  buf->ptr[read_size] = '\0';
180
10
  buf->size = read_size;
181
182
10
  return 0;
183
10
}
184
185
int git_futils_readbuffer_fd_full(git_str *buf, git_file fd)
186
0
{
187
0
  static size_t blocksize = 10240;
188
0
  size_t alloc_len = 0, total_size = 0;
189
0
  ssize_t read_size = 0;
190
191
0
  git_str_clear(buf);
192
193
0
  while (true) {
194
0
    GIT_ERROR_CHECK_ALLOC_ADD(&alloc_len, alloc_len, blocksize);
195
196
0
    if (git_str_grow(buf, alloc_len) < 0)
197
0
      return -1;
198
199
    /* p_read loops internally to read blocksize bytes */
200
0
    read_size = p_read(fd, buf->ptr, blocksize);
201
202
0
    if (read_size < 0) {
203
0
      git_error_set(GIT_ERROR_OS, "failed to read descriptor");
204
0
      git_str_dispose(buf);
205
0
      return -1;
206
0
    }
207
208
0
    total_size += read_size;
209
210
0
    if ((size_t)read_size < blocksize) {
211
0
      break;
212
0
    }
213
0
  }
214
215
0
  buf->ptr[total_size] = '\0';
216
0
  buf->size = total_size;
217
218
0
  return 0;
219
0
}
220
221
int git_futils_readbuffer_updated(
222
  git_str *out,
223
  const char *path,
224
  unsigned char checksum[GIT_HASH_SHA256_SIZE],
225
  int *updated)
226
16.4k
{
227
16.4k
  int error;
228
16.4k
  git_file fd;
229
16.4k
  struct stat st;
230
16.4k
  git_str buf = GIT_STR_INIT;
231
16.4k
  unsigned char checksum_new[GIT_HASH_SHA256_SIZE];
232
233
16.4k
  GIT_ASSERT_ARG(out);
234
16.4k
  GIT_ASSERT_ARG(path && *path);
235
236
16.4k
  if (updated != NULL)
237
3.11k
    *updated = 0;
238
239
16.4k
  if (p_stat(path, &st) < 0)
240
16.4k
    return git_fs_path_set_error(errno, path, "stat");
241
242
243
10
  if (S_ISDIR(st.st_mode)) {
244
0
    git_error_set(GIT_ERROR_INVALID, "requested file is a directory");
245
0
    return GIT_ENOTFOUND;
246
0
  }
247
248
10
  if (!git__is_sizet(st.st_size+1)) {
249
0
    git_error_set(GIT_ERROR_OS, "invalid regular file stat for '%s'", path);
250
0
    return -1;
251
0
  }
252
253
10
  if ((fd = git_futils_open_ro(path)) < 0)
254
0
    return fd;
255
256
10
  if (git_futils_readbuffer_fd(&buf, fd, (size_t)st.st_size) < 0) {
257
0
    p_close(fd);
258
0
    return -1;
259
0
  }
260
261
10
  p_close(fd);
262
263
10
  if (checksum) {
264
0
    error = git_hash_buf(checksum_new, buf.ptr,
265
0
                         buf.size, GIT_HASH_ALGORITHM_SHA256);
266
267
0
    if (error < 0) {
268
0
      git_str_dispose(&buf);
269
0
      return error;
270
0
    }
271
272
    /*
273
     * If we were given a checksum, we only want to use it if it's different
274
     */
275
0
    if (!memcmp(checksum, checksum_new, GIT_HASH_SHA256_SIZE)) {
276
0
      git_str_dispose(&buf);
277
0
      if (updated)
278
0
        *updated = 0;
279
280
0
      return 0;
281
0
    }
282
283
0
    memcpy(checksum, checksum_new, GIT_HASH_SHA256_SIZE);
284
0
  }
285
286
  /*
287
   * If we're here, the file did change, or the user didn't have an old version
288
   */
289
10
  if (updated != NULL)
290
0
    *updated = 1;
291
292
10
  git_str_swap(out, &buf);
293
10
  git_str_dispose(&buf);
294
295
10
  return 0;
296
10
}
297
298
int git_futils_readbuffer(git_str *buf, const char *path)
299
13.3k
{
300
13.3k
  return git_futils_readbuffer_updated(buf, path, NULL, NULL);
301
13.3k
}
302
303
int git_futils_writebuffer(
304
  const git_str *buf, const char *path, int flags, mode_t mode)
305
0
{
306
0
  int fd, do_fsync = 0, error = 0;
307
308
0
  if (!flags)
309
0
    flags = O_CREAT | O_TRUNC | O_WRONLY;
310
311
0
  if ((flags & O_FSYNC) != 0)
312
0
    do_fsync = 1;
313
314
0
  flags &= ~O_FSYNC;
315
316
0
  if (!mode)
317
0
    mode = GIT_FILEMODE_DEFAULT;
318
319
0
  if ((fd = p_open(path, flags, mode)) < 0) {
320
0
    git_error_set(GIT_ERROR_OS, "could not open '%s' for writing", path);
321
0
    return fd;
322
0
  }
323
324
0
  if ((error = p_write(fd, git_str_cstr(buf), git_str_len(buf))) < 0) {
325
0
    git_error_set(GIT_ERROR_OS, "could not write to '%s'", path);
326
0
    (void)p_close(fd);
327
0
    return error;
328
0
  }
329
330
0
  if (do_fsync && (error = p_fsync(fd)) < 0) {
331
0
    git_error_set(GIT_ERROR_OS, "could not fsync '%s'", path);
332
0
    p_close(fd);
333
0
    return error;
334
0
  }
335
336
0
  if ((error = p_close(fd)) < 0) {
337
0
    git_error_set(GIT_ERROR_OS, "error while closing '%s'", path);
338
0
    return error;
339
0
  }
340
341
0
  if (do_fsync && (flags & O_CREAT))
342
0
    error = git_futils_fsync_parent(path);
343
344
0
  return error;
345
0
}
346
347
int git_futils_mv_withpath(const char *from, const char *to, const mode_t dirmode)
348
0
{
349
0
  if (git_futils_mkpath2file(to, dirmode) < 0)
350
0
    return -1;
351
352
0
  if (p_rename(from, to) < 0) {
353
0
    git_error_set(GIT_ERROR_OS, "failed to rename '%s' to '%s'", from, to);
354
0
    return -1;
355
0
  }
356
357
0
  return 0;
358
0
}
359
360
int git_futils_mmap_ro(git_map *out, git_file fd, off64_t begin, size_t len)
361
11.5k
{
362
11.5k
  return p_mmap(out, len, GIT_PROT_READ, GIT_MAP_SHARED, fd, begin);
363
11.5k
}
364
365
int git_futils_mmap_ro_file(git_map *out, const char *path)
366
0
{
367
0
  git_file fd = git_futils_open_ro(path);
368
0
  uint64_t len;
369
0
  int result;
370
371
0
  if (fd < 0)
372
0
    return fd;
373
374
0
  if ((result = git_futils_filesize(&len, fd)) < 0)
375
0
    goto out;
376
377
0
  if (!git__is_sizet(len)) {
378
0
    git_error_set(GIT_ERROR_OS, "file `%s` too large to mmap", path);
379
0
    result = -1;
380
0
    goto out;
381
0
  }
382
383
0
  result = git_futils_mmap_ro(out, fd, 0, (size_t)len);
384
0
out:
385
0
  p_close(fd);
386
0
  return result;
387
0
}
388
389
void git_futils_mmap_free(git_map *out)
390
11.5k
{
391
11.5k
  p_munmap(out);
392
11.5k
}
393
394
GIT_INLINE(int) mkdir_validate_dir(
395
  const char *path,
396
  struct stat *st,
397
  mode_t mode,
398
  uint32_t flags,
399
  struct git_futils_mkdir_options *opts)
400
10
{
401
  /* with exclusive create, existing dir is an error */
402
10
  if ((flags & GIT_MKDIR_EXCL) != 0) {
403
0
    git_error_set(GIT_ERROR_FILESYSTEM,
404
0
      "failed to make directory '%s': directory exists", path);
405
0
    return GIT_EEXISTS;
406
0
  }
407
408
10
  if ((S_ISREG(st->st_mode) && (flags & GIT_MKDIR_REMOVE_FILES)) ||
409
10
    (S_ISLNK(st->st_mode) && (flags & GIT_MKDIR_REMOVE_SYMLINKS))) {
410
0
    if (p_unlink(path) < 0) {
411
0
      git_error_set(GIT_ERROR_OS, "failed to remove %s '%s'",
412
0
        S_ISLNK(st->st_mode) ? "symlink" : "file", path);
413
0
      return GIT_EEXISTS;
414
0
    }
415
416
0
    opts->perfdata.mkdir_calls++;
417
418
0
    if (p_mkdir(path, mode) < 0) {
419
0
      git_error_set(GIT_ERROR_OS, "failed to make directory '%s'", path);
420
0
      return GIT_EEXISTS;
421
0
    }
422
0
  }
423
424
10
  else if (S_ISLNK(st->st_mode)) {
425
    /* Re-stat the target, make sure it's a directory */
426
0
    opts->perfdata.stat_calls++;
427
428
0
    if (p_stat(path, st) < 0) {
429
0
      git_error_set(GIT_ERROR_OS, "failed to make directory '%s'", path);
430
0
      return GIT_EEXISTS;
431
0
    }
432
0
  }
433
434
10
  else if (!S_ISDIR(st->st_mode)) {
435
0
    git_error_set(GIT_ERROR_FILESYSTEM,
436
0
      "failed to make directory '%s': directory exists", path);
437
0
    return GIT_EEXISTS;
438
0
  }
439
440
10
  return 0;
441
10
}
442
443
GIT_INLINE(int) mkdir_validate_mode(
444
  const char *path,
445
  struct stat *st,
446
  bool terminal_path,
447
  mode_t mode,
448
  uint32_t flags,
449
  struct git_futils_mkdir_options *opts)
450
26
{
451
26
  if (((terminal_path && (flags & GIT_MKDIR_CHMOD) != 0) ||
452
26
    (flags & GIT_MKDIR_CHMOD_PATH) != 0) && st->st_mode != mode) {
453
454
0
    opts->perfdata.chmod_calls++;
455
456
0
    if (p_chmod(path, mode) < 0) {
457
0
      git_error_set(GIT_ERROR_OS, "failed to set permissions on '%s'", path);
458
0
      return -1;
459
0
    }
460
0
  }
461
462
26
  return 0;
463
26
}
464
465
GIT_INLINE(int) mkdir_canonicalize(
466
  git_str *path,
467
  uint32_t flags)
468
18
{
469
18
  ssize_t root_len;
470
471
18
  if (path->size == 0) {
472
0
    git_error_set(GIT_ERROR_OS, "attempt to create empty path");
473
0
    return -1;
474
0
  }
475
476
  /* Trim trailing slashes (except the root) */
477
18
  if ((root_len = git_fs_path_root(path->ptr)) < 0)
478
0
    root_len = 0;
479
18
  else
480
18
    root_len++;
481
482
36
  while (path->size > (size_t)root_len && path->ptr[path->size - 1] == '/')
483
18
    path->ptr[--path->size] = '\0';
484
485
  /* if we are not supposed to made the last element, truncate it */
486
18
  if ((flags & GIT_MKDIR_SKIP_LAST2) != 0) {
487
0
    git_fs_path_dirname_r(path, path->ptr);
488
0
    flags |= GIT_MKDIR_SKIP_LAST;
489
0
  }
490
18
  if ((flags & GIT_MKDIR_SKIP_LAST) != 0) {
491
4
    git_fs_path_dirname_r(path, path->ptr);
492
4
  }
493
494
  /* We were either given the root path (or trimmed it to
495
  * the root), we don't have anything to do.
496
  */
497
18
  if (path->size <= (size_t)root_len)
498
0
    git_str_clear(path);
499
500
18
  return 0;
501
18
}
502
503
int git_futils_mkdir(
504
  const char *path,
505
  mode_t mode,
506
  uint32_t flags)
507
6
{
508
6
  git_str make_path = GIT_STR_INIT, parent_path = GIT_STR_INIT;
509
6
  const char *relative;
510
6
  struct git_futils_mkdir_options opts = { 0 };
511
6
  struct stat st;
512
6
  size_t depth = 0;
513
6
  int len = 0, root_len, error;
514
515
6
  if ((error = git_str_puts(&make_path, path)) < 0 ||
516
6
    (error = mkdir_canonicalize(&make_path, flags)) < 0 ||
517
6
    (error = git_str_puts(&parent_path, make_path.ptr)) < 0 ||
518
6
    make_path.size == 0)
519
0
    goto done;
520
521
6
  root_len = git_fs_path_root(make_path.ptr);
522
523
  /* find the first parent directory that exists.  this will be used
524
   * as the base to dirname_relative.
525
   */
526
6
  for (relative = make_path.ptr; parent_path.size; ) {
527
6
    error = p_lstat(parent_path.ptr, &st);
528
529
6
    if (error == 0) {
530
6
      break;
531
6
    } else if (errno != ENOENT) {
532
0
      git_error_set(GIT_ERROR_OS, "failed to stat '%s'", parent_path.ptr);
533
0
      error = -1;
534
0
      goto done;
535
0
    }
536
537
0
    depth++;
538
539
    /* examine the parent of the current path */
540
0
    if ((len = git_fs_path_dirname_r(&parent_path, parent_path.ptr)) < 0) {
541
0
      error = len;
542
0
      goto done;
543
0
    }
544
545
0
    GIT_ASSERT(len);
546
547
    /*
548
     * We've walked all the given path's parents and it's either relative
549
     * (the parent is simply '.') or rooted (the length is less than or
550
     * equal to length of the root path).  The path may be less than the
551
     * root path length on Windows, where `C:` == `C:/`.
552
     */
553
0
    if ((len == 1 && parent_path.ptr[0] == '.') ||
554
0
        (len == 1 && parent_path.ptr[0] == '/') ||
555
0
        len <= root_len) {
556
0
      relative = make_path.ptr;
557
0
      break;
558
0
    }
559
560
0
    relative = make_path.ptr + len + 1;
561
562
    /* not recursive? just make this directory relative to its parent. */
563
0
    if ((flags & GIT_MKDIR_PATH) == 0)
564
0
      break;
565
0
  }
566
567
  /* we found an item at the location we're trying to create,
568
   * validate it.
569
   */
570
6
  if (depth == 0) {
571
6
    error = mkdir_validate_dir(make_path.ptr, &st, mode, flags, &opts);
572
573
6
    if (!error)
574
6
      error = mkdir_validate_mode(
575
6
        make_path.ptr, &st, true, mode, flags, &opts);
576
577
6
    goto done;
578
6
  }
579
580
  /* we already took `SKIP_LAST` and `SKIP_LAST2` into account when
581
   * canonicalizing `make_path`.
582
   */
583
0
  flags &= ~(GIT_MKDIR_SKIP_LAST2 | GIT_MKDIR_SKIP_LAST);
584
585
0
  error = git_futils_mkdir_relative(relative,
586
0
    parent_path.size ? parent_path.ptr : NULL, mode, flags, &opts);
587
588
6
done:
589
6
  git_str_dispose(&make_path);
590
6
  git_str_dispose(&parent_path);
591
6
  return error;
592
0
}
593
594
int git_futils_mkdir_r(const char *path, const mode_t mode)
595
0
{
596
0
  return git_futils_mkdir(path, mode, GIT_MKDIR_PATH);
597
0
}
598
599
int git_futils_mkdir_relative(
600
  const char *relative_path,
601
  const char *base,
602
  mode_t mode,
603
  uint32_t flags,
604
  struct git_futils_mkdir_options *opts)
605
12
{
606
12
  git_str make_path = GIT_STR_INIT;
607
12
  ssize_t root = 0, min_root_len;
608
12
  char lastch = '/', *tail;
609
12
  struct stat st;
610
12
  struct git_futils_mkdir_options empty_opts = {0};
611
12
  int error;
612
613
12
  if (!opts)
614
12
    opts = &empty_opts;
615
616
  /* build path and find "root" where we should start calling mkdir */
617
12
  if (git_fs_path_join_unrooted(&make_path, relative_path, base, &root) < 0)
618
0
    return -1;
619
620
12
  if ((error = mkdir_canonicalize(&make_path, flags)) < 0 ||
621
12
    make_path.size == 0)
622
0
    goto done;
623
624
  /* if we are not supposed to make the whole path, reset root */
625
12
  if ((flags & GIT_MKDIR_PATH) == 0)
626
0
    root = git_str_rfind(&make_path, '/');
627
628
  /* advance root past drive name or network mount prefix */
629
12
  min_root_len = git_fs_path_root(make_path.ptr);
630
12
  if (root < min_root_len)
631
0
    root = min_root_len;
632
12
  while (root >= 0 && make_path.ptr[root] == '/')
633
0
    ++root;
634
635
  /* clip root to make_path length */
636
12
  if (root > (ssize_t)make_path.size)
637
0
    root = (ssize_t)make_path.size; /* i.e. NUL byte of string */
638
12
  if (root < 0)
639
0
    root = 0;
640
641
  /* walk down tail of path making each directory */
642
32
  for (tail = &make_path.ptr[root]; *tail; *tail = lastch) {
643
20
    bool mkdir_attempted = false;
644
645
    /* advance tail to include next path component */
646
28
    while (*tail == '/')
647
8
      tail++;
648
116
    while (*tail && *tail != '/')
649
96
      tail++;
650
651
    /* truncate path at next component */
652
20
    lastch = *tail;
653
20
    *tail = '\0';
654
20
    st.st_mode = 0;
655
656
20
    if (opts->dir_map && git_strmap_exists(opts->dir_map, make_path.ptr))
657
0
      continue;
658
659
    /* See what's going on with this path component */
660
20
    opts->perfdata.stat_calls++;
661
662
20
retry_lstat:
663
20
    if (p_lstat(make_path.ptr, &st) < 0) {
664
16
      if (mkdir_attempted || errno != ENOENT) {
665
0
        git_error_set(GIT_ERROR_OS, "cannot access component in path '%s'", make_path.ptr);
666
0
        error = -1;
667
0
        goto done;
668
0
      }
669
670
16
      git_error_clear();
671
16
      opts->perfdata.mkdir_calls++;
672
16
      mkdir_attempted = true;
673
16
      if (p_mkdir(make_path.ptr, mode) < 0) {
674
0
        if (errno == EEXIST)
675
0
          goto retry_lstat;
676
0
        git_error_set(GIT_ERROR_OS, "failed to make directory '%s'", make_path.ptr);
677
0
        error = -1;
678
0
        goto done;
679
0
      }
680
16
    } else {
681
4
      if ((error = mkdir_validate_dir(
682
4
        make_path.ptr, &st, mode, flags, opts)) < 0)
683
0
        goto done;
684
4
    }
685
686
    /* chmod if requested and necessary */
687
20
    if ((error = mkdir_validate_mode(
688
20
      make_path.ptr, &st, (lastch == '\0'), mode, flags, opts)) < 0)
689
0
      goto done;
690
691
20
    if (opts->dir_map && opts->pool) {
692
0
      char *cache_path;
693
0
      size_t alloc_size;
694
695
0
      GIT_ERROR_CHECK_ALLOC_ADD(&alloc_size, make_path.size, 1);
696
0
      cache_path = git_pool_malloc(opts->pool, alloc_size);
697
0
      GIT_ERROR_CHECK_ALLOC(cache_path);
698
699
0
      memcpy(cache_path, make_path.ptr, make_path.size + 1);
700
701
0
      if ((error = git_strmap_set(opts->dir_map, cache_path, cache_path)) < 0)
702
0
        goto done;
703
0
    }
704
20
  }
705
706
12
  error = 0;
707
708
  /* check that full path really is a directory if requested & needed */
709
12
  if ((flags & GIT_MKDIR_VERIFY_DIR) != 0 &&
710
12
    lastch != '\0') {
711
0
    opts->perfdata.stat_calls++;
712
713
0
    if (p_stat(make_path.ptr, &st) < 0 || !S_ISDIR(st.st_mode)) {
714
0
      git_error_set(GIT_ERROR_OS, "path is not a directory '%s'",
715
0
        make_path.ptr);
716
0
      error = GIT_ENOTFOUND;
717
0
    }
718
0
  }
719
720
12
done:
721
12
  git_str_dispose(&make_path);
722
12
  return error;
723
12
}
724
725
typedef struct {
726
  const char *base;
727
  size_t baselen;
728
  uint32_t flags;
729
  int depth;
730
} futils__rmdir_data;
731
732
0
#define FUTILS_MAX_DEPTH 100
733
734
static int futils__error_cannot_rmdir(const char *path, const char *filemsg)
735
0
{
736
0
  if (filemsg)
737
0
    git_error_set(GIT_ERROR_OS, "could not remove directory '%s': %s",
738
0
           path, filemsg);
739
0
  else
740
0
    git_error_set(GIT_ERROR_OS, "could not remove directory '%s'", path);
741
742
0
  return -1;
743
0
}
744
745
static int futils__rm_first_parent(git_str *path, const char *ceiling)
746
0
{
747
0
  int error = GIT_ENOTFOUND;
748
0
  struct stat st;
749
750
0
  while (error == GIT_ENOTFOUND) {
751
0
    git_str_rtruncate_at_char(path, '/');
752
753
0
    if (!path->size || git__prefixcmp(path->ptr, ceiling) != 0)
754
0
      error = 0;
755
0
    else if (p_lstat_posixly(path->ptr, &st) == 0) {
756
0
      if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))
757
0
        error = p_unlink(path->ptr);
758
0
      else if (!S_ISDIR(st.st_mode))
759
0
        error = -1; /* fail to remove non-regular file */
760
0
    } else if (errno != ENOTDIR)
761
0
      error = -1;
762
0
  }
763
764
0
  if (error)
765
0
    futils__error_cannot_rmdir(path->ptr, "cannot remove parent");
766
767
0
  return error;
768
0
}
769
770
static int futils__rmdir_recurs_foreach(void *opaque, git_str *path)
771
0
{
772
0
  int error = 0;
773
0
  futils__rmdir_data *data = opaque;
774
0
  struct stat st;
775
776
0
  if (data->depth > FUTILS_MAX_DEPTH)
777
0
    error = futils__error_cannot_rmdir(
778
0
      path->ptr, "directory nesting too deep");
779
780
0
  else if ((error = p_lstat_posixly(path->ptr, &st)) < 0) {
781
0
    if (errno == ENOENT)
782
0
      error = 0;
783
0
    else if (errno == ENOTDIR) {
784
      /* asked to remove a/b/c/d/e and a/b is a normal file */
785
0
      if ((data->flags & GIT_RMDIR_REMOVE_BLOCKERS) != 0)
786
0
        error = futils__rm_first_parent(path, data->base);
787
0
      else
788
0
        futils__error_cannot_rmdir(
789
0
          path->ptr, "parent is not directory");
790
0
    }
791
0
    else
792
0
      error = git_fs_path_set_error(errno, path->ptr, "rmdir");
793
0
  }
794
795
0
  else if (S_ISDIR(st.st_mode)) {
796
0
    data->depth++;
797
798
0
    error = git_fs_path_direach(path, 0, futils__rmdir_recurs_foreach, data);
799
800
0
    data->depth--;
801
802
0
    if (error < 0)
803
0
      return error;
804
805
0
    if (data->depth == 0 && (data->flags & GIT_RMDIR_SKIP_ROOT) != 0)
806
0
      return error;
807
808
0
    if ((error = p_rmdir(path->ptr)) < 0) {
809
0
      if ((data->flags & GIT_RMDIR_SKIP_NONEMPTY) != 0 &&
810
0
        (errno == ENOTEMPTY || errno == EEXIST || errno == EBUSY))
811
0
        error = 0;
812
0
      else
813
0
        error = git_fs_path_set_error(errno, path->ptr, "rmdir");
814
0
    }
815
0
  }
816
817
0
  else if ((data->flags & GIT_RMDIR_REMOVE_FILES) != 0) {
818
0
    if (p_unlink(path->ptr) < 0)
819
0
      error = git_fs_path_set_error(errno, path->ptr, "remove");
820
0
  }
821
822
0
  else if ((data->flags & GIT_RMDIR_SKIP_NONEMPTY) == 0)
823
0
    error = futils__error_cannot_rmdir(path->ptr, "still present");
824
825
0
  return error;
826
0
}
827
828
static int futils__rmdir_empty_parent(void *opaque, const char *path)
829
0
{
830
0
  futils__rmdir_data *data = opaque;
831
0
  int error = 0;
832
833
0
  if (strlen(path) <= data->baselen)
834
0
    error = GIT_ITEROVER;
835
836
0
  else if (p_rmdir(path) < 0) {
837
0
    int en = errno;
838
839
0
    if (en == ENOENT || en == ENOTDIR) {
840
      /* do nothing */
841
0
    } else if ((data->flags & GIT_RMDIR_SKIP_NONEMPTY) == 0 &&
842
0
      en == EBUSY) {
843
0
      error = git_fs_path_set_error(errno, path, "rmdir");
844
0
    } else if (en == ENOTEMPTY || en == EEXIST || en == EBUSY) {
845
0
      error = GIT_ITEROVER;
846
0
    } else {
847
0
      error = git_fs_path_set_error(errno, path, "rmdir");
848
0
    }
849
0
  }
850
851
0
  return error;
852
0
}
853
854
int git_futils_rmdir_r(
855
  const char *path, const char *base, uint32_t flags)
856
0
{
857
0
  int error;
858
0
  git_str fullpath = GIT_STR_INIT;
859
0
  futils__rmdir_data data;
860
861
  /* build path and find "root" where we should start calling mkdir */
862
0
  if (git_fs_path_join_unrooted(&fullpath, path, base, NULL) < 0)
863
0
    return -1;
864
865
0
  memset(&data, 0, sizeof(data));
866
0
  data.base    = base ? base : "";
867
0
  data.baselen = base ? strlen(base) : 0;
868
0
  data.flags   = flags;
869
870
0
  error = futils__rmdir_recurs_foreach(&data, &fullpath);
871
872
  /* remove now-empty parents if requested */
873
0
  if (!error && (flags & GIT_RMDIR_EMPTY_PARENTS) != 0)
874
0
    error = git_fs_path_walk_up(
875
0
      &fullpath, base, futils__rmdir_empty_parent, &data);
876
877
0
  if (error == GIT_ITEROVER) {
878
0
    git_error_clear();
879
0
    error = 0;
880
0
  }
881
882
0
  git_str_dispose(&fullpath);
883
884
0
  return error;
885
0
}
886
887
int git_futils_fake_symlink(const char *target, const char *path)
888
0
{
889
0
  int retcode = GIT_ERROR;
890
0
  int fd = git_futils_creat_withpath(path, 0755, 0644);
891
0
  if (fd >= 0) {
892
0
    retcode = p_write(fd, target, strlen(target));
893
0
    p_close(fd);
894
0
  }
895
0
  return retcode;
896
0
}
897
898
static int cp_by_fd(int ifd, int ofd, bool close_fd_when_done)
899
0
{
900
0
  int error = 0;
901
0
  char buffer[GIT_BUFSIZE_FILEIO];
902
0
  ssize_t len = 0;
903
904
0
  while (!error && (len = p_read(ifd, buffer, sizeof(buffer))) > 0)
905
    /* p_write() does not have the same semantics as write().  It loops
906
     * internally and will return 0 when it has completed writing.
907
     */
908
0
    error = p_write(ofd, buffer, len);
909
910
0
  if (len < 0) {
911
0
    git_error_set(GIT_ERROR_OS, "read error while copying file");
912
0
    error = (int)len;
913
0
  }
914
915
0
  if (error < 0)
916
0
    git_error_set(GIT_ERROR_OS, "write error while copying file");
917
918
0
  if (close_fd_when_done) {
919
0
    p_close(ifd);
920
0
    p_close(ofd);
921
0
  }
922
923
0
  return error;
924
0
}
925
926
int git_futils_cp(const char *from, const char *to, mode_t filemode)
927
0
{
928
0
  int ifd, ofd;
929
930
0
  if ((ifd = git_futils_open_ro(from)) < 0)
931
0
    return ifd;
932
933
0
  if ((ofd = p_open(to, O_WRONLY | O_CREAT | O_EXCL, filemode)) < 0) {
934
0
    p_close(ifd);
935
0
    return git_fs_path_set_error(errno, to, "open for writing");
936
0
  }
937
938
0
  return cp_by_fd(ifd, ofd, true);
939
0
}
940
941
int git_futils_touch(const char *path, time_t *when)
942
0
{
943
0
  struct p_timeval times[2];
944
0
  int ret;
945
946
0
  times[0].tv_sec =  times[1].tv_sec  = when ? *when : time(NULL);
947
0
  times[0].tv_usec = times[1].tv_usec = 0;
948
949
0
  ret = p_utimes(path, times);
950
951
0
  return (ret < 0) ? git_fs_path_set_error(errno, path, "touch") : 0;
952
0
}
953
954
static int cp_link(const char *from, const char *to, size_t link_size)
955
0
{
956
0
  int error = 0;
957
0
  ssize_t read_len;
958
0
  char *link_data;
959
0
  size_t alloc_size;
960
961
0
  GIT_ERROR_CHECK_ALLOC_ADD(&alloc_size, link_size, 1);
962
0
  link_data = git__malloc(alloc_size);
963
0
  GIT_ERROR_CHECK_ALLOC(link_data);
964
965
0
  read_len = p_readlink(from, link_data, link_size);
966
0
  if (read_len != (ssize_t)link_size) {
967
0
    git_error_set(GIT_ERROR_OS, "failed to read symlink data for '%s'", from);
968
0
    error = -1;
969
0
  }
970
0
  else {
971
0
    link_data[read_len] = '\0';
972
973
0
    if (p_symlink(link_data, to) < 0) {
974
0
      git_error_set(GIT_ERROR_OS, "could not symlink '%s' as '%s'",
975
0
        link_data, to);
976
0
      error = -1;
977
0
    }
978
0
  }
979
980
0
  git__free(link_data);
981
0
  return error;
982
0
}
983
984
typedef struct {
985
  const char *to_root;
986
  git_str to;
987
  ssize_t from_prefix;
988
  uint32_t flags;
989
  uint32_t mkdir_flags;
990
  mode_t dirmode;
991
} cp_r_info;
992
993
0
#define GIT_CPDIR__MKDIR_DONE_FOR_TO_ROOT (1u << 10)
994
995
static int _cp_r_mkdir(cp_r_info *info, git_str *from)
996
0
{
997
0
  int error = 0;
998
999
  /* create root directory the first time we need to create a directory */
1000
0
  if ((info->flags & GIT_CPDIR__MKDIR_DONE_FOR_TO_ROOT) == 0) {
1001
0
    error = git_futils_mkdir(
1002
0
      info->to_root, info->dirmode,
1003
0
      (info->flags & GIT_CPDIR_CHMOD_DIRS) ? GIT_MKDIR_CHMOD : 0);
1004
1005
0
    info->flags |= GIT_CPDIR__MKDIR_DONE_FOR_TO_ROOT;
1006
0
  }
1007
1008
  /* create directory with root as base to prevent excess chmods */
1009
0
  if (!error)
1010
0
    error = git_futils_mkdir_relative(
1011
0
      from->ptr + info->from_prefix, info->to_root,
1012
0
      info->dirmode, info->mkdir_flags, NULL);
1013
1014
0
  return error;
1015
0
}
1016
1017
static int _cp_r_callback(void *ref, git_str *from)
1018
0
{
1019
0
  int error = 0;
1020
0
  cp_r_info *info = ref;
1021
0
  struct stat from_st, to_st;
1022
0
  bool exists = false;
1023
1024
0
  if ((info->flags & GIT_CPDIR_COPY_DOTFILES) == 0 &&
1025
0
    from->ptr[git_fs_path_basename_offset(from)] == '.')
1026
0
    return 0;
1027
1028
0
  if ((error = git_str_joinpath(
1029
0
      &info->to, info->to_root, from->ptr + info->from_prefix)) < 0)
1030
0
    return error;
1031
1032
0
  if (!(error = git_fs_path_lstat(info->to.ptr, &to_st)))
1033
0
    exists = true;
1034
0
  else if (error != GIT_ENOTFOUND)
1035
0
    return error;
1036
0
  else {
1037
0
    git_error_clear();
1038
0
    error = 0;
1039
0
  }
1040
1041
0
  if ((error = git_fs_path_lstat(from->ptr, &from_st)) < 0)
1042
0
    return error;
1043
1044
0
  if (S_ISDIR(from_st.st_mode)) {
1045
0
    mode_t oldmode = info->dirmode;
1046
1047
    /* if we are not chmod'ing, then overwrite dirmode */
1048
0
    if ((info->flags & GIT_CPDIR_CHMOD_DIRS) == 0)
1049
0
      info->dirmode = from_st.st_mode;
1050
1051
    /* make directory now if CREATE_EMPTY_DIRS is requested and needed */
1052
0
    if (!exists && (info->flags & GIT_CPDIR_CREATE_EMPTY_DIRS) != 0)
1053
0
      error = _cp_r_mkdir(info, from);
1054
1055
    /* recurse onto target directory */
1056
0
    if (!error && (!exists || S_ISDIR(to_st.st_mode)))
1057
0
      error = git_fs_path_direach(from, 0, _cp_r_callback, info);
1058
1059
0
    if (oldmode != 0)
1060
0
      info->dirmode = oldmode;
1061
1062
0
    return error;
1063
0
  }
1064
1065
0
  if (exists) {
1066
0
    if ((info->flags & GIT_CPDIR_OVERWRITE) == 0)
1067
0
      return 0;
1068
1069
0
    if (p_unlink(info->to.ptr) < 0) {
1070
0
      git_error_set(GIT_ERROR_OS, "cannot overwrite existing file '%s'",
1071
0
        info->to.ptr);
1072
0
      return GIT_EEXISTS;
1073
0
    }
1074
0
  }
1075
1076
  /* Done if this isn't a regular file or a symlink */
1077
0
  if (!S_ISREG(from_st.st_mode) &&
1078
0
    (!S_ISLNK(from_st.st_mode) ||
1079
0
     (info->flags & GIT_CPDIR_COPY_SYMLINKS) == 0))
1080
0
    return 0;
1081
1082
  /* Make container directory on demand if needed */
1083
0
  if ((info->flags & GIT_CPDIR_CREATE_EMPTY_DIRS) == 0 &&
1084
0
    (error = _cp_r_mkdir(info, from)) < 0)
1085
0
    return error;
1086
1087
  /* make symlink or regular file */
1088
0
  if (info->flags & GIT_CPDIR_LINK_FILES) {
1089
0
    if ((error = p_link(from->ptr, info->to.ptr)) < 0)
1090
0
      git_error_set(GIT_ERROR_OS, "failed to link '%s'", from->ptr);
1091
0
  } else if (S_ISLNK(from_st.st_mode)) {
1092
0
    error = cp_link(from->ptr, info->to.ptr, (size_t)from_st.st_size);
1093
0
  } else {
1094
0
    mode_t usemode = from_st.st_mode;
1095
1096
0
    if ((info->flags & GIT_CPDIR_SIMPLE_TO_MODE) != 0)
1097
0
      usemode = GIT_PERMS_FOR_WRITE(usemode);
1098
1099
0
    error = git_futils_cp(from->ptr, info->to.ptr, usemode);
1100
0
  }
1101
1102
0
  return error;
1103
0
}
1104
1105
int git_futils_cp_r(
1106
  const char *from,
1107
  const char *to,
1108
  uint32_t flags,
1109
  mode_t dirmode)
1110
0
{
1111
0
  int error;
1112
0
  git_str path = GIT_STR_INIT;
1113
0
  cp_r_info info;
1114
1115
0
  if (git_str_joinpath(&path, from, "") < 0) /* ensure trailing slash */
1116
0
    return -1;
1117
1118
0
  memset(&info, 0, sizeof(info));
1119
0
  info.to_root = to;
1120
0
  info.flags   = flags;
1121
0
  info.dirmode = dirmode;
1122
0
  info.from_prefix = path.size;
1123
0
  git_str_init(&info.to, 0);
1124
1125
  /* precalculate mkdir flags */
1126
0
  if ((flags & GIT_CPDIR_CREATE_EMPTY_DIRS) == 0) {
1127
    /* if not creating empty dirs, then use mkdir to create the path on
1128
     * demand right before files are copied.
1129
     */
1130
0
    info.mkdir_flags = GIT_MKDIR_PATH | GIT_MKDIR_SKIP_LAST;
1131
0
    if ((flags & GIT_CPDIR_CHMOD_DIRS) != 0)
1132
0
      info.mkdir_flags |= GIT_MKDIR_CHMOD_PATH;
1133
0
  } else {
1134
    /* otherwise, we will do simple mkdir as directories are encountered */
1135
0
    info.mkdir_flags =
1136
0
      ((flags & GIT_CPDIR_CHMOD_DIRS) != 0) ? GIT_MKDIR_CHMOD : 0;
1137
0
  }
1138
1139
0
  error = _cp_r_callback(&info, &path);
1140
1141
0
  git_str_dispose(&path);
1142
0
  git_str_dispose(&info.to);
1143
1144
0
  return error;
1145
0
}
1146
1147
int git_futils_filestamp_check(
1148
  git_futils_filestamp *stamp, const char *path)
1149
29.8k
{
1150
29.8k
  struct stat st;
1151
1152
  /* if the stamp is NULL, then always reload */
1153
29.8k
  if (stamp == NULL)
1154
0
    return 1;
1155
1156
29.8k
  if (p_stat(path, &st) < 0)
1157
16.4k
    return GIT_ENOTFOUND;
1158
1159
13.3k
  if (stamp->mtime.tv_sec == st.st_mtime &&
1160
13.3k
#if defined(GIT_USE_NSEC)
1161
13.3k
    stamp->mtime.tv_nsec == st.st_mtime_nsec &&
1162
13.3k
#endif
1163
13.3k
    stamp->size  == (uint64_t)st.st_size   &&
1164
13.3k
    stamp->ino   == (unsigned int)st.st_ino)
1165
13.3k
    return 0;
1166
1167
0
  stamp->mtime.tv_sec = st.st_mtime;
1168
0
#if defined(GIT_USE_NSEC)
1169
0
  stamp->mtime.tv_nsec = st.st_mtime_nsec;
1170
0
#endif
1171
0
  stamp->size  = (uint64_t)st.st_size;
1172
0
  stamp->ino   = (unsigned int)st.st_ino;
1173
1174
0
  return 1;
1175
13.3k
}
1176
1177
void git_futils_filestamp_set(
1178
  git_futils_filestamp *target, const git_futils_filestamp *source)
1179
0
{
1180
0
  if (source)
1181
0
    memcpy(target, source, sizeof(*target));
1182
0
  else
1183
0
    memset(target, 0, sizeof(*target));
1184
0
}
1185
1186
1187
void git_futils_filestamp_set_from_stat(
1188
  git_futils_filestamp *stamp, struct stat *st)
1189
4
{
1190
4
  if (st) {
1191
4
    stamp->mtime.tv_sec = st->st_mtime;
1192
4
#if defined(GIT_USE_NSEC)
1193
4
    stamp->mtime.tv_nsec = st->st_mtime_nsec;
1194
#else
1195
    stamp->mtime.tv_nsec = 0;
1196
#endif
1197
4
    stamp->size  = (uint64_t)st->st_size;
1198
4
    stamp->ino   = (unsigned int)st->st_ino;
1199
4
  } else {
1200
0
    memset(stamp, 0, sizeof(*stamp));
1201
0
  }
1202
4
}
1203
1204
int git_futils_fsync_dir(const char *path)
1205
0
{
1206
#ifdef GIT_WIN32
1207
  GIT_UNUSED(path);
1208
  return 0;
1209
#else
1210
0
  int fd, error = -1;
1211
1212
0
  if ((fd = p_open(path, O_RDONLY)) < 0) {
1213
0
    git_error_set(GIT_ERROR_OS, "failed to open directory '%s' for fsync", path);
1214
0
    return -1;
1215
0
  }
1216
1217
0
  if ((error = p_fsync(fd)) < 0)
1218
0
    git_error_set(GIT_ERROR_OS, "failed to fsync directory '%s'", path);
1219
1220
0
  p_close(fd);
1221
0
  return error;
1222
0
#endif
1223
0
}
1224
1225
int git_futils_fsync_parent(const char *path)
1226
0
{
1227
0
  char *parent;
1228
0
  int error;
1229
1230
0
  if ((parent = git_fs_path_dirname(path)) == NULL)
1231
0
    return -1;
1232
1233
0
  error = git_futils_fsync_dir(parent);
1234
0
  git__free(parent);
1235
0
  return error;
1236
0
}