engine: echo canceller update
[transsip.git] / src / xutils.c
blobc0873d5f3babb43f17c7ff64192a26a09bdfdf33
1 /*
2 * transsip - the telephony network
3 * By Daniel Borkmann <daniel@transsip.org>
4 * Copyright 2011, 2012 Daniel Borkmann <dborkma@tik.ee.ethz.ch>,
5 * Swiss federal institute of technology (ETH Zurich)
6 * Subject to the GPL, version 2.
7 */
9 #define _BSD_SOURCE
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include <string.h>
14 #include <errno.h>
15 #include <fcntl.h>
16 #include <signal.h>
17 #include <stdarg.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <sys/types.h>
21 #include <sys/ioctl.h>
22 #include <sys/socket.h>
24 #include "xutils.h"
25 #include "xmalloc.h"
26 #include "die.h"
28 int open_or_die(const char *file, int flags)
30 int ret = open(file, flags);
31 if (ret < 0)
32 panic("Open error!!\n");
33 return ret;
36 int open_or_die_m(const char *file, int flags, mode_t mode)
38 int ret = open(file, flags, mode);
39 if (ret < 0)
40 panic("Open error!!\n");
41 return ret;
44 ssize_t read_or_die(int fd, void *buf, size_t len)
46 ssize_t ret = read(fd, buf, len);
47 if (ret < 0) {
48 if (errno == EPIPE)
49 exit(EXIT_SUCCESS);
50 panic("Read error!!\n");
53 return ret;
56 ssize_t write_or_die(int fd, const void *buf, size_t len)
58 ssize_t ret = write(fd, buf, len);
59 if (ret < 0) {
60 if (errno == EPIPE)
61 exit(EXIT_SUCCESS);
62 panic("Write error!!\n");
65 return ret;
68 size_t strlcpy(char *dest, const char *src, size_t size)
70 size_t ret = strlen(src);
71 if (size) {
72 size_t len = (ret >= size) ? size - 1 : ret;
73 memcpy(dest, src, len);
74 dest[len] = '\0';
76 return ret;
79 int slprintf(char *dst, size_t size, const char *fmt, ...)
81 int ret;
82 va_list ap;
83 va_start(ap, fmt);
84 ret = vsnprintf(dst, size, fmt, ap);
85 dst[size - 1] = '\0';
86 va_end(ap);
87 return ret;
90 char **strntoargv(char *str, size_t len, int *argc)
92 int done = 0;
93 char **argv = NULL;
95 if (argc == NULL)
96 panic("argc is null!\n");
97 *argc = 0;
98 if (len <= 1) /* '\0' */
99 goto out;
100 while (!done) {
101 while (len > 0 && *str == ' ') {
102 len--;
103 str++;
105 if (len > 0 && *str != '\0') {
106 (*argc)++;
107 argv = xrealloc(argv, 1, sizeof(char *) * (*argc));
108 argv[(*argc) - 1] = str;
109 while (len > 0 && *str != ' ') {
110 len--;
111 str++;
113 if (len > 0 && *str == ' ') {
114 len--;
115 *str = '\0';
116 str++;
118 } else {
119 done = 1;
122 out:
123 return argv;