Sys.random: stop on an error but EINTR, not spin
| @@ -711,14 +711,26 @@ | ||
| 711 | 711 | repeat until SYSCALL(230, 1, 1, ADR(t), 0) # -4; (* clock_nanosleep until t, again after EINTR *) |
| 712 | 712 | end; |
| 713 | 713 | |
| 714 | -(* Fills b with random bytes, from the kernel. *) | |
| 714 | +(* Ends the program: random bytes can't be faked. *) | |
| 715 | +proc noRandom; | |
| 716 | +begin | |
| 717 | + _ := write(stderr, "Sys.random: the kernel gave no random bytes\n"); | |
| 718 | + _ := SYSCALL(231, 2); (* exit *) | |
| 719 | +end; | |
| 720 | + | |
| 721 | +(* Fills b with random bytes, from the kernel. Random bytes can't be | |
| 722 | + faked, so if the kernel can't give them (no getrandom, or a filter | |
| 723 | + refusing it) it says so on standard error and ends the program by | |
| 724 | + exit with status 2. *) | |
| 715 | 725 | proc random*(b: []U8); |
| 716 | 726 | var n, r: INT; |
| 717 | 727 | begin |
| 718 | 728 | n := 0; |
| 719 | 729 | while n < LEN(b) do (* a signal may cut it short *) |
| 720 | 730 | r := SYSCALL(318, ADR(b[n]), LEN(b) - n, 0); (* getrandom *) |
| 721 | - if r > 0 then INC(n, r); end; | |
| 731 | + if r > 0 then INC(n, r); | |
| 732 | + elsif r # errIntr then noRandom(); | |
| 733 | + end; | |
| 722 | 734 | end; |
| 723 | 735 | end; |
| 724 | 736 |
| @@ -783,14 +783,26 @@ | ||
| 783 | 783 | repeat until C.clock_nanosleep(CAbi.clockMonotonic, CAbi.timerAbstime, ^U8(ADR(t)), nil) # CAbi.eIntr; |
| 784 | 784 | end; |
| 785 | 785 | |
| 786 | -(* Fills b with random bytes, from the kernel. *) | |
| 786 | +(* Ends the program: random bytes can't be faked. *) | |
| 787 | +proc noRandom; | |
| 788 | +begin | |
| 789 | + _ := write(stderr, "Sys.random: the kernel gave no random bytes\n"); | |
| 790 | + C._exit(2); | |
| 791 | +end; | |
| 792 | + | |
| 793 | +(* Fills b with random bytes, from the kernel. Random bytes can't be | |
| 794 | + faked, so if the kernel can't give them (no getrandom, or a filter | |
| 795 | + refusing it) it says so on standard error and ends the program by | |
| 796 | + exit with status 2. *) | |
| 787 | 797 | proc random*(b: []U8); |
| 788 | 798 | var n, r: INT; |
| 789 | 799 | begin |
| 790 | 800 | n := 0; |
| 791 | 801 | while n < LEN(b) do (* a signal may cut it short *) |
| 792 | 802 | r := C.getrandom(ADR(b[n]), UINT(LEN(b) - n), 0); |
| 793 | - if r > 0 then INC(n, r); end; | |
| 803 | + if r > 0 then INC(n, r); | |
| 804 | + elsif (r >= 0) or (failed() # errIntr) then noRandom(); (* r = 0 can't be, and is no progress *) | |
| 805 | + end; | |
| 794 | 806 | end; |
| 795 | 807 | end; |
| 796 | 808 |