include/ptotp/ptotp_rand.h

filter: Statementstmt 87.5% 7 / 8 Branchbran 75.0% 3 / 4 Conditioncond n/a MC/DCmcdc n/a Subroutinesub n/a Podpod n/a totaltotal 83.3% 10 / 12 CC 0 SCAR 0
CC
0
Cov
0%
CRAP 0
« include/ptotp/ptotp_otp.h ↑ Summary TOTP.xs »
1 #ifndef PTOTP_RAND_H
2 #define PTOTP_RAND_H
3  
4 #include <stddef.h>
5 #include <stdio.h>
6  
7 #ifdef PTOTP_HAVE_GETENTROPY
8 #include <unistd.h>
9 #ifdef PTOTP_HAVE_SYS_RANDOM_H
10 #include <sys/random.h> /* where getentropy is declared on macOS and glibc */
11 #endif
12 #endif
13  
14 /* ptotp_rand.h - the entropy behind secret generation, which is the
15 * one place in this dist where randomness quality is the whole point.
16 * getentropy when the configure probe LINKED it (compile-only probes
17 * are a recorded CPAN Testers failure), /dev/urandom otherwise, and
18 * failure returns -1 for the caller to croak on: a TOTP secret from a
19 * degraded source is worse than no secret. */
20  
21 6 static int ptotp_random_bytes(unsigned char *out, size_t n)
22 {
23 #ifdef PTOTP_HAVE_GETENTROPY
24 6 size_t off = 0;
25 12 ▶ while (off < n) {
Branch: 1 branch
BranchTrueFalseTotal
while (off < n) { 6 6 12
26 6 size_t take = n - off > 256 ? 256 : n - off;
27 6 ▶ if (getentropy(out + off, take) != 0)
Branch: 1 branch
BranchTrueFalseTotal
if (getentropy(out + off, take) != 0) 0 6 6
28 0 return -1;
29 6 off += take;
30 }
31 6 return 0;
32 #else
33 FILE *f = fopen("/dev/urandom", "rb");
34 size_t got;
35 if (!f)
36 return -1;
37 got = fread(out, 1, n, f);
38 fclose(f);
39 return got == n ? 0 : -1;
40 #endif
41 }
42  
43 #endif /* PTOTP_RAND_H */
« include/ptotp/ptotp_otp.h ↑ Summary TOTP.xs »