monotone

monotone Mtn Source Tree

Root/botan/es_egd.cpp

1/*************************************************
2* EGD EntropySource Source File *
3* (C) 1999-2007 The Botan Project *
4*************************************************/
5
6#include <botan/es_egd.h>
7#include <botan/config.h>
8#include <botan/bit_ops.h>
9#include <botan/parsing.h>
10#include <cstring>
11
12#include <sys/types.h>
13#include <sys/socket.h>
14#include <sys/un.h>
15#include <unistd.h>
16
17#ifndef PF_LOCAL
18 #define PF_LOCAL PF_UNIX
19#endif
20
21namespace Botan {
22
23/*************************************************
24* EGD_EntropySource Constructor *
25*************************************************/
26EGD_EntropySource::EGD_EntropySource(const std::string& egd_paths)
27 {
28 std::vector<std::string> path_list = split_on(egd_paths, ':');
29 std::vector<std::string> defaults =
30 global_config().option_as_list("rng/egd_path");
31
32 for(u32bit j = 0; j != path_list.size(); j++)
33 paths.push_back(path_list[j]);
34 for(u32bit j = 0; j != defaults.size(); j++)
35 paths.push_back(defaults[j]);
36 }
37
38/*************************************************
39* Gather Entropy from EGD *
40*************************************************/
41u32bit EGD_EntropySource::do_poll(byte output[], u32bit length,
42 const std::string& path) const
43 {
44 if(length > 128)
45 length = 128;
46
47 sockaddr_un addr;
48 std::memset(&addr, 0, sizeof(addr));
49 addr.sun_family = PF_LOCAL;
50
51 if(sizeof(addr.sun_path) < path.length() + 1)
52 throw Exception("EGD_EntropySource: Socket path is too long");
53 std::strcpy(addr.sun_path, path.c_str());
54
55 int fd = ::socket(addr.sun_family, SOCK_STREAM, 0);
56 if(fd == -1) return 0;
57
58 int len = sizeof(addr.sun_family) + std::strlen(addr.sun_path) + 1;
59 if(::connect(fd, reinterpret_cast<struct ::sockaddr*>(&addr), len))
60 { ::close(fd); return 0; }
61
62 byte buffer[2];
63 buffer[0] = 1;
64 buffer[1] = static_cast<byte>(length);
65
66 if(::write(fd, buffer, 2) != 2) { ::close(fd); return 0; }
67 if(::read(fd, buffer, 1) != 1) { ::close(fd); return 0; }
68
69 ssize_t count = ::read(fd, output, buffer[0]);
70
71 if(count == -1) { close(fd); return 0; }
72
73 ::close(fd);
74
75 return count;
76 }
77
78/*************************************************
79* Gather Entropy from EGD *
80*************************************************/
81u32bit EGD_EntropySource::slow_poll(byte output[], u32bit length)
82 {
83 for(u32bit j = 0; j != paths.size(); j++)
84 {
85 u32bit got = do_poll(output, length, paths[j]);
86 if(got)
87 return got;
88 }
89 return 0;
90 }
91
92}

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status