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