]> git.ipfire.org Git - thirdparty/git.git/blame - wrapper.c
split-index: accept that a base index can be empty
[thirdparty/git.git] / wrapper.c
CommitLineData
112db553
LT
1/*
2 * Various trivial helper wrappers around standard functions
3 */
4#include "cache.h"
b2141fc1 5#include "config.h"
112db553 6
9a498767
NS
7static intmax_t count_fsync_writeout_only;
8static intmax_t count_fsync_hardware_flush;
9
19d3f228
NS
10#ifdef HAVE_RTLGENRANDOM
11/* This is required to get access to RtlGenRandom. */
12#define SystemFunction036 NTAPI SystemFunction036
13#include <NTSecAPI.h>
14#undef SystemFunction036
15#endif
16
f8bb1d94 17static int memory_limit_check(size_t size, int gentle)
d41489a6 18{
9927d962
SP
19 static size_t limit = 0;
20 if (!limit) {
21 limit = git_env_ulong("GIT_ALLOC_LIMIT", 0);
22 if (!limit)
23 limit = SIZE_MAX;
d41489a6 24 }
f0d89001 25 if (size > limit) {
f8bb1d94 26 if (gentle) {
f0d89001
JH
27 error("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
28 (uintmax_t)size, (uintmax_t)limit);
f8bb1d94
NTND
29 return -1;
30 } else
f0d89001
JH
31 die("attempting to allocate %"PRIuMAX" over limit %"PRIuMAX,
32 (uintmax_t)size, (uintmax_t)limit);
f8bb1d94
NTND
33 }
34 return 0;
d41489a6
NTND
35}
36
112db553
LT
37char *xstrdup(const char *str)
38{
39 char *ret = strdup(str);
9827d4c1
JK
40 if (!ret)
41 die("Out of memory, strdup failed");
112db553
LT
42 return ret;
43}
44
f8bb1d94 45static void *do_xmalloc(size_t size, int gentle)
112db553 46{
d41489a6
NTND
47 void *ret;
48
f8bb1d94
NTND
49 if (memory_limit_check(size, gentle))
50 return NULL;
d41489a6 51 ret = malloc(size);
112db553
LT
52 if (!ret && !size)
53 ret = malloc(1);
54 if (!ret) {
9827d4c1
JK
55 if (!gentle)
56 die("Out of memory, malloc failed (tried to allocate %lu bytes)",
57 (unsigned long)size);
58 else {
59 error("Out of memory, malloc failed (tried to allocate %lu bytes)",
60 (unsigned long)size);
61 return NULL;
f8bb1d94 62 }
112db553
LT
63 }
64#ifdef XMALLOC_POISON
65 memset(ret, 0xA5, size);
66#endif
67 return ret;
68}
69
f8bb1d94
NTND
70void *xmalloc(size_t size)
71{
72 return do_xmalloc(size, 0);
73}
74
75static void *do_xmallocz(size_t size, int gentle)
5bf9219d
IL
76{
77 void *ret;
f8bb1d94
NTND
78 if (unsigned_add_overflows(size, 1)) {
79 if (gentle) {
80 error("Data too large to fit into virtual memory space.");
81 return NULL;
82 } else
83 die("Data too large to fit into virtual memory space.");
84 }
85 ret = do_xmalloc(size + 1, gentle);
86 if (ret)
87 ((char*)ret)[size] = 0;
5bf9219d
IL
88 return ret;
89}
90
f8bb1d94
NTND
91void *xmallocz(size_t size)
92{
93 return do_xmallocz(size, 0);
94}
95
96void *xmallocz_gently(size_t size)
97{
98 return do_xmallocz(size, 1);
99}
100
112db553
LT
101/*
102 * xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
103 * "data" to the allocated memory, zero terminates the allocated memory,
104 * and returns a pointer to the allocated memory. If the allocation fails,
105 * the program dies.
106 */
107void *xmemdupz(const void *data, size_t len)
108{
5bf9219d 109 return memcpy(xmallocz(len), data, len);
112db553
LT
110}
111
112char *xstrndup(const char *str, size_t len)
113{
114 char *p = memchr(str, '\0', len);
115 return xmemdupz(str, p ? p - str : len);
116}
117
14570dc6 118int xstrncmpz(const char *s, const char *t, size_t len)
119{
120 int res = strncmp(s, t, len);
121 if (res)
122 return res;
123 return s[len] == '\0' ? 0 : 1;
124}
125
112db553
LT
126void *xrealloc(void *ptr, size_t size)
127{
d41489a6
NTND
128 void *ret;
129
6479ea4a
JK
130 if (!size) {
131 free(ptr);
132 return xmalloc(0);
133 }
134
f8bb1d94 135 memory_limit_check(size, 0);
d41489a6 136 ret = realloc(ptr, size);
9827d4c1
JK
137 if (!ret)
138 die("Out of memory, realloc failed");
112db553
LT
139 return ret;
140}
141
142void *xcalloc(size_t nmemb, size_t size)
143{
d41489a6
NTND
144 void *ret;
145
e7792a74
JK
146 if (unsigned_mult_overflows(nmemb, size))
147 die("data too large to fit into virtual memory space");
148
f8bb1d94 149 memory_limit_check(size * nmemb, 0);
d41489a6 150 ret = calloc(nmemb, size);
112db553
LT
151 if (!ret && (!nmemb || !size))
152 ret = calloc(1, 1);
9827d4c1
JK
153 if (!ret)
154 die("Out of memory, calloc failed");
112db553
LT
155 return ret;
156}
157
3540c71e
ÆAB
158void xsetenv(const char *name, const char *value, int overwrite)
159{
160 if (setenv(name, value, overwrite))
161 die_errno(_("could not setenv '%s'"), name ? name : "(null)");
162}
163
3ff53df7
PT
164/**
165 * xopen() is the same as open(), but it die()s if the open() fails.
166 */
167int xopen(const char *path, int oflag, ...)
168{
169 mode_t mode = 0;
170 va_list ap;
171
172 /*
173 * va_arg() will have undefined behavior if the specified type is not
174 * compatible with the argument type. Since integers are promoted to
175 * ints, we fetch the next argument as an int, and then cast it to a
176 * mode_t to avoid undefined behavior.
177 */
178 va_start(ap, oflag);
179 if (oflag & O_CREAT)
180 mode = va_arg(ap, int);
181 va_end(ap);
182
183 for (;;) {
184 int fd = open(path, oflag, mode);
185 if (fd >= 0)
186 return fd;
187 if (errno == EINTR)
188 continue;
189
a7439d0f
RS
190 if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
191 die_errno(_("unable to create '%s'"), path);
192 else if ((oflag & O_RDWR) == O_RDWR)
3ff53df7
PT
193 die_errno(_("could not open '%s' for reading and writing"), path);
194 else if ((oflag & O_WRONLY) == O_WRONLY)
195 die_errno(_("could not open '%s' for writing"), path);
196 else
197 die_errno(_("could not open '%s' for reading"), path);
198 }
199}
200
d751dd11
EW
201static int handle_nonblock(int fd, short poll_events, int err)
202{
203 struct pollfd pfd;
204
205 if (err != EAGAIN && err != EWOULDBLOCK)
206 return 0;
207
208 pfd.fd = fd;
209 pfd.events = poll_events;
210
211 /*
212 * no need to check for errors, here;
213 * a subsequent read/write will detect unrecoverable errors
214 */
215 poll(&pfd, 1, -1);
216 return 1;
217}
218
112db553
LT
219/*
220 * xread() is the same a read(), but it automatically restarts read()
221 * operations with a recoverable error (EAGAIN and EINTR). xread()
222 * DOES NOT GUARANTEE that "len" bytes is read even if the data is available.
223 */
224ssize_t xread(int fd, void *buf, size_t len)
225{
226 ssize_t nr;
0b6806b9 227 if (len > MAX_IO_SIZE)
7cd54d37 228 len = MAX_IO_SIZE;
112db553
LT
229 while (1) {
230 nr = read(fd, buf, len);
1079c4be
SB
231 if (nr < 0) {
232 if (errno == EINTR)
233 continue;
d751dd11 234 if (handle_nonblock(fd, POLLIN, errno))
c22f6202 235 continue;
1079c4be 236 }
112db553
LT
237 return nr;
238 }
239}
240
241/*
242 * xwrite() is the same a write(), but it automatically restarts write()
243 * operations with a recoverable error (EAGAIN and EINTR). xwrite() DOES NOT
244 * GUARANTEE that "len" bytes is written even if the operation is successful.
245 */
246ssize_t xwrite(int fd, const void *buf, size_t len)
247{
248 ssize_t nr;
0b6806b9 249 if (len > MAX_IO_SIZE)
7cd54d37 250 len = MAX_IO_SIZE;
112db553
LT
251 while (1) {
252 nr = write(fd, buf, len);
ef1cf016
EW
253 if (nr < 0) {
254 if (errno == EINTR)
255 continue;
d751dd11 256 if (handle_nonblock(fd, POLLOUT, errno))
ef1cf016 257 continue;
ef1cf016
EW
258 }
259
9aa91af0
YM
260 return nr;
261 }
262}
263
264/*
265 * xpread() is the same as pread(), but it automatically restarts pread()
266 * operations with a recoverable error (EAGAIN and EINTR). xpread() DOES
267 * NOT GUARANTEE that "len" bytes is read even if the data is available.
268 */
269ssize_t xpread(int fd, void *buf, size_t len, off_t offset)
270{
271 ssize_t nr;
272 if (len > MAX_IO_SIZE)
273 len = MAX_IO_SIZE;
274 while (1) {
275 nr = pread(fd, buf, len, offset);
276 if ((nr < 0) && (errno == EAGAIN || errno == EINTR))
112db553
LT
277 continue;
278 return nr;
279 }
280}
281
559e840b
JH
282ssize_t read_in_full(int fd, void *buf, size_t count)
283{
284 char *p = buf;
285 ssize_t total = 0;
286
287 while (count > 0) {
288 ssize_t loaded = xread(fd, p, count);
56d7c27a
JK
289 if (loaded < 0)
290 return -1;
291 if (loaded == 0)
292 return total;
559e840b
JH
293 count -= loaded;
294 p += loaded;
295 total += loaded;
296 }
297
298 return total;
299}
300
301ssize_t write_in_full(int fd, const void *buf, size_t count)
302{
303 const char *p = buf;
304 ssize_t total = 0;
305
306 while (count > 0) {
307 ssize_t written = xwrite(fd, p, count);
308 if (written < 0)
309 return -1;
310 if (!written) {
311 errno = ENOSPC;
312 return -1;
313 }
314 count -= written;
315 p += written;
316 total += written;
317 }
318
319 return total;
320}
321
426ddeea
YM
322ssize_t pread_in_full(int fd, void *buf, size_t count, off_t offset)
323{
324 char *p = buf;
325 ssize_t total = 0;
326
327 while (count > 0) {
328 ssize_t loaded = xpread(fd, p, count, offset);
329 if (loaded < 0)
330 return -1;
331 if (loaded == 0)
332 return total;
333 count -= loaded;
334 p += loaded;
335 total += loaded;
336 offset += loaded;
337 }
338
339 return total;
340}
341
112db553
LT
342int xdup(int fd)
343{
344 int ret = dup(fd);
345 if (ret < 0)
d824cbba 346 die_errno("dup failed");
112db553
LT
347 return ret;
348}
349
260eec29
PT
350/**
351 * xfopen() is the same as fopen(), but it die()s if the fopen() fails.
352 */
353FILE *xfopen(const char *path, const char *mode)
354{
355 for (;;) {
356 FILE *fp = fopen(path, mode);
357 if (fp)
358 return fp;
359 if (errno == EINTR)
360 continue;
361
362 if (*mode && mode[1] == '+')
363 die_errno(_("could not open '%s' for reading and writing"), path);
364 else if (*mode == 'w' || *mode == 'a')
365 die_errno(_("could not open '%s' for writing"), path);
366 else
367 die_errno(_("could not open '%s' for reading"), path);
368 }
369}
370
112db553
LT
371FILE *xfdopen(int fd, const char *mode)
372{
373 FILE *stream = fdopen(fd, mode);
afe8a907 374 if (!stream)
d824cbba 375 die_errno("Out of memory? fdopen failed");
112db553
LT
376 return stream;
377}
378
79d7582e
JS
379FILE *fopen_for_writing(const char *path)
380{
381 FILE *ret = fopen(path, "w");
382
383 if (!ret && errno == EPERM) {
384 if (!unlink(path))
385 ret = fopen(path, "w");
386 else
387 errno = EPERM;
388 }
389 return ret;
390}
391
382fb07f
NTND
392static void warn_on_inaccessible(const char *path)
393{
394 warning_errno(_("unable to access '%s'"), path);
395}
396
11dc1fcb
NTND
397int warn_on_fopen_errors(const char *path)
398{
399 if (errno != ENOENT && errno != ENOTDIR) {
400 warn_on_inaccessible(path);
401 return -1;
402 }
403
404 return 0;
405}
406
e9d983f1
NTND
407FILE *fopen_or_warn(const char *path, const char *mode)
408{
409 FILE *fp = fopen(path, mode);
410
411 if (fp)
412 return fp;
413
414 warn_on_fopen_errors(path);
415 return NULL;
416}
417
eb78e23f 418int xmkstemp(char *filename_template)
112db553
LT
419{
420 int fd;
6cf6bb3e 421 char origtemplate[PATH_MAX];
eb78e23f 422 strlcpy(origtemplate, filename_template, sizeof(origtemplate));
112db553 423
eb78e23f 424 fd = mkstemp(filename_template);
6cf6bb3e
AE
425 if (fd < 0) {
426 int saved_errno = errno;
427 const char *nonrelative_template;
428
eb78e23f
BW
429 if (strlen(filename_template) != strlen(origtemplate))
430 filename_template = origtemplate;
6cf6bb3e 431
eb78e23f 432 nonrelative_template = absolute_path(filename_template);
6cf6bb3e
AE
433 errno = saved_errno;
434 die_errno("Unable to create temporary file '%s'",
435 nonrelative_template);
436 }
112db553
LT
437 return fd;
438}
39c68542 439
33f23936
JN
440/* Adapted from libiberty's mkstemp.c. */
441
442#undef TMP_MAX
443#define TMP_MAX 16384
444
445int git_mkstemps_mode(char *pattern, int suffix_len, int mode)
446{
447 static const char letters[] =
448 "abcdefghijklmnopqrstuvwxyz"
449 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
450 "0123456789";
53d687bf
JK
451 static const int num_letters = ARRAY_SIZE(letters) - 1;
452 static const char x_pattern[] = "XXXXXX";
453 static const int num_x = ARRAY_SIZE(x_pattern) - 1;
eb78e23f 454 char *filename_template;
33f23936
JN
455 size_t len;
456 int fd, count;
457
458 len = strlen(pattern);
459
53d687bf 460 if (len < num_x + suffix_len) {
33f23936
JN
461 errno = EINVAL;
462 return -1;
463 }
464
53d687bf 465 if (strncmp(&pattern[len - num_x - suffix_len], x_pattern, num_x)) {
33f23936
JN
466 errno = EINVAL;
467 return -1;
468 }
469
470 /*
471 * Replace pattern's XXXXXX characters with randomness.
472 * Try TMP_MAX different filenames.
473 */
53d687bf 474 filename_template = &pattern[len - num_x - suffix_len];
33f23936 475 for (count = 0; count < TMP_MAX; ++count) {
54a80a9a 476 int i;
47efda96 477 uint64_t v;
478 if (csprng_bytes(&v, sizeof(v)) < 0)
479 return error_errno("unable to get random bytes for temporary file");
480
33f23936 481 /* Fill in the random bits. */
53d687bf 482 for (i = 0; i < num_x; i++) {
54a80a9a
AH
483 filename_template[i] = letters[v % num_letters];
484 v /= num_letters;
485 }
33f23936
JN
486
487 fd = open(pattern, O_CREAT | O_EXCL | O_RDWR, mode);
a2cb86c1 488 if (fd >= 0)
33f23936
JN
489 return fd;
490 /*
491 * Fatal error (EPERM, ENOSPC etc).
492 * It doesn't make sense to loop.
493 */
494 if (errno != EEXIST)
495 break;
33f23936
JN
496 }
497 /* We return the null string if we can't find a unique file name. */
498 pattern[0] = '\0';
499 return -1;
500}
501
502int git_mkstemp_mode(char *pattern, int mode)
503{
504 /* mkstemp is just mkstemps with no suffix */
505 return git_mkstemps_mode(pattern, 0, mode);
506}
507
eb78e23f 508int xmkstemp_mode(char *filename_template, int mode)
b862b61c
MM
509{
510 int fd;
6cf6bb3e 511 char origtemplate[PATH_MAX];
eb78e23f 512 strlcpy(origtemplate, filename_template, sizeof(origtemplate));
b862b61c 513
eb78e23f 514 fd = git_mkstemp_mode(filename_template, mode);
6cf6bb3e
AE
515 if (fd < 0) {
516 int saved_errno = errno;
517 const char *nonrelative_template;
518
eb78e23f
BW
519 if (!filename_template[0])
520 filename_template = origtemplate;
6cf6bb3e 521
eb78e23f 522 nonrelative_template = absolute_path(filename_template);
6cf6bb3e
AE
523 errno = saved_errno;
524 die_errno("Unable to create temporary file '%s'",
525 nonrelative_template);
526 }
b862b61c
MM
527 return fd;
528}
529
abf38abe
NS
530/*
531 * Some platforms return EINTR from fsync. Since fsync is invoked in some
532 * cases by a wrapper that dies on failure, do not expose EINTR to callers.
533 */
534static int fsync_loop(int fd)
535{
536 int err;
537
538 do {
539 err = fsync(fd);
540 } while (err < 0 && errno == EINTR);
541 return err;
542}
543
544int git_fsync(int fd, enum fsync_action action)
545{
546 switch (action) {
547 case FSYNC_WRITEOUT_ONLY:
9a498767 548 count_fsync_writeout_only += 1;
abf38abe
NS
549
550#ifdef __APPLE__
551 /*
552 * On macOS, fsync just causes filesystem cache writeback but
553 * does not flush hardware caches.
554 */
555 return fsync_loop(fd);
556#endif
557
558#ifdef HAVE_SYNC_FILE_RANGE
559 /*
560 * On linux 2.6.17 and above, sync_file_range is the way to
561 * issue a writeback without a hardware flush. An offset of
562 * 0 and size of 0 indicates writeout of the entire file and the
563 * wait flags ensure that all dirty data is written to the disk
564 * (potentially in a disk-side cache) before we continue.
565 */
566
567 return sync_file_range(fd, 0, 0, SYNC_FILE_RANGE_WAIT_BEFORE |
568 SYNC_FILE_RANGE_WRITE |
569 SYNC_FILE_RANGE_WAIT_AFTER);
570#endif
571
572#ifdef fsync_no_flush
573 return fsync_no_flush(fd);
574#endif
575
576 errno = ENOSYS;
577 return -1;
578
579 case FSYNC_HARDWARE_FLUSH:
9a498767
NS
580 count_fsync_hardware_flush += 1;
581
abf38abe
NS
582 /*
583 * On macOS, a special fcntl is required to really flush the
584 * caches within the storage controller. As of this writing,
585 * this is a very expensive operation on Apple SSDs.
586 */
587#ifdef __APPLE__
588 return fcntl(fd, F_FULLFSYNC);
589#else
590 return fsync_loop(fd);
591#endif
592 default:
593 BUG("unexpected git_fsync(%d) call", action);
594 }
595}
596
3a251bac
ÆAB
597static void log_trace_fsync_if(const char *key, intmax_t value)
598{
599 if (value)
600 trace2_data_intmax("fsync", the_repository, key, value);
601}
602
9a498767
NS
603void trace_git_fsync_stats(void)
604{
3a251bac
ÆAB
605 log_trace_fsync_if("fsync/writeout-only", count_fsync_writeout_only);
606 log_trace_fsync_if("fsync/hardware-flush", count_fsync_hardware_flush);
9a498767
NS
607}
608
10e13ec8 609static int warn_if_unremovable(const char *op, const char *file, int rc)
fc71db39 610{
1054af7d
RS
611 int err;
612 if (!rc || errno == ENOENT)
613 return 0;
614 err = errno;
0a288d1e 615 warning_errno("unable to %s '%s'", op, file);
1054af7d 616 errno = err;
fc71db39
AR
617 return rc;
618}
619
9ccc0c08
RS
620int unlink_or_msg(const char *file, struct strbuf *err)
621{
622 int rc = unlink(file);
623
624 assert(err);
625
626 if (!rc || errno == ENOENT)
627 return 0;
628
0a288d1e 629 strbuf_addf(err, "unable to unlink '%s': %s",
9ccc0c08
RS
630 file, strerror(errno));
631 return -1;
632}
633
10e13ec8
PC
634int unlink_or_warn(const char *file)
635{
636 return warn_if_unremovable("unlink", file, unlink(file));
637}
d1723296
PC
638
639int rmdir_or_warn(const char *file)
640{
641 return warn_if_unremovable("rmdir", file, rmdir(file));
642}
80d706af
PC
643
644int remove_or_warn(unsigned int mode, const char *file)
645{
646 return S_ISGITLINK(mode) ? rmdir_or_warn(file) : unlink_or_warn(file);
647}
2f705875 648
4698c8fe
JN
649static int access_error_is_ok(int err, unsigned flag)
650{
c7054209
JH
651 return (is_missing_file_error(err) ||
652 ((flag & ACCESS_EACCES_OK) && err == EACCES));
4698c8fe
JN
653}
654
655int access_or_warn(const char *path, int mode, unsigned flag)
ba8bd830
JK
656{
657 int ret = access(path, mode);
4698c8fe 658 if (ret && !access_error_is_ok(errno, flag))
55b38a48 659 warn_on_inaccessible(path);
ba8bd830
JK
660 return ret;
661}
662
4698c8fe 663int access_or_die(const char *path, int mode, unsigned flag)
96b9e0e3
JN
664{
665 int ret = access(path, mode);
4698c8fe 666 if (ret && !access_error_is_ok(errno, flag))
96b9e0e3
JN
667 die_errno(_("unable to access '%s'"), path);
668 return ret;
669}
670
aa14e980
RS
671char *xgetcwd(void)
672{
673 struct strbuf sb = STRBUF_INIT;
674 if (strbuf_getcwd(&sb))
675 die_errno(_("unable to get current working directory"));
676 return strbuf_detach(&sb, NULL);
677}
316e53e6 678
7b03c89e
JK
679int xsnprintf(char *dst, size_t max, const char *fmt, ...)
680{
681 va_list ap;
682 int len;
683
684 va_start(ap, fmt);
685 len = vsnprintf(dst, max, fmt, ap);
686 va_end(ap);
687
688 if (len < 0)
033abf97 689 BUG("your snprintf is broken");
7b03c89e 690 if (len >= max)
033abf97 691 BUG("attempt to snprintf into too-small buffer");
7b03c89e
JK
692 return len;
693}
694
52563d7e 695void write_file_buf(const char *path, const char *buf, size_t len)
316e53e6 696{
52563d7e 697 int fd = xopen(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
06f46f23 698 if (write_in_full(fd, buf, len) < 0)
0a288d1e 699 die_errno(_("could not write to '%s'"), path);
52563d7e 700 if (close(fd))
0a288d1e 701 die_errno(_("could not close '%s'"), path);
316e53e6 702}
2024d317 703
ef22318c 704void write_file(const char *path, const char *fmt, ...)
12d6ce1d 705{
12d6ce1d 706 va_list params;
316e53e6 707 struct strbuf sb = STRBUF_INIT;
12d6ce1d
JH
708
709 va_start(params, fmt);
ef22318c 710 strbuf_vaddf(&sb, fmt, params);
12d6ce1d 711 va_end(params);
12d6ce1d 712
ef22318c 713 strbuf_complete_line(&sb);
12d6ce1d 714
52563d7e 715 write_file_buf(path, sb.buf, sb.len);
ef22318c 716 strbuf_release(&sb);
12d6ce1d
JH
717}
718
2024d317
JS
719void sleep_millisec(int millisec)
720{
721 poll(NULL, 0, millisec);
722}
5781a9a2
DT
723
724int xgethostname(char *buf, size_t len)
725{
726 /*
727 * If the full hostname doesn't fit in buf, POSIX does not
728 * specify whether the buffer will be null-terminated, so to
729 * be safe, do it ourselves.
730 */
731 int ret = gethostname(buf, len);
732 if (!ret)
733 buf[len - 1] = 0;
734 return ret;
735}
e3b1e3bd
PB
736
737int is_empty_or_missing_file(const char *filename)
738{
739 struct stat st;
740
741 if (stat(filename, &st) < 0) {
742 if (errno == ENOENT)
743 return 1;
744 die_errno(_("could not stat %s"), filename);
745 }
746
747 return !st.st_size;
748}
00611d84
JK
749
750int open_nofollow(const char *path, int flags)
751{
752#ifdef O_NOFOLLOW
753 return open(path, flags | O_NOFOLLOW);
754#else
755 struct stat st;
756 if (lstat(path, &st) < 0)
757 return -1;
758 if (S_ISLNK(st.st_mode)) {
759 errno = ELOOP;
760 return -1;
761 }
762 return open(path, flags);
763#endif
764}
05cd988d 765
766int csprng_bytes(void *buf, size_t len)
767{
768#if defined(HAVE_ARC4RANDOM) || defined(HAVE_ARC4RANDOM_LIBBSD)
769 /* This function never returns an error. */
770 arc4random_buf(buf, len);
771 return 0;
772#elif defined(HAVE_GETRANDOM)
773 ssize_t res;
774 char *p = buf;
775 while (len) {
776 res = getrandom(p, len, 0);
777 if (res < 0)
778 return -1;
779 len -= res;
780 p += res;
781 }
782 return 0;
783#elif defined(HAVE_GETENTROPY)
784 int res;
785 char *p = buf;
786 while (len) {
787 /* getentropy has a maximum size of 256 bytes. */
788 size_t chunk = len < 256 ? len : 256;
789 res = getentropy(p, chunk);
790 if (res < 0)
791 return -1;
792 len -= chunk;
793 p += chunk;
794 }
795 return 0;
796#elif defined(HAVE_RTLGENRANDOM)
797 if (!RtlGenRandom(buf, len))
798 return -1;
799 return 0;
800#elif defined(HAVE_OPENSSL_CSPRNG)
801 int res = RAND_bytes(buf, len);
802 if (res == 1)
803 return 0;
804 if (res == -1)
805 errno = ENOTSUP;
806 else
807 errno = EIO;
808 return -1;
809#else
810 ssize_t res;
811 char *p = buf;
812 int fd, err;
813 fd = open("/dev/urandom", O_RDONLY);
814 if (fd < 0)
815 return -1;
816 while (len) {
817 res = xread(fd, p, len);
818 if (res < 0) {
819 err = errno;
820 close(fd);
821 errno = err;
822 return -1;
823 }
824 len -= res;
825 p += res;
826 }
827 close(fd);
828 return 0;
829#endif
830}