File: egd-linux.c

package info (click to toggle)
ekeyd 1.1.3-3
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 628 kB
  • ctags: 859
  • sloc: ansic: 5,189; sh: 271; makefile: 199; perl: 148
file content (365 lines) | stat: -rw-r--r-- 9,393 bytes parent folder | download
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/* daemon/egd-linux.c
 *
 * Stand-alone EGD => Linux pool entropy transfer agent.
 *
 * Copyright 2009 Simtec Electronics.
 * Copyrithg 2010 Collabora Ltd
 *
 * For licence terms refer to the COPYING file.
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>

#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdbool.h>
#include <poll.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <syslog.h>

#include <linux/types.h>
#include <linux/random.h>
#include <sys/ioctl.h>

#include "daemonise.h"

#define DEFAULT_HOST "127.0.0.1"
#define DEFAULT_PORT "8888"

static const char *pidfilename = NULL;
static int random_fd = 0;
static int egd_fd = -1;
static int shannons = 7;
static unsigned int retry_time = 0;
static char *host;
static char *port;

struct pollfd poll_fds[2] = {
    { .events = POLLOUT },
    { .events = POLLIN }
};

#define RND_POLLFD 0
#define EGD_POLLFD 1

static int bytes_waiting = 0;

static void
usage(FILE *stream, char **argv)
{
    fprintf(stream,
            "%s: Usage:\n"                                              \
            "\n"                                                        \
            "%s [options]\n"                                            \
            "\n"                                                        \
            "Valid options are:\n"                                      \
            "\t-h\tDisplay this help.\n"                                \
            "\t-v\tDisplay the version of this program.\n"              \
            "\t-H <host>\tSet the host IP address to connect to.\n"     \
            "\t-p <postnr>\tSet the port number to connect to.\n"       \
            "\t-b <blocks>\tSet the number of 1024 bit blocks to request each time.\n" \
            "\t-s <S>\tSet the number of shannons per byte to S.\n" \
            "\t-D <pidf>\tDaemonise, writing PID to pidf.\n" \
            "\t-r <time>\tRetry connection every time seconds.\n",
            argv[0], argv[0]);
}

static bool
try_open_random(void)
{
    random_fd = open("/dev/random", O_RDWR);
    poll_fds[RND_POLLFD].fd = random_fd;
    return (random_fd != -1);
}

static void
set_egd_blocking(bool block)
{
    int flags;
    if ((flags = fcntl(egd_fd, F_GETFL)) == -1)
        perror("fcntl");
    flags &= ~(O_NONBLOCK);
    if (block == false)
        flags |= O_NONBLOCK;
    if (fcntl(egd_fd, F_SETFL, flags) == -1)
        perror("fcntl");
}

/** attempt to connect to an EGD server.
 *
 * Create a socket and connect it to an EGD server.
 *
 * @param rtime The time between retry attempts, 0 for no retrys.
 * @return true if the connection was sucessful, false if it was not.
 */
static bool
egd_connect(unsigned int rtime)
{
    int con_res = -1;
    int keepalive = 1;
    socklen_t keepalive_len = sizeof(keepalive);
    struct addrinfo *addrs, *addrs_head;
    struct addrinfo hints;
    int r;

    /* Look up port and address */
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_ADDRCONFIG | AI_V4MAPPED;

    if ((r = getaddrinfo(host, port, &hints, &addrs)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(r));
        return false;
    }

    addrs_head = addrs;
    do {
        while (addrs) {
            /* close fd if we already have one open */
            if (egd_fd >= 0) {
                close(egd_fd);
            }
            
            /* create socket */
            egd_fd = socket(addrs->ai_family, addrs->ai_socktype, addrs->ai_protocol);
            if (egd_fd == -1) {
                perror("socket");
            return false;
            }

            /* Set the keepalive option active */
            if (setsockopt(egd_fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, keepalive_len) < 0) {
                perror("setsockopt");
            }

            con_res = connect(egd_fd, addrs->ai_addr, addrs->ai_addrlen);
            if (con_res == 0) {
                rtime = 0; /* get out of outer loop */
                break;
            }
            addrs = addrs->ai_next;
        }
        if (rtime != 0) {
            sleep(rtime);
            fprintf(stderr, "Retrying connection.\n");
        }
        addrs = addrs_head;
    } while (rtime != 0);
    freeaddrinfo(addrs_head);

    /* Set the keepalive option active */
    if (setsockopt(egd_fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, keepalive_len) < 0) {
        perror("setsockopt");
    }

    if (con_res != 0) {
        perror("connect");
        close(egd_fd);
        egd_fd = -1;
        return false;
    }

    poll_fds[EGD_POLLFD].fd = egd_fd;

    /* ensure the random pool state is reset */
    bytes_waiting = 0;
    poll_fds[RND_POLLFD].events = POLLOUT;

    return true;
}


