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