6 #include <sys/socket.h>
9 #include <linux/if_tun.h>
17 int open_or_die(const char *file
, int flags
)
19 int ret
= open(file
, flags
);
20 if (unlikely(ret
< 0))
21 panic("Cannot open file %s! %s.\n", file
, strerror(errno
));
25 int open_or_die_m(const char *file
, int flags
, mode_t mode
)
27 int ret
= open(file
, flags
, mode
);
28 if (unlikely(ret
< 0))
29 panic("Cannot open or create file %s! %s.", file
, strerror(errno
));
33 int dup_or_die(int oldfd
)
35 int newfd
= dup(oldfd
);
36 if (unlikely(newfd
< 0))
37 panic("Cannot dup old file descriptor!\n");
41 void dup2_or_die(int oldfd
, int newfd
)
43 int ret
= dup2(oldfd
, newfd
);
44 if (unlikely(ret
< 0))
45 panic("Cannot dup2 old/new file descriptor!\n");
48 void create_or_die(const char *file
, mode_t mode
)
50 int fd
= open_or_die_m(file
, O_WRONLY
| O_CREAT
, mode
);
54 void pipe_or_die(int pipefd
[2], int flags
)
56 int ret
= pipe2(pipefd
, flags
);
57 if (unlikely(ret
< 0))
58 panic("Cannot create pipe2 event fd! %s.\n", strerror(errno
));
61 int tun_open_or_die(const char *name
, int type
)
68 panic("No name provided for tundev!\n");
70 fd
= open_or_die("/dev/net/tun", O_RDWR
);
72 memset(&ifr
, 0, sizeof(ifr
));
74 strlcpy(ifr
.ifr_name
, name
, IFNAMSIZ
);
76 ret
= ioctl(fd
, TUNSETIFF
, &ifr
);
77 if (unlikely(ret
< 0))
78 panic("ioctl screwed up! %s.\n", strerror(errno
));
80 ret
= fcntl(fd
, F_SETFL
, fcntl(fd
, F_GETFL
) | O_NONBLOCK
);
81 if (unlikely(ret
< 0))
82 panic("fctnl screwed up! %s.\n", strerror(errno
));
84 flags
= device_get_flags(name
);
85 flags
|= IFF_UP
| IFF_RUNNING
;
86 device_set_flags(name
, flags
);
91 ssize_t
read_or_die(int fd
, void *buf
, size_t len
)
93 ssize_t ret
= read(fd
, buf
, len
);
94 if (unlikely(ret
< 0)) {
97 panic("Cannot read from descriptor! %s.\n", strerror(errno
));
103 ssize_t
write_or_die(int fd
, const void *buf
, size_t len
)
105 ssize_t ret
= write(fd
, buf
, len
);
106 if (unlikely(ret
< 0)) {
109 panic("Cannot write to descriptor! %s.", strerror(errno
));
115 int read_blob_or_die(const char *file
, void *blob
, size_t count
)
119 fd
= open_or_die(file
, O_RDONLY
);
120 ret
= read_or_die(fd
, blob
, count
);
126 int write_blob_or_die(const char *file
, const void *blob
, size_t count
)
130 fd
= open_or_die_m(file
, O_WRONLY
| O_CREAT
| O_TRUNC
, S_IRUSR
| S_IWUSR
);
131 ret
= write_or_die(fd
, blob
, count
);