write: Switch to the alternative post select method.
[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 <pwd.h>
10 #include <sys/utsname.h> /* uname() */
11 #include <string.h>
12 #include <regex.h>
13
14 #include "para.h"
15 #include "string.h"
16 #include "error.h"
17
18 /**
19  * Paraslash's version of realloc().
20  *
21  * \param p Pointer to the memory block, may be \p NULL.
22  * \param size The desired new size.
23  *
24  * A wrapper for realloc(3). It calls \p exit(\p EXIT_FAILURE) on errors,
25  * i.e. there is no need to check the return value in the caller.
26  *
27  * \return A pointer to  the newly allocated memory, which is suitably aligned
28  * for any kind of variable and may be different from \a p.
29  *
30  * \sa realloc(3).
31  */
32 __must_check __malloc void *para_realloc(void *p, size_t size)
33 {
34         /*
35          * No need to check for NULL pointers: If p is NULL, the call
36          * to realloc is equivalent to malloc(size)
37          */
38         assert(size);
39         if (!(p = realloc(p, size))) {
40                 PARA_EMERG_LOG("realloc failed (size = %zu), aborting\n",
41                         size);
42                 exit(EXIT_FAILURE);
43         }
44         return p;
45 }
46
47 /**
48  * Paraslash's version of malloc().
49  *
50  * \param size The desired new size.
51  *
52  * A wrapper for malloc(3) which exits on errors.
53  *
54  * \return A pointer to the allocated memory, which is suitably aligned for any
55  * kind of variable.
56  *
57  * \sa malloc(3).
58  */
59 __must_check __malloc void *para_malloc(size_t size)
60 {
61         void *p;
62
63         assert(size);
64         p = malloc(size);
65         if (!p) {
66                 PARA_EMERG_LOG("malloc failed (size = %zu), aborting\n",
67                         size);
68                 exit(EXIT_FAILURE);
69         }
70         return p;
71 }
72
73 /**
74  * Paraslash's version of calloc().
75  *
76  * \param size The desired new size.
77  *
78  * A wrapper for calloc(3) which exits on errors.
79  *
80  * \return A pointer to the allocated and zeroed-out memory, which is suitably
81  * aligned for any kind of variable.
82  *
83  * \sa calloc(3)
84  */
85 __must_check __malloc void *para_calloc(size_t size)
86 {
87         void *ret = para_malloc(size);
88
89         memset(ret, 0, size);
90         return ret;
91 }
92
93 /**
94  * Paraslash's version of strdup().
95  *
96  * \param s The string to be duplicated.
97  *
98  * A wrapper for strdup(3). It calls \p exit(EXIT_FAILURE) on errors, i.e.
99  * there is no need to check the return value in the caller.
100  *
101  * \return A pointer to the duplicated string. If \a s was the \p NULL pointer,
102  * an pointer to an empty string is returned.
103  *
104  * \sa strdup(3)
105  */
106 __must_check __malloc char *para_strdup(const char *s)
107 {
108         char *ret;
109
110         if ((ret = strdup(s? s: "")))
111                 return ret;
112         PARA_EMERG_LOG("strdup failed, aborting\n");
113         exit(EXIT_FAILURE);
114 }
115
116 /**
117  * Print a formated message to a dynamically allocated string.
118  *
119  * \param result The formated string is returned here.
120  * \param fmt The format string.
121  * \param ap Initialized list of arguments.
122  *
123  * This function is similar to vasprintf(), a GNU extension which is not in C
124  * or POSIX. It allocates a string large enough to hold the output including
125  * the terminating null byte. The allocated string is returned via the first
126  * argument and must be freed by the caller. However, unlike vasprintf(), this
127  * function calls exit() if insufficient memory is available, while vasprintf()
128  * returns -1 in this case.
129  *
130  * \return Number of bytes written, not including the terminating \p NULL
131  * character.
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() or create_shifted_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 static int create_argv_offset(int offset, const char *buf, const char *delim,
818                 char ***result)
819 {
820         char *word, **argv = para_malloc((offset + 1) * sizeof(char *));
821         const char *p;
822         int i, ret;
823
824         for (i = 0; i < offset; i++)
825                 argv[i] = NULL;
826         for (p = buf; p && *p; p += ret, i++) {
827                 ret = get_next_word(p, delim, &word);
828                 if (ret < 0)
829                         goto err;
830                 if (!ret)
831                         break;
832                 argv = para_realloc(argv, (i + 2) * sizeof(char*));
833                 argv[i] = word;
834         }
835         argv[i] = NULL;
836         *result = argv;
837         return i;
838 err:
839         while (i > 0)
840                 free(argv[--i]);
841         free(argv);
842         *result = NULL;
843         return ret;
844 }
845
846 /**
847  * Split a buffer into words.
848  *
849  * This parser honors single and double quotes, backslash-escaped characters
850  * and special characters like \p \\n. The result contains pointers to copies
851  * of the words contained in \a buf and has to be freed by using \ref
852  * free_argv().
853  *
854  * \param buf The buffer to be split.
855  * \param delim Each character in this string is treated as a separator.
856  * \param result The array of words is returned here.
857  *
858  * \return Number of words in \a buf, negative on errors.
859  */
860 int create_argv(const char *buf, const char *delim, char ***result)
861 {
862         return create_argv_offset(0, buf, delim, result);
863 }
864
865 /**
866  * Split a buffer into words, offset one.
867  *
868  * This is similar to \ref create_argv() but the returned array is one element
869  * larger, words start at index one and element zero is initialized to \p NULL.
870  * Callers must set element zero to a non-NULL value before calling free_argv()
871  * on the returned array to avoid a memory leak.
872  *
873  * \param buf See \ref create_argv().
874  * \param delim See \ref create_argv().
875  * \param result See \ref create_argv().
876  *
877  * \return Number of words plus one on success, negative on errors.
878  */
879 int create_shifted_argv(const char *buf, const char *delim, char ***result)
880 {
881         return create_argv_offset(1, buf, delim, result);
882 }
883
884 /**
885  * Find out if the given string is contained in the arg vector.
886  *
887  * \param arg The string to look for.
888  * \param argv The array to search.
889  *
890  * \return The first index whose value equals \a arg, or \p -E_ARG_NOT_FOUND if
891  * arg was not found in \a argv.
892  */
893 int find_arg(const char *arg, char **argv)
894 {
895         int i;
896
897         if (!argv)
898                 return -E_ARG_NOT_FOUND;
899         for (i = 0; argv[i]; i++)
900                 if (strcmp(arg, argv[i]) == 0)
901                         return i;
902         return -E_ARG_NOT_FOUND;
903 }
904
905 /**
906  * Compile a regular expression.
907  *
908  * This simple wrapper calls regcomp() and logs a message on errors.
909  *
910  * \param preg See regcomp(3).
911  * \param regex See regcomp(3).
912  * \param cflags See regcomp(3).
913  *
914  * \return Standard.
915  */
916 int para_regcomp(regex_t *preg, const char *regex, int cflags)
917 {
918         char *buf;
919         size_t size;
920         int ret = regcomp(preg, regex, cflags);
921
922         if (ret == 0)
923                 return 1;
924         size = regerror(ret, preg, NULL, 0);
925         buf = para_malloc(size);
926         regerror(ret, preg, buf, size);
927         PARA_ERROR_LOG("%s\n", buf);
928         free(buf);
929         return -E_REGEX;
930 }
931
932 /**
933  * strdup() for not necessarily zero-terminated strings.
934  *
935  * \param src The source buffer.
936  * \param len The number of bytes to be copied.
937  *
938  * \return A 0-terminated buffer of length \a len + 1.
939  *
940  * This is similar to strndup(), which is a GNU extension. However, one
941  * difference is that strndup() returns \p NULL if insufficient memory was
942  * available while this function aborts in this case.
943  *
944  * \sa strdup(), \ref para_strdup().
945  */
946 char *safe_strdup(const char *src, size_t len)
947 {
948         char *p;
949
950         assert(len < (size_t)-1);
951         p = para_malloc(len + 1);
952         if (len > 0)
953                 memcpy(p, src, len);
954         p[len] = '\0';
955         return p;
956 }
957
958 /**
959  * Copy the value of a key=value pair.
960  *
961  * This checks whether the given buffer starts with "key=", ignoring case. If
962  * yes, a copy of the value is returned. The source buffer may not be
963  * zero-terminated.
964  *
965  * \param src The source buffer.
966  * \param len The number of bytes of the tag.
967  * \param key Only copy if it is the value of this key.
968  *
969  * \return A zero-terminated buffer, or \p NULL if the key was
970  * not of the given type.
971  */
972 char *key_value_copy(const char *src, size_t len, const char *key)
973 {
974         int keylen = strlen(key);
975
976         if (len <= keylen)
977                 return NULL;
978         if (strncasecmp(src, key, keylen))
979                 return NULL;
980         if (src[keylen] != '=')
981                 return NULL;
982         return safe_strdup(src + keylen + 1, len - keylen - 1);
983 }