File: getentropy_wrapper.c

package info (click to toggle)
librandombytes 0~20240318-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 328 kB
  • sloc: ansic: 411; python: 340; sh: 137; makefile: 23
file content (76 lines) | stat: -rw-r--r-- 1,254 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// version 20230919
// public domain
// djb

// 20230919: fixing main getentropy() call; tnx jan mojzis

#include <unistd.h>

// automatic-alternatives 2
#ifdef getentropy_wrapper_2

#include "getentropy_wrapper.h"

int getentropy_wrapper_ready(void)
{
  return 0;
}

void getentropy_wrapper(void *x,long long xbytes)
{
  for (;;) pause();
}

#else

#include <errno.h>
#include <signal.h>

#include "getentropy_wrapper.h"

static int getentropy_wrapper_ready_core(void)
{
  char ch;
  int r;

  for (;;) {
    errno = 0;
    r = getentropy(&ch,1);
    if (r == 0) return 1;
    if (r == -1 && errno == ENOSYS) return 0;
    if (r == -1 && errno == EPERM) return 0;
    if (r == -1 && errno == EIO) return 0;
  }
}

int getentropy_wrapper_ready(void)
{
  struct sigaction old_sigsys;
  int result;

  sigaction(SIGSYS,0,&old_sigsys);
  signal(SIGSYS,SIG_IGN);
  result = getentropy_wrapper_ready_core();
  sigaction(SIGSYS,&old_sigsys,0);
  return result;
}

void getentropy_wrapper(void *x,long long xbytes)
{
  while (xbytes > 0) {
    // getentropy fails for >256 bytes

    int todo = 256;
    if (xbytes < 256) todo = xbytes;

    if (getentropy(x,todo) != 0) {
      sleep(1);
      continue;
    }

    x += todo;
    xbytes -= todo;
  }
}

#endif