tun2socks.c 47 KB

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