]> git.tuebingen.mpg.de Git - paraslash.git/blob - string.c
string: Introduce arr_realloc() and check for integer overflow.
[paraslash.git] / string.c
1 /* Copyright (C) 2004 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file string.c Memory allocation and string handling functions. */
4
5 #include "para.h"
6
7 #include <pwd.h>
8 #include <sys/utsname.h> /* uname() */
9 #include <regex.h>
10 #include <langinfo.h>
11 #include <wchar.h>
12 #include <wctype.h>
13
14 #include "string.h"
15 #include "error.h"
16
17 /**
18  * Reallocate an array, abort on failure or bugs.
19  *
20  * \param ptr Pointer to the memory block, may be NULL.
21  * \param nmemb Number of elements.
22  * \param size The size of one element in bytes.
23  *
24  * A wrapper for realloc(3) which aborts on invalid arguments or integer
25  * overflow. The wrapper also terminates the current process on allocation
26  * errors, so the caller does not need to check for failure.
27  *
28  * \return A pointer to newly allocated memory which is suitably aligned for
29  * any kind of variable and may be different from ptr.
30  *
31  * \sa realloc(3).
32  */
33 __must_check void *arr_realloc(void *ptr, size_t nmemb, size_t size)
34 {
35         size_t pr;
36
37         assert(size > 0);
38         assert(nmemb > 0);
39         assert(!__builtin_mul_overflow(nmemb, size, &pr));
40         assert(pr != 0);
41         ptr = realloc(ptr, pr);
42         assert(ptr);
43         return ptr;
44 }
45
46 /**
47  * Paraslash's version of realloc().
48  *
49  * \param p Pointer to the memory block, may be \p NULL.
50  * \param size The desired new size.
51  *
52  * A wrapper for realloc(3). It calls \p exit(\p EXIT_FAILURE) on errors,
53  * i.e. there is no need to check the return value in the caller.
54  *
55  * \return A pointer to newly allocated memory which is suitably aligned for
56  * any kind of variable and may be different from \a p.
57  *
58  * \sa realloc(3).
59  */
60 __must_check void *para_realloc(void *p, size_t size)
61 {
62         return arr_realloc(p, 1, size);
63 }
64
65 /**
66  * Paraslash's version of malloc().
67  *
68  * \param size The desired new size.
69  *
70  * A wrapper for malloc(3) which exits on errors.
71  *
72  * \return A pointer to the allocated memory, which is suitably aligned for any
73  * kind of variable.
74  *
75  * \sa malloc(3).
76  */
77 __must_check __malloc void *alloc(size_t size)
78 {
79         void *p;
80
81         assert(size);
82         p = malloc(size);
83         if (!p) {
84                 PARA_EMERG_LOG("malloc failed (size = %zu), aborting\n",
85                         size);
86                 exit(EXIT_FAILURE);
87         }
88         return p;
89 }
90
91 /**
92  * Allocate and initialize memory.
93  *
94  * \param size The desired new size.
95  *
96  * \return A pointer to the allocated and zeroed-out memory, which is suitably
97  * aligned for any kind of variable.
98  *
99  * \sa \ref alloc(), calloc(3).
100  */
101 __must_check __malloc void *zalloc(size_t size)
102 {
103         void *ret = alloc(size);
104
105         memset(ret, 0, size);
106         return ret;
107 }
108
109 /**
110  * Paraslash's version of strdup().
111  *
112  * \param s The string to be duplicated.
113  *
114  * A strdup(3)-like function which aborts if insufficient memory was available
115  * to allocate the duplicated string, absolving the caller from the
116  * responsibility to check for failure.
117  *
118  * \return A pointer to the duplicated string. Unlike strdup(3), the caller may
119  * pass NULL, in which case the function returns a pointer to an empty string.
120  * Regardless of whether or not NULL was passed, the returned string is
121  * allocated on the heap and has to be freed by the caller.
122  *
123  * \sa strdup(3).
124  */
125 __must_check __malloc char *para_strdup(const char *s)
126 {
127         char *dupped_string = strdup(s? s: "");
128
129         assert(dupped_string);
130         return dupped_string;
131 }
132
133 /**
134  * Print a formatted message to a dynamically allocated string.
135  *
136  * \param result The formatted string is returned here.
137  * \param fmt The format string.
138  * \param ap Initialized list of arguments.
139  *
140  * This function is similar to vasprintf(), a GNU extension which is not in C
141  * or POSIX. It allocates a string large enough to hold the output including
142  * the terminating null byte. The allocated string is returned via the first
143  * argument and must be freed by the caller. However, unlike vasprintf(), this
144  * function calls exit() if insufficient memory is available, while vasprintf()
145  * returns -1 in this case.
146  *
147  * \return Number of bytes written, not including the terminating \p NULL
148  * character.
149  *
150  * \sa printf(3), vsnprintf(3), va_start(3), vasprintf(3), \ref xasprintf().
151  */
152 __printf_2_0 unsigned xvasprintf(char **result, const char *fmt, va_list ap)
153 {
154         int ret;
155         size_t size = 150;
156         va_list aq;
157
158         *result = alloc(size + 1);
159         va_copy(aq, ap);
160         ret = vsnprintf(*result, size, fmt, aq);
161         va_end(aq);
162         assert(ret >= 0);
163         if (ret < size) /* OK */
164                 return ret;
165         size = ret + 1;
166         *result = para_realloc(*result, size);
167         va_copy(aq, ap);
168         ret = vsnprintf(*result, size, fmt, aq);
169         va_end(aq);
170         assert(ret >= 0 && ret < size);
171         return ret;
172 }
173
174 /**
175  * Print to a dynamically allocated string, variable number of arguments.
176  *
177  * \param result See \ref xvasprintf().
178  * \param fmt Usual format string.
179  *
180  * \return The return value of the underlying call to \ref xvasprintf().
181  *
182  * \sa \ref xvasprintf() and the references mentioned there.
183  */
184 __printf_2_3 unsigned xasprintf(char **result, const char *fmt, ...)
185 {
186         va_list ap;
187         unsigned ret;
188
189         va_start(ap, fmt);
190         ret = xvasprintf(result, fmt, ap);
191         va_end(ap);
192         return ret;
193 }
194
195 /**
196  * Allocate a sufficiently large string and print into it.
197  *
198  * \param fmt A usual format string.
199  *
200  * Produce output according to \p fmt. No artificial bound on the length of the
201  * resulting string is imposed.
202  *
203  * \return This function either returns a pointer to a string that must be
204  * freed by the caller or aborts without returning.
205  *
206  * \sa printf(3), \ref xasprintf().
207  */
208 __must_check __printf_1_2 __malloc char *make_message(const char *fmt, ...)
209 {
210         char *msg;
211         va_list ap;
212
213         va_start(ap, fmt);
214         xvasprintf(&msg, fmt, ap);
215         va_end(ap);
216         return msg;
217 }
218
219 /**
220  * Free the content of a pointer and set it to NULL.
221  *
222  * \param arg A pointer to the pointer whose content should be freed.
223  *
224  * If arg is NULL, the function returns immediately. Otherwise it frees the
225  * memory pointed to by *arg and sets *arg to NULL. Hence callers have to pass
226  * the *address* of the pointer variable that points to the memory which should
227  * be freed.
228  */
229 void freep(void *arg)
230 {
231         if (arg) {
232                 void **ptr = arg;
233                 free(*ptr);
234                 *ptr = NULL;
235         }
236 }
237
238 /**
239  * Paraslash's version of strcat().
240  *
241  * \param a String to be appended to.
242  * \param b String to append.
243  *
244  * Append \p b to \p a.
245  *
246  * \return If \a a is \p NULL, return a pointer to a copy of \a b, i.e.
247  * para_strcat(NULL, b) is equivalent to para_strdup(b). If \a b is \p NULL,
248  * return \a a without making a copy of \a a.  Otherwise, construct the
249  * concatenation \a c, free \a a (but not \a b) and return \a c.
250  *
251  * \sa strcat(3).
252  */
253 __must_check __malloc char *para_strcat(char *a, const char *b)
254 {
255         char *tmp;
256
257         if (!a)
258                 return para_strdup(b);
259         if (!b)
260                 return a;
261         tmp = make_message("%s%s", a, b);
262         free(a);
263         return tmp;
264 }
265
266 /**
267  * Get the logname of the current user.
268  *
269  * \return A dynamically allocated string that must be freed by the caller. On
270  * errors, the string "unknown_user" is returned, i.e. this function never
271  * returns \p NULL.
272  *
273  * \sa getpwuid(3).
274  */
275 __must_check __malloc char *para_logname(void)
276 {
277         struct passwd *pw = getpwuid(getuid());
278         return para_strdup(pw? pw->pw_name : "unknown_user");
279 }
280
281 /**
282  * Get the home directory of the current user.
283  *
284  * \return A dynamically allocated string that must be freed by the caller. If
285  * the home directory could not be found, this function returns "/tmp".
286  */
287 __must_check __malloc char *para_homedir(void)
288 {
289         struct passwd *pw = getpwuid(getuid());
290         return para_strdup(pw? pw->pw_dir : "/tmp");
291 }
292
293 /**
294  * Get the own hostname.
295  *
296  * \return A dynamically allocated string containing the hostname.
297  *
298  * \sa uname(2).
299  */
300 __malloc char *para_hostname(void)
301 {
302         struct utsname u;
303
304         uname(&u);
305         return para_strdup(u.nodename);
306 }
307
308 /**
309  * Call a custom function for each complete line.
310  *
311  * \param flags Any combination of flags defined in \ref for_each_line_flags.
312  * \param buf The buffer containing data separated by newlines.
313  * \param size The number of bytes in \a buf.
314  * \param line_handler The custom function.
315  * \param private_data Pointer passed to \a line_handler.
316  *
317  * For each complete line in \p buf, \p line_handler is called. The first
318  * argument to \p line_handler is (a copy of) the current line, and \p
319  * private_data is passed as the second argument.  If the \p FELF_READ_ONLY
320  * flag is unset, a pointer into \a buf is passed to the line handler,
321  * otherwise a pointer to a copy of the current line is passed instead. This
322  * copy is freed immediately after the line handler returns.
323  *
324  * The function returns if \p line_handler returns a negative value or no more
325  * lines are in the buffer.  The rest of the buffer (last chunk containing an
326  * incomplete line) is moved to the beginning of the buffer if FELF_READ_ONLY is
327  * unset.
328  *
329  * \return On success this function returns the number of bytes not handled to
330  * \p line_handler. The only possible error is a negative return value from the
331  * line handler. In this case processing stops and the return value of the line
332  * handler is returned to indicate failure.
333  *
334  * \sa \ref for_each_line_flags.
335  */
336 int for_each_line(unsigned flags, char *buf, size_t size,
337                 line_handler_t *line_handler, void *private_data)
338 {
339         char *start = buf, *end;
340         int ret, i, num_lines = 0;
341
342 //      PARA_NOTICE_LOG("buf: %s\n", buf);
343         while (start < buf + size) {
344                 char *next_null;
345                 char *next_cr;
346
347                 next_cr = memchr(start, '\n', buf + size - start);
348                 next_null = memchr(start, '\0', next_cr?
349                         next_cr - start : buf + size - start);
350                 if (!next_cr && !next_null)
351                         break;
352                 if (next_null)
353                         end = next_null;
354                 else
355                         end = next_cr;
356                 num_lines++;
357                 if (!(flags & FELF_DISCARD_FIRST) || start != buf) {
358                         if (flags & FELF_READ_ONLY) {
359                                 size_t s = end - start;
360                                 char *b = alloc(s + 1);
361                                 memcpy(b, start, s);
362                                 b[s] = '\0';
363                                 ret = line_handler(b, private_data);
364                                 free(b);
365                         } else {
366                                 *end = '\0';
367                                 ret = line_handler(start, private_data);
368                         }
369                         if (ret < 0)
370                                 return ret;
371                 }
372                 start = ++end;
373         }
374         i = buf + size - start;
375         if (i && i != size && !(flags & FELF_READ_ONLY))
376                 memmove(buf, start, i);
377         return i;
378 }
379
380 /** Return the hex characters of the lower 4 bits. */
381 #define hex(a) (hexchar[(a) & 15])
382
383 static void write_size_header(char *buf, int n)
384 {
385         static char hexchar[] = "0123456789abcdef";
386
387         buf[0] = hex(n >> 12);
388         buf[1] = hex(n >> 8);
389         buf[2] = hex(n >> 4);
390         buf[3] = hex(n);
391         buf[4] = ' ';
392 }
393
394 /**
395  * Read a four-byte hex-number and return its value.
396  *
397  * Each status item sent by para_server is prefixed with such a hex number in
398  * ASCII which describes the size of the status item.
399  *
400  * \param buf The buffer which must be at least four bytes long.
401  *
402  * \return The value of the hex number on success, \p -E_SIZE_PREFIX if the
403  * buffer did not contain only hex digits.
404  */
405 int read_size_header(const char *buf)
406 {
407         int i, len = 0;
408
409         for (i = 0; i < 4; i++) {
410                 unsigned char c = buf[i];
411                 len <<= 4;
412                 if (c >= '0' && c <= '9') {
413                         len += c - '0';
414                         continue;
415                 }
416                 if (c >= 'a' && c <= 'f') {
417                         len += c - 'a' + 10;
418                         continue;
419                 }
420                 return -E_SIZE_PREFIX;
421         }
422         if (buf[4] != ' ')
423                 return -E_SIZE_PREFIX;
424         return len;
425 }
426
427 /**
428  * Safely print into a buffer at a given offset.
429  *
430  * \param b Determines the buffer, its size, and the offset.
431  * \param fmt The format string.
432  *
433  * This function prints into the buffer given by \a b at the offset which is
434  * also given by \a b. If there is not enough space to hold the result, the
435  * buffer size is doubled until the underlying call to vsnprintf() succeeds
436  * or the size of the buffer exceeds the maximal size specified in \a b.
437  *
438  * In the latter case the unmodified \a buf and \a offset values as well as the
439  * private_data pointer of \a b are passed to the \a max_size_handler of \a b.
440  * If this function succeeds, i.e. returns a non-negative value, the offset of
441  * \a b is reset to zero and the given data is written to the beginning of the
442  * buffer. If \a max_size_handler() returns a negative value, this value is
443  * returned by \a para_printf().
444  *
445  * Upon return, the offset of \a b is adjusted accordingly so that subsequent
446  * calls to this function append data to what is already contained in the
447  * buffer.
448  *
449  * It's OK to call this function with \p b->buf being \p NULL. In this case, an
450  * initial buffer is allocated.
451  *
452  * \return The number of bytes printed into the buffer (not including the
453  * terminating \p NULL byte) on success, negative on errors. If there is no
454  * size-bound on \a b, i.e. if \p b->max_size is zero, this function never
455  * fails.
456  *
457  * \sa make_message(), vsnprintf(3).
458  */
459 __printf_2_3 int para_printf(struct para_buffer *b, const char *fmt, ...)
460 {
461         int ret, sz_off = (b->flags & PBF_SIZE_PREFIX)? 5 : 0;
462
463         if (!b->buf) {
464                 b->buf = alloc(128);
465                 b->size = 128;
466                 b->offset = 0;
467         }
468         while (1) {
469                 char *p = b->buf + b->offset;
470                 size_t size = b->size - b->offset;
471                 va_list ap;
472
473                 if (size > sz_off) {
474                         va_start(ap, fmt);
475                         ret = vsnprintf(p + sz_off, size - sz_off, fmt, ap);
476                         va_end(ap);
477                         if (ret > -1 && ret < size - sz_off) { /* success */
478                                 b->offset += ret + sz_off;
479                                 if (sz_off)
480                                         write_size_header(p, ret);
481                                 return ret + sz_off;
482                         }
483                 }
484                 /* check if we may grow the buffer */
485                 if (!b->max_size || 2 * b->size < b->max_size) { /* yes */
486                         /* try again with more space */
487                         b->size *= 2;
488                         b->buf = para_realloc(b->buf, b->size);
489                         continue;
490                 }
491                 /* can't grow buffer */
492                 if (!b->offset || !b->max_size_handler) /* message too large */
493                         return -ERRNO_TO_PARA_ERROR(ENOSPC);
494                 ret = b->max_size_handler(b->buf, b->offset, b->private_data);
495                 if (ret < 0)
496                         return ret;
497                 b->offset = 0;
498         }
499 }
500
501 /** \cond llong_minmax */
502 /* LLONG_MAX and LLONG_MIN might not be defined. */
503 #ifndef LLONG_MAX
504 #define LLONG_MAX 9223372036854775807LL
505 #endif
506 #ifndef LLONG_MIN
507 #define LLONG_MIN (-LLONG_MAX - 1LL)
508 #endif
509 /** \endcond llong_minmax */
510
511 /**
512  * Convert a string to a 64-bit signed integer value.
513  *
514  * \param str The string to be converted.
515  * \param value Result pointer.
516  *
517  * \return Standard.
518  *
519  * \sa \ref para_atoi32(), strtol(3), atoi(3).
520  */
521 int para_atoi64(const char *str, int64_t *value)
522 {
523         char *endptr;
524         long long tmp;
525
526         errno = 0; /* To distinguish success/failure after call */
527         tmp = strtoll(str, &endptr, 10);
528         if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
529                 return -E_ATOI_OVERFLOW;
530         /*
531          * If there were no digits at all, strtoll() stores the original value
532          * of str in *endptr.
533          */
534         if (endptr == str)
535                 return -E_ATOI_NO_DIGITS;
536         /*
537          * The implementation may also set errno and return 0 in case no
538          * conversion was performed.
539          */
540         if (errno != 0 && tmp == 0)
541                 return -E_ATOI_NO_DIGITS;
542         if (*endptr != '\0') /* Further characters after number */
543                 return -E_ATOI_JUNK_AT_END;
544         *value = tmp;
545         return 1;
546 }
547
548 /**
549  * Convert a string to a 32-bit signed integer value.
550  *
551  * \param str The string to be converted.
552  * \param value Result pointer.
553  *
554  * \return Standard.
555  *
556  * \sa \ref para_atoi64().
557 */
558 int para_atoi32(const char *str, int32_t *value)
559 {
560         int64_t tmp;
561         int ret;
562         const int32_t max = 2147483647;
563
564         ret = para_atoi64(str, &tmp);
565         if (ret < 0)
566                 return ret;
567         if (tmp > max || tmp < -max - 1)
568                 return -E_ATOI_OVERFLOW;
569         *value = tmp;
570         return 1;
571 }
572
573 static inline int loglevel_equal(const char *arg, const char * const ll)
574 {
575         return !strncasecmp(arg, ll, strlen(ll));
576 }
577
578 /**
579  * Compute the loglevel number from its name.
580  *
581  * \param txt The name of the loglevel (debug, info, ...).
582  *
583  * \return The numeric representation of the loglevel name.
584  */
585 int get_loglevel_by_name(const char *txt)
586 {
587         if (loglevel_equal(txt, "debug"))
588                 return LL_DEBUG;
589         if (loglevel_equal(txt, "info"))
590                 return LL_INFO;
591         if (loglevel_equal(txt, "notice"))
592                 return LL_NOTICE;
593         if (loglevel_equal(txt, "warning"))
594                 return LL_WARNING;
595         if (loglevel_equal(txt, "error"))
596                 return LL_ERROR;
597         if (loglevel_equal(txt, "crit"))
598                 return LL_CRIT;
599         if (loglevel_equal(txt, "emerg"))
600                 return LL_EMERG;
601         return -E_BAD_LL;
602 }
603
604 static int get_next_word(const char *buf, const char *delim, char **word)
605 {
606         enum line_state_flags {LSF_HAVE_WORD = 1, LSF_BACKSLASH = 2,
607                 LSF_SINGLE_QUOTE = 4, LSF_DOUBLE_QUOTE = 8};
608         const char *in;
609         char *out;
610         int ret, state = 0;
611
612         out = alloc(strlen(buf) + 1);
613         *out = '\0';
614         *word = out;
615         for (in = buf; *in; in++) {
616                 const char *p;
617
618                 switch (*in) {
619                 case '\\':
620                         if (state & LSF_BACKSLASH) /* \\ */
621                                 goto copy_char;
622                         state |= LSF_BACKSLASH;
623                         state |= LSF_HAVE_WORD;
624                         continue;
625                 case 'n':
626                 case 't':
627                         if (state & LSF_BACKSLASH) { /* \n or \t */
628                                 *out++ = (*in == 'n')? '\n' : '\t';
629                                 state &= ~LSF_BACKSLASH;
630                                 continue;
631                         }
632                         goto copy_char;
633                 case '"':
634                         if (state & LSF_BACKSLASH) /* \" */
635                                 goto copy_char;
636                         if (state & LSF_SINGLE_QUOTE) /* '" */
637                                 goto copy_char;
638                         if (state & LSF_DOUBLE_QUOTE) {
639                                 state &= ~LSF_DOUBLE_QUOTE;
640                                 continue;
641                         }
642                         state |= LSF_HAVE_WORD;
643                         state |= LSF_DOUBLE_QUOTE;
644                         continue;
645                 case '\'':
646                         if (state & LSF_BACKSLASH) /* \' */
647                                 goto copy_char;
648                         if (state & LSF_DOUBLE_QUOTE) /* "' */
649                                 goto copy_char;
650                         if (state & LSF_SINGLE_QUOTE) {
651                                 state &= ~LSF_SINGLE_QUOTE;
652                                 continue;
653                         }
654                         state |= LSF_HAVE_WORD;
655                         state |= LSF_SINGLE_QUOTE;
656                         continue;
657                 }
658                 for (p = delim; *p; p++) {
659                         if (*in != *p)
660                                 continue;
661                         if (state & LSF_BACKSLASH)
662                                 goto copy_char;
663                         if (state & LSF_SINGLE_QUOTE)
664                                 goto copy_char;
665                         if (state & LSF_DOUBLE_QUOTE)
666                                 goto copy_char;
667                         if (state & LSF_HAVE_WORD)
668                                 goto success;
669                         break;
670                 }
671                 if (*p) /* ignore delimiter at the beginning */
672                         continue;
673 copy_char:
674                 state |= LSF_HAVE_WORD;
675                 *out++ = *in;
676                 state &= ~LSF_BACKSLASH;
677         }
678         ret = 0;
679         if (!(state & LSF_HAVE_WORD))
680                 goto out;
681         ret = -ERRNO_TO_PARA_ERROR(EINVAL);
682         if (state & LSF_BACKSLASH) {
683                 PARA_ERROR_LOG("trailing backslash\n");
684                 goto out;
685         }
686         if ((state & LSF_SINGLE_QUOTE) || (state & LSF_DOUBLE_QUOTE)) {
687                 PARA_ERROR_LOG("unmatched quote character\n");
688                 goto out;
689         }
690 success:
691         *out = '\0';
692         return in - buf;
693 out:
694         free(*word);
695         *word = NULL;
696         return ret;
697 }
698
699 /**
700  * Get the number of the word the cursor is on.
701  *
702  * \param buf The zero-terminated line buffer.
703  * \param delim Characters that separate words.
704  * \param point The cursor position.
705  *
706  * \return Zero-based word number.
707  */
708 int compute_word_num(const char *buf, const char *delim, int point)
709 {
710         int ret, num_words;
711         const char *p;
712         char *word;
713
714         for (p = buf, num_words = 0; ; p += ret, num_words++) {
715                 ret = get_next_word(p, delim, &word);
716                 if (ret <= 0)
717                         break;
718                 free(word);
719                 if (p + ret >= buf + point)
720                         break;
721         }
722         return num_words;
723 }
724
725 /**
726  * Free an array of words created by create_argv() or create_shifted_argv().
727  *
728  * \param argv A pointer previously obtained by \ref create_argv().
729  */
730 void free_argv(char **argv)
731 {
732         int i;
733
734         if (!argv)
735                 return;
736         for (i = 0; argv[i]; i++)
737                 free(argv[i]);
738         free(argv);
739 }
740
741 static int create_argv_offset(int offset, const char *buf, const char *delim,
742                 char ***result)
743 {
744         char *word, **argv = alloc((offset + 1) * sizeof(char *));
745         const char *p;
746         int i, ret;
747
748         for (i = 0; i < offset; i++)
749                 argv[i] = NULL;
750         for (p = buf; p && *p; p += ret, i++) {
751                 ret = get_next_word(p, delim, &word);
752                 if (ret < 0)
753                         goto err;
754                 if (!ret)
755                         break;
756                 argv = arr_realloc(argv, i + 2, sizeof(char*));
757                 argv[i] = word;
758         }
759         argv[i] = NULL;
760         *result = argv;
761         return i;
762 err:
763         while (i > 0)
764                 free(argv[--i]);
765         free(argv);
766         *result = NULL;
767         return ret;
768 }
769
770 /**
771  * Split a buffer into words.
772  *
773  * This parser honors single and double quotes, backslash-escaped characters
774  * and special characters like \\n. The result contains pointers to copies of
775  * the words contained in buf and has to be freed by using \ref free_argv().
776  *
777  * \param buf The buffer to be split.
778  * \param delim Each character in this string is treated as a separator.
779  * \param result The array of words is returned here.
780  *
781  * It's OK to pass NULL as the buffer argument. This is equivalent to passing
782  * the empty string.
783  *
784  * \return Number of words in buf, negative on errors. The array returned
785  * through the result pointer is NULL terminated.
786  */
787 int create_argv(const char *buf, const char *delim, char ***result)
788 {
789         return create_argv_offset(0, buf, delim, result);
790 }
791
792 /**
793  * Split a buffer into words, offset one.
794  *
795  * This is similar to \ref create_argv() but the returned array is one element
796  * larger, words start at index one and element zero is initialized to \p NULL.
797  * Callers must set element zero to a non-NULL value before calling free_argv()
798  * on the returned array to avoid a memory leak.
799  *
800  * \param buf See \ref create_argv().
801  * \param delim See \ref create_argv().
802  * \param result See \ref create_argv().
803  *
804  * \return Number of words plus one on success, negative on errors.
805  */
806 int create_shifted_argv(const char *buf, const char *delim, char ***result)
807 {
808         return create_argv_offset(1, buf, delim, result);
809 }
810
811 /**
812  * Find out if the given string is contained in the arg vector.
813  *
814  * \param arg The string to look for.
815  * \param argv The array to search.
816  *
817  * \return The first index whose value equals \a arg, or \p -E_ARG_NOT_FOUND if
818  * arg was not found in \a argv.
819  */
820 int find_arg(const char *arg, char **argv)
821 {
822         int i;
823
824         if (!argv)
825                 return -E_ARG_NOT_FOUND;
826         for (i = 0; argv[i]; i++)
827                 if (strcmp(arg, argv[i]) == 0)
828                         return i;
829         return -E_ARG_NOT_FOUND;
830 }
831
832 /**
833  * Compile a regular expression.
834  *
835  * This simple wrapper calls regcomp() and logs a message on errors.
836  *
837  * \param preg See regcomp(3).
838  * \param regex See regcomp(3).
839  * \param cflags See regcomp(3).
840  *
841  * \return Standard.
842  */
843 int para_regcomp(regex_t *preg, const char *regex, int cflags)
844 {
845         char *buf;
846         size_t size;
847         int ret = regcomp(preg, regex, cflags);
848
849         if (ret == 0)
850                 return 1;
851         size = regerror(ret, preg, NULL, 0);
852         buf = alloc(size);
853         regerror(ret, preg, buf, size);
854         PARA_ERROR_LOG("%s\n", buf);
855         free(buf);
856         return -E_REGEX;
857 }
858
859 /**
860  * strdup() for not necessarily zero-terminated strings.
861  *
862  * \param src The source buffer.
863  * \param len The number of bytes to be copied.
864  *
865  * \return A 0-terminated buffer of length \a len + 1.
866  *
867  * This is similar to strndup(), which is a GNU extension. However, one
868  * difference is that strndup() returns \p NULL if insufficient memory was
869  * available while this function aborts in this case.
870  *
871  * \sa strdup(), \ref para_strdup().
872  */
873 char *safe_strdup(const char *src, size_t len)
874 {
875         char *p;
876
877         assert(len < (size_t)-1);
878         p = alloc(len + 1);
879         if (len > 0)
880                 memcpy(p, src, len);
881         p[len] = '\0';
882         return p;
883 }
884
885 /**
886  * Copy the value of a key=value pair.
887  *
888  * This checks whether the given buffer starts with "key=", ignoring case. If
889  * yes, a copy of the value is returned. The source buffer may not be
890  * zero-terminated.
891  *
892  * \param src The source buffer.
893  * \param len The number of bytes of the tag.
894  * \param key Only copy if it is the value of this key.
895  *
896  * \return A zero-terminated buffer, or \p NULL if the key was
897  * not of the given type.
898  */
899 char *key_value_copy(const char *src, size_t len, const char *key)
900 {
901         int keylen = strlen(key);
902
903         if (len <= keylen)
904                 return NULL;
905         if (strncasecmp(src, key, keylen))
906                 return NULL;
907         if (src[keylen] != '=')
908                 return NULL;
909         return safe_strdup(src + keylen + 1, len - keylen - 1);
910 }
911
912 static bool utf8_mode(void)
913 {
914         static bool initialized, have_utf8;
915
916         if (!initialized) {
917                 char *info = nl_langinfo(CODESET);
918                 have_utf8 = (info && strcmp(info, "UTF-8") == 0);
919                 initialized = true;
920                 PARA_INFO_LOG("%susing UTF-8 character encoding\n",
921                         have_utf8? "" : "not ");
922         }
923         return have_utf8;
924 }
925
926 static int xwcwidth(wchar_t wc, size_t pos)
927 {
928         int n;
929
930         /* special-case for tab */
931         if (wc == 0x09) /* tab */
932                 return (pos | 7) + 1 - pos;
933         n = wcwidth(wc);
934         /* wcswidth() returns -1 for non-printable characters */
935         return n >= 0? n : 1;
936 }
937
938 static size_t xwcswidth(const wchar_t *s, size_t n)
939 {
940         size_t w = 0;
941
942         while (n--)
943                 w += xwcwidth(*s++, w);
944         return w;
945 }
946
947 /**
948  * Skip a given number of cells at the beginning of a string.
949  *
950  * \param s The input string.
951  * \param cells_to_skip Desired number of cells that should be skipped.
952  * \param bytes_to_skip Result.
953  *
954  * This function computes how many input bytes must be skipped to advance a
955  * string by the given width. If the current character encoding is not UTF-8,
956  * this is simply the given number of cells, i.e. \a cells_to_skip. Otherwise,
957  * \a s is treated as a multibyte string and on successful return, \a s +
958  * bytes_to_skip points to the start of a multibyte string such that the total
959  * width of the multibyte characters that are skipped by advancing \a s that
960  * many bytes equals at least \a cells_to_skip.
961  *
962  * \return Standard.
963  */
964 int skip_cells(const char *s, size_t cells_to_skip, size_t *bytes_to_skip)
965 {
966         wchar_t wc;
967         mbstate_t ps;
968         size_t n, bytes_parsed, cells_skipped;
969
970         *bytes_to_skip = 0;
971         if (cells_to_skip == 0)
972                 return 0;
973         if (!utf8_mode()) {
974                 *bytes_to_skip = cells_to_skip;
975                 return 0;
976         }
977         bytes_parsed = cells_skipped = 0;
978         memset(&ps, 0, sizeof(ps));
979         n = strlen(s);
980         while (cells_to_skip > cells_skipped) {
981                 size_t mbret;
982
983                 mbret = mbrtowc(&wc, s + bytes_parsed, n - bytes_parsed, &ps);
984                 assert(mbret != 0);
985                 if (mbret == (size_t)-1 || mbret == (size_t)-2)
986                         return -ERRNO_TO_PARA_ERROR(EILSEQ);
987                 bytes_parsed += mbret;
988                 cells_skipped += xwcwidth(wc, cells_skipped);
989         }
990         *bytes_to_skip = bytes_parsed;
991         return 1;
992 }
993
994 /**
995  * Compute the width of an UTF-8 string.
996  *
997  * \param s The string.
998  * \param result The width of \a s is returned here.
999  *
1000  * If not in UTF8-mode. this function is just a wrapper for strlen(3).
1001  * Otherwise \a s is treated as an UTF-8 string and its display width is
1002  * computed. Note that this function may fail if the underlying call to
1003  * mbsrtowcs(3) fails, so the caller must check the return value.
1004  *
1005  * \sa nl_langinfo(3), wcswidth(3).
1006  *
1007  * \return Standard.
1008  */
1009 __must_check int strwidth(const char *s, size_t *result)
1010 {
1011         const char *src = s;
1012         mbstate_t state;
1013         static wchar_t *dest;
1014         size_t num_wchars;
1015
1016         /*
1017          * Never call any log function here. This may result in an endless loop
1018          * as para_gui's para_log() calls this function.
1019          */
1020
1021         if (!utf8_mode()) {
1022                 *result = strlen(s);
1023                 return 0;
1024         }
1025         memset(&state, 0, sizeof(state));
1026         *result = 0;
1027         num_wchars = mbsrtowcs(NULL, &src, 0, &state);
1028         if (num_wchars == (size_t)-1)
1029                 return -ERRNO_TO_PARA_ERROR(errno);
1030         if (num_wchars == 0)
1031                 return 0;
1032         dest = alloc((num_wchars + 1) * sizeof(*dest));
1033         src = s;
1034         memset(&state, 0, sizeof(state));
1035         num_wchars = mbsrtowcs(dest, &src, num_wchars, &state);
1036         assert(num_wchars > 0 && num_wchars != (size_t)-1);
1037         *result = xwcswidth(dest, num_wchars);
1038         free(dest);
1039         return 1;
1040 }
1041
1042 /**
1043  * Truncate and sanitize a (wide character) string.
1044  *
1045  * This replaces all non-printable characters by spaces and makes sure that the
1046  * modified string does not exceed the given maximal width.
1047  *
1048  * \param src The source string in multi-byte form.
1049  * \param max_width The maximal number of cells the result may occupy.
1050  * \param result Sanitized multi-byte string, must be freed by caller.
1051  * \param width The width of the sanitized string, always <= max_width.
1052  *
1053  * The function is wide-character aware but falls back to C strings for
1054  * non-UTF-8 locales.
1055  *
1056  * \return Standard. On success, *result points to a sanitized copy of the
1057  * given string. This copy was allocated with malloc() and should hence be
1058  * freed when the caller is no longer interested in the result.
1059  *
1060  * The function fails if the given string contains an invalid multibyte
1061  * sequence. In this case, *result is set to NULL, and *width to zero.
1062  */
1063 __must_check int sanitize_str(const char *src, size_t max_width,
1064                 char **result, size_t *width)
1065 {
1066         mbstate_t state;
1067         static wchar_t *wcs;
1068         size_t num_wchars, n;
1069
1070         if (!utf8_mode()) {
1071                 *result = para_strdup(src);
1072                 /* replace non-printable characters by spaces */
1073                 for (n = 0; n < max_width && src[n]; n++) {
1074                         if (!isprint((unsigned char)src[n]))
1075                                 (*result)[n] = ' ';
1076                 }
1077                 (*result)[n] = '\0';
1078                 *width = n;
1079                 return 0;
1080         }
1081         *result = NULL;
1082         *width = 0;
1083         memset(&state, 0, sizeof(state));
1084         num_wchars = mbsrtowcs(NULL, &src, 0, &state);
1085         if (num_wchars == (size_t)-1)
1086                 return -ERRNO_TO_PARA_ERROR(errno);
1087         wcs = alloc((num_wchars + 1) * sizeof(*wcs));
1088         memset(&state, 0, sizeof(state));
1089         num_wchars = mbsrtowcs(wcs, &src, num_wchars + 1, &state);
1090         assert(num_wchars != (size_t)-1);
1091         for (n = 0; n < num_wchars && *width < max_width; n++) {
1092                 if (!iswprint(wcs[n]))
1093                         wcs[n] = L' ';
1094                 *width += xwcwidth(wcs[n], *width);
1095         }
1096         wcs[n] = L'\0';
1097         n = wcstombs(NULL, wcs, 0) + 1;
1098         *result = alloc(n);
1099         num_wchars = wcstombs(*result, wcs, n);
1100         assert(num_wchars != (size_t)-1);
1101         free(wcs);
1102         return 1;
1103 }