9 #include <sys/socket.h>
12 #include <linux/if_tun.h>
20 int open_or_die(const char *file
, int flags
)
22 int ret
= open(file
, flags
);
23 if (unlikely(ret
< 0))
24 panic("Cannot open file %s! %s.\n", file
, strerror(errno
));
28 int open_or_die_m(const char *file
, int flags
, mode_t mode
)
30 int ret
= open(file
, flags
, mode
);
31 if (unlikely(ret
< 0))
32 panic("Cannot open or create file %s! %s.", file
, strerror(errno
));
36 int dup_or_die(int oldfd
)
38 int newfd
= dup(oldfd
);
39 if (unlikely(newfd
< 0))
40 panic("Cannot dup old file descriptor!\n");
44 void dup2_or_die(int oldfd
, int newfd
)
46 int ret
= dup2(oldfd
, newfd
);
47 if (unlikely(ret
< 0))
48 panic("Cannot dup2 old/new file descriptor!\n");
51 void create_or_die(const char *file
, mode_t mode
)
53 int fd
= open_or_die_m(file
, O_WRONLY
| O_CREAT
, mode
);
57 int mkostemp_or_die(char *templ
, int flags
)
59 /* mode is 0600 (S_IRUSR | S_IWUSR) by default */
60 int fd
= mkostemp(templ
, flags
);
62 panic("Cannot create unique temporary file! %s\n", strerror(errno
));
66 void pipe_or_die(int pipefd
[2], int flags
)
68 int ret
= pipe2(pipefd
, flags
);
69 if (unlikely(ret
< 0))
70 panic("Cannot create pipe2 event fd! %s.\n", strerror(errno
));
73 int tun_open_or_die(const char *name
, int type
)
80 panic("No name provided for tundev!\n");
82 fd
= open_or_die("/dev/net/tun", O_RDWR
);
84 memset(&ifr
, 0, sizeof(ifr
));
86 strlcpy(ifr
.ifr_name
, name
, IFNAMSIZ
);
88 ret
= ioctl(fd
, TUNSETIFF
, &ifr
);
89 if (unlikely(ret
< 0))
90 panic("ioctl screwed up! %s.\n", strerror(errno
));
92 ret
= fcntl(fd
, F_SETFL
, fcntl(fd
, F_GETFL
) | O_NONBLOCK
);
93 if (unlikely(ret
< 0))
94 panic("fctnl screwed up! %s.\n", strerror(errno
));
96 flags
= device_get_flags(name
);
97 flags
|= IFF_UP
| IFF_RUNNING
;
98 device_set_flags(name
, flags
);
103 ssize_t
read_or_die(int fd
, void *buf
, size_t len
)
105 ssize_t ret
= read(fd
, buf
, len
);
106 if (unlikely(ret
< 0)) {
109 panic("Cannot read from descriptor! %s.\n", strerror(errno
));
115 ssize_t
write_or_die(int fd
, const void *buf
, size_t len
)
117 ssize_t ret
= write(fd
, buf
, len
);
118 if (unlikely(ret
< 0)) {
121 panic("Cannot write to descriptor! %s.", strerror(errno
));
127 int read_blob_or_die(const char *file
, void *blob
, size_t count
)
131 fd
= open_or_die(file
, O_RDONLY
);
132 ret
= read_or_die(fd
, blob
, count
);
138 int write_blob_or_die(const char *file
, const void *blob
, size_t count
)
142 fd
= open_or_die_m(file
, O_WRONLY
| O_CREAT
| O_TRUNC
, S_IRUSR
| S_IWUSR
);
143 ret
= write_or_die(fd
, blob
, count
);