server.c: Initialize vss _after_ afs.
[paraslash.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 "para.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 NULL
23  * \param size 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 \p 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 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                 PARA_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 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 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         PARA_EMERG_LOG("%s", "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 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         PARA_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 \p a is NULL, return a pointer to a copy of \p b, i.e.
146  * para_strcat(NULL, b) is equivalent to para_strdup(b). If \p b is NULL,
147  * return \p a without making a copy of \p a.  Otherwise, construct the
148  * concatenation \p c, free \p a (but not \p b) and return \p 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 \p name is \p NULL or the empty string, return \p NULL.
173  * Otherwise, Make a copy of \p 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 of \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  * create unique temporary file
255  *
256  * \param template the template to be passed to mkstemp()
257  * \param mode the desired mode of the tempfile
258  *
259  * This wrapper for mkstemp additionally uses fchmod() to
260  * set the given mode of the tempfile if mkstemp() returned success.
261  *
262  * \return The file descriptor of the temp file just created on success.
263  * On errors, -E_MKSTEMP or -E_FCHMOD is returned.
264  */
265 __must_check int para_mkstemp(char *template, mode_t mode)
266 {
267         int tmp, fd = mkstemp(template);
268
269         if (fd < 0)
270                 return -E_MKSTEMP;
271         tmp = fchmod(fd, mode);
272         if (tmp >= 0)
273                 return fd;
274         close(fd);
275         unlink(template);
276         return -E_FCHMOD;
277 }
278
279 /**
280  * get the logname of the current user
281  *
282  * \return A dynammically allocated string that must be freed by the caller. On
283  * errors, the string "unknown user" is returned, i.e. this function never
284  * returns NULL.
285  *
286  * \sa getpwuid(3)
287  */
288 __must_check __malloc char *para_logname(void)
289 {
290         struct passwd *pw = getpwuid(getuid());
291         return para_strdup(pw? pw->pw_name : "unknown_user");
292 }
293
294 /**
295  * get the home directory of the current user
296  *
297  * \return A dynammically allocated string that must be freed by the caller. If
298  * the home directory could not be found, this function returns "/tmp".
299  */
300 __must_check __malloc char *para_homedir(void)
301 {
302         struct passwd *pw = getpwuid(getuid());
303         return para_strdup(pw? pw->pw_dir : "/tmp");
304 }
305
306 /**
307  * split string and return pointers to its parts.
308  *
309  * \param args the string to be split
310  * \param argv_ptr  pointer to the list of substrings
311  * \param delim delimiter
312  *
313  * This function modifies \a args by replacing each occurance of \a delim by
314  * zero. A \p NULL-terminated array of pointers to char* is allocated dynamically
315  * and these pointers are initialized to point to the broken-up substrings
316  * within \a args. A pointer to this array is returned via \a argv_ptr. It's OK
317  * to call this function with \a args \a == \p NULL.
318  *
319  * \return The number of substrings found in \a args.
320  */
321 __must_check unsigned split_args(char *args, char *** const argv_ptr, const char *delim)
322 {
323         char *p = args;
324         char **argv;
325         size_t n = 0, i, j;
326
327         p = args + strspn(args, delim);
328         for (;;) {
329                 i = strcspn(p, delim);
330                 if (!i)
331                         break;
332                 p += i;
333                 n++;
334                 p += strspn(p, delim);
335         }
336         *argv_ptr = para_malloc((n + 1) * sizeof(char *));
337         argv = *argv_ptr;
338         i = 0;
339         p = args + strspn(args, delim);
340         while (p) {
341                 argv[i] = p;
342                 j = strcspn(p, delim);
343                 if (!j)
344                         break;
345                 p += strcspn(p, delim);
346                 if (*p) {
347                         *p = '\0';
348                         p++;
349                         p += strspn(p, delim);
350                 }
351                 i++;
352         }
353         argv[n] = NULL;
354         return n;
355 }
356
357 /**
358  * ensure that file descriptors 0, 1, and 2 are valid
359  *
360  * Common approach that opens /dev/null until it gets a file descriptor greater
361  * than two.
362  *
363  * \sa okir's Black Hats Manual.
364  */
365 void valid_fd_012(void)
366 {
367         while (1) {
368         int     fd;
369
370                 fd = open("/dev/null", O_RDWR);
371                 if (fd < 0)
372                         exit(EXIT_FAILURE);
373                 if (fd > 2) {
374                         close(fd);
375                         break;
376                 }
377         }
378 }
379
380 /**
381  * get the own hostname
382  *
383  * \return A dynammically allocated string containing the hostname.
384  *
385  * \sa uname(2)
386  */
387 __malloc char *para_hostname(void)
388 {
389         struct utsname u;
390
391         uname(&u);
392         return para_strdup(u.nodename);
393 }
394
395 /**
396  * Used to distinguish between read-only and read-write mode.
397  *
398  * \sa for_each_line(), for_each_line_ro().
399  */
400 enum for_each_line_modes{
401         /** Activate read-only mode. */
402         LINE_MODE_RO,
403         /** Activate read-write mode. */
404         LINE_MODE_RW
405 };
406
407 static int for_each_complete_line(enum for_each_line_modes mode, char *buf,
408                 size_t size, line_handler_t *line_handler, void *private_data)
409 {
410         char *start = buf, *end;
411         int ret, i, num_lines = 0;
412
413 //      PARA_NOTICE_LOG("buf: %s\n", buf);
414         while (start < buf + size) {
415                 char *next_null;
416                 char *next_cr;
417
418                 next_cr = memchr(start, '\n', buf + size - start);
419                 next_null = memchr(start, '\0', buf + size - start);
420                 if (!next_cr && !next_null)
421                         break;
422                 if (next_cr && next_null) {
423                         end = next_cr < next_null? next_cr : next_null;
424                 } else if (next_null) {
425                         end = next_null;
426                 } else
427                         end = next_cr;
428                 num_lines++;
429                 if (!line_handler) {
430                         start = ++end;
431                         continue;
432                 }
433                 if (mode == LINE_MODE_RO) {
434                         size_t s = end - start;
435                         char *b = para_malloc(s + 1);
436                         memcpy(b, start, s);
437                         b[s] = '\0';
438 //                      PARA_NOTICE_LOG("b: %s, start: %s\n", b, start);
439                         ret = line_handler(b, private_data);
440                         free(b);
441                 } else {
442                         *end = '\0';
443                         ret = line_handler(start, private_data);
444                 }
445                 if (ret < 0)
446                         return ret;
447                 start = ++end;
448         }
449         if (!line_handler || mode == LINE_MODE_RO)
450                 return num_lines;
451         i = buf + size - start;
452         if (i && i != size)
453                 memmove(buf, start, i);
454         return i;
455 }
456
457 /**
458  * Call a custom function for each complete line.
459  *
460  * \param buf The buffer containing data seperated by newlines.
461  * \param size The number of bytes in \a buf.
462  * \param line_handler The custom function.
463  * \param private_data Pointer passed to \a line_handler.
464  *
465  * If \p line_handler is \p NULL, the function returns the number of complete
466  * lines in \p buf.  Otherwise, \p line_handler is called for each complete
467  * line in \p buf.  The first argument to \p line_handler is the current line,
468  * and \p private_data is passed as the second argument.  The function returns
469  * if \p line_handler returns a negative value or no more lines are in the
470  * buffer.  The rest of the buffer (last chunk containing an incomplete line)
471  * is moved to the beginning of the buffer.
472  *
473  * \return If \p line_handler is not \p NULL, this function returns the number
474  * of bytes not handled to \p line_handler on success, or the negative return
475  * value of the \p line_handler on errors.
476  *
477  * \sa for_each_line_ro().
478  */
479 int for_each_line(char *buf, size_t size, line_handler_t *line_handler,
480                 void *private_data)
481 {
482         return for_each_complete_line(LINE_MODE_RW, buf, size, line_handler,
483                 private_data);
484 }
485
486 /**
487  * Call a custom function for each complete line.
488  *
489  * \param buf Same meaning as in \p for_each_line().
490  * \param size Same meaning as in \p for_each_line().
491  * \param line_handler Same meaning as in \p for_each_line().
492  * \param private_data Same meaning as in \p for_each_line().
493  *
494  * This function behaves like \p for_each_line(), but \a buf is left unchanged.
495  *
496  * \return On success, the function returns the number of complete lines in \p
497  * buf, otherwise the (negative) return value of \p line_handler is returned.
498  *
499  * \sa for_each_line().
500  */
501 int for_each_line_ro(char *buf, size_t size, line_handler_t *line_handler,
502                 void *private_data)
503 {
504         return for_each_complete_line(LINE_MODE_RO, buf, size, line_handler,
505                 private_data);
506 }
507
508 /**
509  * Safely print into a buffer at a given offset
510  *
511  * \param b Determines the buffer, its size, and the offset.
512  * \param fmt The format string.
513  *
514  * This function prints into the buffer given by \a b at the offset which is
515  * also given by \a b. If there is not enough space to hold the result, the
516  * buffer size is doubled until the underlying call to vsnprintf() succeeds.
517  * Upon return, the offset of \a b is adjusted accordingly so that subsequent
518  * calls to this function append data to what is already contained in the
519  * buffer.
520  *
521  * It's OK to call this function with \p b->buf being \p NULL. In this case, an
522  * initial buffer is allocated.
523  *
524  * \return The number of bytes printed into the buffer (not including the
525  * therminating \p NULL byte).
526  *
527  * \sa make_message(), vsnprintf(3).
528  */
529 __printf_2_3 int para_printf(struct para_buffer *b, const char *fmt, ...)
530 {
531         int ret;
532
533         if (!b->buf) {
534                 b->buf = para_malloc(128);
535                 b->size = 128;
536                 b->offset = 0;
537         } else if (b->size <= b->offset + 1) {
538                 b->size *= 2;
539                 b->buf = para_realloc(b->buf, b->size);
540         }
541         while (1) {
542                 char *p = b->buf + b->offset;
543                 size_t size = b->size - b->offset;
544                 va_list ap;
545                 va_start(ap, fmt);
546                 ret = vsnprintf(p, size, fmt, ap);
547                 va_end(ap);
548                 if (ret > -1 && ret < size) { /* success */
549                         b->offset += ret;
550                         break;
551                 }
552                 /* try again with more space */
553                 b->size *= 2;
554                 b->buf = para_realloc(b->buf, b->size);
555         }
556         return ret;
557 }
558
559 /** \cond LLONG_MAX and LLONG_LIN might not be defined. */
560 #ifndef LLONG_MAX
561 #define LLONG_MAX (1 << (sizeof(long) - 1))
562 #endif
563 #ifndef LLONG_MIN
564 #define LLONG_MIN (-LLONG_MAX - 1LL)
565 #endif
566 /** \endcond */
567
568 /**
569  * Convert a string to a 64-bit signed integer value.
570  *
571  * \param str The string to be converted.
572  * \param value Result pointer.
573  *
574  * \return Positive on success, negative on errors.
575  *
576  * \sa para_atoi32(), strtol(3), atoi(3).
577  */
578 int para_atoi64(const char *str, int64_t *value)
579 {
580         char *endptr;
581         long long tmp;
582
583         errno = 0; /* To distinguish success/failure after call */
584         tmp = strtoll(str, &endptr, 10);
585         if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
586                 return -E_ATOI_OVERFLOW;
587         if (errno != 0 && tmp == 0) /* other error */
588                 return -E_STRTOLL;
589         if (endptr == str)
590                 return -E_ATOI_NO_DIGITS;
591         if (*endptr != '\0') /* Further characters after number */
592                 return -E_ATOI_JUNK_AT_END;
593         *value = tmp;
594         return 1;
595 }
596
597 /**
598  * Convert a string to a 32-bit signed integer value.
599  *
600  * \param str The string to be converted.
601  * \param value Result pointer.
602  *
603  * \return Positive on success, negative on errors.
604  *
605  * \sa para_atoi64().
606 */
607 int para_atoi32(const char *str, int32_t *value)
608 {
609         int64_t tmp;
610         int ret;
611         const int32_t max = 2147483647;
612
613         ret = para_atoi64(str, &tmp);
614         if (ret < 0)
615                 return ret;
616         if (tmp > max || tmp < -max - 1)
617                 return -E_ATOI_OVERFLOW;
618         *value = tmp;
619         return 1;
620 }