8 #include <sys/socket.h>
11 #include <linux/if_tun.h>
19 int open_or_die(const char *file
, int flags
)
21 int ret
= open(file
, flags
);
22 if (unlikely(ret
< 0))
23 panic("Cannot open file %s! %s.\n", file
, strerror(errno
));
27 int open_or_die_m(const char *file
, int flags
, mode_t mode
)
29 int ret
= open(file
, flags
, mode
);
30 if (unlikely(ret
< 0))
31 panic("Cannot open or create file %s! %s.", file
, strerror(errno
));
35 int dup_or_die(int oldfd
)
37 int newfd
= dup(oldfd
);
38 if (unlikely(newfd
< 0))
39 panic("Cannot dup old file descriptor!\n");
43 void dup2_or_die(int oldfd
, int newfd
)
45 int ret
= dup2(oldfd
, newfd
);
46 if (unlikely(ret
< 0))
47 panic("Cannot dup2 old/new file descriptor!\n");
50 void create_or_die(const char *file
, mode_t mode
)
52 int fd
= open_or_die_m(file
, O_WRONLY
| O_CREAT
, mode
);
56 void pipe_or_die(int pipefd
[2], int flags
)
58 int ret
= pipe2(pipefd
, flags
);
59 if (unlikely(ret
< 0))
60 panic("Cannot create pipe2 event fd! %s.\n", strerror(errno
));
63 int tun_open_or_die(const char *name
, int type
)
70 panic("No name provided for tundev!\n");
72 fd
= open_or_die("/dev/net/tun", O_RDWR
);
74 memset(&ifr
, 0, sizeof(ifr
));
76 strlcpy(ifr
.ifr_name
, name
, IFNAMSIZ
);
78 ret
= ioctl(fd
, TUNSETIFF
, &ifr
);
79 if (unlikely(ret
< 0))
80 panic("ioctl screwed up! %s.\n", strerror(errno
));
82 ret
= fcntl(fd
, F_SETFL
, fcntl(fd
, F_GETFL
) | O_NONBLOCK
);
83 if (unlikely(ret
< 0))
84 panic("fctnl screwed up! %s.\n", strerror(errno
));
86 flags
= device_get_flags(name
);
87 flags
|= IFF_UP
| IFF_RUNNING
;
88 device_set_flags(name
, flags
);
93 ssize_t
read_or_die(int fd
, void *buf
, size_t len
)
95 ssize_t ret
= read(fd
, buf
, len
);
96 if (unlikely(ret
< 0)) {
99 panic("Cannot read from descriptor! %s.\n", strerror(errno
));
105 ssize_t
write_or_die(int fd
, const void *buf
, size_t len
)
107 ssize_t ret
= write(fd
, buf
, len
);
108 if (unlikely(ret
< 0)) {
111 panic("Cannot write to descriptor! %s.", strerror(errno
));
117 int read_blob_or_die(const char *file
, void *blob
, size_t count
)
121 fd
= open_or_die(file
, O_RDONLY
);
122 ret
= read_or_die(fd
, blob
, count
);
128 int write_blob_or_die(const char *file
, const void *blob
, size_t count
)
132 fd
= open_or_die_m(file
, O_WRONLY
| O_CREAT
| O_TRUNC
, S_IRUSR
| S_IWUSR
);
133 ret
= write_or_die(fd
, blob
, count
);