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