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