BTap.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  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. #else
  31. #include <linux/if_tun.h>
  32. #include <net/if.h>
  33. #include <net/if_arp.h>
  34. #include <sys/ioctl.h>
  35. #include <sys/types.h>
  36. #include <sys/stat.h>
  37. #include <sys/socket.h>
  38. #include <fcntl.h>
  39. #include <unistd.h>
  40. #include <errno.h>
  41. #endif
  42. #include <tuntap/BTap.h>
  43. #define REGNAME_SIZE 256
  44. static void report_error (BTap *o);
  45. static void input_handler_send (BTap *o, uint8_t *data, int data_len);
  46. static void input_handler_cancel (BTap *o);
  47. static void output_handler_recv (BTap *o, uint8_t *data);
  48. #ifdef BADVPN_USE_WINAPI
  49. static int try_send (BTap *o, uint8_t *data, int data_len)
  50. {
  51. // setup overlapped
  52. memset(&o->input_ol, 0, sizeof(o->input_ol));
  53. o->input_ol.hEvent = o->input_event;
  54. // attempt write
  55. if (!WriteFile(o->device, data, data_len, NULL, &o->input_ol)) {
  56. DWORD error = GetLastError();
  57. if (error == ERROR_IO_PENDING) {
  58. // write pending
  59. return 0;
  60. }
  61. DEBUG("WARNING: WriteFile failed (%u)", error);
  62. return 1;
  63. }
  64. // read result
  65. DWORD bytes;
  66. if (!GetOverlappedResult(o->device, &o->input_ol, &bytes, FALSE)) {
  67. DEBUG("WARNING: GetOverlappedResult failed (%u)", GetLastError());
  68. }
  69. else if (bytes != data_len) {
  70. DEBUG("WARNING: written %d expected %d", (int)bytes, data_len);
  71. }
  72. // reset event
  73. ASSERT_FORCE(ResetEvent(o->input_event))
  74. return 1;
  75. }
  76. static int try_recv (BTap *o, uint8_t *data, int *data_len)
  77. {
  78. // setup overlapped
  79. memset(&o->output_ol, 0, sizeof(o->output_ol));
  80. o->output_ol.hEvent = o->output_event;
  81. // attempt read
  82. if (!ReadFile(o->device, data, o->frame_mtu, NULL, &o->output_ol)) {
  83. DWORD error = GetLastError();
  84. if (error == ERROR_IO_PENDING) {
  85. // read pending
  86. return 0;
  87. }
  88. DEBUG("ReadFile failed (%u)", error);
  89. // fatal error
  90. return -1;
  91. }
  92. // read result
  93. DWORD bytes;
  94. if (!GetOverlappedResult(o->device, &o->output_ol, &bytes, FALSE)) {
  95. DEBUG("GetOverlappedResult (output) failed (%u)", GetLastError());
  96. // fatal error
  97. return -1;
  98. }
  99. ASSERT_FORCE(bytes <= o->frame_mtu)
  100. // reset event
  101. ASSERT_FORCE(ResetEvent(o->output_event))
  102. *data_len = bytes;
  103. return 1;
  104. }
  105. static void write_handle_handler (BTap *o)
  106. {
  107. ASSERT(o->input_packet_len >= 0)
  108. DebugObject_Access(&o->d_obj);
  109. // disable handle event
  110. BReactor_DisableHandle(o->reactor, &o->input_bhandle);
  111. // read result
  112. DWORD bytes;
  113. if (!GetOverlappedResult(o->device, &o->input_ol, &bytes, FALSE)) {
  114. DEBUG("WARNING: GetOverlappedResult (input) failed (%u)", GetLastError());
  115. } else if (bytes != o->input_packet_len) {
  116. DEBUG("WARNING: written %d expected %d", (int)bytes, o->input_packet_len);
  117. }
  118. // set no input packet
  119. o->input_packet_len = -1;
  120. // reset event
  121. ASSERT_FORCE(ResetEvent(o->input_event))
  122. // inform sender we finished the packet
  123. PacketPassInterface_Done(&o->input);
  124. }
  125. static void read_handle_handler (BTap *o)
  126. {
  127. ASSERT(o->output_packet)
  128. DebugObject_Access(&o->d_obj);
  129. int bytes;
  130. // read result
  131. DWORD dbytes;
  132. if (!GetOverlappedResult(o->device, &o->output_ol, &dbytes, FALSE)) {
  133. DWORD error = GetLastError();
  134. DEBUG("GetOverlappedResult (output) failed (%u)", error);
  135. // handle accidental cancelation from input_handler_cancel
  136. if (error == ERROR_OPERATION_ABORTED) {
  137. DEBUG("retrying read");
  138. // reset event
  139. ASSERT_FORCE(ResetEvent(o->output_event))
  140. // try receiving
  141. int res;
  142. if ((res = try_recv(o, o->output_packet, &bytes)) < 0) {
  143. goto fatal_error;
  144. }
  145. if (!res) {
  146. // keep waiting
  147. return;
  148. }
  149. goto done;
  150. }
  151. fatal_error:
  152. // set no output packet (so that BTap_Free doesn't try getting the result again)
  153. o->output_packet = NULL;
  154. // report fatal error
  155. report_error(o);
  156. return;
  157. }
  158. // reset event
  159. ASSERT_FORCE(ResetEvent(o->output_event))
  160. bytes = dbytes;
  161. done:
  162. ASSERT_FORCE(bytes <= o->frame_mtu)
  163. // disable handle event
  164. BReactor_DisableHandle(o->reactor, &o->output_bhandle);
  165. // set no output packet
  166. o->output_packet = NULL;
  167. // inform receiver we finished the packet
  168. PacketRecvInterface_Done(&o->output, bytes);
  169. }
  170. #else
  171. static void fd_handler (BTap *o, int events)
  172. {
  173. DebugObject_Access(&o->d_obj);
  174. DEAD_DECLARE
  175. if (events&BREACTOR_ERROR) {
  176. DEBUG("WARNING: device fd reports error?");
  177. }
  178. if (events&BREACTOR_WRITE) do {
  179. ASSERT(o->input_packet_len >= 0)
  180. int bytes = write(o->fd, o->input_packet, o->input_packet_len);
  181. if (bytes < 0) {
  182. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  183. // retry later
  184. break;
  185. }
  186. // malformed packets will cause errors, ignore them and act like
  187. // the packet was accepeted
  188. } else {
  189. if (bytes != o->input_packet_len) {
  190. DEBUG("WARNING: written %d expected %d", bytes, o->input_packet_len);
  191. }
  192. }
  193. // set no input packet
  194. o->input_packet_len = -1;
  195. // update events
  196. o->poll_events &= ~BREACTOR_WRITE;
  197. BReactor_SetFileDescriptorEvents(o->reactor, &o->bfd, o->poll_events);
  198. // inform sender we finished the packet
  199. PacketPassInterface_Done(&o->input);
  200. } while (0);
  201. if (events&BREACTOR_READ) do {
  202. ASSERT(o->output_packet)
  203. // try reading into the buffer
  204. int bytes = read(o->fd, o->output_packet, o->frame_mtu);
  205. if (bytes < 0) {
  206. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  207. // retry later
  208. break;
  209. }
  210. // report fatal error
  211. report_error(o);
  212. return;
  213. }
  214. ASSERT_FORCE(bytes <= o->frame_mtu)
  215. // set no output packet
  216. o->output_packet = NULL;
  217. // update events
  218. o->poll_events &= ~BREACTOR_READ;
  219. BReactor_SetFileDescriptorEvents(o->reactor, &o->bfd, o->poll_events);
  220. // inform receiver we finished the packet
  221. PacketRecvInterface_Done(&o->output, bytes);
  222. } while (0);
  223. }
  224. #endif
  225. void report_error (BTap *o)
  226. {
  227. #ifndef NDEBUG
  228. DEAD_ENTER(o->dead)
  229. #endif
  230. o->handler_error(o->handler_error_user);
  231. #ifndef NDEBUG
  232. ASSERT(DEAD_KILLED)
  233. DEAD_LEAVE(o->dead);
  234. #endif
  235. }
  236. void input_handler_send (BTap *o, uint8_t *data, int data_len)
  237. {
  238. ASSERT(data_len >= 0)
  239. ASSERT(data_len <= o->frame_mtu)
  240. ASSERT(o->input_packet_len == -1)
  241. DebugObject_Access(&o->d_obj);
  242. #ifdef BADVPN_USE_WINAPI
  243. if (!try_send(o, data, data_len)) {
  244. // write pending
  245. o->input_packet = data;
  246. o->input_packet_len = data_len;
  247. BReactor_EnableHandle(o->reactor, &o->input_bhandle);
  248. return;
  249. }
  250. #else
  251. int bytes = write(o->fd, data, data_len);
  252. if (bytes < 0) {
  253. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  254. // retry later in fd_handler
  255. // remember packet
  256. o->input_packet = data;
  257. o->input_packet_len = data_len;
  258. // update events
  259. o->poll_events |= BREACTOR_WRITE;
  260. BReactor_SetFileDescriptorEvents(o->reactor, &o->bfd, o->poll_events);
  261. return;
  262. }
  263. // malformed packets will cause errors, ignore them and act like
  264. // the packet was accepeted
  265. } else {
  266. if (bytes != data_len) {
  267. DEBUG("WARNING: written %d expected %d", bytes, data_len);
  268. }
  269. }
  270. #endif
  271. PacketPassInterface_Done(&o->input);
  272. }
  273. void input_handler_cancel (BTap *o)
  274. {
  275. DebugObject_Access(&o->d_obj);
  276. ASSERT(o->input_packet_len >= 0)
  277. #ifdef BADVPN_USE_WINAPI
  278. // disable handle event
  279. BReactor_DisableHandle(o->reactor, &o->input_bhandle);
  280. // cancel I/O on the device
  281. // this also cancels reading, so handle the aborted error code in read_handle_handler
  282. ASSERT_FORCE(CancelIo(o->device))
  283. // wait for it
  284. DWORD bytes;
  285. if (!GetOverlappedResult(o->device, &o->input_ol, &bytes, TRUE)) {
  286. DWORD error = GetLastError();
  287. if (error != ERROR_OPERATION_ABORTED) {
  288. DEBUG("WARNING: GetOverlappedResult (input) failed (%u)", error);
  289. }
  290. } else if (bytes != o->input_packet_len) {
  291. DEBUG("WARNING: written %d expected %d", (int)bytes, o->input_packet_len);
  292. }
  293. // reset event
  294. ASSERT_FORCE(ResetEvent(o->input_event))
  295. #else
  296. // update events
  297. o->poll_events &= ~BREACTOR_WRITE;
  298. BReactor_SetFileDescriptorEvents(o->reactor, &o->bfd, o->poll_events);
  299. #endif
  300. // set no input packet
  301. o->input_packet_len = -1;
  302. }
  303. void output_handler_recv (BTap *o, uint8_t *data)
  304. {
  305. ASSERT(data)
  306. ASSERT(!o->output_packet)
  307. DebugObject_Access(&o->d_obj);
  308. #ifdef BADVPN_USE_WINAPI
  309. int bytes;
  310. int res;
  311. if ((res = try_recv(o, data, &bytes)) < 0) {
  312. // report fatal error
  313. report_error(o);
  314. return;
  315. }
  316. if (!res) {
  317. // read pending
  318. o->output_packet = data;
  319. BReactor_EnableHandle(o->reactor, &o->output_bhandle);
  320. return;
  321. }
  322. #else
  323. // attempt read
  324. int bytes = read(o->fd, data, o->frame_mtu);
  325. if (bytes < 0) {
  326. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  327. // retry later in fd_handler
  328. // remember packet
  329. o->output_packet = data;
  330. // update events
  331. o->poll_events |= BREACTOR_READ;
  332. BReactor_SetFileDescriptorEvents(o->reactor, &o->bfd, o->poll_events);
  333. return;
  334. }
  335. // report fatal error
  336. report_error(o);
  337. return;
  338. }
  339. #endif
  340. ASSERT_FORCE(bytes <= o->frame_mtu)
  341. PacketRecvInterface_Done(&o->output, bytes);
  342. }
  343. int BTap_Init (BTap *o, BReactor *reactor, char *devname, BTap_handler_error handler_error, void *handler_error_user, int tun)
  344. {
  345. ASSERT(tun == 0 || tun == 1)
  346. // init arguments
  347. o->reactor = reactor;
  348. o->handler_error = handler_error;
  349. o->handler_error_user = handler_error_user;
  350. #ifdef BADVPN_USE_WINAPI
  351. if (tun) {
  352. DEBUG("TUN not supported on Windows");
  353. goto fail0;
  354. }
  355. char *device_component_id;
  356. char *device_name;
  357. char strdata[(devname ? strlen(devname) + 1 : 0)];
  358. if (!devname) {
  359. device_component_id = TAP_COMPONENT_ID;
  360. device_name = NULL;
  361. } else {
  362. strcpy(strdata, devname);
  363. char *colon = strstr(strdata, ":");
  364. if (!colon) {
  365. DEBUG("No colon in device string");
  366. goto fail0;
  367. }
  368. *colon = '\0';
  369. device_component_id = strdata;
  370. device_name = colon + 1;
  371. if (strlen(device_component_id) == 0) {
  372. device_component_id = TAP_COMPONENT_ID;
  373. }
  374. if (strlen(device_name) == 0) {
  375. device_name = NULL;
  376. }
  377. }
  378. DEBUG("Opening component ID %s, name %s", device_component_id, device_name);
  379. // open adapter key
  380. // used to find all devices with the given ComponentId
  381. HKEY adapter_key;
  382. if (RegOpenKeyEx(
  383. HKEY_LOCAL_MACHINE,
  384. ADAPTER_KEY,
  385. 0,
  386. KEY_READ,
  387. &adapter_key
  388. ) != ERROR_SUCCESS) {
  389. DEBUG("Error opening adapter key");
  390. goto fail0;
  391. }
  392. char net_cfg_instance_id[REGNAME_SIZE];
  393. int found = 0;
  394. DWORD i;
  395. for (i = 0;; i++) {
  396. DWORD len;
  397. DWORD type;
  398. char key_name[REGNAME_SIZE];
  399. len = sizeof(key_name);
  400. if (RegEnumKeyEx(adapter_key, i, key_name, &len, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) {
  401. break;
  402. }
  403. char unit_string[REGNAME_SIZE];
  404. snprintf(unit_string, sizeof(unit_string), "%s\\%s", ADAPTER_KEY, key_name);
  405. HKEY unit_key;
  406. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, unit_string, 0, KEY_READ, &unit_key) != ERROR_SUCCESS) {
  407. continue;
  408. }
  409. char component_id[REGNAME_SIZE];
  410. len = sizeof(component_id);
  411. if (RegQueryValueEx(unit_key, "ComponentId", NULL, &type, component_id, &len) != ERROR_SUCCESS || type != REG_SZ) {
  412. ASSERT_FORCE(RegCloseKey(unit_key) == ERROR_SUCCESS)
  413. continue;
  414. }
  415. len = sizeof(net_cfg_instance_id);
  416. if (RegQueryValueEx(unit_key, "NetCfgInstanceId", NULL, &type, net_cfg_instance_id, &len) != ERROR_SUCCESS || type != REG_SZ) {
  417. ASSERT_FORCE(RegCloseKey(unit_key) == ERROR_SUCCESS)
  418. continue;
  419. }
  420. RegCloseKey(unit_key);
  421. // check if ComponentId matches
  422. if (!strcmp(component_id, device_component_id)) {
  423. // if no name was given, use the first device with the given ComponentId
  424. if (!device_name) {
  425. found = 1;
  426. break;
  427. }
  428. // open connection key
  429. char conn_string[REGNAME_SIZE];
  430. snprintf(conn_string, sizeof(conn_string), "%s\\%s\\Connection", NETWORK_CONNECTIONS_KEY, net_cfg_instance_id);
  431. HKEY conn_key;
  432. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, conn_string, 0, KEY_READ, &conn_key) != ERROR_SUCCESS) {
  433. continue;
  434. }
  435. // read name
  436. char name[REGNAME_SIZE];
  437. len = sizeof(name);
  438. if (RegQueryValueEx(conn_key, "Name", NULL, &type, name, &len) != ERROR_SUCCESS || type != REG_SZ) {
  439. ASSERT_FORCE(RegCloseKey(conn_key) == ERROR_SUCCESS)
  440. continue;
  441. }
  442. ASSERT_FORCE(RegCloseKey(conn_key) == ERROR_SUCCESS)
  443. // check name
  444. if (!strcmp(name, device_name)) {
  445. found = 1;
  446. break;
  447. }
  448. }
  449. }
  450. ASSERT_FORCE(RegCloseKey(adapter_key) == ERROR_SUCCESS)
  451. if (!found) {
  452. DEBUG("Could not find TAP device");
  453. goto fail0;
  454. }
  455. char device_path[REGNAME_SIZE];
  456. snprintf(device_path, sizeof(device_path), "%s%s%s", USERMODEDEVICEDIR, net_cfg_instance_id, TAPSUFFIX);
  457. DEBUG("Opening device %s", device_path);
  458. if ((o->device = CreateFile(
  459. device_path,
  460. GENERIC_READ | GENERIC_WRITE,
  461. 0,
  462. 0,
  463. OPEN_EXISTING,
  464. FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED,
  465. 0
  466. )) == INVALID_HANDLE_VALUE) {
  467. DEBUG("CreateFile failed");
  468. goto fail0;
  469. }
  470. // get MTU
  471. ULONG umtu;
  472. DWORD len;
  473. if (!DeviceIoControl(o->device, TAP_IOCTL_GET_MTU, NULL, 0, &umtu, sizeof(umtu), &len, NULL)) {
  474. DEBUG("DeviceIoControl(TAP_IOCTL_GET_MTU) failed");
  475. goto fail1;
  476. }
  477. o->frame_mtu = umtu + BTAP_ETHERNET_HEADER_LENGTH;
  478. // set connected
  479. ULONG upstatus = TRUE;
  480. if (!DeviceIoControl(o->device, TAP_IOCTL_SET_MEDIA_STATUS, &upstatus, sizeof(upstatus), &upstatus, sizeof(upstatus), &len, NULL)) {
  481. DEBUG("DeviceIoControl(TAP_IOCTL_SET_MEDIA_STATUS) failed");
  482. goto fail1;
  483. }
  484. DEBUG("Device opened");
  485. // init input/output
  486. if (!(o->input_event = CreateEvent(NULL, TRUE, FALSE, NULL))) {
  487. DEBUG("CreateEvent failed");
  488. goto fail1;
  489. }
  490. if (!(o->output_event = CreateEvent(NULL, TRUE, FALSE, NULL))) {
  491. DEBUG("CreateEvent failed");
  492. goto fail2;
  493. }
  494. BHandle_Init(&o->input_bhandle, o->input_event, (BHandle_handler)write_handle_handler, o);
  495. BHandle_Init(&o->output_bhandle, o->output_event, (BHandle_handler)read_handle_handler, o);
  496. if (!BReactor_AddHandle(o->reactor, &o->input_bhandle)) {
  497. goto fail3;
  498. }
  499. if (!BReactor_AddHandle(o->reactor, &o->output_bhandle)) {
  500. goto fail4;
  501. }
  502. goto success;
  503. fail4:
  504. BReactor_RemoveHandle(o->reactor, &o->input_bhandle);
  505. fail3:
  506. ASSERT_FORCE(CloseHandle(o->output_event))
  507. fail2:
  508. ASSERT_FORCE(CloseHandle(o->input_event))
  509. fail1:
  510. ASSERT_FORCE(CloseHandle(o->device))
  511. fail0:
  512. return 0;
  513. #else
  514. // open device
  515. if ((o->fd = open("/dev/net/tun", O_RDWR)) < 0) {
  516. DEBUG("error opening device");
  517. goto fail0;
  518. }
  519. // configure device
  520. struct ifreq ifr;
  521. memset(&ifr, 0, sizeof(ifr));
  522. ifr.ifr_flags |= IFF_NO_PI;
  523. if (tun) {
  524. ifr.ifr_flags |= IFF_TUN;
  525. } else {
  526. ifr.ifr_flags |= IFF_TAP;
  527. }
  528. if (devname) {
  529. snprintf(ifr.ifr_name, IFNAMSIZ, "%s", devname);
  530. }
  531. if (ioctl(o->fd, TUNSETIFF, (void *)&ifr) < 0) {
  532. DEBUG("error configuring device");
  533. goto fail1;
  534. }
  535. strcpy(o->devname, ifr.ifr_name);
  536. // get MTU
  537. if (tun) {
  538. o->frame_mtu = 65535;
  539. } else {
  540. // open dummy socket for ioctls
  541. int sock = socket(AF_INET, SOCK_DGRAM, 0);
  542. if (sock < 0) {
  543. DEBUG("socket failed");
  544. goto fail1;
  545. }
  546. memset(&ifr, 0, sizeof(ifr));
  547. strcpy(ifr.ifr_name, o->devname);
  548. if (ioctl(sock, SIOCGIFMTU, (void *)&ifr) < 0) {
  549. DEBUG("error getting MTU");
  550. close(sock);
  551. goto fail1;
  552. }
  553. o->frame_mtu = ifr.ifr_mtu + BTAP_ETHERNET_HEADER_LENGTH;
  554. close(sock);
  555. }
  556. // set non-blocking
  557. if (fcntl(o->fd, F_SETFL, O_NONBLOCK) < 0) {
  558. DEBUG("cannot set non-blocking");
  559. goto fail1;
  560. }
  561. // init file descriptor object
  562. BFileDescriptor_Init(&o->bfd, o->fd, (BFileDescriptor_handler)fd_handler, o);
  563. if (!BReactor_AddFileDescriptor(o->reactor, &o->bfd)) {
  564. DEBUG("BReactor_AddFileDescriptor failed");
  565. goto fail1;
  566. }
  567. o->poll_events = 0;
  568. goto success;
  569. fail1:
  570. ASSERT_FORCE(close(o->fd) == 0)
  571. fail0:
  572. return 0;
  573. #endif
  574. success:
  575. // init dead var
  576. DEAD_INIT(o->dead);
  577. // init input
  578. PacketPassInterface_Init(&o->input, o->frame_mtu, (PacketPassInterface_handler_send)input_handler_send, o, BReactor_PendingGroup(o->reactor));
  579. PacketPassInterface_EnableCancel(&o->input, (PacketPassInterface_handler_cancel)input_handler_cancel);
  580. // init output
  581. PacketRecvInterface_Init(&o->output, o->frame_mtu, (PacketRecvInterface_handler_recv)output_handler_recv, o, BReactor_PendingGroup(o->reactor));
  582. // set no input packet
  583. o->input_packet_len = -1;
  584. // set no output packet
  585. o->output_packet = NULL;
  586. DebugObject_Init(&o->d_obj);
  587. return 1;
  588. }
  589. void BTap_Free (BTap *o)
  590. {
  591. DebugObject_Free(&o->d_obj);
  592. // free output
  593. PacketRecvInterface_Free(&o->output);
  594. // free input
  595. PacketPassInterface_Free(&o->input);
  596. // kill dead variable
  597. DEAD_KILL(o->dead);
  598. #ifdef BADVPN_USE_WINAPI
  599. // wait for pending i/o
  600. ASSERT_FORCE(CancelIo(o->device))
  601. DWORD bytes;
  602. DWORD error;
  603. if (o->input_packet_len >= 0) {
  604. if (!GetOverlappedResult(o->device, &o->input_ol, &bytes, TRUE)) {
  605. error = GetLastError();
  606. if (error != ERROR_OPERATION_ABORTED) {
  607. DEBUG("WARNING: GetOverlappedResult (input) failed (%u)", error);
  608. }
  609. }
  610. }
  611. if (o->output_packet) {
  612. if (!GetOverlappedResult(o->device, &o->output_ol, &bytes, TRUE)) {
  613. error = GetLastError();
  614. if (error != ERROR_OPERATION_ABORTED) {
  615. DEBUG("WARNING: GetOverlappedResult (output) failed (%u)", error);
  616. }
  617. }
  618. }
  619. // free stuff
  620. BReactor_RemoveHandle(o->reactor, &o->input_bhandle);
  621. BReactor_RemoveHandle(o->reactor, &o->output_bhandle);
  622. ASSERT_FORCE(CloseHandle(o->output_event))
  623. ASSERT_FORCE(CloseHandle(o->input_event))
  624. ASSERT_FORCE(CloseHandle(o->device))
  625. #else
  626. // free BFileDescriptor
  627. BReactor_RemoveFileDescriptor(o->reactor, &o->bfd);
  628. // close file descriptor
  629. ASSERT_FORCE(close(o->fd) == 0)
  630. #endif
  631. }
  632. int BTap_GetMTU (BTap *o)
  633. {
  634. DebugObject_Access(&o->d_obj);
  635. return o->frame_mtu;
  636. }
  637. PacketPassInterface * BTap_GetInput (BTap *o)
  638. {
  639. DebugObject_Access(&o->d_obj);
  640. return &o->input;
  641. }
  642. PacketRecvInterface * BTap_GetOutput (BTap *o)
  643. {
  644. DebugObject_Access(&o->d_obj);
  645. return &o->output;
  646. }