static void
issue_read_for_random(int nblocks)
{
    set_egd_blocking(true);
    bytes_waiting += nblocks * 128;
    while (nblocks--)
        if (write(egd_fd, (const void *)"\x02\x80", 2) != 2) {
            perror("write");
            bytes_waiting = 0;
            return;
        }
    set_egd_blocking(false);
}

static void
punt_entropy(void)
{
    static unsigned char buffer[128];
    struct rand_pool_info *rndpool;
    int bread;

    bread = read(egd_fd, buffer, 128);
    if (bread < 0) {
        perror("read");
        exit(1);
    }

    if (bread == 0) {
        /* EOF on the EGD socket is never good, reset the world */
        fprintf(stderr, "EGD Client Daemon reconnecting to server\n");
        syslog(LOG_ERR, "Reconnecting to EGD server");
        if (egd_connect(retry_time) == false) {
            exit(1);
        }
        return;
    }

    rndpool = alloca(sizeof(struct rand_pool_info) + bread);

    rndpool->entropy_count = bread * shannons;
    rndpool->buf_size = bread;
    memcpy(rndpool->buf, buffer, bread);

    if (ioctl(random_fd, RNDADDENTROPY, rndpool) == -1) {
        perror("ioctl");
        exit(1);
    }

    bytes_waiting -= bread;
    if (bytes_waiting == 0) {
        poll_fds[0].events = POLLOUT;
    }
}

int
main(int argc, char **argv)
{
    int opt;
    bool daemonise = false;
    int blocks = 4;

    /* setup default host address */
    host = DEFAULT_HOST;
    port = DEFAULT_PORT;

    /* command line option parsing */
    while ((opt = getopt(argc, argv, "vhH:p:D:b:S:r:")) != -1) {
        switch (opt) {
        case 'v':
            printf("%s: Version 1.1\n", argv[0]);
            return 0;
            break;

        case 'h':
            usage(stdout, argv);
            return 0;
            break;

        case 'H':
            host = strdup(optarg);
            break;

        case 'p':
            port = strdup(optarg);
            break;

        case 'D':
            daemonise = true;
            pidfilename = optarg;
            break;

        case 'b':
            blocks = atoi(optarg);
            if (blocks < 1 || blocks > 4) {
                fprintf(stderr, "Reading %d blocks makes no sense\n", blocks);
                return 1;
            }
            break;

        case 'S':
            shannons = atoi(optarg);
            if (shannons < 1 || shannons > 8) {
                fprintf(stderr, "Claiming %d shannons per byte is pointless.\n", shannons);
                return 1;
            }
            break;

        case 'r':
            retry_time = strtoul(optarg, NULL, 10);
            break;

        default:
            usage(stderr, argv);
            return 1;
            break;
        }
    }

    if (try_open_random() == false) {
        fprintf(stderr, "Unable to open /dev/random for writing\n");
        return 1;
    }

    /* try initial connect to EGD server */
    egd_connect(0);
    if ((retry_time == 0) && (egd_fd == -1)) {
        fprintf(stderr, "Unable to connect to EGD server.\n");
        return 1;
    }

    if (daemonise)
        do_daemonise(pidfilename);

    /* now we are a daemon, start system logging */
    openlog("ekey-egd-linux", LOG_ODELAY, LOG_DAEMON);

    syslog(LOG_INFO, "Starting EGD Client Daemon");

    /* retry EGD server connection if necessary */
    if (egd_fd == -1)
        egd_connect(retry_time);

    /* ignore pipe signal */
    signal(SIGPIPE, SIG_IGN);

    /* Main poll for activity */
    for (int ret = 0; (ret != -1) || (errno == EINTR); ret = poll(poll_fds, 2, -1)) {
      
        if (poll_fds[RND_POLLFD].revents & (POLLERR | POLLHUP | POLLNVAL)) {
            syslog(LOG_INFO, "Linux random device poll error");
            break;
        }

        if (poll_fds[EGD_POLLFD].revents & (POLLERR | POLLHUP | POLLNVAL)) {
            if (retry_time != 0) {
                syslog(LOG_INFO, "EGD server poll error, reconnecting");
                sleep(retry_time);
                egd_connect(retry_time);
                continue;
            } else {
                syslog(LOG_ERR, "EGD server poll error");
                break;
            }
        }

        if (poll_fds[RND_POLLFD].revents & POLLOUT) {
            poll_fds[RND_POLLFD].events = 0;
            issue_read_for_random(blocks);
        }

        if (poll_fds[EGD_POLLFD].revents & POLLIN) {
            punt_entropy();
        }

    }

    if (egd_fd != -1)
        close(egd_fd);

    close(random_fd);

    syslog(LOG_INFO, "EGD Client Daemon Stopping");

    return 0;
}