]> git.tuebingen.mpg.de Git - paraslash.git/blob - string.c
Consult $HOME rather than calling getpwuid(),
[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  * Allocate an array, abort on failure or bugs.
48  *
49  * \param nmemb See \ref arr_realloc().
50  * \param size See \ref arr_realloc().
51  *
52  * Like \ref arr_realloc(), this aborts on invalid arguments, integer overflow
53  * and allocation errors.
54  *
55  * \return A pointer to newly allocated memory which is suitably aligned for
56  * any kind of variable.
57  *
58  * \sa See \ref arr_realloc().
59  */
60 __must_check __malloc void *arr_alloc(size_t nmemb, size_t size)
61 {
62         return arr_realloc(NULL, nmemb, size);
63 }
64
65 /**
66  * Allocate and initialize an array, abort on failure or bugs.
67  *
68  * \param nmemb See \ref arr_realloc().
69  * \param size See \ref arr_realloc().
70  *
71  * This calls \ref arr_alloc() and zeroes-out the array.
72  *
73  * \return See \ref arr_alloc().
74  */
75 __must_check __malloc void *arr_zalloc(size_t nmemb, size_t size)
76 {
77         void *ptr = arr_alloc(nmemb, size);
78
79         /*
80          * This multiplication can not overflow because the above call to \ref
81          * arr_alloc() aborts on overflow.
82          */
83         memset(ptr, 0, nmemb * size);
84         return ptr;
85 }
86
87 /**
88  * Allocate and initialize memory.
89  *
90  * \param size The desired new size.
91  *
92  * \return A pointer to the allocated and zeroed-out memory, which is suitably
93  * aligned for any kind of variable.
94  *
95  * \sa \ref alloc(), calloc(3).
96  */
97 __must_check void *zalloc(size_t size)
98 {
99         return arr_zalloc(1, size);
100 }
101
102 /**
103  * Paraslash's version of realloc().
104  *
105  * \param p Pointer to the memory block, may be \p NULL.
106  * \param size The desired new size.
107  *
108  * A wrapper for realloc(3). It calls \p exit(\p EXIT_FAILURE) on errors,
109  * i.e. there is no need to check the return value in the caller.
110  *
111  * \return A pointer to newly allocated memory which is suitably aligned for
112  * any kind of variable and may be different from \a p.
113  *
114  * \sa realloc(3).
115  */
116 __must_check void *para_realloc(void *p, size_t size)
117 {
118         return arr_realloc(p, 1, size);
119 }
120
121 /**
122  * Paraslash's version of malloc().
123  *
124  * \param size The desired new size.
125  *
126  * A wrapper for malloc(3) which exits on errors.
127  *
128  * \return A pointer to the allocated memory, which is suitably aligned for any
129  * kind of variable.
130  *
131  * \sa malloc(3).
132  */
133 __must_check __malloc void *alloc(size_t size)
134 {
135         return arr_alloc(1, size);
136 }
137
138 /**
139  * Paraslash's version of strdup().
140  *
141  * \param s The string to be duplicated.
142  *
143  * A strdup(3)-like function which aborts if insufficient memory was available
144  * to allocate the duplicated string, absolving the caller from the
145  * responsibility to check for failure.
146  *
147  * \return A pointer to the duplicated string. Unlike strdup(3), the caller may
148  * pass NULL, in which case the function returns a pointer to an empty string.
149  * Regardless of whether or not NULL was passed, the returned string is
150  * allocated on the heap and has to be freed by the caller.
151  *
152  * \sa strdup(3).
153  */
154 __must_check __malloc char *para_strdup(const char *s)
155 {
156         char *dupped_string = strdup(s? s: "");
157
158         assert(dupped_string);
159         return dupped_string;
160 }
161
162 /**
163  * Print a formatted message to a dynamically allocated string.
164  *
165  * \param result The formatted string is returned here.
166  * \param fmt The format string.
167  * \param ap Initialized list of arguments.
168  *
169  * This function is similar to vasprintf(), a GNU extension which is not in C
170  * or POSIX. It allocates a string large enough to hold the output including
171  * the terminating null byte. The allocated string is returned via the first
172  * argument and must be freed by the caller. However, unlike vasprintf(), this
173  * function calls exit() if insufficient memory is available, while vasprintf()
174  * returns -1 in this case.
175  *
176  * \return Number of bytes written, not including the terminating \p NULL
177  * character.
178  *
179  * \sa printf(3), vsnprintf(3), va_start(3), vasprintf(3), \ref xasprintf().
180  */
181 __printf_2_0 unsigned xvasprintf(char **result, const char *fmt, va_list ap)
182 {
183         int ret;
184         size_t size = 150;
185         va_list aq;
186
187         *result = alloc(size + 1);
188         va_copy(aq, ap);
189         ret = vsnprintf(*result, size, fmt, aq);
190         va_end(aq);
191         assert(ret >= 0);
192         if (ret < size) /* OK */
193                 return ret;
194         size = ret + 1;
195         *result = para_realloc(*result, size);
196         va_copy(aq, ap);
197         ret = vsnprintf(*result, size, fmt, aq);
198         va_end(aq);
199         assert(ret >= 0 && ret < size);
200         return ret;
201 }
202
203 /**
204  * Print to a dynamically allocated string, variable number of arguments.
205  *
206  * \param result See \ref xvasprintf().
207  * \param fmt Usual format string.
208  *
209  * \return The return value of the underlying call to \ref xvasprintf().
210  *
211  * \sa \ref xvasprintf() and the references mentioned there.
212  */
213 __printf_2_3 unsigned xasprintf(char **result, const char *fmt, ...)
214 {
215         va_list ap;
216         unsigned ret;
217
218         va_start(ap, fmt);
219         ret = xvasprintf(result, fmt, ap);
220         va_end(ap);
221         return ret;
222 }
223
224 /**
225  * Allocate a sufficiently large string and print into it.
226  *
227  * \param fmt A usual format string.
228  *
229  * Produce output according to \p fmt. No artificial bound on the length of the
230  * resulting string is imposed.
231  *
232  * \return This function either returns a pointer to a string that must be
233  * freed by the caller or aborts without returning.
234  *
235  * \sa printf(3), \ref xasprintf().
236  */
237 __must_check __printf_1_2 __malloc char *make_message(const char *fmt, ...)
238 {
239         char *msg;
240         va_list ap;
241
242         va_start(ap, fmt);
243         xvasprintf(&msg, fmt, ap);
244         va_end(ap);
245         return msg;
246 }
247
248 /**
249  * Free the content of a pointer and set it to NULL.
250  *
251  * \param arg A pointer to the pointer whose content should be freed.
252  *
253  * If arg is NULL, the function returns immediately. Otherwise it frees the
254  * memory pointed to by *arg and sets *arg to NULL. Hence callers have to pass
255  * the *address* of the pointer variable that points to the memory which should
256  * be freed.
257  */
258 void freep(void *arg)
259 {
260         if (arg) {
261                 void **ptr = arg;
262                 free(*ptr);
263                 *ptr = NULL;
264         }
265 }
266
267 /**
268  * Paraslash's version of strcat().
269  *
270  * \param a String to be appended to.
271  * \param b String to append.
272  *
273  * Append \p b to \p a.
274  *
275  * \return If \a a is \p NULL, return a pointer to a copy of \a b, i.e.
276  * para_strcat(NULL, b) is equivalent to para_strdup(b). If \a b is \p NULL,
277  * return \a a without making a copy of \a a.  Otherwise, construct the
278  * concatenation \a c, free \a a (but not \a b) and return \a c.
279  *
280  * \sa strcat(3).
281  */
282 __must_check __malloc char *para_strcat(char *a, const char *b)
283 {
284         char *tmp;
285
286         if (!a)
287                 return para_strdup(b);
288         if (!b)
289                 return a;
290         tmp = make_message("%s%s", a, b);
291         free(a);
292         return tmp;
293 }
294
295 /**
296  * Get the logname of the current user.
297  *
298  * \return A dynamically allocated string that must be freed by the caller. On
299  * errors, the string "unknown_user" is returned, i.e. this function never
300  * returns \p NULL.
301  *
302  * \sa getpwuid(3).
303  */
304 __must_check __malloc char *para_logname(void)
305 {
306         struct passwd *pw = getpwuid(getuid());
307         return para_strdup(pw? pw->pw_name : "unknown_user");
308 }
309
310 /**
311  * Investigate $HOME to get the home directory of the calling user.
312  *
313  * \return A pointer to read-only memory that must not be freed by the caller.
314  * If the environment variable HOME is unset or empty, the function prints an
315  * error message and aborts.
316  *
317  * \sa getenv(3), getuid(2).
318  */
319 const char *get_homedir(void)
320 {
321         const char *home = getenv("HOME");
322         if (home && *home)
323                 return home;
324         PARA_EMERG_LOG("fatal: HOME is unset or empty");
325         exit(EXIT_FAILURE);
326 }
327
328 /**
329  * Get the own hostname.
330  *
331  * \return A dynamically allocated string containing the hostname.
332  *
333  * \sa uname(2).
334  */
335 __malloc char *para_hostname(void)
336 {
337         struct utsname u;
338
339         uname(&u);
340         return para_strdup(u.nodename);
341 }
342
343 /**
344  * Call a custom function for each complete line.
345  *
346  * \param flags Any combination of flags defined in \ref for_each_line_flags.
347  * \param buf The buffer containing data separated by newlines.
348  * \param size The number of bytes in \a buf.
349  * \param line_handler The custom function.
350  * \param private_data Pointer passed to \a line_handler.
351  *
352  * For each complete line in \p buf, \p line_handler is called. The first
353  * argument to \p line_handler is (a copy of) the current line, and \p
354  * private_data is passed as the second argument.  If the \p FELF_READ_ONLY
355  * flag is unset, a pointer into \a buf is passed to the line handler,
356  * otherwise a pointer to a copy of the current line is passed instead. This
357  * copy is freed immediately after the line handler returns.
358  *
359  * The function returns if \p line_handler returns a negative value or no more
360  * lines are in the buffer.  The rest of the buffer (last chunk containing an
361  * incomplete line) is moved to the beginning of the buffer if FELF_READ_ONLY is
362  * unset.
363  *
364  * \return On success this function returns the number of bytes not handled to
365  * \p line_handler. The only possible error is a negative return value from the
366  * line handler. In this case processing stops and the return value of the line
367  * handler is returned to indicate failure.
368  *
369  * \sa \ref for_each_line_flags.
370  */
371 int for_each_line(unsigned flags, char *buf, size_t size,
372                 line_handler_t *line_handler, void *private_data)
373 {
374         char *start = buf, *end;
375         int ret, i, num_lines = 0;
376
377 //      PARA_NOTICE_LOG("buf: %s\n", buf);
378         while (start < buf + size) {
379                 char *next_null;
380                 char *next_cr;
381
382                 next_cr = memchr(start, '\n', buf + size - start);
383                 next_null = memchr(start, '\0', next_cr?
384                         next_cr - start : buf + size - start);
385                 if (!next_cr && !next_null)
386                         break;
387                 if (next_null)
388                         end = next_null;
389                 else
390                         end = next_cr;
391                 num_lines++;
392                 if (!(flags & FELF_DISCARD_FIRST) || start != buf) {
393                         if (flags & FELF_READ_ONLY) {
394                                 size_t s = end - start;
395                                 char *b = alloc(s + 1);
396                                 memcpy(b, start, s);
397                                 b[s] = '\0';
398                                 ret = line_handler(b, private_data);
399                                 free(b);
400                         } else {
401                                 *end = '\0';
402                                 ret = line_handler(start, private_data);
403                         }
404                         if (ret < 0)
405                                 return ret;
406                 }
407                 start = ++end;
408         }
409         i = buf + size - start;
410         if (i && i != size && !(flags & FELF_READ_ONLY))
411                 memmove(buf, start, i);
412         return i;
413 }
414
415 /** Return the hex characters of the lower 4 bits. */
416 #define hex(a) (hexchar[(a) & 15])
417
418 static void write_size_header(char *buf, int n)
419 {
420         static char hexchar[] = "0123456789abcdef";
421
422         buf[0] = hex(n >> 12);
423         buf[1] = hex(n >> 8);
424         buf[2] = hex(n >> 4);
425         buf[3] = hex(n);
426         buf[4] = ' ';
427 }
428
429 /**
430  * Read a four-byte hex-number and return its value.
431  *
432  * Each status item sent by para_server is prefixed with such a hex number in
433  * ASCII which describes the size of the status item.
434  *
435  * \param buf The buffer which must be at least four bytes long.
436  *
437  * \return The value of the hex number on success, \p -E_SIZE_PREFIX if the
438  * buffer did not contain only hex digits.
439  */
440 int read_size_header(const char *buf)
441 {
442         int i, len = 0;
443
444         for (i = 0; i < 4; i++) {
445                 unsigned char c = buf[i];
446                 len <<= 4;
447                 if (c >= '0' && c <= '9') {
448                         len += c - '0';
449                         continue;
450                 }
451                 if (c >= 'a' && c <= 'f') {
452                         len += c - 'a' + 10;
453                         continue;
454                 }
455                 return -E_SIZE_PREFIX;
456         }
457         if (buf[4] != ' ')
458                 return -E_SIZE_PREFIX;
459         return len;
460 }
461
462 /**
463  * Safely print into a buffer at a given offset.
464  *
465  * \param b Determines the buffer, its size, and the offset.
466  * \param fmt The format string.
467  *
468  * This function prints into the buffer given by \a b at the offset which is
469  * also given by \a b. If there is not enough space to hold the result, the
470  * buffer size is doubled until the underlying call to vsnprintf() succeeds
471  * or the size of the buffer exceeds the maximal size specified in \a b.
472  *
473  * In the latter case the unmodified \a buf and \a offset values as well as the
474  * private_data pointer of \a b are passed to the \a max_size_handler of \a b.
475  * If this function succeeds, i.e. returns a non-negative value, the offset of
476  * \a b is reset to zero and the given data is written to the beginning of the
477  * buffer. If \a max_size_handler() returns a negative value, this value is
478  * returned by \a para_printf().
479  *
480  * Upon return, the offset of \a b is adjusted accordingly so that subsequent
481  * calls to this function append data to what is already contained in the
482  * buffer.
483  *
484  * It's OK to call this function with \p b->buf being \p NULL. In this case, an
485  * initial buffer is allocated.
486  *
487  * \return The number of bytes printed into the buffer (not including the
488  * terminating \p NULL byte) on success, negative on errors. If there is no
489  * size-bound on \a b, i.e. if \p b->max_size is zero, this function never
490  * fails.
491  *
492  * \sa make_message(), vsnprintf(3).
493  */
494 __printf_2_3 int para_printf(struct para_buffer *b, const char *fmt, ...)
495 {
496         int ret, sz_off = (b->flags & PBF_SIZE_PREFIX)? 5 : 0;
497
498         if (!b->buf) {
499                 b->buf = alloc(128);
500                 b->size = 128;
501                 b->offset = 0;
502         }
503         while (1) {
504                 char *p = b->buf + b->offset;
505                 size_t size = b->size - b->offset;
506                 va_list ap;
507
508                 if (size > sz_off) {
509                         va_start(ap, fmt);
510                         ret = vsnprintf(p + sz_off, size - sz_off, fmt, ap);
511                         va_end(ap);
512                         if (ret > -1 && ret < size - sz_off) { /* success */
513                                 b->offset += ret + sz_off;
514                                 if (sz_off)
515                                         write_size_header(p, ret);
516                                 return ret + sz_off;
517                         }
518                 }
519                 /* check if we may grow the buffer */
520                 if (!b->max_size || 2 * b->size < b->max_size) { /* yes */
521                         /* try again with more space */
522                         b->size *= 2;
523                         b->buf = para_realloc(b->buf, b->size);
524                         continue;
525                 }
526                 /* can't grow buffer */
527                 if (!b->offset || !b->max_size_handler) /* message too large */
528                         return -ERRNO_TO_PARA_ERROR(ENOSPC);
529                 ret = b->max_size_handler(b->buf, b->offset, b->private_data);
530                 if (ret < 0)
531                         return ret;
532                 b->offset = 0;
533         }
534 }
535
536 /** \cond llong_minmax */
537 /* LLONG_MAX and LLONG_MIN might not be defined. */
538 #ifndef LLONG_MAX
539 #define LLONG_MAX 9223372036854775807LL
540 #endif
541 #ifndef LLONG_MIN
542 #define LLONG_MIN (-LLONG_MAX - 1LL)
543 #endif
544 /** \endcond llong_minmax */
545
546 /**
547  * Convert a string to a 64-bit signed integer value.
548  *
549  * \param str The string to be converted.
550  * \param value Result pointer.
551  *
552  * \return Standard.
553  *
554  * \sa \ref para_atoi32(), strtol(3), atoi(3).
555  */
556 int para_atoi64(const char *str, int64_t *value)
557 {
558         char *endptr;
559         long long tmp;
560
561         errno = 0; /* To distinguish success/failure after call */
562         tmp = strtoll(str, &endptr, 10);
563         if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
564                 return -E_ATOI_OVERFLOW;
565         /*
566          * If there were no digits at all, strtoll() stores the original value
567          * of str in *endptr.
568          */
569         if (endptr == str)
570                 return -E_ATOI_NO_DIGITS;
571         /*
572          * The implementation may also set errno and return 0 in case no
573          * conversion was performed.
574          */
575         if (errno != 0 && tmp == 0)
576                 return -E_ATOI_NO_DIGITS;
577         if (*endptr != '\0') /* Further characters after number */
578                 return -E_ATOI_JUNK_AT_END;
579         *value = tmp;
580         return 1;
581 }
582
583 /**
584  * Convert a string to a 32-bit signed integer value.
585  *
586  * \param str The string to be converted.
587  * \param value Result pointer.
588  *
589  * \return Standard.
590  *
591  * \sa \ref para_atoi64().
592 */
593 int para_atoi32(const char *str, int32_t *value)
594 {
595         int64_t tmp;
596         int ret;
597         const int32_t max = 2147483647;
598
599         ret = para_atoi64(str, &tmp);
600         if (ret < 0)
601                 return ret;
602         if (tmp > max || tmp < -max - 1)
603                 return -E_ATOI_OVERFLOW;
604         *value = tmp;
605         return 1;
606 }
607
608 static int get_next_word(const char *buf, const char *delim, char **word)
609 {
610         enum line_state_flags {LSF_HAVE_WORD = 1, LSF_BACKSLASH = 2,
611                 LSF_SINGLE_QUOTE = 4, LSF_DOUBLE_QUOTE = 8};
612         const char *in;
613         char *out;
614         int ret, state = 0;
615
616         out = alloc(strlen(buf) + 1);
617         *out = '\0';
618         *word = out;
619         for (in = buf; *in; in++) {
620                 const char *p;
621
622                 switch (*in) {
623                 case '\\':
624                         if (state & LSF_BACKSLASH) /* \\ */
625                                 goto copy_char;
626                         state |= LSF_BACKSLASH;
627                         state |= LSF_HAVE_WORD;
628                         continue;
629                 case 'n':
630                 case 't':
631                         if (state & LSF_BACKSLASH) { /* \n or \t */
632                                 *out++ = (*in == 'n')? '\n' : '\t';
633                                 state &= ~LSF_BACKSLASH;
634                                 continue;
635                         }
636                         goto copy_char;
637                 case '"':
638                         if (state & LSF_BACKSLASH) /* \" */
639                                 goto copy_char;
640                         if (state & LSF_SINGLE_QUOTE) /* '" */
641                                 goto copy_char;
642                         if (state & LSF_DOUBLE_QUOTE) {
643                                 state &= ~LSF_DOUBLE_QUOTE;
644                                 continue;
645                         }
646                         state |= LSF_HAVE_WORD;
647                         state |= LSF_DOUBLE_QUOTE;
648                         continue;
649                 case '\'':
650                         if (state & LSF_BACKSLASH) /* \' */
651                                 goto copy_char;
652                         if (state & LSF_DOUBLE_QUOTE) /* "' */
653                                 goto copy_char;
654                         if (state & LSF_SINGLE_QUOTE) {
655                                 state &= ~LSF_SINGLE_QUOTE;
656                                 continue;
657                         }
658                         state |= LSF_HAVE_WORD;
659                         state |= LSF_SINGLE_QUOTE;
660                         continue;
661                 }
662                 for (p = delim; *p; p++) {
663                         if (*in != *p)
664                                 continue;
665                         if (state & LSF_BACKSLASH)
666                                 goto copy_char;
667                         if (state & LSF_SINGLE_QUOTE)
668                                 goto copy_char;
669                         if (state & LSF_DOUBLE_QUOTE)
670                                 goto copy_char;
671                         if (state & LSF_HAVE_WORD)
672                                 goto success;
673                         break;
674                 }
675                 if (*p) /* ignore delimiter at the beginning */
676                         continue;
677 copy_char:
678                 state |= LSF_HAVE_WORD;
679                 *out++ = *in;
680                 state &= ~LSF_BACKSLASH;
681         }
682         ret = 0;
683         if (!(state & LSF_HAVE_WORD))
684                 goto out;
685         ret = -ERRNO_TO_PARA_ERROR(EINVAL);
686         if (state & LSF_BACKSLASH) {
687                 PARA_ERROR_LOG("trailing backslash\n");
688                 goto out;
689         }
690         if ((state & LSF_SINGLE_QUOTE) || (state & LSF_DOUBLE_QUOTE)) {
691                 PARA_ERROR_LOG("unmatched quote character\n");
692                 goto out;
693         }
694 success:
695         *out = '\0';
696         return in - buf;
697 out:
698         free(*word);
699         *word = NULL;
700         return ret;
701 }
702
703 /**
704  * Get the number of the word the cursor is on.
705  *
706  * \param buf The zero-terminated line buffer.
707  * \param delim Characters that separate words.
708  * \param point The cursor position.
709  *
710  * \return Zero-based word number.
711  */
712 int compute_word_num(const char *buf, const char *delim, int point)
713 {
714         int ret, num_words;
715         const char *p;
716         char *word;
717
718         for (p = buf, num_words = 0; ; p += ret, num_words++) {
719                 ret = get_next_word(p, delim, &word);
720                 if (ret <= 0)
721                         break;
722                 free(word);
723                 if (p + ret >= buf + point)
724                         break;
725         }
726         return num_words;
727 }
728
729 /**
730  * Free an array of words created by create_argv() or create_shifted_argv().
731  *
732  * \param argv A pointer previously obtained by \ref create_argv().
733  */
734 void free_argv(char **argv)
735 {
736         int i;
737
738         if (!argv)
739                 return;
740         for (i = 0; argv[i]; i++)
741                 free(argv[i]);
742         free(argv);
743 }
744
745 static int create_argv_offset(int offset, const char *buf, const char *delim,
746                 char ***result)
747 {
748         char *word, **argv = arr_zalloc(offset + 1, sizeof(char *));
749         const char *p;
750         int i, ret;
751
752         for (p = buf, i = offset; p && *p; p += ret, i++) {
753                 ret = get_next_word(p, delim, &word);
754                 if (ret < 0)
755                         goto err;
756                 if (!ret)
757                         break;
758                 argv = arr_realloc(argv, i + 2, sizeof(char*));
759                 argv[i] = word;
760         }
761         argv[i] = NULL;
762         *result = argv;
763         return i;
764 err:
765         while (i > 0)
766                 free(argv[--i]);
767         free(argv);
768         *result = NULL;
769         return ret;
770 }
771
772 /**
773  * Split a buffer into words.
774  *
775  * This parser honors single and double quotes, backslash-escaped characters
776  * and special characters like \\n. The result contains pointers to copies of
777  * the words contained in buf and has to be freed by using \ref free_argv().
778  *
779  * \param buf The buffer to be split.
780  * \param delim Each character in this string is treated as a separator.
781  * \param result The array of words is returned here.
782  *
783  * It's OK to pass NULL as the buffer argument. This is equivalent to passing
784  * the empty string.
785  *
786  * \return Number of words in buf, negative on errors. The array returned
787  * through the result pointer is NULL terminated.
788  */
789 int create_argv(const char *buf, const char *delim, char ***result)
790 {
791         return create_argv_offset(0, buf, delim, result);
792 }
793
794 /**
795  * Split a buffer into words, offset one.
796  *
797  * This is similar to \ref create_argv() but the returned array is one element
798  * larger, words start at index one and element zero is initialized to \p NULL.
799  * Callers must set element zero to a non-NULL value before calling free_argv()
800  * on the returned array to avoid a memory leak.
801  *
802  * \param buf See \ref create_argv().
803  * \param delim See \ref create_argv().
804  * \param result See \ref create_argv().
805  *
806  * \return Number of words plus one on success, negative on errors.
807  */
808 int create_shifted_argv(const char *buf, const char *delim, char ***result)
809 {
810         return create_argv_offset(1, buf, delim, result);
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 = arr_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 = arr_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 }