[3a33812] | 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 | |
---|
[1b39ee5] | 33 | // must start with a letter/number |
---|
| 34 | if (!isalnum(string[0])) return 0; |
---|
| 35 | |
---|
| 36 | // Name must be alphanumeric or - or _ |
---|
| 37 | for (i = 1; string[i] != '\0'; ++i) |
---|
| 38 | if (!isalnum(string[i]) && string[i] != '-' && string[i] != '_') |
---|
[3a33812] | 39 | return 0; |
---|
| 40 | |
---|
| 41 | return 1; |
---|
| 42 | } |
---|
| 43 | |
---|
| 44 | chunk_t creddy_generate_serial() { |
---|
| 45 | chunk_t serial = chunk_empty; |
---|
| 46 | |
---|
| 47 | // create a serial (stolen from strongswan pki) |
---|
| 48 | rng_t *rng = lib->crypto->create_rng(lib->crypto, RNG_WEAK); |
---|
| 49 | if (!rng) |
---|
| 50 | errx(1, "no random number generator"); |
---|
| 51 | |
---|
| 52 | rng->allocate_bytes(rng, 8, &serial); |
---|
| 53 | while (serial.ptr[0] == 0) |
---|
| 54 | // don't get leading 0's |
---|
| 55 | rng->get_bytes(rng, 1, serial.ptr); |
---|
| 56 | rng->destroy(rng); |
---|
| 57 | |
---|
| 58 | return serial; |
---|
| 59 | } |
---|