file writer: Use xwrite() instead of plain write().
[paraslash.git] / string.c
1 /*
2 * Copyright (C) 2004-2013 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 __malloc 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;
146 va_list aq;
147
148 va_copy(aq, ap);
149 ret = vsnprintf(NULL, 0, fmt, aq);
150 va_end(aq);
151 assert(ret >= 0);
152 size = ret + 1;
153 *result = para_malloc(size);
154 va_copy(aq, ap);
155 ret = vsnprintf(*result, size, fmt, aq);
156 va_end(aq);
157 assert(ret >= 0 && ret < size);
158 return ret;
159 }
160
161 /**
162 * Print to a dynamically allocated string, variable number of arguments.
163 *
164 * \param result See \ref xvasprintf().
165 * \param fmt Usual format string.
166 *
167 * \return The return value of the underlying call to \ref xvasprintf().
168 *
169 * \sa \ref xvasprintf() and the references mentioned there.
170 */
171 __printf_2_3 unsigned xasprintf(char **result, const char *fmt, ...)
172 {
173 va_list ap;
174 unsigned ret;
175
176 va_start(ap, fmt);
177 ret = xvasprintf(result, fmt, ap);
178 va_end(ap);
179 return ret;
180 }
181
182 /**
183 * Allocate a sufficiently large string and print into it.
184 *
185 * \param fmt A usual format string.
186 *
187 * Produce output according to \p fmt. No artificial bound on the length of the
188 * resulting string is imposed.
189 *
190 * \return This function either returns a pointer to a string that must be
191 * freed by the caller or aborts without returning.
192 *
193 * \sa printf(3), xasprintf().
194 */
195 __must_check __printf_1_2 __malloc char *make_message(const char *fmt, ...)
196 {
197 char *msg;
198 va_list ap;
199
200 va_start(ap, fmt);
201 xvasprintf(&msg, fmt, ap);
202 va_end(ap);
203 return msg;
204 }
205
206 /**
207 * Free the content of a pointer and set it to \p NULL.
208 *
209 * This is equivalent to "free(*arg); *arg = NULL;".
210 *
211 * \param arg The pointer whose content should be freed.
212 */
213 void freep(void *arg)
214 {
215 void **ptr = (void **)arg;
216 free(*ptr);
217 *ptr = NULL;
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 * Paraslash's version of dirname().
250 *
251 * \param name Pointer to the full path.
252 *
253 * Compute the directory component of \p name.
254 *
255 * \return If \a name is \p NULL or the empty string, return \p NULL.
256 * Otherwise, Make a copy of \a name and return its directory component. Caller
257 * is responsible to free the result.
258 */
259 __must_check __malloc char *para_dirname(const char *name)
260 {
261 char *p, *ret;
262
263 if (!name || !*name)
264 return NULL;
265 ret = para_strdup(name);
266 p = strrchr(ret, '/');
267 if (!p)
268 *ret = '\0';
269 else
270 *p = '\0';
271 return ret;
272 }
273
274 /**
275 * Paraslash's version of basename().
276 *
277 * \param name Pointer to the full path.
278 *
279 * Compute the filename component of \a name.
280 *
281 * \return \p NULL if (a) \a name is the empty string or \p NULL, or (b) name
282 * ends with a slash. Otherwise, a pointer within \a name is returned. Caller
283 * must not free the result.
284 */
285 __must_check char *para_basename(const char *name)
286 {
287 char *ret;
288
289 if (!name || !*name)
290 return NULL;
291 ret = strrchr(name, '/');
292 if (!ret)
293 return (char *)name;
294 ret++;
295 return ret;
296 }
297
298 /**
299 * Cut trailing newline.
300 *
301 * \param buf The string to be chopped.
302 *
303 * Replace the last character in \p buf by zero if it is equal to
304 * the newline character.
305 */
306 void chop(char *buf)
307 {
308 int n = strlen(buf);
309
310 if (!n)
311 return;
312 if (buf[n - 1] == '\n')
313 buf[n - 1] = '\0';
314 }
315
316 /**
317 * Get the logname of the current user.
318 *
319 * \return A dynamically allocated string that must be freed by the caller. On
320 * errors, the string "unknown_user" is returned, i.e. this function never
321 * returns \p NULL.
322 *
323 * \sa getpwuid(3).
324 */
325 __must_check __malloc char *para_logname(void)
326 {
327 struct passwd *pw = getpwuid(getuid());
328 return para_strdup(pw? pw->pw_name : "unknown_user");
329 }
330
331 /**
332 * Get the home directory of the current user.
333 *
334 * \return A dynamically allocated string that must be freed by the caller. If
335 * the home directory could not be found, this function returns "/tmp".
336 */
337 __must_check __malloc char *para_homedir(void)
338 {
339 struct passwd *pw = getpwuid(getuid());
340 return para_strdup(pw? pw->pw_dir : "/tmp");
341 }
342
343 /**
344 * Get the own hostname.
345 *
346 * \return A dynamically allocated string containing the hostname.
347 *
348 * \sa uname(2).
349 */
350 __malloc char *para_hostname(void)
351 {
352 struct utsname u;
353
354 uname(&u);
355 return para_strdup(u.nodename);
356 }
357
358 /**
359 * Used to distinguish between read-only and read-write mode.
360 *
361 * \sa for_each_line(), for_each_line_ro().
362 */
363 enum for_each_line_modes{
364 /** Activate read-only mode. */
365 LINE_MODE_RO,
366 /** Activate read-write mode. */
367 LINE_MODE_RW
368 };
369
370 static int for_each_complete_line(enum for_each_line_modes mode, char *buf,
371 size_t size, line_handler_t *line_handler, void *private_data)
372 {
373 char *start = buf, *end;
374 int ret, i, num_lines = 0;
375
376 // PARA_NOTICE_LOG("buf: %s\n", buf);
377 while (start < buf + size) {
378 char *next_null;
379 char *next_cr;
380
381 next_cr = memchr(start, '\n', buf + size - start);
382 next_null = memchr(start, '\0', buf + size - start);
383 if (!next_cr && !next_null)
384 break;
385 if (next_cr && next_null) {
386 end = next_cr < next_null? next_cr : next_null;
387 } else if (next_null) {
388 end = next_null;
389 } else
390 end = next_cr;
391 num_lines++;
392 if (!line_handler) {
393 start = ++end;
394 continue;
395 }
396 if (mode == LINE_MODE_RO) {
397 size_t s = end - start;
398 char *b = para_malloc(s + 1);
399 memcpy(b, start, s);
400 b[s] = '\0';
401 // PARA_NOTICE_LOG("b: %s, start: %s\n", b, start);
402 ret = line_handler(b, private_data);
403 free(b);
404 } else {
405 *end = '\0';
406 ret = line_handler(start, private_data);
407 }
408 if (ret < 0)
409 return ret;
410 start = ++end;
411 }
412 if (!line_handler || mode == LINE_MODE_RO)
413 return num_lines;
414 i = buf + size - start;
415 if (i && i != size)
416 memmove(buf, start, i);
417 return i;
418 }
419
420 /**
421 * Call a custom function for each complete line.
422 *
423 * \param buf The buffer containing data separated by newlines.
424 * \param size The number of bytes in \a buf.
425 * \param line_handler The custom function.
426 * \param private_data Pointer passed to \a line_handler.
427 *
428 * If \p line_handler is \p NULL, the function returns the number of complete
429 * lines in \p buf. Otherwise, \p line_handler is called for each complete
430 * line in \p buf. The first argument to \p line_handler is the current line,
431 * and \p private_data is passed as the second argument. The function returns
432 * if \p line_handler returns a negative value or no more lines are in the
433 * buffer. The rest of the buffer (last chunk containing an incomplete line)
434 * is moved to the beginning of the buffer.
435 *
436 * \return If \p line_handler is not \p NULL, this function returns the number
437 * of bytes not handled to \p line_handler on success, or the negative return
438 * value of the \p line_handler on errors.
439 *
440 * \sa for_each_line_ro().
441 */
442 int for_each_line(char *buf, size_t size, line_handler_t *line_handler,
443 void *private_data)
444 {
445 return for_each_complete_line(LINE_MODE_RW, buf, size, line_handler,
446 private_data);
447 }
448
449 /**
450 * Call a custom function for each complete line.
451 *
452 * \param buf Same meaning as in \p for_each_line().
453 * \param size Same meaning as in \p for_each_line().
454 * \param line_handler Same meaning as in \p for_each_line().
455 * \param private_data Same meaning as in \p for_each_line().
456 *
457 * This function behaves like \p for_each_line(), but \a buf is left unchanged.
458 *
459 * \return On success, the function returns the number of complete lines in \p
460 * buf, otherwise the (negative) return value of \p line_handler is returned.
461 *
462 * \sa for_each_line().
463 */
464 int for_each_line_ro(char *buf, size_t size, line_handler_t *line_handler,
465 void *private_data)
466 {
467 return for_each_complete_line(LINE_MODE_RO, buf, size, line_handler,
468 private_data);
469 }
470
471 /** Return the hex characters of the lower 4 bits. */
472 #define hex(a) (hexchar[(a) & 15])
473
474 static void write_size_header(char *buf, int n)
475 {
476 static char hexchar[] = "0123456789abcdef";
477
478 buf[0] = hex(n >> 12);
479 buf[1] = hex(n >> 8);
480 buf[2] = hex(n >> 4);
481 buf[3] = hex(n);
482 buf[4] = ' ';
483 }
484
485 /**
486 * Read a four-byte hex-number and return its value.
487 *
488 * Each status item sent by para_server is prefixed with such a hex number in
489 * ASCII which describes the size of the status item.
490 *
491 * \param buf The buffer which must be at least four bytes long.
492 *
493 * \return The value of the hex number on success, \p -E_SIZE_PREFIX if the
494 * buffer did not contain only hex digits.
495 */
496 int read_size_header(const char *buf)
497 {
498 int i, len = 0;
499
500 for (i = 0; i < 4; i++) {
501 unsigned char c = buf[i];
502 len <<= 4;
503 if (c >= '0' && c <= '9') {
504 len += c - '0';
505 continue;
506 }
507 if (c >= 'a' && c <= 'f') {
508 len += c - 'a' + 10;
509 continue;
510 }
511 return -E_SIZE_PREFIX;
512 }
513 if (buf[4] != ' ')
514 return -E_SIZE_PREFIX;
515 return len;
516 }
517
518 /**
519 * Safely print into a buffer at a given offset.
520 *
521 * \param b Determines the buffer, its size, and the offset.
522 * \param fmt The format string.
523 *
524 * This function prints into the buffer given by \a b at the offset which is
525 * also given by \a b. If there is not enough space to hold the result, the
526 * buffer size is doubled until the underlying call to vsnprintf() succeeds
527 * or the size of the buffer exceeds the maximal size specified in \a b.
528 *
529 * In the latter case the unmodified \a buf and \a offset values as well as the
530 * private_data pointer of \a b are passed to the \a max_size_handler of \a b.
531 * If this function succeeds, i.e. returns a non-negative value, the offset of
532 * \a b is reset to zero and the given data is written to the beginning of the
533 * buffer. If \a max_size_handler() returns a negative value, this value is
534 * returned by \a para_printf().
535 *
536 * Upon return, the offset of \a b is adjusted accordingly so that subsequent
537 * calls to this function append data to what is already contained in the
538 * buffer.
539 *
540 * It's OK to call this function with \p b->buf being \p NULL. In this case, an
541 * initial buffer is allocated.
542 *
543 * \return The number of bytes printed into the buffer (not including the
544 * terminating \p NULL byte) on success, negative on errors. If there is no
545 * size-bound on \a b, i.e. if \p b->max_size is zero, this function never
546 * fails.
547 *
548 * \sa make_message(), vsnprintf(3).
549 */
550 __printf_2_3 int para_printf(struct para_buffer *b, const char *fmt, ...)
551 {
552 int ret, sz_off = (b->flags & PBF_SIZE_PREFIX)? 5 : 0;
553
554 if (!b->buf) {
555 b->buf = para_malloc(128);
556 b->size = 128;
557 b->offset = 0;
558 }
559 while (1) {
560 char *p = b->buf + b->offset;
561 size_t size = b->size - b->offset;
562 va_list ap;
563
564 if (size > sz_off) {
565 va_start(ap, fmt);
566 ret = vsnprintf(p + sz_off, size - sz_off, fmt, ap);
567 va_end(ap);
568 if (ret > -1 && ret < size - sz_off) { /* success */
569 b->offset += ret + sz_off;
570 if (sz_off)
571 write_size_header(p, ret);
572 return ret + sz_off;
573 }
574 }
575 /* check if we may grow the buffer */
576 if (!b->max_size || 2 * b->size < b->max_size) { /* yes */
577 /* try again with more space */
578 b->size *= 2;
579 b->buf = para_realloc(b->buf, b->size);
580 continue;
581 }
582 /* can't grow buffer */
583 if (!b->offset || !b->max_size_handler) /* message too large */
584 return -ERRNO_TO_PARA_ERROR(ENOSPC);
585 ret = b->max_size_handler(b->buf, b->offset, b->private_data);
586 if (ret < 0)
587 return ret;
588 b->offset = 0;
589 }
590 }
591
592 /** \cond llong_minmax */
593 /* LLONG_MAX and LLONG_MIN might not be defined. */
594 #ifndef LLONG_MAX
595 #define LLONG_MAX 9223372036854775807LL
596 #endif
597 #ifndef LLONG_MIN
598 #define LLONG_MIN (-LLONG_MAX - 1LL)
599 #endif
600 /** \endcond llong_minmax */
601
602 /**
603 * Convert a string to a 64-bit signed integer value.
604 *
605 * \param str The string to be converted.
606 * \param value Result pointer.
607 *
608 * \return Standard.
609 *
610 * \sa para_atoi32(), strtol(3), atoi(3).
611 */
612 int para_atoi64(const char *str, int64_t *value)
613 {
614 char *endptr;
615 long long tmp;
616
617 errno = 0; /* To distinguish success/failure after call */
618 tmp = strtoll(str, &endptr, 10);
619 if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
620 return -E_ATOI_OVERFLOW;
621 if (errno != 0 && tmp == 0) /* other error */
622 return -E_STRTOLL;
623 if (endptr == str)
624 return -E_ATOI_NO_DIGITS;
625 if (*endptr != '\0') /* Further characters after number */
626 return -E_ATOI_JUNK_AT_END;
627 *value = tmp;
628 return 1;
629 }
630
631 /**
632 * Convert a string to a 32-bit signed integer value.
633 *
634 * \param str The string to be converted.
635 * \param value Result pointer.
636 *
637 * \return Standard.
638 *
639 * \sa para_atoi64().
640 */
641 int para_atoi32(const char *str, int32_t *value)
642 {
643 int64_t tmp;
644 int ret;
645 const int32_t max = 2147483647;
646
647 ret = para_atoi64(str, &tmp);
648 if (ret < 0)
649 return ret;
650 if (tmp > max || tmp < -max - 1)
651 return -E_ATOI_OVERFLOW;
652 *value = tmp;
653 return 1;
654 }
655
656 static inline int loglevel_equal(const char *arg, const char * const ll)
657 {
658 return !strncasecmp(arg, ll, strlen(ll));
659 }
660
661 /**
662 * Compute the loglevel number from its name.
663 *
664 * \param txt The name of the loglevel (debug, info, ...).
665 *
666 * \return The numeric representation of the loglevel name.
667 */
668 int get_loglevel_by_name(const char *txt)
669 {
670 if (loglevel_equal(txt, "debug"))
671 return LL_DEBUG;
672 if (loglevel_equal(txt, "info"))
673 return LL_INFO;
674 if (loglevel_equal(txt, "notice"))
675 return LL_NOTICE;
676 if (loglevel_equal(txt, "warning"))
677 return LL_WARNING;
678 if (loglevel_equal(txt, "error"))
679 return LL_ERROR;
680 if (loglevel_equal(txt, "crit"))
681 return LL_CRIT;
682 if (loglevel_equal(txt, "emerg"))
683 return LL_EMERG;
684 return -1;
685 }
686
687 static int get_next_word(const char *buf, const char *delim, char **word)
688 {
689 enum line_state_flags {LSF_HAVE_WORD = 1, LSF_BACKSLASH = 2,
690 LSF_SINGLE_QUOTE = 4, LSF_DOUBLE_QUOTE = 8};
691 const char *in;
692 char *out;
693 int ret, state = 0;
694
695 out = para_malloc(strlen(buf) + 1);
696 *out = '\0';
697 *word = out;
698 for (in = buf; *in; in++) {
699 const char *p;
700
701 switch (*in) {
702 case '\\':
703 if (state & LSF_BACKSLASH) /* \\ */
704 goto copy_char;
705 state |= LSF_BACKSLASH;
706 state |= LSF_HAVE_WORD;
707 continue;
708 case 'n':
709 case 't':
710 if (state & LSF_BACKSLASH) { /* \n or \t */
711 *out++ = (*in == 'n')? '\n' : '\t';
712 state &= ~LSF_BACKSLASH;
713 continue;
714 }
715 goto copy_char;
716 case '"':
717 if (state & LSF_BACKSLASH) /* \" */
718 goto copy_char;
719 if (state & LSF_SINGLE_QUOTE) /* '" */
720 goto copy_char;
721 if (state & LSF_DOUBLE_QUOTE) {
722 state &= ~LSF_DOUBLE_QUOTE;
723 continue;
724 }
725 state |= LSF_HAVE_WORD;
726 state |= LSF_DOUBLE_QUOTE;
727 continue;
728 case '\'':
729 if (state & LSF_BACKSLASH) /* \' */
730 goto copy_char;
731 if (state & LSF_DOUBLE_QUOTE) /* "' */
732 goto copy_char;
733 if (state & LSF_SINGLE_QUOTE) {
734 state &= ~LSF_SINGLE_QUOTE;
735 continue;
736 }
737 state |= LSF_HAVE_WORD;
738 state |= LSF_SINGLE_QUOTE;
739 continue;
740 }
741 for (p = delim; *p; p++) {
742 if (*in != *p)
743 continue;
744 if (state & LSF_BACKSLASH)
745 goto copy_char;
746 if (state & LSF_SINGLE_QUOTE)
747 goto copy_char;
748 if (state & LSF_DOUBLE_QUOTE)
749 goto copy_char;
750 if (state & LSF_HAVE_WORD)
751 goto success;
752 break;
753 }
754 if (*p) /* ignore delimiter at the beginning */
755 continue;
756 copy_char:
757 state |= LSF_HAVE_WORD;
758 *out++ = *in;
759 state &= ~LSF_BACKSLASH;
760 }
761 ret = 0;
762 if (!(state & LSF_HAVE_WORD))
763 goto out;
764 ret = -ERRNO_TO_PARA_ERROR(EINVAL);
765 if (state & LSF_BACKSLASH) {
766 PARA_ERROR_LOG("trailing backslash\n");
767 goto out;
768 }
769 if ((state & LSF_SINGLE_QUOTE) || (state & LSF_DOUBLE_QUOTE)) {
770 PARA_ERROR_LOG("unmatched quote character\n");
771 goto out;
772 }
773 success:
774 *out = '\0';
775 return in - buf;
776 out:
777 free(*word);
778 *word = NULL;
779 return ret;
780 }
781
782 /**
783 * Get the number of the word the cursor is on.
784 *
785 * \param buf The zero-terminated line buffer.
786 * \param delim Characters that separate words.
787 * \param point The cursor position.
788 *
789 * \return Zero-based word number.
790 */
791 int compute_word_num(const char *buf, const char *delim, int point)
792 {
793 int ret, num_words;
794 const char *p;
795 char *word;
796
797 for (p = buf, num_words = 0; ; p += ret, num_words++) {
798 ret = get_next_word(p, delim, &word);
799 if (ret <= 0)
800 break;
801 free(word);
802 if (p + ret >= buf + point)
803 break;
804 }
805 return num_words;
806 }
807
808 /**
809 * Free an array of words created by create_argv() or create_shifted_argv().
810 *
811 * \param argv A pointer previously obtained by \ref create_argv().
812 */
813 void free_argv(char **argv)
814 {
815 int i;
816
817 if (!argv)
818 return;
819 for (i = 0; argv[i]; i++)
820 free(argv[i]);
821 free(argv);
822 }
823
824 static int create_argv_offset(int offset, const char *buf, const char *delim,
825 char ***result)
826 {
827 char *word, **argv = para_malloc((offset + 1) * sizeof(char *));
828 const char *p;
829 int i, ret;
830
831 for (i = 0; i < offset; i++)
832 argv[i] = NULL;
833 for (p = buf; p && *p; p += ret, i++) {
834 ret = get_next_word(p, delim, &word);
835 if (ret < 0)
836 goto err;
837 if (!ret)
838 break;
839 argv = para_realloc(argv, (i + 2) * sizeof(char*));
840 argv[i] = word;
841 }
842 argv[i] = NULL;
843 *result = argv;
844 return i;
845 err:
846 while (i > 0)
847 free(argv[--i]);
848 free(argv);
849 *result = NULL;
850 return ret;
851 }
852
853 /**
854 * Split a buffer into words.
855 *
856 * This parser honors single and double quotes, backslash-escaped characters
857 * and special characters like \p \\n. The result contains pointers to copies
858 * of the words contained in \a buf and has to be freed by using \ref
859 * free_argv().
860 *
861 * \param buf The buffer to be split.
862 * \param delim Each character in this string is treated as a separator.
863 * \param result The array of words is returned here.
864 *
865 * \return Number of words in \a buf, negative on errors.
866 */
867 int create_argv(const char *buf, const char *delim, char ***result)
868 {
869 return create_argv_offset(0, buf, delim, result);
870 }
871
872 /**
873 * Split a buffer into words, offset one.
874 *
875 * This is similar to \ref create_argv() but the returned array is one element
876 * larger, words start at index one and element zero is initialized to \p NULL.
877 * Callers must set element zero to a non-NULL value before calling free_argv()
878 * on the returned array to avoid a memory leak.
879 *
880 * \param buf See \ref create_argv().
881 * \param delim See \ref create_argv().
882 * \param result See \ref create_argv().
883 *
884 * \return Number of words plus one on success, negative on errors.
885 */
886 int create_shifted_argv(const char *buf, const char *delim, char ***result)
887 {
888 return create_argv_offset(1, buf, delim, result);
889 }
890
891 /**
892 * Find out if the given string is contained in the arg vector.
893 *
894 * \param arg The string to look for.
895 * \param argv The array to search.
896 *
897 * \return The first index whose value equals \a arg, or \p -E_ARG_NOT_FOUND if
898 * arg was not found in \a argv.
899 */
900 int find_arg(const char *arg, char **argv)
901 {
902 int i;
903
904 if (!argv)
905 return -E_ARG_NOT_FOUND;
906 for (i = 0; argv[i]; i++)
907 if (strcmp(arg, argv[i]) == 0)
908 return i;
909 return -E_ARG_NOT_FOUND;
910 }
911
912 /**
913 * Compile a regular expression.
914 *
915 * This simple wrapper calls regcomp() and logs a message on errors.
916 *
917 * \param preg See regcomp(3).
918 * \param regex See regcomp(3).
919 * \param cflags See regcomp(3).
920 *
921 * \return Standard.
922 */
923 int para_regcomp(regex_t *preg, const char *regex, int cflags)
924 {
925 char *buf;
926 size_t size;
927 int ret = regcomp(preg, regex, cflags);
928
929 if (ret == 0)
930 return 1;
931 size = regerror(ret, preg, NULL, 0);
932 buf = para_malloc(size);
933 regerror(ret, preg, buf, size);
934 PARA_ERROR_LOG("%s\n", buf);
935 free(buf);
936 return -E_REGEX;
937 }
938
939 /**
940 * strdup() for not necessarily zero-terminated strings.
941 *
942 * \param src The source buffer.
943 * \param len The number of bytes to be copied.
944 *
945 * \return A 0-terminated buffer of length \a len + 1.
946 *
947 * This is similar to strndup(), which is a GNU extension. However, one
948 * difference is that strndup() returns \p NULL if insufficient memory was
949 * available while this function aborts in this case.
950 *
951 * \sa strdup(), \ref para_strdup().
952 */
953 char *safe_strdup(const char *src, size_t len)
954 {
955 char *p;
956
957 assert(len < (size_t)-1);
958 p = para_malloc(len + 1);
959 if (len > 0)
960 memcpy(p, src, len);
961 p[len] = '\0';
962 return p;
963 }
964
965 /**
966 * Copy the value of a key=value pair.
967 *
968 * This checks whether the given buffer starts with "key=", ignoring case. If
969 * yes, a copy of the value is returned. The source buffer may not be
970 * zero-terminated.
971 *
972 * \param src The source buffer.
973 * \param len The number of bytes of the tag.
974 * \param key Only copy if it is the value of this key.
975 *
976 * \return A zero-terminated buffer, or \p NULL if the key was
977 * not of the given type.
978 */
979 char *key_value_copy(const char *src, size_t len, const char *key)
980 {
981 int keylen = strlen(key);
982
983 if (len <= keylen)
984 return NULL;
985 if (strncasecmp(src, key, keylen))
986 return NULL;
987 if (src[keylen] != '=')
988 return NULL;
989 return safe_strdup(src + keylen + 1, len - keylen - 1);
990 }
991
992 static bool utf8_mode(void)
993 {
994 static bool initialized, have_utf8;
995
996 if (!initialized) {
997 char *info = nl_langinfo(CODESET);
998 have_utf8 = (info && strcmp(info, "UTF-8") == 0);
999 initialized = true;
1000 PARA_INFO_LOG("%susing UTF-8 character encoding\n",
1001 have_utf8? "" : "not ");
1002 }
1003 return have_utf8;
1004 }
1005
1006 /*
1007 * glibc's wcswidth returns -1 if the string contains a tab character, which
1008 * makes the function next to useless. The two functions below are taken from
1009 * mutt.
1010 */
1011
1012 #define IsWPrint(wc) (iswprint(wc) || wc >= 0xa0)
1013
1014 static int mutt_wcwidth(wchar_t wc, size_t pos)
1015 {
1016 int n;
1017
1018 if (wc == 0x09) /* tab */
1019 return (pos | 7) + 1 - pos;
1020 n = wcwidth(wc);
1021 if (IsWPrint(wc) && n > 0)
1022 return n;
1023 if (!(wc & ~0x7f))
1024 return 2;
1025 if (!(wc & ~0xffff))
1026 return 6;
1027 return 10;
1028 }
1029
1030 static size_t mutt_wcswidth(const wchar_t *s, size_t n)
1031 {
1032 size_t w = 0;
1033
1034 while (n--)
1035 w += mutt_wcwidth(*s++, w);
1036 return w;
1037 }
1038
1039 /**
1040 * Skip a given number of cells at the beginning of a string.
1041 *
1042 * \param s The input string.
1043 * \param cells_to_skip Desired number of cells that should be skipped.
1044 * \param bytes_to_skip Result.
1045 *
1046 * This function computes how many input bytes must be skipped to advance a
1047 * string by the given width. If the current character encoding is not UTF-8,
1048 * this is simply the given number of cells, i.e. \a cells_to_skip. Otherwise,
1049 * \a s is treated as a multibyte string and on successful return, \a s +
1050 * bytes_to_skip points to the start of a multibyte string such that the total
1051 * width of the multibyte characters that are skipped by advancing \a s that
1052 * many bytes equals at least \a cells_to_skip.
1053 *
1054 * \return Standard.
1055 */
1056 int skip_cells(const char *s, size_t cells_to_skip, size_t *bytes_to_skip)
1057 {
1058 wchar_t wc;
1059 mbstate_t ps;
1060 size_t n, bytes_parsed, cells_skipped;
1061
1062 *bytes_to_skip = 0;
1063 if (cells_to_skip == 0)
1064 return 0;
1065 if (!utf8_mode()) {
1066 *bytes_to_skip = cells_to_skip;
1067 return 0;
1068 }
1069 bytes_parsed = cells_skipped = 0;
1070 memset(&ps, 0, sizeof(ps));
1071 n = strlen(s);
1072 while (cells_to_skip > cells_skipped) {
1073 size_t mbret;
1074
1075 mbret = mbrtowc(&wc, s + bytes_parsed, n - bytes_parsed, &ps);
1076 assert(mbret != 0);
1077 if (mbret == (size_t)-1 || mbret == (size_t)-2)
1078 return -ERRNO_TO_PARA_ERROR(EILSEQ);
1079 bytes_parsed += mbret;
1080 cells_skipped += mutt_wcwidth(wc, cells_skipped);
1081 }
1082 *bytes_to_skip = bytes_parsed;
1083 return 1;
1084 }
1085
1086 /**
1087 * Compute the width of an UTF-8 string.
1088 *
1089 * \param s The string.
1090 * \param result The width of \a s is returned here.
1091 *
1092 * If not in UTF8-mode. this function is just a wrapper for strlen(3).
1093 * Otherwise \a s is treated as an UTF-8 string and its display width is
1094 * computed. Note that this function may fail if the underlying call to
1095 * mbsrtowcs(3) fails, so the caller must check the return value.
1096 *
1097 * \sa nl_langinfo(3), wcswidth(3).
1098 *
1099 * \return Standard.
1100 */
1101 __must_check int strwidth(const char *s, size_t *result)
1102 {
1103 const char *src = s;
1104 mbstate_t state;
1105 static wchar_t *dest;
1106 size_t num_wchars;
1107
1108 /*
1109 * Never call any log function here. This may result in an endless loop
1110 * as para_gui's para_log() calls this function.
1111 */
1112
1113 if (!utf8_mode()) {
1114 *result = strlen(s);
1115 return 0;
1116 }
1117 memset(&state, 0, sizeof(state));
1118 *result = 0;
1119 num_wchars = mbsrtowcs(NULL, &src, 0, &state);
1120 if (num_wchars == (size_t)-1)
1121 return -ERRNO_TO_PARA_ERROR(errno);
1122 if (num_wchars == 0)
1123 return 0;
1124 dest = para_malloc(num_wchars * sizeof(*dest));
1125 src = s;
1126 memset(&state, 0, sizeof(state));
1127 num_wchars = mbsrtowcs(dest, &src, num_wchars, &state);
1128 assert(num_wchars > 0 && num_wchars != (size_t)-1);
1129 *result = mutt_wcswidth(dest, num_wchars);
1130 free(dest);
1131 return 1;
1132 }