first check-in of feisty meow codebase. many things broken still due to recent
[feisty_meow.git] / core / library / crypto / ssl_init.cpp
1 /*****************************************************************************\
2 *                                                                             *
3 *  Name   : SSL initialization helper                                         *
4 *  Author : Chris Koeritz                                                     *
5 *                                                                             *
6 *******************************************************************************
7 * Copyright (c) 2005-$now By Author.  This program is free software; you can  *
8 * redistribute it and/or modify it under the terms of the GNU General Public  *
9 * License as published by the Free Software Foundation; either version 2 of   *
10 * the License or (at your option) any later version.  This is online at:      *
11 *     http://www.fsf.org/copyleft/gpl.html                                    *
12 * Please send any updates to: fred@gruntose.com                               *
13 \*****************************************************************************/
14
15 #include "ssl_init.h"
16
17 #include <basis/functions.h>
18 #include <basis/mutex.h>
19 #include <structures/static_memory_gremlin.h>
20
21 #include <openssl/crypto.h>
22 #include <openssl/err.h>
23 #include <openssl/rand.h>
24
25 using namespace basis;
26 using namespace mathematics;
27 using namespace structures;
28
29 namespace crypto {
30
31 #define LOG(s) CLASS_EMERGENCY_LOG(program_wide_logger::get(), s)
32
33 const int SEED_SIZE = 100;
34   // the size of the random seed that we'll use.
35
36 // our global initialization object.
37 SAFE_STATIC_CONST(ssl_init, static_ssl_initializer, )
38
39 //#define DEBUG_SSL
40   // uncomment to cause more debugging information to be generated, plus
41   // more checking to be performed in the SSL support.
42
43 ssl_init::ssl_init()
44 : c_rando()
45 {
46 #ifdef DEBUG_SSL
47   CRYPTO_malloc_debug_init();
48   CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL);
49   CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
50 #endif
51   RAND_seed(random_bytes(SEED_SIZE).observe(), SEED_SIZE);
52 }
53
54 ssl_init::~ssl_init()
55 {
56   CRYPTO_cleanup_all_ex_data();
57   ERR_remove_state(0);
58   CRYPTO_mem_leaks_fp(stderr);
59 }
60
61 const chaos &ssl_init::randomizer() const { return c_rando; }
62
63 byte_array ssl_init::random_bytes(int length) const
64 {
65   byte_array seed;
66   for (int i = 0; i < length; i++)
67     seed += abyte(c_rando.inclusive(0, 255));
68   return seed;
69 }
70
71 } //namespace.
72