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