aboutsummaryrefslogtreecommitdiff
path: root/util.c
blob: 7ec62badeb33c31965ce493ea62c49170e745e10 (plain) (blame)
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
/* See LICENSE file for copyright and license details. */
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>

#include "util.h"

void
die(const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	vfprintf(stderr, fmt, ap);
	va_end(ap);

	if (fmt[0] && fmt[strlen(fmt)-1] == ':') {
		fputc(' ', stderr);
		perror(NULL);
	} else {
		fputc('\n', stderr);
	}

	exit(1);
}

void *
ecalloc(size_t nmemb, size_t size)
{
	void *p;

	if (!(p = calloc(nmemb, size)))
		die("calloc:");
	return p;
}

int
reMatch(const char *regex, const char *str) {
    char reErr[1024] = {0};
    regex_t *re = calloc(1, sizeof(regex_t));
    int rc = 0;

    if (!re)
        return -1;

    rc = regcomp(re, regex, REG_EXTENDED|REG_ICASE|REG_NOSUB);
    if (rc != 0) {
        regerror(rc, re, reErr, 1024);
		regfree(re); re = NULL;
        fprintf(stderr, "Regex compile err: %s %s\n", regex, reErr);
        return -1;
    }

    rc = regexec(re, str, 0, NULL, 0);
    regfree(re); re = NULL;
    if (rc != 0) {
        regerror(rc, re, reErr, 1024);
        fprintf(stderr, "Regex match error: %s -> %s : %s\n",
                regex, str, reErr);
        return -1;
    }

    return rc;
}

int
readEnv(FILE *fh)
{
	int ret;
	char *name = alloca(1024*sizeof(char)), *value = alloca(8192*sizeof(char));

	while (1) {
		if ((ret = fscanf(fh, "%1023[^=]=%8191[^\n]\n", name, value)) == EOF)
			break;
		else if (ret == 0)
			break;

		fprintf(stderr, "Setting: '%s' = '%s'\n", name, value);
		setenv(name, value, 1);
	}

	return 0;
}