tun2socks.c 43 KB

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