Add some missing source code documentation.
[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 "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 \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 \p s was the 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 /**
139 * Paraslash's version of strcat().
140 *
141 * \param a String to be appended to.
142 * \param b String to append.
143 *
144 * Append \p b to \p a.
145 *
146 * \return If \a a is \p NULL, return a pointer to a copy of \a b, i.e.
147 * para_strcat(NULL, b) is equivalent to para_strdup(b). If \a b is \p NULL,
148 * return \a a without making a copy of \a a. Otherwise, construct the
149 * concatenation \a c, free \a a (but not \a b) and return \a c.
150 *
151 * \sa strcat(3)
152 */
153 __must_check __malloc char *para_strcat(char *a, const char *b)
154 {
155 char *tmp;
156
157 if (!a)
158 return para_strdup(b);
159 if (!b)
160 return a;
161 tmp = make_message("%s%s", a, b);
162 free(a);
163 return tmp;
164 }
165
166 /**
167 * Paraslash's version of dirname().
168 *
169 * \param name Pointer to the full path.
170 *
171 * Compute the directory component of \p name.
172 *
173 * \return If \a name is \p NULL or the empty string, return \p NULL.
174 * Otherwise, Make a copy of \a name and return its directory component. Caller
175 * is responsible to free the result.
176 */
177 __must_check __malloc char *para_dirname(const char *name)
178 {
179 char *p, *ret;
180
181 if (!name || !*name)
182 return NULL;
183 ret = para_strdup(name);
184 p = strrchr(ret, '/');
185 if (!p)
186 *ret = '\0';
187 else
188 *p = '\0';
189 return ret;
190 }
191
192 /**
193 * Paraslash's version of basename().
194 *
195 * \param name Pointer to the full path.
196 *
197 * Compute the filename component of \a name.
198 *
199 * \return \p NULL if (a) \a name is the empty string or \p NULL, or (b) name
200 * ends with a slash. Otherwise, a pointer within \a name is returned. Caller
201 * must not free the result.
202 */
203 __must_check const char *para_basename(const char *name)
204 {
205 const char *ret;
206
207 if (!name || !*name)
208 return NULL;
209 ret = strrchr(name, '/');
210 if (!ret)
211 return name;
212 ret++;
213 return ret;
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 * Get the logname of the current user.
256 *
257 * \return A dynammically allocated string that must be freed by the caller. On
258 * errors, the string "unknown user" is returned, i.e. this function never
259 * returns \p NULL.
260 *
261 * \sa getpwuid(3).
262 */
263 __must_check __malloc char *para_logname(void)
264 {
265 struct passwd *pw = getpwuid(getuid());
266 return para_strdup(pw? pw->pw_name : "unknown_user");
267 }
268
269 /**
270 * Get the home directory of the current user.
271 *
272 * \return A dynammically allocated string that must be freed by the caller. If
273 * the home directory could not be found, this function returns "/tmp".
274 */
275 __must_check __malloc char *para_homedir(void)
276 {
277 struct passwd *pw = getpwuid(getuid());
278 return para_strdup(pw? pw->pw_dir : "/tmp");
279 }
280
281 /**
282 * Split string and return pointers to its parts.
283 *
284 * \param args The string to be split.
285 * \param argv_ptr Pointer to the list of substrings.
286 * \param delim Delimiter.
287 *
288 * This function modifies \a args by replacing each occurance of \a delim by
289 * zero. A \p NULL-terminated array of pointers to char* is allocated dynamically
290 * and these pointers are initialized to point to the broken-up substrings
291 * within \a args. A pointer to this array is returned via \a argv_ptr.
292 *
293 * \return The number of substrings found in \a args.
294 */
295 unsigned split_args(char *args, char *** const argv_ptr, const char *delim)
296 {
297 char *p;
298 char **argv;
299 size_t n = 0, i, j;
300
301 p = args + strspn(args, delim);
302 for (;;) {
303 i = strcspn(p, delim);
304 if (!i)
305 break;
306 p += i;
307 n++;
308 p += strspn(p, delim);
309 }
310 *argv_ptr = para_malloc((n + 1) * sizeof(char *));
311 argv = *argv_ptr;
312 i = 0;
313 p = args + strspn(args, delim);
314 while (p) {
315 argv[i] = p;
316 j = strcspn(p, delim);
317 if (!j)
318 break;
319 p += strcspn(p, delim);
320 if (*p) {
321 *p = '\0';
322 p++;
323 p += strspn(p, delim);
324 }
325 i++;
326 }
327 argv[n] = NULL;
328 return n;
329 }
330
331 /**
332 * Get the own hostname.
333 *
334 * \return A dynammically allocated string containing the hostname.
335 *
336 * \sa uname(2).
337 */
338 __malloc char *para_hostname(void)
339 {
340 struct utsname u;
341
342 uname(&u);
343 return para_strdup(u.nodename);
344 }
345
346 /**
347 * Used to distinguish between read-only and read-write mode.
348 *
349 * \sa for_each_line(), for_each_line_ro().
350 */
351 enum for_each_line_modes{
352 /** Activate read-only mode. */
353 LINE_MODE_RO,
354 /** Activate read-write mode. */
355 LINE_MODE_RW
356 };
357
358 static int for_each_complete_line(enum for_each_line_modes mode, char *buf,
359 size_t size, line_handler_t *line_handler, void *private_data)
360 {
361 char *start = buf, *end;
362 int ret, i, num_lines = 0;
363
364 // PARA_NOTICE_LOG("buf: %s\n", buf);
365 while (start < buf + size) {
366 char *next_null;
367 char *next_cr;
368
369 next_cr = memchr(start, '\n', buf + size - start);
370 next_null = memchr(start, '\0', buf + size - start);
371 if (!next_cr && !next_null)
372 break;
373 if (next_cr && next_null) {
374 end = next_cr < next_null? next_cr : next_null;
375 } else if (next_null) {
376 end = next_null;
377 } else
378 end = next_cr;
379 num_lines++;
380 if (!line_handler) {
381 start = ++end;
382 continue;
383 }
384 if (mode == LINE_MODE_RO) {
385 size_t s = end - start;
386 char *b = para_malloc(s + 1);
387 memcpy(b, start, s);
388 b[s] = '\0';
389 // PARA_NOTICE_LOG("b: %s, start: %s\n", b, start);
390 ret = line_handler(b, private_data);
391 free(b);
392 } else {
393 *end = '\0';
394 ret = line_handler(start, private_data);
395 }
396 if (ret < 0)
397 return ret;
398 start = ++end;
399 }
400 if (!line_handler || mode == LINE_MODE_RO)
401 return num_lines;
402 i = buf + size - start;
403 if (i && i != size)
404 memmove(buf, start, i);
405 return i;
406 }
407
408 /**
409 * Call a custom function for each complete line.
410 *
411 * \param buf The buffer containing data seperated by newlines.
412 * \param size The number of bytes in \a buf.
413 * \param line_handler The custom function.
414 * \param private_data Pointer passed to \a line_handler.
415 *
416 * If \p line_handler is \p NULL, the function returns the number of complete
417 * lines in \p buf. Otherwise, \p line_handler is called for each complete
418 * line in \p buf. The first argument to \p line_handler is the current line,
419 * and \p private_data is passed as the second argument. The function returns
420 * if \p line_handler returns a negative value or no more lines are in the
421 * buffer. The rest of the buffer (last chunk containing an incomplete line)
422 * is moved to the beginning of the buffer.
423 *
424 * \return If \p line_handler is not \p NULL, this function returns the number
425 * of bytes not handled to \p line_handler on success, or the negative return
426 * value of the \p line_handler on errors.
427 *
428 * \sa for_each_line_ro().
429 */
430 int for_each_line(char *buf, size_t size, line_handler_t *line_handler,
431 void *private_data)
432 {
433 return for_each_complete_line(LINE_MODE_RW, buf, size, line_handler,
434 private_data);
435 }
436
437 /**
438 * Call a custom function for each complete line.
439 *
440 * \param buf Same meaning as in \p for_each_line().
441 * \param size Same meaning as in \p for_each_line().
442 * \param line_handler Same meaning as in \p for_each_line().
443 * \param private_data Same meaning as in \p for_each_line().
444 *
445 * This function behaves like \p for_each_line(), but \a buf is left unchanged.
446 *
447 * \return On success, the function returns the number of complete lines in \p
448 * buf, otherwise the (negative) return value of \p line_handler is returned.
449 *
450 * \sa for_each_line().
451 */
452 int for_each_line_ro(char *buf, size_t size, line_handler_t *line_handler,
453 void *private_data)
454 {
455 return for_each_complete_line(LINE_MODE_RO, buf, size, line_handler,
456 private_data);
457 }
458
459 /**
460 * Safely print into a buffer at a given offset
461 *
462 * \param b Determines the buffer, its size, and the offset.
463 * \param fmt The format string.
464 *
465 * This function prints into the buffer given by \a b at the offset which is
466 * also given by \a b. If there is not enough space to hold the result, the
467 * buffer size is doubled until the underlying call to vsnprintf() succeeds
468 * or the size of the buffer exceeds the maximal size specified in \a pb.
469 *
470 * In the latter case the unmodified \a buf and \a offset values as well as the
471 * private_data pointer of \a b are passed to the \a max_size_handler of \a b.
472 * If this function succeeds, i.e. returns a non-negative value, the offset of
473 * \a b is reset to zero and the given data is written to the beginning of the
474 * buffer.
475 *
476 * Upon return, the offset of \a b is adjusted accordingly so that subsequent
477 * calls to this function append data to what is already contained in the
478 * buffer.
479 *
480 * It's OK to call this function with \p b->buf being \p NULL. In this case, an
481 * initial buffer is allocated.
482 *
483 * \return The number of bytes printed into the buffer (not including the
484 * therminating \p NULL byte).
485 *
486 * \sa make_message(), vsnprintf(3).
487 */
488 __printf_2_3 int para_printf(struct para_buffer *b, const char *fmt, ...)
489 {
490 int ret;
491
492 if (!b->buf) {
493 b->buf = para_malloc(128);
494 b->size = 128;
495 b->offset = 0;
496 }
497 while (1) {
498 char *p = b->buf + b->offset;
499 size_t size = b->size - b->offset;
500 va_list ap;
501 if (size) {
502 va_start(ap, fmt);
503 ret = vsnprintf(p, size, fmt, ap);
504 va_end(ap);
505 if (ret > -1 && ret < size) { /* success */
506 b->offset += ret;
507 return ret;
508 }
509 }
510 /* check if we may grow the buffer */
511 if (!b->max_size || 2 * b->size < b->max_size) { /* yes */
512 /* try again with more space */
513 b->size *= 2;
514 b->buf = para_realloc(b->buf, b->size);
515 continue;
516 }
517 /* can't grow buffer */
518 if (!b->offset || !b->max_size_handler) /* message too large */
519 return -ERRNO_TO_PARA_ERROR(ENOSPC);
520 ret = b->max_size_handler(b->buf, b->offset, b->private_data);
521 if (ret < 0)
522 return ret;
523 b->offset = 0;
524 }
525 }
526
527 /** \cond LLONG_MAX and LLONG_LIN might not be defined. */
528 #ifndef LLONG_MAX
529 #define LLONG_MAX (1 << (sizeof(long) - 1))
530 #endif
531 #ifndef LLONG_MIN
532 #define LLONG_MIN (-LLONG_MAX - 1LL)
533 #endif
534 /** \endcond */
535
536 /**
537 * Convert a string to a 64-bit signed integer value.
538 *
539 * \param str The string to be converted.
540 * \param value Result pointer.
541 *
542 * \return Standard.
543 *
544 * \sa para_atoi32(), strtol(3), atoi(3).
545 */
546 int para_atoi64(const char *str, int64_t *value)
547 {
548 char *endptr;
549 long long tmp;
550
551 errno = 0; /* To distinguish success/failure after call */
552 tmp = strtoll(str, &endptr, 10);
553 if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
554 return -E_ATOI_OVERFLOW;
555 if (errno != 0 && tmp == 0) /* other error */
556 return -E_STRTOLL;
557 if (endptr == str)
558 return -E_ATOI_NO_DIGITS;
559 if (*endptr != '\0') /* Further characters after number */
560 return -E_ATOI_JUNK_AT_END;
561 *value = tmp;
562 return 1;
563 }
564
565 /**
566 * Convert a string to a 32-bit signed integer value.
567 *
568 * \param str The string to be converted.
569 * \param value Result pointer.
570 *
571 * \return Standard.
572 *
573 * \sa para_atoi64().
574 */
575 int para_atoi32(const char *str, int32_t *value)
576 {
577 int64_t tmp;
578 int ret;
579 const int32_t max = 2147483647;
580
581 ret = para_atoi64(str, &tmp);
582 if (ret < 0)
583 return ret;
584 if (tmp > max || tmp < -max - 1)
585 return -E_ATOI_OVERFLOW;
586 *value = tmp;
587 return 1;
588 }
589
590 /**
591 * Compute the loglevel number from its name.
592 *
593 * \param txt The name of the loglevel (debug, info, ...).
594 *
595 * \return The numeric representation of the loglevel name.
596 */
597 int get_loglevel_by_name(const char *txt)
598 {
599 if (!strcasecmp(txt, "debug"))
600 return LL_DEBUG;
601 if (!strcasecmp(txt, "info"))
602 return LL_INFO;
603 if (!strcasecmp(txt, "notice"))
604 return LL_NOTICE;
605 if (!strcasecmp(txt, "warning"))
606 return LL_WARNING;
607 if (!strcasecmp(txt, "error"))
608 return LL_ERROR;
609 if (!strcasecmp(txt, "crit"))
610 return LL_CRIT;
611 if (!strcasecmp(txt, "emerg"))
612 return LL_EMERG;
613 return -1;
614 }