source: libabac/abac_util.c @ 63dcd99

abac0-leak
Last change on this file since 63dcd99 was 1bf0f03, checked in by Mei <mei@…>, 11 years ago

1) save a copy before fixup of tests directory

  • Property mode set to 100644
File size: 1.9 KB
Line 
1
2/* abac_util.c */
3
4#include <err.h>
5#include <stdlib.h>
6#include <string.h>
7#include <assert.h>
8#include <ctype.h>
9
10/**
11 * Malloc, fatal on error.
12 */
13void *abac_xmalloc(size_t size) {
14    void *ret;
15   
16    ret = malloc(size);
17    if (ret == NULL)
18        err(1, "malloc");
19
20    return ret;
21}
22
23/**
24 * strdup fatal on error
25 */
26char *abac_xstrdup(char *source) {
27    char *ret;
28
29    if (source == NULL)
30        return NULL;
31
32    ret = strdup(source);
33    if (ret == NULL)
34        err(1, "strdup");
35
36    return ret;
37}
38
39void *abac_xrealloc(void *ptr, size_t size) {
40    void *ret = realloc(ptr, size);
41    if (ret == NULL)
42        err(1, "couldn't realloc %zu bytes\n", size);
43    return ret;
44}
45
46/**
47 * Split a string based on the given delimiter.  The substrings are pointers
48 * into string, which has string terminators added to slice it into substrings.
49 * Do not free the returned substrings.  num passes in the maximum number of
50 * substrings to create and is returned as the number actually created.
51 */
52#define MAXSPLIT    1024
53void abac_split(char *string, char *delim, char **ret, int *num) {
54    int len = strlen(delim);
55    char *start = string;
56    int count = 0;
57    int lim = (num && *num > 0) ? *num : MAXSPLIT;
58
59    // split the string by the delim.  Split into at most lim parts
60    while ((start = strstr(string, delim)) != NULL && count < lim-1) {
61        *start = 0;
62        ret[count++] = string;
63        string = start + len;
64    }
65    ret[count++] = string;
66
67    *num = count;
68}
69
70int abac_clean_name(char *string) {
71    int i;
72
73    assert(string != NULL);
74
75    // must start with a letter/number
76    if (!isalnum(string[0])) return 0;
77
78    // Name must be alphanumeric or - or _ or :
79    for (i = 1; string[i] != '\0'; ++i)
80        if (!isalnum(string[i]) && string[i] != '-' && string[i] != '_' &&
81                string[i] != ':')
82            return 0;
83
84    return 1;
85}
86
Note: See TracBrowser for help on using the repository browser.