gui: Use variable-sized input buffer for the audiod pipe.
[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 char *para_basename(const char *name)
204 {
205 char *ret;
206
207 if (!name || !*name)
208 return NULL;
209 ret = strrchr(name, '/');
210 if (!ret)
211 return (char *)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 the logname of the current user.
236 *
237 * \return A dynamically allocated string that must be freed by the caller. On
238 * errors, the string "unknown_user" is returned, i.e. this function never
239 * returns \p NULL.
240 *
241 * \sa getpwuid(3).
242 */
243 __must_check __malloc char *para_logname(void)
244 {
245 struct passwd *pw = getpwuid(getuid());
246 return para_strdup(pw? pw->pw_name : "unknown_user");
247 }
248
249 /**
250 * Get the home directory of the current user.
251 *
252 * \return A dynamically allocated string that must be freed by the caller. If
253 * the home directory could not be found, this function returns "/tmp".
254 */
255 __must_check __malloc char *para_homedir(void)
256 {
257 struct passwd *pw = getpwuid(getuid());
258 return para_strdup(pw? pw->pw_dir : "/tmp");
259 }
260
261 /**
262 * Split string and return pointers to its parts.
263 *
264 * \param args The string to be split.
265 * \param argv_ptr Pointer to the list of substrings.
266 * \param delim Delimiter.
267 *
268 * This function modifies \a args by replacing each occurrence of \a delim by
269 * zero. A \p NULL-terminated array of pointers to char* is allocated dynamically
270 * and these pointers are initialized to point to the broken-up substrings
271 * within \a args. A pointer to this array is returned via \a argv_ptr.
272 *
273 * \return The number of substrings found in \a args.
274 */
275 unsigned split_args(char *args, char *** const argv_ptr, const char *delim)
276 {
277 char *p;
278 char **argv;
279 size_t n = 0, i, j;
280
281 p = args + strspn(args, delim);
282 for (;;) {
283 i = strcspn(p, delim);
284 if (!i)
285 break;
286 p += i;
287 n++;
288 p += strspn(p, delim);
289 }
290 *argv_ptr = para_malloc((n + 1) * sizeof(char *));
291 argv = *argv_ptr;
292 i = 0;
293 p = args + strspn(args, delim);
294 while (p) {
295 argv[i] = p;
296 j = strcspn(p, delim);
297 if (!j)
298 break;
299 p += strcspn(p, delim);
300 if (*p) {
301 *p = '\0';
302 p++;
303 p += strspn(p, delim);
304 }
305 i++;
306 }
307 argv[n] = NULL;
308 return n;
309 }
310
311 /**
312 * Get the own hostname.
313 *
314 * \return A dynamically allocated string containing the hostname.
315 *
316 * \sa uname(2).
317 */
318 __malloc char *para_hostname(void)
319 {
320 struct utsname u;
321
322 uname(&u);
323 return para_strdup(u.nodename);
324 }
325
326 /**
327 * Used to distinguish between read-only and read-write mode.
328 *
329 * \sa for_each_line(), for_each_line_ro().
330 */
331 enum for_each_line_modes{
332 /** Activate read-only mode. */
333 LINE_MODE_RO,
334 /** Activate read-write mode. */
335 LINE_MODE_RW
336 };
337
338 static int for_each_complete_line(enum for_each_line_modes mode, char *buf,
339 size_t size, line_handler_t *line_handler, void *private_data)
340 {
341 char *start = buf, *end;
342 int ret, i, num_lines = 0;
343
344 // PARA_NOTICE_LOG("buf: %s\n", buf);
345 while (start < buf + size) {
346 char *next_null;
347 char *next_cr;
348
349 next_cr = memchr(start, '\n', buf + size - start);
350 next_null = memchr(start, '\0', buf + size - start);
351 if (!next_cr && !next_null)
352 break;
353 if (next_cr && next_null) {
354 end = next_cr < next_null? next_cr : next_null;
355 } else if (next_null) {
356 end = next_null;
357 } else
358 end = next_cr;
359 num_lines++;
360 if (!line_handler) {
361 start = ++end;
362 continue;
363 }
364 if (mode == LINE_MODE_RO) {
365 size_t s = end - start;
366 char *b = para_malloc(s + 1);
367 memcpy(b, start, s);
368 b[s] = '\0';
369 // PARA_NOTICE_LOG("b: %s, start: %s\n", b, start);
370 ret = line_handler(b, private_data);
371 free(b);
372 } else {
373 *end = '\0';
374 ret = line_handler(start, private_data);
375 }
376 if (ret < 0)
377 return ret;
378 start = ++end;
379 }
380 if (!line_handler || mode == LINE_MODE_RO)
381 return num_lines;
382 i = buf + size - start;
383 if (i && i != size)
384 memmove(buf, start, i);
385 return i;
386 }
387
388 /**
389 * Call a custom function for each complete line.
390 *
391 * \param buf The buffer containing data separated by newlines.
392 * \param size The number of bytes in \a buf.
393 * \param line_handler The custom function.
394 * \param private_data Pointer passed to \a line_handler.
395 *
396 * If \p line_handler is \p NULL, the function returns the number of complete
397 * lines in \p buf. Otherwise, \p line_handler is called for each complete
398 * line in \p buf. The first argument to \p line_handler is the current line,
399 * and \p private_data is passed as the second argument. The function returns
400 * if \p line_handler returns a negative value or no more lines are in the
401 * buffer. The rest of the buffer (last chunk containing an incomplete line)
402 * is moved to the beginning of the buffer.
403 *
404 * \return If \p line_handler is not \p NULL, this function returns the number
405 * of bytes not handled to \p line_handler on success, or the negative return
406 * value of the \p line_handler on errors.
407 *
408 * \sa for_each_line_ro().
409 */
410 int for_each_line(char *buf, size_t size, line_handler_t *line_handler,
411 void *private_data)
412 {
413 return for_each_complete_line(LINE_MODE_RW, buf, size, line_handler,
414 private_data);
415 }
416
417 /**
418 * Call a custom function for each complete line.
419 *
420 * \param buf Same meaning as in \p for_each_line().
421 * \param size Same meaning as in \p for_each_line().
422 * \param line_handler Same meaning as in \p for_each_line().
423 * \param private_data Same meaning as in \p for_each_line().
424 *
425 * This function behaves like \p for_each_line(), but \a buf is left unchanged.
426 *
427 * \return On success, the function returns the number of complete lines in \p
428 * buf, otherwise the (negative) return value of \p line_handler is returned.
429 *
430 * \sa for_each_line().
431 */
432 int for_each_line_ro(char *buf, size_t size, line_handler_t *line_handler,
433 void *private_data)
434 {
435 return for_each_complete_line(LINE_MODE_RO, buf, size, line_handler,
436 private_data);
437 }
438
439 #define hex(a) (hexchar[(a) & 15])
440 static void write_size_header(char *buf, int n)
441 {
442 static char hexchar[] = "0123456789abcdef";
443
444 buf[0] = hex(n >> 12);
445 buf[1] = hex(n >> 8);
446 buf[2] = hex(n >> 4);
447 buf[3] = hex(n);
448 buf[4] = ' ';
449 }
450
451 int read_size_header(const char *buf)
452 {
453 int i, len = 0;
454
455 for (i = 0; i < 4; i++) {
456 unsigned char c = buf[i];
457 len <<= 4;
458 if (c >= '0' && c <= '9') {
459 len += c - '0';
460 continue;
461 }
462 if (c >= 'a' && c <= 'f') {
463 len += c - 'a' + 10;
464 continue;
465 }
466 return -E_SIZE_PREFIX;
467 }
468 if (buf[4] != ' ')
469 return -E_SIZE_PREFIX;
470 return len;
471 }
472
473 /**
474 * Safely print into a buffer at a given offset.
475 *
476 * \param b Determines the buffer, its size, and the offset.
477 * \param fmt The format string.
478 *
479 * This function prints into the buffer given by \a b at the offset which is
480 * also given by \a b. If there is not enough space to hold the result, the
481 * buffer size is doubled until the underlying call to vsnprintf() succeeds
482 * or the size of the buffer exceeds the maximal size specified in \a b.
483 *
484 * In the latter case the unmodified \a buf and \a offset values as well as the
485 * private_data pointer of \a b are passed to the \a max_size_handler of \a b.
486 * If this function succeeds, i.e. returns a non-negative value, the offset of
487 * \a b is reset to zero and the given data is written to the beginning of the
488 * buffer. If \a max_size_handler() returns a negative value, this value is
489 * returned by \a para_printf().
490 *
491 * Upon return, the offset of \a b is adjusted accordingly so that subsequent
492 * calls to this function append data to what is already contained in the
493 * buffer.
494 *
495 * It's OK to call this function with \p b->buf being \p NULL. In this case, an
496 * initial buffer is allocated.
497 *
498 * \return The number of bytes printed into the buffer (not including the
499 * terminating \p NULL byte) on success, negative on errors. If there is no
500 * size-bound on \a b, i.e. if \p b->max_size is zero, this function never
501 * fails.
502 *
503 * \sa make_message(), vsnprintf(3).
504 */
505 __printf_2_3 int para_printf(struct para_buffer *b, const char *fmt, ...)
506 {
507 int ret, sz_off = (b->flags & PBF_SIZE_PREFIX)? 5 : 0;
508
509 if (!b->buf) {
510 b->buf = para_malloc(128);
511 b->size = 128;
512 b->offset = 0;
513 }
514 while (1) {
515 char *p = b->buf + b->offset;
516 size_t size = b->size - b->offset;
517 va_list ap;
518
519 if (size > sz_off) {
520 va_start(ap, fmt);
521 ret = vsnprintf(p + sz_off, size - sz_off, fmt, ap);
522 va_end(ap);
523 if (ret > -1 && ret < size - sz_off) { /* success */
524 b->offset += ret + sz_off;
525 if (sz_off)
526 write_size_header(p, ret);
527 return ret + sz_off;
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_PARA_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 }
609
610 static inline int loglevel_equal(const char *arg, const char * const ll)
611 {
612 return !strncasecmp(arg, ll, strlen(ll));
613 }
614
615 /**
616 * Compute the loglevel number from its name.
617 *
618 * \param txt The name of the loglevel (debug, info, ...).
619 *
620 * \return The numeric representation of the loglevel name.
621 */
622 int get_loglevel_by_name(const char *txt)
623 {
624 if (loglevel_equal(txt, "debug"))
625 return LL_DEBUG;
626 if (loglevel_equal(txt, "info"))
627 return LL_INFO;
628 if (loglevel_equal(txt, "notice"))
629 return LL_NOTICE;
630 if (loglevel_equal(txt, "warning"))
631 return LL_WARNING;
632 if (loglevel_equal(txt, "error"))
633 return LL_ERROR;
634 if (loglevel_equal(txt, "crit"))
635 return LL_CRIT;
636 if (loglevel_equal(txt, "emerg"))
637 return LL_EMERG;
638 return -1;
639 }