tun2socks.c 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  1. /**
  2. * @file tun2socks.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 <stdint.h>
  23. #include <stdio.h>
  24. #include <stddef.h>
  25. #include <string.h>
  26. #include <misc/version.h>
  27. #include <misc/loggers_string.h>
  28. #include <misc/loglevel.h>
  29. #include <misc/minmax.h>
  30. #include <misc/offset.h>
  31. #include <misc/dead.h>
  32. #include <structure/LinkedList2.h>
  33. #include <system/BLog.h>
  34. #include <system/BReactor.h>
  35. #include <system/BSocket.h>
  36. #include <system/BSignal.h>
  37. #include <system/BAddr.h>
  38. #include <flow/PacketBuffer.h>
  39. #include <flow/BufferWriter.h>
  40. #include <flow/SinglePacketBuffer.h>
  41. #include <socksclient/BSocksClient.h>
  42. #include <tuntap/BTap.h>
  43. #include <lwip/init.h>
  44. #include <lwip/tcp_impl.h>
  45. #include <lwip/netif.h>
  46. #include <lwip/tcp.h>
  47. #ifndef BADVPN_USE_WINAPI
  48. #include <system/BLog_syslog.h>
  49. #endif
  50. #include <tun2socks/tun2socks.h>
  51. #include <generated/blog_channel_tun2socks.h>
  52. #define LOGGER_STDOUT 1
  53. #define LOGGER_SYSLOG 2
  54. #define SYNC_DECL \
  55. BPending sync_mark; \
  56. #define SYNC_FROMHERE \
  57. BPending_Init(&sync_mark, BReactor_PendingGroup(&ss), NULL, NULL); \
  58. BPending_Set(&sync_mark);
  59. #define SYNC_BREAK \
  60. BPending_Free(&sync_mark);
  61. #define SYNC_COMMIT \
  62. BReactor_Synchronize(&ss, &sync_mark); \
  63. BPending_Free(&sync_mark);
  64. // command-line options
  65. struct {
  66. int help;
  67. int version;
  68. int logger;
  69. #ifndef BADVPN_USE_WINAPI
  70. char *logger_syslog_facility;
  71. char *logger_syslog_ident;
  72. #endif
  73. int loglevel;
  74. int loglevels[BLOG_NUM_CHANNELS];
  75. char *tundev;
  76. char *netif_ipaddr;
  77. char *netif_netmask;
  78. char *socks_server_addr;
  79. } options;
  80. // TCP client
  81. struct tcp_client {
  82. dead_t dead;
  83. dead_t dead_client;
  84. LinkedList2Node list_node;
  85. BAddr local_addr;
  86. BAddr remote_addr;
  87. struct tcp_pcb *pcb;
  88. int client_closed;
  89. uint8_t buf[TCP_WND];
  90. int buf_used;
  91. BSocksClient socks_client;
  92. int socks_up;
  93. int socks_closed;
  94. StreamPassInterface *socks_send_if;
  95. int socks_send_prev_buf_used;
  96. BPending socks_send_finished_job;
  97. StreamRecvInterface *socks_recv_if;
  98. uint8_t socks_recv_buf[CLIENT_SOCKS_RECV_BUF_SIZE];
  99. int socks_recv_buf_used;
  100. int socks_recv_buf_sent;
  101. int socks_recv_waiting;
  102. int socks_recv_tcp_pending;
  103. };
  104. // IP address of netif
  105. BIPAddr netif_ipaddr;
  106. // netmask of netif
  107. BIPAddr netif_netmask;
  108. // SOCKS server address
  109. BAddr socks_server_addr;
  110. // reactor
  111. BReactor ss;
  112. // set to 1 by terminate
  113. int quitting;
  114. // TUN device
  115. BTap device;
  116. // device writing
  117. BufferWriter device_write_writer;
  118. PacketBuffer device_write_buffer;
  119. // device reading
  120. SinglePacketBuffer device_read_buffer;
  121. PacketPassInterface device_read_interface;
  122. // TCP timer
  123. BTimer tcp_timer;
  124. // job for initializing lwip
  125. BPending lwip_init_job;
  126. // lwip netif
  127. int have_netif;
  128. struct netif netif;
  129. // lwip TCP listener
  130. struct tcp_pcb *listener;
  131. // TCP clients
  132. LinkedList2 tcp_clients;
  133. // number of clients
  134. int num_clients;
  135. static void terminate (void);
  136. static void print_help (const char *name);
  137. static void print_version (void);
  138. static int parse_arguments (int argc, char *argv[]);
  139. static int process_arguments (void);
  140. static void signal_handler (void *unused);
  141. static void lwip_init_job_hadler (void *unused);
  142. static void tcp_timer_handler (void *unused);
  143. static void device_error_handler (void *unused);
  144. static void device_read_handler_send (void *unused, uint8_t *data, int data_len);
  145. static err_t netif_init_func (struct netif *netif);
  146. static err_t netif_output_func (struct netif *netif, struct pbuf *p, ip_addr_t *ipaddr);
  147. static void client_log (struct tcp_client *client, int level, const char *fmt, ...);
  148. static err_t listener_accept_func (void *arg, struct tcp_pcb *newpcb, err_t err);
  149. static void client_handle_freed_client (struct tcp_client *client, int was_abrt);
  150. static int client_free_client (struct tcp_client *client);
  151. static void client_abort_client (struct tcp_client *client);
  152. static void client_free_socks (struct tcp_client *client);
  153. static void client_murder (struct tcp_client *client);
  154. static void client_dealloc (struct tcp_client *client);
  155. static void client_err_func (void *arg, err_t err);
  156. static err_t client_recv_func (void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err);
  157. static void client_socks_handler (struct tcp_client *client, int event);
  158. static void client_send_to_socks (struct tcp_client *client);
  159. static void client_socks_send_handler_done (struct tcp_client *client, int data_len);
  160. static void client_socks_send_finished_job_handler (struct tcp_client *client);
  161. static void client_socks_recv_initiate (struct tcp_client *client);
  162. static void client_socks_recv_handler_done (struct tcp_client *client, int data_len);
  163. static int client_socks_recv_send_out (struct tcp_client *client);
  164. static err_t client_sent_func (void *arg, struct tcp_pcb *tpcb, u16_t len);
  165. int main (int argc, char **argv)
  166. {
  167. if (argc <= 0) {
  168. return 1;
  169. }
  170. // parse command-line arguments
  171. if (!parse_arguments(argc, argv)) {
  172. fprintf(stderr, "Failed to parse arguments\n");
  173. print_help(argv[0]);
  174. goto fail0;
  175. }
  176. // handle --help and --version
  177. if (options.help) {
  178. print_version();
  179. print_help(argv[0]);
  180. return 0;
  181. }
  182. if (options.version) {
  183. print_version();
  184. return 0;
  185. }
  186. // initialize logger
  187. switch (options.logger) {
  188. case LOGGER_STDOUT:
  189. BLog_InitStdout();
  190. break;
  191. #ifndef BADVPN_USE_WINAPI
  192. case LOGGER_SYSLOG:
  193. if (!BLog_InitSyslog(options.logger_syslog_ident, options.logger_syslog_facility)) {
  194. fprintf(stderr, "Failed to initialize syslog logger\n");
  195. goto fail0;
  196. }
  197. break;
  198. #endif
  199. default:
  200. ASSERT(0);
  201. }
  202. // configure logger channels
  203. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  204. if (options.loglevels[i] >= 0) {
  205. BLog_SetChannelLoglevel(i, options.loglevels[i]);
  206. }
  207. else if (options.loglevel >= 0) {
  208. BLog_SetChannelLoglevel(i, options.loglevel);
  209. }
  210. }
  211. BLog(BLOG_NOTICE, "initializing "GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION);
  212. // initialize sockets
  213. if (BSocket_GlobalInit() < 0) {
  214. BLog(BLOG_ERROR, "BSocket_GlobalInit failed");
  215. goto fail1;
  216. }
  217. // process arguments
  218. if (!process_arguments()) {
  219. BLog(BLOG_ERROR, "Failed to process arguments");
  220. goto fail1;
  221. }
  222. // init time
  223. BTime_Init();
  224. // init reactor
  225. if (!BReactor_Init(&ss)) {
  226. BLog(BLOG_ERROR, "BReactor_Init failed");
  227. goto fail1;
  228. }
  229. // set not quitting
  230. quitting = 0;
  231. // setup signal handler
  232. if (!BSignal_Init(&ss, signal_handler, NULL)) {
  233. BLog(BLOG_ERROR, "BSignal_Init failed");
  234. goto fail2;
  235. }
  236. // init TUN device
  237. if (!BTap_Init(&device, &ss, options.tundev, device_error_handler, NULL, 1)) {
  238. BLog(BLOG_ERROR, "BTap_Init failed");
  239. goto fail3;
  240. }
  241. // NOTE: the order of the following is important:
  242. // first device writing must evaluate,
  243. // then lwip (so it can send packets to the device),
  244. // then device reading (so it can pass received packets to lwip).
  245. // init device reading
  246. PacketPassInterface_Init(&device_read_interface, BTap_GetMTU(&device), device_read_handler_send, NULL, BReactor_PendingGroup(&ss));
  247. if (!SinglePacketBuffer_Init(&device_read_buffer, BTap_GetOutput(&device), &device_read_interface, BReactor_PendingGroup(&ss))) {
  248. BLog(BLOG_ERROR, "SinglePacketBuffer_Init failed");
  249. goto fail4;
  250. }
  251. // init lwip init job
  252. BPending_Init(&lwip_init_job, BReactor_PendingGroup(&ss), lwip_init_job_hadler, NULL);
  253. BPending_Set(&lwip_init_job);
  254. // init device writing
  255. BufferWriter_Init(&device_write_writer, BTap_GetMTU(&device), BReactor_PendingGroup(&ss));
  256. if (!PacketBuffer_Init(&device_write_buffer, BufferWriter_GetOutput(&device_write_writer), BTap_GetInput(&device), DEVICE_WRITE_BUFFER_SIZE, BReactor_PendingGroup(&ss))) {
  257. BLog(BLOG_ERROR, "PacketBuffer_Init failed");
  258. goto fail5;
  259. }
  260. // init TCP timer
  261. // it won't trigger before lwip is initialized, becuase the lwip init is a job
  262. BTimer_Init(&tcp_timer, TCP_TMR_INTERVAL, tcp_timer_handler, NULL);
  263. BReactor_SetTimer(&ss, &tcp_timer);
  264. // set no netif
  265. have_netif = 0;
  266. // set no listener
  267. listener = NULL;
  268. // init clients list
  269. LinkedList2_Init(&tcp_clients);
  270. // init number of clients
  271. num_clients = 0;
  272. // enter event loop
  273. BLog(BLOG_NOTICE, "entering event loop");
  274. BReactor_Exec(&ss);
  275. // free clients
  276. LinkedList2Node *node;
  277. while (node = LinkedList2_GetFirst(&tcp_clients)) {
  278. struct tcp_client *client = UPPER_OBJECT(node, struct tcp_client, list_node);
  279. client_murder(client);
  280. }
  281. // free listener
  282. if (listener) {
  283. tcp_close(listener);
  284. }
  285. // free netif
  286. if (have_netif) {
  287. netif_remove(&netif);
  288. }
  289. BReactor_RemoveTimer(&ss, &tcp_timer);
  290. PacketBuffer_Free(&device_write_buffer);
  291. fail5:
  292. BufferWriter_Free(&device_write_writer);
  293. BPending_Free(&lwip_init_job);
  294. SinglePacketBuffer_Free(&device_read_buffer);
  295. fail4:
  296. PacketPassInterface_Free(&device_read_interface);
  297. BTap_Free(&device);
  298. fail3:
  299. BSignal_Finish();
  300. fail2:
  301. BReactor_Free(&ss);
  302. fail1:
  303. BLog(BLOG_NOTICE, "exiting");
  304. BLog_Free();
  305. fail0:
  306. DebugObjectGlobal_Finish();
  307. return 1;
  308. }
  309. void terminate (void)
  310. {
  311. ASSERT(!quitting)
  312. BLog(BLOG_NOTICE, "tearing down");
  313. // set quitting
  314. quitting = 1;
  315. // exit event loop
  316. BReactor_Quit(&ss, 1);
  317. }
  318. void print_help (const char *name)
  319. {
  320. printf(
  321. "Usage:\n"
  322. " %s\n"
  323. " [--help]\n"
  324. " [--version]\n"
  325. " [--logger <"LOGGERS_STRING">]\n"
  326. #ifndef BADVPN_USE_WINAPI
  327. " (logger=syslog?\n"
  328. " [--syslog-facility <string>]\n"
  329. " [--syslog-ident <string>]\n"
  330. " )\n"
  331. #endif
  332. " [--loglevel <0-5/none/error/warning/notice/info/debug>]\n"
  333. " [--channel-loglevel <channel-name> <0-5/none/error/warning/notice/info/debug>] ...\n"
  334. " [--tundev <name>]\n"
  335. " --netif-ipaddr <ipaddr>\n"
  336. " --netif-netmask <ipnetmask>\n"
  337. " --socks-server-addr <addr>\n"
  338. "Address format is a.b.c.d:port (IPv4) or [addr]:port (IPv6).\n",
  339. name
  340. );
  341. }
  342. void print_version (void)
  343. {
  344. printf(GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION"\n"GLOBAL_COPYRIGHT_NOTICE"\n");
  345. }
  346. int parse_arguments (int argc, char *argv[])
  347. {
  348. if (argc <= 0) {
  349. return 0;
  350. }
  351. options.help = 0;
  352. options.version = 0;
  353. options.logger = LOGGER_STDOUT;
  354. #ifndef BADVPN_USE_WINAPI
  355. options.logger_syslog_facility = "daemon";
  356. options.logger_syslog_ident = argv[0];
  357. #endif
  358. options.loglevel = -1;
  359. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  360. options.loglevels[i] = -1;
  361. }
  362. options.tundev = NULL;
  363. options.netif_ipaddr = NULL;
  364. options.netif_netmask = NULL;
  365. options.socks_server_addr = NULL;
  366. int i;
  367. for (i = 1; i < argc; i++) {
  368. char *arg = argv[i];
  369. if (!strcmp(arg, "--help")) {
  370. options.help = 1;
  371. }
  372. else if (!strcmp(arg, "--version")) {
  373. options.version = 1;
  374. }
  375. else if (!strcmp(arg, "--logger")) {
  376. if (1 >= argc - i) {
  377. fprintf(stderr, "%s: requires an argument\n", arg);
  378. return 0;
  379. }
  380. char *arg2 = argv[i + 1];
  381. if (!strcmp(arg2, "stdout")) {
  382. options.logger = LOGGER_STDOUT;
  383. }
  384. #ifndef BADVPN_USE_WINAPI
  385. else if (!strcmp(arg2, "syslog")) {
  386. options.logger = LOGGER_SYSLOG;
  387. }
  388. #endif
  389. else {
  390. fprintf(stderr, "%s: wrong argument\n", arg);
  391. return 0;
  392. }
  393. i++;
  394. }
  395. #ifndef BADVPN_USE_WINAPI
  396. else if (!strcmp(arg, "--syslog-facility")) {
  397. if (1 >= argc - i) {
  398. fprintf(stderr, "%s: requires an argument\n", arg);
  399. return 0;
  400. }
  401. options.logger_syslog_facility = argv[i + 1];
  402. i++;
  403. }
  404. else if (!strcmp(arg, "--syslog-ident")) {
  405. if (1 >= argc - i) {
  406. fprintf(stderr, "%s: requires an argument\n", arg);
  407. return 0;
  408. }
  409. options.logger_syslog_ident = argv[i + 1];
  410. i++;
  411. }
  412. #endif
  413. else if (!strcmp(arg, "--loglevel")) {
  414. if (1 >= argc - i) {
  415. fprintf(stderr, "%s: requires an argument\n", arg);
  416. return 0;
  417. }
  418. if ((options.loglevel = parse_loglevel(argv[i + 1])) < 0) {
  419. fprintf(stderr, "%s: wrong argument\n", arg);
  420. return 0;
  421. }
  422. i++;
  423. }
  424. else if (!strcmp(arg, "--channel-loglevel")) {
  425. if (2 >= argc - i) {
  426. fprintf(stderr, "%s: requires two arguments\n", arg);
  427. return 0;
  428. }
  429. int channel = BLogGlobal_GetChannelByName(argv[i + 1]);
  430. if (channel < 0) {
  431. fprintf(stderr, "%s: wrong channel argument\n", arg);
  432. return 0;
  433. }
  434. int loglevel = parse_loglevel(argv[i + 2]);
  435. if (loglevel < 0) {
  436. fprintf(stderr, "%s: wrong loglevel argument\n", arg);
  437. return 0;
  438. }
  439. options.loglevels[channel] = loglevel;
  440. i += 2;
  441. }
  442. else if (!strcmp(arg, "--tundev")) {
  443. if (1 >= argc - i) {
  444. fprintf(stderr, "%s: requires an argument\n", arg);
  445. return 0;
  446. }
  447. options.tundev = argv[i + 1];
  448. i++;
  449. }
  450. else if (!strcmp(arg, "--netif-ipaddr")) {
  451. if (1 >= argc - i) {
  452. fprintf(stderr, "%s: requires an argument\n", arg);
  453. return 0;
  454. }
  455. options.netif_ipaddr = argv[i + 1];
  456. i++;
  457. }
  458. else if (!strcmp(arg, "--netif-netmask")) {
  459. if (1 >= argc - i) {
  460. fprintf(stderr, "%s: requires an argument\n", arg);
  461. return 0;
  462. }
  463. options.netif_netmask = argv[i + 1];
  464. i++;
  465. }
  466. else if (!strcmp(arg, "--socks-server-addr")) {
  467. if (1 >= argc - i) {
  468. fprintf(stderr, "%s: requires an argument\n", arg);
  469. return 0;
  470. }
  471. options.socks_server_addr = argv[i + 1];
  472. i++;
  473. }
  474. else {
  475. fprintf(stderr, "unknown option: %s\n", arg);
  476. return 0;
  477. }
  478. }
  479. if (options.help || options.version) {
  480. return 1;
  481. }
  482. if (!options.netif_ipaddr) {
  483. fprintf(stderr, "--netif-ipaddr is required\n");
  484. return 0;
  485. }
  486. if (!options.netif_netmask) {
  487. fprintf(stderr, "--netif-netmask is required\n");
  488. return 0;
  489. }
  490. if (!options.socks_server_addr) {
  491. fprintf(stderr, "--socks-server-addr is required\n");
  492. return 0;
  493. }
  494. return 1;
  495. }
  496. int process_arguments (void)
  497. {
  498. // resolve netif ipaddr
  499. if (!BIPAddr_Resolve(&netif_ipaddr, options.netif_ipaddr, 0)) {
  500. BLog(BLOG_ERROR, "netif ipaddr: BIPAddr_Resolve failed");
  501. return 0;
  502. }
  503. if (netif_ipaddr.type != BADDR_TYPE_IPV4) {
  504. BLog(BLOG_ERROR, "netif ipaddr: must be an IPv4 address");
  505. return 0;
  506. }
  507. // resolve netif netmask
  508. if (!BIPAddr_Resolve(&netif_netmask, options.netif_netmask, 0)) {
  509. BLog(BLOG_ERROR, "netif netmask: BIPAddr_Resolve failed");
  510. return 0;
  511. }
  512. if (netif_netmask.type != BADDR_TYPE_IPV4) {
  513. BLog(BLOG_ERROR, "netif netmask: must be an IPv4 address");
  514. return 0;
  515. }
  516. // resolve SOCKS server address
  517. if (!BAddr_Parse2(&socks_server_addr, options.socks_server_addr, NULL, 0, 0)) {
  518. BLog(BLOG_ERROR, "socks server addr: BAddr_Parse2 failed");
  519. return 0;
  520. }
  521. return 1;
  522. }
  523. void signal_handler (void *unused)
  524. {
  525. ASSERT(!quitting)
  526. BLog(BLOG_NOTICE, "termination requested");
  527. terminate();
  528. }
  529. void lwip_init_job_hadler (void *unused)
  530. {
  531. ASSERT(!quitting)
  532. ASSERT(netif_ipaddr.type == BADDR_TYPE_IPV4)
  533. ASSERT(netif_netmask.type == BADDR_TYPE_IPV4)
  534. ASSERT(!have_netif)
  535. BLog(BLOG_DEBUG, "lwip init");
  536. // NOTE: the device may fail during this, but there's no harm in not checking
  537. // for that at every step
  538. int res;
  539. // init lwip
  540. lwip_init();
  541. // make addresses for netif
  542. ip_addr_t addr;
  543. addr.addr = netif_ipaddr.ipv4;
  544. ip_addr_t netmask;
  545. netmask.addr = netif_netmask.ipv4;
  546. ip_addr_t gw;
  547. ip_addr_set_any(&gw);
  548. // init netif
  549. if (!netif_add(&netif, &addr, &netmask, &gw, NULL, netif_init_func, ip_input)) {
  550. BLog(BLOG_ERROR, "netif_add failed");
  551. goto fail;
  552. }
  553. have_netif = 1;
  554. // set netif up
  555. netif_set_up(&netif);
  556. // set netif pretend TCP
  557. netif_set_pretend_tcp(&netif, 1);
  558. // init listener
  559. struct tcp_pcb *l = tcp_new();
  560. if (!l) {
  561. BLog(BLOG_ERROR, "tcp_new failed");
  562. goto fail;
  563. }
  564. // bind listener
  565. if (tcp_bind_to_netif(l, "ho0") != ERR_OK) {
  566. BLog(BLOG_ERROR, "tcp_bind_to_netif failed");
  567. tcp_close(l);
  568. goto fail;
  569. }
  570. // listen listener
  571. struct tcp_pcb *l2 = tcp_listen(l);
  572. if (!l2) {
  573. BLog(BLOG_ERROR, "tcp_listen failed");
  574. tcp_close(l);
  575. goto fail;
  576. }
  577. listener = l2;
  578. // setup accept handler
  579. tcp_accept(listener, listener_accept_func);
  580. return;
  581. fail:
  582. if (!quitting) {
  583. terminate();
  584. }
  585. }
  586. void tcp_timer_handler (void *unused)
  587. {
  588. ASSERT(!quitting)
  589. BLog(BLOG_DEBUG, "TCP timer");
  590. // schedule next timer
  591. // TODO: calculate timeout so we don't drift
  592. BReactor_SetTimer(&ss, &tcp_timer);
  593. tcp_tmr();
  594. return;
  595. }
  596. void device_error_handler (void *unused)
  597. {
  598. ASSERT(!quitting)
  599. BLog(BLOG_ERROR, "device error");
  600. terminate();
  601. return;
  602. }
  603. void device_read_handler_send (void *unused, uint8_t *data, int data_len)
  604. {
  605. ASSERT(!quitting)
  606. BLog(BLOG_DEBUG, "device: received packet");
  607. // accept packet
  608. PacketPassInterface_Done(&device_read_interface);
  609. // obtain pbuf
  610. struct pbuf *p = pbuf_alloc(PBUF_RAW, data_len, PBUF_POOL);
  611. if (!p) {
  612. BLog(BLOG_WARNING, "device read: pbuf_alloc failed");
  613. return;
  614. }
  615. // write packet to pbuf
  616. ASSERT_FORCE(pbuf_take(p, data, data_len) == ERR_OK)
  617. // pass pbuf to input
  618. if (netif.input(p, &netif) != ERR_OK) {
  619. BLog(BLOG_WARNING, "device read: input failed");
  620. pbuf_free(p);
  621. }
  622. }
  623. err_t netif_init_func (struct netif *netif)
  624. {
  625. BLog(BLOG_DEBUG, "netif func init");
  626. netif->name[0] = 'h';
  627. netif->name[1] = 'o';
  628. netif->output = netif_output_func;
  629. return ERR_OK;
  630. }
  631. err_t netif_output_func (struct netif *netif, struct pbuf *p, ip_addr_t *ipaddr)
  632. {
  633. SYNC_DECL
  634. BLog(BLOG_DEBUG, "device write: send packet");
  635. if (quitting) {
  636. return ERR_OK;
  637. }
  638. uint8_t *out;
  639. if (!BufferWriter_StartPacket(&device_write_writer, &out)) {
  640. DEBUG("netif func output: BufferWriter_StartPacket failed");
  641. return ERR_OK;
  642. }
  643. int len = 0;
  644. while (p) {
  645. int remain = BTap_GetMTU(&device) - len;
  646. if (p->len > remain) {
  647. BLog(BLOG_WARNING, "netif func output: no space left");
  648. break;
  649. }
  650. memcpy(out + len, p->payload, p->len);
  651. len += p->len;
  652. p = p->next;
  653. }
  654. SYNC_FROMHERE
  655. BufferWriter_EndPacket(&device_write_writer, len);
  656. SYNC_COMMIT
  657. return ERR_OK;
  658. }
  659. void client_log (struct tcp_client *client, int level, const char *fmt, ...)
  660. {
  661. va_list vl;
  662. va_start(vl, fmt);
  663. char local_addr_s[BADDR_MAX_PRINT_LEN];
  664. BAddr_Print(&client->local_addr, local_addr_s);
  665. char remote_addr_s[BADDR_MAX_PRINT_LEN];
  666. BAddr_Print(&client->remote_addr, remote_addr_s);
  667. BLog_Append("%05d (%s %s): ", num_clients, local_addr_s, remote_addr_s);
  668. BLog_LogToChannelVarArg(BLOG_CURRENT_CHANNEL, level, fmt, vl);
  669. va_end(vl);
  670. }
  671. err_t listener_accept_func (void *arg, struct tcp_pcb *newpcb, err_t err)
  672. {
  673. ASSERT(listener)
  674. ASSERT(err == ERR_OK)
  675. // signal accepted
  676. tcp_accepted(listener);
  677. // allocate client structure
  678. struct tcp_client *client = malloc(sizeof(*client));
  679. if (!client) {
  680. BLog(BLOG_ERROR, "listener accept: malloc failed");
  681. return ERR_MEM;
  682. }
  683. SYNC_DECL
  684. SYNC_FROMHERE
  685. // init SOCKS
  686. BAddr addr;
  687. BAddr_InitIPv4(&addr, newpcb->local_ip.addr, hton16(newpcb->local_port));
  688. #ifdef OVERRIDE_DEST_ADDR
  689. ASSERT_FORCE(BAddr_Parse2(&addr, OVERRIDE_DEST_ADDR, NULL, 0, 1))
  690. #endif
  691. if (!BSocksClient_Init(&client->socks_client, socks_server_addr, addr, (BSocksClient_handler)client_socks_handler, client, &ss)) {
  692. BLog(BLOG_ERROR, "listener accept: BSocksClient_Init failed");
  693. SYNC_BREAK
  694. free(client);
  695. return ERR_MEM;
  696. }
  697. // init dead vars
  698. DEAD_INIT(client->dead);
  699. DEAD_INIT(client->dead_client);
  700. // add to linked list
  701. LinkedList2_Append(&tcp_clients, &client->list_node);
  702. // increment counter
  703. ASSERT(num_clients >= 0)
  704. num_clients++;
  705. // set pcb
  706. client->pcb = newpcb;
  707. // set client not closed
  708. client->client_closed = 0;
  709. // read addresses
  710. BAddr_InitIPv4(&client->local_addr, client->pcb->local_ip.addr, hton16(client->pcb->local_port));
  711. BAddr_InitIPv4(&client->remote_addr, client->pcb->remote_ip.addr, hton16(client->pcb->remote_port));
  712. // setup handler argument
  713. tcp_arg(client->pcb, client);
  714. // setup handlers
  715. tcp_err(client->pcb, client_err_func);
  716. tcp_recv(client->pcb, client_recv_func);
  717. // setup buffer
  718. client->buf_used = 0;
  719. // set SOCKS not up, not closed
  720. client->socks_up = 0;
  721. client->socks_closed = 0;
  722. client_log(client, BLOG_INFO, "accepted");
  723. DEAD_ENTER(client->dead_client)
  724. SYNC_COMMIT
  725. DEAD_LEAVE2(client->dead_client)
  726. if (DEAD_KILLED == -1) {
  727. return ERR_ABRT;
  728. }
  729. return ERR_OK;
  730. }
  731. void client_handle_freed_client (struct tcp_client *client, int was_abrt)
  732. {
  733. ASSERT(!client->client_closed)
  734. ASSERT(was_abrt == 0 || was_abrt == 1)
  735. // pcb was taken care of by the caller
  736. // kill client dead var
  737. DEAD_KILL_WITH(client->dead_client, (was_abrt ? -1 : 1));
  738. // set client closed
  739. client->client_closed = 1;
  740. // if we have data to be sent to SOCKS and can send it, keep sending
  741. if (client->buf_used > 0 && !client->socks_closed) {
  742. client_log(client, BLOG_INFO, "waiting untill buffered data is sent to SOCKS");
  743. } else {
  744. if (!client->socks_closed) {
  745. client_free_socks(client);
  746. } else {
  747. client_dealloc(client);
  748. }
  749. }
  750. }
  751. int client_free_client (struct tcp_client *client)
  752. {
  753. ASSERT(!client->client_closed)
  754. int was_abrt = 0;
  755. // remove callbacks
  756. tcp_err(client->pcb, NULL);
  757. tcp_recv(client->pcb, NULL);
  758. tcp_sent(client->pcb, NULL);
  759. // free pcb
  760. err_t err = tcp_close(client->pcb);
  761. if (err != ERR_OK) {
  762. client_log(client, BLOG_ERROR, "tcp_close failed (%d)", err);
  763. tcp_abort(client->pcb);
  764. was_abrt = 1;
  765. }
  766. client_handle_freed_client(client, was_abrt);
  767. return was_abrt;
  768. }
  769. void client_abort_client (struct tcp_client *client)
  770. {
  771. ASSERT(!client->client_closed)
  772. // remove callbacks
  773. tcp_err(client->pcb, NULL);
  774. tcp_recv(client->pcb, NULL);
  775. tcp_sent(client->pcb, NULL);
  776. // free pcb
  777. tcp_abort(client->pcb);
  778. client_handle_freed_client(client, 1);
  779. }
  780. void client_free_socks (struct tcp_client *client)
  781. {
  782. ASSERT(!client->socks_closed)
  783. // stop sending to SOCKS
  784. if (client->socks_up) {
  785. // remove send finished job
  786. BPending_Free(&client->socks_send_finished_job);
  787. // stop receiving from client
  788. if (!client->client_closed) {
  789. tcp_recv(client->pcb, NULL);
  790. }
  791. }
  792. // free SOCKS
  793. BSocksClient_Free(&client->socks_client);
  794. // set SOCKS closed
  795. client->socks_closed = 1;
  796. // if we have data to be sent to the client and we can send it, keep sending
  797. if (client->socks_up && (client->socks_recv_buf_used >= 0 || client->socks_recv_tcp_pending > 0) && !client->client_closed) {
  798. client_log(client, BLOG_INFO, "waiting until buffered data is sent to client");
  799. } else {
  800. if (!client->client_closed) {
  801. client_free_client(client);
  802. } else {
  803. client_dealloc(client);
  804. }
  805. }
  806. }
  807. void client_murder (struct tcp_client *client)
  808. {
  809. // free client
  810. if (!client->client_closed) {
  811. // remove callbacks
  812. tcp_err(client->pcb, NULL);
  813. tcp_recv(client->pcb, NULL);
  814. tcp_sent(client->pcb, NULL);
  815. // abort
  816. tcp_abort(client->pcb);
  817. // kill client dead var
  818. DEAD_KILL_WITH(client->dead_client, -1);
  819. // set client closed
  820. client->client_closed = 1;
  821. }
  822. // free SOCKS
  823. if (!client->socks_closed) {
  824. if (client->socks_up) {
  825. // remove send finished job
  826. BPending_Free(&client->socks_send_finished_job);
  827. }
  828. // free SOCKS
  829. BSocksClient_Free(&client->socks_client);
  830. // set SOCKS closed
  831. client->socks_closed = 1;
  832. }
  833. // dealloc entry
  834. client_dealloc(client);
  835. }
  836. void client_dealloc (struct tcp_client *client)
  837. {
  838. ASSERT(client->client_closed)
  839. ASSERT(client->socks_closed)
  840. // decrement counter
  841. ASSERT(num_clients > 0)
  842. num_clients--;
  843. // remove client entry
  844. LinkedList2_Remove(&tcp_clients, &client->list_node);
  845. // kill dead var
  846. DEAD_KILL(client->dead);
  847. // free memory
  848. free(client);
  849. }
  850. void client_err_func (void *arg, err_t err)
  851. {
  852. struct tcp_client *client = arg;
  853. ASSERT(!client->client_closed)
  854. client_log(client, BLOG_INFO, "client error (%d)", (int)err);
  855. // the pcb was taken care of by the caller
  856. client_handle_freed_client(client, 0);
  857. }
  858. err_t client_recv_func (void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
  859. {
  860. struct tcp_client *client = arg;
  861. ASSERT(!client->client_closed)
  862. ASSERT(err == ERR_OK) // checked in lwIP source. Otherwise, I've no idea what should
  863. // be done with the pbuf in case of an error.
  864. if (!p) {
  865. client_log(client, BLOG_INFO, "client closed");
  866. int ret = client_free_client(client);
  867. return (err ? ERR_ABRT : ERR_OK);
  868. }
  869. ASSERT(p->tot_len > 0)
  870. // check if we have enough buffer
  871. if (p->tot_len > sizeof(client->buf) - client->buf_used) {
  872. client_log(client, BLOG_ERROR, "no buffer for data !?!");
  873. return ERR_MEM;
  874. }
  875. // copy data to buffer
  876. ASSERT_EXECUTE(pbuf_copy_partial(p, client->buf + client->buf_used, p->tot_len, 0) == p->tot_len)
  877. client->buf_used += p->tot_len;
  878. // if there was nothing in the buffer before, and SOCKS is up, start send data
  879. if (client->buf_used == p->tot_len && client->socks_up) {
  880. ASSERT(!client->socks_closed) // this callback is removed when SOCKS is closed
  881. SYNC_DECL
  882. SYNC_FROMHERE
  883. client_send_to_socks(client);
  884. DEAD_ENTER(client->dead_client)
  885. SYNC_COMMIT
  886. DEAD_LEAVE2(client->dead_client)
  887. if (DEAD_KILLED == -1) {
  888. return ERR_ABRT;
  889. }
  890. }
  891. // free pbuff
  892. pbuf_free(p);
  893. return ERR_OK;
  894. }
  895. void client_socks_handler (struct tcp_client *client, int event)
  896. {
  897. ASSERT(!client->socks_closed)
  898. switch (event) {
  899. case BSOCKSCLIENT_EVENT_ERROR: {
  900. client_log(client, BLOG_INFO, "SOCKS error");
  901. client_free_socks(client);
  902. } break;
  903. case BSOCKSCLIENT_EVENT_UP: {
  904. ASSERT(!client->socks_up)
  905. client_log(client, BLOG_INFO, "SOCKS up");
  906. // init sending
  907. client->socks_send_if = BSocksClient_GetSendInterface(&client->socks_client);
  908. StreamPassInterface_Sender_Init(client->socks_send_if, (StreamPassInterface_handler_done)client_socks_send_handler_done, client);
  909. client->socks_send_prev_buf_used = -1;
  910. BPending_Init(&client->socks_send_finished_job, BReactor_PendingGroup(&ss), (BPending_handler)client_socks_send_finished_job_handler, client);
  911. // init receiving
  912. client->socks_recv_if = BSocksClient_GetRecvInterface(&client->socks_client);
  913. StreamRecvInterface_Receiver_Init(client->socks_recv_if, (StreamRecvInterface_handler_done)client_socks_recv_handler_done, client);
  914. client->socks_recv_buf_used = -1;
  915. client->socks_recv_tcp_pending = 0;
  916. tcp_sent(client->pcb, client_sent_func);
  917. // set up
  918. client->socks_up = 1;
  919. // start sending data if there is any
  920. if (client->buf_used > 0) {
  921. client_send_to_socks(client);
  922. }
  923. // start receiving data if client is still up
  924. if (!client->client_closed) {
  925. client_socks_recv_initiate(client);
  926. }
  927. } break;
  928. case BSOCKSCLIENT_EVENT_ERROR_CLOSED: {
  929. ASSERT(client->socks_up)
  930. client_log(client, BLOG_INFO, "SOCKS closed");
  931. client_free_socks(client);
  932. } break;
  933. default:
  934. ASSERT(0);
  935. }
  936. }
  937. void client_send_to_socks (struct tcp_client *client)
  938. {
  939. ASSERT(!client->socks_closed)
  940. ASSERT(client->socks_up)
  941. ASSERT(client->buf_used > 0)
  942. ASSERT(client->socks_send_prev_buf_used == -1)
  943. // remember amount of data in buffer
  944. client->socks_send_prev_buf_used = client->buf_used;
  945. // schedule finished job
  946. BPending_Set(&client->socks_send_finished_job);
  947. // schedule sending
  948. StreamPassInterface_Sender_Send(client->socks_send_if, client->buf, client->buf_used);
  949. }
  950. void client_socks_send_handler_done (struct tcp_client *client, int data_len)
  951. {
  952. ASSERT(!client->socks_closed)
  953. ASSERT(client->socks_up)
  954. ASSERT(client->buf_used > 0)
  955. ASSERT(client->socks_send_prev_buf_used > 0)
  956. ASSERT(data_len > 0)
  957. ASSERT(data_len <= client->buf_used)
  958. // remove sent data from buffer
  959. memmove(client->buf, client->buf + data_len, client->buf_used - data_len);
  960. client->buf_used -= data_len;
  961. // send any further data
  962. if (client->buf_used > 0) {
  963. StreamPassInterface_Sender_Send(client->socks_send_if, client->buf, client->buf_used);
  964. }
  965. }
  966. void client_socks_send_finished_job_handler (struct tcp_client *client)
  967. {
  968. ASSERT(!client->socks_closed)
  969. ASSERT(client->socks_up)
  970. ASSERT(client->socks_send_prev_buf_used > 0)
  971. ASSERT(client->buf_used <= client->socks_send_prev_buf_used)
  972. // calculate how much data was sent
  973. int sent = client->socks_send_prev_buf_used - client->buf_used;
  974. // unset remembered amount of data in buffer
  975. client->socks_send_prev_buf_used = -1;
  976. if (client->client_closed) {
  977. // client was closed we've sent everything we had buffered; we're done with it
  978. client_log(client, BLOG_INFO, "removing after client went down");
  979. client_free_socks(client);
  980. } else {
  981. // confirm sent data
  982. if (sent > 0) {
  983. tcp_recved(client->pcb, sent);
  984. }
  985. }
  986. }
  987. void client_socks_recv_initiate (struct tcp_client *client)
  988. {
  989. ASSERT(!client->client_closed)
  990. ASSERT(!client->socks_closed)
  991. ASSERT(client->socks_up)
  992. ASSERT(client->socks_recv_buf_used == -1)
  993. StreamRecvInterface_Receiver_Recv(client->socks_recv_if, client->socks_recv_buf, sizeof(client->socks_recv_buf));
  994. }
  995. void client_socks_recv_handler_done (struct tcp_client *client, int data_len)
  996. {
  997. ASSERT(data_len > 0)
  998. ASSERT(data_len <= sizeof(client->socks_recv_buf))
  999. ASSERT(!client->socks_closed)
  1000. ASSERT(client->socks_up)
  1001. ASSERT(client->socks_recv_buf_used == -1)
  1002. // if client was closed, stop receiving
  1003. if (client->client_closed) {
  1004. return;
  1005. }
  1006. // set amount of data in buffer
  1007. client->socks_recv_buf_used = data_len;
  1008. client->socks_recv_buf_sent = 0;
  1009. client->socks_recv_waiting = 0;
  1010. // send to client
  1011. if (client_socks_recv_send_out(client) < 0) {
  1012. return;
  1013. }
  1014. // continue receiving if needed
  1015. if (client->socks_recv_buf_used == -1) {
  1016. client_socks_recv_initiate(client);
  1017. }
  1018. }
  1019. int client_socks_recv_send_out (struct tcp_client *client)
  1020. {
  1021. ASSERT(!client->client_closed)
  1022. ASSERT(client->socks_up)
  1023. ASSERT(client->socks_recv_buf_used > 0)
  1024. ASSERT(client->socks_recv_buf_sent < client->socks_recv_buf_used)
  1025. ASSERT(!client->socks_recv_waiting)
  1026. // return value -1 means tcp_abort() was done,
  1027. // 0 means it wasn't and the client (pcb) is still up
  1028. do {
  1029. int to_write = bmin_int(client->socks_recv_buf_used - client->socks_recv_buf_sent, tcp_sndbuf(client->pcb));
  1030. if (to_write == 0) {
  1031. break;
  1032. }
  1033. err_t err = tcp_write(client->pcb, client->socks_recv_buf + client->socks_recv_buf_sent, to_write, TCP_WRITE_FLAG_COPY);
  1034. if (err != ERR_OK) {
  1035. if (err == ERR_MEM) {
  1036. break;
  1037. }
  1038. client_log(client, BLOG_INFO, "tcp_write failed (%d)", (int)err);
  1039. client_abort_client(client);
  1040. return -1;
  1041. }
  1042. client->socks_recv_buf_sent += to_write;
  1043. client->socks_recv_tcp_pending += to_write;
  1044. } while (client->socks_recv_buf_sent < client->socks_recv_buf_used);
  1045. // start sending now
  1046. err_t err = tcp_output(client->pcb);
  1047. if (err != ERR_OK) {
  1048. client_log(client, BLOG_INFO, "tcp_output failed (%d)", (int)err);
  1049. client_abort_client(client);
  1050. return -1;
  1051. }
  1052. // more data to queue?
  1053. if (client->socks_recv_buf_sent < client->socks_recv_buf_used) {
  1054. if (client->socks_recv_tcp_pending == 0) {
  1055. client_log(client, BLOG_ERROR, "can't queue data, but all data was confirmed !?!");
  1056. client_abort_client(client);
  1057. return -1;
  1058. }
  1059. // set waiting, continue in client_sent_func
  1060. client->socks_recv_waiting = 1;
  1061. return 0;
  1062. }
  1063. // everything was queued
  1064. client->socks_recv_buf_used = -1;
  1065. return 0;
  1066. }
  1067. err_t client_sent_func (void *arg, struct tcp_pcb *tpcb, u16_t len)
  1068. {
  1069. struct tcp_client *client = arg;
  1070. ASSERT(!client->client_closed)
  1071. ASSERT(client->socks_up)
  1072. ASSERT(len > 0)
  1073. ASSERT(len <= client->socks_recv_tcp_pending)
  1074. // decrement pending
  1075. client->socks_recv_tcp_pending -= len;
  1076. // continue queuing
  1077. if (client->socks_recv_buf_used > 0) {
  1078. ASSERT(client->socks_recv_waiting)
  1079. ASSERT(client->socks_recv_buf_sent < client->socks_recv_buf_used)
  1080. // set not waiting
  1081. client->socks_recv_waiting = 0;
  1082. // possibly send more data
  1083. if (client_socks_recv_send_out(client) < 0) {
  1084. return ERR_ABRT;
  1085. }
  1086. // we just queued some data, so it can't have been confirmed yet
  1087. ASSERT(client->socks_recv_tcp_pending > 0)
  1088. // continue receiving if needed
  1089. if (client->socks_recv_buf_used == -1 && !client->socks_closed) {
  1090. SYNC_DECL
  1091. SYNC_FROMHERE
  1092. client_socks_recv_initiate(client);
  1093. DEAD_ENTER(client->dead)
  1094. SYNC_COMMIT
  1095. DEAD_LEAVE2(client->dead)
  1096. if (DEAD_KILLED) {
  1097. return ERR_ABRT;
  1098. }
  1099. }
  1100. return ERR_OK;
  1101. }
  1102. // have we sent everything after SOCKS was closed?
  1103. if (client->socks_closed && client->socks_recv_tcp_pending == 0) {
  1104. client_log(client, BLOG_INFO, "removing after SOCKS went down");
  1105. int ret = client_free_client(client);
  1106. return (ret ? ERR_ABRT : ERR_OK);
  1107. }
  1108. return ERR_OK;
  1109. }