Debian Codegraph @

android/app/jni/extern/macports-legacy-support/src/getentropy.c

raw
1
2 /*
3 * Copyright (c) 2021
4 *
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17
18 // MP support header
19 #include "MacportsLegacySupport.h"
20 #if __MP_LEGACY_SUPPORT_GETENTROPY__
21
22 #include <fcntl.h>
23 #include <stdint.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <sys/types.h>
28 #include <sys/random.h>
29 #include <stdio.h>
30 #include <stdarg.h>
31 #include <errno.h>
32
33 void
34 _error(int doexit, int err, const char* fmt, ...)
35 {
36 va_list ap;
37
38 fflush(stdout);
39 fflush(stderr);
40 va_start(ap, fmt);
41 vfprintf(stderr, fmt, ap);
42 va_end(ap);
43
44 if (err > 0)
45 fprintf(stderr, "\n %s (Errno %d)\n", strerror(err), err);
46
47 if (doexit) {
48 fflush(stderr);
49 exit(1);
50 }
51 }
52
53 static int
54 _randopen(const char* name)
55 {
56 int fd = open(name, O_RDONLY);
57 if (fd < 0) {
58 _error(1, errno, "Cannot open system random number dev %s", name);
59 }
60
61 return fd;
62 }
63
64 int
65 getentropy(void* buf, size_t n)
66 {
67
68 static int fd = -1;
69 uint8_t* b = (uint8_t*)buf;
70
71 if (fd < 0)
72 fd = _randopen("/dev/urandom");
73
74 while (n > 0)
75 {
76 ssize_t m = (read)(fd, b, n);
77
78 if (m < 0) {
79 if (errno == EINTR) continue;
80 _error(1, errno, "Fatal read error while reading rand dev");
81 }
82 b += m;
83 n -= m;
84 }
85
86 return 0;
87 }
88
89 #endif /* __MP_LEGACY_SUPPORT_GETENTROPY__ */