BTap.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. /**
  2. * @file BTap.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. */
  22. #include <string.h>
  23. #include <stdio.h>
  24. #ifdef BADVPN_USE_WINAPI
  25. #include <windows.h>
  26. #include <winioctl.h>
  27. #include <objbase.h>
  28. #include <wtypes.h>
  29. #include "wintap-common.h"
  30. #include <tuntap/tapwin32-funcs.h>
  31. #else
  32. #include <fcntl.h>
  33. #include <unistd.h>
  34. #include <errno.h>
  35. #include <sys/ioctl.h>
  36. #include <sys/types.h>
  37. #include <sys/stat.h>
  38. #include <sys/socket.h>
  39. #include <net/if.h>
  40. #include <net/if_arp.h>
  41. #ifdef BADVPN_LINUX
  42. #include <linux/if_tun.h>
  43. #endif
  44. #ifdef BADVPN_FREEBSD
  45. #include <net/if_tun.h>
  46. #include <net/if_tap.h>
  47. #endif
  48. #endif
  49. #include <base/BLog.h>
  50. #include <tuntap/BTap.h>
  51. #include <generated/blog_channel_BTap.h>
  52. static void report_error (BTap *o);
  53. static void output_handler_recv (BTap *o, uint8_t *data);
  54. #ifdef BADVPN_USE_WINAPI
  55. static void recv_olap_handler (BTap *o, int event, DWORD bytes)
  56. {
  57. DebugObject_Access(&o->d_obj);
  58. ASSERT(o->output_packet)
  59. ASSERT(event == BREACTOR_IOCP_EVENT_SUCCEEDED || event == BREACTOR_IOCP_EVENT_FAILED)
  60. // set no output packet
  61. o->output_packet = NULL;
  62. if (event == BREACTOR_IOCP_EVENT_FAILED) {
  63. BLog(BLOG_ERROR, "read operation failed");
  64. report_error(o);
  65. return;
  66. }
  67. ASSERT(bytes >= 0)
  68. ASSERT(bytes <= o->frame_mtu)
  69. // done
  70. PacketRecvInterface_Done(&o->output, bytes);
  71. }
  72. #else
  73. static void fd_handler (BTap *o, int events)
  74. {
  75. DebugObject_Access(&o->d_obj);
  76. DebugError_AssertNoError(&o->d_err);
  77. if (events&BREACTOR_ERROR) {
  78. BLog(BLOG_WARNING, "device fd reports error?");
  79. }
  80. if (events&BREACTOR_READ) do {
  81. ASSERT(o->output_packet)
  82. // try reading into the buffer
  83. int bytes = read(o->fd, o->output_packet, o->frame_mtu);
  84. if (bytes < 0) {
  85. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  86. // retry later
  87. break;
  88. }
  89. // report fatal error
  90. report_error(o);
  91. return;
  92. }
  93. ASSERT_FORCE(bytes <= o->frame_mtu)
  94. // set no output packet
  95. o->output_packet = NULL;
  96. // update events
  97. o->poll_events &= ~BREACTOR_READ;
  98. BReactor_SetFileDescriptorEvents(o->reactor, &o->bfd, o->poll_events);
  99. // inform receiver we finished the packet
  100. PacketRecvInterface_Done(&o->output, bytes);
  101. } while (0);
  102. }
  103. #endif
  104. void report_error (BTap *o)
  105. {
  106. DEBUGERROR(&o->d_err, o->handler_error(o->handler_error_user));
  107. }
  108. void output_handler_recv (BTap *o, uint8_t *data)
  109. {
  110. DebugObject_Access(&o->d_obj);
  111. DebugError_AssertNoError(&o->d_err);
  112. ASSERT(data)
  113. ASSERT(!o->output_packet)
  114. #ifdef BADVPN_USE_WINAPI
  115. memset(&o->recv_olap.olap, 0, sizeof(o->recv_olap.olap));
  116. // read
  117. BOOL res = ReadFile(o->device, data, o->frame_mtu, NULL, &o->recv_olap.olap);
  118. if (res == FALSE && GetLastError() != ERROR_IO_PENDING) {
  119. BLog(BLOG_ERROR, "ReadFile failed (%u)", GetLastError());
  120. report_error(o);
  121. return;
  122. }
  123. o->output_packet = data;
  124. #else
  125. // attempt read
  126. int bytes = read(o->fd, data, o->frame_mtu);
  127. if (bytes < 0) {
  128. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  129. // retry later in fd_handler
  130. // remember packet
  131. o->output_packet = data;
  132. // update events
  133. o->poll_events |= BREACTOR_READ;
  134. BReactor_SetFileDescriptorEvents(o->reactor, &o->bfd, o->poll_events);
  135. return;
  136. }
  137. // report fatal error
  138. report_error(o);
  139. return;
  140. }
  141. ASSERT_FORCE(bytes <= o->frame_mtu)
  142. PacketRecvInterface_Done(&o->output, bytes);
  143. #endif
  144. }
  145. int BTap_Init (BTap *o, BReactor *reactor, char *devname, BTap_handler_error handler_error, void *handler_error_user, int tun)
  146. {
  147. ASSERT(tun == 0 || tun == 1)
  148. // init arguments
  149. o->reactor = reactor;
  150. o->handler_error = handler_error;
  151. o->handler_error_user = handler_error_user;
  152. #ifdef BADVPN_USE_WINAPI
  153. // parse device specification
  154. if (!devname) {
  155. BLog(BLOG_ERROR, "no device specification provided");
  156. return 0;
  157. }
  158. int devname_len = strlen(devname);
  159. char device_component_id[devname_len + 1];
  160. char device_name[devname_len + 1];
  161. uint32_t tun_addrs[3];
  162. if (tun) {
  163. if (!tapwin32_parse_tun_spec(devname, device_component_id, device_name, tun_addrs)) {
  164. BLog(BLOG_ERROR, "failed to parse TUN device specification");
  165. return 0;
  166. }
  167. } else {
  168. if (!tapwin32_parse_tap_spec(devname, device_component_id, device_name)) {
  169. BLog(BLOG_ERROR, "failed to parse TAP device specification");
  170. return 0;
  171. }
  172. }
  173. // locate device path
  174. char device_path[TAPWIN32_MAX_REG_SIZE];
  175. BLog(BLOG_INFO, "Looking for TAP-Win32 with component ID %s, name %s", device_component_id, device_name);
  176. if (!tapwin32_find_device(device_component_id, device_name, &device_path)) {
  177. BLog(BLOG_ERROR, "Could not find device");
  178. goto fail0;
  179. }
  180. // open device
  181. BLog(BLOG_INFO, "Opening device %s", device_path);
  182. o->device = CreateFile(device_path, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM|FILE_FLAG_OVERLAPPED, 0);
  183. if (o->device == INVALID_HANDLE_VALUE) {
  184. BLog(BLOG_ERROR, "CreateFile failed");
  185. goto fail0;
  186. }
  187. // set TUN if needed
  188. DWORD len;
  189. if (tun) {
  190. if (!DeviceIoControl(o->device, TAP_IOCTL_CONFIG_TUN, tun_addrs, sizeof(tun_addrs), tun_addrs, sizeof(tun_addrs), &len, NULL)) {
  191. BLog(BLOG_ERROR, "DeviceIoControl(TAP_IOCTL_CONFIG_TUN) failed");
  192. goto fail1;
  193. }
  194. }
  195. // get MTU
  196. ULONG umtu;
  197. if (!DeviceIoControl(o->device, TAP_IOCTL_GET_MTU, NULL, 0, &umtu, sizeof(umtu), &len, NULL)) {
  198. BLog(BLOG_ERROR, "DeviceIoControl(TAP_IOCTL_GET_MTU) failed");
  199. goto fail1;
  200. }
  201. if (tun) {
  202. o->frame_mtu = umtu;
  203. } else {
  204. o->frame_mtu = umtu + BTAP_ETHERNET_HEADER_LENGTH;
  205. }
  206. // set connected
  207. ULONG upstatus = TRUE;
  208. if (!DeviceIoControl(o->device, TAP_IOCTL_SET_MEDIA_STATUS, &upstatus, sizeof(upstatus), &upstatus, sizeof(upstatus), &len, NULL)) {
  209. BLog(BLOG_ERROR, "DeviceIoControl(TAP_IOCTL_SET_MEDIA_STATUS) failed");
  210. goto fail1;
  211. }
  212. BLog(BLOG_INFO, "Device opened");
  213. // associate device with IOCP
  214. if (!CreateIoCompletionPort(o->device, BReactor_GetIOCPHandle(o->reactor), 0, 0)) {
  215. BLog(BLOG_ERROR, "CreateIoCompletionPort failed");
  216. goto fail1;
  217. }
  218. // init send olap
  219. BReactorIOCPOverlapped_Init(&o->send_olap, o->reactor, o, NULL);
  220. // init recv olap
  221. BReactorIOCPOverlapped_Init(&o->recv_olap, o->reactor, o, (BReactorIOCPOverlapped_handler)recv_olap_handler);
  222. goto success;
  223. fail1:
  224. ASSERT_FORCE(CloseHandle(o->device))
  225. fail0:
  226. return 0;
  227. #endif
  228. #if defined(BADVPN_LINUX) || defined(BADVPN_FREEBSD)
  229. char devname_real[IFNAMSIZ];
  230. #ifdef BADVPN_LINUX
  231. // open device
  232. if ((o->fd = open("/dev/net/tun", O_RDWR)) < 0) {
  233. BLog(BLOG_ERROR, "error opening device");
  234. goto fail0;
  235. }
  236. // configure device
  237. struct ifreq ifr;
  238. memset(&ifr, 0, sizeof(ifr));
  239. ifr.ifr_flags |= IFF_NO_PI;
  240. if (tun) {
  241. ifr.ifr_flags |= IFF_TUN;
  242. } else {
  243. ifr.ifr_flags |= IFF_TAP;
  244. }
  245. if (devname) {
  246. snprintf(ifr.ifr_name, IFNAMSIZ, "%s", devname);
  247. }
  248. if (ioctl(o->fd, TUNSETIFF, (void *)&ifr) < 0) {
  249. BLog(BLOG_ERROR, "error configuring device");
  250. goto fail1;
  251. }
  252. strcpy(devname_real, ifr.ifr_name);
  253. #endif
  254. #ifdef BADVPN_FREEBSD
  255. if (tun) {
  256. BLog(BLOG_ERROR, "TUN not supported on FreeBSD");
  257. goto fail0;
  258. }
  259. if (!devname) {
  260. BLog(BLOG_ERROR, "no device specified");
  261. goto fail0;
  262. }
  263. // open device
  264. char devnode[10 + IFNAMSIZ];
  265. snprintf(devnode, sizeof(devnode), "/dev/%s", devname);
  266. if ((o->fd = open(devnode, O_RDWR)) < 0) {
  267. BLog(BLOG_ERROR, "error opening device");
  268. goto fail0;
  269. }
  270. // get name
  271. struct ifreq ifr;
  272. memset(&ifr, 0, sizeof(ifr));
  273. if (ioctl(o->fd, TAPGIFNAME, (void *)&ifr) < 0) {
  274. BLog(BLOG_ERROR, "error configuring device");
  275. goto fail1;
  276. }
  277. strcpy(devname_real, ifr.ifr_name);
  278. #endif
  279. // get MTU
  280. // open dummy socket for ioctls
  281. int sock = socket(AF_INET, SOCK_DGRAM, 0);
  282. if (sock < 0) {
  283. BLog(BLOG_ERROR, "socket failed");
  284. goto fail1;
  285. }
  286. memset(&ifr, 0, sizeof(ifr));
  287. strcpy(ifr.ifr_name, devname_real);
  288. if (ioctl(sock, SIOCGIFMTU, (void *)&ifr) < 0) {
  289. BLog(BLOG_ERROR, "error getting MTU");
  290. close(sock);
  291. goto fail1;
  292. }
  293. if (tun) {
  294. o->frame_mtu = ifr.ifr_mtu;
  295. } else {
  296. o->frame_mtu = ifr.ifr_mtu + BTAP_ETHERNET_HEADER_LENGTH;
  297. }
  298. close(sock);
  299. // set non-blocking
  300. if (fcntl(o->fd, F_SETFL, O_NONBLOCK) < 0) {
  301. BLog(BLOG_ERROR, "cannot set non-blocking");
  302. goto fail1;
  303. }
  304. // init file descriptor object
  305. BFileDescriptor_Init(&o->bfd, o->fd, (BFileDescriptor_handler)fd_handler, o);
  306. if (!BReactor_AddFileDescriptor(o->reactor, &o->bfd)) {
  307. BLog(BLOG_ERROR, "BReactor_AddFileDescriptor failed");
  308. goto fail1;
  309. }
  310. o->poll_events = 0;
  311. goto success;
  312. fail1:
  313. ASSERT_FORCE(close(o->fd) == 0)
  314. fail0:
  315. return 0;
  316. #endif
  317. success:
  318. // init output
  319. PacketRecvInterface_Init(&o->output, o->frame_mtu, (PacketRecvInterface_handler_recv)output_handler_recv, o, BReactor_PendingGroup(o->reactor));
  320. // set no output packet
  321. o->output_packet = NULL;
  322. DebugError_Init(&o->d_err, BReactor_PendingGroup(o->reactor));
  323. DebugObject_Init(&o->d_obj);
  324. return 1;
  325. }
  326. void BTap_Free (BTap *o)
  327. {
  328. DebugObject_Free(&o->d_obj);
  329. DebugError_Free(&o->d_err);
  330. // free output
  331. PacketRecvInterface_Free(&o->output);
  332. #ifdef BADVPN_USE_WINAPI
  333. // cancel I/O
  334. ASSERT_FORCE(CancelIo(o->device))
  335. // wait receiving to finish
  336. if (o->output_packet) {
  337. BLog(BLOG_DEBUG, "waiting for receiving to finish");
  338. BReactorIOCPOverlapped_Wait(&o->recv_olap, NULL, NULL);
  339. }
  340. // free recv olap
  341. BReactorIOCPOverlapped_Free(&o->recv_olap);
  342. // free send olap
  343. BReactorIOCPOverlapped_Free(&o->send_olap);
  344. // close device
  345. ASSERT_FORCE(CloseHandle(o->device))
  346. #else
  347. // free BFileDescriptor
  348. BReactor_RemoveFileDescriptor(o->reactor, &o->bfd);
  349. // close file descriptor
  350. ASSERT_FORCE(close(o->fd) == 0)
  351. #endif
  352. }
  353. int BTap_GetMTU (BTap *o)
  354. {
  355. DebugObject_Access(&o->d_obj);
  356. return o->frame_mtu;
  357. }
  358. void BTap_Send (BTap *o, uint8_t *data, int data_len)
  359. {
  360. DebugObject_Access(&o->d_obj);
  361. DebugError_AssertNoError(&o->d_err);
  362. ASSERT(data_len >= 0)
  363. ASSERT(data_len <= o->frame_mtu)
  364. #ifdef BADVPN_USE_WINAPI
  365. // ignore frames without an Ethernet header, or we get errors in WriteFile
  366. if (data_len < 14) {
  367. return;
  368. }
  369. memset(&o->send_olap.olap, 0, sizeof(o->send_olap.olap));
  370. // write
  371. BOOL res = WriteFile(o->device, data, data_len, NULL, &o->send_olap.olap);
  372. if (res == FALSE && GetLastError() != ERROR_IO_PENDING) {
  373. BLog(BLOG_ERROR, "WriteFile failed (%u)", GetLastError());
  374. return;
  375. }
  376. // wait
  377. int succeeded;
  378. DWORD bytes;
  379. BReactorIOCPOverlapped_Wait(&o->send_olap, &succeeded, &bytes);
  380. if (!succeeded) {
  381. BLog(BLOG_ERROR, "write operation failed");
  382. } else {
  383. ASSERT(bytes >= 0)
  384. ASSERT(bytes <= data_len)
  385. if (bytes < data_len) {
  386. BLog(BLOG_ERROR, "write operation didn't write everything");
  387. }
  388. }
  389. #else
  390. int bytes = write(o->fd, data, data_len);
  391. if (bytes < 0) {
  392. // malformed packets will cause errors, ignore them and act like
  393. // the packet was accepeted
  394. } else {
  395. if (bytes != data_len) {
  396. BLog(BLOG_WARNING, "written %d expected %d", bytes, data_len);
  397. }
  398. }
  399. #endif
  400. }
  401. PacketRecvInterface * BTap_GetOutput (BTap *o)
  402. {
  403. DebugObject_Access(&o->d_obj);
  404. return &o->output;
  405. }