chiark / gitweb /
copyright: Add notice to random-fake-userv
[secnet.git] / test-example / random-fake-userv
1 #!/usr/bin/perl -w
2 #
3 # stunt userv-ipif standin which generates random data
4 #
5 # This file is part of secnet.
6 # See README for full list of copyright holders.
7 #
8 # secnet is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12
13 # secnet is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 # General Public License for more details.
17
18 # You should have received a copy of the GNU General Public License
19 # version 3 along with secnet; if not, see
20 # https://www.gnu.org/licenses/gpl.html.
21
22 use strict;
23 use POSIX;
24
25 open R, '/dev/urandom' or die $!;
26
27 system 'cat >/dev/null &';
28
29 sub randbytes ($) {
30     my ($count) = @_;
31     my $s;
32     my $r = read R, $s, $count;
33     die $! unless $r==$count;
34     return $s;
35 }
36
37 sub randbyteval () {
38     my $b = randbytes 1;
39     my ($r) = unpack 'C', $b;
40     return $r;
41 }
42
43 sub randvalue ($$) {
44     my ($min,$maxplus1) = @_;
45     my $b = randbyteval;
46     return floor(($b/256.0) * ($maxplus1-$min)) + $min;
47 }
48
49 for (;;) {
50     my $lenbits = randvalue 0,14;
51     my $len= (randbyteval << 8) | randbyteval;
52     $len &= (1 << $lenbits)-1;
53     my $data = randbytes $len;
54     if (randbyteval >= 0x80) {
55         $data =~ s{[\xc0\xdb]}{
56             $& eq "\xc0" ? "\xcb\xdc" :
57             $& eq "\xdb" ? "\xcb\xdd" :
58             die
59         }ge;
60     }
61     print "\xc0";
62     print $data;
63     STDOUT->flush;
64 }