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