Init the format info struct in interactive mode.
[adu.git] / string.c
1 /*
2  * Copyright (C) 2004-2008 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file string.c Memory allocation and string handling functions. */
8
9 #include "adu.h"
10 #include "string.h"
11 #include <string.h>
12 #include "error.h"
13
14 /**
15  * Paraslash's version of realloc().
16  *
17  * \param p Pointer to the memory block, may be \p NULL.
18  * \param size The desired new size.
19  *
20  * A wrapper for realloc(3). It calls \p exit(\p EXIT_FAILURE) on errors,
21  * i.e. there is no need to check the return value in the caller.
22  *
23  * \return A pointer to  the newly allocated memory, which is suitably aligned
24  * for any kind of variable and may be different from \a p.
25  *
26  * \sa realloc(3).
27  */
28 __must_check __malloc void *adu_realloc(void *p, size_t size)
29 {
30         /*
31          * No need to check for NULL pointers: If p is NULL, the  call
32          * to realloc is equivalent to malloc(size)
33          */
34         assert(size);
35         if (!(p = realloc(p, size))) {
36                 EMERG_LOG("realloc failed (size = %zu), aborting\n",
37                         size);
38                 exit(EXIT_FAILURE);
39         }
40         return p;
41 }
42
43 /**
44  * Paraslash's version of malloc().
45  *
46  * \param size The desired new size.
47  *
48  * A wrapper for malloc(3) which exits on errors.
49  *
50  * \return A pointer to the allocated memory, which is suitably aligned for any
51  * kind of variable.
52  *
53  * \sa malloc(3).
54  */
55 __must_check __malloc void *adu_malloc(size_t size)
56 {
57         assert(size);
58         void *p = malloc(size);
59
60         if (!p) {
61                 EMERG_LOG("malloc failed (size = %zu),  aborting\n",
62                         size);
63                 exit(EXIT_FAILURE);
64         }
65         return p;
66 }
67
68 /**
69  * Paraslash's version of calloc().
70  *
71  * \param size The desired new size.
72  *
73  * A wrapper for calloc(3) which exits on errors.
74  *
75  * \return A pointer to the allocated and zeroed-out memory, which is suitably
76  * aligned for any kind of variable.
77  *
78  * \sa calloc(3)
79  */
80 __must_check __malloc void *adu_calloc(size_t size)
81 {
82         void *ret = adu_malloc(size);
83
84         memset(ret, 0, size);
85         return ret;
86 }
87
88 /**
89  * Paraslash's version of strdup().
90  *
91  * \param s The string to be duplicated.
92  *
93  * A wrapper for strdup(3). It calls \p exit(EXIT_FAILURE) on errors, i.e.
94  * there is no need to check the return value in the caller.
95  *
96  * \return A pointer to the duplicated string. If \p s was the NULL pointer,
97  * an pointer to an empty string is returned.
98  *
99  * \sa strdup(3)
100  */
101 __must_check __malloc char *adu_strdup(const char *s)
102 {
103         char *ret;
104
105         if ((ret = strdup(s? s: "")))
106                 return ret;
107         EMERG_LOG("strdup failed, aborting\n");
108         exit(EXIT_FAILURE);
109 }
110
111 /**
112  * Allocate a sufficiently large string and print into it.
113  *
114  * \param fmt A usual format string.
115  *
116  * Produce output according to \p fmt. No artificial bound on the length of the
117  * resulting string is imposed.
118  *
119  * \return This function either returns a pointer to a string that must be
120  * freed by the caller or aborts without returning.
121  *
122  * \sa printf(3).
123  */
124 __must_check __printf_1_2 __malloc char *make_message(const char *fmt, ...)
125 {
126         char *msg;
127
128         VSPRINTF(fmt, msg);
129         return msg;
130 }
131
132 /**
133  * adu's version of strcat().
134  *
135  * \param a String to be appended to.
136  * \param b String to append.
137  *
138  * Append \p b to \p a.
139  *
140  * \return If \a a is \p NULL, return a pointer to a copy of \a b, i.e.
141  * para_strcat(NULL, b) is equivalent to para_strdup(b). If \a b is \p NULL,
142  * return \a a without making a copy of \a a.  Otherwise, construct the
143  * concatenation \a c, free \a a (but not \a b) and return \a c.
144  *
145  * \sa strcat(3).
146  */
147 __must_check __malloc char *adu_strcat(char *a, const char *b)
148 {
149         char *tmp;
150
151         if (!a)
152                 return adu_strdup(b);
153         if (!b)
154                 return a;
155         tmp = make_message("%s%s", a, b);
156         free(a);
157         return tmp;
158 }
159
160 /** \cond LLONG_MAX and LLONG_LIN might not be defined. */
161 #ifndef LLONG_MAX
162 #define LLONG_MAX (1 << (sizeof(long) - 1))
163 #endif
164 #ifndef LLONG_MIN
165 #define LLONG_MIN (-LLONG_MAX - 1LL)
166 #endif
167 /** \endcond */
168
169 /**
170  * Convert a string to a 64-bit signed integer value.
171  *
172  * \param str The string to be converted.
173  * \param value Result pointer.
174  *
175  * \return Standard.
176  *
177  * \sa strtol(3), atoi(3).
178  */
179 __must_check int atoi64(const char *str, int64_t *result)
180 {
181         char *endptr;
182         long long tmp;
183
184         errno = 0; /* To distinguish success/failure after call */
185         tmp = strtoll(str, &endptr, 10);
186         if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
187                 return -E_ATOI_OVERFLOW;
188         if (errno != 0 && tmp == 0) /* other error */
189                 return -E_STRTOLL;
190         if (endptr == str)
191                 return -E_ATOI_NO_DIGITS;
192         if (*endptr != '\0') /* Further characters after number */
193                 return -E_ATOI_JUNK_AT_END;
194         *result = tmp;
195         return 1;
196 }
197
198 /**
199  * Split string and return pointers to its parts.
200  *
201  * \param args The string to be split.
202  * \param argv_ptr Pointer to the list of substrings.
203  * \param delim Delimiter.
204  *
205  * This function modifies \a args by replacing each occurance of \a delim by
206  * zero. A \p NULL-terminated array of pointers to char* is allocated dynamically
207  * and these pointers are initialized to point to the broken-up substrings
208  * within \a args. A pointer to this array is returned via \a argv_ptr.
209  *
210  * \return The number of substrings found in \a args.
211  */
212 __must_check unsigned split_args(char *args, char *** const argv_ptr, const char *delim)
213 {
214         char *p = args;
215         char **argv;
216         size_t n = 0, i, j;
217
218         p = args + strspn(args, delim);
219         for (;;) {
220                 i = strcspn(p, delim);
221                 if (!i)
222                         break;
223                 p += i;
224                 n++;
225                 p += strspn(p, delim);
226         }
227         *argv_ptr = adu_malloc((n + 1) * sizeof(char *));
228         argv = *argv_ptr;
229         i = 0;
230         p = args + strspn(args, delim);
231         while (p) {
232                 argv[i] = p;
233                 j = strcspn(p, delim);
234                 if (!j)
235                         break;
236                 p += strcspn(p, delim);
237                 if (*p) {
238                         *p = '\0';
239                         p++;
240                         p += strspn(p, delim);
241                 }
242                 i++;
243         }
244         argv[n] = NULL;
245         return n;
246 }
247
248 static int check_uid_arg(const char *arg, uint32_t *uid)
249 {
250         const uint32_t max = ~0U;
251         /*
252          * we need an 64-bit int for string -> uid conversion because strtoll()
253          * returns a signed value.
254          */
255         int64_t val;
256         int ret = atoi64(arg, &val);
257
258         if (ret < 0)
259                 return ret;
260         if (val < 0 || val > max)
261                 return -ERRNO_TO_ERROR(EINVAL);
262         *uid = val;
263         return 1;
264 }
265
266 int parse_uid_range(const char *orig_arg, struct uid_range *ur)
267 {
268         int ret;
269         char *arg = adu_strdup(orig_arg), *p = strchr(arg, '-');
270
271         if (!p || p == arg) { /* -42 or 42 */
272                 ret = check_uid_arg(p? p + 1 : arg, &ur->high);
273                 if (ret < 0)
274                         goto out;
275                 ur->low = p? 0 : ur->high;
276                 ret = 1;
277                 goto out;
278         }
279         /* 42- or 42-4711 */
280         *p = '\0';
281         p++;
282         ret = check_uid_arg(arg, &ur->low);
283         if (ret < 0)
284                 goto out;
285         ur->high = ~0U;
286         if (*p) { /* 42-4711 */
287                 ret = check_uid_arg(p, &ur->high);
288                 if (ret < 0)
289                         goto out;
290         }
291         if (ur->low > ur->high)
292                 ret = -ERRNO_TO_ERROR(EINVAL);
293 out:
294         if (ret < 0)
295                 ERROR_LOG("bad uid option: %s\n", orig_arg);
296         else
297                 INFO_LOG("admissible uid range: %u - %u\n", ur->low,
298                         ur->high);
299         free(arg);
300         return ret;
301 }
302
303 int parse_uid_arg(const char *orig_arg, struct uid_range **ur)
304 {
305         char *arg, **argv;
306         unsigned n;
307         int i, ret = 1;
308
309         if (!orig_arg)
310                 return 0;
311         arg = adu_strdup(orig_arg);
312         n = split_args(arg, &argv, ",");
313         if (!n)
314                 return -E_SYNTAX;
315         *ur = adu_malloc((n + 1) * sizeof(struct uid_range));
316         for (i = 0; i < n; i++) {
317                 ret = parse_uid_range(argv[i], *ur + i);
318                 if (ret < 0)
319                         break;
320         }
321         free(argv);
322         free(arg);
323         if (ret < 0) {
324                 free(*ur);
325                 *ur = NULL;
326                 return ret;
327         }
328         /* an empty range indicates the end of the list */
329         (*ur)[n].low = 1;
330         (*ur)[n].high = 0;
331         return n;
332 }
333
334 enum line_state_flags {LSF_HAVE_WORD = 1, LSF_BACKSLASH = 2, LSF_QUOTE = 4};
335
336 static int get_next_word(const char *line, char **word)
337 {
338         const char *in;
339         char *out;
340         int ret, state = 0;
341
342         out = adu_malloc(strlen(line) + 1);
343         *out = '\0';
344         *word = out;
345         for (in = line; *in; in++) {
346                 switch (*in) {
347                 case '\\':
348                         if (state & LSF_BACKSLASH) /* \\ */
349                                 break;
350                         state |= LSF_BACKSLASH;
351                         state |= LSF_HAVE_WORD;
352                         continue;
353                 case 'n':
354                 case 't':
355                         if (state & LSF_BACKSLASH) { /* \n or \t */
356                                 *out++ = (*in == 'n')? '\n' : '\t';
357                                 state &= ~LSF_BACKSLASH;
358                                 continue;
359                         }
360                         break;
361                 case '"':
362                         if (state & LSF_BACKSLASH) /* \" */
363                                 break;
364                         if (state & LSF_QUOTE) {
365                                 state &= ~LSF_QUOTE;
366                                 continue;
367                         }
368                         state |= LSF_HAVE_WORD;
369                         state |= LSF_QUOTE;
370                         continue;
371                 case ' ':
372                 case '\t':
373                 case '\n':
374                         if (state & LSF_BACKSLASH)
375                                 break;
376                         if (state & LSF_QUOTE)
377                                 break;
378                         if (state & LSF_HAVE_WORD)
379                                 goto success;
380                         /* ignore space at the beginning */
381                         continue;
382                 }
383                 /* copy char */
384                 state |= LSF_HAVE_WORD;
385                 *out++ = *in;
386                 state &= ~LSF_BACKSLASH;
387         }
388         ret = 0;
389         if (!(state & LSF_HAVE_WORD))
390                 goto out;
391         ret = -ERRNO_TO_ERROR(EINVAL);
392         if (state & LSF_BACKSLASH) {
393                 ERROR_LOG("trailing backslash\n");
394                 goto out;
395         }
396         if (state & LSF_QUOTE) {
397                 ERROR_LOG("unmatched quote character\n");
398                 goto out;
399         }
400 success:
401         *out = '\0';
402         return in - line;
403 out:
404         free(*word);
405         *word = NULL;
406         return ret;
407 }
408
409 void free_argv(char **argv)
410 {
411         int i;
412
413         for (i = 0; argv[i]; i++)
414                 free(argv[i]);
415         free(argv);
416 }
417
418 /**
419  * \return Number of words in \a line, negative on errors.
420  */
421 int create_argv(const char *line, char ***result)
422 {
423         char *word, **argv = adu_malloc(2 * sizeof(char *));
424         const char *p;
425         int ret, num_words;
426
427         argv[0] = adu_strdup(line);
428         for (p = line, num_words = 1; ; p += ret, num_words++) {
429                 ret = get_next_word(p, &word);
430                 if (ret < 0)
431                         goto err;
432                 if (!ret)
433                         break;
434                 argv = adu_realloc(argv, (num_words + 2) * sizeof(char*));
435                 argv[num_words] = word;
436         }
437         argv[num_words] = NULL;
438         *result = argv;
439         return num_words;
440 err:
441         while (num_words > 0)
442                 free(argv[--num_words]);
443         free(argv);
444         return ret;
445 }