string: Simplify for_each_line().
[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 * For each complete line in \p buf, \p line_handler is called. The first
362 * argument to \p line_handler is (a copy of) the current line, and \p
363 * private_data is passed as the second argument. If the \p FELF_READ_ONLY
364 * flag is unset, a pointer into \a buf is passed to the line handler,
365 * otherwise a pointer to a copy of the current line is passed instead. This
366 * copy is freed immediately after the line handler returns.
367 *
368 * The function returns if \p line_handler returns a negative value or no more
369 * lines are in the buffer. The rest of the buffer (last chunk containing an
370 * incomplete line) is moved to the beginning of the buffer if FELF_READ_ONLY is
371 * unset.
372 *
373 * \return If \p FELF_READ_ONLY is not set in \a flags, this function returns
374 * the number of bytes not handled to \p line_handler, otherwise the number of
375 * complete lines. On errors the negative error code of the \p line_handler is
376 * returned.
377 *
378 * \sa \ref for_each_line_flags.
379 */
380 int for_each_line(unsigned flags, char *buf, size_t size,
381 line_handler_t *line_handler, void *private_data)
382 {
383 char *start = buf, *end;
384 int ret, i, num_lines = 0;
385
386 // PARA_NOTICE_LOG("buf: %s\n", buf);
387 while (start < buf + size) {
388 char *next_null;
389 char *next_cr;
390
391 next_cr = memchr(start, '\n', buf + size - start);
392 next_null = memchr(start, '\0', buf + size - start);
393 if (!next_cr && !next_null)
394 break;
395 if (next_cr && next_null) {
396 end = next_cr < next_null? next_cr : next_null;
397 } else if (next_null) {
398 end = next_null;
399 } else
400 end = next_cr;
401 num_lines++;
402 if (flags & FELF_READ_ONLY) {
403 size_t s = end - start;
404 char *b = para_malloc(s + 1);
405 memcpy(b, start, s);
406 b[s] = '\0';
407 // PARA_NOTICE_LOG("b: %s, start: %s\n", b, start);
408 ret = line_handler(b, private_data);
409 free(b);
410 } else {
411 *end = '\0';
412 ret = line_handler(start, private_data);
413 }
414 if (ret < 0)
415 return ret;
416 start = ++end;
417 }
418 if (flags & FELF_READ_ONLY)
419 return num_lines;
420 i = buf + size - start;
421 if (i && i != size)
422 memmove(buf, start, i);
423 return i;
424 }
425
426 /** Return the hex characters of the lower 4 bits. */
427 #define hex(a) (hexchar[(a) & 15])
428
429 static void write_size_header(char *buf, int n)
430 {
431 static char hexchar[] = "0123456789abcdef";
432
433 buf[0] = hex(n >> 12);
434 buf[1] = hex(n >> 8);
435 buf[2] = hex(n >> 4);
436 buf[3] = hex(n);
437 buf[4] = ' ';
438 }
439
440 /**
441 * Read a four-byte hex-number and return its value.
442 *
443 * Each status item sent by para_server is prefixed with such a hex number in
444 * ASCII which describes the size of the status item.
445 *
446 * \param buf The buffer which must be at least four bytes long.
447 *
448 * \return The value of the hex number on success, \p -E_SIZE_PREFIX if the
449 * buffer did not contain only hex digits.
450 */
451 int read_size_header(const char *buf)
452 {
453 int i, len = 0;
454
455 for (i = 0; i < 4; i++) {
456 unsigned char c = buf[i];
457 len <<= 4;
458 if (c >= '0' && c <= '9') {
459 len += c - '0';
460 continue;
461 }
462 if (c >= 'a' && c <= 'f') {
463 len += c - 'a' + 10;
464 continue;
465 }
466 return -E_SIZE_PREFIX;
467 }
468 if (buf[4] != ' ')
469 return -E_SIZE_PREFIX;
470 return len;
471 }
472
473 /**
474 * Safely print into a buffer at a given offset.
475 *
476 * \param b Determines the buffer, its size, and the offset.
477 * \param fmt The format string.
478 *
479 * This function prints into the buffer given by \a b at the offset which is
480 * also given by \a b. If there is not enough space to hold the result, the
481 * buffer size is doubled until the underlying call to vsnprintf() succeeds
482 * or the size of the buffer exceeds the maximal size specified in \a b.
483 *
484 * In the latter case the unmodified \a buf and \a offset values as well as the
485 * private_data pointer of \a b are passed to the \a max_size_handler of \a b.
486 * If this function succeeds, i.e. returns a non-negative value, the offset of
487 * \a b is reset to zero and the given data is written to the beginning of the
488 * buffer. If \a max_size_handler() returns a negative value, this value is
489 * returned by \a para_printf().
490 *
491 * Upon return, the offset of \a b is adjusted accordingly so that subsequent
492 * calls to this function append data to what is already contained in the
493 * buffer.
494 *
495 * It's OK to call this function with \p b->buf being \p NULL. In this case, an
496 * initial buffer is allocated.
497 *
498 * \return The number of bytes printed into the buffer (not including the
499 * terminating \p NULL byte) on success, negative on errors. If there is no
500 * size-bound on \a b, i.e. if \p b->max_size is zero, this function never
501 * fails.
502 *
503 * \sa make_message(), vsnprintf(3).
504 */
505 __printf_2_3 int para_printf(struct para_buffer *b, const char *fmt, ...)
506 {
507 int ret, sz_off = (b->flags & PBF_SIZE_PREFIX)? 5 : 0;
508
509 if (!b->buf) {
510 b->buf = para_malloc(128);
511 b->size = 128;
512 b->offset = 0;
513 }
514 while (1) {
515 char *p = b->buf + b->offset;
516 size_t size = b->size - b->offset;
517 va_list ap;
518
519 if (size > sz_off) {
520 va_start(ap, fmt);
521 ret = vsnprintf(p + sz_off, size - sz_off, fmt, ap);
522 va_end(ap);
523 if (ret > -1 && ret < size - sz_off) { /* success */
524 b->offset += ret + sz_off;
525 if (sz_off)
526 write_size_header(p, ret);
527 return ret + sz_off;
528 }
529 }
530 /* check if we may grow the buffer */
531 if (!b->max_size || 2 * b->size < b->max_size) { /* yes */
532 /* try again with more space */
533 b->size *= 2;
534 b->buf = para_realloc(b->buf, b->size);
535 continue;
536 }
537 /* can't grow buffer */
538 if (!b->offset || !b->max_size_handler) /* message too large */
539 return -ERRNO_TO_PARA_ERROR(ENOSPC);
540 ret = b->max_size_handler(b->buf, b->offset, b->private_data);
541 if (ret < 0)
542 return ret;
543 b->offset = 0;
544 }
545 }
546
547 /** \cond llong_minmax */
548 /* LLONG_MAX and LLONG_MIN might not be defined. */
549 #ifndef LLONG_MAX
550 #define LLONG_MAX 9223372036854775807LL
551 #endif
552 #ifndef LLONG_MIN
553 #define LLONG_MIN (-LLONG_MAX - 1LL)
554 #endif
555 /** \endcond llong_minmax */
556
557 /**
558 * Convert a string to a 64-bit signed integer value.
559 *
560 * \param str The string to be converted.
561 * \param value Result pointer.
562 *
563 * \return Standard.
564 *
565 * \sa para_atoi32(), strtol(3), atoi(3).
566 */
567 int para_atoi64(const char *str, int64_t *value)
568 {
569 char *endptr;
570 long long tmp;
571
572 errno = 0; /* To distinguish success/failure after call */
573 tmp = strtoll(str, &endptr, 10);
574 if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
575 return -E_ATOI_OVERFLOW;
576 if (errno != 0 && tmp == 0) /* other error */
577 return -E_STRTOLL;
578 if (endptr == str)
579 return -E_ATOI_NO_DIGITS;
580 if (*endptr != '\0') /* Further characters after number */
581 return -E_ATOI_JUNK_AT_END;
582 *value = tmp;
583 return 1;
584 }
585
586 /**
587 * Convert a string to a 32-bit signed integer value.
588 *
589 * \param str The string to be converted.
590 * \param value Result pointer.
591 *
592 * \return Standard.
593 *
594 * \sa para_atoi64().
595 */
596 int para_atoi32(const char *str, int32_t *value)
597 {
598 int64_t tmp;
599 int ret;
600 const int32_t max = 2147483647;
601
602 ret = para_atoi64(str, &tmp);
603 if (ret < 0)
604 return ret;
605 if (tmp > max || tmp < -max - 1)
606 return -E_ATOI_OVERFLOW;
607 *value = tmp;
608 return 1;
609 }
610
611 static inline int loglevel_equal(const char *arg, const char * const ll)
612 {
613 return !strncasecmp(arg, ll, strlen(ll));
614 }
615
616 /**
617 * Compute the loglevel number from its name.
618 *
619 * \param txt The name of the loglevel (debug, info, ...).
620 *
621 * \return The numeric representation of the loglevel name.
622 */
623 int get_loglevel_by_name(const char *txt)
624 {
625 if (loglevel_equal(txt, "debug"))
626 return LL_DEBUG;
627 if (loglevel_equal(txt, "info"))
628 return LL_INFO;
629 if (loglevel_equal(txt, "notice"))
630 return LL_NOTICE;
631 if (loglevel_equal(txt, "warning"))
632 return LL_WARNING;
633 if (loglevel_equal(txt, "error"))
634 return LL_ERROR;
635 if (loglevel_equal(txt, "crit"))
636 return LL_CRIT;
637 if (loglevel_equal(txt, "emerg"))
638 return LL_EMERG;
639 return -1;
640 }
641
642 static int get_next_word(const char *buf, const char *delim, char **word)
643 {
644 enum line_state_flags {LSF_HAVE_WORD = 1, LSF_BACKSLASH = 2,
645 LSF_SINGLE_QUOTE = 4, LSF_DOUBLE_QUOTE = 8};
646 const char *in;
647 char *out;
648 int ret, state = 0;
649
650 out = para_malloc(strlen(buf) + 1);
651 *out = '\0';
652 *word = out;
653 for (in = buf; *in; in++) {
654 const char *p;
655
656 switch (*in) {
657 case '\\':
658 if (state & LSF_BACKSLASH) /* \\ */
659 goto copy_char;
660 state |= LSF_BACKSLASH;
661 state |= LSF_HAVE_WORD;
662 continue;
663 case 'n':
664 case 't':
665 if (state & LSF_BACKSLASH) { /* \n or \t */
666 *out++ = (*in == 'n')? '\n' : '\t';
667 state &= ~LSF_BACKSLASH;
668 continue;
669 }
670 goto copy_char;
671 case '"':
672 if (state & LSF_BACKSLASH) /* \" */
673 goto copy_char;
674 if (state & LSF_SINGLE_QUOTE) /* '" */
675 goto copy_char;
676 if (state & LSF_DOUBLE_QUOTE) {
677 state &= ~LSF_DOUBLE_QUOTE;
678 continue;
679 }
680 state |= LSF_HAVE_WORD;
681 state |= LSF_DOUBLE_QUOTE;
682 continue;
683 case '\'':
684 if (state & LSF_BACKSLASH) /* \' */
685 goto copy_char;
686 if (state & LSF_DOUBLE_QUOTE) /* "' */
687 goto copy_char;
688 if (state & LSF_SINGLE_QUOTE) {
689 state &= ~LSF_SINGLE_QUOTE;
690 continue;
691 }
692 state |= LSF_HAVE_WORD;
693 state |= LSF_SINGLE_QUOTE;
694 continue;
695 }
696 for (p = delim; *p; p++) {
697 if (*in != *p)
698 continue;
699 if (state & LSF_BACKSLASH)
700 goto copy_char;
701 if (state & LSF_SINGLE_QUOTE)
702 goto copy_char;
703 if (state & LSF_DOUBLE_QUOTE)
704 goto copy_char;
705 if (state & LSF_HAVE_WORD)
706 goto success;
707 break;
708 }
709 if (*p) /* ignore delimiter at the beginning */
710 continue;
711 copy_char:
712 state |= LSF_HAVE_WORD;
713 *out++ = *in;
714 state &= ~LSF_BACKSLASH;
715 }
716 ret = 0;
717 if (!(state & LSF_HAVE_WORD))
718 goto out;
719 ret = -ERRNO_TO_PARA_ERROR(EINVAL);
720 if (state & LSF_BACKSLASH) {
721 PARA_ERROR_LOG("trailing backslash\n");
722 goto out;
723 }
724 if ((state & LSF_SINGLE_QUOTE) || (state & LSF_DOUBLE_QUOTE)) {
725 PARA_ERROR_LOG("unmatched quote character\n");
726 goto out;
727 }
728 success:
729 *out = '\0';
730 return in - buf;
731 out:
732 free(*word);
733 *word = NULL;
734 return ret;
735 }
736
737 /**
738 * Get the number of the word the cursor is on.
739 *
740 * \param buf The zero-terminated line buffer.
741 * \param delim Characters that separate words.
742 * \param point The cursor position.
743 *
744 * \return Zero-based word number.
745 */
746 int compute_word_num(const char *buf, const char *delim, int point)
747 {
748 int ret, num_words;
749 const char *p;
750 char *word;
751
752 for (p = buf, num_words = 0; ; p += ret, num_words++) {
753 ret = get_next_word(p, delim, &word);
754 if (ret <= 0)
755 break;
756 free(word);
757 if (p + ret >= buf + point)
758 break;
759 }
760 return num_words;
761 }
762
763 /**
764 * Free an array of words created by create_argv() or create_shifted_argv().
765 *
766 * \param argv A pointer previously obtained by \ref create_argv().
767 */
768 void free_argv(char **argv)
769 {
770 int i;
771
772 if (!argv)
773 return;
774 for (i = 0; argv[i]; i++)
775 free(argv[i]);
776 free(argv);
777 }
778
779 static int create_argv_offset(int offset, const char *buf, const char *delim,
780 char ***result)
781 {
782 char *word, **argv = para_malloc((offset + 1) * sizeof(char *));
783 const char *p;
784 int i, ret;
785
786 for (i = 0; i < offset; i++)
787 argv[i] = NULL;
788 for (p = buf; p && *p; p += ret, i++) {
789 ret = get_next_word(p, delim, &word);
790 if (ret < 0)
791 goto err;
792 if (!ret)
793 break;
794 argv = para_realloc(argv, (i + 2) * sizeof(char*));
795 argv[i] = word;
796 }
797 argv[i] = NULL;
798 *result = argv;
799 return i;
800 err:
801 while (i > 0)
802 free(argv[--i]);
803 free(argv);
804 *result = NULL;
805 return ret;
806 }
807
808 /**
809 * Split a buffer into words.
810 *
811 * This parser honors single and double quotes, backslash-escaped characters
812 * and special characters like \p \\n. The result contains pointers to copies
813 * of the words contained in \a buf and has to be freed by using \ref
814 * free_argv().
815 *
816 * \param buf The buffer to be split.
817 * \param delim Each character in this string is treated as a separator.
818 * \param result The array of words is returned here.
819 *
820 * \return Number of words in \a buf, negative on errors.
821 */
822 int create_argv(const char *buf, const char *delim, char ***result)
823 {
824 return create_argv_offset(0, buf, delim, result);
825 }
826
827 /**
828 * Split a buffer into words, offset one.
829 *
830 * This is similar to \ref create_argv() but the returned array is one element
831 * larger, words start at index one and element zero is initialized to \p NULL.
832 * Callers must set element zero to a non-NULL value before calling free_argv()
833 * on the returned array to avoid a memory leak.
834 *
835 * \param buf See \ref create_argv().
836 * \param delim See \ref create_argv().
837 * \param result See \ref create_argv().
838 *
839 * \return Number of words plus one on success, negative on errors.
840 */
841 int create_shifted_argv(const char *buf, const char *delim, char ***result)
842 {
843 return create_argv_offset(1, buf, delim, result);
844 }
845
846 /**
847 * Find out if the given string is contained in the arg vector.
848 *
849 * \param arg The string to look for.
850 * \param argv The array to search.
851 *
852 * \return The first index whose value equals \a arg, or \p -E_ARG_NOT_FOUND if
853 * arg was not found in \a argv.
854 */
855 int find_arg(const char *arg, char **argv)
856 {
857 int i;
858
859 if (!argv)
860 return -E_ARG_NOT_FOUND;
861 for (i = 0; argv[i]; i++)
862 if (strcmp(arg, argv[i]) == 0)
863 return i;
864 return -E_ARG_NOT_FOUND;
865 }
866
867 /**
868 * Compile a regular expression.
869 *
870 * This simple wrapper calls regcomp() and logs a message on errors.
871 *
872 * \param preg See regcomp(3).
873 * \param regex See regcomp(3).
874 * \param cflags See regcomp(3).
875 *
876 * \return Standard.
877 */
878 int para_regcomp(regex_t *preg, const char *regex, int cflags)
879 {
880 char *buf;
881 size_t size;
882 int ret = regcomp(preg, regex, cflags);
883
884 if (ret == 0)
885 return 1;
886 size = regerror(ret, preg, NULL, 0);
887 buf = para_malloc(size);
888 regerror(ret, preg, buf, size);
889 PARA_ERROR_LOG("%s\n", buf);
890 free(buf);
891 return -E_REGEX;
892 }
893
894 /**
895 * strdup() for not necessarily zero-terminated strings.
896 *
897 * \param src The source buffer.
898 * \param len The number of bytes to be copied.
899 *
900 * \return A 0-terminated buffer of length \a len + 1.
901 *
902 * This is similar to strndup(), which is a GNU extension. However, one
903 * difference is that strndup() returns \p NULL if insufficient memory was
904 * available while this function aborts in this case.
905 *
906 * \sa strdup(), \ref para_strdup().
907 */
908 char *safe_strdup(const char *src, size_t len)
909 {
910 char *p;
911
912 assert(len < (size_t)-1);
913 p = para_malloc(len + 1);
914 if (len > 0)
915 memcpy(p, src, len);
916 p[len] = '\0';
917 return p;
918 }
919
920 /**
921 * Copy the value of a key=value pair.
922 *
923 * This checks whether the given buffer starts with "key=", ignoring case. If
924 * yes, a copy of the value is returned. The source buffer may not be
925 * zero-terminated.
926 *
927 * \param src The source buffer.
928 * \param len The number of bytes of the tag.
929 * \param key Only copy if it is the value of this key.
930 *
931 * \return A zero-terminated buffer, or \p NULL if the key was
932 * not of the given type.
933 */
934 char *key_value_copy(const char *src, size_t len, const char *key)
935 {
936 int keylen = strlen(key);
937
938 if (len <= keylen)
939 return NULL;
940 if (strncasecmp(src, key, keylen))
941 return NULL;
942 if (src[keylen] != '=')
943 return NULL;
944 return safe_strdup(src + keylen + 1, len - keylen - 1);
945 }