BTap.c 18 KB

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