tun2socks.c 44 KB

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