aboutsummaryrefslogtreecommitdiff
path: root/tests/torture_pki.c
blob: 07c0109476e09965d3e08c9a6b8d12447cf422a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include "torture_pki.h"

char *torture_pki_read_file(const char *filename)
{
    char *key;
    int fd;
    int size;
    int rc;
    struct stat sb;

    if (filename == NULL || filename[0] == '\0') {
        return NULL;
    }

    fd = open(filename, O_RDONLY);
    if (fd < 0) {
        return NULL;
    }

    rc = fstat(fd, &sb);
    if (rc != 0) {
        close(fd);
        return NULL;
    }

    key = malloc(sb.st_size + 1);
    if (key == NULL) {
        close(fd);
        return NULL;
    }

    size = read(fd, key, sb.st_size);
    close(fd);
    if (size != sb.st_size) {
        free(key);
        return NULL;
    }

    key[size] = '\0';
    return key;
}

int torture_read_one_line(const char *filename, char *buffer, size_t len)
{
    FILE *fp;
    size_t nmemb;

    fp = fopen(filename, "r");
    if (fp == NULL) {
        return -1;
    }

    nmemb = fread(buffer, len - 2, 1, fp);
    if (nmemb != 0 || ferror(fp)) {
        fclose(fp);
        return -1;
    }
    buffer[len - 1] = '\0';

    fclose(fp);

    return 0;
}

/**
 * @internal
 *
 * Returns the character len of a public key string, omitting the comment part
 */
size_t torture_pubkey_len(const char *pubkey)
{
    const char *ptr;

    ptr = strchr(pubkey, ' ');
    if (ptr != NULL) {
        ptr = strchr(ptr + 1, ' ');
        if (ptr != NULL) {
            return ptr - pubkey;
        }
    }

    return 0;
}