string: constant value
[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 \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 /**
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 equal to
222 * the newline character.
223 */
224 void chop(char *buf)
225 {
226 int n = strlen(buf);
227
228 if (!n)
229 return;
230 if (buf[n - 1] == '\n')
231 buf[n - 1] = '\0';
232 }
233
234 /**
235 * Get a random filename.
236 *
237 * This is by no means a secure way to create temporary files in a hostile
238 * directory like \p /tmp. However, it is OK to use for temp files, fifos,
239 * sockets that are created in ~/.paraslash. Result must be freed by the
240 * caller.
241 *
242 * \return A pointer to a random filename.
243 */
244 __must_check __malloc char *para_tmpname(void)
245 {
246 struct timeval now;
247 unsigned int seed;
248
249 gettimeofday(&now, NULL);
250 seed = now.tv_usec;
251 srand(seed);
252 return make_message("%08i", rand());
253 }
254
255 /**
256 * Get the logname of the current user.
257 *
258 * \return A dynamically allocated string that must be freed by the caller. On
259 * errors, the string "unknown_user" is returned, i.e. this function never
260 * returns \p NULL.
261 *
262 * \sa getpwuid(3).
263 */
264 __must_check __malloc char *para_logname(void)
265 {
266 struct passwd *pw = getpwuid(getuid());
267 return para_strdup(pw? pw->pw_name : "unknown_user");
268 }
269
270 /**
271 * Get the home directory of the current user.
272 *
273 * \return A dynamically allocated string that must be freed by the caller. If
274 * the home directory could not be found, this function returns "/tmp".
275 */
276 __must_check __malloc char *para_homedir(void)
277 {
278 struct passwd *pw = getpwuid(getuid());
279 return para_strdup(pw? pw->pw_dir : "/tmp");
280 }
281
282 /**
283 * Split string and return pointers to its parts.
284 *
285 * \param args The string to be split.
286 * \param argv_ptr Pointer to the list of substrings.
287 * \param delim Delimiter.
288 *
289 * This function modifies \a args by replacing each occurrence of \a delim by
290 * zero. A \p NULL-terminated array of pointers to char* is allocated dynamically
291 * and these pointers are initialized to point to the broken-up substrings
292 * within \a args. A pointer to this array is returned via \a argv_ptr.
293 *
294 * \return The number of substrings found in \a args.
295 */
296 unsigned split_args(char *args, char *** const argv_ptr, const char *delim)
297 {
298 char *p;
299 char **argv;
300 size_t n = 0, i, j;
301
302 p = args + strspn(args, delim);
303 for (;;) {
304 i = strcspn(p, delim);
305 if (!i)
306 break;
307 p += i;
308 n++;
309 p += strspn(p, delim);
310 }
311 *argv_ptr = para_malloc((n + 1) * sizeof(char *));
312 argv = *argv_ptr;
313 i = 0;
314 p = args + strspn(args, delim);
315 while (p) {
316 argv[i] = p;
317 j = strcspn(p, delim);
318 if (!j)
319 break;
320 p += strcspn(p, delim);
321 if (*p) {
322 *p = '\0';
323 p++;
324 p += strspn(p, delim);
325 }
326 i++;
327 }
328 argv[n] = NULL;
329 return n;
330 }
331
332 /**
333 * Get the own hostname.
334 *
335 * \return A dynamically allocated string containing the hostname.
336 *
337 * \sa uname(2).
338 */
339 __malloc char *para_hostname(void)
340 {
341 struct utsname u;
342
343 uname(&u);
344 return para_strdup(u.nodename);
345 }
346
347 /**
348 * Used to distinguish between read-only and read-write mode.
349 *
350 * \sa for_each_line(), for_each_line_ro().
351 */
352 enum for_each_line_modes{
353 /** Activate read-only mode. */
354 LINE_MODE_RO,
355 /** Activate read-write mode. */
356 LINE_MODE_RW
357 };
358
359 static int for_each_complete_line(enum for_each_line_modes mode, char *buf,
360 size_t size, line_handler_t *line_handler, void *private_data)
361 {
362 char *start = buf, *end;
363 int ret, i, num_lines = 0;
364
365 // PARA_NOTICE_LOG("buf: %s\n", buf);
366 while (start < buf + size) {
367 char *next_null;
368 char *next_cr;
369
370 next_cr = memchr(start, '\n', buf + size - start);
371 next_null = memchr(start, '\0', buf + size - start);
372 if (!next_cr && !next_null)
373 break;
374 if (next_cr && next_null) {
375 end = next_cr < next_null? next_cr : next_null;
376 } else if (next_null) {
377 end = next_null;
378 } else
379 end = next_cr;
380 num_lines++;
381 if (!line_handler) {
382 start = ++end;
383 continue;
384 }
385 if (mode == LINE_MODE_RO) {
386 size_t s = end - start;
387 char *b = para_malloc(s + 1);
388 memcpy(b, start, s);
389 b[s] = '\0';
390 // PARA_NOTICE_LOG("b: %s, start: %s\n", b, start);
391 ret = line_handler(b, private_data);
392 free(b);
393 } else {
394 *end = '\0';
395 ret = line_handler(start, private_data);
396 }
397 if (ret < 0)
398 return ret;
399 start = ++end;
400 }
401 if (!line_handler || mode == LINE_MODE_RO)
402 return num_lines;
403 i = buf + size - start;
404 if (i && i != size)
405 memmove(buf, start, i);
406 return i;
407 }
408
409 /**
410 * Call a custom function for each complete line.
411 *
412 * \param buf The buffer containing data separated by newlines.
413 * \param size The number of bytes in \a buf.
414 * \param line_handler The custom function.
415 * \param private_data Pointer passed to \a line_handler.
416 *
417 * If \p line_handler is \p NULL, the function returns the number of complete
418 * lines in \p buf. Otherwise, \p line_handler is called for each complete
419 * line in \p buf. The first argument to \p line_handler is the current line,
420 * and \p private_data is passed as the second argument. The function returns
421 * if \p line_handler returns a negative value or no more lines are in the
422 * buffer. The rest of the buffer (last chunk containing an incomplete line)
423 * is moved to the beginning of the buffer.
424 *
425 * \return If \p line_handler is not \p NULL, this function returns the number
426 * of bytes not handled to \p line_handler on success, or the negative return
427 * value of the \p line_handler on errors.
428 *
429 * \sa for_each_line_ro().
430 */
431 int for_each_line(char *buf, size_t size, line_handler_t *line_handler,
432 void *private_data)
433 {
434 return for_each_complete_line(LINE_MODE_RW, buf, size, line_handler,
435 private_data);
436 }
437
438 /**
439 * Call a custom function for each complete line.
440 *
441 * \param buf Same meaning as in \p for_each_line().
442 * \param size Same meaning as in \p for_each_line().
443 * \param line_handler Same meaning as in \p for_each_line().
444 * \param private_data Same meaning as in \p for_each_line().
445 *
446 * This function behaves like \p for_each_line(), but \a buf is left unchanged.
447 *
448 * \return On success, the function returns the number of complete lines in \p
449 * buf, otherwise the (negative) return value of \p line_handler is returned.
450 *
451 * \sa for_each_line().
452 */
453 int for_each_line_ro(char *buf, size_t size, line_handler_t *line_handler,
454 void *private_data)
455 {
456 return for_each_complete_line(LINE_MODE_RO, buf, size, line_handler,
457 private_data);
458 }
459
460 /**
461 * Safely print into a buffer at a given offset.
462 *
463 * \param b Determines the buffer, its size, and the offset.
464 * \param fmt The format string.
465 *
466 * This function prints into the buffer given by \a b at the offset which is
467 * also given by \a b. If there is not enough space to hold the result, the
468 * buffer size is doubled until the underlying call to vsnprintf() succeeds
469 * or the size of the buffer exceeds the maximal size specified in \a b.
470 *
471 * In the latter case the unmodified \a buf and \a offset values as well as the
472 * private_data pointer of \a b are passed to the \a max_size_handler of \a b.
473 * If this function succeeds, i.e. returns a non-negative value, the offset of
474 * \a b is reset to zero and the given data is written to the beginning of the
475 * buffer.
476 *
477 * Upon return, the offset of \a b is adjusted accordingly so that subsequent
478 * calls to this function append data to what is already contained in the
479 * buffer.
480 *
481 * It's OK to call this function with \p b->buf being \p NULL. In this case, an
482 * initial buffer is allocated.
483 *
484 * \return The number of bytes printed into the buffer (not including the
485 * terminating \p NULL byte).
486 *
487 * \sa make_message(), vsnprintf(3).
488 */
489 __printf_2_3 int para_printf(struct para_buffer *b, const char *fmt, ...)
490 {
491 int ret;
492
493 if (!b->buf) {
494 b->buf = para_malloc(128);
495 b->size = 128;
496 b->offset = 0;
497 }
498 while (1) {
499 char *p = b->buf + b->offset;
500 size_t size = b->size - b->offset;
501 va_list ap;
502 if (size) {
503 va_start(ap, fmt);
504 ret = vsnprintf(p, size, fmt, ap);
505 va_end(ap);
506 if (ret > -1 && ret < size) { /* success */
507 b->offset += ret;
508 return ret;
509 }
510 }
511 /* check if we may grow the buffer */
512 if (!b->max_size || 2 * b->size < b->max_size) { /* yes */
513 /* try again with more space */
514 b->size *= 2;
515 b->buf = para_realloc(b->buf, b->size);
516 continue;
517 }
518 /* can't grow buffer */
519 if (!b->offset || !b->max_size_handler) /* message too large */
520 return -ERRNO_TO_PARA_ERROR(ENOSPC);
521 ret = b->max_size_handler(b->buf, b->offset, b->private_data);
522 if (ret < 0)
523 return ret;
524 b->offset = 0;
525 }
526 }
527
528 /** \cond LLONG_MAX and LLONG_MIN might not be defined. */
529 #ifndef LLONG_MAX
530 #define LLONG_MAX 9223372036854775807LL
531 #endif
532 #ifndef LLONG_MIN
533 #define LLONG_MIN (-LLONG_MAX - 1LL)
534 #endif
535 /** \endcond */
536
537 /**
538 * Convert a string to a 64-bit signed integer value.
539 *
540 * \param str The string to be converted.
541 * \param value Result pointer.
542 *
543 * \return Standard.
544 *
545 * \sa para_atoi32(), strtol(3), atoi(3).
546 */
547 int para_atoi64(const char *str, int64_t *value)
548 {
549 char *endptr;
550 long long tmp;
551
552 errno = 0; /* To distinguish success/failure after call */
553 tmp = strtoll(str, &endptr, 10);
554 if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
555 return -E_ATOI_OVERFLOW;
556 if (errno != 0 && tmp == 0) /* other error */
557 return -E_STRTOLL;
558 if (endptr == str)
559 return -E_ATOI_NO_DIGITS;
560 if (*endptr != '\0') /* Further characters after number */
561 return -E_ATOI_JUNK_AT_END;
562 *value = tmp;
563 return 1;
564 }
565
566 /**
567 * Convert a string to a 32-bit signed integer value.
568 *
569 * \param str The string to be converted.
570 * \param value Result pointer.
571 *
572 * \return Standard.
573 *
574 * \sa para_atoi64().
575 */
576 int para_atoi32(const char *str, int32_t *value)
577 {
578 int64_t tmp;
579 int ret;
580 const int32_t max = 2147483647;
581
582 ret = para_atoi64(str, &tmp);
583 if (ret < 0)
584 return ret;
585 if (tmp > max || tmp < -max - 1)
586 return -E_ATOI_OVERFLOW;
587 *value = tmp;
588 return 1;
589 }
590
591 static inline int loglevel_equal(const char *arg, const char * const ll)
592 {
593 return !strncasecmp(arg, ll, strlen(ll));
594 }
595
596 /**
597 * Compute the loglevel number from its name.
598 *
599 * \param txt The name of the loglevel (debug, info, ...).
600 *
601 * \return The numeric representation of the loglevel name.
602 */
603 int get_loglevel_by_name(const char *txt)
604 {
605 if (loglevel_equal(txt, "debug"))
606 return LL_DEBUG;
607 if (loglevel_equal(txt, "info"))
608 return LL_INFO;
609 if (loglevel_equal(txt, "notice"))
610 return LL_NOTICE;
611 if (loglevel_equal(txt, "warning"))
612 return LL_WARNING;
613 if (loglevel_equal(txt, "error"))
614 return LL_ERROR;
615 if (loglevel_equal(txt, "crit"))
616 return LL_CRIT;
617 if (loglevel_equal(txt, "emerg"))
618 return LL_EMERG;
619 return -1;
620 }