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