Makefile.in: Drop dist target
[secnet] / random.c
CommitLineData
c215a4bc
IJ
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
9c6a8729 7 * the Free Software Foundation; either version 3 of the License, or
c215a4bc
IJ
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
8689b3a9 20#include "secnet.h"
2fe58dfd
SE
21#include <stdio.h>
22#include <fcntl.h>
23#include <string.h>
2fe58dfd
SE
24#include <sys/stat.h>
25#include <unistd.h>
4f5e39ec 26#include <assert.h>
2fe58dfd 27
2fe58dfd
SE
28struct rgen_data {
29 closure_t cl;
30 struct random_if ops;
31 struct cloc loc;
32 int fd;
33};
34
35static random_fn random_generate;
e3f13757 36static void random_generate(void *data, int32_t bytes, uint8_t *buff)
2fe58dfd
SE
37{
38 struct rgen_data *st=data;
4f5e39ec 39 int r;
2fe58dfd 40
4f5e39ec
SE
41 r= read(st->fd,buff,bytes);
42
43 assert(r == bytes);
e3f13757
IJ
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.
4f5e39ec 47 */
2fe58dfd
SE
48}
49
50static 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
b7886fd4 57 NEW(st);
2fe58dfd
SE
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) {
4f5e39ec 72 cfgfatal(loc,"randomsource","requires a filename\n");
2fe58dfd
SE
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) {
4f5e39ec 89 cfgfatal(loc,"randomsource","requires a filename\n");
2fe58dfd
SE
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
99void random_module(dict_t *d)
100{
101 add_closure(d,"randomfile",random_apply);
102}