string: Clean up for_each_line() and related functions.
[paraslash.git] / string.c
1 /*
2 * Copyright (C) 2004-2013 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 <sys/time.h> /* gettimeofday */
10 #include <pwd.h>
11 #include <sys/utsname.h> /* uname() */
12 #include <string.h>
13 #include <regex.h>
14
15 #include "para.h"
16 #include "string.h"
17 #include "error.h"
18
19 /**
20 * Paraslash's version of realloc().
21 *
22 * \param p Pointer to the memory block, may be \p NULL.
23 * \param size The desired new size.
24 *
25 * A wrapper for realloc(3). It calls \p exit(\p EXIT_FAILURE) on errors,
26 * i.e. there is no need to check the return value in the caller.
27 *
28 * \return A pointer to the newly allocated memory, which is suitably aligned
29 * for any kind of variable and may be different from \a p.
30 *
31 * \sa realloc(3).
32 */
33 __must_check __malloc void *para_realloc(void *p, size_t size)
34 {
35 /*
36 * No need to check for NULL pointers: If p is NULL, the call
37 * to realloc is equivalent to malloc(size)
38 */
39 assert(size);
40 if (!(p = realloc(p, size))) {
41 PARA_EMERG_LOG("realloc failed (size = %zu), aborting\n",
42 size);
43 exit(EXIT_FAILURE);
44 }
45 return p;
46 }
47
48 /**
49 * Paraslash's version of malloc().
50 *
51 * \param size The desired new size.
52 *
53 * A wrapper for malloc(3) which exits on errors.
54 *
55 * \return A pointer to the allocated memory, which is suitably aligned for any
56 * kind of variable.
57 *
58 * \sa malloc(3).
59 */
60 __must_check __malloc void *para_malloc(size_t size)
61 {
62 void *p;
63
64 assert(size);
65 p = malloc(size);
66 if (!p) {
67 PARA_EMERG_LOG("malloc failed (size = %zu), aborting\n",
68 size);
69 exit(EXIT_FAILURE);
70 }
71 return p;
72 }
73
74 /**
75 * Paraslash's version of calloc().
76 *
77 * \param size The desired new size.
78 *
79 * A wrapper for calloc(3) which exits on errors.
80 *
81 * \return A pointer to the allocated and zeroed-out memory, which is suitably
82 * aligned for any kind of variable.
83 *
84 * \sa calloc(3)
85 */
86 __must_check __malloc void *para_calloc(size_t size)
87 {
88 void *ret = para_malloc(size);
89
90 memset(ret, 0, size);
91 return ret;
92 }
93
94 /**
95 * Paraslash's version of strdup().
96 *
97 * \param s The string to be duplicated.
98 *
99 * A wrapper for strdup(3). It calls \p exit(EXIT_FAILURE) on errors, i.e.
100 * there is no need to check the return value in the caller.
101 *
102 * \return A pointer to the duplicated string. If \a s was the \p NULL pointer,
103 * an pointer to an empty string is returned.
104 *
105 * \sa strdup(3)
106 */
107 __must_check __malloc char *para_strdup(const char *s)
108 {
109 char *ret;
110
111 if ((ret = strdup(s? s: "")))
112 return ret;
113 PARA_EMERG_LOG("strdup failed, aborting\n");
114 exit(EXIT_FAILURE);
115 }
116
117 /**
118 * Print a formated message to a dynamically allocated string.
119 *
120 * \param result The formated string is returned here.
121 * \param fmt The format string.
122 * \param ap Initialized list of arguments.
123 *
124 * This function is similar to vasprintf(), a GNU extension which is not in C
125 * or POSIX. It allocates a string large enough to hold the output including
126 * the terminating null byte. The allocated string is returned via the first
127 * argument and must be freed by the caller. However, unlike vasprintf(), this
128 * function calls exit() if insufficient memory is available, while vasprintf()
129 * returns -1 in this case.
130 *
131 * \return Number of bytes written, not including the terminating \p NULL
132 * character.
133 *
134 * \sa printf(3), vsnprintf(3), va_start(3), vasprintf(3), \ref xasprintf().
135 */
136 __printf_2_0 unsigned xvasprintf(char **result, const char *fmt, va_list ap)
137 {
138 int ret;
139 size_t size;
140 va_list aq;
141
142 va_copy(aq, ap);
143 ret = vsnprintf(NULL, 0, fmt, aq);
144 va_end(aq);
145 assert(ret >= 0);
146 size = ret + 1;
147 *result = para_malloc(size);
148 va_copy(aq, ap);
149 ret = vsnprintf(*result, size, fmt, aq);
150 va_end(aq);
151 assert(ret >= 0 && ret < size);
152 return ret;
153 }
154
155 /**
156 * Print to a dynamically allocated string, variable number of arguments.
157 *
158 * \param result See \ref xvasprintf().
159 * \param fmt Usual format string.
160 *
161 * \return The return value of the underlying call to \ref xvasprintf().
162 *
163 * \sa \ref xvasprintf() and the references mentioned there.
164 */
165 __printf_2_3 unsigned xasprintf(char **result, const char *fmt, ...)
166 {
167 va_list ap;
168 unsigned ret;
169
170 va_start(ap, fmt);
171 ret = xvasprintf(result, fmt, ap);
172 va_end(ap);
173 return ret;
174 }
175
176 /**
177 * Allocate a sufficiently large string and print into it.
178 *
179 * \param fmt A usual format string.
180 *
181 * Produce output according to \p fmt. No artificial bound on the length of the
182 * resulting string is imposed.
183 *
184 * \return This function either returns a pointer to a string that must be
185 * freed by the caller or aborts without returning.
186 *
187 * \sa printf(3), xasprintf().
188 */
189 __must_check __printf_1_2 __malloc char *make_message(const char *fmt, ...)
190 {
191 char *msg;
192 va_list ap;
193
194 va_start(ap, fmt);
195 xvasprintf(&msg, fmt, ap);
196 va_end(ap);
197 return msg;
198 }
199
200 /**
201 * Free the content of a pointer and set it to \p NULL.
202 *
203 * This is equivalent to "free(*arg); *arg = NULL;".
204 *
205 * \param arg The pointer whose content should be freed.
206 */
207 void freep(void *arg)
208 {
209 void **ptr = (void **)arg;
210 free(*ptr);
211 *ptr = NULL;
212 }
213
214 /**
215 * Paraslash's version of strcat().
216 *
217 * \param a String to be appended to.
218 * \param b String to append.
219 *
220 * Append \p b to \p a.
221 *
222 * \return If \a a is \p NULL, return a pointer to a copy of \a b, i.e.
223 * para_strcat(NULL, b) is equivalent to para_strdup(b). If \a b is \p NULL,
224 * return \a a without making a copy of \a a. Otherwise, construct the
225 * concatenation \a c, free \a a (but not \a b) and return \a c.
226 *
227 * \sa strcat(3)
228 */
229 __must_check __malloc char *para_strcat(char *a, const char *b)
230 {
231 char *tmp;
232
233 if (!a)
234 return para_strdup(b);
235 if (!b)
236 return a;
237 tmp = make_message("%s%s", a, b);
238 free(a);
239 return tmp;
240 }
241
242 /**
243 * Paraslash's version of dirname().
244 *
245 * \param name Pointer to the full path.
246 *
247 * Compute the directory component of \p name.
248 *
249 * \return If \a name is \p NULL or the empty string, return \p NULL.
250 * Otherwise, Make a copy of \a name and return its directory component. Caller
251 * is responsible to free the result.
252 */
253 __must_check __malloc char *para_dirname(const char *name)
254 {
255 char *p, *ret;
256
257 if (!name || !*name)
258 return NULL;
259 ret = para_strdup(name);
260 p = strrchr(ret, '/');
261 if (!p)
262 *ret = '\0';
263 else
264 *p = '\0';
265 return ret;
266 }
267
268 /**
269 * Paraslash's version of basename().
270 *
271 * \param name Pointer to the full path.
272 *
273 * Compute the filename component of \a name.
274 *
275 * \return \p NULL if (a) \a name is the empty string or \p NULL, or (b) name
276 * ends with a slash. Otherwise, a pointer within \a name is returned. Caller
277 * must not free the result.
278 */
279 __must_check char *para_basename(const char *name)
280 {
281 char *ret;
282
283 if (!name || !*name)
284 return NULL;
285 ret = strrchr(name, '/');
286 if (!ret)
287 return (char *)name;
288 ret++;
289 return ret;
290 }
291
292 /**
293 * Cut trailing newline.
294 *
295 * \param buf The string to be chopped.
296 *
297 * Replace the last character in \p buf by zero if it is equal to
298 * the newline character.
299 */
300 void chop(char *buf)
301 {
302 int n = strlen(buf);
303
304 if (!n)
305 return;
306 if (buf[n - 1] == '\n')
307 buf[n - 1] = '\0';
308 }
309
310 /**
311 * Get the logname of the current user.
312 *
313 * \return A dynamically allocated string that must be freed by the caller. On
314 * errors, the string "unknown_user" is returned, i.e. this function never
315 * returns \p NULL.
316 *
317 * \sa getpwuid(3).
318 */
319 __must_check __malloc char *para_logname(void)
320 {
321 struct passwd *pw = getpwuid(getuid());
322 return para_strdup(pw? pw->pw_name : "unknown_user");
323 }
324
325 /**
326 * Get the home directory of the current user.
327 *
328 * \return A dynamically allocated string that must be freed by the caller. If
329 * the home directory could not be found, this function returns "/tmp".
330 */
331 __must_check __malloc char *para_homedir(void)
332 {
333 struct passwd *pw = getpwuid(getuid());
334 return para_strdup(pw? pw->pw_dir : "/tmp");
335 }
336
337 /**
338 * Get the own hostname.
339 *
340 * \return A dynamically allocated string containing the hostname.
341 *
342 * \sa uname(2).
343 */
344 __malloc char *para_hostname(void)
345 {
346 struct utsname u;
347
348 uname(&u);
349 return para_strdup(u.nodename);
350 }
351
352 /**
353 * Call a custom function for each complete line.
354 *
355 * \param flags Any combination of flags defined in \ref for_each_line_flags.
356 * \param buf The buffer containing data separated by newlines.
357 * \param size The number of bytes in \a buf.
358 * \param line_handler The custom function.
359 * \param private_data Pointer passed to \a line_handler.
360 *
361 * If \p line_handler is \p NULL, the function returns the number of complete
362 * lines in \p buf.
363 *
364 * Otherwise, \p line_handler is called for each complete line in \p buf. The
365 * first argument to \p line_handler is (a copy of) the current line, and \p
366 * private_data is passed as the second argument. If the \p FELF_READ_ONLY
367 * flag is unset, a pointer into \a buf is passed to the line handler,
368 * otherwise a pointer to a copy of each line is passed instead. This copy is
369 * freed immediately after the line handler returns.
370 *
371 * The function returns if \p line_handler returns a negative value or no more
372 * lines are in the buffer. The rest of the buffer (last chunk containing an
373 * incomplete line) is moved to the beginning of the buffer if FELF_READ_ONLY is
374 * unset.
375 *
376 * \return If \p line_handler is not \p NULL and FELF_READ_ONLY is not set,
377 * this function returns the number of bytes not handled to \p line_handler,
378 * otherwise number of complete lines. On errors the negative error code of
379 * the \p line_handler is returned.
380 *
381 * \sa \ref for_each_line_flags.
382 */
383 int for_each_line(unsigned flags, char *buf, size_t size,
384 line_handler_t *line_handler, void *private_data)
385 {
386 char *start = buf, *end;
387 int ret, i, num_lines = 0;
388
389 // PARA_NOTICE_LOG("buf: %s\n", buf);
390 while (start < buf + size) {
391 char *next_null;
392 char *next_cr;
393
394 next_cr = memchr(start, '\n', buf + size - start);
395 next_null = memchr(start, '\0', buf + size - start);
396 if (!next_cr && !next_null)
397 break;
398 if (next_cr && next_null) {
399 end = next_cr < next_null? next_cr : next_null;
400 } else if (next_null) {
401 end = next_null;
402 } else
403 end = next_cr;
404 num_lines++;
405 if (!line_handler) {
406 start = ++end;
407 continue;
408 }
409 if (flags & FELF_READ_ONLY) {
410 size_t s = end - start;
411 char *b = para_malloc(s + 1);
412 memcpy(b, start, s);
413 b[s] = '\0';
414 // PARA_NOTICE_LOG("b: %s, start: %s\n", b, start);
415 ret = line_handler(b, private_data);
416 free(b);
417 } else {
418 *end = '\0';
419 ret = line_handler(start, private_data);
420 }
421 if (ret < 0)
422 return ret;
423 start = ++end;
424 }
425 if (!line_handler || (flags & FELF_READ_ONLY))
426 return num_lines;
427 i = buf + size - start;
428 if (i && i != size)
429 memmove(buf, start, i);
430 return i;
431 }
432
433 /** Return the hex characters of the lower 4 bits. */
434 #define hex(a) (hexchar[(a) & 15])
435
436 static void write_size_header(char *buf, int n)
437 {
438 static char hexchar[] = "0123456789abcdef";
439
440 buf[0] = hex(n >> 12);
441 buf[1] = hex(n >> 8);
442 buf[2] = hex(n >> 4);
443 buf[3] = hex(n);
444 buf[4] = ' ';
445 }
446
447 /**
448 * Read a four-byte hex-number and return its value.
449 *
450 * Each status item sent by para_server is prefixed with such a hex number in
451 * ASCII which describes the size of the status item.
452 *
453 * \param buf The buffer which must be at least four bytes long.
454 *
455 * \return The value of the hex number on success, \p -E_SIZE_PREFIX if the
456 * buffer did not contain only hex digits.
457 */
458 int read_size_header(const char *buf)
459 {
460 int i, len = 0;
461
462 for (i = 0; i < 4; i++) {
463 unsigned char c = buf[i];
464 len <<= 4;
465 if (c >= '0' && c <= '9') {
466 len += c - '0';
467 continue;
468 }
469 if (c >= 'a' && c <= 'f') {
470 len += c - 'a' + 10;
471 continue;
472 }
473 return -E_SIZE_PREFIX;
474 }
475 if (buf[4] != ' ')
476 return -E_SIZE_PREFIX;
477 return len;
478 }
479
480 /**
481 * Safely print into a buffer at a given offset.
482 *
483 * \param b Determines the buffer, its size, and the offset.
484 * \param fmt The format string.
485 *
486 * This function prints into the buffer given by \a b at the offset which is
487 * also given by \a b. If there is not enough space to hold the result, the
488 * buffer size is doubled until the underlying call to vsnprintf() succeeds
489 * or the size of the buffer exceeds the maximal size specified in \a b.
490 *
491 * In the latter case the unmodified \a buf and \a offset values as well as the
492 * private_data pointer of \a b are passed to the \a max_size_handler of \a b.
493 * If this function succeeds, i.e. returns a non-negative value, the offset of
494 * \a b is reset to zero and the given data is written to the beginning of the
495 * buffer. If \a max_size_handler() returns a negative value, this value is
496 * returned by \a para_printf().
497 *
498 * Upon return, the offset of \a b is adjusted accordingly so that subsequent
499 * calls to this function append data to what is already contained in the
500 * buffer.
501 *
502 * It's OK to call this function with \p b->buf being \p NULL. In this case, an
503 * initial buffer is allocated.
504 *
505 * \return The number of bytes printed into the buffer (not including the
506 * terminating \p NULL byte) on success, negative on errors. If there is no
507 * size-bound on \a b, i.e. if \p b->max_size is zero, this function never
508 * fails.
509 *
510 * \sa make_message(), vsnprintf(3).
511 */
512 __printf_2_3 int para_printf(struct para_buffer *b, const char *fmt, ...)
513 {
514 int ret, sz_off = (b->flags & PBF_SIZE_PREFIX)? 5 : 0;
515
516 if (!b->buf) {
517 b->buf = para_malloc(128);
518 b->size = 128;
519 b->offset = 0;
520 }
521 while (1) {
522 char *p = b->buf + b->offset;
523 size_t size = b->size - b->offset;
524 va_list ap;
525
526 if (size > sz_off) {
527 va_start(ap, fmt);
528 ret = vsnprintf(p + sz_off, size - sz_off, fmt, ap);
529 va_end(ap);
530 if (ret > -1 && ret < size - sz_off) { /* success */
531 b->offset += ret + sz_off;
532 if (sz_off)
533 write_size_header(p, ret);
534 return ret + sz_off;
535 }
536 }
537 /* check if we may grow the buffer */
538 if (!b->max_size || 2 * b->size < b->max_size) { /* yes */
539 /* try again with more space */
540 b->size *= 2;
541 b->buf = para_realloc(b->buf, b->size);
542 continue;
543 }
544 /* can't grow buffer */
545 if (!b->offset || !b->max_size_handler) /* message too large */
546 return -ERRNO_TO_PARA_ERROR(ENOSPC);
547 ret = b->max_size_handler(b->buf, b->offset, b->private_data);
548 if (ret < 0)
549 return ret;
550 b->offset = 0;
551 }
552 }
553
554 /** \cond llong_minmax */
555 /* LLONG_MAX and LLONG_MIN might not be defined. */
556 #ifndef LLONG_MAX
557 #define LLONG_MAX 9223372036854775807LL
558 #endif
559 #ifndef LLONG_MIN
560 #define LLONG_MIN (-LLONG_MAX - 1LL)
561 #endif
562 /** \endcond llong_minmax */
563
564 /**
565 * Convert a string to a 64-bit signed integer value.
566 *
567 * \param str The string to be converted.
568 * \param value Result pointer.
569 *
570 * \return Standard.
571 *
572 * \sa para_atoi32(), strtol(3), atoi(3).
573 */
574 int para_atoi64(const char *str, int64_t *value)
575 {
576 char *endptr;
577 long long tmp;
578
579 errno = 0; /* To distinguish success/failure after call */
580 tmp = strtoll(str, &endptr, 10);
581 if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
582 return -E_ATOI_OVERFLOW;
583 if (errno != 0 && tmp == 0) /* other error */
584 return -E_STRTOLL;
585 if (endptr == str)
586 return -E_ATOI_NO_DIGITS;
587 if (*endptr != '\0') /* Further characters after number */
588 return -E_ATOI_JUNK_AT_END;
589 *value = tmp;
590 return 1;
591 }
592
593 /**
594 * Convert a string to a 32-bit signed integer value.
595 *
596 * \param str The string to be converted.
597 * \param value Result pointer.
598 *
599 * \return Standard.
600 *
601 * \sa para_atoi64().
602 */
603 int para_atoi32(const char *str, int32_t *value)
604 {
605 int64_t tmp;
606 int ret;
607 const int32_t max = 2147483647;
608
609 ret = para_atoi64(str, &tmp);
610 if (ret < 0)
611 return ret;
612 if (tmp > max || tmp < -max - 1)
613 return -E_ATOI_OVERFLOW;
614 *value = tmp;
615 return 1;
616 }
617
618 static inline int loglevel_equal(const char *arg, const char * const ll)
619 {
620 return !strncasecmp(arg, ll, strlen(ll));
621 }
622
623 /**
624 * Compute the loglevel number from its name.
625 *
626 * \param txt The name of the loglevel (debug, info, ...).
627 *
628 * \return The numeric representation of the loglevel name.
629 */
630 int get_loglevel_by_name(const char *txt)
631 {
632 if (loglevel_equal(txt, "debug"))
633 return LL_DEBUG;
634 if (loglevel_equal(txt, "info"))
635 return LL_INFO;
636 if (loglevel_equal(txt, "notice"))
637 return LL_NOTICE;
638 if (loglevel_equal(txt, "warning"))
639 return LL_WARNING;
640 if (loglevel_equal(txt, "error"))
641 return LL_ERROR;
642 if (loglevel_equal(txt, "crit"))
643 return LL_CRIT;
644 if (loglevel_equal(txt, "emerg"))
645 return LL_EMERG;
646 return -1;
647 }
648
649 static int get_next_word(const char *buf, const char *delim, char **word)
650 {
651 enum line_state_flags {LSF_HAVE_WORD = 1, LSF_BACKSLASH = 2,
652 LSF_SINGLE_QUOTE = 4, LSF_DOUBLE_QUOTE = 8};
653 const char *in;
654 char *out;
655 int ret, state = 0;
656
657 out = para_malloc(strlen(buf) + 1);
658 *out = '\0';
659 *word = out;
660 for (in = buf; *in; in++) {
661 const char *p;
662
663 switch (*in) {
664 case '\\':
665 if (state & LSF_BACKSLASH) /* \\ */
666 goto copy_char;
667 state |= LSF_BACKSLASH;
668 state |= LSF_HAVE_WORD;
669 continue;
670 case 'n':
671 case 't':
672 if (state & LSF_BACKSLASH) { /* \n or \t */
673 *out++ = (*in == 'n')? '\n' : '\t';
674 state &= ~LSF_BACKSLASH;
675 continue;
676 }
677 goto copy_char;
678 case '"':
679 if (state & LSF_BACKSLASH) /* \" */
680 goto copy_char;
681 if (state & LSF_SINGLE_QUOTE) /* '" */
682 goto copy_char;
683 if (state & LSF_DOUBLE_QUOTE) {
684 state &= ~LSF_DOUBLE_QUOTE;
685 continue;
686 }
687 state |= LSF_HAVE_WORD;
688 state |= LSF_DOUBLE_QUOTE;
689 continue;
690 case '\'':
691 if (state & LSF_BACKSLASH) /* \' */
692 goto copy_char;
693 if (state & LSF_DOUBLE_QUOTE) /* "' */
694 goto copy_char;
695 if (state & LSF_SINGLE_QUOTE) {
696 state &= ~LSF_SINGLE_QUOTE;
697 continue;
698 }
699 state |= LSF_HAVE_WORD;
700 state |= LSF_SINGLE_QUOTE;
701 continue;
702 }
703 for (p = delim; *p; p++) {
704 if (*in != *p)
705 continue;
706 if (state & LSF_BACKSLASH)
707 goto copy_char;
708 if (state & LSF_SINGLE_QUOTE)
709 goto copy_char;
710 if (state & LSF_DOUBLE_QUOTE)
711 goto copy_char;
712 if (state & LSF_HAVE_WORD)
713 goto success;
714 break;
715 }
716 if (*p) /* ignore delimiter at the beginning */
717 continue;
718 copy_char:
719 state |= LSF_HAVE_WORD;
720 *out++ = *in;
721 state &= ~LSF_BACKSLASH;
722 }
723 ret = 0;
724 if (!(state & LSF_HAVE_WORD))
725 goto out;
726 ret = -ERRNO_TO_PARA_ERROR(EINVAL);
727 if (state & LSF_BACKSLASH) {
728 PARA_ERROR_LOG("trailing backslash\n");
729 goto out;
730 }
731 if ((state & LSF_SINGLE_QUOTE) || (state & LSF_DOUBLE_QUOTE)) {
732 PARA_ERROR_LOG("unmatched quote character\n");
733 goto out;
734 }
735 success:
736 *out = '\0';
737 return in - buf;
738 out:
739 free(*word);
740 *word = NULL;
741 return ret;
742 }
743
744 /**
745 * Get the number of the word the cursor is on.
746 *
747 * \param buf The zero-terminated line buffer.
748 * \param delim Characters that separate words.
749 * \param point The cursor position.
750 *
751 * \return Zero-based word number.
752 */
753 int compute_word_num(const char *buf, const char *delim, int point)
754 {
755 int ret, num_words;
756 const char *p;
757 char *word;
758
759 for (p = buf, num_words = 0; ; p += ret, num_words++) {
760 ret = get_next_word(p, delim, &word);
761 if (ret <= 0)
762 break;
763 free(word);
764 if (p + ret >= buf + point)
765 break;
766 }
767 return num_words;
768 }
769
770 /**
771 * Free an array of words created by create_argv() or create_shifted_argv().
772 *
773 * \param argv A pointer previously obtained by \ref create_argv().
774 */
775 void free_argv(char **argv)
776 {
777 int i;
778
779 if (!argv)
780 return;
781 for (i = 0; argv[i]; i++)
782 free(argv[i]);
783 free(argv);
784 }
785
786 static int create_argv_offset(int offset, const char *buf, const char *delim,
787 char ***result)
788 {
789 char *word, **argv = para_malloc((offset + 1) * sizeof(char *));
790 const char *p;
791 int i, ret;
792
793 for (i = 0; i < offset; i++)
794 argv[i] = NULL;
795 for (p = buf; p && *p; p += ret, i++) {
796 ret = get_next_word(p, delim, &word);
797 if (ret < 0)
798 goto err;
799 if (!ret)
800 break;
801 argv = para_realloc(argv, (i + 2) * sizeof(char*));
802 argv[i] = word;
803 }
804 argv[i] = NULL;
805 *result = argv;
806 return i;
807 err:
808 while (i > 0)
809 free(argv[--i]);
810 free(argv);
811 *result = NULL;
812 return ret;
813 }
814
815 /**
816 * Split a buffer into words.
817 *
818 * This parser honors single and double quotes, backslash-escaped characters
819 * and special characters like \p \\n. The result contains pointers to copies
820 * of the words contained in \a buf and has to be freed by using \ref
821 * free_argv().
822 *
823 * \param buf The buffer to be split.
824 * \param delim Each character in this string is treated as a separator.
825 * \param result The array of words is returned here.
826 *
827 * \return Number of words in \a buf, negative on errors.
828 */
829 int create_argv(const char *buf, const char *delim, char ***result)
830 {
831 return create_argv_offset(0, buf, delim, result);
832 }
833
834 /**
835 * Split a buffer into words, offset one.
836 *
837 * This is similar to \ref create_argv() but the returned array is one element
838 * larger, words start at index one and element zero is initialized to \p NULL.
839 * Callers must set element zero to a non-NULL value before calling free_argv()
840 * on the returned array to avoid a memory leak.
841 *
842 * \param buf See \ref create_argv().
843 * \param delim See \ref create_argv().
844 * \param result See \ref create_argv().
845 *
846 * \return Number of words plus one on success, negative on errors.
847 */
848 int create_shifted_argv(const char *buf, const char *delim, char ***result)
849 {
850 return create_argv_offset(1, buf, delim, result);
851 }
852
853 /**
854 * Find out if the given string is contained in the arg vector.
855 *
856 * \param arg The string to look for.
857 * \param argv The array to search.
858 *
859 * \return The first index whose value equals \a arg, or \p -E_ARG_NOT_FOUND if
860 * arg was not found in \a argv.
861 */
862 int find_arg(const char *arg, char **argv)
863 {
864 int i;
865
866 if (!argv)
867 return -E_ARG_NOT_FOUND;
868 for (i = 0; argv[i]; i++)
869 if (strcmp(arg, argv[i]) == 0)
870 return i;
871 return -E_ARG_NOT_FOUND;
872 }
873
874 /**
875 * Compile a regular expression.
876 *
877 * This simple wrapper calls regcomp() and logs a message on errors.
878 *
879 * \param preg See regcomp(3).
880 * \param regex See regcomp(3).
881 * \param cflags See regcomp(3).
882 *
883 * \return Standard.
884 */
885 int para_regcomp(regex_t *preg, const char *regex, int cflags)
886 {
887 char *buf;
888 size_t size;
889 int ret = regcomp(preg, regex, cflags);
890
891 if (ret == 0)
892 return 1;
893 size = regerror(ret, preg, NULL, 0);
894 buf = para_malloc(size);
895 regerror(ret, preg, buf, size);
896 PARA_ERROR_LOG("%s\n", buf);
897 free(buf);
898 return -E_REGEX;
899 }
900
901 /**
902 * strdup() for not necessarily zero-terminated strings.
903 *
904 * \param src The source buffer.
905 * \param len The number of bytes to be copied.
906 *
907 * \return A 0-terminated buffer of length \a len + 1.
908 *
909 * This is similar to strndup(), which is a GNU extension. However, one
910 * difference is that strndup() returns \p NULL if insufficient memory was
911 * available while this function aborts in this case.
912 *
913 * \sa strdup(), \ref para_strdup().
914 */
915 char *safe_strdup(const char *src, size_t len)
916 {
917 char *p;
918
919 assert(len < (size_t)-1);
920 p = para_malloc(len + 1);
921 if (len > 0)
922 memcpy(p, src, len);
923 p[len] = '\0';
924 return p;
925 }
926
927 /**
928 * Copy the value of a key=value pair.
929 *
930 * This checks whether the given buffer starts with "key=", ignoring case. If
931 * yes, a copy of the value is returned. The source buffer may not be
932 * zero-terminated.
933 *
934 * \param src The source buffer.
935 * \param len The number of bytes of the tag.
936 * \param key Only copy if it is the value of this key.
937 *
938 * \return A zero-terminated buffer, or \p NULL if the key was
939 * not of the given type.
940 */
941 char *key_value_copy(const char *src, size_t len, const char *key)
942 {
943 int keylen = strlen(key);
944
945 if (len <= keylen)
946 return NULL;
947 if (strncasecmp(src, key, keylen))
948 return NULL;
949 if (src[keylen] != '=')
950 return NULL;
951 return safe_strdup(src + keylen + 1, len - keylen - 1);
952 }