BTap.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. /**
  2. * @file BTap.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the author nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. */
  29. #include <string.h>
  30. #include <stdio.h>
  31. #ifdef BADVPN_USE_WINAPI
  32. #include <windows.h>
  33. #include <winioctl.h>
  34. #include <objbase.h>
  35. #include <wtypes.h>
  36. #include "wintap-common.h"
  37. #include <tuntap/tapwin32-funcs.h>
  38. #else
  39. #include <fcntl.h>
  40. #include <unistd.h>
  41. #include <errno.h>
  42. #include <sys/ioctl.h>
  43. #include <sys/types.h>
  44. #include <sys/stat.h>
  45. #include <sys/socket.h>
  46. #include <net/if.h>
  47. #include <net/if_arp.h>
  48. #ifdef BADVPN_LINUX
  49. #include <linux/if_tun.h>
  50. #endif
  51. #ifdef BADVPN_FREEBSD
  52. #include <net/if_tun.h>
  53. #include <net/if_tap.h>
  54. #endif
  55. #endif
  56. #include <base/BLog.h>
  57. #include <tuntap/BTap.h>
  58. #include <generated/blog_channel_BTap.h>
  59. static void report_error (BTap *o);
  60. static void output_handler_recv (BTap *o, uint8_t *data);
  61. #ifdef BADVPN_USE_WINAPI
  62. static void recv_olap_handler (BTap *o, int event, DWORD bytes)
  63. {
  64. DebugObject_Access(&o->d_obj);
  65. ASSERT(o->output_packet)
  66. ASSERT(event == BREACTOR_IOCP_EVENT_SUCCEEDED || event == BREACTOR_IOCP_EVENT_FAILED)
  67. // set no output packet
  68. o->output_packet = NULL;
  69. if (event == BREACTOR_IOCP_EVENT_FAILED) {
  70. BLog(BLOG_ERROR, "read operation failed");
  71. report_error(o);
  72. return;
  73. }
  74. ASSERT(bytes >= 0)
  75. ASSERT(bytes <= o->frame_mtu)
  76. // done
  77. PacketRecvInterface_Done(&o->output, bytes);
  78. }
  79. #else
  80. static void fd_handler (BTap *o, int events)
  81. {
  82. DebugObject_Access(&o->d_obj);
  83. DebugError_AssertNoError(&o->d_err);
  84. if (events&(BREACTOR_ERROR|BREACTOR_HUP)) {
  85. BLog(BLOG_WARNING, "device fd reports error?");
  86. }
  87. if (events&BREACTOR_READ) do {
  88. ASSERT(o->output_packet)
  89. // try reading into the buffer
  90. int bytes = read(o->fd, o->output_packet, o->frame_mtu);
  91. if (bytes < 0) {
  92. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  93. // retry later
  94. break;
  95. }
  96. // report fatal error
  97. report_error(o);
  98. return;
  99. }
  100. ASSERT_FORCE(bytes <= o->frame_mtu)
  101. // set no output packet
  102. o->output_packet = NULL;
  103. // update events
  104. o->poll_events &= ~BREACTOR_READ;
  105. BReactor_SetFileDescriptorEvents(o->reactor, &o->bfd, o->poll_events);
  106. // inform receiver we finished the packet
  107. PacketRecvInterface_Done(&o->output, bytes);
  108. } while (0);
  109. }
  110. #endif
  111. void report_error (BTap *o)
  112. {
  113. DEBUGERROR(&o->d_err, o->handler_error(o->handler_error_user));
  114. }
  115. void output_handler_recv (BTap *o, uint8_t *data)
  116. {
  117. DebugObject_Access(&o->d_obj);
  118. DebugError_AssertNoError(&o->d_err);
  119. ASSERT(data)
  120. ASSERT(!o->output_packet)
  121. #ifdef BADVPN_USE_WINAPI
  122. memset(&o->recv_olap.olap, 0, sizeof(o->recv_olap.olap));
  123. // read
  124. BOOL res = ReadFile(o->device, data, o->frame_mtu, NULL, &o->recv_olap.olap);
  125. if (res == FALSE && GetLastError() != ERROR_IO_PENDING) {
  126. BLog(BLOG_ERROR, "ReadFile failed (%u)", GetLastError());
  127. report_error(o);
  128. return;
  129. }
  130. o->output_packet = data;
  131. #else
  132. // attempt read
  133. int bytes = read(o->fd, data, o->frame_mtu);
  134. if (bytes < 0) {
  135. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  136. // retry later in fd_handler
  137. // remember packet
  138. o->output_packet = data;
  139. // update events
  140. o->poll_events |= BREACTOR_READ;
  141. BReactor_SetFileDescriptorEvents(o->reactor, &o->bfd, o->poll_events);
  142. return;
  143. }
  144. // report fatal error
  145. report_error(o);
  146. return;
  147. }
  148. ASSERT_FORCE(bytes <= o->frame_mtu)
  149. PacketRecvInterface_Done(&o->output, bytes);
  150. #endif
  151. }
  152. int BTap_Init (BTap *o, BReactor *reactor, char *devname, BTap_handler_error handler_error, void *handler_error_user, int tun)
  153. {
  154. ASSERT(tun == 0 || tun == 1)
  155. struct BTap_init_data init_data;
  156. init_data.dev_type = tun ? BTAP_DEV_TUN : BTAP_DEV_TAP;
  157. init_data.init_type = BTAP_INIT_STRING;
  158. init_data.init.string = devname;
  159. return BTap_Init2(o, reactor, init_data, handler_error, handler_error_user);
  160. }
  161. int BTap_Init2 (BTap *o, BReactor *reactor, struct BTap_init_data init_data, BTap_handler_error handler_error, void *handler_error_user)
  162. {
  163. ASSERT(init_data.dev_type == BTAP_DEV_TUN || init_data.dev_type == BTAP_DEV_TAP)
  164. // init arguments
  165. o->reactor = reactor;
  166. o->handler_error = handler_error;
  167. o->handler_error_user = handler_error_user;
  168. #ifdef BADVPN_USE_WINAPI
  169. ASSERT(init_data.init_type == BTAP_INIT_STRING)
  170. // parse device specification
  171. if (!init_data.init.string) {
  172. BLog(BLOG_ERROR, "no device specification provided");
  173. goto fail0;
  174. }
  175. char *device_component_id;
  176. char *device_name;
  177. uint32_t tun_addrs[3];
  178. if (init_data.dev_type == BTAP_DEV_TUN) {
  179. if (!tapwin32_parse_tun_spec(init_data.init.string, &device_component_id, &device_name, tun_addrs)) {
  180. BLog(BLOG_ERROR, "failed to parse TUN device specification");
  181. goto fail0;
  182. }
  183. } else {
  184. if (!tapwin32_parse_tap_spec(init_data.init.string, &device_component_id, &device_name)) {
  185. BLog(BLOG_ERROR, "failed to parse TAP device specification");
  186. goto fail0;
  187. }
  188. }
  189. // locate device path
  190. char device_path[TAPWIN32_MAX_REG_SIZE];
  191. BLog(BLOG_INFO, "Looking for TAP-Win32 with component ID %s, name %s", device_component_id, device_name);
  192. if (!tapwin32_find_device(device_component_id, device_name, &device_path)) {
  193. BLog(BLOG_ERROR, "Could not find device");
  194. goto fail1;
  195. }
  196. // open device
  197. BLog(BLOG_INFO, "Opening device %s", device_path);
  198. o->device = CreateFile(device_path, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM|FILE_FLAG_OVERLAPPED, 0);
  199. if (o->device == INVALID_HANDLE_VALUE) {
  200. BLog(BLOG_ERROR, "CreateFile failed");
  201. goto fail1;
  202. }
  203. // set TUN if needed
  204. DWORD len;
  205. if (init_data.dev_type == BTAP_DEV_TUN) {
  206. if (!DeviceIoControl(o->device, TAP_IOCTL_CONFIG_TUN, tun_addrs, sizeof(tun_addrs), tun_addrs, sizeof(tun_addrs), &len, NULL)) {
  207. BLog(BLOG_ERROR, "DeviceIoControl(TAP_IOCTL_CONFIG_TUN) failed");
  208. goto fail2;
  209. }
  210. }
  211. // get MTU
  212. ULONG umtu;
  213. if (!DeviceIoControl(o->device, TAP_IOCTL_GET_MTU, NULL, 0, &umtu, sizeof(umtu), &len, NULL)) {
  214. BLog(BLOG_ERROR, "DeviceIoControl(TAP_IOCTL_GET_MTU) failed");
  215. goto fail2;
  216. }
  217. if (init_data.dev_type == BTAP_DEV_TUN) {
  218. o->frame_mtu = umtu;
  219. } else {
  220. o->frame_mtu = umtu + BTAP_ETHERNET_HEADER_LENGTH;
  221. }
  222. // set connected
  223. ULONG upstatus = TRUE;
  224. if (!DeviceIoControl(o->device, TAP_IOCTL_SET_MEDIA_STATUS, &upstatus, sizeof(upstatus), &upstatus, sizeof(upstatus), &len, NULL)) {
  225. BLog(BLOG_ERROR, "DeviceIoControl(TAP_IOCTL_SET_MEDIA_STATUS) failed");
  226. goto fail2;
  227. }
  228. BLog(BLOG_INFO, "Device opened");
  229. // associate device with IOCP
  230. if (!CreateIoCompletionPort(o->device, BReactor_GetIOCPHandle(o->reactor), 0, 0)) {
  231. BLog(BLOG_ERROR, "CreateIoCompletionPort failed");
  232. goto fail2;
  233. }
  234. // init send olap
  235. BReactorIOCPOverlapped_Init(&o->send_olap, o->reactor, o, NULL);
  236. // init recv olap
  237. BReactorIOCPOverlapped_Init(&o->recv_olap, o->reactor, o, (BReactorIOCPOverlapped_handler)recv_olap_handler);
  238. free(device_name);
  239. free(device_component_id);
  240. goto success;
  241. fail2:
  242. ASSERT_FORCE(CloseHandle(o->device))
  243. fail1:
  244. free(device_name);
  245. free(device_component_id);
  246. fail0:
  247. return 0;
  248. #endif
  249. #if defined(BADVPN_LINUX) || defined(BADVPN_FREEBSD)
  250. o->close_fd = (init_data.init_type != BTAP_INIT_FD);
  251. switch (init_data.init_type) {
  252. case BTAP_INIT_FD: {
  253. ASSERT(init_data.init.fd.fd >= 0)
  254. ASSERT(init_data.init.fd.mtu >= 0)
  255. ASSERT(init_data.dev_type != BTAP_DEV_TAP || init_data.init.fd.mtu >= BTAP_ETHERNET_HEADER_LENGTH)
  256. o->fd = init_data.init.fd.fd;
  257. o->frame_mtu = init_data.init.fd.mtu;
  258. } break;
  259. case BTAP_INIT_STRING: {
  260. char devname_real[IFNAMSIZ];
  261. #ifdef BADVPN_LINUX
  262. // open device
  263. if ((o->fd = open("/dev/net/tun", O_RDWR)) < 0) {
  264. BLog(BLOG_ERROR, "error opening device");
  265. goto fail0;
  266. }
  267. // configure device
  268. struct ifreq ifr;
  269. memset(&ifr, 0, sizeof(ifr));
  270. ifr.ifr_flags |= IFF_NO_PI;
  271. if (init_data.dev_type == BTAP_DEV_TUN) {
  272. ifr.ifr_flags |= IFF_TUN;
  273. } else {
  274. ifr.ifr_flags |= IFF_TAP;
  275. }
  276. if (init_data.init.string) {
  277. snprintf(ifr.ifr_name, IFNAMSIZ, "%s", init_data.init.string);
  278. }
  279. if (ioctl(o->fd, TUNSETIFF, (void *)&ifr) < 0) {
  280. BLog(BLOG_ERROR, "error configuring device");
  281. goto fail1;
  282. }
  283. strcpy(devname_real, ifr.ifr_name);
  284. #endif
  285. #ifdef BADVPN_FREEBSD
  286. if (init_data.dev_type == BTAP_DEV_TUN) {
  287. BLog(BLOG_ERROR, "TUN not supported on FreeBSD");
  288. goto fail0;
  289. }
  290. if (!init_data.init.string) {
  291. BLog(BLOG_ERROR, "no device specified");
  292. goto fail0;
  293. }
  294. // open device
  295. char devnode[10 + IFNAMSIZ];
  296. snprintf(devnode, sizeof(devnode), "/dev/%s", init_data.init.string);
  297. if ((o->fd = open(devnode, O_RDWR)) < 0) {
  298. BLog(BLOG_ERROR, "error opening device");
  299. goto fail0;
  300. }
  301. // get name
  302. struct ifreq ifr;
  303. memset(&ifr, 0, sizeof(ifr));
  304. if (ioctl(o->fd, TAPGIFNAME, (void *)&ifr) < 0) {
  305. BLog(BLOG_ERROR, "error configuring device");
  306. goto fail1;
  307. }
  308. strcpy(devname_real, ifr.ifr_name);
  309. #endif
  310. // get MTU
  311. // open dummy socket for ioctls
  312. int sock = socket(AF_INET, SOCK_DGRAM, 0);
  313. if (sock < 0) {
  314. BLog(BLOG_ERROR, "socket failed");
  315. goto fail1;
  316. }
  317. memset(&ifr, 0, sizeof(ifr));
  318. strcpy(ifr.ifr_name, devname_real);
  319. if (ioctl(sock, SIOCGIFMTU, (void *)&ifr) < 0) {
  320. BLog(BLOG_ERROR, "error getting MTU");
  321. close(sock);
  322. goto fail1;
  323. }
  324. if (init_data.dev_type == BTAP_DEV_TUN) {
  325. o->frame_mtu = ifr.ifr_mtu;
  326. } else {
  327. o->frame_mtu = ifr.ifr_mtu + BTAP_ETHERNET_HEADER_LENGTH;
  328. }
  329. close(sock);
  330. } break;
  331. default: ASSERT(0);
  332. }
  333. // set non-blocking
  334. if (fcntl(o->fd, F_SETFL, O_NONBLOCK) < 0) {
  335. BLog(BLOG_ERROR, "cannot set non-blocking");
  336. goto fail1;
  337. }
  338. // init file descriptor object
  339. BFileDescriptor_Init(&o->bfd, o->fd, (BFileDescriptor_handler)fd_handler, o);
  340. if (!BReactor_AddFileDescriptor(o->reactor, &o->bfd)) {
  341. BLog(BLOG_ERROR, "BReactor_AddFileDescriptor failed");
  342. goto fail1;
  343. }
  344. o->poll_events = 0;
  345. goto success;
  346. fail1:
  347. if (o->close_fd) {
  348. ASSERT_FORCE(close(o->fd) == 0)
  349. }
  350. fail0:
  351. return 0;
  352. #endif
  353. success:
  354. // init output
  355. PacketRecvInterface_Init(&o->output, o->frame_mtu, (PacketRecvInterface_handler_recv)output_handler_recv, o, BReactor_PendingGroup(o->reactor));
  356. // set no output packet
  357. o->output_packet = NULL;
  358. DebugError_Init(&o->d_err, BReactor_PendingGroup(o->reactor));
  359. DebugObject_Init(&o->d_obj);
  360. return 1;
  361. }
  362. void BTap_Free (BTap *o)
  363. {
  364. DebugObject_Free(&o->d_obj);
  365. DebugError_Free(&o->d_err);
  366. // free output
  367. PacketRecvInterface_Free(&o->output);
  368. #ifdef BADVPN_USE_WINAPI
  369. // cancel I/O
  370. ASSERT_FORCE(CancelIo(o->device))
  371. // wait receiving to finish
  372. if (o->output_packet) {
  373. BLog(BLOG_DEBUG, "waiting for receiving to finish");
  374. BReactorIOCPOverlapped_Wait(&o->recv_olap, NULL, NULL);
  375. }
  376. // free recv olap
  377. BReactorIOCPOverlapped_Free(&o->recv_olap);
  378. // free send olap
  379. BReactorIOCPOverlapped_Free(&o->send_olap);
  380. // close device
  381. ASSERT_FORCE(CloseHandle(o->device))
  382. #else
  383. // free BFileDescriptor
  384. BReactor_RemoveFileDescriptor(o->reactor, &o->bfd);
  385. if (o->close_fd) {
  386. // close file descriptor
  387. ASSERT_FORCE(close(o->fd) == 0)
  388. }
  389. #endif
  390. }
  391. int BTap_GetMTU (BTap *o)
  392. {
  393. DebugObject_Access(&o->d_obj);
  394. return o->frame_mtu;
  395. }
  396. void BTap_Send (BTap *o, uint8_t *data, int data_len)
  397. {
  398. DebugObject_Access(&o->d_obj);
  399. DebugError_AssertNoError(&o->d_err);
  400. ASSERT(data_len >= 0)
  401. ASSERT(data_len <= o->frame_mtu)
  402. #ifdef BADVPN_USE_WINAPI
  403. // ignore frames without an Ethernet header, or we get errors in WriteFile
  404. if (data_len < 14) {
  405. return;
  406. }
  407. memset(&o->send_olap.olap, 0, sizeof(o->send_olap.olap));
  408. // write
  409. BOOL res = WriteFile(o->device, data, data_len, NULL, &o->send_olap.olap);
  410. if (res == FALSE && GetLastError() != ERROR_IO_PENDING) {
  411. BLog(BLOG_ERROR, "WriteFile failed (%u)", GetLastError());
  412. return;
  413. }
  414. // wait
  415. int succeeded;
  416. DWORD bytes;
  417. BReactorIOCPOverlapped_Wait(&o->send_olap, &succeeded, &bytes);
  418. if (!succeeded) {
  419. BLog(BLOG_ERROR, "write operation failed");
  420. } else {
  421. ASSERT(bytes >= 0)
  422. ASSERT(bytes <= data_len)
  423. if (bytes < data_len) {
  424. BLog(BLOG_ERROR, "write operation didn't write everything");
  425. }
  426. }
  427. #else
  428. int bytes = write(o->fd, data, data_len);
  429. if (bytes < 0) {
  430. // malformed packets will cause errors, ignore them and act like
  431. // the packet was accepeted
  432. } else {
  433. if (bytes != data_len) {
  434. BLog(BLOG_WARNING, "written %d expected %d", bytes, data_len);
  435. }
  436. }
  437. #endif
  438. }
  439. PacketRecvInterface * BTap_GetOutput (BTap *o)
  440. {
  441. DebugObject_Access(&o->d_obj);
  442. return &o->output;
  443. }