Makefile.in: Drop dist target
[secnet] / random.c
1 /*
2 * This file is part of secnet.
3 * See README for full list of copyright holders.
4 *
5 * secnet is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * secnet is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * version 3 along with secnet; if not, see
17 * https://www.gnu.org/licenses/gpl.html.
18 */
19
20 #include "secnet.h"
21 #include <stdio.h>
22 #include <fcntl.h>
23 #include <string.h>
24 #include <sys/stat.h>
25 #include <unistd.h>
26 #include <assert.h>
27
28 struct rgen_data {
29 closure_t cl;
30 struct random_if ops;
31 struct cloc loc;
32 int fd;
33 };
34
35 static random_fn random_generate;
36 static void random_generate(void *data, int32_t bytes, uint8_t *buff)
37 {
38 struct rgen_data *st=data;
39 int r;
40
41 r= read(st->fd,buff,bytes);
42
43 assert(r == bytes);
44 /* This is totally crap error checking, but callers of
45 * this function do not check the return value and dealing
46 * with failure of this everywhere would be very inconvenient.
47 */
48 }
49
50 static list_t *random_apply(closure_t *self, struct cloc loc,
51 dict_t *context, list_t *args)
52 {
53 struct rgen_data *st;
54 item_t *arg1, *arg2;
55 string_t filename=NULL;
56
57 NEW(st);
58
59 st->cl.description="randomsource";
60 st->cl.type=CL_RANDOMSRC;
61 st->cl.apply=NULL;
62 st->cl.interface=&st->ops;
63 st->ops.st=st;
64 st->ops.blocking=False;
65 st->ops.generate=random_generate;
66 st->loc=loc;
67
68 arg1=list_elem(args,0);
69 arg2=list_elem(args,1);
70
71 if (!arg1) {
72 cfgfatal(loc,"randomsource","requires a filename\n");
73 }
74 if (arg1->type != t_string) {
75 cfgfatal(arg1->loc,"randomsource",
76 "filename (arg1) must be a string\n");
77 }
78 filename=arg1->data.string;
79
80 if (arg2) {
81 if (arg2->type != t_bool) {
82 cfgfatal(arg2->loc,"randomsource",
83 "blocking parameter (arg2) must be bool\n");
84 }
85 st->ops.blocking=arg2->data.bool;
86 }
87
88 if (!filename) {
89 cfgfatal(loc,"randomsource","requires a filename\n");
90 }
91 st->fd=open(filename,O_RDONLY);
92 if (st->fd<0) {
93 fatal_perror("randomsource (%s:%d): cannot open %s",arg1->loc.file,
94 arg1->loc.line,filename);
95 }
96 return new_closure(&st->cl);
97 }
98
99 void random_module(dict_t *d)
100 {
101 add_closure(d,"randomfile",random_apply);
102 }