NeoMutt  2024-12-12-14-g7b49f7
Teaching an old dog new tricks
DOXYGEN
Loading...
Searching...
No Matches
random.c
Go to the documentation of this file.
1
29#include "config.h"
30#include <errno.h>
31#include <stddef.h>
32#include <stdint.h>
33#include <stdio.h>
34#include <string.h>
35#include <sys/types.h>
36#include "random.h"
37#include "exit.h"
38#include "file.h"
39#include "logging2.h"
40#include "message.h"
41#ifdef HAVE_SYS_RANDOM_H
42#include <sys/random.h>
43#endif
44
46static FILE *FpRandom = NULL;
47
49static const unsigned char Base32[] = "abcdefghijklmnopqrstuvwxyz234567";
50
58static int mutt_randbuf(void *buf, size_t buflen)
59{
60 if (buflen > 1048576)
61 {
62 mutt_error(_("mutt_randbuf buflen=%zu"), buflen);
63 return -1;
64 }
65
66#ifdef HAVE_GETRANDOM
67 ssize_t rc;
68 ssize_t count = 0;
69 do
70 {
71 // getrandom() can return less than requested if there's insufficient
72 // entropy or it's interrupted by a signal.
73 rc = getrandom((char *) buf + count, buflen - count, 0);
74 if (rc > 0)
75 count += rc;
76 } while (((rc >= 0) && (count < buflen)) || ((rc == -1) && (errno == EINTR)));
77 if (count == buflen)
78 return 0;
79#endif
80 /* let's try urandom in case we're on an old kernel, or the user has
81 * configured selinux, seccomp or something to not allow getrandom */
82 if (!FpRandom)
83 {
84 FpRandom = mutt_file_fopen("/dev/urandom", "r");
85 if (!FpRandom)
86 {
87 mutt_error(_("open /dev/urandom: %s"), strerror(errno));
88 return -1;
89 }
90 setbuf(FpRandom, NULL);
91 }
92 if (fread(buf, 1, buflen, FpRandom) != buflen)
93 {
94 mutt_error(_("read /dev/urandom: %s"), strerror(errno));
95 return -1;
96 }
97
98 return 0;
99}
100
106void mutt_rand_base32(char *buf, size_t buflen)
107{
108 if (!buf || (buflen == 0))
109 return;
110
111 uint8_t *p = (uint8_t *) buf;
112
113 if (mutt_randbuf(p, buflen) < 0)
114 mutt_exit(1); // LCOV_EXCL_LINE
115 for (size_t pos = 0; pos < buflen; pos++)
116 p[pos] = Base32[p[pos] % 32];
117}
118
123uint64_t mutt_rand64(void)
124{
125 uint64_t num = 0;
126
127 if (mutt_randbuf(&num, sizeof(num)) < 0)
128 mutt_exit(1); // LCOV_EXCL_LINE
129 return num;
130}
Leave the program NOW.
File management functions.
#define mutt_file_fopen(PATH, MODE)
Definition: file.h:137
#define mutt_error(...)
Definition: logging2.h:92
Logging Dispatcher.
void mutt_exit(int code)
Leave NeoMutt NOW.
Definition: main.c:266
Message logging.
#define _(a)
Definition: message.h:28
static const unsigned char Base32[]
Base 32 alphabet.
Definition: random.c:49
uint64_t mutt_rand64(void)
Create a 64-bit random number.
Definition: random.c:123
static int mutt_randbuf(void *buf, size_t buflen)
Fill a buffer with randomness.
Definition: random.c:58
static FILE * FpRandom
FILE pointer of the random source.
Definition: random.c:46
void mutt_rand_base32(char *buf, size_t buflen)
Fill a buffer with a base32-encoded random string.
Definition: random.c:106
Random number/string functions.