1 | #include <assert.h> |
---|
2 | #include <ctype.h> |
---|
3 | #include <err.h> |
---|
4 | |
---|
5 | #include "libcreddy_common.h" |
---|
6 | |
---|
7 | void *creddy_xmalloc(size_t len) { |
---|
8 | void *ret = malloc(len); |
---|
9 | if (ret == NULL) |
---|
10 | err(1, "couldn't malloc %d bytes\n", len); |
---|
11 | return ret; |
---|
12 | } |
---|
13 | |
---|
14 | void *creddy_xrealloc(void *ptr, size_t size) { |
---|
15 | void *ret = realloc(ptr, size); |
---|
16 | if (ret == NULL) |
---|
17 | err(1, "couldn't realloc %d bytes\n", size); |
---|
18 | return ret; |
---|
19 | } |
---|
20 | |
---|
21 | char *creddy_xstrdup(char *string) { |
---|
22 | char *dup = strdup(string); |
---|
23 | if (dup == NULL) |
---|
24 | err(1, "Can't dup %s", string); |
---|
25 | return dup; |
---|
26 | } |
---|
27 | |
---|
28 | int creddy_clean_name(char *string) { |
---|
29 | int i; |
---|
30 | |
---|
31 | assert(string != NULL); |
---|
32 | |
---|
33 | // Name must be alphanumeric or _ |
---|
34 | for (i = 0; string[i] != '\0'; ++i) |
---|
35 | if (!isalnum(string[i]) && string[i] != '_') |
---|
36 | return 0; |
---|
37 | |
---|
38 | return 1; |
---|
39 | } |
---|
40 | |
---|
41 | chunk_t creddy_generate_serial() { |
---|
42 | chunk_t serial = chunk_empty; |
---|
43 | |
---|
44 | // create a serial (stolen from strongswan pki) |
---|
45 | rng_t *rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK); |
---|
46 | if (!rng) |
---|
47 | errx(1, "no random number generator"); |
---|
48 | |
---|
49 | rng->allocate_bytes(rng, 8, &serial); |
---|
50 | while (serial.ptr[0] == 0) |
---|
51 | // don't get leading 0's |
---|
52 | rng->get_bytes(rng, 1, serial.ptr); |
---|
53 | rng->destroy(rng); |
---|
54 | |
---|
55 | return serial; |
---|
56 | } |
---|
57 | |
---|
58 | void creddy_init(void) { |
---|
59 | static int has_been_init = 0; |
---|
60 | |
---|
61 | if (has_been_init) |
---|
62 | return; |
---|
63 | |
---|
64 | // silence all debugging |
---|
65 | dbg_default_set_level(-1); |
---|
66 | |
---|
67 | if (!library_init(NULL)) |
---|
68 | exit(SS_RC_LIBSTRONGSWAN_INTEGRITY); |
---|
69 | |
---|
70 | if (!lib->plugins->load(lib->plugins, NULL, |
---|
71 | lib->settings->get_str(lib->settings, "pki.load", PLUGINS))) |
---|
72 | exit(SS_RC_INITIALIZATION_FAILED); |
---|
73 | |
---|
74 | atexit(library_deinit); |
---|
75 | |
---|
76 | has_been_init = 1; |
---|
77 | } |
---|