BadVPN – Blame information for rev 1

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 office 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  
29 #include <stdint.h>
30 #include <stdio.h>
31 #include <stddef.h>
32 #include <string.h>
33 #include <limits.h>
34  
35 #include <misc/version.h>
36 #include <misc/loggers_string.h>
37 #include <misc/loglevel.h>
38 #include <misc/minmax.h>
39 #include <misc/offset.h>
40 #include <misc/dead.h>
41 #include <misc/ipv4_proto.h>
42 #include <misc/ipv6_proto.h>
43 #include <misc/udp_proto.h>
44 #include <misc/byteorder.h>
45 #include <misc/balloc.h>
46 #include <misc/open_standard_streams.h>
47 #include <misc/read_file.h>
48 #include <misc/ipaddr6.h>
49 #include <misc/concat_strings.h>
50 #include <structure/LinkedList1.h>
51 #include <base/BLog.h>
52 #include <system/BReactor.h>
53 #include <system/BSignal.h>
54 #include <system/BAddr.h>
55 #include <system/BNetwork.h>
56 #include <flow/SinglePacketBuffer.h>
57 #include <socksclient/BSocksClient.h>
58 #include <tuntap/BTap.h>
59 #include <lwip/init.h>
60 #include <lwip/ip_addr.h>
61 #include <lwip/priv/tcp_priv.h>
62 #include <lwip/netif.h>
63 #include <lwip/tcp.h>
64 #include <lwip/ip4_frag.h>
65 #include <lwip/nd6.h>
66 #include <lwip/ip6_frag.h>
67 #include <tun2socks/SocksUdpGwClient.h>
68 #include <socks_udp_client/SocksUdpClient.h>
69  
70 #ifndef BADVPN_USE_WINAPI
71 #include <base/BLog_syslog.h>
72 #endif
73  
74 #include <tun2socks/tun2socks.h>
75  
76 #include <generated/blog_channel_tun2socks.h>
77  
78 #define LOGGER_STDOUT 1
79 #define LOGGER_SYSLOG 2
80  
81 #define SYNC_DECL \
82 BPending sync_mark; \
83  
84 #define SYNC_FROMHERE \
85 BPending_Init(&sync_mark, BReactor_PendingGroup(&ss), NULL, NULL); \
86 BPending_Set(&sync_mark);
87  
88 #define SYNC_BREAK \
89 BPending_Free(&sync_mark);
90  
91 #define SYNC_COMMIT \
92 BReactor_Synchronize(&ss, &sync_mark.base); \
93 BPending_Free(&sync_mark);
94  
95 // command-line options
96 struct {
97 int help;
98 int version;
99 int logger;
100 #ifndef BADVPN_USE_WINAPI
101 char *logger_syslog_facility;
102 char *logger_syslog_ident;
103 #endif
104 int loglevel;
105 int loglevels[BLOG_NUM_CHANNELS];
106 char *tundev;
107 char *netif_ipaddr;
108 char *netif_netmask;
109 char *netif_ip6addr;
110 char *socks_server_addr;
111 char *username;
112 char *password;
113 char *password_file;
114 int append_source_to_username;
115 char *udpgw_remote_server_addr;
116 int udpgw_max_connections;
117 int udpgw_connection_buffer_size;
118 int udpgw_transparent_dns;
119 int socks5_udp;
120 } options;
121  
122 // TCP client
123 struct tcp_client {
124 int aborted;
125 dead_t dead_aborted;
126 LinkedList1Node list_node;
127 BAddr local_addr;
128 BAddr remote_addr;
129 struct tcp_pcb *pcb;
130 int client_closed;
131 uint8_t buf[TCP_WND];
132 int buf_used;
133 char *socks_username;
134 BSocksClient socks_client;
135 int socks_up;
136 int socks_closed;
137 StreamPassInterface *socks_send_if;
138 StreamRecvInterface *socks_recv_if;
139 uint8_t socks_recv_buf[CLIENT_SOCKS_RECV_BUF_SIZE];
140 int socks_recv_buf_used;
141 int socks_recv_buf_sent;
142 int socks_recv_waiting;
143 int socks_recv_tcp_pending;
144 };
145  
146 // IP address of netif
147 BIPAddr netif_ipaddr;
148  
149 // netmask of netif
150 BIPAddr netif_netmask;
151  
152 // IP6 address of netif
153 struct ipv6_addr netif_ip6addr;
154  
155 // SOCKS server address
156 BAddr socks_server_addr;
157  
158 // allocated password file contents
159 uint8_t *password_file_contents;
160  
161 // SOCKS authentication information
162 struct BSocksClient_auth_info socks_auth_info[2];
163 size_t socks_num_auth_info;
164  
165 // remote udpgw server addr, if provided
166 BAddr udpgw_remote_server_addr;
167  
168 // reactor
169 BReactor ss;
170  
171 // set to 1 by terminate
172 int quitting;
173  
174 // TUN device
175 BTap device;
176  
177 // device write buffer
178 uint8_t *device_write_buf;
179  
180 // device reading
181 SinglePacketBuffer device_read_buffer;
182 PacketPassInterface device_read_interface;
183  
184 // UDP support mode
185 enum UdpMode {UdpModeNone, UdpModeUdpgw, UdpModeSocks};
186 enum UdpMode udp_mode;
187  
188 // udpgw client
189 SocksUdpGwClient udpgw_client;
190 int udp_mtu;
191  
192 // SOCKS5-UDP client
193 SocksUdpClient socks_udp_client;
194  
195 // TCP timer
196 BTimer tcp_timer;
197 int tcp_timer_mod4;
198  
199 // job for initializing lwip
200 BPending lwip_init_job;
201  
202 // lwip netif
203 int have_netif;
204 struct netif the_netif;
205  
206 // lwip TCP listener
207 struct tcp_pcb *listener;
208  
209 // lwip TCP/IPv6 listener
210 struct tcp_pcb *listener_ip6;
211  
212 // TCP clients
213 LinkedList1 tcp_clients;
214  
215 // number of clients
216 int num_clients;
217  
218 static void terminate (void);
219 static void print_help (const char *name);
220 static void print_version (void);
221 static int parse_arguments (int argc, char *argv[]);
222 static int process_arguments (void);
223 static void signal_handler (void *unused);
224 static BAddr baddr_from_lwip (const ip_addr_t *ip_addr, uint16_t port_hostorder);
225 static void lwip_init_job_hadler (void *unused);
226 static void tcp_timer_handler (void *unused);
227 static void device_error_handler (void *unused);
228 static void device_read_handler_send (void *unused, uint8_t *data, int data_len);
229 static int process_device_udp_packet (uint8_t *data, int data_len);
230 static err_t netif_init_func (struct netif *netif);
231 static err_t netif_output_func (struct netif *netif, struct pbuf *p, const ip4_addr_t *ipaddr);
232 static err_t netif_output_ip6_func (struct netif *netif, struct pbuf *p, const ip6_addr_t *ipaddr);
233 static err_t common_netif_output (struct netif *netif, struct pbuf *p);
234 static err_t netif_input_func (struct pbuf *p, struct netif *inp);
235 static void client_logfunc (struct tcp_client *client);
236 static void client_log (struct tcp_client *client, int level, const char *fmt, ...);
237 static err_t listener_accept_func (void *arg, struct tcp_pcb *newpcb, err_t err);
238 static void client_handle_freed_client (struct tcp_client *client);
239 static void client_free_client (struct tcp_client *client);
240 static void client_abort_client (struct tcp_client *client);
241 static void client_abort_pcb (struct tcp_client *client);
242 static void client_free_socks (struct tcp_client *client);
243 static void client_murder (struct tcp_client *client);
244 static void client_dealloc (struct tcp_client *client);
245 static void client_err_func (void *arg, err_t err);
246 static err_t client_recv_func (void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err);
247 static void client_socks_handler (struct tcp_client *client, int event);
248 static void client_send_to_socks (struct tcp_client *client);
249 static void client_socks_send_handler_done (struct tcp_client *client, int data_len);
250 static void client_socks_recv_initiate (struct tcp_client *client);
251 static void client_socks_recv_handler_done (struct tcp_client *client, int data_len);
252 static int client_socks_recv_send_out (struct tcp_client *client);
253 static err_t client_sent_func (void *arg, struct tcp_pcb *tpcb, u16_t len);
254 static void udp_send_packet_to_device (void *unused, BAddr local_addr, BAddr remote_addr, const uint8_t *data, int data_len);
255  
256 int main (int argc, char **argv)
257 {
258 if (argc <= 0) {
259 return 1;
260 }
261  
262 // open standard streams
263 open_standard_streams();
264  
265 // parse command-line arguments
266 if (!parse_arguments(argc, argv)) {
267 fprintf(stderr, "Failed to parse arguments\n");
268 print_help(argv[0]);
269 goto fail0;
270 }
271  
272 // handle --help and --version
273 if (options.help) {
274 print_version();
275 print_help(argv[0]);
276 return 0;
277 }
278 if (options.version) {
279 print_version();
280 return 0;
281 }
282  
283 // initialize logger
284 switch (options.logger) {
285 case LOGGER_STDOUT:
286 BLog_InitStdout();
287 break;
288 #ifndef BADVPN_USE_WINAPI
289 case LOGGER_SYSLOG:
290 if (!BLog_InitSyslog(options.logger_syslog_ident, options.logger_syslog_facility)) {
291 fprintf(stderr, "Failed to initialize syslog logger\n");
292 goto fail0;
293 }
294 break;
295 #endif
296 default:
297 ASSERT(0);
298 }
299  
300 // configure logger channels
301 for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
302 if (options.loglevels[i] >= 0) {
303 BLog_SetChannelLoglevel(i, options.loglevels[i]);
304 }
305 else if (options.loglevel >= 0) {
306 BLog_SetChannelLoglevel(i, options.loglevel);
307 }
308 }
309  
310 BLog(BLOG_NOTICE, "initializing "GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION);
311  
312 // clear password contents pointer
313 password_file_contents = NULL;
314  
315 // initialize network
316 if (!BNetwork_GlobalInit()) {
317 BLog(BLOG_ERROR, "BNetwork_GlobalInit failed");
318 goto fail1;
319 }
320  
321 // process arguments
322 if (!process_arguments()) {
323 BLog(BLOG_ERROR, "Failed to process arguments");
324 goto fail1;
325 }
326  
327 // init time
328 BTime_Init();
329  
330 // init reactor
331 if (!BReactor_Init(&ss)) {
332 BLog(BLOG_ERROR, "BReactor_Init failed");
333 goto fail1;
334 }
335  
336 // set not quitting
337 quitting = 0;
338  
339 // setup signal handler
340 if (!BSignal_Init(&ss, signal_handler, NULL)) {
341 BLog(BLOG_ERROR, "BSignal_Init failed");
342 goto fail2;
343 }
344  
345 // init TUN device
346 if (!BTap_Init(&device, &ss, options.tundev, device_error_handler, NULL, 1)) {
347 BLog(BLOG_ERROR, "BTap_Init failed");
348 goto fail3;
349 }
350  
351 // NOTE: the order of the following is important:
352 // first device writing must evaluate,
353 // then lwip (so it can send packets to the device),
354 // then device reading (so it can pass received packets to lwip).
355  
356 // init device reading
357 PacketPassInterface_Init(&device_read_interface, BTap_GetMTU(&device), device_read_handler_send, NULL, BReactor_PendingGroup(&ss));
358 if (!SinglePacketBuffer_Init(&device_read_buffer, BTap_GetOutput(&device), &device_read_interface, BReactor_PendingGroup(&ss))) {
359 BLog(BLOG_ERROR, "SinglePacketBuffer_Init failed");
360 goto fail4;
361 }
362  
363 // Compute the largest possible UDP payload that we can receive from or send to the
364 // TUN device.
365 udp_mtu = BTap_GetMTU(&device) - (int)(sizeof(struct ipv4_header) + sizeof(struct udp_header));
366 if (options.netif_ip6addr) {
367 int udp_ip6_mtu = BTap_GetMTU(&device) - (int)(sizeof(struct ipv6_header) + sizeof(struct udp_header));
368 if (udp_mtu < udp_ip6_mtu) {
369 udp_mtu = udp_ip6_mtu;
370 }
371 }
372 if (udp_mtu < 0) {
373 udp_mtu = 0;
374 }
375  
376 if (options.udpgw_remote_server_addr) {
377 udp_mode = UdpModeUdpgw;
378  
379 // make sure our UDP payloads aren't too large for udpgw
380 int udpgw_mtu = udpgw_compute_mtu(udp_mtu);
381 if (udpgw_mtu < 0 || udpgw_mtu > PACKETPROTO_MAXPAYLOAD) {
382 BLog(BLOG_ERROR, "device MTU is too large for UDP");
383 goto fail4a;
384 }
385  
386 // init udpgw client
387 if (!SocksUdpGwClient_Init(&udpgw_client, udp_mtu, DEFAULT_UDPGW_MAX_CONNECTIONS,
388 options.udpgw_connection_buffer_size, UDPGW_KEEPALIVE_TIME, socks_server_addr,
389 socks_auth_info, socks_num_auth_info, udpgw_remote_server_addr,
390 UDPGW_RECONNECT_TIME, &ss, NULL, udp_send_packet_to_device))
391 {
392 BLog(BLOG_ERROR, "SocksUdpGwClient_Init failed");
393 goto fail4a;
394 }
395 } else if (options.socks5_udp) {
396 udp_mode = UdpModeSocks;
397  
398 // init SOCKS UDP client
399 SocksUdpClient_Init(&socks_udp_client, udp_mtu, DEFAULT_UDPGW_MAX_CONNECTIONS,
400 SOCKS_UDP_SEND_BUFFER_PACKETS, UDPGW_KEEPALIVE_TIME, socks_server_addr,
401 socks_auth_info, socks_num_auth_info, &ss, NULL, udp_send_packet_to_device);
402 } else {
403 udp_mode = UdpModeNone;
404 }
405  
406 // init lwip init job
407 BPending_Init(&lwip_init_job, BReactor_PendingGroup(&ss), lwip_init_job_hadler, NULL);
408 BPending_Set(&lwip_init_job);
409  
410 // init device write buffer
411 if (!(device_write_buf = (uint8_t *)BAlloc(BTap_GetMTU(&device)))) {
412 BLog(BLOG_ERROR, "BAlloc failed");
413 goto fail5;
414 }
415  
416 // init TCP timer
417 // it won't trigger before lwip is initialized, becuase the lwip init is a job
418 BTimer_Init(&tcp_timer, TCP_TMR_INTERVAL, tcp_timer_handler, NULL);
419 BReactor_SetTimer(&ss, &tcp_timer);
420 tcp_timer_mod4 = 0;
421  
422 // set no netif
423 have_netif = 0;
424  
425 // set no listener
426 listener = NULL;
427 listener_ip6 = NULL;
428  
429 // init clients list
430 LinkedList1_Init(&tcp_clients);
431  
432 // init number of clients
433 num_clients = 0;
434  
435 // enter event loop
436 BLog(BLOG_NOTICE, "entering event loop");
437 BReactor_Exec(&ss);
438  
439 // free clients
440 LinkedList1Node *node;
441 while (node = LinkedList1_GetFirst(&tcp_clients)) {
442 struct tcp_client *client = UPPER_OBJECT(node, struct tcp_client, list_node);
443 client_murder(client);
444 }
445  
446 // free listener
447 if (listener_ip6) {
448 tcp_close(listener_ip6);
449 }
450 if (listener) {
451 tcp_close(listener);
452 }
453  
454 // free netif
455 if (have_netif) {
456 netif_remove(&the_netif);
457 }
458  
459 BReactor_RemoveTimer(&ss, &tcp_timer);
460 BFree(device_write_buf);
461 fail5:
462 BPending_Free(&lwip_init_job);
463 if (udp_mode == UdpModeUdpgw) {
464 SocksUdpGwClient_Free(&udpgw_client);
465 } else if (udp_mode == UdpModeSocks) {
466 SocksUdpClient_Free(&socks_udp_client);
467 }
468 fail4a:
469 SinglePacketBuffer_Free(&device_read_buffer);
470 fail4:
471 PacketPassInterface_Free(&device_read_interface);
472 BTap_Free(&device);
473 fail3:
474 BSignal_Finish();
475 fail2:
476 BReactor_Free(&ss);
477 fail1:
478 BFree(password_file_contents);
479 BLog(BLOG_NOTICE, "exiting");
480 BLog_Free();
481 fail0:
482 DebugObjectGlobal_Finish();
483  
484 return 1;
485 }
486  
487 void terminate (void)
488 {
489 ASSERT(!quitting)
490  
491 BLog(BLOG_NOTICE, "tearing down");
492  
493 // set quitting
494 quitting = 1;
495  
496 // exit event loop
497 BReactor_Quit(&ss, 1);
498 }
499  
500 void print_help (const char *name)
501 {
502 printf(
503 "Usage:\n"
504 " %s\n"
505 " [--help]\n"
506 " [--version]\n"
507 " [--logger <"LOGGERS_STRING">]\n"
508 #ifndef BADVPN_USE_WINAPI
509 " (logger=syslog?\n"
510 " [--syslog-facility <string>]\n"
511 " [--syslog-ident <string>]\n"
512 " )\n"
513 #endif
514 " [--loglevel <0-5/none/error/warning/notice/info/debug>]\n"
515 " [--channel-loglevel <channel-name> <0-5/none/error/warning/notice/info/debug>] ...\n"
516 " [--tundev <name>]\n"
517 " --netif-ipaddr <ipaddr>\n"
518 " --netif-netmask <ipnetmask>\n"
519 " --socks-server-addr <addr>\n"
520 " [--netif-ip6addr <addr>]\n"
521 " [--username <username>]\n"
522 " [--password <password>]\n"
523 " [--password-file <file>]\n"
524 " [--append-source-to-username]\n"
525 " [--udpgw-remote-server-addr <addr>]\n"
526 " [--udpgw-max-connections <number>]\n"
527 " [--udpgw-connection-buffer-size <number>]\n"
528 " [--udpgw-transparent-dns]\n"
529 " [--socks5-udp]\n"
530 "Address format is a.b.c.d:port (IPv4) or [addr]:port (IPv6).\n",
531 name
532 );
533 }
534  
535 void print_version (void)
536 {
537 printf(GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION"\n"GLOBAL_COPYRIGHT_NOTICE"\n");
538 }
539  
540 int parse_arguments (int argc, char *argv[])
541 {
542 if (argc <= 0) {
543 return 0;
544 }
545  
546 options.help = 0;
547 options.version = 0;
548 options.logger = LOGGER_STDOUT;
549 #ifndef BADVPN_USE_WINAPI
550 options.logger_syslog_facility = "daemon";
551 options.logger_syslog_ident = argv[0];
552 #endif
553 options.loglevel = -1;
554 for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
555 options.loglevels[i] = -1;
556 }
557 options.tundev = NULL;
558 options.netif_ipaddr = NULL;
559 options.netif_netmask = NULL;
560 options.netif_ip6addr = NULL;
561 options.socks_server_addr = NULL;
562 options.username = NULL;
563 options.password = NULL;
564 options.password_file = NULL;
565 options.append_source_to_username = 0;
566 options.udpgw_remote_server_addr = NULL;
567 options.udpgw_max_connections = DEFAULT_UDPGW_MAX_CONNECTIONS;
568 options.udpgw_connection_buffer_size = DEFAULT_UDPGW_CONNECTION_BUFFER_SIZE;
569 options.udpgw_transparent_dns = 0;
570 options.socks5_udp = 0;
571  
572 int i;
573 for (i = 1; i < argc; i++) {
574 char *arg = argv[i];
575 if (!strcmp(arg, "--help")) {
576 options.help = 1;
577 }
578 else if (!strcmp(arg, "--version")) {
579 options.version = 1;
580 }
581 else if (!strcmp(arg, "--logger")) {
582 if (1 >= argc - i) {
583 fprintf(stderr, "%s: requires an argument\n", arg);
584 return 0;
585 }
586 char *arg2 = argv[i + 1];
587 if (!strcmp(arg2, "stdout")) {
588 options.logger = LOGGER_STDOUT;
589 }
590 #ifndef BADVPN_USE_WINAPI
591 else if (!strcmp(arg2, "syslog")) {
592 options.logger = LOGGER_SYSLOG;
593 }
594 #endif
595 else {
596 fprintf(stderr, "%s: wrong argument\n", arg);
597 return 0;
598 }
599 i++;
600 }
601 #ifndef BADVPN_USE_WINAPI
602 else if (!strcmp(arg, "--syslog-facility")) {
603 if (1 >= argc - i) {
604 fprintf(stderr, "%s: requires an argument\n", arg);
605 return 0;
606 }
607 options.logger_syslog_facility = argv[i + 1];
608 i++;
609 }
610 else if (!strcmp(arg, "--syslog-ident")) {
611 if (1 >= argc - i) {
612 fprintf(stderr, "%s: requires an argument\n", arg);
613 return 0;
614 }
615 options.logger_syslog_ident = argv[i + 1];
616 i++;
617 }
618 #endif
619 else if (!strcmp(arg, "--loglevel")) {
620 if (1 >= argc - i) {
621 fprintf(stderr, "%s: requires an argument\n", arg);
622 return 0;
623 }
624 if ((options.loglevel = parse_loglevel(argv[i + 1])) < 0) {
625 fprintf(stderr, "%s: wrong argument\n", arg);
626 return 0;
627 }
628 i++;
629 }
630 else if (!strcmp(arg, "--channel-loglevel")) {
631 if (2 >= argc - i) {
632 fprintf(stderr, "%s: requires two arguments\n", arg);
633 return 0;
634 }
635 int channel = BLogGlobal_GetChannelByName(argv[i + 1]);
636 if (channel < 0) {
637 fprintf(stderr, "%s: wrong channel argument\n", arg);
638 return 0;
639 }
640 int loglevel = parse_loglevel(argv[i + 2]);
641 if (loglevel < 0) {
642 fprintf(stderr, "%s: wrong loglevel argument\n", arg);
643 return 0;
644 }
645 options.loglevels[channel] = loglevel;
646 i += 2;
647 }
648 else if (!strcmp(arg, "--tundev")) {
649 if (1 >= argc - i) {
650 fprintf(stderr, "%s: requires an argument\n", arg);
651 return 0;
652 }
653 options.tundev = argv[i + 1];
654 i++;
655 }
656 else if (!strcmp(arg, "--netif-ipaddr")) {
657 if (1 >= argc - i) {
658 fprintf(stderr, "%s: requires an argument\n", arg);
659 return 0;
660 }
661 options.netif_ipaddr = argv[i + 1];
662 i++;
663 }
664 else if (!strcmp(arg, "--netif-netmask")) {
665 if (1 >= argc - i) {
666 fprintf(stderr, "%s: requires an argument\n", arg);
667 return 0;
668 }
669 options.netif_netmask = argv[i + 1];
670 i++;
671 }
672 else if (!strcmp(arg, "--netif-ip6addr")) {
673 if (1 >= argc - i) {
674 fprintf(stderr, "%s: requires an argument\n", arg);
675 return 0;
676 }
677 options.netif_ip6addr = argv[i + 1];
678 i++;
679 }
680 else if (!strcmp(arg, "--socks-server-addr")) {
681 if (1 >= argc - i) {
682 fprintf(stderr, "%s: requires an argument\n", arg);
683 return 0;
684 }
685 options.socks_server_addr = argv[i + 1];
686 i++;
687 }
688 else if (!strcmp(arg, "--username")) {
689 if (1 >= argc - i) {
690 fprintf(stderr, "%s: requires an argument\n", arg);
691 return 0;
692 }
693 options.username = argv[i + 1];
694 i++;
695 }
696 else if (!strcmp(arg, "--password")) {
697 if (1 >= argc - i) {
698 fprintf(stderr, "%s: requires an argument\n", arg);
699 return 0;
700 }
701 options.password = argv[i + 1];
702 i++;
703 }
704 else if (!strcmp(arg, "--password-file")) {
705 if (1 >= argc - i) {
706 fprintf(stderr, "%s: requires an argument\n", arg);
707 return 0;
708 }
709 options.password_file = argv[i + 1];
710 i++;
711 }
712 else if (!strcmp(arg, "--append-source-to-username")) {
713 options.append_source_to_username = 1;
714 }
715 else if (!strcmp(arg, "--udpgw-remote-server-addr")) {
716 if (1 >= argc - i) {
717 fprintf(stderr, "%s: requires an argument\n", arg);
718 return 0;
719 }
720 options.udpgw_remote_server_addr = argv[i + 1];
721 i++;
722 }
723 else if (!strcmp(arg, "--udpgw-max-connections")) {
724 if (1 >= argc - i) {
725 fprintf(stderr, "%s: requires an argument\n", arg);
726 return 0;
727 }
728 if ((options.udpgw_max_connections = atoi(argv[i + 1])) <= 0) {
729 fprintf(stderr, "%s: wrong argument\n", arg);
730 return 0;
731 }
732 i++;
733 }
734 else if (!strcmp(arg, "--udpgw-connection-buffer-size")) {
735 if (1 >= argc - i) {
736 fprintf(stderr, "%s: requires an argument\n", arg);
737 return 0;
738 }
739 if ((options.udpgw_connection_buffer_size = atoi(argv[i + 1])) <= 0) {
740 fprintf(stderr, "%s: wrong argument\n", arg);
741 return 0;
742 }
743 i++;
744 }
745 else if (!strcmp(arg, "--udpgw-transparent-dns")) {
746 options.udpgw_transparent_dns = 1;
747 }
748 else if (!strcmp(arg, "--socks5-udp")) {
749 options.socks5_udp = 1;
750 }
751 else {
752 fprintf(stderr, "unknown option: %s\n", arg);
753 return 0;
754 }
755 }
756  
757 if (options.help || options.version) {
758 return 1;
759 }
760  
761 if (!options.netif_ipaddr) {
762 fprintf(stderr, "--netif-ipaddr is required\n");
763 return 0;
764 }
765  
766 if (!options.netif_netmask) {
767 fprintf(stderr, "--netif-netmask is required\n");
768 return 0;
769 }
770  
771 if (!options.socks_server_addr) {
772 fprintf(stderr, "--socks-server-addr is required\n");
773 return 0;
774 }
775  
776 if (options.username) {
777 if (!options.password && !options.password_file) {
778 fprintf(stderr, "username given but password not given\n");
779 return 0;
780 }
781  
782 if (options.password && options.password_file) {
783 fprintf(stderr, "--password and --password-file cannot both be given\n");
784 return 0;
785 }
786 }
787  
788 return 1;
789 }
790  
791 int process_arguments (void)
792 {
793 ASSERT(!password_file_contents)
794  
795 // resolve netif ipaddr
796 if (!BIPAddr_Resolve(&netif_ipaddr, options.netif_ipaddr, 0)) {
797 BLog(BLOG_ERROR, "netif ipaddr: BIPAddr_Resolve failed");
798 return 0;
799 }
800 if (netif_ipaddr.type != BADDR_TYPE_IPV4) {
801 BLog(BLOG_ERROR, "netif ipaddr: must be an IPv4 address");
802 return 0;
803 }
804  
805 // resolve netif netmask
806 if (!BIPAddr_Resolve(&netif_netmask, options.netif_netmask, 0)) {
807 BLog(BLOG_ERROR, "netif netmask: BIPAddr_Resolve failed");
808 return 0;
809 }
810 if (netif_netmask.type != BADDR_TYPE_IPV4) {
811 BLog(BLOG_ERROR, "netif netmask: must be an IPv4 address");
812 return 0;
813 }
814  
815 // parse IP6 address
816 if (options.netif_ip6addr) {
817 if (!ipaddr6_parse_ipv6_addr(MemRef_MakeCstr(options.netif_ip6addr), &netif_ip6addr)) {
818 BLog(BLOG_ERROR, "netif ip6addr: incorrect");
819 return 0;
820 }
821 }
822  
823 // resolve SOCKS server address
824 if (!BAddr_Parse2(&socks_server_addr, options.socks_server_addr, NULL, 0, 0)) {
825 BLog(BLOG_ERROR, "socks server addr: BAddr_Parse2 failed");
826 return 0;
827 }
828  
829 // add none socks authentication method
830 socks_auth_info[0] = BSocksClient_auth_none();
831 socks_num_auth_info = 1;
832  
833 // add password socks authentication method
834 if (options.username) {
835 const char *password;
836 size_t password_len;
837 if (options.password) {
838 password = options.password;
839 password_len = strlen(options.password);
840 } else {
841 if (!read_file(options.password_file, &password_file_contents, &password_len)) {
842 BLog(BLOG_ERROR, "failed to read password file");
843 return 0;
844 }
845 password = (char *)password_file_contents;
846 }
847  
848 socks_auth_info[socks_num_auth_info++] = BSocksClient_auth_password(
849 options.username, strlen(options.username),
850 password, password_len
851 );
852 }
853  
854 // resolve remote udpgw server address
855 if (options.udpgw_remote_server_addr) {
856 if (!BAddr_Parse2(&udpgw_remote_server_addr, options.udpgw_remote_server_addr, NULL, 0, 0)) {
857 BLog(BLOG_ERROR, "remote udpgw server addr: BAddr_Parse2 failed");
858 return 0;
859 }
860 }
861  
862 return 1;
863 }
864  
865 void signal_handler (void *unused)
866 {
867 ASSERT(!quitting)
868  
869 BLog(BLOG_NOTICE, "termination requested");
870  
871 terminate();
872 }
873  
874 BAddr baddr_from_lwip (const ip_addr_t *ip_addr, uint16_t port_hostorder)
875 {
876 BAddr addr;
877 if (IP_IS_V6(ip_addr)) {
878 BAddr_InitIPv6(&addr, (uint8_t *)ip_addr->u_addr.ip6.addr, hton16(port_hostorder));
879 } else {
880 BAddr_InitIPv4(&addr, ip_addr->u_addr.ip4.addr, hton16(port_hostorder));
881 }
882 return addr;
883 }
884  
885 void lwip_init_job_hadler (void *unused)
886 {
887 ASSERT(!quitting)
888 ASSERT(netif_ipaddr.type == BADDR_TYPE_IPV4)
889 ASSERT(netif_netmask.type == BADDR_TYPE_IPV4)
890 ASSERT(!have_netif)
891 ASSERT(!listener)
892 ASSERT(!listener_ip6)
893  
894 BLog(BLOG_DEBUG, "lwip init");
895  
896 // NOTE: the device may fail during this, but there's no harm in not checking
897 // for that at every step
898  
899 // init lwip
900 lwip_init();
901  
902 // make addresses for netif
903 ip4_addr_t addr;
904 addr.addr = netif_ipaddr.ipv4;
905 ip4_addr_t netmask;
906 netmask.addr = netif_netmask.ipv4;
907 ip4_addr_t gw;
908 ip4_addr_set_any(&gw);
909  
910 // init netif
911 if (!netif_add(&the_netif, &addr, &netmask, &gw, NULL, netif_init_func, netif_input_func)) {
912 BLog(BLOG_ERROR, "netif_add failed");
913 goto fail;
914 }
915 have_netif = 1;
916  
917 // set netif up
918 netif_set_up(&the_netif);
919  
920 // set netif link up, otherwise ip route will refuse to route
921 netif_set_link_up(&the_netif);
922  
923 // set netif pretend TCP
924 netif_set_pretend_tcp(&the_netif, 1);
925  
926 // set netif default
927 netif_set_default(&the_netif);
928  
929 if (options.netif_ip6addr) {
930 // add IPv6 address
931 ip6_addr_t ip6addr;
932 memset(&ip6addr, 0, sizeof(ip6addr)); // clears any "zone"
933 memcpy(ip6addr.addr, netif_ip6addr.bytes, sizeof(netif_ip6addr.bytes));
934 netif_ip6_addr_set(&the_netif, 0, &ip6addr);
935 netif_ip6_addr_set_state(&the_netif, 0, IP6_ADDR_VALID);
936 }
937  
938 // init listener
939 struct tcp_pcb *l = tcp_new_ip_type(IPADDR_TYPE_V4);
940 if (!l) {
941 BLog(BLOG_ERROR, "tcp_new_ip_type failed");
942 goto fail;
943 }
944  
945 // bind listener
946 if (tcp_bind_to_netif(l, "ho0") != ERR_OK) {
947 BLog(BLOG_ERROR, "tcp_bind_to_netif failed");
948 tcp_close(l);
949 goto fail;
950 }
951  
952 // ensure the listener only accepts connections from this netif
953 tcp_bind_netif(l, &the_netif);
954  
955 // listen listener
956 if (!(listener = tcp_listen(l))) {
957 BLog(BLOG_ERROR, "tcp_listen failed");
958 tcp_close(l);
959 goto fail;
960 }
961  
962 // setup listener accept handler
963 tcp_accept(listener, listener_accept_func);
964  
965 if (options.netif_ip6addr) {
966 struct tcp_pcb *l_ip6 = tcp_new_ip_type(IPADDR_TYPE_V6);
967 if (!l_ip6) {
968 BLog(BLOG_ERROR, "tcp_new_ip_type failed");
969 goto fail;
970 }
971  
972 if (tcp_bind_to_netif(l_ip6, "ho0") != ERR_OK) {
973 BLog(BLOG_ERROR, "tcp_bind_to_netif failed");
974 tcp_close(l_ip6);
975 goto fail;
976 }
977  
978 tcp_bind_netif(l_ip6, &the_netif);
979  
980 if (!(listener_ip6 = tcp_listen(l_ip6))) {
981 BLog(BLOG_ERROR, "tcp_listen failed");
982 tcp_close(l_ip6);
983 goto fail;
984 }
985  
986 tcp_accept(listener_ip6, listener_accept_func);
987 }
988  
989 return;
990  
991 fail:
992 if (!quitting) {
993 terminate();
994 }
995 }
996  
997 void tcp_timer_handler (void *unused)
998 {
999 ASSERT(!quitting)
1000  
1001 BLog(BLOG_DEBUG, "TCP timer");
1002  
1003 // schedule next timer
1004 BReactor_SetTimer(&ss, &tcp_timer);
1005  
1006 // call the TCP timer function (every 1/4 second)
1007 tcp_tmr();
1008  
1009 // increment tcp_timer_mod4
1010 tcp_timer_mod4 = (tcp_timer_mod4 + 1) % 4;
1011  
1012 // every second, call other timer functions
1013 if (tcp_timer_mod4 == 0) {
1014 #if IP_REASSEMBLY
1015 ASSERT(IP_TMR_INTERVAL == 4 * TCP_TMR_INTERVAL)
1016 ip_reass_tmr();
1017 #endif
1018  
1019 #if LWIP_IPV6
1020 ASSERT(ND6_TMR_INTERVAL == 4 * TCP_TMR_INTERVAL)
1021 nd6_tmr();
1022 #endif
1023  
1024 #if LWIP_IPV6 && LWIP_IPV6_REASS
1025 ASSERT(IP6_REASS_TMR_INTERVAL == 4 * TCP_TMR_INTERVAL)
1026 ip6_reass_tmr();
1027 #endif
1028 }
1029 }
1030  
1031 void device_error_handler (void *unused)
1032 {
1033 ASSERT(!quitting)
1034  
1035 BLog(BLOG_ERROR, "device error");
1036  
1037 terminate();
1038 return;
1039 }
1040  
1041 void device_read_handler_send (void *unused, uint8_t *data, int data_len)
1042 {
1043 ASSERT(!quitting)
1044 ASSERT(data_len >= 0)
1045  
1046 BLog(BLOG_DEBUG, "device: received packet");
1047  
1048 // accept packet
1049 PacketPassInterface_Done(&device_read_interface);
1050  
1051 // process UDP directly
1052 if (process_device_udp_packet(data, data_len)) {
1053 return;
1054 }
1055  
1056 // obtain pbuf
1057 if (data_len > UINT16_MAX) {
1058 BLog(BLOG_WARNING, "device read: packet too large");
1059 return;
1060 }
1061 struct pbuf *p = pbuf_alloc(PBUF_RAW, data_len, PBUF_POOL);
1062 if (!p) {
1063 BLog(BLOG_WARNING, "device read: pbuf_alloc failed");
1064 return;
1065 }
1066  
1067 // write packet to pbuf
1068 ASSERT_FORCE(pbuf_take(p, data, data_len) == ERR_OK)
1069  
1070 // pass pbuf to input
1071 if (the_netif.input(p, &the_netif) != ERR_OK) {
1072 BLog(BLOG_WARNING, "device read: input failed");
1073 pbuf_free(p);
1074 }
1075 }
1076  
1077 int process_device_udp_packet (uint8_t *data, int data_len)
1078 {
1079 ASSERT(data_len >= 0)
1080  
1081 // do nothing if we don't use udpgw or SOCKS UDP
1082 if (udp_mode == UdpModeNone) {
1083 goto fail;
1084 }
1085  
1086 BAddr local_addr;
1087 BAddr remote_addr;
1088 int is_dns;
1089  
1090 uint8_t ip_version = 0;
1091 if (data_len > 0) {
1092 ip_version = (data[0] >> 4);
1093 }
1094  
1095 switch (ip_version) {
1096 case 4: {
1097 // ignore non-UDP packets
1098 if (data_len < sizeof(struct ipv4_header) || data[offsetof(struct ipv4_header, protocol)] != IPV4_PROTOCOL_UDP) {
1099 goto fail;
1100 }
1101  
1102 // parse IPv4 header
1103 struct ipv4_header ipv4_header;
1104 if (!ipv4_check(data, data_len, &ipv4_header, &data, &data_len)) {
1105 goto fail;
1106 }
1107  
1108 // parse UDP
1109 struct udp_header udp_header;
1110 if (!udp_check(data, data_len, &udp_header, &data, &data_len)) {
1111 goto fail;
1112 }
1113  
1114 // verify UDP checksum
1115 uint16_t checksum_in_packet = udp_header.checksum;
1116 udp_header.checksum = 0;
1117 uint16_t checksum_computed = udp_checksum(&udp_header, data, data_len, ipv4_header.source_address, ipv4_header.destination_address);
1118 if (checksum_in_packet != checksum_computed) {
1119 goto fail;
1120 }
1121  
1122 BLog(BLOG_INFO, "UDP: from device %d bytes", data_len);
1123  
1124 // construct addresses
1125 BAddr_InitIPv4(&local_addr, ipv4_header.source_address, udp_header.source_port);
1126 BAddr_InitIPv4(&remote_addr, ipv4_header.destination_address, udp_header.dest_port);
1127  
1128 // if transparent DNS is enabled, any packet arriving at out netif
1129 // address to port 53 is considered a DNS packet
1130 is_dns = (options.udpgw_transparent_dns &&
1131 ipv4_header.destination_address == netif_ipaddr.ipv4 &&
1132 udp_header.dest_port == hton16(53));
1133 } break;
1134  
1135 case 6: {
1136 // ignore if IPv6 support is disabled
1137 if (!options.netif_ip6addr) {
1138 goto fail;
1139 }
1140  
1141 // ignore non-UDP packets
1142 if (data_len < sizeof(struct ipv6_header) || data[offsetof(struct ipv6_header, next_header)] != IPV6_NEXT_UDP) {
1143 goto fail;
1144 }
1145  
1146 // parse IPv6 header
1147 struct ipv6_header ipv6_header;
1148 if (!ipv6_check(data, data_len, &ipv6_header, &data, &data_len)) {
1149 goto fail;
1150 }
1151  
1152 // parse UDP
1153 struct udp_header udp_header;
1154 if (!udp_check(data, data_len, &udp_header, &data, &data_len)) {
1155 goto fail;
1156 }
1157  
1158 // verify UDP checksum
1159 uint16_t checksum_in_packet = udp_header.checksum;
1160 udp_header.checksum = 0;
1161 uint16_t checksum_computed = udp_ip6_checksum(&udp_header, data, data_len, ipv6_header.source_address, ipv6_header.destination_address);
1162 if (checksum_in_packet != checksum_computed) {
1163 goto fail;
1164 }
1165  
1166 BLog(BLOG_INFO, "UDP/IPv6: from device %d bytes", data_len);
1167  
1168 // construct addresses
1169 BAddr_InitIPv6(&local_addr, ipv6_header.source_address, udp_header.source_port);
1170 BAddr_InitIPv6(&remote_addr, ipv6_header.destination_address, udp_header.dest_port);
1171  
1172 // TODO dns
1173 is_dns = 0;
1174 } break;
1175  
1176 default: {
1177 goto fail;
1178 } break;
1179 }
1180  
1181 // check payload length
1182 if (data_len > udp_mtu) {
1183 BLog(BLOG_ERROR, "packet is too large, cannot send to udpgw");
1184 goto fail;
1185 }
1186  
1187 // submit packet to udpgw or SOCKS UDP
1188 if (udp_mode == UdpModeUdpgw) {
1189 SocksUdpGwClient_SubmitPacket(&udpgw_client, local_addr, remote_addr,
1190 is_dns, data, data_len);
1191 } else if (udp_mode == UdpModeSocks) {
1192 SocksUdpClient_SubmitPacket(&socks_udp_client, local_addr, remote_addr, data, data_len);
1193 }
1194  
1195 return 1;
1196  
1197 fail:
1198 return 0;
1199 }
1200  
1201 err_t netif_init_func (struct netif *netif)
1202 {
1203 BLog(BLOG_DEBUG, "netif func init");
1204  
1205 netif->name[0] = 'h';
1206 netif->name[1] = 'o';
1207 netif->output = netif_output_func;
1208 netif->output_ip6 = netif_output_ip6_func;
1209  
1210 return ERR_OK;
1211 }
1212  
1213 err_t netif_output_func (struct netif *netif, struct pbuf *p, const ip4_addr_t *ipaddr)
1214 {
1215 return common_netif_output(netif, p);
1216 }
1217  
1218 err_t netif_output_ip6_func (struct netif *netif, struct pbuf *p, const ip6_addr_t *ipaddr)
1219 {
1220 return common_netif_output(netif, p);
1221 }
1222  
1223 err_t common_netif_output (struct netif *netif, struct pbuf *p)
1224 {
1225 SYNC_DECL
1226  
1227 BLog(BLOG_DEBUG, "device write: send packet");
1228  
1229 if (quitting) {
1230 return ERR_OK;
1231 }
1232  
1233 // if there is just one chunk, send it directly, else via buffer
1234 if (!p->next) {
1235 if (p->len > BTap_GetMTU(&device)) {
1236 BLog(BLOG_WARNING, "netif func output: no space left");
1237 goto out;
1238 }
1239  
1240 SYNC_FROMHERE
1241 BTap_Send(&device, (uint8_t *)p->payload, p->len);
1242 SYNC_COMMIT
1243 } else {
1244 int len = 0;
1245 do {
1246 if (p->len > BTap_GetMTU(&device) - len) {
1247 BLog(BLOG_WARNING, "netif func output: no space left");
1248 goto out;
1249 }
1250 memcpy(device_write_buf + len, p->payload, p->len);
1251 len += p->len;
1252 } while (p = p->next);
1253  
1254 SYNC_FROMHERE
1255 BTap_Send(&device, device_write_buf, len);
1256 SYNC_COMMIT
1257 }
1258  
1259 out:
1260 return ERR_OK;
1261 }
1262  
1263 err_t netif_input_func (struct pbuf *p, struct netif *inp)
1264 {
1265 uint8_t ip_version = 0;
1266 if (p->len > 0) {
1267 ip_version = (((uint8_t *)p->payload)[0] >> 4);
1268 }
1269  
1270 switch (ip_version) {
1271 case 4: {
1272 return ip_input(p, inp);
1273 } break;
1274 case 6: {
1275 if (options.netif_ip6addr) {
1276 return ip6_input(p, inp);
1277 }
1278 } break;
1279 }
1280  
1281 pbuf_free(p);
1282 return ERR_OK;
1283 }
1284  
1285 void client_logfunc (struct tcp_client *client)
1286 {
1287 char local_addr_s[BADDR_MAX_PRINT_LEN];
1288 BAddr_Print(&client->local_addr, local_addr_s);
1289 char remote_addr_s[BADDR_MAX_PRINT_LEN];
1290 BAddr_Print(&client->remote_addr, remote_addr_s);
1291  
1292 BLog_Append("%05d (%s %s): ", num_clients, local_addr_s, remote_addr_s);
1293 }
1294  
1295 void client_log (struct tcp_client *client, int level, const char *fmt, ...)
1296 {
1297 va_list vl;
1298 va_start(vl, fmt);
1299 BLog_LogViaFuncVarArg((BLog_logfunc)client_logfunc, client, BLOG_CURRENT_CHANNEL, level, fmt, vl);
1300 va_end(vl);
1301 }
1302  
1303 err_t listener_accept_func (void *arg, struct tcp_pcb *newpcb, err_t err)
1304 {
1305 ASSERT(err == ERR_OK)
1306  
1307 // allocate client structure
1308 struct tcp_client *client = (struct tcp_client *)malloc(sizeof(*client));
1309 if (!client) {
1310 BLog(BLOG_ERROR, "listener accept: malloc failed");
1311 goto fail0;
1312 }
1313 client->socks_username = NULL;
1314  
1315 SYNC_DECL
1316 SYNC_FROMHERE
1317  
1318 // read addresses
1319 client->local_addr = baddr_from_lwip(&newpcb->local_ip, newpcb->local_port);
1320 client->remote_addr = baddr_from_lwip(&newpcb->remote_ip, newpcb->remote_port);
1321  
1322 // get destination address
1323 BAddr addr = client->local_addr;
1324 #ifdef OVERRIDE_DEST_ADDR
1325 ASSERT_FORCE(BAddr_Parse2(&addr, OVERRIDE_DEST_ADDR, NULL, 0, 1))
1326 #endif
1327  
1328 // add source address to username if requested
1329 if (options.username && options.append_source_to_username) {
1330 char addr_str[BADDR_MAX_PRINT_LEN];
1331 BAddr_Print(&client->remote_addr, addr_str);
1332 client->socks_username = concat_strings(3, options.username, "@", addr_str);
1333 if (!client->socks_username) {
1334 goto fail1;
1335 }
1336 socks_auth_info[1].password.username = client->socks_username;
1337 socks_auth_info[1].password.username_len = strlen(client->socks_username);
1338 }
1339  
1340 // init SOCKS
1341 if (!BSocksClient_Init(&client->socks_client,
1342 socks_server_addr, socks_auth_info, socks_num_auth_info, addr, /*udp=*/false,
1343 (BSocksClient_handler)client_socks_handler, client, &ss))
1344 {
1345 BLog(BLOG_ERROR, "listener accept: BSocksClient_Init failed");
1346 goto fail1;
1347 }
1348  
1349 // init aborted and dead_aborted
1350 client->aborted = 0;
1351 DEAD_INIT(client->dead_aborted);
1352  
1353 // add to linked list
1354 LinkedList1_Append(&tcp_clients, &client->list_node);
1355  
1356 // increment counter
1357 ASSERT(num_clients >= 0)
1358 num_clients++;
1359  
1360 // set pcb
1361 client->pcb = newpcb;
1362  
1363 // set client not closed
1364 client->client_closed = 0;
1365  
1366 // setup handler argument
1367 tcp_arg(client->pcb, client);
1368  
1369 // setup handlers
1370 tcp_err(client->pcb, client_err_func);
1371 tcp_recv(client->pcb, client_recv_func);
1372  
1373 // setup buffer
1374 client->buf_used = 0;
1375  
1376 // set SOCKS not up, not closed
1377 client->socks_up = 0;
1378 client->socks_closed = 0;
1379  
1380 client_log(client, BLOG_INFO, "accepted");
1381  
1382 DEAD_ENTER(client->dead_aborted)
1383 SYNC_COMMIT
1384 DEAD_LEAVE2(client->dead_aborted)
1385  
1386 // Return ERR_ABRT if and only if tcp_abort was called from this callback.
1387 return (DEAD_KILLED > 0) ? ERR_ABRT : ERR_OK;
1388  
1389 fail1:
1390 SYNC_BREAK
1391 free(client->socks_username);
1392 free(client);
1393 fail0:
1394 return ERR_MEM;
1395 }
1396  
1397 void client_handle_freed_client (struct tcp_client *client)
1398 {
1399 ASSERT(!client->client_closed)
1400  
1401 // pcb was taken care of by the caller
1402  
1403 // set client closed
1404 client->client_closed = 1;
1405  
1406 // if we have data to be sent to SOCKS and can send it, keep sending
1407 if (client->buf_used > 0 && !client->socks_closed) {
1408 client_log(client, BLOG_INFO, "waiting untill buffered data is sent to SOCKS");
1409 } else {
1410 if (!client->socks_closed) {
1411 client_free_socks(client);
1412 } else {
1413 client_dealloc(client);
1414 }
1415 }
1416 }
1417  
1418 void client_free_client (struct tcp_client *client)
1419 {
1420 ASSERT(!client->client_closed)
1421  
1422 // remove callbacks
1423 tcp_err(client->pcb, NULL);
1424 tcp_recv(client->pcb, NULL);
1425 tcp_sent(client->pcb, NULL);
1426  
1427 // free pcb
1428 err_t err = tcp_close(client->pcb);
1429 if (err != ERR_OK) {
1430 client_log(client, BLOG_ERROR, "tcp_close failed (%d)", err);
1431 client_abort_pcb(client);
1432 }
1433  
1434 client_handle_freed_client(client);
1435 }
1436  
1437 void client_abort_client (struct tcp_client *client)
1438 {
1439 ASSERT(!client->client_closed)
1440  
1441 // remove callbacks
1442 tcp_err(client->pcb, NULL);
1443 tcp_recv(client->pcb, NULL);
1444 tcp_sent(client->pcb, NULL);
1445  
1446 // abort
1447 client_abort_pcb(client);
1448  
1449 client_handle_freed_client(client);
1450 }
1451  
1452 void client_abort_pcb (struct tcp_client *client)
1453 {
1454 ASSERT(!client->aborted)
1455  
1456 // abort the PCB
1457 tcp_abort(client->pcb);
1458  
1459 // mark aborted
1460 client->aborted = 1;
1461  
1462 // kill dead_aborted with value 1 signaling that tcp_abort was done;
1463 // this is contrasted to killing with value -1 from client_dealloc
1464 // signaling that the client was freed without tcp_abort
1465 DEAD_KILL_WITH(client->dead_aborted, 1);
1466 }
1467  
1468 void client_free_socks (struct tcp_client *client)
1469 {
1470 ASSERT(!client->socks_closed)
1471  
1472 // stop sending to SOCKS
1473 if (client->socks_up) {
1474 // stop receiving from client
1475 if (!client->client_closed) {
1476 tcp_recv(client->pcb, NULL);
1477 }
1478 }
1479  
1480 // free SOCKS
1481 BSocksClient_Free(&client->socks_client);
1482  
1483 // set SOCKS closed
1484 client->socks_closed = 1;
1485  
1486 // if we have data to be sent to the client and we can send it, keep sending
1487 if (client->socks_up && (client->socks_recv_buf_used >= 0 || client->socks_recv_tcp_pending > 0) && !client->client_closed) {
1488 client_log(client, BLOG_INFO, "waiting until buffered data is sent to client");
1489 } else {
1490 if (!client->client_closed) {
1491 client_free_client(client);
1492 } else {
1493 client_dealloc(client);
1494 }
1495 }
1496 }
1497  
1498 void client_murder (struct tcp_client *client)
1499 {
1500 // free client
1501 if (!client->client_closed) {
1502 // remove callbacks
1503 tcp_err(client->pcb, NULL);
1504 tcp_recv(client->pcb, NULL);
1505 tcp_sent(client->pcb, NULL);
1506  
1507 // abort
1508 client_abort_pcb(client);
1509  
1510 // set client closed
1511 client->client_closed = 1;
1512 }
1513  
1514 // free SOCKS
1515 if (!client->socks_closed) {
1516 // free SOCKS
1517 BSocksClient_Free(&client->socks_client);
1518  
1519 // set SOCKS closed
1520 client->socks_closed = 1;
1521 }
1522  
1523 // dealloc entry
1524 client_dealloc(client);
1525 }
1526  
1527 void client_dealloc (struct tcp_client *client)
1528 {
1529 ASSERT(client->client_closed)
1530 ASSERT(client->socks_closed)
1531  
1532 // decrement counter
1533 ASSERT(num_clients > 0)
1534 num_clients--;
1535  
1536 // remove client entry
1537 LinkedList1_Remove(&tcp_clients, &client->list_node);
1538  
1539 // kill dead_aborted with value -1 unless already aborted
1540 if (!client->aborted) {
1541 DEAD_KILL_WITH(client->dead_aborted, -1);
1542 }
1543  
1544 // free memory
1545 free(client->socks_username);
1546 free(client);
1547 }
1548  
1549 void client_err_func (void *arg, err_t err)
1550 {
1551 struct tcp_client *client = (struct tcp_client *)arg;
1552 ASSERT(!client->client_closed)
1553  
1554 client_log(client, BLOG_INFO, "client error (%d)", (int)err);
1555  
1556 // the pcb was taken care of by the caller
1557 client_handle_freed_client(client);
1558 }
1559  
1560 err_t client_recv_func (void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
1561 {
1562 struct tcp_client *client = (struct tcp_client *)arg;
1563 ASSERT(!client->client_closed)
1564 ASSERT(err == ERR_OK) // checked in lwIP source. Otherwise, I've no idea what should
1565 // be done with the pbuf in case of an error.
1566  
1567 DEAD_ENTER(client->dead_aborted)
1568  
1569 if (!p) {
1570 client_log(client, BLOG_INFO, "client closed");
1571 client_free_client(client);
1572 } else {
1573 ASSERT(p->tot_len > 0)
1574  
1575 // check if we have enough buffer
1576 if (p->tot_len > sizeof(client->buf) - client->buf_used) {
1577 client_log(client, BLOG_ERROR, "no buffer for data !?!");
1578 DEAD_LEAVE2(client->dead_aborted)
1579 return ERR_MEM;
1580 }
1581  
1582 // copy data to buffer
1583 ASSERT_EXECUTE(pbuf_copy_partial(p, client->buf + client->buf_used, p->tot_len, 0) == p->tot_len)
1584 client->buf_used += p->tot_len;
1585  
1586 // free pbuff
1587 int p_tot_len = p->tot_len;
1588 pbuf_free(p);
1589  
1590 // if there was nothing in the buffer before, and SOCKS is up, start send data
1591 if (client->buf_used == p_tot_len && client->socks_up) {
1592 ASSERT(!client->socks_closed) // this callback is removed when SOCKS is closed
1593  
1594 SYNC_DECL
1595 SYNC_FROMHERE
1596 client_send_to_socks(client);
1597 SYNC_COMMIT
1598 }
1599 }
1600  
1601 DEAD_LEAVE2(client->dead_aborted)
1602  
1603 // Return ERR_ABRT if and only if tcp_abort was called from this callback.
1604 return (DEAD_KILLED > 0) ? ERR_ABRT : ERR_OK;
1605 }
1606  
1607 void client_socks_handler (struct tcp_client *client, int event)
1608 {
1609 ASSERT(!client->socks_closed)
1610  
1611 switch (event) {
1612 case BSOCKSCLIENT_EVENT_ERROR: {
1613 client_log(client, BLOG_INFO, "SOCKS error");
1614  
1615 client_free_socks(client);
1616 } break;
1617  
1618 case BSOCKSCLIENT_EVENT_UP: {
1619 ASSERT(!client->socks_up)
1620  
1621 client_log(client, BLOG_INFO, "SOCKS up");
1622  
1623 // init sending
1624 client->socks_send_if = BSocksClient_GetSendInterface(&client->socks_client);
1625 StreamPassInterface_Sender_Init(client->socks_send_if, (StreamPassInterface_handler_done)client_socks_send_handler_done, client);
1626  
1627 // init receiving
1628 client->socks_recv_if = BSocksClient_GetRecvInterface(&client->socks_client);
1629 StreamRecvInterface_Receiver_Init(client->socks_recv_if, (StreamRecvInterface_handler_done)client_socks_recv_handler_done, client);
1630 client->socks_recv_buf_used = -1;
1631 client->socks_recv_tcp_pending = 0;
1632 if (!client->client_closed) {
1633 tcp_sent(client->pcb, client_sent_func);
1634 }
1635  
1636 // set up
1637 client->socks_up = 1;
1638  
1639 // start sending data if there is any
1640 if (client->buf_used > 0) {
1641 client_send_to_socks(client);
1642 }
1643  
1644 // start receiving data if client is still up
1645 if (!client->client_closed) {
1646 client_socks_recv_initiate(client);
1647 }
1648 } break;
1649  
1650 case BSOCKSCLIENT_EVENT_ERROR_CLOSED: {
1651 ASSERT(client->socks_up)
1652  
1653 client_log(client, BLOG_INFO, "SOCKS closed");
1654  
1655 client_free_socks(client);
1656 } break;
1657 }
1658 }
1659  
1660 void client_send_to_socks (struct tcp_client *client)
1661 {
1662 ASSERT(!client->socks_closed)
1663 ASSERT(client->socks_up)
1664 ASSERT(client->buf_used > 0)
1665  
1666 // schedule sending
1667 StreamPassInterface_Sender_Send(client->socks_send_if, client->buf, client->buf_used);
1668 }
1669  
1670 void client_socks_send_handler_done (struct tcp_client *client, int data_len)
1671 {
1672 ASSERT(!client->socks_closed)
1673 ASSERT(client->socks_up)
1674 ASSERT(client->buf_used > 0)
1675 ASSERT(data_len > 0)
1676 ASSERT(data_len <= client->buf_used)
1677  
1678 // remove sent data from buffer
1679 memmove(client->buf, client->buf + data_len, client->buf_used - data_len);
1680 client->buf_used -= data_len;
1681  
1682 if (!client->client_closed) {
1683 // confirm sent data
1684 tcp_recved(client->pcb, data_len);
1685 }
1686  
1687 if (client->buf_used > 0) {
1688 // send any further data
1689 StreamPassInterface_Sender_Send(client->socks_send_if, client->buf, client->buf_used);
1690 }
1691 else if (client->client_closed) {
1692 // client was closed we've sent everything we had buffered; we're done with it
1693 client_log(client, BLOG_INFO, "removing after client went down");
1694  
1695 client_free_socks(client);
1696 }
1697 }
1698  
1699 void client_socks_recv_initiate (struct tcp_client *client)
1700 {
1701 ASSERT(!client->client_closed)
1702 ASSERT(!client->socks_closed)
1703 ASSERT(client->socks_up)
1704 ASSERT(client->socks_recv_buf_used == -1)
1705  
1706 StreamRecvInterface_Receiver_Recv(client->socks_recv_if, client->socks_recv_buf, sizeof(client->socks_recv_buf));
1707 }
1708  
1709 void client_socks_recv_handler_done (struct tcp_client *client, int data_len)
1710 {
1711 ASSERT(data_len > 0)
1712 ASSERT(data_len <= sizeof(client->socks_recv_buf))
1713 ASSERT(!client->socks_closed)
1714 ASSERT(client->socks_up)
1715 ASSERT(client->socks_recv_buf_used == -1)
1716  
1717 // if client was closed, stop receiving
1718 if (client->client_closed) {
1719 return;
1720 }
1721  
1722 // set amount of data in buffer
1723 client->socks_recv_buf_used = data_len;
1724 client->socks_recv_buf_sent = 0;
1725 client->socks_recv_waiting = 0;
1726  
1727 // send to client
1728 if (client_socks_recv_send_out(client) < 0) {
1729 return;
1730 }
1731  
1732 // continue receiving if needed
1733 if (client->socks_recv_buf_used == -1) {
1734 client_socks_recv_initiate(client);
1735 }
1736 }
1737  
1738 int client_socks_recv_send_out (struct tcp_client *client)
1739 {
1740 ASSERT(!client->client_closed)
1741 ASSERT(client->socks_up)
1742 ASSERT(client->socks_recv_buf_used > 0)
1743 ASSERT(client->socks_recv_buf_sent < client->socks_recv_buf_used)
1744 ASSERT(!client->socks_recv_waiting)
1745  
1746 // return value -1 means tcp_abort() was done,
1747 // 0 means it wasn't and the client (pcb) is still up
1748  
1749 do {
1750 int to_write = bmin_int(client->socks_recv_buf_used - client->socks_recv_buf_sent, tcp_sndbuf(client->pcb));
1751 if (to_write == 0) {
1752 break;
1753 }
1754  
1755 err_t err = tcp_write(client->pcb, client->socks_recv_buf + client->socks_recv_buf_sent, to_write, TCP_WRITE_FLAG_COPY);
1756 if (err != ERR_OK) {
1757 if (err == ERR_MEM) {
1758 break;
1759 }
1760  
1761 client_log(client, BLOG_INFO, "tcp_write failed (%d)", (int)err);
1762  
1763 client_abort_client(client);
1764 return -1;
1765 }
1766  
1767 client->socks_recv_buf_sent += to_write;
1768 client->socks_recv_tcp_pending += to_write;
1769 } while (client->socks_recv_buf_sent < client->socks_recv_buf_used);
1770  
1771 // start sending now
1772 err_t err = tcp_output(client->pcb);
1773 if (err != ERR_OK) {
1774 client_log(client, BLOG_INFO, "tcp_output failed (%d)", (int)err);
1775  
1776 client_abort_client(client);
1777 return -1;
1778 }
1779  
1780 // more data to queue?
1781 if (client->socks_recv_buf_sent < client->socks_recv_buf_used) {
1782 if (client->socks_recv_tcp_pending == 0) {
1783 client_log(client, BLOG_ERROR, "can't queue data, but all data was confirmed !?!");
1784  
1785 client_abort_client(client);
1786 return -1;
1787 }
1788  
1789 // set waiting, continue in client_sent_func
1790 client->socks_recv_waiting = 1;
1791 return 0;
1792 }
1793  
1794 // everything was queued
1795 client->socks_recv_buf_used = -1;
1796  
1797 return 0;
1798 }
1799  
1800 err_t client_sent_func (void *arg, struct tcp_pcb *tpcb, u16_t len)
1801 {
1802 struct tcp_client *client = (struct tcp_client *)arg;
1803  
1804 ASSERT(!client->client_closed)
1805 ASSERT(client->socks_up)
1806 ASSERT(len > 0)
1807 ASSERT(len <= client->socks_recv_tcp_pending)
1808  
1809 DEAD_ENTER(client->dead_aborted)
1810  
1811 // decrement pending
1812 client->socks_recv_tcp_pending -= len;
1813  
1814 // continue queuing
1815 if (client->socks_recv_buf_used > 0) {
1816 ASSERT(client->socks_recv_waiting)
1817 ASSERT(client->socks_recv_buf_sent < client->socks_recv_buf_used)
1818  
1819 // set not waiting
1820 client->socks_recv_waiting = 0;
1821  
1822 // possibly send more data
1823 if (client_socks_recv_send_out(client) < 0) {
1824 goto out;
1825 }
1826  
1827 // we just queued some data, so it can't have been confirmed yet
1828 ASSERT(client->socks_recv_tcp_pending > 0)
1829  
1830 // continue receiving if needed
1831 if (client->socks_recv_buf_used == -1 && !client->socks_closed) {
1832 SYNC_DECL
1833 SYNC_FROMHERE
1834 client_socks_recv_initiate(client);
1835 SYNC_COMMIT
1836 }
1837 } else {
1838 // have we sent everything after SOCKS was closed?
1839 if (client->socks_closed && client->socks_recv_tcp_pending == 0) {
1840 client_log(client, BLOG_INFO, "removing after SOCKS went down");
1841 client_free_client(client);
1842 }
1843 }
1844  
1845 out:
1846 DEAD_LEAVE2(client->dead_aborted)
1847  
1848 // Return ERR_ABRT if and only if tcp_abort was called from this callback.
1849 return (DEAD_KILLED > 0) ? ERR_ABRT : ERR_OK;
1850 }
1851  
1852 void udp_send_packet_to_device (void *unused, BAddr local_addr, BAddr remote_addr, const uint8_t *data, int data_len)
1853 {
1854 ASSERT(udp_mode != UdpModeNone)
1855 ASSERT(local_addr.type == BADDR_TYPE_IPV4 || local_addr.type == BADDR_TYPE_IPV6)
1856 ASSERT(local_addr.type == remote_addr.type)
1857 ASSERT(data_len >= 0)
1858  
1859 char const *source_name = (udp_mode == UdpModeUdpgw) ? "udpgw" : "SOCKS UDP";
1860  
1861 int packet_length = 0;
1862  
1863 switch (local_addr.type) {
1864 case BADDR_TYPE_IPV4: {
1865 BLog(BLOG_INFO, "UDP: from %s %d bytes", source_name, data_len);
1866  
1867 if (data_len > UINT16_MAX - (sizeof(struct ipv4_header) + sizeof(struct udp_header)) ||
1868 data_len > BTap_GetMTU(&device) - (int)(sizeof(struct ipv4_header) + sizeof(struct udp_header))
1869 ) {
1870 BLog(BLOG_ERROR, "UDP: packet is too large");
1871 return;
1872 }
1873  
1874 // build IP header
1875 struct ipv4_header iph;
1876 iph.version4_ihl4 = IPV4_MAKE_VERSION_IHL(sizeof(iph));
1877 iph.ds = hton8(0);
1878 iph.total_length = hton16(sizeof(iph) + sizeof(struct udp_header) + data_len);
1879 iph.identification = hton16(0);
1880 iph.flags3_fragmentoffset13 = hton16(0);
1881 iph.ttl = hton8(64);
1882 iph.protocol = hton8(IPV4_PROTOCOL_UDP);
1883 iph.checksum = hton16(0);
1884 iph.source_address = remote_addr.ipv4.ip;
1885 iph.destination_address = local_addr.ipv4.ip;
1886 iph.checksum = ipv4_checksum(&iph, NULL, 0);
1887  
1888 // build UDP header
1889 struct udp_header udph;
1890 udph.source_port = remote_addr.ipv4.port;
1891 udph.dest_port = local_addr.ipv4.port;
1892 udph.length = hton16(sizeof(udph) + data_len);
1893 udph.checksum = hton16(0);
1894 udph.checksum = udp_checksum(&udph, data, data_len, iph.source_address, iph.destination_address);
1895  
1896 // write packet
1897 memcpy(device_write_buf, &iph, sizeof(iph));
1898 memcpy(device_write_buf + sizeof(iph), &udph, sizeof(udph));
1899 memcpy(device_write_buf + sizeof(iph) + sizeof(udph), data, data_len);
1900 packet_length = sizeof(iph) + sizeof(udph) + data_len;
1901 } break;
1902  
1903 case BADDR_TYPE_IPV6: {
1904 BLog(BLOG_INFO, "UDP/IPv6: from %s %d bytes", source_name, data_len);
1905  
1906 if (!options.netif_ip6addr) {
1907 BLog(BLOG_ERROR, "got IPv6 packet from %s but IPv6 is disabled", source_name);
1908 return;
1909 }
1910  
1911 if (data_len > UINT16_MAX - sizeof(struct udp_header) ||
1912 data_len > BTap_GetMTU(&device) - (int)(sizeof(struct ipv6_header) + sizeof(struct udp_header))
1913 ) {
1914 BLog(BLOG_ERROR, "UDP/IPv6: packet is too large");
1915 return;
1916 }
1917  
1918 // build IPv6 header
1919 struct ipv6_header iph;
1920 iph.version4_tc4 = hton8((6 << 4));
1921 iph.tc4_fl4 = hton8(0);
1922 iph.fl = hton16(0);
1923 iph.payload_length = hton16(sizeof(struct udp_header) + data_len);
1924 iph.next_header = hton8(IPV6_NEXT_UDP);
1925 iph.hop_limit = hton8(64);
1926 memcpy(iph.source_address, remote_addr.ipv6.ip, 16);
1927 memcpy(iph.destination_address, local_addr.ipv6.ip, 16);
1928  
1929 // build UDP header
1930 struct udp_header udph;
1931 udph.source_port = remote_addr.ipv6.port;
1932 udph.dest_port = local_addr.ipv6.port;
1933 udph.length = hton16(sizeof(udph) + data_len);
1934 udph.checksum = hton16(0);
1935 udph.checksum = udp_ip6_checksum(&udph, data, data_len, iph.source_address, iph.destination_address);
1936  
1937 // write packet
1938 memcpy(device_write_buf, &iph, sizeof(iph));
1939 memcpy(device_write_buf + sizeof(iph), &udph, sizeof(udph));
1940 memcpy(device_write_buf + sizeof(iph) + sizeof(udph), data, data_len);
1941 packet_length = sizeof(iph) + sizeof(udph) + data_len;
1942 } break;
1943 }
1944  
1945 // submit packet
1946 BTap_Send(&device, device_write_buf, packet_length);
1947 }