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