Return to random_rng.c CVS log | Up to [ELWIX - Embedded LightWeight unIX -] / embedaddon / strongswan / src / libstrongswan / plugins / random |
1.1 misho 1: /* 2: * Copyright (C) 2005-2008 Martin Willi 3: * Copyright (C) 2005 Jan Hutter 4: * HSR Hochschule fuer Technik Rapperswil 5: * 6: * This program is free software; you can redistribute it and/or modify it 7: * under the terms of the GNU General Public License as published by the 8: * Free Software Foundation; either version 2 of the License, or (at your 9: * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. 10: * 11: * This program is distributed in the hope that it will be useful, but 12: * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 13: * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14: * for more details. 15: */ 16: 17: #include <string.h> 18: #include <unistd.h> 19: #include <errno.h> 20: #include <utils/debug.h> 21: 22: #include "random_rng.h" 23: #include "random_plugin.h" 24: 25: typedef struct private_random_rng_t private_random_rng_t; 26: 27: /** 28: * Private data of an random_rng_t object. 29: */ 30: struct private_random_rng_t { 31: 32: /** 33: * Public random_rng_t interface. 34: */ 35: random_rng_t public; 36: 37: /** 38: * random device, depends on quality 39: */ 40: int fd; 41: }; 42: 43: METHOD(rng_t, get_bytes, bool, 44: private_random_rng_t *this, size_t bytes, uint8_t *buffer) 45: { 46: size_t done; 47: ssize_t got; 48: 49: done = 0; 50: 51: while (done < bytes) 52: { 53: got = read(this->fd, buffer + done, bytes - done); 54: if (got <= 0) 55: { 56: DBG1(DBG_LIB, "reading from random FD %d failed: %s, retrying...", 57: this->fd, strerror(errno)); 58: sleep(1); 59: continue; 60: } 61: done += got; 62: } 63: return TRUE; 64: } 65: 66: METHOD(rng_t, allocate_bytes, bool, 67: private_random_rng_t *this, size_t bytes, chunk_t *chunk) 68: { 69: *chunk = chunk_alloc(bytes); 70: get_bytes(this, chunk->len, chunk->ptr); 71: return TRUE; 72: } 73: 74: METHOD(rng_t, destroy, void, 75: private_random_rng_t *this) 76: { 77: free(this); 78: } 79: 80: /* 81: * Described in header. 82: */ 83: random_rng_t *random_rng_create(rng_quality_t quality) 84: { 85: private_random_rng_t *this; 86: 87: INIT(this, 88: .public = { 89: .rng = { 90: .get_bytes = _get_bytes, 91: .allocate_bytes = _allocate_bytes, 92: .destroy = _destroy, 93: }, 94: }, 95: ); 96: 97: switch (quality) 98: { 99: case RNG_TRUE: 100: this->fd = random_plugin_get_dev_random(); 101: break; 102: case RNG_STRONG: 103: this->fd = random_plugin_get_strong_equals_true() ? 104: random_plugin_get_dev_random() : 105: random_plugin_get_dev_urandom(); 106: break; 107: case RNG_WEAK: 108: default: 109: this->fd = random_plugin_get_dev_urandom(); 110: break; 111: } 112: 113: return &this->public; 114: } 115: