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