mailmap: add mail alias
[transsip-mirror.git] / src / xutils.c
blob482c580ddab4b42102cb058a4cc062b351078833
1 /*
2 * transsip - the telephony toolkit
3 * By Daniel Borkmann <daniel@transsip.org>
4 * Copyright 2011, 2012 Daniel Borkmann <dborkma@tik.ee.ethz.ch>
5 * Subject to the GPL, version 2.
6 */
8 #define _BSD_SOURCE
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <unistd.h>
12 #include <string.h>
13 #include <errno.h>
14 #include <fcntl.h>
15 #include <signal.h>
16 #include <stdarg.h>
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <sys/types.h>
20 #include <sys/ioctl.h>
21 #include <sys/socket.h>
23 #include "xutils.h"
24 #include "xmalloc.h"
25 #include "die.h"
27 int open_or_die(const char *file, int flags)
29 int ret = open(file, flags);
30 if (ret < 0)
31 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");
42 return ret;
45 ssize_t read_or_die(int fd, void *buf, size_t len)
47 ssize_t ret = read(fd, buf, len);
48 if (ret < 0) {
49 if (errno == EPIPE)
50 exit(EXIT_SUCCESS);
51 panic("Read error!!\n");
54 return ret;
57 ssize_t write_or_die(int fd, const void *buf, size_t len)
59 ssize_t ret = write(fd, buf, len);
60 if (ret < 0) {
61 if (errno == EPIPE)
62 exit(EXIT_SUCCESS);
63 panic("Write error!!\n");
66 return ret;
69 size_t strlcpy(char *dest, const char *src, size_t size)
71 size_t ret = strlen(src);
72 if (size) {
73 size_t len = (ret >= size) ? size - 1 : ret;
75 memcpy(dest, src, len);
76 dest[len] = '\0';
79 return ret;
82 int slprintf(char *dst, size_t size, const char *fmt, ...)
84 int ret;
85 va_list ap;
87 va_start(ap, fmt);
88 ret = vsnprintf(dst, size, fmt, ap);
89 dst[size - 1] = '\0';
90 va_end(ap);
92 return ret;
95 char **strntoargv(char *str, size_t len, int *argc)
97 int done = 0;
98 char **argv = NULL;
100 if (argc == NULL)
101 panic("argc is null!\n");
102 *argc = 0;
103 if (len <= 1) /* '\0' */
104 goto out;
105 while (!done) {
106 while (len > 0 && *str == ' ') {
107 len--;
108 str++;
110 if (len > 0 && *str != '\0') {
111 (*argc)++;
112 argv = xrealloc(argv, 1, sizeof(char *) * (*argc));
113 argv[(*argc) - 1] = str;
114 while (len > 0 && *str != ' ') {
115 len--;
116 str++;
118 if (len > 0 && *str == ' ') {
119 len--;
120 *str = '\0';
121 str++;
123 } else {
124 done = 1;
127 out:
128 return argv;