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
);
21 panic("Cannot open file %s! %s.\n", file
, strerror(errno
));
26 int open_or_die_m(const char *file
, int flags
, mode_t mode
)
28 int ret
= open(file
, flags
, mode
);
30 panic("Cannot open or create file %s! %s.", file
, strerror(errno
));
34 int dup_or_die(int oldfd
)
36 int newfd
= dup(oldfd
);
37 if (unlikely(newfd
< 0))
38 panic("Cannot dup old file descriptor!\n");
42 void dup2_or_die(int oldfd
, int newfd
)
44 int ret
= dup2(oldfd
, newfd
);
45 if (unlikely(ret
< 0))
46 panic("Cannot dup2 old/new file descriptor!\n");
49 void create_or_die(const char *file
, mode_t mode
)
51 int fd
= open_or_die_m(file
, O_WRONLY
| O_CREAT
, mode
);
55 void pipe_or_die(int pipefd
[2], int flags
)
57 int ret
= pipe2(pipefd
, flags
);
59 panic("Cannot create pipe2 event fd! %s.\n", strerror(errno
));
62 int tun_open_or_die(char *name
, int type
)
69 panic("No name provided for tundev!\n");
71 fd
= open_or_die("/dev/net/tun", O_RDWR
);
73 memset(&ifr
, 0, sizeof(ifr
));
75 strlcpy(ifr
.ifr_name
, name
, IFNAMSIZ
);
77 ret
= ioctl(fd
, TUNSETIFF
, &ifr
);
79 panic("ioctl screwed up! %s.\n", strerror(errno
));
81 ret
= fcntl(fd
, F_SETFL
, fcntl(fd
, F_GETFL
) | O_NONBLOCK
);
83 panic("fctnl screwed up! %s.\n", strerror(errno
));
85 flags
= device_get_flags(name
);
86 flags
|= IFF_UP
| IFF_RUNNING
;
87 device_set_flags(name
, flags
);
92 ssize_t
read_or_die(int fd
, void *buf
, size_t len
)
94 ssize_t ret
= read(fd
, buf
, len
);
98 panic("Cannot read from descriptor! %s.\n", strerror(errno
));
104 ssize_t
write_or_die(int fd
, const void *buf
, size_t len
)
106 ssize_t ret
= write(fd
, buf
, len
);
110 panic("Cannot write to descriptor! %s.", strerror(errno
));
116 int read_blob_or_die(const char *file
, void *blob
, size_t count
)
120 fd
= open_or_die(file
, O_RDONLY
);
121 ret
= read_or_die(fd
, blob
, count
);
127 int write_blob_or_die(const char *file
, const void *blob
, size_t count
)
131 fd
= open_or_die_m(file
, O_WRONLY
| O_CREAT
| O_TRUNC
, S_IRUSR
| S_IWUSR
);
132 ret
= write_or_die(fd
, blob
, count
);