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