BTap.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. /**
  2. * @file BTap.c
  3. * @author Ambroz Bizjak <[email protected]>
  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) {
  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. // init arguments
  156. o->reactor = reactor;
  157. o->handler_error = handler_error;
  158. o->handler_error_user = handler_error_user;
  159. #ifdef BADVPN_USE_WINAPI
  160. // parse device specification
  161. if (!devname) {
  162. BLog(BLOG_ERROR, "no device specification provided");
  163. return 0;
  164. }
  165. int devname_len = strlen(devname);
  166. char device_component_id[devname_len + 1];
  167. char device_name[devname_len + 1];
  168. uint32_t tun_addrs[3];
  169. if (tun) {
  170. if (!tapwin32_parse_tun_spec(devname, device_component_id, device_name, tun_addrs)) {
  171. BLog(BLOG_ERROR, "failed to parse TUN device specification");
  172. return 0;
  173. }
  174. } else {
  175. if (!tapwin32_parse_tap_spec(devname, device_component_id, device_name)) {
  176. BLog(BLOG_ERROR, "failed to parse TAP device specification");
  177. return 0;
  178. }
  179. }
  180. // locate device path
  181. char device_path[TAPWIN32_MAX_REG_SIZE];
  182. BLog(BLOG_INFO, "Looking for TAP-Win32 with component ID %s, name %s", device_component_id, device_name);
  183. if (!tapwin32_find_device(device_component_id, device_name, &device_path)) {
  184. BLog(BLOG_ERROR, "Could not find device");
  185. goto fail0;
  186. }
  187. // open device
  188. BLog(BLOG_INFO, "Opening device %s", device_path);
  189. o->device = CreateFile(device_path, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM|FILE_FLAG_OVERLAPPED, 0);
  190. if (o->device == INVALID_HANDLE_VALUE) {
  191. BLog(BLOG_ERROR, "CreateFile failed");
  192. goto fail0;
  193. }
  194. // set TUN if needed
  195. DWORD len;
  196. if (tun) {
  197. if (!DeviceIoControl(o->device, TAP_IOCTL_CONFIG_TUN, tun_addrs, sizeof(tun_addrs), tun_addrs, sizeof(tun_addrs), &len, NULL)) {
  198. BLog(BLOG_ERROR, "DeviceIoControl(TAP_IOCTL_CONFIG_TUN) failed");
  199. goto fail1;
  200. }
  201. }
  202. // get MTU
  203. ULONG umtu;
  204. if (!DeviceIoControl(o->device, TAP_IOCTL_GET_MTU, NULL, 0, &umtu, sizeof(umtu), &len, NULL)) {
  205. BLog(BLOG_ERROR, "DeviceIoControl(TAP_IOCTL_GET_MTU) failed");
  206. goto fail1;
  207. }
  208. if (tun) {
  209. o->frame_mtu = umtu;
  210. } else {
  211. o->frame_mtu = umtu + BTAP_ETHERNET_HEADER_LENGTH;
  212. }
  213. // set connected
  214. ULONG upstatus = TRUE;
  215. if (!DeviceIoControl(o->device, TAP_IOCTL_SET_MEDIA_STATUS, &upstatus, sizeof(upstatus), &upstatus, sizeof(upstatus), &len, NULL)) {
  216. BLog(BLOG_ERROR, "DeviceIoControl(TAP_IOCTL_SET_MEDIA_STATUS) failed");
  217. goto fail1;
  218. }
  219. BLog(BLOG_INFO, "Device opened");
  220. // associate device with IOCP
  221. if (!CreateIoCompletionPort(o->device, BReactor_GetIOCPHandle(o->reactor), 0, 0)) {
  222. BLog(BLOG_ERROR, "CreateIoCompletionPort failed");
  223. goto fail1;
  224. }
  225. // init send olap
  226. BReactorIOCPOverlapped_Init(&o->send_olap, o->reactor, o, NULL);
  227. // init recv olap
  228. BReactorIOCPOverlapped_Init(&o->recv_olap, o->reactor, o, (BReactorIOCPOverlapped_handler)recv_olap_handler);
  229. goto success;
  230. fail1:
  231. ASSERT_FORCE(CloseHandle(o->device))
  232. fail0:
  233. return 0;
  234. #endif
  235. #if defined(BADVPN_LINUX) || defined(BADVPN_FREEBSD)
  236. char devname_real[IFNAMSIZ];
  237. #ifdef BADVPN_LINUX
  238. // open device
  239. if ((o->fd = open("/dev/net/tun", O_RDWR)) < 0) {
  240. BLog(BLOG_ERROR, "error opening device");
  241. goto fail0;
  242. }
  243. // configure device
  244. struct ifreq ifr;
  245. memset(&ifr, 0, sizeof(ifr));
  246. ifr.ifr_flags |= IFF_NO_PI;
  247. if (tun) {
  248. ifr.ifr_flags |= IFF_TUN;
  249. } else {
  250. ifr.ifr_flags |= IFF_TAP;
  251. }
  252. if (devname) {
  253. snprintf(ifr.ifr_name, IFNAMSIZ, "%s", devname);
  254. }
  255. if (ioctl(o->fd, TUNSETIFF, (void *)&ifr) < 0) {
  256. BLog(BLOG_ERROR, "error configuring device");
  257. goto fail1;
  258. }
  259. strcpy(devname_real, ifr.ifr_name);
  260. #endif
  261. #ifdef BADVPN_FREEBSD
  262. if (tun) {
  263. BLog(BLOG_ERROR, "TUN not supported on FreeBSD");
  264. goto fail0;
  265. }
  266. if (!devname) {
  267. BLog(BLOG_ERROR, "no device specified");
  268. goto fail0;
  269. }
  270. // open device
  271. char devnode[10 + IFNAMSIZ];
  272. snprintf(devnode, sizeof(devnode), "/dev/%s", devname);
  273. if ((o->fd = open(devnode, O_RDWR)) < 0) {
  274. BLog(BLOG_ERROR, "error opening device");
  275. goto fail0;
  276. }
  277. // get name
  278. struct ifreq ifr;
  279. memset(&ifr, 0, sizeof(ifr));
  280. if (ioctl(o->fd, TAPGIFNAME, (void *)&ifr) < 0) {
  281. BLog(BLOG_ERROR, "error configuring device");
  282. goto fail1;
  283. }
  284. strcpy(devname_real, ifr.ifr_name);
  285. #endif
  286. // get MTU
  287. // open dummy socket for ioctls
  288. int sock = socket(AF_INET, SOCK_DGRAM, 0);
  289. if (sock < 0) {
  290. BLog(BLOG_ERROR, "socket failed");
  291. goto fail1;
  292. }
  293. memset(&ifr, 0, sizeof(ifr));
  294. strcpy(ifr.ifr_name, devname_real);
  295. if (ioctl(sock, SIOCGIFMTU, (void *)&ifr) < 0) {
  296. BLog(BLOG_ERROR, "error getting MTU");
  297. close(sock);
  298. goto fail1;
  299. }
  300. if (tun) {
  301. o->frame_mtu = ifr.ifr_mtu;
  302. } else {
  303. o->frame_mtu = ifr.ifr_mtu + BTAP_ETHERNET_HEADER_LENGTH;
  304. }
  305. close(sock);
  306. // set non-blocking
  307. if (fcntl(o->fd, F_SETFL, O_NONBLOCK) < 0) {
  308. BLog(BLOG_ERROR, "cannot set non-blocking");
  309. goto fail1;
  310. }
  311. // init file descriptor object
  312. BFileDescriptor_Init(&o->bfd, o->fd, (BFileDescriptor_handler)fd_handler, o);
  313. if (!BReactor_AddFileDescriptor(o->reactor, &o->bfd)) {
  314. BLog(BLOG_ERROR, "BReactor_AddFileDescriptor failed");
  315. goto fail1;
  316. }
  317. o->poll_events = 0;
  318. goto success;
  319. fail1:
  320. ASSERT_FORCE(close(o->fd) == 0)
  321. fail0:
  322. return 0;
  323. #endif
  324. success:
  325. // init output
  326. PacketRecvInterface_Init(&o->output, o->frame_mtu, (PacketRecvInterface_handler_recv)output_handler_recv, o, BReactor_PendingGroup(o->reactor));
  327. // set no output packet
  328. o->output_packet = NULL;
  329. DebugError_Init(&o->d_err, BReactor_PendingGroup(o->reactor));
  330. DebugObject_Init(&o->d_obj);
  331. return 1;
  332. }
  333. void BTap_Free (BTap *o)
  334. {
  335. DebugObject_Free(&o->d_obj);
  336. DebugError_Free(&o->d_err);
  337. // free output
  338. PacketRecvInterface_Free(&o->output);
  339. #ifdef BADVPN_USE_WINAPI
  340. // cancel I/O
  341. ASSERT_FORCE(CancelIo(o->device))
  342. // wait receiving to finish
  343. if (o->output_packet) {
  344. BLog(BLOG_DEBUG, "waiting for receiving to finish");
  345. BReactorIOCPOverlapped_Wait(&o->recv_olap, NULL, NULL);
  346. }
  347. // free recv olap
  348. BReactorIOCPOverlapped_Free(&o->recv_olap);
  349. // free send olap
  350. BReactorIOCPOverlapped_Free(&o->send_olap);
  351. // close device
  352. ASSERT_FORCE(CloseHandle(o->device))
  353. #else
  354. // free BFileDescriptor
  355. BReactor_RemoveFileDescriptor(o->reactor, &o->bfd);
  356. // close file descriptor
  357. ASSERT_FORCE(close(o->fd) == 0)
  358. #endif
  359. }
  360. int BTap_GetMTU (BTap *o)
  361. {
  362. DebugObject_Access(&o->d_obj);
  363. return o->frame_mtu;
  364. }
  365. void BTap_Send (BTap *o, uint8_t *data, int data_len)
  366. {
  367. DebugObject_Access(&o->d_obj);
  368. DebugError_AssertNoError(&o->d_err);
  369. ASSERT(data_len >= 0)
  370. ASSERT(data_len <= o->frame_mtu)
  371. #ifdef BADVPN_USE_WINAPI
  372. // ignore frames without an Ethernet header, or we get errors in WriteFile
  373. if (data_len < 14) {
  374. return;
  375. }
  376. memset(&o->send_olap.olap, 0, sizeof(o->send_olap.olap));
  377. // write
  378. BOOL res = WriteFile(o->device, data, data_len, NULL, &o->send_olap.olap);
  379. if (res == FALSE && GetLastError() != ERROR_IO_PENDING) {
  380. BLog(BLOG_ERROR, "WriteFile failed (%u)", GetLastError());
  381. return;
  382. }
  383. // wait
  384. int succeeded;
  385. DWORD bytes;
  386. BReactorIOCPOverlapped_Wait(&o->send_olap, &succeeded, &bytes);
  387. if (!succeeded) {
  388. BLog(BLOG_ERROR, "write operation failed");
  389. } else {
  390. ASSERT(bytes >= 0)
  391. ASSERT(bytes <= data_len)
  392. if (bytes < data_len) {
  393. BLog(BLOG_ERROR, "write operation didn't write everything");
  394. }
  395. }
  396. #else
  397. int bytes = write(o->fd, data, data_len);
  398. if (bytes < 0) {
  399. // malformed packets will cause errors, ignore them and act like
  400. // the packet was accepeted
  401. } else {
  402. if (bytes != data_len) {
  403. BLog(BLOG_WARNING, "written %d expected %d", bytes, data_len);
  404. }
  405. }
  406. #endif
  407. }
  408. PacketRecvInterface * BTap_GetOutput (BTap *o)
  409. {
  410. DebugObject_Access(&o->d_obj);
  411. return &o->output;
  412. }