BTap.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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. // Treat zero return value the same as EAGAIN.
  93. // See: https://bugzilla.kernel.org/show_bug.cgi?id=96381
  94. if (bytes == 0 || errno == EAGAIN || errno == EWOULDBLOCK) {
  95. // retry later
  96. break;
  97. }
  98. // report fatal error
  99. report_error(o);
  100. return;
  101. }
  102. ASSERT_FORCE(bytes <= o->frame_mtu)
  103. // set no output packet
  104. o->output_packet = NULL;
  105. // update events
  106. o->poll_events &= ~BREACTOR_READ;
  107. BReactor_SetFileDescriptorEvents(o->reactor, &o->bfd, o->poll_events);
  108. // inform receiver we finished the packet
  109. PacketRecvInterface_Done(&o->output, bytes);
  110. } while (0);
  111. }
  112. #endif
  113. void report_error (BTap *o)
  114. {
  115. DEBUGERROR(&o->d_err, o->handler_error(o->handler_error_user));
  116. }
  117. void output_handler_recv (BTap *o, uint8_t *data)
  118. {
  119. DebugObject_Access(&o->d_obj);
  120. DebugError_AssertNoError(&o->d_err);
  121. ASSERT(data)
  122. ASSERT(!o->output_packet)
  123. #ifdef BADVPN_USE_WINAPI
  124. memset(&o->recv_olap.olap, 0, sizeof(o->recv_olap.olap));
  125. // read
  126. BOOL res = ReadFile(o->device, data, o->frame_mtu, NULL, &o->recv_olap.olap);
  127. if (res == FALSE && GetLastError() != ERROR_IO_PENDING) {
  128. BLog(BLOG_ERROR, "ReadFile failed (%u)", GetLastError());
  129. report_error(o);
  130. return;
  131. }
  132. o->output_packet = data;
  133. #else
  134. // attempt read
  135. int bytes = read(o->fd, data, o->frame_mtu);
  136. if (bytes <= 0) {
  137. if (bytes == 0 || errno == EAGAIN || errno == EWOULDBLOCK) {
  138. // See note about zero return in fd_handler.
  139. // retry later in fd_handler
  140. // remember packet
  141. o->output_packet = data;
  142. // update events
  143. o->poll_events |= BREACTOR_READ;
  144. BReactor_SetFileDescriptorEvents(o->reactor, &o->bfd, o->poll_events);
  145. return;
  146. }
  147. // report fatal error
  148. report_error(o);
  149. return;
  150. }
  151. ASSERT_FORCE(bytes <= o->frame_mtu)
  152. PacketRecvInterface_Done(&o->output, bytes);
  153. #endif
  154. }
  155. int BTap_Init (BTap *o, BReactor *reactor, char *devname, BTap_handler_error handler_error, void *handler_error_user, int tun)
  156. {
  157. ASSERT(tun == 0 || tun == 1)
  158. struct BTap_init_data init_data;
  159. init_data.dev_type = tun ? BTAP_DEV_TUN : BTAP_DEV_TAP;
  160. init_data.init_type = BTAP_INIT_STRING;
  161. init_data.init.string = devname;
  162. return BTap_Init2(o, reactor, init_data, handler_error, handler_error_user);
  163. }
  164. int BTap_Init2 (BTap *o, BReactor *reactor, struct BTap_init_data init_data, BTap_handler_error handler_error, void *handler_error_user)
  165. {
  166. ASSERT(init_data.dev_type == BTAP_DEV_TUN || init_data.dev_type == BTAP_DEV_TAP)
  167. // init arguments
  168. o->reactor = reactor;
  169. o->handler_error = handler_error;
  170. o->handler_error_user = handler_error_user;
  171. #ifdef BADVPN_USE_WINAPI
  172. ASSERT(init_data.init_type == BTAP_INIT_STRING)
  173. // parse device specification
  174. if (!init_data.init.string) {
  175. BLog(BLOG_ERROR, "no device specification provided");
  176. goto fail0;
  177. }
  178. char *device_component_id;
  179. char *device_name;
  180. uint32_t tun_addrs[3];
  181. if (init_data.dev_type == BTAP_DEV_TUN) {
  182. if (!tapwin32_parse_tun_spec(init_data.init.string, &device_component_id, &device_name, tun_addrs)) {
  183. BLog(BLOG_ERROR, "failed to parse TUN device specification");
  184. goto fail0;
  185. }
  186. } else {
  187. if (!tapwin32_parse_tap_spec(init_data.init.string, &device_component_id, &device_name)) {
  188. BLog(BLOG_ERROR, "failed to parse TAP device specification");
  189. goto fail0;
  190. }
  191. }
  192. // locate device path
  193. char device_path[TAPWIN32_MAX_REG_SIZE];
  194. BLog(BLOG_INFO, "Looking for TAP-Win32 with component ID %s, name %s", device_component_id, device_name);
  195. if (!tapwin32_find_device(device_component_id, device_name, &device_path)) {
  196. BLog(BLOG_ERROR, "Could not find device");
  197. goto fail1;
  198. }
  199. // open device
  200. BLog(BLOG_INFO, "Opening device %s", device_path);
  201. o->device = CreateFile(device_path, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM|FILE_FLAG_OVERLAPPED, 0);
  202. if (o->device == INVALID_HANDLE_VALUE) {
  203. BLog(BLOG_ERROR, "CreateFile failed");
  204. goto fail1;
  205. }
  206. // set TUN if needed
  207. DWORD len;
  208. if (init_data.dev_type == BTAP_DEV_TUN) {
  209. if (!DeviceIoControl(o->device, TAP_IOCTL_CONFIG_TUN, tun_addrs, sizeof(tun_addrs), tun_addrs, sizeof(tun_addrs), &len, NULL)) {
  210. BLog(BLOG_ERROR, "DeviceIoControl(TAP_IOCTL_CONFIG_TUN) failed");
  211. goto fail2;
  212. }
  213. }
  214. // get MTU
  215. ULONG umtu;
  216. if (!DeviceIoControl(o->device, TAP_IOCTL_GET_MTU, NULL, 0, &umtu, sizeof(umtu), &len, NULL)) {
  217. BLog(BLOG_ERROR, "DeviceIoControl(TAP_IOCTL_GET_MTU) failed");
  218. goto fail2;
  219. }
  220. if (init_data.dev_type == BTAP_DEV_TUN) {
  221. o->frame_mtu = umtu;
  222. } else {
  223. o->frame_mtu = umtu + BTAP_ETHERNET_HEADER_LENGTH;
  224. }
  225. // set connected
  226. ULONG upstatus = TRUE;
  227. if (!DeviceIoControl(o->device, TAP_IOCTL_SET_MEDIA_STATUS, &upstatus, sizeof(upstatus), &upstatus, sizeof(upstatus), &len, NULL)) {
  228. BLog(BLOG_ERROR, "DeviceIoControl(TAP_IOCTL_SET_MEDIA_STATUS) failed");
  229. goto fail2;
  230. }
  231. BLog(BLOG_INFO, "Device opened");
  232. // associate device with IOCP
  233. if (!CreateIoCompletionPort(o->device, BReactor_GetIOCPHandle(o->reactor), 0, 0)) {
  234. BLog(BLOG_ERROR, "CreateIoCompletionPort failed");
  235. goto fail2;
  236. }
  237. // init send olap
  238. BReactorIOCPOverlapped_Init(&o->send_olap, o->reactor, o, NULL);
  239. // init recv olap
  240. BReactorIOCPOverlapped_Init(&o->recv_olap, o->reactor, o, (BReactorIOCPOverlapped_handler)recv_olap_handler);
  241. free(device_name);
  242. free(device_component_id);
  243. goto success;
  244. fail2:
  245. ASSERT_FORCE(CloseHandle(o->device))
  246. fail1:
  247. free(device_name);
  248. free(device_component_id);
  249. fail0:
  250. return 0;
  251. #endif
  252. #if defined(BADVPN_LINUX) || defined(BADVPN_FREEBSD)
  253. o->close_fd = (init_data.init_type != BTAP_INIT_FD);
  254. switch (init_data.init_type) {
  255. case BTAP_INIT_FD: {
  256. ASSERT(init_data.init.fd.fd >= 0)
  257. ASSERT(init_data.init.fd.mtu >= 0)
  258. ASSERT(init_data.dev_type != BTAP_DEV_TAP || init_data.init.fd.mtu >= BTAP_ETHERNET_HEADER_LENGTH)
  259. o->fd = init_data.init.fd.fd;
  260. o->frame_mtu = init_data.init.fd.mtu;
  261. } break;
  262. case BTAP_INIT_STRING: {
  263. char devname_real[IFNAMSIZ];
  264. #ifdef BADVPN_LINUX
  265. // open device
  266. if ((o->fd = open("/dev/net/tun", O_RDWR)) < 0) {
  267. BLog(BLOG_ERROR, "error opening device");
  268. goto fail0;
  269. }
  270. // configure device
  271. struct ifreq ifr;
  272. memset(&ifr, 0, sizeof(ifr));
  273. ifr.ifr_flags |= IFF_NO_PI;
  274. if (init_data.dev_type == BTAP_DEV_TUN) {
  275. ifr.ifr_flags |= IFF_TUN;
  276. } else {
  277. ifr.ifr_flags |= IFF_TAP;
  278. }
  279. if (init_data.init.string) {
  280. snprintf(ifr.ifr_name, IFNAMSIZ, "%s", init_data.init.string);
  281. }
  282. if (ioctl(o->fd, TUNSETIFF, (void *)&ifr) < 0) {
  283. BLog(BLOG_ERROR, "error configuring device");
  284. goto fail1;
  285. }
  286. strcpy(devname_real, ifr.ifr_name);
  287. #endif
  288. #ifdef BADVPN_FREEBSD
  289. if (init_data.dev_type == BTAP_DEV_TUN) {
  290. BLog(BLOG_ERROR, "TUN not supported on FreeBSD");
  291. goto fail0;
  292. }
  293. if (!init_data.init.string) {
  294. BLog(BLOG_ERROR, "no device specified");
  295. goto fail0;
  296. }
  297. // open device
  298. char devnode[10 + IFNAMSIZ];
  299. snprintf(devnode, sizeof(devnode), "/dev/%s", init_data.init.string);
  300. if ((o->fd = open(devnode, O_RDWR)) < 0) {
  301. BLog(BLOG_ERROR, "error opening device");
  302. goto fail0;
  303. }
  304. // get name
  305. struct ifreq ifr;
  306. memset(&ifr, 0, sizeof(ifr));
  307. if (ioctl(o->fd, TAPGIFNAME, (void *)&ifr) < 0) {
  308. BLog(BLOG_ERROR, "error configuring device");
  309. goto fail1;
  310. }
  311. strcpy(devname_real, ifr.ifr_name);
  312. #endif
  313. // get MTU
  314. // open dummy socket for ioctls
  315. int sock = socket(AF_INET, SOCK_DGRAM, 0);
  316. if (sock < 0) {
  317. BLog(BLOG_ERROR, "socket failed");
  318. goto fail1;
  319. }
  320. memset(&ifr, 0, sizeof(ifr));
  321. strcpy(ifr.ifr_name, devname_real);
  322. if (ioctl(sock, SIOCGIFMTU, (void *)&ifr) < 0) {
  323. BLog(BLOG_ERROR, "error getting MTU");
  324. close(sock);
  325. goto fail1;
  326. }
  327. if (init_data.dev_type == BTAP_DEV_TUN) {
  328. o->frame_mtu = ifr.ifr_mtu;
  329. } else {
  330. o->frame_mtu = ifr.ifr_mtu + BTAP_ETHERNET_HEADER_LENGTH;
  331. }
  332. close(sock);
  333. } break;
  334. default: ASSERT(0);
  335. }
  336. // set non-blocking
  337. if (fcntl(o->fd, F_SETFL, O_NONBLOCK) < 0) {
  338. BLog(BLOG_ERROR, "cannot set non-blocking");
  339. goto fail1;
  340. }
  341. // init file descriptor object
  342. BFileDescriptor_Init(&o->bfd, o->fd, (BFileDescriptor_handler)fd_handler, o);
  343. if (!BReactor_AddFileDescriptor(o->reactor, &o->bfd)) {
  344. BLog(BLOG_ERROR, "BReactor_AddFileDescriptor failed");
  345. goto fail1;
  346. }
  347. o->poll_events = 0;
  348. goto success;
  349. fail1:
  350. if (o->close_fd) {
  351. ASSERT_FORCE(close(o->fd) == 0)
  352. }
  353. fail0:
  354. return 0;
  355. #endif
  356. success:
  357. // init output
  358. PacketRecvInterface_Init(&o->output, o->frame_mtu, (PacketRecvInterface_handler_recv)output_handler_recv, o, BReactor_PendingGroup(o->reactor));
  359. // set no output packet
  360. o->output_packet = NULL;
  361. DebugError_Init(&o->d_err, BReactor_PendingGroup(o->reactor));
  362. DebugObject_Init(&o->d_obj);
  363. return 1;
  364. }
  365. void BTap_Free (BTap *o)
  366. {
  367. DebugObject_Free(&o->d_obj);
  368. DebugError_Free(&o->d_err);
  369. // free output
  370. PacketRecvInterface_Free(&o->output);
  371. #ifdef BADVPN_USE_WINAPI
  372. // cancel I/O
  373. ASSERT_FORCE(CancelIo(o->device))
  374. // wait receiving to finish
  375. if (o->output_packet) {
  376. BLog(BLOG_DEBUG, "waiting for receiving to finish");
  377. BReactorIOCPOverlapped_Wait(&o->recv_olap, NULL, NULL);
  378. }
  379. // free recv olap
  380. BReactorIOCPOverlapped_Free(&o->recv_olap);
  381. // free send olap
  382. BReactorIOCPOverlapped_Free(&o->send_olap);
  383. // close device
  384. ASSERT_FORCE(CloseHandle(o->device))
  385. #else
  386. // free BFileDescriptor
  387. BReactor_RemoveFileDescriptor(o->reactor, &o->bfd);
  388. if (o->close_fd) {
  389. // close file descriptor
  390. ASSERT_FORCE(close(o->fd) == 0)
  391. }
  392. #endif
  393. }
  394. int BTap_GetMTU (BTap *o)
  395. {
  396. DebugObject_Access(&o->d_obj);
  397. return o->frame_mtu;
  398. }
  399. void BTap_Send (BTap *o, uint8_t *data, int data_len)
  400. {
  401. DebugObject_Access(&o->d_obj);
  402. DebugError_AssertNoError(&o->d_err);
  403. ASSERT(data_len >= 0)
  404. ASSERT(data_len <= o->frame_mtu)
  405. #ifdef BADVPN_USE_WINAPI
  406. // ignore frames without an Ethernet header, or we get errors in WriteFile
  407. if (data_len < 14) {
  408. return;
  409. }
  410. memset(&o->send_olap.olap, 0, sizeof(o->send_olap.olap));
  411. // write
  412. BOOL res = WriteFile(o->device, data, data_len, NULL, &o->send_olap.olap);
  413. if (res == FALSE && GetLastError() != ERROR_IO_PENDING) {
  414. BLog(BLOG_ERROR, "WriteFile failed (%u)", GetLastError());
  415. return;
  416. }
  417. // wait
  418. int succeeded;
  419. DWORD bytes;
  420. BReactorIOCPOverlapped_Wait(&o->send_olap, &succeeded, &bytes);
  421. if (!succeeded) {
  422. BLog(BLOG_ERROR, "write operation failed");
  423. } else {
  424. ASSERT(bytes >= 0)
  425. ASSERT(bytes <= data_len)
  426. if (bytes < data_len) {
  427. BLog(BLOG_ERROR, "write operation didn't write everything");
  428. }
  429. }
  430. #else
  431. int bytes = write(o->fd, data, data_len);
  432. if (bytes < 0) {
  433. // malformed packets will cause errors, ignore them and act like
  434. // the packet was accepeted
  435. } else {
  436. if (bytes != data_len) {
  437. BLog(BLOG_WARNING, "written %d expected %d", bytes, data_len);
  438. }
  439. }
  440. #endif
  441. }
  442. PacketRecvInterface * BTap_GetOutput (BTap *o)
  443. {
  444. DebugObject_Access(&o->d_obj);
  445. return &o->output;
  446. }