Initial git checkin.
[adu.git] / string.c
1 /*
2  * Copyright (C) 2004-2008 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 "adu.h"
10 #include "string.h"
11
12 #include <sys/time.h> /* gettimeofday */
13 #include <pwd.h>
14 #include <sys/utsname.h> /* uname() */
15 #include <string.h>
16
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                 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         assert(size);
63         void *p = malloc(size);
64
65         if (!p) {
66                 EMERG_LOG("malloc failed (size = %zu),  aborting\n",
67                         size);
68                 exit(EXIT_FAILURE);
69         }
70         return p;
71 }
72
73 /**
74  * Paraslash's version of calloc().
75  *
76  * \param size The desired new size.
77  *
78  * A wrapper for calloc(3) which exits on errors.
79  *
80  * \return A pointer to the allocated and zeroed-out memory, which is suitably
81  * aligned for any kind of variable.
82  *
83  * \sa calloc(3)
84  */
85 __must_check __malloc void *para_calloc(size_t size)
86 {
87         void *ret = para_malloc(size);
88
89         memset(ret, 0, size);
90         return ret;
91 }
92
93 /**
94  * Paraslash's version of strdup().
95  *
96  * \param s The string to be duplicated.
97  *
98  * A wrapper for strdup(3). It calls \p exit(EXIT_FAILURE) on errors, i.e.
99  * there is no need to check the return value in the caller.
100  *
101  * \return A pointer to the duplicated string. If \p s was the NULL pointer,
102  * an pointer to an empty string is returned.
103  *
104  * \sa strdup(3)
105  */
106 __must_check __malloc char *para_strdup(const char *s)
107 {
108         char *ret;
109
110         if ((ret = strdup(s? s: "")))
111                 return ret;
112         EMERG_LOG("strdup failed, aborting\n");
113         exit(EXIT_FAILURE);
114 }
115
116 /**
117  * Allocate a sufficiently large string and print into it.
118  *
119  * \param fmt A usual format string.
120  *
121  * Produce output according to \p fmt. No artificial bound on the length of the
122  * resulting string is imposed.
123  *
124  * \return This function either returns a pointer to a string that must be
125  * freed by the caller or aborts without returning.
126  *
127  * \sa printf(3).
128  */
129 __must_check __printf_1_2 __malloc char *make_message(const char *fmt, ...)
130 {
131         char *msg;
132
133         VSPRINTF(fmt, msg);
134         return msg;
135 }
136
137 /**
138  * Paraslash's version of strcat().
139  *
140  * \param a String to be appended to.
141  * \param b String to append.
142  *
143  * Append \p b to \p a.
144  *
145  * \return If \a a is \p NULL, return a pointer to a copy of \a b, i.e.
146  * para_strcat(NULL, b) is equivalent to para_strdup(b). If \a b is \p NULL,
147  * return \a a without making a copy of \a a.  Otherwise, construct the
148  * concatenation \a c, free \a a (but not \a b) and return \a c.
149  *
150  * \sa strcat(3)
151  */
152 __must_check __malloc char *para_strcat(char *a, const char *b)
153 {
154         char *tmp;
155
156         if (!a)
157                 return para_strdup(b);
158         if (!b)
159                 return a;
160         tmp = make_message("%s%s", a, b);
161         free(a);
162         return tmp;
163 }
164
165 /**
166  * Paraslash's version of dirname().
167  *
168  * \param name Pointer to the full path.
169  *
170  * Compute the directory component of \p name.
171  *
172  * \return If \a name is \p NULL or the empty string, return \p NULL.
173  * Otherwise, Make a copy of \a name and return its directory component. Caller
174  * is responsible to free the result.
175  */
176 __must_check __malloc char *para_dirname(const char *name)
177 {
178         char *p, *ret;
179
180         if (!name || !*name)
181                 return NULL;
182         ret = para_strdup(name);
183         p = strrchr(ret, '/');
184         if (!p)
185                 *ret = '\0';
186         else
187                 *p = '\0';
188         return ret;
189 }
190
191 /**
192  * Paraslash's version of basename().
193  *
194  * \param name Pointer to the full path.
195  *
196  * Compute the filename component of \a name.
197  *
198  * \return \p NULL if (a) \a name is the empty string or \p NULL, or (b) name
199  * ends with a slash.  Otherwise, a pointer within \a name is returned.  Caller
200  * must not free the result.
201  */
202 __must_check const char *para_basename(const char *name)
203 {
204         const char *ret;
205
206         if (!name || !*name)
207                 return NULL;
208         ret = strrchr(name, '/');
209         if (!ret)
210                 return name;
211         ret++;
212         return ret;
213 }
214
215 /**
216  * Cut trailing newline.
217  *
218  * \param buf The string to be chopped.
219  *
220  * Replace the last character in \p buf by zero if it is euqal to
221  * the newline character.
222  */
223 void chop(char *buf)
224 {
225         int n = strlen(buf);
226         if (!n)
227                 return;
228         if (buf[n - 1] == '\n')
229                 buf[n - 1] = '\0';
230 }
231
232 /**
233  * Get a random filename.
234  *
235  * This is by no means a secure way to create temporary files in a hostile
236  * direcory like \p /tmp. However, it is OK to use for temp files, fifos,
237  * sockets that are created in ~/.paraslash. Result must be freed by the
238  * caller.
239  *
240  * \return A pointer to a random filename.
241  */
242 __must_check __malloc char *para_tmpname(void)
243 {
244         struct timeval now;
245         unsigned int seed;
246
247         gettimeofday(&now, NULL);
248         seed = now.tv_usec;
249         srand(seed);
250         return make_message("%08i", rand());
251 }
252
253 /**
254  * Get the logname of the current user.
255  *
256  * \return A dynammically allocated string that must be freed by the caller. On
257  * errors, the string "unknown user" is returned, i.e. this function never
258  * returns \p NULL.
259  *
260  * \sa getpwuid(3).
261  */
262 __must_check __malloc char *para_logname(void)
263 {
264         struct passwd *pw = getpwuid(getuid());
265         return para_strdup(pw? pw->pw_name : "unknown_user");
266 }
267
268 /**
269  * Get the home directory of the current user.
270  *
271  * \return A dynammically allocated string that must be freed by the caller. If
272  * the home directory could not be found, this function returns "/tmp".
273  */
274 __must_check __malloc char *para_homedir(void)
275 {
276         struct passwd *pw = getpwuid(getuid());
277         return para_strdup(pw? pw->pw_dir : "/tmp");
278 }
279
280 /**
281  * Split string and return pointers to its parts.
282  *
283  * \param args The string to be split.
284  * \param argv_ptr Pointer to the list of substrings.
285  * \param delim Delimiter.
286  *
287  * This function modifies \a args by replacing each occurance of \a delim by
288  * zero. A \p NULL-terminated array of pointers to char* is allocated dynamically
289  * and these pointers are initialized to point to the broken-up substrings
290  * within \a args. A pointer to this array is returned via \a argv_ptr.
291  *
292  * \return The number of substrings found in \a args.
293  */
294 __must_check unsigned split_args(char *args, char *** const argv_ptr, const char *delim)
295 {
296         char *p = args;
297         char **argv;
298         size_t n = 0, i, j;
299
300         p = args + strspn(args, delim);
301         for (;;) {
302                 i = strcspn(p, delim);
303                 if (!i)
304                         break;
305                 p += i;
306                 n++;
307                 p += strspn(p, delim);
308         }
309         *argv_ptr = para_malloc((n + 1) * sizeof(char *));
310         argv = *argv_ptr;
311         i = 0;
312         p = args + strspn(args, delim);
313         while (p) {
314                 argv[i] = p;
315                 j = strcspn(p, delim);
316                 if (!j)
317                         break;
318                 p += strcspn(p, delim);
319                 if (*p) {
320                         *p = '\0';
321                         p++;
322                         p += strspn(p, delim);
323                 }
324                 i++;
325         }
326         argv[n] = NULL;
327         return n;
328 }
329
330 /**
331  * Ensure that file descriptors 0, 1, and 2 are valid.
332  *
333  * Common approach that opens /dev/null until it gets a file descriptor greater
334  * than two.
335  *
336  * \sa okir's Black Hats Manual.
337  */
338 void valid_fd_012(void)
339 {
340         while (1) {
341                 int fd = open("/dev/null", O_RDWR);
342                 if (fd < 0)
343                         exit(EXIT_FAILURE);
344                 if (fd > 2) {
345                         close(fd);
346                         break;
347                 }
348         }
349 }
350
351 /**
352  * Get the own hostname.
353  *
354  * \return A dynammically allocated string containing the hostname.
355  *
356  * \sa uname(2).
357  */
358 __malloc char *para_hostname(void)
359 {
360         struct utsname u;
361
362         uname(&u);
363         return para_strdup(u.nodename);
364 }
365
366 /**
367  * Used to distinguish between read-only and read-write mode.
368  *
369  * \sa for_each_line(), for_each_line_ro().
370  */
371 enum for_each_line_modes{
372         /** Activate read-only mode. */
373         LINE_MODE_RO,
374         /** Activate read-write mode. */
375         LINE_MODE_RW
376 };
377
378 static int for_each_complete_line(enum for_each_line_modes mode, char *buf,
379                 size_t size, line_handler_t *line_handler, void *private_data)
380 {
381         char *start = buf, *end;
382         int ret, i, num_lines = 0;
383
384 //      PARA_NOTICE_LOG("buf: %s\n", buf);
385         while (start < buf + size) {
386                 char *next_null;
387                 char *next_cr;
388
389                 next_cr = memchr(start, '\n', buf + size - start);
390                 next_null = memchr(start, '\0', buf + size - start);
391                 if (!next_cr && !next_null)
392                         break;
393                 if (next_cr && next_null) {
394                         end = next_cr < next_null? next_cr : next_null;
395                 } else if (next_null) {
396                         end = next_null;
397                 } else
398                         end = next_cr;
399                 num_lines++;
400                 if (!line_handler) {
401                         start = ++end;
402                         continue;
403                 }
404                 if (mode == LINE_MODE_RO) {
405                         size_t s = end - start;
406                         char *b = para_malloc(s + 1);
407                         memcpy(b, start, s);
408                         b[s] = '\0';
409 //                      PARA_NOTICE_LOG("b: %s, start: %s\n", b, start);
410                         ret = line_handler(b, private_data);
411                         free(b);
412                 } else {
413                         *end = '\0';
414                         ret = line_handler(start, private_data);
415                 }
416                 if (ret < 0)
417                         return ret;
418                 start = ++end;
419         }
420         if (!line_handler || mode == LINE_MODE_RO)
421                 return num_lines;
422         i = buf + size - start;
423         if (i && i != size)
424                 memmove(buf, start, i);
425         return i;
426 }
427
428 /**
429  * Call a custom function for each complete line.
430  *
431  * \param buf The buffer containing data seperated by newlines.
432  * \param size The number of bytes in \a buf.
433  * \param line_handler The custom function.
434  * \param private_data Pointer passed to \a line_handler.
435  *
436  * If \p line_handler is \p NULL, the function returns the number of complete
437  * lines in \p buf.  Otherwise, \p line_handler is called for each complete
438  * line in \p buf.  The first argument to \p line_handler is the current line,
439  * and \p private_data is passed as the second argument.  The function returns
440  * if \p line_handler returns a negative value or no more lines are in the
441  * buffer.  The rest of the buffer (last chunk containing an incomplete line)
442  * is moved to the beginning of the buffer.
443  *
444  * \return If \p line_handler is not \p NULL, this function returns the number
445  * of bytes not handled to \p line_handler on success, or the negative return
446  * value of the \p line_handler on errors.
447  *
448  * \sa for_each_line_ro().
449  */
450 int for_each_line(char *buf, size_t size, line_handler_t *line_handler,
451                 void *private_data)
452 {
453         return for_each_complete_line(LINE_MODE_RW, buf, size, line_handler,
454                 private_data);
455 }
456
457 /**
458  * Call a custom function for each complete line.
459  *
460  * \param buf Same meaning as in \p for_each_line().
461  * \param size Same meaning as in \p for_each_line().
462  * \param line_handler Same meaning as in \p for_each_line().
463  * \param private_data Same meaning as in \p for_each_line().
464  *
465  * This function behaves like \p for_each_line(), but \a buf is left unchanged.
466  *
467  * \return On success, the function returns the number of complete lines in \p
468  * buf, otherwise the (negative) return value of \p line_handler is returned.
469  *
470  * \sa for_each_line().
471  */
472 int for_each_line_ro(char *buf, size_t size, line_handler_t *line_handler,
473                 void *private_data)
474 {
475         return for_each_complete_line(LINE_MODE_RO, buf, size, line_handler,
476                 private_data);
477 }
478
479 /**
480  * Safely print into a buffer at a given offset
481  *
482  * \param b Determines the buffer, its size, and the offset.
483  * \param fmt The format string.
484  *
485  * This function prints into the buffer given by \a b at the offset which is
486  * also given by \a b. If there is not enough space to hold the result, the
487  * buffer size is doubled until the underlying call to vsnprintf() succeeds
488  * or the size of the buffer exceeds the maximal size specified in \a pb.
489  *
490  * In the latter case the unmodified \a buf and \a offset values as well as the
491  * private_data pointer of \a b are passed to the \a max_size_handler of \a b.
492  * If this function succeeds, i.e. returns a non-negative value, the offset of
493  * \a b is reset to zero and the given data is written to the beginning of the
494  * buffer.
495  *
496  * Upon return, the offset of \a b is adjusted accordingly so that subsequent
497  * calls to this function append data to what is already contained in the
498  * buffer.
499  *
500  * It's OK to call this function with \p b->buf being \p NULL. In this case, an
501  * initial buffer is allocated.
502  *
503  * \return The number of bytes printed into the buffer (not including the
504  * therminating \p NULL byte).
505  *
506  * \sa make_message(), vsnprintf(3).
507  */
508 __printf_2_3 int para_printf(struct para_buffer *b, const char *fmt, ...)
509 {
510         int ret;
511
512         if (!b->buf) {
513                 b->buf = para_malloc(128);
514                 b->size = 128;
515                 b->offset = 0;
516         }
517         while (1) {
518                 char *p = b->buf + b->offset;
519                 size_t size = b->size - b->offset;
520                 va_list ap;
521                 if (size) {
522                         va_start(ap, fmt);
523                         ret = vsnprintf(p, size, fmt, ap);
524                         va_end(ap);
525                         if (ret > -1 && ret < size) { /* success */
526                                 b->offset += ret;
527                                 return ret;
528                         }
529                 }
530                 /* check if we may grow the buffer */
531                 if (!b->max_size || 2 * b->size < b->max_size) { /* yes */
532                         /* try again with more space */
533                         b->size *= 2;
534                         b->buf = para_realloc(b->buf, b->size);
535                         continue;
536                 }
537                 /* can't grow buffer */
538                 if (!b->offset || !b->max_size_handler) /* message too large */
539                         return -ERRNO_TO_ERROR(ENOSPC);
540                 ret = b->max_size_handler(b->buf, b->offset, b->private_data);
541                 if (ret < 0)
542                         return ret;
543                 b->offset = 0;
544         }
545 }
546
547 /** \cond LLONG_MAX and LLONG_LIN might not be defined. */
548 #ifndef LLONG_MAX
549 #define LLONG_MAX (1 << (sizeof(long) - 1))
550 #endif
551 #ifndef LLONG_MIN
552 #define LLONG_MIN (-LLONG_MAX - 1LL)
553 #endif
554 /** \endcond */
555
556 /**
557  * Convert a string to a 64-bit signed integer value.
558  *
559  * \param str The string to be converted.
560  * \param value Result pointer.
561  *
562  * \return Standard.
563  *
564  * \sa para_atoi32(), strtol(3), atoi(3).
565  */
566 int para_atoi64(const char *str, int64_t *value)
567 {
568         char *endptr;
569         long long tmp;
570
571         errno = 0; /* To distinguish success/failure after call */
572         tmp = strtoll(str, &endptr, 10);
573         if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
574                 return -E_ATOI_OVERFLOW;
575         if (errno != 0 && tmp == 0) /* other error */
576                 return -E_STRTOLL;
577         if (endptr == str)
578                 return -E_ATOI_NO_DIGITS;
579         if (*endptr != '\0') /* Further characters after number */
580                 return -E_ATOI_JUNK_AT_END;
581         *value = tmp;
582         return 1;
583 }
584
585 /**
586  * Convert a string to a 32-bit signed integer value.
587  *
588  * \param str The string to be converted.
589  * \param value Result pointer.
590  *
591  * \return Standard.
592  *
593  * \sa para_atoi64().
594 */
595 int para_atoi32(const char *str, int32_t *value)
596 {
597         int64_t tmp;
598         int ret;
599         const int32_t max = 2147483647;
600
601         ret = para_atoi64(str, &tmp);
602         if (ret < 0)
603                 return ret;
604         if (tmp > max || tmp < -max - 1)
605                 return -E_ATOI_OVERFLOW;
606         *value = tmp;
607         return 1;
608 }