simplify fft_init() due to split_radix is always 1.
[paraslash.git] / string.c
1 /*
2  * Copyright (C) 2004-2009 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 #include <sys/time.h> /* gettimeofday */
10 #include <pwd.h>
11 #include <sys/utsname.h> /* uname() */
12 #include <string.h>
13 #include <regex.h>
14
15 #include "para.h"
16 #include "string.h"
17 #include "error.h"
18
19 /**
20  * Paraslash's version of realloc().
21  *
22  * \param p Pointer to the memory block, may be \p NULL.
23  * \param size The desired new size.
24  *
25  * A wrapper for realloc(3). It calls \p exit(\p EXIT_FAILURE) on errors,
26  * i.e. there is no need to check the return value in the caller.
27  *
28  * \return A pointer to  the newly allocated memory, which is suitably aligned
29  * for any kind of variable and may be different from \a p.
30  *
31  * \sa realloc(3).
32  */
33 __must_check __malloc void *para_realloc(void *p, size_t size)
34 {
35         /*
36          * No need to check for NULL pointers: If p is NULL, the call
37          * to realloc is equivalent to malloc(size)
38          */
39         assert(size);
40         if (!(p = realloc(p, size))) {
41                 PARA_EMERG_LOG("realloc failed (size = %zu), aborting\n",
42                         size);
43                 exit(EXIT_FAILURE);
44         }
45         return p;
46 }
47
48 /**
49  * Paraslash's version of malloc().
50  *
51  * \param size The desired new size.
52  *
53  * A wrapper for malloc(3) which exits on errors.
54  *
55  * \return A pointer to the allocated memory, which is suitably aligned for any
56  * kind of variable.
57  *
58  * \sa malloc(3).
59  */
60 __must_check __malloc void *para_malloc(size_t size)
61 {
62         void *p;
63
64         assert(size);
65         p = malloc(size);
66         if (!p) {
67                 PARA_EMERG_LOG("malloc failed (size = %zu), aborting\n",
68                         size);
69                 exit(EXIT_FAILURE);
70         }
71         return p;
72 }
73
74 /**
75  * Paraslash's version of calloc().
76  *
77  * \param size The desired new size.
78  *
79  * A wrapper for calloc(3) which exits on errors.
80  *
81  * \return A pointer to the allocated and zeroed-out memory, which is suitably
82  * aligned for any kind of variable.
83  *
84  * \sa calloc(3)
85  */
86 __must_check __malloc void *para_calloc(size_t size)
87 {
88         void *ret = para_malloc(size);
89
90         memset(ret, 0, size);
91         return ret;
92 }
93
94 /**
95  * Paraslash's version of strdup().
96  *
97  * \param s The string to be duplicated.
98  *
99  * A wrapper for strdup(3). It calls \p exit(EXIT_FAILURE) on errors, i.e.
100  * there is no need to check the return value in the caller.
101  *
102  * \return A pointer to the duplicated string. If \a s was the \p NULL pointer,
103  * an pointer to an empty string is returned.
104  *
105  * \sa strdup(3)
106  */
107 __must_check __malloc char *para_strdup(const char *s)
108 {
109         char *ret;
110
111         if ((ret = strdup(s? s: "")))
112                 return ret;
113         PARA_EMERG_LOG("strdup failed, aborting\n");
114         exit(EXIT_FAILURE);
115 }
116
117 /**
118  * Allocate a sufficiently large string and print into it.
119  *
120  * \param fmt A usual format string.
121  *
122  * Produce output according to \p fmt. No artificial bound on the length of the
123  * resulting string is imposed.
124  *
125  * \return This function either returns a pointer to a string that must be
126  * freed by the caller or aborts without returning.
127  *
128  * \sa printf(3).
129  */
130 __must_check __printf_1_2 __malloc char *make_message(const char *fmt, ...)
131 {
132         char *msg;
133
134         PARA_VSPRINTF(fmt, msg);
135         return msg;
136 }
137
138 void freep(void *arg)
139 {
140         void **ptr = (void **)arg;
141         free(*ptr);
142         *ptr = NULL;
143 }
144
145 /**
146  * Paraslash's version of strcat().
147  *
148  * \param a String to be appended to.
149  * \param b String to append.
150  *
151  * Append \p b to \p a.
152  *
153  * \return If \a a is \p NULL, return a pointer to a copy of \a b, i.e.
154  * para_strcat(NULL, b) is equivalent to para_strdup(b). If \a b is \p NULL,
155  * return \a a without making a copy of \a a.  Otherwise, construct the
156  * concatenation \a c, free \a a (but not \a b) and return \a c.
157  *
158  * \sa strcat(3)
159  */
160 __must_check __malloc char *para_strcat(char *a, const char *b)
161 {
162         char *tmp;
163
164         if (!a)
165                 return para_strdup(b);
166         if (!b)
167                 return a;
168         tmp = make_message("%s%s", a, b);
169         free(a);
170         return tmp;
171 }
172
173 /**
174  * Paraslash's version of dirname().
175  *
176  * \param name Pointer to the full path.
177  *
178  * Compute the directory component of \p name.
179  *
180  * \return If \a name is \p NULL or the empty string, return \p NULL.
181  * Otherwise, Make a copy of \a name and return its directory component. Caller
182  * is responsible to free the result.
183  */
184 __must_check __malloc char *para_dirname(const char *name)
185 {
186         char *p, *ret;
187
188         if (!name || !*name)
189                 return NULL;
190         ret = para_strdup(name);
191         p = strrchr(ret, '/');
192         if (!p)
193                 *ret = '\0';
194         else
195                 *p = '\0';
196         return ret;
197 }
198
199 /**
200  * Paraslash's version of basename().
201  *
202  * \param name Pointer to the full path.
203  *
204  * Compute the filename component of \a name.
205  *
206  * \return \p NULL if (a) \a name is the empty string or \p NULL, or (b) name
207  * ends with a slash.  Otherwise, a pointer within \a name is returned.  Caller
208  * must not free the result.
209  */
210 __must_check char *para_basename(const char *name)
211 {
212         char *ret;
213
214         if (!name || !*name)
215                 return NULL;
216         ret = strrchr(name, '/');
217         if (!ret)
218                 return (char *)name;
219         ret++;
220         return ret;
221 }
222
223 /**
224  * Cut trailing newline.
225  *
226  * \param buf The string to be chopped.
227  *
228  * Replace the last character in \p buf by zero if it is equal to
229  * the newline character.
230  */
231 void chop(char *buf)
232 {
233         int n = strlen(buf);
234
235         if (!n)
236                 return;
237         if (buf[n - 1] == '\n')
238                 buf[n - 1] = '\0';
239 }
240
241 /**
242  * Get the logname of the current user.
243  *
244  * \return A dynamically allocated string that must be freed by the caller. On
245  * errors, the string "unknown_user" is returned, i.e. this function never
246  * returns \p NULL.
247  *
248  * \sa getpwuid(3).
249  */
250 __must_check __malloc char *para_logname(void)
251 {
252         struct passwd *pw = getpwuid(getuid());
253         return para_strdup(pw? pw->pw_name : "unknown_user");
254 }
255
256 /**
257  * Get the home directory of the current user.
258  *
259  * \return A dynamically allocated string that must be freed by the caller. If
260  * the home directory could not be found, this function returns "/tmp".
261  */
262 __must_check __malloc char *para_homedir(void)
263 {
264         struct passwd *pw = getpwuid(getuid());
265         return para_strdup(pw? pw->pw_dir : "/tmp");
266 }
267
268 /**
269  * Get the own hostname.
270  *
271  * \return A dynamically allocated string containing the hostname.
272  *
273  * \sa uname(2).
274  */
275 __malloc char *para_hostname(void)
276 {
277         struct utsname u;
278
279         uname(&u);
280         return para_strdup(u.nodename);
281 }
282
283 /**
284  * Used to distinguish between read-only and read-write mode.
285  *
286  * \sa for_each_line(), for_each_line_ro().
287  */
288 enum for_each_line_modes{
289         /** Activate read-only mode. */
290         LINE_MODE_RO,
291         /** Activate read-write mode. */
292         LINE_MODE_RW
293 };
294
295 static int for_each_complete_line(enum for_each_line_modes mode, char *buf,
296                 size_t size, line_handler_t *line_handler, void *private_data)
297 {
298         char *start = buf, *end;
299         int ret, i, num_lines = 0;
300
301 //      PARA_NOTICE_LOG("buf: %s\n", buf);
302         while (start < buf + size) {
303                 char *next_null;
304                 char *next_cr;
305
306                 next_cr = memchr(start, '\n', buf + size - start);
307                 next_null = memchr(start, '\0', buf + size - start);
308                 if (!next_cr && !next_null)
309                         break;
310                 if (next_cr && next_null) {
311                         end = next_cr < next_null? next_cr : next_null;
312                 } else if (next_null) {
313                         end = next_null;
314                 } else
315                         end = next_cr;
316                 num_lines++;
317                 if (!line_handler) {
318                         start = ++end;
319                         continue;
320                 }
321                 if (mode == LINE_MODE_RO) {
322                         size_t s = end - start;
323                         char *b = para_malloc(s + 1);
324                         memcpy(b, start, s);
325                         b[s] = '\0';
326 //                      PARA_NOTICE_LOG("b: %s, start: %s\n", b, start);
327                         ret = line_handler(b, private_data);
328                         free(b);
329                 } else {
330                         *end = '\0';
331                         ret = line_handler(start, private_data);
332                 }
333                 if (ret < 0)
334                         return ret;
335                 start = ++end;
336         }
337         if (!line_handler || mode == LINE_MODE_RO)
338                 return num_lines;
339         i = buf + size - start;
340         if (i && i != size)
341                 memmove(buf, start, i);
342         return i;
343 }
344
345 /**
346  * Call a custom function for each complete line.
347  *
348  * \param buf The buffer containing data separated by newlines.
349  * \param size The number of bytes in \a buf.
350  * \param line_handler The custom function.
351  * \param private_data Pointer passed to \a line_handler.
352  *
353  * If \p line_handler is \p NULL, the function returns the number of complete
354  * lines in \p buf.  Otherwise, \p line_handler is called for each complete
355  * line in \p buf.  The first argument to \p line_handler is the current line,
356  * and \p private_data is passed as the second argument.  The function returns
357  * if \p line_handler returns a negative value or no more lines are in the
358  * buffer.  The rest of the buffer (last chunk containing an incomplete line)
359  * is moved to the beginning of the buffer.
360  *
361  * \return If \p line_handler is not \p NULL, this function returns the number
362  * of bytes not handled to \p line_handler on success, or the negative return
363  * value of the \p line_handler on errors.
364  *
365  * \sa for_each_line_ro().
366  */
367 int for_each_line(char *buf, size_t size, line_handler_t *line_handler,
368                 void *private_data)
369 {
370         return for_each_complete_line(LINE_MODE_RW, buf, size, line_handler,
371                 private_data);
372 }
373
374 /**
375  * Call a custom function for each complete line.
376  *
377  * \param buf Same meaning as in \p for_each_line().
378  * \param size Same meaning as in \p for_each_line().
379  * \param line_handler Same meaning as in \p for_each_line().
380  * \param private_data Same meaning as in \p for_each_line().
381  *
382  * This function behaves like \p for_each_line(), but \a buf is left unchanged.
383  *
384  * \return On success, the function returns the number of complete lines in \p
385  * buf, otherwise the (negative) return value of \p line_handler is returned.
386  *
387  * \sa for_each_line().
388  */
389 int for_each_line_ro(char *buf, size_t size, line_handler_t *line_handler,
390                 void *private_data)
391 {
392         return for_each_complete_line(LINE_MODE_RO, buf, size, line_handler,
393                 private_data);
394 }
395
396 #define hex(a) (hexchar[(a) & 15])
397 static void write_size_header(char *buf, int n)
398 {
399         static char hexchar[] = "0123456789abcdef";
400
401         buf[0] = hex(n >> 12);
402         buf[1] = hex(n >> 8);
403         buf[2] = hex(n >> 4);
404         buf[3] = hex(n);
405         buf[4] = ' ';
406 }
407
408 int read_size_header(const char *buf)
409 {
410         int i, len = 0;
411
412         for (i = 0; i < 4; i++) {
413                 unsigned char c = buf[i];
414                 len <<= 4;
415                 if (c >= '0' && c <= '9') {
416                         len += c - '0';
417                         continue;
418                 }
419                 if (c >= 'a' && c <= 'f') {
420                         len += c - 'a' + 10;
421                         continue;
422                 }
423                 return -E_SIZE_PREFIX;
424         }
425         if (buf[4] != ' ')
426                 return -E_SIZE_PREFIX;
427         return len;
428 }
429
430 /**
431  * Safely print into a buffer at a given offset.
432  *
433  * \param b Determines the buffer, its size, and the offset.
434  * \param fmt The format string.
435  *
436  * This function prints into the buffer given by \a b at the offset which is
437  * also given by \a b. If there is not enough space to hold the result, the
438  * buffer size is doubled until the underlying call to vsnprintf() succeeds
439  * or the size of the buffer exceeds the maximal size specified in \a b.
440  *
441  * In the latter case the unmodified \a buf and \a offset values as well as the
442  * private_data pointer of \a b are passed to the \a max_size_handler of \a b.
443  * If this function succeeds, i.e. returns a non-negative value, the offset of
444  * \a b is reset to zero and the given data is written to the beginning of the
445  * buffer. If \a max_size_handler() returns a negative value, this value is
446  * returned by \a para_printf().
447  *
448  * Upon return, the offset of \a b is adjusted accordingly so that subsequent
449  * calls to this function append data to what is already contained in the
450  * buffer.
451  *
452  * It's OK to call this function with \p b->buf being \p NULL. In this case, an
453  * initial buffer is allocated.
454  *
455  * \return The number of bytes printed into the buffer (not including the
456  * terminating \p NULL byte) on success, negative on errors. If there is no
457  * size-bound on \a b, i.e. if \p b->max_size is zero, this function never
458  * fails.
459  *
460  * \sa make_message(), vsnprintf(3).
461  */
462 __printf_2_3 int para_printf(struct para_buffer *b, const char *fmt, ...)
463 {
464         int ret, sz_off = (b->flags & PBF_SIZE_PREFIX)? 5 : 0;
465
466         if (!b->buf) {
467                 b->buf = para_malloc(128);
468                 b->size = 128;
469                 b->offset = 0;
470         }
471         while (1) {
472                 char *p = b->buf + b->offset;
473                 size_t size = b->size - b->offset;
474                 va_list ap;
475
476                 if (size > sz_off) {
477                         va_start(ap, fmt);
478                         ret = vsnprintf(p + sz_off, size - sz_off, fmt, ap);
479                         va_end(ap);
480                         if (ret > -1 && ret < size - sz_off) { /* success */
481                                 b->offset += ret + sz_off;
482                                 if (sz_off)
483                                         write_size_header(p, ret);
484                                 return ret + sz_off;
485                         }
486                 }
487                 /* check if we may grow the buffer */
488                 if (!b->max_size || 2 * b->size < b->max_size) { /* yes */
489                         /* try again with more space */
490                         b->size *= 2;
491                         b->buf = para_realloc(b->buf, b->size);
492                         continue;
493                 }
494                 /* can't grow buffer */
495                 if (!b->offset || !b->max_size_handler) /* message too large */
496                         return -ERRNO_TO_PARA_ERROR(ENOSPC);
497                 ret = b->max_size_handler(b->buf, b->offset, b->private_data);
498                 if (ret < 0)
499                         return ret;
500                 b->offset = 0;
501         }
502 }
503
504 /** \cond LLONG_MAX and LLONG_LIN might not be defined. */
505 #ifndef LLONG_MAX
506 #define LLONG_MAX (1 << (sizeof(long) - 1))
507 #endif
508 #ifndef LLONG_MIN
509 #define LLONG_MIN (-LLONG_MAX - 1LL)
510 #endif
511 /** \endcond */
512
513 /**
514  * Convert a string to a 64-bit signed integer value.
515  *
516  * \param str The string to be converted.
517  * \param value Result pointer.
518  *
519  * \return Standard.
520  *
521  * \sa para_atoi32(), strtol(3), atoi(3).
522  */
523 int para_atoi64(const char *str, int64_t *value)
524 {
525         char *endptr;
526         long long tmp;
527
528         errno = 0; /* To distinguish success/failure after call */
529         tmp = strtoll(str, &endptr, 10);
530         if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
531                 return -E_ATOI_OVERFLOW;
532         if (errno != 0 && tmp == 0) /* other error */
533                 return -E_STRTOLL;
534         if (endptr == str)
535                 return -E_ATOI_NO_DIGITS;
536         if (*endptr != '\0') /* Further characters after number */
537                 return -E_ATOI_JUNK_AT_END;
538         *value = tmp;
539         return 1;
540 }
541
542 /**
543  * Convert a string to a 32-bit signed integer value.
544  *
545  * \param str The string to be converted.
546  * \param value Result pointer.
547  *
548  * \return Standard.
549  *
550  * \sa para_atoi64().
551 */
552 int para_atoi32(const char *str, int32_t *value)
553 {
554         int64_t tmp;
555         int ret;
556         const int32_t max = 2147483647;
557
558         ret = para_atoi64(str, &tmp);
559         if (ret < 0)
560                 return ret;
561         if (tmp > max || tmp < -max - 1)
562                 return -E_ATOI_OVERFLOW;
563         *value = tmp;
564         return 1;
565 }
566
567 static inline int loglevel_equal(const char *arg, const char * const ll)
568 {
569         return !strncasecmp(arg, ll, strlen(ll));
570 }
571
572 /**
573  * Compute the loglevel number from its name.
574  *
575  * \param txt The name of the loglevel (debug, info, ...).
576  *
577  * \return The numeric representation of the loglevel name.
578  */
579 int get_loglevel_by_name(const char *txt)
580 {
581         if (loglevel_equal(txt, "debug"))
582                 return LL_DEBUG;
583         if (loglevel_equal(txt, "info"))
584                 return LL_INFO;
585         if (loglevel_equal(txt, "notice"))
586                 return LL_NOTICE;
587         if (loglevel_equal(txt, "warning"))
588                 return LL_WARNING;
589         if (loglevel_equal(txt, "error"))
590                 return LL_ERROR;
591         if (loglevel_equal(txt, "crit"))
592                 return LL_CRIT;
593         if (loglevel_equal(txt, "emerg"))
594                 return LL_EMERG;
595         return -1;
596 }
597
598 static int get_next_word(const char *buf, const char *delim,  char **word)
599 {
600         enum line_state_flags {LSF_HAVE_WORD = 1, LSF_BACKSLASH = 2,
601                 LSF_SINGLE_QUOTE = 4, LSF_DOUBLE_QUOTE = 8};
602         const char *in;
603         char *out;
604         int ret, state = 0;
605
606         out = para_malloc(strlen(buf) + 1);
607         *out = '\0';
608         *word = out;
609         for (in = buf; *in; in++) {
610                 const char *p;
611
612                 switch (*in) {
613                 case '\\':
614                         if (state & LSF_BACKSLASH) /* \\ */
615                                 goto copy_char;
616                         state |= LSF_BACKSLASH;
617                         state |= LSF_HAVE_WORD;
618                         continue;
619                 case 'n':
620                 case 't':
621                         if (state & LSF_BACKSLASH) { /* \n or \t */
622                                 *out++ = (*in == 'n')? '\n' : '\t';
623                                 state &= ~LSF_BACKSLASH;
624                                 continue;
625                         }
626                         goto copy_char;
627                 case '"':
628                         if (state & LSF_BACKSLASH) /* \" */
629                                 goto copy_char;
630                         if (state & LSF_SINGLE_QUOTE) /* '" */
631                                 goto copy_char;
632                         if (state & LSF_DOUBLE_QUOTE) {
633                                 state &= ~LSF_DOUBLE_QUOTE;
634                                 continue;
635                         }
636                         state |= LSF_HAVE_WORD;
637                         state |= LSF_DOUBLE_QUOTE;
638                         continue;
639                 case '\'':
640                         if (state & LSF_BACKSLASH) /* \' */
641                                 goto copy_char;
642                         if (state & LSF_DOUBLE_QUOTE) /* "' */
643                                 goto copy_char;
644                         if (state & LSF_SINGLE_QUOTE) {
645                                 state &= ~LSF_SINGLE_QUOTE;
646                                 continue;
647                         }
648                         state |= LSF_HAVE_WORD;
649                         state |= LSF_SINGLE_QUOTE;
650                         continue;
651                 }
652                 for (p = delim; *p; p++) {
653                         if (*in != *p)
654                                 continue;
655                         if (state & LSF_BACKSLASH)
656                                 goto copy_char;
657                         if (state & LSF_SINGLE_QUOTE)
658                                 goto copy_char;
659                         if (state & LSF_DOUBLE_QUOTE)
660                                 goto copy_char;
661                         if (state & LSF_HAVE_WORD)
662                                 goto success;
663                         break;
664                 }
665                 if (*p) /* ignore delimiter at the beginning */
666                         continue;
667 copy_char:
668                 state |= LSF_HAVE_WORD;
669                 *out++ = *in;
670                 state &= ~LSF_BACKSLASH;
671         }
672         ret = 0;
673         if (!(state & LSF_HAVE_WORD))
674                 goto out;
675         ret = -ERRNO_TO_PARA_ERROR(EINVAL);
676         if (state & LSF_BACKSLASH) {
677                 PARA_ERROR_LOG("trailing backslash\n");
678                 goto out;
679         }
680         if ((state & LSF_SINGLE_QUOTE) || (state & LSF_DOUBLE_QUOTE)) {
681                 PARA_ERROR_LOG("unmatched quote character\n");
682                 goto out;
683         }
684 success:
685         *out = '\0';
686         return in - buf;
687 out:
688         free(*word);
689         *word = NULL;
690         return ret;
691 }
692
693 /**
694  * Free an array of words created by create_argv().
695  *
696  * \param argv A pointer previously obtained by \ref create_argv().
697  */
698 void free_argv(char **argv)
699 {
700         int i;
701
702         for (i = 0; argv[i]; i++)
703                 free(argv[i]);
704         free(argv);
705 }
706
707 /**
708  * Split a buffer into words.
709  *
710  * This parser honors single and double quotes, backslash-escaped characters
711  * and special characters like \p \\n. The result contains pointers to copies
712  * of the words contained in \a buf and has to be freed by using \ref
713  * free_argv().
714  *
715  * \param buf The buffer to be split.
716  * \param delim Each character in this string is treated as a separator.
717  * \param result The array of words is returned here.
718  *
719  * \return Number of words in \a buf, negative on errors.
720  */
721 int create_argv(const char *buf, const char *delim, char ***result)
722 {
723         char *word, **argv = para_malloc(2 * sizeof(char *));
724         const char *p;
725         int ret, num_words;
726
727         for (p = buf, num_words = 0; ; p += ret, num_words++) {
728                 ret = get_next_word(p, delim, &word);
729                 if (ret < 0)
730                         goto err;
731                 if (!ret)
732                         break;
733                 argv = para_realloc(argv, (num_words + 2) * sizeof(char*));
734                 argv[num_words] = word;
735         }
736         argv[num_words] = NULL;
737         *result = argv;
738         return num_words;
739 err:
740         while (num_words > 0)
741                 free(argv[--num_words]);
742         free(argv);
743         return ret;
744 }
745
746 int para_regcomp(regex_t *preg, const char *regex, int cflags)
747 {
748         char *buf;
749         size_t size;
750         int ret = regcomp(preg, regex, cflags);
751
752         if (ret == 0)
753                 return 1;
754         size = regerror(ret, preg, NULL, 0);
755         buf = para_malloc(size);
756         regerror(ret, preg, buf, size);
757         PARA_ERROR_LOG("%s\n", buf);
758         free(buf);
759         return -E_REGEX;
760 }