1/*
2 * This program is free software; you can redistribute it and/or
3 * modify it under the terms of the GNU General Public License as
4 * published by the Free Software Foundation; either version 2 of
5 * the License, or (at your option) any later version.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
15 * MA 02111-1307 USA
16 */
17#include <rtconfig.h>
18#ifdef RTCONFIG_USB_MODEM
19#include <usb_info.h>
20#endif
21
22#include "wanduck.h"
23#ifdef RTCONFIG_TMOBILE
24#include <sys/reboot.h>
25#endif
26
27#define NO_DETECT_INTERNET
28#define NO_IOS_DETECT_INTERNET
29#ifdef RTCONFIG_LAN4WAN_LED
30int LanWanLedCtrl(void);
31#endif
32
33static int wdbg = 0;
34
35#define _wdbg(fmt, args...) do { if (wdbg) { dbg(fmt, ## args); }; } while (0)
36
37int update_wan_leds(int wan_unit)
38{
39#if defined(RTCONFIG_LANWAN_LED)
40#if defined(RTCONFIG_WANRED_LED)
41	int mode = sw_mode, l = link_wan[wan_unit], state;
42	char s[] = "wanX_state_tXXX";
43
44	if (wan_unit < 0 || wan_unit >= WAN_UNIT_MAX)
45		return -1;
46
47	if (mode < SW_MODE_ROUTER || mode > SW_MODE_HOTSPOT)
48		mode = nvram_get_int("sw_mode");
49	/* Turn on/off WAN BLUE/RED LED in accordance with wan status. */
50	switch (mode) {
51	case SW_MODE_ROUTER:
52#if defined(RTCONFIG_DUALWAN)
53		if (!strcmp(dualwan_mode, "lb")) {
54			int u, onoff = 0;
55
56			if (wan_unit)
57				return 0;
58
59			/* Turn on WAN BLUE LED if any WAN unit is connected in load-balanced mode. */
60			for (u = WAN_UNIT_FIRST; !onoff && u < WAN_UNIT_MAX; ++u) {
61				sprintf(s, "wan%d_state_t", u);
62				state = nvram_get_int(s);
63				l = link_wan[u];
64				if (dualwan_unit__nonusbif(u))
65					l = get_wanports_status(u);
66
67				if (l == CONNED && state == WAN_STATE_CONNECTED)
68					onoff++;
69			}
70
71			if (onoff) {
72				wan_red_led_control(LED_OFF);
73				led_control(LED_WAN, LED_ON);
74			} else {
75				wan_red_led_control(LED_ON);
76				led_control(LED_WAN, LED_OFF);
77			}
78		} else {
79#endif
80			if (wan_primary_ifunit() != wan_unit)
81				return 0;
82
83			sprintf(s, "wan%d_state_t", wan_unit);
84			state = nvram_get_int(s);
85			if (dualwan_unit__nonusbif(wan_unit))
86				l = get_wanports_status(wan_unit);
87
88			if (l == CONNED && state == WAN_STATE_CONNECTED) {
89				wan_red_led_control(LED_OFF);
90				led_control(LED_WAN, LED_ON);
91			} else {
92				wan_red_led_control(LED_ON);
93				led_control(LED_WAN, LED_OFF);
94			}
95#if defined(RTCONFIG_DUALWAN)
96		}
97#endif
98		break;
99	case SW_MODE_REPEATER:	/* fallthrough */
100	case SW_MODE_AP:
101		wan_red_led_control(LED_OFF);
102		break;
103	}
104#else	/* !RTCONFIG_WANRED_LED */
105	/* Turn on/off WAN LED in accordance with link status of WAN port */
106	if (link_wan[wan_unit]) {
107		led_control(LED_WAN, LED_ON);
108	} else {
109		led_control(LED_WAN, LED_OFF);
110	}
111#endif	/* RTCONFIG_WANRED_LED */
112#endif	/* RTCONFIG_LANWAN_LED */
113
114	return 0;
115}
116
117static void safe_leave(int signo){
118	csprintf("\n## wanduck.safeexit ##\n");
119	signal(SIGTERM, SIG_IGN);
120	signal(SIGUSR1, SIG_IGN);
121	signal(SIGUSR2, SIG_IGN);
122	signal(SIGINT, SIG_IGN);
123
124	FD_ZERO(&allset);
125	close(http_sock);
126	close(dns_sock);
127
128	int i, ret;
129	for(i = 0; i < maxfd; ++i){
130		ret = close(i);
131		csprintf("## close %d: result=%d.\n", i, ret);
132	}
133
134#ifndef RTCONFIG_BCMARM
135	sleep(1);
136#endif
137
138#ifdef RTCONFIG_WIRELESSREPEATER
139	if(sw_mode == SW_MODE_REPEATER){
140		eval("ebtables", "-t", "broute", "-F");
141		eval("ebtables", "-t", "filter", "-F");
142		f_write_string("/proc/net/dnsmqctrl", "", 0, 0);
143	}
144#endif
145
146		int len;
147		char *fn = NAT_RULES, ln[PATH_MAX];
148		struct stat s;
149
150		csprintf("\n# Disable direct rule(exit wanduck)\n");
151
152		rule_setup = 0;
153		conn_changed_state[current_wan_unit] = CONNED; // for cleaning the redirect rules.
154
155#if 0
156		// in the function safe_leave(), couldn't set any nvram using nvram_set().
157		// So the notify mechanism would be invalid.
158#if 0
159		handle_wan_line(current_wan_unit, rule_setup);
160#else // or
161		start_nat_rules();
162#endif
163#else
164		// Couldn't directly use nvram_set().
165		// Must use the command: nvram, and set the nat_state.
166		char buf[16];
167		FILE *fp = fopen(NAT_RULES, "r");
168
169		memset(buf, 0, 16);
170		if(fp != NULL){
171			fclose(fp);
172
173			if (!lstat(NAT_RULES, &s) && S_ISLNK(s.st_mode) &&
174			    (len = readlink(NAT_RULES, ln, sizeof(ln))) > 0) {
175				ln[len] = '\0';
176				fn = ln;
177			}
178
179			sprintf(buf, "nat_state=%d", NAT_STATE_NORMAL);
180			eval("nvram", "set", buf);
181
182			csprintf("%s: apply the nat_rules(%s): %s!\n", __FUNCTION__, fn, buf);
183			logmessage("wanduck exit", "apply the nat_rules(%s)!", fn);
184
185			setup_ct_timeout(TRUE);
186			setup_udp_timeout(TRUE);
187
188			eval("iptables-restore", NAT_RULES);
189		}
190		else{
191			sprintf(buf, "nat_state=%d", NAT_STATE_INITIALIZING);
192			eval("nvram", "set", buf);
193
194			csprintf("%s: initial the nat_rules: %s!\n", __FUNCTION__, buf);
195			logmessage("wanduck exit", "initial the nat_rules!");
196		}
197#endif
198
199	remove(WANDUCK_PID_FILE);
200
201	csprintf("\n# return(exit wanduck)\n");
202	exit(0);
203}
204
205void get_related_nvram(){
206	int unit;
207
208	sw_mode = nvram_get_int("sw_mode");
209
210	boot_end = nvram_get_int("success_start_service");
211
212	if(nvram_match("x_Setting", "1"))
213		isFirstUse = 0;
214	else
215		isFirstUse = 1;
216
217	if(nvram_match("nat_redirect_enable", "0"))
218		nat_redirect_enable = 0;
219	else
220		nat_redirect_enable = 1;
221
222#ifdef RTCONFIG_WIRELESSREPEATER
223	if(strlen(nvram_safe_get("wlc_ssid")) > 0)
224		setAP = 1;
225	else
226		setAP = 0;
227#endif
228
229#ifdef RTCONFIG_DUALWAN
230	memset(dualwan_mode, 0, 8);
231	strcpy(dualwan_mode, nvram_safe_get("wans_mode"));
232	memset(dualwan_wans, 0, 16);
233	strcpy(dualwan_wans, nvram_safe_get("wans_dualwan"));
234
235	memset(wandog_target, 0, PATH_MAX);
236	if(sw_mode == SW_MODE_ROUTER){
237		wandog_enable = nvram_get_int("wandog_enable");
238		scan_interval = nvram_get_int("wandog_interval");
239		for(unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit)
240			max_disconn_count[unit] = nvram_get_int("wandog_maxfail");
241		wandog_delay = nvram_get_int("wandog_delay");
242
243		if((!strcmp(dualwan_mode, "fo") || !strcmp(dualwan_mode, "fb"))
244				&& wandog_enable == 1
245				){
246			strcpy(wandog_target, nvram_safe_get("wandog_target"));
247		}
248
249		if(!strcmp(dualwan_mode, "fb")){
250			max_fb_count = nvram_get_int("wandog_fb_count");
251			max_fb_wait_time = scan_interval*max_fb_count;
252		}
253	}
254	else{
255		wandog_enable = 0;
256		scan_interval = DEFAULT_SCAN_INTERVAL;
257		for(unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit)
258			max_disconn_count[unit] = DEFAULT_MAX_DISCONN_COUNT;
259		wandog_delay = -1;
260	}
261#else
262	wandog_enable = 0;
263	scan_interval = DEFAULT_SCAN_INTERVAL;
264	for(unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit)
265		max_disconn_count[unit] = DEFAULT_MAX_DISCONN_COUNT;
266#endif
267	for(unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit)
268		max_wait_time[unit] = scan_interval*max_disconn_count[unit];
269}
270
271void get_lan_nvram(){
272	char nvram_name[16];
273
274	current_lan_unit = nvram_get_int("lan_unit");
275
276	memset(prefix_lan, 0, 8);
277	if(current_lan_unit < 0)
278		strcpy(prefix_lan, "lan_");
279	else
280		sprintf(prefix_lan, "lan%d_", current_lan_unit);
281
282	memset(current_lan_ifname, 0, 16);
283	strcpy(current_lan_ifname, nvram_safe_get(strcat_r(prefix_lan, "ifname", nvram_name)));
284
285	memset(current_lan_proto, 0, 16);
286	strcpy(current_lan_proto, nvram_safe_get(strcat_r(prefix_lan, "proto", nvram_name)));
287
288	memset(current_lan_ipaddr, 0, 16);
289	strcpy(current_lan_ipaddr, nvram_safe_get(strcat_r(prefix_lan, "ipaddr", nvram_name)));
290
291	memset(current_lan_netmask, 0, 16);
292	strcpy(current_lan_netmask, nvram_safe_get(strcat_r(prefix_lan, "netmask", nvram_name)));
293
294	memset(current_lan_gateway, 0, 16);
295	strcpy(current_lan_gateway, nvram_safe_get(strcat_r(prefix_lan, "gateway", nvram_name)));
296
297	memset(current_lan_dns, 0, 256);
298	strcpy(current_lan_dns, nvram_safe_get(strcat_r(prefix_lan, "dns", nvram_name)));
299
300	memset(current_lan_subnet, 0, 11);
301	strcpy(current_lan_subnet, nvram_safe_get(strcat_r(prefix_lan, "subnet", nvram_name)));
302
303#ifdef RTCONFIG_WIRELESSREPEATER
304	if(sw_mode == SW_MODE_REPEATER){
305		wlc_state = nvram_get_int("wlc_state");
306		got_notify = 1;
307	}
308#endif
309
310	csprintf("# wanduck: Got LAN(%d) information:\n", current_lan_unit);
311	if(nvram_match("wanduck_debug", "1")){
312#ifdef RTCONFIG_WIRELESSREPEATER
313		if(sw_mode == SW_MODE_REPEATER){
314			csprintf("# wanduck:   ipaddr=%s.\n", current_lan_ipaddr);
315			csprintf("# wanduck:wlc_state=%d.\n", wlc_state);
316		}
317		else
318#endif
319		{
320			csprintf("# wanduck:   ifname=%s.\n", current_lan_ifname);
321			csprintf("# wanduck:    proto=%s.\n", current_lan_proto);
322			csprintf("# wanduck:   ipaddr=%s.\n", current_lan_ipaddr);
323			csprintf("# wanduck:  netmask=%s.\n", current_lan_netmask);
324			csprintf("# wanduck:  gateway=%s.\n", current_lan_gateway);
325			csprintf("# wanduck:      dns=%s.\n", current_lan_dns);
326			csprintf("# wanduck:   subnet=%s.\n", current_lan_subnet);
327		}
328	}
329}
330
331static void get_network_nvram(int signo){
332	if(sw_mode == SW_MODE_AP)
333		get_lan_nvram();
334#ifdef RTCONFIG_WIRELESSREPEATER
335	if(sw_mode == SW_MODE_REPEATER)
336		get_lan_nvram();
337	else if(sw_mode == SW_MODE_HOTSPOT)
338		wlc_state = nvram_get_int("wlc_state");
339#endif
340}
341
342/* 67u,87u,3200: have each led on every port.
343 * 88u,3100,5300: have one led to hint wan port but this led is the union of all ports
344 * force led_on on usb modem case */
345
346void enable_wan_wled()
347{
348	int usb_wan = get_dualwan_by_unit(wan_primary_ifunit()) == WANS_DUALWAN_IF_USB ? 1:0;
349
350	if(usb_wan) {
351		switch (get_model()) {
352			case MODEL_RTAC68U:
353				if (strcmp(get_productid(), "RT-AC66U V2"))
354					break;
355			case MODEL_RTAC3200:
356			case MODEL_RTAC87U:
357				eval("et", "-i", "eth0", "robowr", "0", "0x18", "0x01ff");
358				eval("et", "-i", "eth0", "robowr", "0", "0x1a", "0x01fe");
359				return;
360
361			case MODEL_RTAC5300:
362			case MODEL_RTAC5300R:
363			case MODEL_RTAC88U:
364			case MODEL_RTAC3100:
365				eval("et", "-i", "eth0", "robowr", "0", "0x18", "0x01ff");
366				eval("et", "-i", "eth0", "robowr", "0", "0x1a", "0");
367				return;
368		}
369	}
370
371	eval("et", "-i", "eth0", "robowr", "0", "0x18", "0x01ff");
372	eval("et", "-i", "eth0", "robowr", "0", "0x1a", "0x01ff");
373}
374
375void disable_wan_wled()
376{
377	eval("et", "-i", "eth0", "robowr", "0", "0x18", "0x01fe");
378	eval("et", "-i", "eth0", "robowr", "0", "0x1a", "0x01fe");
379}
380
381static void wan_led_control(int sig) {
382#if 0
383#if defined(RTAC68U) || defined(RTAC87U) || defined(RTAC3200) || defined(RTAC88U) || defined(RTAC3100) || defined(RTAC5300) || defined(RTAC5300R)
384#ifdef RTAC68U
385	if (strcmp(get_productid(), "RT-AC66U V2"))
386		return;
387#endif
388	char buf[16];
389	snprintf(buf, 16, "%s", nvram_safe_get("wans_dualwan"));
390	if (strcmp(buf, "wan none") != 0){
391		logmessage("DualWAN", "skip single wan wan_led_control()");
392		return;
393	}
394#endif
395#endif
396#if defined(RTAC68U) ||  defined(RTAC87U) || defined(RTAC3200) || defined(RTAC88U) || defined(RTAC3100) || defined(RTAC5300) || defined(RTAC5300R) || defined(DSL_AC68U)
397	if(nvram_match("AllLED", "1")
398#ifdef RTAC68U
399		&& !strcmp(get_productid(), "RT-AC66U V2")
400#endif
401	) {
402#if defined(RTAC68U) ||  defined(RTAC87U) || defined(RTAC3200) || defined(RTAC88U) || defined(RTAC3100) || defined(RTAC5300) || defined(RTAC5300R)
403		if (rule_setup) {
404			led_control(LED_WAN, LED_ON);
405			disable_wan_wled();
406		} else {
407			led_control(LED_WAN, LED_OFF);
408			enable_wan_wled();
409		}
410#elif defined(DSL_AC68U)
411		if (rule_setup) {
412			led_control(LED_WAN, LED_OFF);
413		} else {
414			led_control(LED_WAN, LED_ON);
415		}
416#endif
417	}
418#endif
419}
420
421int do_ping_detect(int wan_unit)
422{
423#if 0
424	char buf[16], *next;
425	char prefix_wan[8], nvram_name[16], wan_dns[256];
426	char cmd[256];
427
428	memset(prefix_wan, 0, 8);
429	sprintf(prefix_wan, "wan%d_", wan_unit);
430
431	memset(wan_dns, 0, 256);
432	strcpy(wan_dns, nvram_safe_get(strcat_r(prefix_wan, "dns", nvram_name)));
433
434	foreach(buf, wan_dns, next){
435		sprintf(cmd, "ping -c 1 -W %d %s && touch %s", TCPCHECK_TIMEOUT, buf, PING_RESULT_FILE);
436		system(cmd);
437
438		if(check_if_file_exist(PING_RESULT_FILE)){
439			unlink(PING_RESULT_FILE);
440			return 1;
441		}
442	}
443//elif defined(RTCONFIG_DUALWAN)
444#endif
445#if defined(RTCONFIG_DUALWAN)
446	char cmd[256];
447#if 0
448
449	csprintf("wanduck: ping %s to %s...", wandog_target, PING_RESULT_FILE);
450	sprintf(cmd, "ping -c 1 -w 2 %s >/dev/null && touch %s", wandog_target, PING_RESULT_FILE);
451	system(cmd);
452
453	if(check_if_file_exist(PING_RESULT_FILE)){
454		csprintf("ok.\n");
455		unlink(PING_RESULT_FILE);
456		return 1;
457	}
458#else
459	FILE *fp;
460
461	printf("wanduck: ping %s...", wandog_target);
462	snprintf(cmd, 256, "ping -c1 -w2 -s32 -t128 -Mdont %s", wandog_target);
463	if((fp = popen(cmd, "r")) != NULL){
464		char var[256];
465
466		var[0] = '\0';
467		while(fgets(var, sizeof(var), fp)){
468			if(!strstr(var, "1 packets received"))
469				continue;
470
471			printf("ok.\n");
472			fclose(fp);
473			return 1;
474		}
475		fclose(fp);
476	}
477#endif
478#else // RTCONFIG_DUALWAN
479	return 1;
480#endif // RTCONFIG_DUALWAN
481	printf("\n ping failed.\n");
482	return 0;
483}
484
485#ifndef NO_DETECT_INTERNET
486int get_packets_of_net_dev(const char *net_dev, unsigned long *rx_packets, unsigned long *tx_packets){
487	FILE *fp;
488	char buf[256];
489	char *ifname;
490	char *ptr;
491	int i, got_packets = 0;
492
493	if((fp = fopen(PROC_NET_DEV, "r")) == NULL){
494		_dprintf("%s: Can't open the file: %s.\n", __FUNCTION__, PROC_NET_DEV);
495		return got_packets;
496	}
497
498	fcntl(fileno(fp), F_SETFL, fcntl(fileno(fp), F_GETFL) | O_NONBLOCK);
499
500	// headers.
501	for(i = 0; i < 2; ++i){
502		if(fgets(buf, sizeof(buf), fp) == NULL){
503			fclose(fp);
504			logmessage("wanduck", "%s: Can't read out the headers of %s.\n", __FUNCTION__, PROC_NET_DEV);
505			if(errno == EAGAIN || errno == EWOULDBLOCK)
506				got_packets = 1;
507
508			return got_packets;
509		}
510	}
511
512	while(fgets(buf, sizeof(buf), fp) != NULL){
513		if((ptr = strchr(buf, ':')) == NULL)
514			continue;
515
516		*ptr = 0;
517		if((ifname = strrchr(buf, ' ')) == NULL)
518			ifname = buf;
519		else
520			++ifname;
521
522		if(strcmp(ifname, net_dev))
523			continue;
524
525		// <rx bytes, packets, errors, dropped, fifo errors, frame errors, compressed, multicast><tx ...>
526		if(sscanf(ptr+1, "%*u%lu%*u%*u%*u%*u%*u%*u%*u%lu", rx_packets, tx_packets) != 2){
527			fclose(fp);
528			logmessage("wanduck", "%s: Can't read the packet's number in %s.\n", __FUNCTION__, PROC_NET_DEV);
529			if(errno == EAGAIN || errno == EWOULDBLOCK)
530				got_packets = 1;
531
532			return got_packets;
533		}
534
535		got_packets = 1;
536		break;
537	}
538	fclose(fp);
539
540	return got_packets;
541}
542
543char *organize_tcpcheck_cmd(char *dns_list, char *cmd, int size){
544	char buf[256], *next;
545
546	if(cmd == NULL || size <= 0)
547		return NULL;
548
549	memset(cmd, 0, size);
550
551	sprintf(cmd, "/sbin/tcpcheck %d", TCPCHECK_TIMEOUT);
552
553	foreach(buf, dns_list, next){
554		sprintf(cmd, "%s %s:53", cmd, buf);
555	}
556
557	sprintf(cmd, "%s >>%s", cmd, DETECT_FILE);
558
559	return cmd;
560}
561
562int do_tcp_dns_detect(int wan_unit){
563	FILE *fp = NULL;
564	char line[80], cmd[PATH_MAX];
565	char prefix_wan[8], nvram_name[16], wan_dns[256];
566
567	if(remove(DETECT_FILE) < 0)
568	{
569		logmessage("%s: cannot remove DETECT_FILE.\n", __FUNCTION__);
570		return 0;
571	}
572
573	memset(prefix_wan, 0, 8);
574	sprintf(prefix_wan, "wan%d_", wan_unit);
575
576	memset(wan_dns, 0, 256);
577	strcpy(wan_dns, nvram_safe_get(strcat_r(prefix_wan, "dns", nvram_name)));
578
579	if(organize_tcpcheck_cmd(wan_dns, cmd, PATH_MAX) == NULL){
580		csprintf("wanduck: No tcpcheck cmd.\n");
581		return 0;
582	}
583	system(cmd);
584
585	if((fp = fopen(DETECT_FILE, "r")) == NULL){
586		_dprintf("wanduck: No file: %s.\n", DETECT_FILE);
587		return 0;
588	}
589
590	fcntl(fileno(fp), F_SETFL, fcntl(fileno(fp), F_GETFL) | O_NONBLOCK);
591
592	while(fgets(line, sizeof(line), fp) != NULL){
593		if(strstr(line, "alive")){
594			fclose(fp);
595			return 1;
596		}
597	}
598	fclose(fp);
599
600	return 0;
601}
602#endif
603
604int detect_internet(int wan_unit){
605	int link_internet;
606#ifndef NO_DETECT_INTERNET
607	unsigned long rx_packets, tx_packets;
608#endif
609	char prefix_wan[8], wan_ifname[16];
610
611	memset(prefix_wan, 0, 8);
612	sprintf(prefix_wan, "wan%d_", wan_unit);
613
614	memset(wan_ifname, 0, 16);
615	strcpy(wan_ifname, get_wan_ifname(wan_unit));
616
617	if(
618#ifdef RTCONFIG_DUALWAN
619			strcmp(dualwan_mode, "lb") &&
620#endif
621			!found_default_route(wan_unit)
622			)
623		link_internet = DISCONN;
624#ifndef NO_DETECT_INTERNET
625	else if(!get_packets_of_net_dev(wan_ifname, &rx_packets, &tx_packets) || rx_packets <= RX_THRESHOLD)
626		link_internet = DISCONN;
627	else if(!isFirstUse && (!do_dns_detect() && !do_tcp_dns_detect(wan_unit) && !do_ping_detect(wan_unit)))
628		link_internet = DISCONN;
629#endif
630#ifdef RTCONFIG_DUALWAN
631	else if((!strcmp(dualwan_mode, "fo") || !strcmp(dualwan_mode, "fb"))
632			&& wandog_enable == 1 && !isFirstUse && !do_ping_detect(wan_unit))
633		link_internet = DISCONN;
634#endif
635	else
636		link_internet = CONNED;
637
638	if(link_internet == DISCONN){
639#ifndef NO_DETECT_INTERNET
640		nvram_set_int("link_internet", 1);
641#endif
642		record_wan_state_nvram(wan_unit, -1, -1, WAN_AUXSTATE_NO_INTERNET_ACTIVITY);
643
644		if(!(nvram_get_int("web_redirect")&WEBREDIRECT_FLAG_NOINTERNET)) {
645#ifndef NO_DETECT_INTERNET
646			nvram_set_int("link_internet", 2);
647#endif
648			link_internet = CONNED;
649		}
650	}
651	else{
652#ifndef NO_DETECT_INTERNET
653		nvram_set_int("link_internet", 2);
654#endif
655		record_wan_state_nvram(wan_unit, -1, -1, WAN_AUXSTATE_NONE);
656	}
657
658	return link_internet;
659}
660
661int passivesock(char *service, int protocol_num, int qlen){
662	//struct servent *pse;
663	struct sockaddr_in sin;
664	int s, type, on;
665
666	memset(&sin, 0, sizeof(sin));
667	sin.sin_family = AF_INET;
668	sin.sin_addr.s_addr = INADDR_ANY;
669
670	// map service name to port number
671	if((sin.sin_port = htons((u_short)atoi(service))) == 0){
672		perror("cannot get service entry");
673
674		return -1;
675	}
676
677	if(protocol_num == IPPROTO_UDP)
678		type = SOCK_DGRAM;
679	else
680		type = SOCK_STREAM;
681
682	s = socket(PF_INET, type, protocol_num);
683	if(s < 0){
684		perror("cannot create socket");
685
686		return -1;
687	}
688
689	on = 1;
690	if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on)) < 0){
691		perror("cannot set socket's option: SO_REUSEADDR");
692		close(s);
693
694		return -1;
695	}
696
697	if(bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0){
698		perror("cannot bind port");
699		close(s);
700
701		return -1;
702	}
703
704	if(type == SOCK_STREAM && listen(s, qlen) < 0){
705		perror("cannot listen to port");
706		close(s);
707
708		return -1;
709	}
710
711	return s;
712}
713
714#if 0
715int check_ppp_exist(){
716	DIR *dir;
717	struct dirent *dent;
718	char task_file[64], cmdline[64];
719	int pid, fd;
720
721	if((dir = opendir("/proc")) == NULL){
722		perror("open proc");
723		return 0;
724	}
725
726	while((dent = readdir(dir)) != NULL){
727		if((pid = atoi(dent->d_name)) > 1){
728			memset(task_file, 0, 64);
729			sprintf(task_file, "/proc/%d/cmdline", pid);
730			if((fd = open(task_file, O_RDONLY | O_NONBLOCK)) > 0){
731				memset(cmdline, 0, 64);
732				read(fd, cmdline, 64);
733				close(fd);
734
735				if(strstr(cmdline, "pppd")
736						|| strstr(cmdline, "l2tpd")
737						|| (errno==EAGAIN || errno==EWOULDBLOCK)
738						){
739					closedir(dir);
740					return 1;
741				}
742			}
743			else
744				printf("cannot open %s\n", task_file);
745		}
746	}
747	closedir(dir);
748
749	return 0;
750}
751#endif
752
753unsigned long long get_wan_flow(int wan_unit){
754	unsigned long long rx, tx, total;
755
756	if(dualwan_unit__usbif(wan_unit)){
757		rx = strtoull(nvram_safe_get("modem_bytes_rx"), NULL, 10);
758		tx = strtoull(nvram_safe_get("modem_bytes_tx"), NULL, 10);
759
760		total = rx+tx;
761	}
762	else{
763		// TODO: Data limit for the ethernet connection.
764#ifdef RTCONFIG_TRAFFIC_LIMITER
765		total = (unsigned long long)traffic_limiter_get_realtime(wan_unit) * 1024 * 1024 * 1024;
766		if(test_log) _dprintf("[TRAFFIC LIMITER] /tmp/tl%d_realtime = %lld\n", wan_unit, total);
767#else
768		total = 0;
769#endif
770	}
771
772	return total;
773}
774
775int chk_proto(int wan_unit){
776	int wan_sbstate = nvram_get_int(nvram_sbstate[wan_unit]);
777	char prefix_wan[8], nvram_name[16], wan_proto[16];
778#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
779	char buff[128];
780	unsigned long long total = get_wan_flow(wan_unit);
781#endif
782
783	memset(prefix_wan, 0, 8);
784	sprintf(prefix_wan, "wan%d_", wan_unit);
785
786	memset(wan_proto, 0, 16);
787	strcpy(wan_proto, nvram_safe_get(strcat_r(prefix_wan, "proto", nvram_name)));
788
789#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
790	// had detected the DATA limit before.
791	if(wan_sbstate == WAN_STOPPED_REASON_DATALIMIT){
792		if(nvram_get_int("modem_sms_limit") == 1 && nvram_get_int("modem_sms_limit_send") == 0){
793			snprintf(buff, 128, "start_sendSMS limit");
794			nvram_set("freeze_duck", "5");
795			notify_rc(buff);
796			nvram_set("modem_sms_limit_send", "1");
797			// if send the limit SMS, the alert SMS is not needed.
798			nvram_set("modem_sms_alert_send", "1");
799		}
800
801		disconn_case[wan_unit] = CASE_DATALIMIT;
802		return DISCONN;
803	}
804	else
805#endif
806#ifdef RTCONFIG_WIRELESSREPEATER
807	if(sw_mode == SW_MODE_HOTSPOT){
808		if(current_state[wan_unit] == WAN_STATE_STOPPED) {
809			if(wan_sbstate == WAN_STOPPED_REASON_INVALID_IPADDR)
810				disconn_case[wan_unit] = CASE_THESAMESUBNET;
811			else disconn_case[wan_unit] = CASE_DHCPFAIL;
812			return DISCONN;
813		}
814		else if(current_state[wan_unit] == WAN_STATE_INITIALIZING){
815			disconn_case[wan_unit] = CASE_DHCPFAIL;
816			return DISCONN;
817		}
818		else if(current_state[wan_unit] == WAN_STATE_CONNECTING){
819			disconn_case[wan_unit] = CASE_DHCPFAIL;
820			return DISCONN;
821		}
822		else if(current_state[wan_unit] == WAN_STATE_DISCONNECTED){
823			disconn_case[wan_unit] = CASE_DHCPFAIL;
824			return DISCONN;
825		}
826	}
827	else
828#endif
829	// Start chk_proto() in SW_MODE_ROUTER.
830#ifdef RTCONFIG_USB_MODEM
831	if (dualwan_unit__usbif(wan_unit)) {
832#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
833		unsigned long long alert, limit;
834
835		eval("modem_status.sh", "bytes");
836
837		alert = strtoull(nvram_safe_get("modem_bytes_data_warning"), NULL, 10);
838		limit = strtoull(nvram_safe_get("modem_bytes_data_limit"), NULL, 10);
839
840		if(limit > 0 && total >= limit){
841			if(current_state[wan_unit] != WAN_STATE_STOPPED || wan_sbstate != WAN_STOPPED_REASON_DATALIMIT){
842				csprintf("wanduck(%d): chk_proto() detect the data limit.\n", wan_unit);
843				record_wan_state_nvram(wan_unit, WAN_STATE_STOPPED, WAN_STOPPED_REASON_DATALIMIT, -1);
844				current_state[wan_unit] = WAN_STATE_STOPPED;
845				wan_sbstate = WAN_STOPPED_REASON_DATALIMIT;
846			}
847
848			if(nvram_get_int("modem_sms_limit") == 1 && nvram_get_int("modem_sms_limit_send") == 0){
849				snprintf(buff, 128, "start_sendSMS limit");
850				nvram_set("freeze_duck", "5");
851				notify_rc(buff);
852				nvram_set("modem_sms_limit_send", "1");
853				// if send the limit SMS, the alert SMS is not needed.
854				nvram_set("modem_sms_alert_send", "1");
855			}
856		}
857
858		if(alert > 0 && total >= alert){
859			if(nvram_get_int("modem_sms_limit") == 1 && nvram_get_int("modem_sms_alert_send") == 0){
860				snprintf(buff, 128, "start_sendSMS alert");
861				nvram_set("freeze_duck", "5");
862				notify_rc(buff);
863				nvram_set("modem_sms_alert_send", "1");
864			}
865		}
866#endif
867
868		if(current_state[wan_unit] == WAN_STATE_INITIALIZING){
869			disconn_case[wan_unit] = CASE_PPPFAIL;
870			return DISCONN;
871		}
872		else if(current_state[wan_unit] == WAN_STATE_CONNECTING){
873			ppp_fail_state = pppstatus();
874
875			if(ppp_fail_state == WAN_STOPPED_REASON_PPP_AUTH_FAIL)
876				record_wan_state_nvram(wan_unit, -1, WAN_STOPPED_REASON_PPP_AUTH_FAIL, -1);
877			else if(ppp_fail_state == WAN_STOPPED_REASON_PPP_LACK_ACTIVITY)
878				record_wan_state_nvram(wan_unit, -1, WAN_STOPPED_REASON_PPP_LACK_ACTIVITY, -1);
879			else if(ppp_fail_state == WAN_STOPPED_REASON_PPP_NO_ACTIVITY)
880				record_wan_state_nvram(wan_unit, -1, WAN_STOPPED_REASON_PPP_NO_ACTIVITY, -1);
881
882			disconn_case[wan_unit] = CASE_PPPFAIL;
883			return DISCONN;
884		}
885		else if(current_state[wan_unit] == WAN_STATE_DISCONNECTED){
886			disconn_case[wan_unit] = CASE_PPPFAIL;
887			return DISCONN;
888		}
889		else if(current_state[wan_unit] == WAN_STATE_STOPPED){
890#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
891			if(wan_sbstate == WAN_STOPPED_REASON_DATALIMIT)
892				disconn_case[wan_unit] = CASE_DATALIMIT;
893			else
894#endif
895			if(wan_sbstate == WAN_STOPPED_REASON_INVALID_IPADDR)
896				disconn_case[wan_unit] = CASE_THESAMESUBNET;
897			else if(!strcmp(wan_proto, "dhcp"))
898				disconn_case[wan_unit] = CASE_DHCPFAIL;
899			else
900				disconn_case[wan_unit] = CASE_PPPFAIL;
901
902			return DISCONN;
903		}
904	}
905	else
906#endif // RTCONFIG_USB_MODEM
907	if(!strcmp(wan_proto, "dhcp")
908			|| !strcmp(wan_proto, "static")){
909#ifdef RTCONFIG_TRAFFIC_LIMITER
910		traffic_limiter_limitdata_check();
911
912		// TODO: Data limit for the ethernet connection.
913		if(traffic_limiter_wanduck_check(wan_unit)){
914			if(current_state[wan_unit] != WAN_STATE_STOPPED || wan_sbstate != WAN_STOPPED_REASON_DATALIMIT){
915				csprintf("wanduck(%d): chk_proto() detect the data limit - dhcp / static.\n", wan_unit);
916				record_wan_state_nvram(wan_unit, WAN_STATE_STOPPED, WAN_STOPPED_REASON_DATALIMIT, -1);
917				current_state[wan_unit] = WAN_STATE_STOPPED;
918				wan_sbstate = WAN_STOPPED_REASON_DATALIMIT;
919			}
920		}
921#endif
922
923		if(current_state[wan_unit] == WAN_STATE_INITIALIZING){
924			disconn_case[wan_unit] = CASE_DHCPFAIL;
925			return DISCONN;
926		}
927		else if(current_state[wan_unit] == WAN_STATE_CONNECTING){
928#if defined(RTCONFIG_WANRED_LED)
929			int r = CASE_DHCPFAIL, v = DISCONN;
930
931			if (!strcmp(wan_proto, "static") && link_wan[wan_unit]) {
932				r = CASE_NONE;
933				v = CONNED;
934			}
935
936			disconn_case[wan_unit] = r;
937			return v;
938#else
939			disconn_case[wan_unit] = CASE_DHCPFAIL;
940			return DISCONN;
941#endif
942		}
943		else if(current_state[wan_unit] == WAN_STATE_DISCONNECTED){
944			disconn_case[wan_unit] = CASE_DHCPFAIL;
945			return DISCONN;
946		}
947		else if(current_state[wan_unit] == WAN_STATE_STOPPED) {
948#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
949			if(wan_sbstate == WAN_STOPPED_REASON_DATALIMIT)
950				disconn_case[wan_unit] = CASE_DATALIMIT;
951			else
952#endif
953			if(wan_sbstate == WAN_STOPPED_REASON_INVALID_IPADDR)
954				disconn_case[wan_unit] = CASE_THESAMESUBNET;
955			else
956				disconn_case[wan_unit] = CASE_DHCPFAIL;
957
958			return DISCONN;
959		}
960	}
961	else if(!strcmp(wan_proto, "pppoe")
962			|| !strcmp(wan_proto, "pptp")
963			|| !strcmp(wan_proto, "l2tp")
964			){
965		ppp_fail_state = pppstatus();
966#ifdef RTCONFIG_TRAFFIC_LIMITER
967		traffic_limiter_limitdata_check();
968
969		// TODO: Data limit for the ethernet connection.
970		if(traffic_limiter_wanduck_check(wan_unit)){
971			if(current_state[wan_unit] != WAN_STATE_STOPPED || wan_sbstate != WAN_STOPPED_REASON_DATALIMIT){
972				csprintf("wanduck(%d): chk_proto() detect the data limit - pppoe / pptp / l2tp.\n", wan_unit);
973				record_wan_state_nvram(wan_unit, WAN_STATE_STOPPED, WAN_STOPPED_REASON_DATALIMIT, -1);
974				current_state[wan_unit] = WAN_STATE_STOPPED;
975				wan_sbstate = WAN_STOPPED_REASON_DATALIMIT;
976			}
977		}
978#endif
979
980		if(current_state[wan_unit] != WAN_STATE_CONNECTED
981				&& ppp_fail_state == WAN_STOPPED_REASON_PPP_LACK_ACTIVITY){
982			// PPP is into the idle mode.
983			if(current_state[wan_unit] == WAN_STATE_STOPPED) // Sometimes ip_down() didn't set it.
984				record_wan_state_nvram(wan_unit, -1, WAN_STOPPED_REASON_PPP_LACK_ACTIVITY, -1);
985		}
986		else if(current_state[wan_unit] == WAN_STATE_INITIALIZING){
987			disconn_case[wan_unit] = CASE_PPPFAIL;
988			return DISCONN;
989		}
990		else if(current_state[wan_unit] == WAN_STATE_CONNECTING){
991			if(ppp_fail_state == WAN_STOPPED_REASON_PPP_AUTH_FAIL)
992				record_wan_state_nvram(wan_unit, -1, WAN_STOPPED_REASON_PPP_AUTH_FAIL, -1);
993			else if(ppp_fail_state == WAN_STOPPED_REASON_PPP_LACK_ACTIVITY)
994				record_wan_state_nvram(wan_unit, -1, WAN_STOPPED_REASON_PPP_LACK_ACTIVITY, -1);
995			else if(ppp_fail_state == WAN_STOPPED_REASON_PPP_NO_ACTIVITY)
996				record_wan_state_nvram(wan_unit, -1, WAN_STOPPED_REASON_PPP_NO_ACTIVITY, -1);
997
998			disconn_case[wan_unit] = CASE_PPPFAIL;
999			return DISCONN;
1000		}
1001		else if(current_state[wan_unit] == WAN_STATE_DISCONNECTED){
1002			disconn_case[wan_unit] = CASE_PPPFAIL;
1003			return DISCONN;
1004		}
1005		else if(current_state[wan_unit] == WAN_STATE_STOPPED){
1006#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
1007			if(wan_sbstate == WAN_STOPPED_REASON_DATALIMIT)
1008				disconn_case[wan_unit] = CASE_DATALIMIT;
1009			else
1010#endif
1011				disconn_case[wan_unit] = CASE_PPPFAIL;
1012			return DISCONN;
1013		}
1014	}
1015
1016	return CONNED;
1017}
1018
1019int if_wan_phyconnected(int wan_unit){
1020	char wired_link_nvram[16];
1021#ifdef RTCONFIG_WIRELESSREPEATER
1022	int link_ap = 0;
1023#endif
1024	int link_changed = 0;
1025	char prefix[] = "wanXXXXXX_", tmp[100] = "";
1026	char wan_proto[16];
1027#ifdef RTCONFIG_USB_MODEM
1028	int find_modem_node = 0;
1029	int wan_state = 0;
1030	int sim_state = 0;
1031#endif
1032
1033#ifdef RTCONFIG_USB_MODEM
1034#ifdef RTCONFIG_DYN_MODEM
1035#ifdef RTCONFIG_DUALWAN
1036	if(wan_unit == WAN_UNIT_FIRST && dualwan_unit__nonusbif(wan_unit) && get_dualwan_by_unit(other_wan_unit) == WANS_DUALWAN_IF_NONE){
1037		snprintf(prefix, sizeof(prefix), "wan%d_", other_wan_unit);
1038
1039		find_modem_node = 0;
1040		wan_state = nvram_get_int(nvram_state[other_wan_unit]);
1041
1042#ifdef RTCONFIG_INTERNAL_GOBI
1043		if(strlen(usb_if) <= 0 && nvram_get_int("usb_gobi") == 1){
1044			snprintf(usb_if, 16, "%s", nvram_safe_get(strcat_r(prefix, "ifname", tmp)));
1045csprintf("wanduck: try to get usb_if=%s.\n", usb_if);
1046		}
1047
1048		if(strlen(usb_if) > 0){
1049			if(strlen(nvram_safe_get("usb_modem_act_imei")) <= 0)
1050				eval("modem_status.sh", "imei");
1051			if(strlen(nvram_safe_get("usb_modem_act_hwver")) <= 0)
1052				eval("modem_status.sh", "hwver");
1053			if(strlen(nvram_safe_get("usb_modem_act_swver")) <= 0)
1054				eval("modem_status.sh", "swver");
1055		}
1056#endif
1057
1058		link_wan[other_wan_unit] = is_usb_modem_ready(); // include find_modem_type.sh
1059		if(link_wan[other_wan_unit] && strlen(modem_type) <= 0)
1060			snprintf(modem_type, 32, "%s", nvram_safe_get("usb_modem_act_type"));
1061		sim_state = nvram_get_int("usb_modem_act_sim");
1062
1063		if(!strcmp(modem_type, "qmi") || !strcmp(modem_type, "gobi")){
1064			if(link_wan[other_wan_unit] == 1){
1065				if(!strcmp(nvram_safe_get("usb_modem_act_int"), "")){
1066					if(!strcmp(modem_type, "qmi")){	// e.q. Huawei E398.
1067						csprintf("wanduck(%d): Sleep 3 seconds to wait modem nodes.\n", other_wan_unit);
1068						sleep(3);
1069					}
1070					else{
1071						csprintf("wanduck(%d): Sleep 2 seconds to wait modem nodes.\n", other_wan_unit);
1072						sleep(2);
1073					}
1074
1075					wan_state = nvram_get_int(nvram_state[other_wan_unit]); // after sleep(), wan_state is changed.
1076
1077					if(!strcmp(nvram_safe_get("usb_modem_act_int"), ""))
1078						find_modem_node = 1;
1079				}
1080
1081				if((!strcmp(modem_type, "tty") || !strcmp(modem_type, "mbim"))
1082						&& !strcmp(nvram_safe_get("usb_modem_act_bulk"), "")
1083						&& strcmp(nvram_safe_get("usb_modem_act_vid"), "6610") // e.q. ZTE MF637U
1084						){
1085					csprintf("wanduck(%d): finding the second tty node...\n", other_wan_unit);
1086					find_modem_node = 1;
1087				}
1088
1089				if(find_modem_node)
1090					eval("find_modem_node.sh");
1091
1092				if(!strcmp(modem_type, "tty") && !strcmp(nvram_safe_get("usb_modem_act_vid"), "6610")){ // e.q. ZTE MF637U
1093					if(wan_state == WAN_STATE_INITIALIZING)
1094						eval("modem_status.sh", "sim");
1095				}
1096				else if(wan_state != WAN_STATE_CONNECTING)
1097					eval("modem_status.sh", "sim");
1098
1099				sim_state = nvram_get_int("usb_modem_act_sim");
1100				if(sim_state == 2 || sim_state == 3){
1101					sim_lock = 1;
1102
1103					if(sim_state == 3 || !strcmp(nvram_safe_get("modem_pincode"), "") || nvram_get_int(nvram_auxstate[other_wan_unit]) == WAN_STOPPED_REASON_PINCODE_ERR)
1104						link_wan[other_wan_unit] = 3;
1105				}
1106				else if(sim_state != 1)
1107					link_wan[other_wan_unit] = 0;
1108
1109#ifdef RTCONFIG_INTERNAL_GOBI
1110				if(sim_state > 1 && sim_state <= 6 && !strcmp(nvram_safe_get("usb_modem_act_auth"), ""))
1111					eval("modem_status.sh", "simauth");
1112#endif
1113			}
1114		}
1115
1116		nvram_set_int(strcat_r(prefix, "is_usb_modem_ready", tmp), link_wan[other_wan_unit]);
1117if(test_log)
1118_dprintf("# wanduck: if_wan_phyconnected: x_Setting=%d, link_modem=%d, sim_state=%d.\n", !isFirstUse, link_wan[other_wan_unit], sim_state);
1119
1120		snprintf(wired_link_nvram, 16, "link_wan%d", other_wan_unit);
1121		if(link_wan[other_wan_unit] != nvram_get_int(wired_link_nvram)){
1122			nvram_set_int(wired_link_nvram, link_wan[other_wan_unit]);
1123			if(link_wan[other_wan_unit] != 0)
1124				record_wan_state_nvram(other_wan_unit, -1, -1, WAN_AUXSTATE_NONE);
1125		}
1126
1127		disconn_case[other_wan_unit] = CASE_DYN_MODEM;
1128	}
1129#endif
1130#endif // RTCONFIG_DYN_MODEM
1131
1132	if(dualwan_unit__usbif(wan_unit)){
1133		snprintf(prefix, sizeof(prefix), "wan%d_", wan_unit);
1134
1135		find_modem_node = 0;
1136		wan_state = nvram_get_int(nvram_state[wan_unit]);
1137
1138#ifdef RTCONFIG_INTERNAL_GOBI
1139		if(strlen(usb_if) <= 0 && nvram_get_int("usb_gobi") == 1){
1140			snprintf(usb_if, 16, "%s", nvram_safe_get(strcat_r(prefix, "ifname", tmp)));
1141csprintf("wanduck: try to get usb_if=%s.\n", usb_if);
1142		}
1143
1144		if(strlen(usb_if) > 0){
1145			if(strlen(nvram_safe_get("usb_modem_act_imei")) <= 0)
1146				eval("modem_status.sh", "imei");
1147			if(
1148#ifdef CONFIG_BCMWL5
1149				!factory_debug()
1150#else
1151				!IS_ATE_FACTORY_MODE()
1152#endif
1153					&& strlen(nvram_safe_get("usb_modem_act_hwver")) <= 0)
1154				eval("modem_status.sh", "hwver");
1155			if(strlen(nvram_safe_get("usb_modem_act_swver")) <= 0)
1156				eval("modem_status.sh", "swver");
1157#ifdef RTCONFIG_USB_SMS_MODEM
1158			if(strlen(nvram_safe_get("usb_modem_act_smsc")) <= 0)
1159				eval("modem_status.sh", "smsc");
1160#endif
1161		}
1162#endif
1163
1164		// need to check before detecting SIM. If not, the detect of wanduck will be blocked.
1165		if(nvram_get_int("usb_modem_act_scanning") != 0){
1166			csprintf("wanduck(%d): detect the USB scan.\n", wan_unit);
1167			link_wan[wan_unit] = 4;
1168			sim_lock = 1;
1169		}
1170		else{
1171			modem_act_reset = nvram_get_int("usb_modem_act_reset");
1172			if(modem_act_reset == 1 || modem_act_reset == 2)
1173				return CONNED;
1174
1175			if(wan_state == WAN_STATE_CONNECTING)
1176				return CONNED;
1177
1178			link_wan[wan_unit] = is_usb_modem_ready(); // include find_modem_type.sh
1179			if(link_wan[wan_unit] && strlen(modem_type) <= 0)
1180				snprintf(modem_type, 32, "%s", nvram_safe_get("usb_modem_act_type"));
1181			sim_state = nvram_get_int("usb_modem_act_sim");
1182		}
1183
1184		if(!strcmp(modem_type, "qmi") || !strcmp(modem_type, "gobi")){
1185			if(link_wan[wan_unit] == 1){
1186				if(!strcmp(nvram_safe_get("usb_modem_act_int"), "")){
1187					if(!strcmp(modem_type, "qmi")){	// e.q. Huawei E398.
1188						csprintf("wanduck(%d): Sleep 3 seconds to wait modem nodes.\n", wan_unit);
1189						sleep(3);
1190					}
1191					else{
1192						csprintf("wanduck(%d): Sleep 2 seconds to wait modem nodes.\n", wan_unit);
1193						sleep(2);
1194					}
1195
1196					wan_state = nvram_get_int(nvram_state[wan_unit]); // after sleep(), wan_state is changed.
1197
1198					if(!strcmp(nvram_safe_get("usb_modem_act_int"), ""))
1199						find_modem_node = 1;
1200				}
1201
1202				if((!strcmp(modem_type, "tty") || !strcmp(modem_type, "mbim"))
1203						&& !strcmp(nvram_safe_get("usb_modem_act_bulk"), "")
1204						&& strcmp(nvram_safe_get("usb_modem_act_vid"), "6610") // e.q. ZTE MF637U
1205						){
1206					csprintf("wanduck(%d): finding the second tty node...\n", wan_unit);
1207					find_modem_node = 1;
1208				}
1209
1210				if(find_modem_node)
1211					eval("find_modem_node.sh");
1212
1213				if(!strcmp(modem_type, "tty") && !strcmp(nvram_safe_get("usb_modem_act_vid"), "6610")){ // e.q. ZTE MF637U
1214					if(wan_state == WAN_STATE_INITIALIZING)
1215						eval("modem_status.sh", "sim");
1216				}
1217				else if(wan_state != WAN_STATE_CONNECTING)
1218					eval("modem_status.sh", "sim");
1219
1220				sim_state = nvram_get_int("usb_modem_act_sim");
1221				if(sim_state == 2 || sim_state == 3){
1222					sim_lock = 1;
1223
1224					if(sim_state == 3 || !strcmp(nvram_safe_get("modem_pincode"), "") || nvram_get_int(nvram_auxstate[wan_unit]) == WAN_STOPPED_REASON_PINCODE_ERR)
1225						link_wan[wan_unit] = 3;
1226				}
1227				else if(sim_state != 1)
1228					link_wan[wan_unit] = 0;
1229
1230#ifdef RTCONFIG_INTERNAL_GOBI
1231				if(sim_state > 1 && sim_state <= 6 && !strcmp(nvram_safe_get("usb_modem_act_auth"), ""))
1232					eval("modem_status.sh", "simauth");
1233
1234				if(sim_state == 1 && is_wan_connect(wan_unit)){
1235#ifdef TMAC1900V2
1236					if(!nvram_get_int("lteled_down")){
1237						eval("modem_status.sh", "operation");
1238						eval("modem_status.sh", "signal");
1239					}
1240#else	// 4G-AC55U
1241					eval("modem_status.sh", "fullsignal");
1242#endif
1243				}
1244#endif
1245			}
1246		}
1247
1248		nvram_set_int(strcat_r(prefix, "is_usb_modem_ready", tmp), link_wan[wan_unit]);
1249if(test_log)
1250_dprintf("# wanduck: if_wan_phyconnected: x_Setting=%d, link_modem=%d, sim_state=%d.\n", !isFirstUse, link_wan[wan_unit], sim_state);
1251
1252#if defined(RTCONFIG_WANRED_LED)
1253		update_wan_leds(wan_unit);
1254#endif
1255
1256		if(wan_unit == WAN_UNIT_FIRST)
1257			snprintf(wired_link_nvram, 16, "link_wan");
1258		else
1259			snprintf(wired_link_nvram, 16, "link_wan%d", wan_unit);
1260
1261		if(link_wan[wan_unit] != nvram_get_int(wired_link_nvram)){
1262			nvram_set_int(wired_link_nvram, link_wan[wan_unit]);
1263			if(link_wan[wan_unit] != 0)
1264				record_wan_state_nvram(wan_unit, -1, -1, WAN_AUXSTATE_NONE);
1265
1266			if(link_wan[wan_unit] == 3){
1267				if(sim_state == 3)
1268					logmessage("wanduck", "The modem need the PUK code to reset PIN.");
1269				else
1270					logmessage("wanduck", "The modem need the PIN code to unlock.");
1271			}
1272			else if(link_wan[wan_unit] == 4){
1273				logmessage("wanduck", "The modem is scanning the stations.");
1274			}
1275			//else if(strcmp(modem_type, "ncm"))
1276			else
1277				link_changed = 1;
1278		}
1279
1280		if(link_wan[wan_unit] == 3)
1281			return SET_PIN;
1282		else if(link_wan[wan_unit] == 4)
1283			return SET_USBSCAN;
1284	}
1285	else
1286#endif // RTCONFIG_USB_MODEM
1287	{
1288		snprintf(prefix, sizeof(prefix), "wan%d_", wan_unit);
1289		snprintf(wan_proto, 16, "%s", nvram_safe_get(strcat_r(prefix, "proto", tmp)));
1290
1291		// check wan port.
1292		link_wan[wan_unit] = get_wanports_status(wan_unit);
1293
1294		if (get_dualwan_by_unit(wan_unit) == WANS_DUALWAN_IF_WAN
1295#if defined(RTCONFIG_WANRED_LED)
1296		    || get_dualwan_by_unit(wan_unit) == WANS_DUALWAN_IF_LAN
1297#endif
1298		   )
1299		{
1300			update_wan_leds(wan_unit);
1301		}
1302
1303		if(wan_unit == WAN_UNIT_FIRST)
1304			snprintf(wired_link_nvram, 16, "link_wan");
1305		else
1306			snprintf(wired_link_nvram, 16, "link_wan%d", wan_unit);
1307
1308		if(link_wan[wan_unit] != nvram_get_int(wired_link_nvram)){
1309			if(link_wan[wan_unit]){
1310				nvram_set_int(wired_link_nvram, CONNED);
1311				record_wan_state_nvram(wan_unit, -1, -1, WAN_AUXSTATE_NONE);
1312			}
1313			else{
1314				nvram_set_int(wired_link_nvram, DISCONN);
1315				record_wan_state_nvram(wan_unit, -1, -1, WAN_AUXSTATE_NOPHY);
1316			}
1317
1318			link_changed = 1;
1319		}
1320
1321		// after update_wan_state(), auxstate will be cleaned.
1322		if(!link_wan[wan_unit])
1323			record_wan_state_nvram(wan_unit, -1, -1, WAN_AUXSTATE_NOPHY);
1324	}
1325
1326#ifdef RTCONFIG_LANWAN_LED
1327	if(get_lanports_status()) led_control(LED_LAN, LED_ON);
1328	else led_control(LED_LAN, LED_OFF);
1329#endif
1330
1331#ifdef RTCONFIG_LAN4WAN_LED
1332	LanWanLedCtrl();
1333#endif
1334
1335#ifdef RTCONFIG_WIRELESSREPEATER
1336	// check if set AP.
1337	if(sw_mode == SW_MODE_REPEATER || sw_mode == SW_MODE_HOTSPOT){
1338		link_ap = (wlc_state == WLC_STATE_CONNECTED);
1339		if(link_ap != nvram_get_int("link_ap"))
1340			nvram_set_int("link_ap", link_ap);
1341	}
1342#endif
1343
1344	if(sw_mode == SW_MODE_ROUTER){
1345		// this means D2C because of reconnecting the WAN port.
1346		if(link_changed){
1347#ifdef RTCONFIG_USB_MODEM
1348			if(dualwan_unit__usbif(wan_unit)){
1349				if(link_wan[wan_unit]){
1350					if(sim_lock){
1351						sim_lock = 0;
1352						record_wan_state_nvram(wan_unit, WAN_STATE_INITIALIZING, WAN_STOPPED_REASON_NONE, WAN_AUXSTATE_NONE);
1353					}
1354
1355					csprintf("wanduck(%d): PHY_RECONN.\n", wan_unit);
1356					return PHY_RECONN;
1357				}
1358				else{
1359					record_wan_state_nvram(wan_unit, WAN_STATE_STOPPED, -1, WAN_AUXSTATE_NOPHY);
1360					csprintf("wanduck(%d): SIM or modem is pulled off.\n", wan_unit);
1361					return DISCONN;
1362				}
1363			}
1364			else
1365#endif
1366			// WAN port was disconnected, arm reconnect
1367			if(!link_setup[wan_unit] && !link_wan[wan_unit]){
1368				link_setup[wan_unit] = 1;
1369			}
1370			// WAN port was connected, fire reconnect if armed
1371			else if(link_setup[wan_unit]){
1372				link_setup[wan_unit] = 0;
1373
1374				// Only handle this case when WAN proto is DHCP or Static
1375				if(!strcmp(wan_proto, "static")){
1376					disconn_case[wan_unit] = CASE_DISWAN;
1377					return PHY_RECONN;
1378				}
1379				else if(!strcmp(wan_proto, "dhcp")){
1380					disconn_case[wan_unit] = CASE_DHCPFAIL;
1381					return PHY_RECONN;
1382				}
1383			}
1384		}
1385		else if(!link_wan[wan_unit]){
1386#ifndef NO_DETECT_INTERNET
1387#ifdef RTCONFIG_DUALWAN
1388			if(strcmp(dualwan_mode, "lb"))
1389#endif
1390				nvram_set_int("link_internet", 1);
1391#endif
1392
1393			if((nvram_get_int("web_redirect")&WEBREDIRECT_FLAG_NOLINK)){
1394				disconn_case[wan_unit] = CASE_DISWAN;
1395			}
1396
1397			max_disconn_count[wan_unit] = max_disconn_count[wan_unit]/2;
1398			if(max_disconn_count[wan_unit] < 1)
1399				max_disconn_count[wan_unit] = 1;
1400			max_wait_time[wan_unit] = scan_interval*max_disconn_count[wan_unit];
1401
1402			return DISCONN;
1403		}
1404	}
1405	else if(sw_mode == SW_MODE_AP){
1406#if 0
1407		if(!link_wan[wan_unit]){
1408			// ?: type error?
1409			nvram_set_int("link_internet", 1);
1410
1411			record_wan_state_nvram(wan_unit, -1, -1, WAN_AUXSTATE_NOPHY);
1412
1413			if((nvram_get_int("web_redirect")&WEBREDIRECT_FLAG_NOLINK)){
1414				disconn_case[wan_unit] = CASE_DISWAN;
1415				return DISCONN;
1416			}
1417		}
1418#else
1419		if(nvram_get_int("link_internet") != 2)
1420			nvram_set_int("link_internet", 2);
1421
1422#ifdef RTCONFIG_DHCP_OVERRIDE
1423		if (nvram_match("dnsqmode", "2")) {
1424			disconn_case[wan_unit] = CASE_DISWAN;
1425			return DISCONN;
1426		}
1427		else
1428#endif
1429		return CONNED;
1430#endif
1431	}
1432#ifdef RTCONFIG_WIRELESSREPEATER
1433	else{ // sw_mode == SW_MODE_REPEATER, SW_MODE_HOTSPOT.
1434		if(!link_ap){
1435			if(nvram_get_int("link_internet") != 1)
1436				nvram_set_int("link_internet", 1);
1437
1438			if(sw_mode == SW_MODE_HOTSPOT)
1439				record_wan_state_nvram(wan_unit, -1, -1, WAN_AUXSTATE_NOPHY);
1440
1441			disconn_case[wan_unit] = CASE_AP_DISCONN;
1442			return DISCONN;
1443		}
1444		else if(sw_mode == SW_MODE_REPEATER){
1445			if(nvram_match("lan_proto", "dhcp") && nvram_get_int("lan_state_t") != LAN_STATE_CONNECTED){
1446				if(nvram_get_int("link_internet") != 1)
1447					nvram_set_int("link_internet", 1);
1448
1449				return DISCONN;
1450			}
1451			else{
1452				if(nvram_get_int("link_internet") != 2)
1453					nvram_set_int("link_internet", 2);
1454
1455				return CONNED;
1456			}
1457		}
1458	}
1459#endif
1460
1461	return CONNED;
1462}
1463
1464int if_wan_connected(int wan_unit){
1465	if(chk_proto(wan_unit) != CONNED)
1466		return DISCONN;
1467	else if(sw_mode == SW_MODE_ROUTER) // TODO: temparily let detect_internet() service in SW_MODE_ROUTER.
1468		return detect_internet(wan_unit);
1469
1470	return CONNED;
1471}
1472
1473void handle_wan_line(int wan_unit, int action){
1474	char cmd[32];
1475	char prefix_wan[8], nvram_name[16], wan_proto[16];
1476
1477	// Redirect rules.
1478	if(action){
1479_dprintf("nat_rule: stop_nat_rules 3.\n");
1480		stop_nat_rules();
1481	}
1482	/*
1483	 * When C2C and remove the redirect rules,
1484	 * it means dissolve the default state.
1485	 */
1486	else if(conn_changed_state[wan_unit] == D2C || conn_changed_state[wan_unit] == CONNED){
1487_dprintf("nat_rule: start_nat_rules 3.\n");
1488		start_nat_rules();
1489
1490		snprintf(prefix_wan, 8, "wan%d_", wan_unit);
1491
1492		snprintf(wan_proto, 16, "%s", nvram_safe_get(strcat_r(prefix_wan, "proto", nvram_name)));
1493
1494		if(!strcmp(wan_proto, "static")){
1495#if defined(RTCONFIG_WANRED_LED)
1496			char tmp[100];
1497			char *gateway, *wan_ifname;
1498
1499			wan_ifname = nvram_safe_get(strcat_r(prefix_wan, "ifname", tmp));
1500			gateway = nvram_safe_get(strcat_r(prefix_wan, "gateway", tmp));
1501			if (!test_gateway(gateway, wan_ifname)) {
1502				update_wan_state(prefix_wan, WAN_STATE_CONNECTED, 0);
1503			} else {
1504				update_wan_state(prefix_wan, WAN_STATE_CONNECTING, 0);
1505			}
1506#endif
1507			/* Sync time */
1508			refresh_ntpc();
1509		}
1510
1511#if defined(RTCONFIG_APP_PREINSTALLED) || defined(RTCONFIG_APP_NETINSTALLED)
1512		if(check_if_dir_exist("/opt/lib/ipkg")){
1513			csprintf("wanduck: update the APP's lists...\n");
1514			notify_rc("start_apps_update");
1515		}
1516#endif
1517	}
1518	else{ // conn_changed_state[wan_unit] == PHY_RECONN
1519		_dprintf("\n# wanduck(%d): Try to restart_wan_if.\n", action);
1520		snprintf(cmd, 32, "restart_wan_if %d", wan_unit);
1521		notify_rc_and_wait(cmd);
1522#if RTCONFIG_MULTICAST_IPTV
1523		if (nvram_get_int("switch_stb_x") > 6) {
1524			int unit;
1525			for (unit = WAN_UNIT_IPTV; unit < WAN_UNIT_MULTICAST_IPTV_MAX; unit++) {
1526				snprintf(cmd, sizeof(cmd), "restart_wan_if %d", unit);
1527				notify_rc_and_wait(cmd);
1528			}
1529		}
1530#endif
1531	}
1532}
1533
1534void close_socket(int sockfd, char type){
1535	close(sockfd);
1536	FD_CLR(sockfd, &allset);
1537	client[fd_i].sfd = -1;
1538	client[fd_i].type = 0;
1539}
1540
1541int build_socket(char *http_port, char *dns_port, int *hd, int *dd){
1542	if((*hd = passivesock(http_port, IPPROTO_TCP, 10)) < 0){
1543		csprintf("Fail to socket for httpd port: %s.\n", http_port);
1544		return -1;
1545	}
1546
1547	if((*dd = passivesock(dns_port, IPPROTO_UDP, 10)) < 0){
1548		csprintf("Fail to socket for DNS port: %s.\n", dns_port);
1549		return -1;
1550	}
1551
1552	return 0;
1553}
1554
1555void send_page(int wan_unit, int sfd, char *file_dest, char *url){
1556	char buf[2*MAXLINE];
1557	time_t now;
1558	char timebuf[100];
1559	char dut_addr[64];
1560	char dut_proto[16];
1561	char dut_port[5];
1562	char redirection[100];
1563
1564	memset(buf, 0, sizeof(buf));
1565	now = time(NULL);
1566	strftime(timebuf, sizeof(timebuf), RFC1123FMT, gmtime(&now));
1567
1568#ifdef NO_IOS_DETECT_INTERNET
1569	// disable iOS popup window. Jerry5 2012.11.27
1570	if (!strcmp(url,"www.apple.com/library/test/success.html") && nvram_get_int("disiosdet") == 1){
1571		sprintf(buf, "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s", buf, "HTTP/1.0 200 OK\r\n", "Server: Apache/2.2.3 (Oracle)\r\n", "Content-Type: text/html; charset=UTF-8\r\n", "Cache-Control: max-age=557\r\n","Expires: ", timebuf, "\r\n", "Date: ", timebuf, "\r\n", "Content-Length: 127\r\n", "Connection: close\r\n\r\n","<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\n","<HTML>\n","<HEAD>\n\t","<TITLE>Success</TITLE>\n","</HEAD>\n","<BODY>\n","Success\n","</BODY>\n","</HTML>\n");
1572	}
1573	else{
1574#endif
1575
1576	sprintf(buf, "%s%s%s%s%s%s", buf, "HTTP/1.0 302 Moved Temporarily\r\n", "Server: wanduck\r\n", "Date: ", timebuf, "\r\n");
1577	memset(dut_addr, 0, 64);
1578	memset(redirection, 0, 100);
1579
1580#ifdef RTCONFIG_WIRELESSREPEATER
1581	if(sw_mode == SW_MODE_REPEATER || sw_mode == SW_MODE_HOTSPOT)
1582		strcpy(dut_addr, DUT_DOMAIN_NAME);
1583	else
1584#endif
1585	if(isFirstUse)
1586		strcpy(dut_addr, DUT_DOMAIN_NAME);
1587	else
1588		strcpy(dut_addr, nvram_safe_get("lan_ipaddr"));
1589
1590#ifdef RTCONFIG_HTTPS
1591	if (nvram_get_int("http_enable") == 1) {
1592		strcpy(dut_proto, "https://");
1593		snprintf(dut_port, sizeof(dut_port), "%d", nvram_get_int("https_lanport") ? : 443);
1594	} else
1595#endif
1596	{
1597		strcpy(dut_proto, "http://");
1598		snprintf(dut_port, sizeof(dut_port), "%d", /*nvram_get_int("http_lanport") ? :*/ 80);
1599	}
1600
1601	if(strstr(url, "hotspot-detect") || strstr(url, "generate_204")){
1602		sprintf(redirection, "%s%s%s", "Location:", dut_proto, dut_addr);
1603	}
1604	else{
1605		sprintf(redirection, "%s%s%s%s%s", "refresh:1.0001; url=", dut_proto, dut_addr, ":", dut_port);
1606	}
1607
1608	// TODO: Only send pages for the wan(0)'s state.
1609	if(isFirstUse){
1610#ifdef RTCONFIG_WIRELESSREPEATER
1611		if(sw_mode == SW_MODE_REPEATER || sw_mode == SW_MODE_HOTSPOT)
1612			sprintf(buf, "%s%s%s%s%s%s%s" ,buf , "Connection: close\r\n", "", redirection, "/QIS_default.cgi?flag=sitesurvey", "\r\nContent-Type: text/plain\r\n", "\r\n<html></html>\r\n");
1613		else
1614#endif
1615#ifdef RTCONFIG_TMOBILE
1616			sprintf(buf, "%s%s%s%s%s%s%s" ,buf , "Connection: close\r\n", "", redirection, "/MobileQIS_Login.asp", "\r\nContent-Type: text/plain\r\n", "\r\n<html></html>\r\n");
1617#else
1618			sprintf(buf, "%s%s%s%s%s%s%s" ,buf , "Connection: close\r\n", "", redirection, "/QIS_default.cgi?flag=welcome", "\r\nContent-Type: text/plain\r\n", "\r\n<html></html>\r\n");
1619#endif
1620	}
1621	else if(conn_changed_state[wan_unit] == C2D || conn_changed_state[wan_unit] == DISCONN){
1622#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
1623		if(disconn_case[wan_unit] == CASE_DATALIMIT)
1624			sprintf(buf, "%s%s%s%s%s%d%s%s" ,buf , "Connection: close\r\n", "", redirection, "/blocking.asp?flag=", disconn_case[wan_unit], "\r\nContent-Type: text/plain\r\n", "");
1625		else
1626#endif
1627#ifdef RTCONFIG_USB_MODEM
1628#ifdef RTCONFIG_DYN_MODEM
1629		if(wan_unit == WAN_UNIT_FIRST && dualwan_unit__nonusbif(wan_unit) && get_dualwan_by_unit(other_wan_unit) == WANS_DUALWAN_IF_NONE && link_wan[other_wan_unit])
1630			sprintf(buf, "%s%s%s%s%s%d%s%s" ,buf , "Connection: close\r\n", "", redirection, "/error_page.htm?flag=", disconn_case[other_wan_unit], "\r\nContent-Type: text/plain\r\n", "");
1631		else
1632#endif
1633#endif
1634		if(disconn_case[wan_unit] == CASE_THESAMESUBNET)
1635			sprintf(buf, "%s%s%s%s%s%d%s%s" ,buf , "Connection: close\r\n", "", redirection, "/error_page.htm?flag=", disconn_case[wan_unit], "\r\nContent-Type: text/plain\r\n", "");
1636		else
1637			sprintf(buf, "%s%s%s%s%s%d%s%s" ,buf , "Connection: close\r\n", "", redirection, "/error_page.htm?flag=", disconn_case[wan_unit], "\r\nContent-Type: text/plain\r\n", "");
1638	}
1639#ifdef RTCONFIG_WIRELESSREPEATER
1640	else
1641		sprintf(buf, "%s%s%s%s%s", buf, "Connection: close\r\n", "", redirection, "/index.asp\r\nContent-Type: text/plain\r\n\r\n<html></html>\r\n");
1642#endif
1643
1644#ifdef NO_IOS_DETECT_INTERNET
1645	}
1646#endif
1647	write(sfd, buf, strlen(buf));
1648	close_socket(sfd, T_HTTP);
1649}
1650
1651void parse_dst_url(char *page_src){
1652	int i, j;
1653	char dest[PATHLEN], host[64];
1654	char host_strtitle[7], *hp;
1655
1656	j = 0;
1657	memset(dest, 0, sizeof(dest));
1658	memset(host, 0, sizeof(host));
1659	memset(host_strtitle, 0, sizeof(host_strtitle));
1660
1661	for(i = 0; i < strlen(page_src); ++i){
1662		if(i >= PATHLEN)
1663			break;
1664
1665		if(page_src[i] == ' ' || page_src[i] == '?'){
1666			dest[j] = '\0';
1667			break;
1668		}
1669
1670		dest[j++] = page_src[i];
1671	}
1672
1673	host_strtitle[0] = '\n';
1674	host_strtitle[1] = 'H';
1675	host_strtitle[2] = 'o';
1676	host_strtitle[3] = 's';
1677	host_strtitle[4] = 't';
1678	host_strtitle[5] = ':';
1679	host_strtitle[6] = ' ';
1680
1681	if((hp = strstr(page_src, host_strtitle)) != NULL){
1682		hp += 7;
1683		j = 0;
1684		for(i = 0; i < strlen(hp); ++i){
1685			if(i >= 64)
1686				break;
1687
1688			if(hp[i] == '\r' || hp[i] == '\n'){
1689				host[j] = '\0';
1690				break;
1691			}
1692
1693			host[j++] = hp[i];
1694		}
1695	}
1696
1697	memset(dst_url, 0, sizeof(dst_url));
1698	sprintf(dst_url, "%s/%s", host, dest);
1699}
1700
1701void parse_req_queries(char *content, char *lp, int len, int *reply_size){
1702	int i, rn;
1703
1704	rn = *(reply_size);
1705	for(i = 0; i < len; ++i){
1706		content[rn+i] = lp[i];
1707		if(lp[i] == 0){
1708			++i;
1709			break;
1710		}
1711	}
1712
1713	if(i >= len)
1714		return;
1715
1716	content[rn+i] = lp[i];
1717	content[rn+i+1] = lp[i+1];
1718	content[rn+i+2] = lp[i+2];
1719	content[rn+i+3] = lp[i+3];
1720	i += 4;
1721
1722	*reply_size += i;
1723}
1724
1725void handle_http_req(int sfd, char *line){
1726	int len;
1727
1728	if(!strncmp(line, "GET /", 5)){
1729		parse_dst_url(line+5);
1730
1731		len = strlen(dst_url);
1732		if((dst_url[len-4] == '.') &&
1733				(dst_url[len-3] == 'i') &&
1734				(dst_url[len-2] == 'c') &&
1735				(dst_url[len-1] == 'o')){
1736			close_socket(sfd, T_HTTP);
1737
1738			return;
1739		}
1740
1741		send_page(current_wan_unit, sfd, NULL, dst_url);
1742	}
1743	else
1744		close_socket(sfd, T_HTTP);
1745}
1746
1747void handle_dns_req(int sfd, char *line, int maxlen, struct sockaddr *pcliaddr, int clen){
1748	dns_query_packet d_req;
1749	dns_response_packet d_reply;
1750	int reply_size;
1751	char reply_content[MAXLINE];
1752	void *data = &d_reply.answers;
1753	size_t data_len = sizeof(d_reply.answers);
1754	in_addr_t lan_ipaddr = inet_addr_(nvram_safe_get("lan_ipaddr"));	// router's LAN IP
1755#if !defined(RTCONFIG_FINDASUS)
1756	unsigned char auth_name_srv[] = {
1757		0x00, 0x00, 0x06, 0x00, 0x01, 0x00,
1758		0x00, 0x2a, 0x30, 0x00, 0x40, 0x01, 0x61, 0x0c,
1759		0x72, 0x6f, 0x6f, 0x74, 0x2d, 0x73, 0x65, 0x72,
1760		0x76, 0x65, 0x72, 0x73, 0x03, 0x6e, 0x65, 0x74,
1761		0x00, 0x05, 0x6e, 0x73, 0x74, 0x6c, 0x64, 0x0c,
1762		0x76, 0x65, 0x72, 0x69, 0x73, 0x69, 0x67, 0x6e,
1763		0x2d, 0x67, 0x72, 0x73, 0x03, 0x63, 0x6f, 0x6d,
1764		0x00, 0x78, 0x1b, 0x1a, 0xfd, 0x00, 0x00, 0x07,
1765		0x08, 0x00, 0x00, 0x03, 0x84, 0x00, 0x09, 0x3a,
1766		0x80, 0x00, 0x01, 0x51, 0x80
1767	};
1768#endif
1769
1770	reply_size = 0;
1771	memset(reply_content, 0, MAXLINE);
1772	memset(&d_req, 0, sizeof(d_req));
1773	memcpy(&d_req.header, line, sizeof(d_req.header));
1774
1775	// header
1776	memcpy(&d_reply.header, &d_req.header, sizeof(dns_header));
1777	d_reply.header.flag_set.flag_num = htons(0x8580);
1778	//d_reply.header.flag_set.flag_num = htons(0x8180);
1779	d_reply.header.answer_rrs = htons(0x0001);
1780	memcpy(reply_content, &d_reply.header, sizeof(d_reply.header));
1781	reply_size += sizeof(d_reply.header);
1782
1783	reply_content[5] = 1;	// Questions
1784	reply_content[7] = 1;	// Answer RRS
1785	reply_content[9] = 0;	// Authority RRS
1786	reply_content[11] = 0;	// Additional RRS
1787
1788	// queries
1789	parse_req_queries(reply_content, line+sizeof(dns_header), maxlen-sizeof(dns_header), &reply_size);
1790
1791	// answers
1792	d_reply.answers.name = htons(0xc00c);
1793	d_reply.answers.type = htons(0x0001);
1794	d_reply.answers.ip_class = htons(0x0001);
1795	//d_reply.answers.ttl = htonl(0x00000001);
1796	d_reply.answers.ttl = htonl(0x00000000);
1797	d_reply.answers.data_len = htons(0x0004);
1798
1799	char query_name[PATHLEN];
1800	int len, i;
1801
1802	strncpy(query_name, line+sizeof(dns_header)+1, PATHLEN);
1803	len = strlen(query_name);
1804	for(i = 0; i < len; ++i)
1805		if(query_name[i] < 32)
1806			query_name[i] = '.';
1807
1808	if ((repeater_mode() || mediabridge_mode()) &&
1809	    nvram_match("lan_proto", "dhcp") && nvram_get_int("lan_state_t") != LAN_STATE_CONNECTED)
1810		lan_ipaddr = inet_addr_(nvram_default_get("lan_ipaddr"));
1811
1812	if(!upper_strcmp(query_name, router_name)){
1813		d_reply.answers.addr = lan_ipaddr;
1814	}
1815	else if (!upper_strcmp(query_name, "findasus.local")) {
1816#ifdef RTCONFIG_FINDASUS
1817		d_reply.answers.addr = lan_ipaddr;
1818#else
1819		data = auth_name_srv;
1820		data_len = sizeof(auth_name_srv);
1821		d_reply.header.flag_set.flag_num = htons(0x8183);			/* No such name */
1822		memcpy(reply_content, &d_reply.header, sizeof(d_reply.header));
1823		reply_content[5] = 1;	// Questions
1824		reply_content[7] = 0;	// Answer RRS
1825		reply_content[9] = 1;	// Authority RRS
1826		reply_content[11] = 0;	// Additional RRS
1827#endif
1828	}
1829	else
1830		d_reply.answers.addr = htonl(0x0a000001);	// 10.0.0.1
1831
1832	memcpy(reply_content+reply_size, data, data_len);
1833	reply_size += data_len;
1834
1835	sendto(sfd, reply_content, reply_size, 0, pcliaddr, clen);
1836}
1837
1838void run_http_serv(int sockfd){
1839	ssize_t n;
1840	char line[MAXLINE];
1841
1842	memset(line, 0, sizeof(line));
1843
1844	if((n = read(sockfd, line, MAXLINE)) == 0){	// client close
1845		close_socket(sockfd, T_HTTP);
1846
1847		return;
1848	}
1849	else if(n < 0){
1850		perror("wanduck serv http");
1851		return;
1852	}
1853	else{
1854		if(client[fd_i].type == T_HTTP)
1855			handle_http_req(sockfd, line);
1856		else
1857			close_socket(sockfd, T_HTTP);
1858	}
1859}
1860
1861void run_dns_serv(int sockfd){
1862	int n;
1863	char line[MAXLINE];
1864	struct sockaddr_in cliaddr;
1865	int clilen = sizeof(cliaddr);
1866
1867	memset(line, 0, MAXLINE);
1868	memset(&cliaddr, 0, clilen);
1869
1870	if((n = recvfrom(sockfd, line, MAXLINE, 0, (struct sockaddr *)&cliaddr, (socklen_t *)&clilen)) == 0)	// client close
1871		return;
1872	else if(n < 0){
1873		perror("wanduck serv dns");
1874		return;
1875	}
1876	else
1877		handle_dns_req(sockfd, line, n, (struct sockaddr *)&cliaddr, clilen);
1878}
1879
1880void record_wan_state_nvram(int wan_unit, int state, int sbstate, int auxstate){
1881	if(state != -1 && state != nvram_get_int(nvram_state[wan_unit]))
1882		nvram_set_int(nvram_state[wan_unit], state);
1883
1884	if(sbstate != -1 && sbstate != nvram_get_int(nvram_sbstate[wan_unit]))
1885		nvram_set_int(nvram_sbstate[wan_unit], sbstate);
1886
1887	if(auxstate != -1 && auxstate != nvram_get_int(nvram_auxstate[wan_unit]))
1888		nvram_set_int(nvram_auxstate[wan_unit], auxstate);
1889}
1890
1891void record_conn_status(int wan_unit){
1892	char prefix_wan[8], nvram_name[16], wan_proto[16];
1893	char log_title[32];
1894
1895	memset(log_title, 0, 32);
1896#ifdef RTCONFIG_DUALWAN
1897	if(!strcmp(dualwan_mode, "lb") || !strcmp(dualwan_mode, "fb"))
1898		sprintf(log_title, "WAN(%d) Connection", wan_unit);
1899	else
1900#endif
1901		strcpy(log_title, "WAN Connection");
1902
1903	memset(prefix_wan, 0, 8);
1904	sprintf(prefix_wan, "wan%d_", wan_unit);
1905
1906	memset(wan_proto, 0, 16);
1907	strcpy(wan_proto, nvram_safe_get(strcat_r(prefix_wan, "proto", nvram_name)));
1908
1909	if(conn_changed_state[wan_unit] == DISCONN || conn_changed_state[wan_unit] == C2D){
1910#ifdef RTCONFIG_WIRELESSREPEATER
1911		if(disconn_case[wan_unit] == CASE_AP_DISCONN){
1912			if(disconn_case_old[wan_unit] == CASE_AP_DISCONN)
1913				return;
1914			disconn_case_old[wan_unit] = CASE_AP_DISCONN;
1915
1916			logmessage(log_title, "Don't connect the AP yet.");
1917		}
1918		else
1919#endif
1920		if(disconn_case[wan_unit] == CASE_DISWAN){
1921			if(disconn_case_old[wan_unit] == CASE_DISWAN)
1922				return;
1923			disconn_case_old[wan_unit] = CASE_DISWAN;
1924
1925			logmessage(log_title, "Ethernet link down.");
1926		}
1927		else if(disconn_case[wan_unit] == CASE_PPPFAIL){
1928			if(disconn_case_old[wan_unit] == CASE_PPPFAIL)
1929				return;
1930			disconn_case_old[wan_unit] = CASE_PPPFAIL;
1931
1932			if(ppp_fail_state == WAN_STOPPED_REASON_PPP_AUTH_FAIL)
1933				logmessage(log_title, "Failed to authenticate ourselves to peer.");
1934			else if(ppp_fail_state == WAN_STOPPED_REASON_PPP_LACK_ACTIVITY)
1935				logmessage(log_title, "Terminating connection due to lack of activity.");
1936			else if(ppp_fail_state == WAN_STOPPED_REASON_PPP_NO_ACTIVITY)
1937				logmessage(log_title, "No response from ISP.");
1938			else
1939				logmessage(log_title, "Fail to connect with some issues.");
1940		}
1941		else if(disconn_case[wan_unit] == CASE_DHCPFAIL){
1942			if(disconn_case_old[wan_unit] == CASE_DHCPFAIL)
1943				return;
1944			disconn_case_old[wan_unit] = CASE_DHCPFAIL;
1945
1946			if(!strcmp(wan_proto, "dhcp")
1947#ifdef RTCONFIG_WIRELESSREPEATER
1948					|| sw_mode == SW_MODE_HOTSPOT
1949#endif
1950					)
1951				logmessage(log_title, "ISP's DHCP did not function properly.");
1952#if 0
1953			else
1954				logmessage(log_title, "Detected that the WAN Connection Type was PPPoE. But the PPPoE Setting was not complete.");
1955#endif
1956		}
1957		else if(disconn_case[wan_unit] == CASE_MISROUTE){
1958			if(disconn_case_old[wan_unit] == CASE_MISROUTE)
1959				return;
1960			disconn_case_old[wan_unit] = CASE_MISROUTE;
1961
1962			logmessage(log_title, "The router's ip was the same as gateway's ip. It led to your packages couldn't dispatch to internet correctly.");
1963		}
1964		else if(disconn_case[wan_unit] == CASE_THESAMESUBNET){
1965			if(disconn_case_old[wan_unit] == CASE_THESAMESUBNET)
1966				return;
1967			disconn_case_old[wan_unit] = CASE_THESAMESUBNET;
1968
1969			logmessage(log_title, "The LAN's subnet may be the same with the WAN's subnet.");
1970
1971#ifdef RTCONFIG_TMOBILE
1972			logmessage(log_title, "reset LAN subnet and dhcp pool.");
1973			if(!strncmp(nvram_safe_get("lan_ipaddr"), "192.168.29.", 11))
1974			{
1975				nvram_set("lan_ipaddr"   , "192.168.24.1");
1976				nvram_set("lan_ipaddr_rt", "192.168.24.1");
1977				nvram_set("dhcp_start"   , "192.168.24.100");
1978				nvram_set("dhcp_end"     , "192.168.24.254");
1979			} else {
1980				nvram_set("lan_ipaddr"   , "192.168.29.1");
1981				nvram_set("lan_ipaddr_rt", "192.168.29.1");
1982				nvram_set("dhcp_start"   , "192.168.29.100");
1983				nvram_set("dhcp_end"     , "192.168.29.254");
1984			}
1985			nvram_commit();
1986			reboot(RB_AUTOBOOT);
1987#endif
1988		}
1989#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
1990		else if(disconn_case[wan_unit] == CASE_DATALIMIT){
1991			if(disconn_case_old[wan_unit] == CASE_DATALIMIT)
1992				return;
1993			disconn_case_old[wan_unit] = CASE_DATALIMIT;
1994
1995			logmessage(log_title, "The Data is at limit.");
1996		}
1997#endif
1998		else{	// disconn_case[wan_unit] == CASE_OTHERS
1999			if(disconn_case_old[wan_unit] == CASE_OTHERS)
2000				return;
2001			disconn_case_old[wan_unit] = CASE_OTHERS;
2002
2003			logmessage(log_title, "WAN was exceptionally disconnected.");
2004		}
2005	}
2006	else if(conn_changed_state[wan_unit] == D2C){
2007		if(disconn_case_old[wan_unit] == 10)
2008			return;
2009		disconn_case_old[wan_unit] = 10;
2010
2011		logmessage(log_title, "WAN was restored.");
2012	}
2013	else if(conn_changed_state[wan_unit] == PHY_RECONN){
2014		logmessage(log_title, "Ethernet link up.");
2015	}
2016}
2017
2018int get_disconn_count(int wan_unit){
2019	return changed_count[wan_unit];
2020}
2021
2022void set_disconn_count(int wan_unit, int flag){
2023	changed_count[wan_unit] = flag;
2024}
2025
2026int get_next_unit(int wan_unit){
2027	int next = (wan_unit+1)%WAN_UNIT_MAX;
2028
2029	return next;
2030}
2031
2032int get_last_unit(int wan_unit){
2033	int last = wan_unit-1;
2034
2035	if(last < WAN_UNIT_FIRST)
2036		last = WAN_UNIT_MAX-1;
2037
2038	return last;
2039}
2040
2041int switch_wan_line(const int wan_unit, const int restart_other){
2042#ifdef RTCONFIG_USB_MODEM
2043	int retry, lock;
2044#endif
2045	char cmd[32];
2046	int unit;
2047	char prefix[] = "wanXXXXXX_", tmp[100] = "";
2048
2049	for(unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit)
2050		if(unit == wan_unit)
2051			break;
2052	if(unit == WAN_UNIT_MAX)
2053		return 0;
2054
2055	if(wan_primary_ifunit() == wan_unit) // Already have no running modem.
2056		return 0;
2057#ifdef RTCONFIG_USB_MODEM
2058	else if (dualwan_unit__usbif(wan_unit)) {
2059		if(!link_wan[wan_unit]) {
2060			snprintf(prefix, sizeof(prefix), "wan%d_", wan_unit);
2061			nvram_set_int(strcat_r(prefix, "is_usb_modem_ready", tmp), link_wan[wan_unit]);
2062			return 0; // No modem in USB ports.
2063		}
2064	}
2065#endif
2066
2067	csprintf("%s: wan(%d) Starting...\n", __FUNCTION__, wan_unit);
2068	// Set the modem to be running.
2069	set_wan_primary_ifunit(wan_unit);
2070
2071#ifdef RTCONFIG_USB_MODEM
2072	if (nvram_invmatch("modem_enable", "4") && dualwan_unit__usbif(wan_unit)) {
2073		// Wait the PPP config file to be done.
2074		retry = 0;
2075		while((lock = file_lock("3g")) == -1 && retry < MAX_WAIT_FILE)
2076			sleep(1);
2077
2078		if(lock == -1){
2079			csprintf("(%d): No pppd conf file and turn off the state of USB Modem.\n", wan_unit);
2080			set_wan_primary_ifunit(get_last_unit(wan_unit));
2081			return 0;
2082		}
2083		else
2084			file_unlock(lock);
2085	}
2086#endif
2087
2088	// TODO: don't know if it's necessary?
2089	// clean or restart the other line.
2090	if(restart_other)
2091	{
2092		for(unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit){
2093			if(unit == wan_unit)
2094				continue;
2095
2096			csprintf("wanduck1: restart_wan_if %d.\n", unit);
2097			snprintf(cmd, 32, "restart_wan_if %d", unit);
2098			notify_rc_and_wait(cmd);
2099			sleep(1);
2100		}
2101	}
2102#ifdef RTCONFIG_USB_MODEM
2103	else{
2104		for(unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit){
2105			if(unit == wan_unit)
2106				continue;
2107
2108			if(dualwan_unit__nonusbif(unit))
2109				continue;
2110
2111			csprintf("wanduck1: stop_wan_if %d.\n", unit);
2112			snprintf(cmd, 32, "stop_wan_if %d", unit);
2113			notify_rc_and_wait(cmd);
2114			sleep(1);
2115		}
2116	}
2117#endif
2118
2119#if defined(RTCONFIG_IPV6) && defined(RTCONFIG_DUALWAN)
2120	int ipv6_service = 0;
2121	/* Start each configured and enabled wan connection and its undelying i/f */
2122	for (unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit)
2123		if (get_ipv6_service_by_unit(unit) != IPV6_DISABLED) {
2124			ipv6_service = 1;
2125			break;
2126		}
2127#endif
2128
2129	// restart the primary line.
2130	if (get_wan_state(wan_unit) == WAN_STATE_CONNECTED
2131#if defined(RTCONFIG_IPV6) && defined(RTCONFIG_DUALWAN)
2132		&& !(!strstr(dualwan_wans, "none")
2133			&& (!strcmp(dualwan_mode, "fo") || !strcmp(dualwan_mode, "fb"))
2134			&& ipv6_service)
2135#endif
2136	)
2137		snprintf(cmd, 32, "restart_wan_line %d", wan_unit);
2138	else
2139		snprintf(cmd, 32, "restart_wan_if %d", wan_unit);
2140	csprintf("wanduck2: %s.\n", cmd);
2141	notify_rc_and_wait(cmd);
2142
2143#ifdef RTCONFIG_DUALWAN
2144	if(sw_mode == SW_MODE_ROUTER
2145			&& (!strcmp(dualwan_mode, "fo") || !strcmp(dualwan_mode, "fb"))
2146			){
2147		delay_detect = 1;
2148	}
2149#endif
2150
2151	csprintf("%s: wan(%d) End.\n", __FUNCTION__, wan_unit);
2152	return 1;
2153}
2154
2155int wanduck_main(int argc, char *argv[]){
2156	char *http_servport, *dns_servport;
2157	int clilen;
2158	struct sockaddr_in cliaddr;
2159	struct timeval  tval;
2160	int nready, maxi, sockfd;
2161	int wan_unit, wan_sbstate;
2162	char prefix_wan[8];
2163	char cmd[32];
2164	char tmp[100]="";
2165#ifdef RTCONFIG_WIRELESSREPEATER
2166	char domain_mapping[64];
2167#endif
2168#ifdef RTCONFIG_DSL
2169	int usb_switched_back_dsl = 0;
2170#endif
2171	unsigned int now;
2172#ifdef RTCONFIG_DUALWAN
2173#if defined(RTAC68U) ||  defined(RTAC87U) || defined(RTAC3200) || defined(RTAC88U) || defined(RTAC3100) || defined(RTAC5300)|| defined(RTAC5300R)
2174	int wanred_led_status = 0;	/* 1 is no internet, 2 is internet ok */
2175	int u, link_status;
2176#endif
2177#endif
2178#ifdef RTCONFIG_QTN
2179	time_t qtn_now;
2180	struct tm *qtn_tm;
2181	char *time_string[14] = {0};
2182#endif
2183
2184	signal(SIGHUP, SIG_IGN);
2185	signal(SIGTERM, safe_leave);
2186	signal(SIGCHLD, chld_reap);
2187	signal(SIGUSR1, get_network_nvram);
2188	signal(SIGUSR2, wan_led_control);
2189
2190	if(argc < 3){
2191		http_servport = DFL_HTTP_SERV_PORT;
2192		dns_servport = DFL_DNS_SERV_PORT;
2193	}
2194	else{
2195		if(atoi(argv[1]) <= 0)
2196			http_servport = DFL_HTTP_SERV_PORT;
2197		else
2198			http_servport = (char *)argv[1];
2199
2200		if(atoi(argv[2]) <= 0)
2201			dns_servport = DFL_DNS_SERV_PORT;
2202		else
2203			dns_servport = (char *)argv[2];
2204	}
2205
2206	wdbg = nvram_get_int("wdbg");
2207
2208	if(build_socket(http_servport, dns_servport, &http_sock, &dns_sock) < 0){
2209		csprintf("\n*** Fail to build socket! ***\n");
2210		exit(0);
2211	}
2212	if(fcntl(dns_sock, F_SETFL, fcntl(dns_sock, F_GETFL, 0) | O_NONBLOCK) < 0){
2213		_dprintf("wanduck set dnssock [%d] nonblock fail !\n", dns_sock);
2214		exit(0);
2215	}
2216
2217	test_log = nvram_get_int("wanduck_debug");
2218
2219	FILE *fp = fopen(WANDUCK_PID_FILE, "w");
2220
2221	if(fp != NULL){
2222		fprintf(fp, "%d", getpid());
2223		fclose(fp);
2224	}
2225
2226	maxfd = (http_sock > dns_sock)?http_sock:dns_sock;
2227	maxi = -1;
2228
2229	FD_ZERO(&allset);
2230	FD_SET(http_sock, &allset);
2231	FD_SET(dns_sock, &allset);
2232
2233	for(fd_i = 0; fd_i < MAX_USER; ++fd_i){
2234		client[fd_i].sfd = -1;
2235		client[fd_i].type = 0;
2236	}
2237
2238	rule_setup = 0;
2239	got_notify = 0;
2240	modem_act_reset = 0;
2241	clilen = sizeof(cliaddr);
2242
2243	sprintf(router_name, "%s", DUT_DOMAIN_NAME);
2244
2245#ifndef NO_DETECT_INTERNET
2246	nvram_set_int("link_internet", 0);
2247#endif
2248#ifdef RTCONFIG_WIRELESSREPEATER
2249	nvram_set_int("link_ap", 2);
2250#endif
2251
2252	for(wan_unit = WAN_UNIT_FIRST; wan_unit < WAN_UNIT_MAX; ++wan_unit){
2253		if(wan_unit != WAN_UNIT_FIRST)
2254			snprintf(tmp, 100, "link_wan%d", wan_unit);
2255		else
2256			snprintf(tmp, 100, "link_wan");
2257		nvram_set_int(tmp, 0);
2258
2259		link_setup[wan_unit] = 0;
2260		link_wan[wan_unit] = 0;
2261
2262		changed_count[wan_unit] = S_IDLE;
2263		disconn_case[wan_unit] = CASE_NONE;
2264
2265		memset(prefix_wan, 0, 8);
2266		sprintf(prefix_wan, "wan%d_", wan_unit);
2267
2268		strcat_r(prefix_wan, "state_t", nvram_state[wan_unit]);
2269		strcat_r(prefix_wan, "sbstate_t", nvram_sbstate[wan_unit]);
2270		strcat_r(prefix_wan, "auxstate_t", nvram_auxstate[wan_unit]);
2271
2272		set_disconn_count(wan_unit, S_IDLE);
2273#ifdef RTCONFIG_USB_MODEM
2274		nvram_set_int(strcat_r(prefix_wan, "is_usb_modem_ready", tmp), link_wan[wan_unit]);
2275#endif
2276	}
2277
2278#ifdef RTCONFIG_USB_MODEM
2279	memset(modem_type, 0, 32);
2280#ifdef RTCONFIG_INTERNAL_GOBI
2281	memset(usb_if, 0, 32);
2282#endif
2283#endif
2284
2285	loop_sec = uptime();
2286
2287	get_related_nvram(); // initial the System's variables.
2288	get_lan_nvram(); // initial the LAN's variables.
2289
2290	nat_redirect_enable_old = nat_redirect_enable;
2291
2292#ifdef RTCONFIG_DUALWAN
2293#if 1
2294	WAN_FB_UNIT = WAN_UNIT_FIRST;
2295#else
2296	WAN_FB_UNIT = WAN_UNIT_SECOND;
2297#endif
2298
2299#ifdef WEB_REDIRECT
2300	if(nvram_get_int("freeze_duck"))
2301		_dprintf("\n<*>freeze the duck, %ds left!\n", nvram_get_int("freeze_duck"));	// don't check conn state during inner events period
2302	else
2303#endif
2304	if(sw_mode == SW_MODE_ROUTER && !strcmp(dualwan_mode, "lb")){
2305		cross_state = DISCONN;
2306		for(wan_unit = WAN_UNIT_FIRST; wan_unit < WAN_UNIT_MAX; ++wan_unit){
2307			conn_state[wan_unit] = if_wan_phyconnected(wan_unit);
2308			if(conn_state[wan_unit] == CONNED){
2309				current_state[wan_unit] = nvram_get_int(nvram_state[wan_unit]);
2310#ifdef RTCONFIG_USB_MODEM
2311				if(!(dualwan_unit__usbif(wan_unit) && current_state[wan_unit] == WAN_STATE_INITIALIZING))
2312#endif
2313					conn_state[wan_unit] = if_wan_connected(wan_unit);
2314			}
2315			else
2316				conn_state[wan_unit] = DISCONN;
2317
2318			conn_changed_state[wan_unit] = conn_state[wan_unit];
2319
2320			if(conn_state[wan_unit] == CONNED && cross_state != CONNED)
2321				cross_state = CONNED;
2322
2323			conn_state_old[wan_unit] = conn_state[wan_unit];
2324
2325			record_conn_status(wan_unit);
2326
2327			if(cross_state == CONNED)
2328				set_disconn_count(wan_unit, S_IDLE);
2329			else
2330				set_disconn_count(wan_unit, S_COUNT);
2331		}
2332	}
2333	else if(sw_mode == SW_MODE_ROUTER
2334			&& (!strcmp(dualwan_mode, "fo") || !strcmp(dualwan_mode, "fb"))
2335			){
2336		if(wandog_delay > 0){
2337			csprintf("wanduck: delay %d seconds...\n", wandog_delay);
2338			sleep(wandog_delay);
2339			delay_detect = 0;
2340		}
2341
2342		// To check the phy connection of the standby line.
2343		for(wan_unit = WAN_UNIT_FIRST; wan_unit < WAN_UNIT_MAX; ++wan_unit){
2344			if(get_dualwan_by_unit(wan_unit) != WANS_DUALWAN_IF_NONE)
2345				conn_state[wan_unit] = if_wan_phyconnected(wan_unit);
2346		}
2347
2348		current_wan_unit = wan_primary_ifunit();
2349		other_wan_unit = get_next_unit(current_wan_unit);
2350if(test_log)
2351_dprintf("wanduck(%d)(first detect start): state %d, state_old %d, changed %d, wan_state %d.\n"
2352		, current_wan_unit, conn_state[current_wan_unit], conn_state_old[current_wan_unit], conn_changed_state[current_wan_unit], current_state[current_wan_unit]);
2353
2354		if(conn_state[current_wan_unit] == CONNED){
2355			current_state[current_wan_unit] = nvram_get_int(nvram_state[current_wan_unit]);
2356#ifdef RTCONFIG_USB_MODEM
2357			if(!(dualwan_unit__usbif(current_wan_unit) && current_state[current_wan_unit] == WAN_STATE_INITIALIZING))
2358#endif
2359				conn_state[current_wan_unit] = if_wan_connected(current_wan_unit);
2360
2361			cross_state = conn_state[current_wan_unit];
2362		}
2363		else
2364			cross_state = DISCONN;
2365
2366		conn_changed_state[current_wan_unit] = conn_state[current_wan_unit];
2367
2368		conn_state_old[current_wan_unit] = conn_state[current_wan_unit];
2369
2370		record_conn_status(current_wan_unit);
2371	}
2372	else
2373#endif // RTCONFIG_DUALWAN
2374	if(sw_mode == SW_MODE_ROUTER
2375#ifdef RTCONFIG_WIRELESSREPEATER
2376			|| sw_mode == SW_MODE_HOTSPOT
2377#endif
2378			){
2379		current_wan_unit = wan_primary_ifunit();
2380		other_wan_unit = get_next_unit(current_wan_unit);
2381
2382		conn_state[current_wan_unit] = if_wan_phyconnected(current_wan_unit);
2383		if(conn_state[current_wan_unit] == CONNED){
2384			current_state[current_wan_unit] = nvram_get_int(nvram_state[current_wan_unit]);
2385#ifdef RTCONFIG_USB_MODEM
2386			if(!(dualwan_unit__usbif(current_wan_unit) && current_state[current_wan_unit] == WAN_STATE_INITIALIZING))
2387#endif
2388				conn_state[current_wan_unit] = if_wan_connected(current_wan_unit);
2389
2390			cross_state = conn_state[current_wan_unit];
2391		}
2392		else
2393			cross_state = DISCONN;
2394
2395		conn_changed_state[current_wan_unit] = conn_state[current_wan_unit];
2396
2397		conn_state_old[current_wan_unit] = conn_state[current_wan_unit];
2398
2399		record_conn_status(current_wan_unit);
2400	}
2401	else{ // sw_mode == SW_MODE_AP, SW_MODE_REPEATER.
2402		current_wan_unit = WAN_UNIT_FIRST;
2403
2404		conn_state[current_wan_unit] = if_wan_phyconnected(current_wan_unit);
2405
2406		cross_state = conn_state[current_wan_unit];
2407
2408		conn_state_old[current_wan_unit] = conn_state[current_wan_unit];
2409
2410#ifdef RTCONFIG_WIRELESSREPEATER
2411		if(sw_mode == SW_MODE_REPEATER)
2412			record_conn_status(current_wan_unit);
2413#endif
2414
2415		if(sw_mode == SW_MODE_AP){
2416#ifdef RTCONFIG_REDIRECT_DNAME
2417			if(cross_state == DISCONN){
2418				csprintf("\n# AP mode: Enable direct rule(DISCONN)\n");
2419				eval("ebtables", "-t", "broute", "-F");
2420				eval("ebtables", "-t", "filter", "-F");
2421				redirect_setting();
2422				eval("iptables-restore", "/tmp/redirect_rules");
2423			}
2424			else if(cross_state == CONNED){
2425				csprintf("\n# AP mode: Disable direct rule(CONNED)\n");
2426				eval("ebtables", "-t", "broute", "-F");
2427				eval("ebtables", "-t", "filter", "-F");
2428				eval("ebtables", "-t", "broute", "-I", "BROUTING", "-p", "ipv4", "--ip-proto", "udp", "--ip-dport", "53", "-j", "redirect", "--redirect-target", "DROP");
2429				redirect_nat_setting();
2430				eval("iptables-restore", NAT_RULES);
2431			}
2432
2433#endif
2434
2435#ifdef RTCONFIG_RESTRICT_GUI
2436			if(cross_state == CONNED){
2437				if(nvram_get_int("fw_restrict_gui")){
2438					char word[PATH_MAX], *next_word;
2439
2440					foreach(word, nvram_safe_get("lan_ifnames"), next_word){
2441						if(!strncmp(word, "vlan", 4))
2442							continue;
2443
2444						eval("ebtables", "-t", "broute", "-I", "BROUTING", "-i", word, "-j", "mark", "--mark-set", BIT_RES_GUI, "--mark-target", "CONTINUE");
2445					}
2446
2447					repeater_filter_setting(0);
2448				}
2449			}
2450#endif
2451		}
2452	}
2453
2454	/*
2455	 * Because start_wanduck() is run early than start_wan()
2456	 * and the redirect rules is already set before running wanduck,
2457	 * handle_wan_line() must not be run at the first detect.
2458	 */
2459#ifdef WEB_REDIRECT
2460	if(nvram_get_int("freeze_duck"))
2461		_dprintf("\n<**>freeze the duck, %ds left!\n", nvram_get_int("freeze_duck"));	// don't check conn state during inner events period
2462	else
2463#endif
2464	if(cross_state == DISCONN){
2465		csprintf("\n# Enable direct rule\n");
2466		rule_setup = 1;
2467	}
2468	else if(cross_state == CONNED && isFirstUse){
2469		csprintf("\n#CONNED : Enable direct rule\n");
2470		rule_setup = 1;
2471	}
2472if(test_log)
2473_dprintf("wanduck(%d)(first detect   end): state %d, state_old %d, changed %d, wan_state %d.\n"
2474		, current_wan_unit, conn_state[current_wan_unit], conn_state_old[current_wan_unit], conn_changed_state[current_wan_unit], current_state[current_wan_unit]);
2475
2476	int first_loop = 1;
2477	unsigned int diff;
2478	for(;;){
2479		if(!first_loop){
2480			now = uptime();
2481			diff = now-loop_sec;
2482
2483			if(diff < scan_interval){
2484				rset = allset;
2485				tval.tv_sec = scan_interval-diff;
2486				tval.tv_usec = 0;
2487
2488				goto WANDUCK_SELECT;
2489			}
2490
2491			loop_sec = now;
2492		}
2493		else
2494			first_loop = 0;
2495
2496		rset = allset;
2497		tval.tv_sec = scan_interval;
2498		tval.tv_usec = 0;
2499
2500		get_related_nvram();
2501
2502		// Sam 2014/10/14
2503		// rule_setup depend on wan status,
2504		// if nat_redirect_enable changed, rebuild nat rule.
2505		if(rule_setup) {
2506			if(nat_redirect_enable_old == 0 && nat_redirect_enable == 1)	//need redirect
2507			{
2508_dprintf("nat_rule: stop_nat_rules 4.\n");
2509				stop_nat_rules();
2510			}
2511			else if(nat_redirect_enable_old == 1 && nat_redirect_enable == 0)	//don't redirect
2512			{
2513_dprintf("nat_rule: start_nat_rules 4.\n");
2514				start_nat_rules();
2515			}
2516		}
2517
2518		if(nat_redirect_enable_old != nat_redirect_enable)
2519			nat_redirect_enable_old = nat_redirect_enable;
2520		//_dprintf("rule_setup: %d, nat_state: %s\n", rule_setup, nvram_safe_get("nat_state"));
2521
2522#ifdef WEB_REDIRECT
2523		if(nvram_get_int("freeze_duck")){
2524			_dprintf("\n<****>freeze the duck, %ds left!\n", nvram_get_int("freeze_duck"));	// don't check conn state during inner events period
2525			goto WANDUCK_SELECT;
2526		}
2527		else
2528#endif
2529#ifdef RTCONFIG_DUALWAN
2530		if(sw_mode == SW_MODE_ROUTER && !strcmp(dualwan_mode, "lb")){
2531			cross_state = DISCONN;
2532			for(wan_unit = WAN_UNIT_FIRST; wan_unit < WAN_UNIT_MAX; ++wan_unit){
2533#if 0
2534#ifdef RTCONFIG_USB_MODEM
2535				if(dualwan_unit__usbif(wan_unit) && !link_wan[wan_unit]){
2536					if_wan_phyconnected(wan_unit);
2537					continue;
2538				}
2539#endif
2540#endif
2541
2542				current_state[wan_unit] = nvram_get_int(nvram_state[wan_unit]);
2543
2544				if(current_state[wan_unit] == WAN_STATE_DISABLED){
2545					//record_wan_state_nvram(wan_unit, WAN_STATE_STOPPED, WAN_STOPPED_REASON_MANUAL, -1);
2546
2547					disconn_case[wan_unit] = CASE_OTHERS;
2548					conn_state[wan_unit] = DISCONN;
2549				}
2550#ifdef RTCONFIG_USB_MODEM
2551				else if(dualwan_unit__usbif(wan_unit)
2552						&& (modem_act_reset == 1 || modem_act_reset == 2)
2553						){
2554_dprintf("wanduck(%d): detect the modem to be reset...\n", wan_unit);
2555					disconn_case[wan_unit] = CASE_OTHERS;
2556					conn_state[wan_unit] = DISCONN;
2557					set_disconn_count(wan_unit, S_IDLE);
2558				}
2559#endif
2560				else{
2561					conn_state[wan_unit] = if_wan_phyconnected(wan_unit);
2562					if(conn_state[wan_unit] == CONNED){
2563#ifdef RTCONFIG_USB_MODEM
2564						if(!(dualwan_unit__usbif(wan_unit) && current_state[wan_unit] == WAN_STATE_INITIALIZING))
2565#endif
2566							conn_state[wan_unit] = if_wan_connected(wan_unit);
2567					}
2568				}
2569
2570				wan_sbstate = nvram_get_int(nvram_sbstate[wan_unit]);
2571
2572#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
2573				if(disconn_case_old[wan_unit] != CASE_DATALIMIT && wan_sbstate == WAN_STOPPED_REASON_DATALIMIT){
2574					csprintf("wanduck(%d)(lb): detect the data limit.\n", wan_unit);
2575					conn_state[wan_unit] = DISCONN;
2576				}
2577#endif
2578
2579				if(conn_state[wan_unit] == CONNED && cross_state != CONNED)
2580					cross_state = CONNED;
2581
2582#ifdef RTCONFIG_USB_MODEM
2583				if(wan_sbstate != WAN_STOPPED_REASON_DATALIMIT && dualwan_unit__usbif(wan_unit)){
2584					if(link_wan[wan_unit] == 1 && current_state[wan_unit] == WAN_STATE_INITIALIZING && boot_end == 1){
2585						csprintf("wanduck: start_wan_if %d.\n", wan_unit);
2586						snprintf(cmd, 32, "start_wan_if %d", wan_unit);
2587						notify_rc(cmd);
2588						continue;
2589					}
2590					else if(!link_wan[wan_unit] && current_state[wan_unit] != WAN_STATE_INITIALIZING){
2591						csprintf("wanduck2: stop_wan_if %d.\n", wan_unit);
2592						snprintf(cmd, 32, "stop_wan_if %d", wan_unit);
2593						notify_rc(cmd);
2594						continue;
2595					}
2596				}
2597
2598				if(conn_state[wan_unit] == SET_PIN){
2599					conn_changed_state[wan_unit] = SET_PIN;
2600					set_disconn_count(wan_unit, S_IDLE);
2601				}
2602				else if(conn_state[wan_unit] == SET_USBSCAN){
2603					conn_changed_state[wan_unit] = SET_USBSCAN;
2604					set_disconn_count(wan_unit, S_IDLE);
2605				}
2606				else
2607#endif
2608				if(conn_state[wan_unit] != conn_state_old[wan_unit]){
2609					conn_state_old[wan_unit] = conn_state[wan_unit];
2610
2611					if(conn_state[wan_unit] == PHY_RECONN){
2612						conn_changed_state[wan_unit] = PHY_RECONN;
2613					}
2614					else if(conn_state[wan_unit] == DISCONN){
2615						conn_changed_state[wan_unit] = C2D;
2616
2617#ifdef RTCONFIG_USB_MODEM
2618						if (dualwan_unit__usbif(wan_unit))
2619							set_disconn_count(wan_unit, max_disconn_count[wan_unit]);
2620						else
2621#endif
2622#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
2623						if(disconn_case[wan_unit] == CASE_DATALIMIT)
2624							set_disconn_count(wan_unit, max_disconn_count[wan_unit]);
2625						else
2626#endif
2627							set_disconn_count(wan_unit, S_COUNT);
2628					}
2629					else if(conn_state[wan_unit] == CONNED){
2630						conn_changed_state[wan_unit] = D2C;
2631
2632						set_disconn_count(wan_unit, S_IDLE);
2633					}
2634					else
2635						conn_changed_state[wan_unit] = CONNED;
2636
2637					record_conn_status(wan_unit);
2638				}
2639
2640				if(get_disconn_count(wan_unit) != S_IDLE){
2641					if(conn_state[wan_unit] == PHY_RECONN)
2642						set_disconn_count(wan_unit, max_disconn_count[wan_unit]);
2643
2644					if(get_disconn_count(wan_unit) >= max_disconn_count[wan_unit]){
2645						set_disconn_count(wan_unit, S_IDLE);
2646
2647#ifdef RTCONFIG_USB_MODEM
2648						if(dualwan_unit__usbif(wan_unit))
2649							csprintf("\n# wanduck(usb): type=%s.\n", modem_type);
2650						if(dualwan_unit__usbif(wan_unit) &&
2651								(!strcmp(modem_type, "ecm") || !strcmp(modem_type, "ncm") || !strcmp(modem_type, "rndis") || !strcmp(modem_type, "asix") || !strcmp(modem_type, "qmi") || !strcmp(modem_type, "gobi"))
2652								){
2653							csprintf("\n# wanduck(usb): skip to run restart_wan_if %d.\n", wan_unit);
2654							if(!link_wan[wan_unit] && strlen(modem_type) > 0)
2655								memset(modem_type, 0, 32);
2656						}
2657						else
2658#endif
2659						{
2660							csprintf("\n# wanduck(%d): run restart_wan_if.\n", wan_unit);
2661							memset(cmd, 0, 32);
2662							sprintf(cmd, "restart_wan_if %d", wan_unit);
2663							notify_rc_and_period_wait(cmd, 30);
2664						}
2665
2666						if(get_wan_state(get_next_unit(wan_unit)) == WAN_STATE_CONNECTED){
2667							memset(cmd, 0, 32);
2668							sprintf(cmd, "restart_wan_line %d", get_next_unit(wan_unit));
2669							notify_rc(cmd);
2670						}
2671					}
2672					else
2673						set_disconn_count(wan_unit, get_disconn_count(wan_unit)+1);
2674
2675					csprintf("%s: wan(%d) disconn count = %d/%d ...\n", __FUNCTION__, wan_unit, get_disconn_count(wan_unit), max_disconn_count[wan_unit]);
2676				}
2677			}
2678if(test_log)
2679_dprintf("wanduck(%d)(lb change): state %d, state_old %d, changed %d, cross_state=%d, wan_state %d.\n"
2680		, current_wan_unit, conn_state[current_wan_unit], conn_state_old[current_wan_unit], conn_changed_state[current_wan_unit], cross_state, current_state[current_wan_unit]);
2681		}
2682		else if(sw_mode == SW_MODE_ROUTER && !strcmp(dualwan_mode, "fo")){
2683			if(delay_detect == 1 && wandog_delay > 0){
2684				csprintf("wanduck: delay %d seconds...\n", wandog_delay);
2685				sleep(wandog_delay);
2686				delay_detect = 0;
2687			}
2688
2689			// To check the phy connection of the standby line.
2690			for(wan_unit = WAN_UNIT_FIRST; wan_unit < WAN_UNIT_MAX; ++wan_unit){
2691				if(get_dualwan_by_unit(wan_unit) != WANS_DUALWAN_IF_NONE)
2692					conn_state[wan_unit] = if_wan_phyconnected(wan_unit);
2693			}
2694
2695			current_wan_unit = wan_primary_ifunit();
2696			other_wan_unit = get_next_unit(current_wan_unit);
2697
2698			current_state[current_wan_unit] = nvram_get_int(nvram_state[current_wan_unit]);
2699if(test_log)
2700_dprintf("wanduck(%d)(fo    phy): state %d, state_old %d, changed %d, wan_state %d.\n"
2701		, current_wan_unit, conn_state[current_wan_unit], conn_state_old[current_wan_unit], conn_changed_state[current_wan_unit], current_state[current_wan_unit]);
2702
2703			if(current_state[current_wan_unit] == WAN_STATE_DISABLED){
2704				//record_wan_state_nvram(current_wan_unit, WAN_STATE_STOPPED, WAN_STOPPED_REASON_MANUAL, -1);
2705
2706				disconn_case[current_wan_unit] = CASE_OTHERS;
2707				conn_state[current_wan_unit] = DISCONN;
2708				set_disconn_count(current_wan_unit, S_IDLE);
2709			}
2710#ifdef RTCONFIG_USB_MODEM
2711			else if(dualwan_unit__usbif(current_wan_unit)
2712					&& (modem_act_reset == 1 || modem_act_reset == 2)
2713					){
2714_dprintf("wanduck(%d): detect the modem to be reset...\n", current_wan_unit);
2715				disconn_case[current_wan_unit] = CASE_OTHERS;
2716				conn_state[current_wan_unit] = DISCONN;
2717				set_disconn_count(current_wan_unit, S_IDLE);
2718			}
2719#endif
2720			else{
2721				if(conn_state[current_wan_unit] == CONNED){
2722#ifdef RTCONFIG_USB_MODEM
2723					if(!(dualwan_unit__usbif(current_wan_unit) && current_state[current_wan_unit] == WAN_STATE_INITIALIZING))
2724#endif
2725						conn_state[current_wan_unit] = if_wan_connected(current_wan_unit);
2726if(test_log)
2727_dprintf("wanduck(%d)(fo   conn): state %d, state_old %d, changed %d, wan_state %d.\n"
2728		, current_wan_unit, conn_state[current_wan_unit], conn_state_old[current_wan_unit], conn_changed_state[current_wan_unit], current_state[current_wan_unit]);
2729				}
2730			}
2731
2732			wan_sbstate = nvram_get_int(nvram_sbstate[current_wan_unit]);
2733
2734			if(conn_state[current_wan_unit] == PHY_RECONN){
2735				conn_changed_state[current_wan_unit] = PHY_RECONN;
2736
2737				conn_state_old[current_wan_unit] = DISCONN;
2738
2739				// When the current line is re-plugged and the other line has plugged, the count has to be reset.
2740				if(get_dualwan_by_unit(other_wan_unit) != WANS_DUALWAN_IF_NONE && link_wan[other_wan_unit]){
2741					csprintf("# wanduck: set S_COUNT: PHY_RECONN.\n");
2742					set_disconn_count(current_wan_unit, S_COUNT);
2743				}
2744			}
2745#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
2746			else if(wan_sbstate == WAN_STOPPED_REASON_DATALIMIT){
2747				if(conn_state_old[current_wan_unit] == CONNED){
2748					csprintf("wanduck(%d)(fo): detect the data limit.\n", current_wan_unit);
2749					conn_changed_state[current_wan_unit] = C2D;
2750				}
2751				else
2752					conn_changed_state[current_wan_unit] = DISCONN;
2753
2754				conn_state_old[current_wan_unit] = DISCONN;
2755
2756				if(get_dualwan_by_unit(other_wan_unit) != WANS_DUALWAN_IF_NONE
2757						&& link_wan[other_wan_unit]
2758						&& nvram_get_int(nvram_sbstate[other_wan_unit]) != WAN_STOPPED_REASON_DATALIMIT)
2759					set_disconn_count(current_wan_unit, max_disconn_count[current_wan_unit]);
2760				else
2761					set_disconn_count(current_wan_unit, S_IDLE);
2762			}
2763#endif
2764#ifdef RTCONFIG_USB_MODEM
2765			else if(conn_state[current_wan_unit] == SET_PIN){
2766				conn_changed_state[current_wan_unit] = SET_PIN;
2767
2768				conn_state_old[current_wan_unit] = DISCONN;
2769				// The USB modem needs the PIN code to unlock.
2770				set_disconn_count(current_wan_unit, S_IDLE);
2771			}
2772			else if(conn_state[current_wan_unit] == SET_USBSCAN){
2773				conn_changed_state[current_wan_unit] = C2D;
2774
2775				conn_state_old[current_wan_unit] = DISCONN;
2776				// The USB modem is scanning the stations.
2777				set_disconn_count(current_wan_unit, S_IDLE);
2778			}
2779#if 0
2780#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
2781			else if(dualwan_unit__usbif(current_wan_unit) && wan_sbstate == WAN_STOPPED_REASON_DATALIMIT){
2782				if(conn_state_old[current_wan_unit] == CONNED){
2783					csprintf("wanduck(%d)(fo): detect the data limit.\n", current_wan_unit);
2784					conn_changed_state[current_wan_unit] = C2D;
2785				}
2786				else
2787					conn_changed_state[current_wan_unit] = DISCONN;
2788
2789				conn_state_old[current_wan_unit] = DISCONN;
2790				//set_disconn_count(current_wan_unit, max_disconn_count[current_wan_unit]);
2791				set_disconn_count(current_wan_unit, S_IDLE);
2792			}
2793#endif
2794#endif
2795#endif
2796			else if(conn_state[current_wan_unit] == CONNED){
2797				if(conn_state_old[current_wan_unit] == DISCONN)
2798					conn_changed_state[current_wan_unit] = D2C;
2799				else
2800					conn_changed_state[current_wan_unit] = CONNED;
2801
2802				conn_state_old[current_wan_unit] = conn_state[current_wan_unit];
2803				set_disconn_count(current_wan_unit, S_IDLE);
2804			}
2805			else if(conn_state[current_wan_unit] == DISCONN){
2806				if(conn_state_old[current_wan_unit] == CONNED)
2807					conn_changed_state[current_wan_unit] = C2D;
2808				else
2809					conn_changed_state[current_wan_unit] = DISCONN;
2810
2811				conn_state_old[current_wan_unit] = conn_state[current_wan_unit];
2812
2813				if(disconn_case[current_wan_unit] == CASE_THESAMESUBNET){
2814					csprintf("# wanduck: set S_IDLE: CASE_THESAMESUBNET.\n");
2815					set_disconn_count(current_wan_unit, S_IDLE);
2816				}
2817#ifdef RTCONFIG_USB_MODEM
2818				// when the other line is modem and not plugged, the current disconnected line would not count.
2819				else if(!link_wan[other_wan_unit] && dualwan_unit__usbif(other_wan_unit))
2820					set_disconn_count(current_wan_unit, S_IDLE);
2821#endif
2822				else if(get_disconn_count(current_wan_unit) == S_IDLE && current_state[current_wan_unit] != WAN_STATE_DISABLED
2823						&& get_dualwan_by_unit(other_wan_unit) != WANS_DUALWAN_IF_NONE
2824						)
2825					set_disconn_count(current_wan_unit, S_COUNT);
2826			}
2827
2828			if(get_disconn_count(current_wan_unit) != S_IDLE){
2829				if(get_disconn_count(current_wan_unit) < max_disconn_count[current_wan_unit]){
2830					set_disconn_count(current_wan_unit, get_disconn_count(current_wan_unit)+1);
2831					csprintf("# wanduck(%d): wait time for switching: %d/%d.\n", current_wan_unit, get_disconn_count(current_wan_unit)*scan_interval, max_wait_time[current_wan_unit]);
2832				}
2833				else{
2834					csprintf("# wanduck(%d): set S_COUNT: changed_count[] >= max_disconn_count.\n", current_wan_unit);
2835				}
2836			}
2837
2838			record_conn_status(current_wan_unit);
2839if(test_log)
2840_dprintf("wanduck(%d)(fo change): state %d, state_old %d, changed %d, wan_state %d.\n"
2841		, current_wan_unit, conn_state[current_wan_unit], conn_state_old[current_wan_unit], conn_changed_state[current_wan_unit], current_state[current_wan_unit]);
2842		}
2843		else if(sw_mode == SW_MODE_ROUTER && !strcmp(dualwan_mode, "fb")){
2844			if(delay_detect == 1 && wandog_delay > 0){
2845				csprintf("wanduck: delay %d seconds...\n", wandog_delay);
2846				sleep(wandog_delay);
2847				delay_detect = 0;
2848			}
2849
2850			// To check the phy connection of the standby line.
2851			for(wan_unit = WAN_UNIT_FIRST; wan_unit < WAN_UNIT_MAX; ++wan_unit){
2852				if(get_dualwan_by_unit(wan_unit) != WANS_DUALWAN_IF_NONE)
2853					conn_state[wan_unit] = if_wan_phyconnected(wan_unit);
2854			}
2855
2856			current_wan_unit = wan_primary_ifunit();
2857			other_wan_unit = get_next_unit(current_wan_unit);
2858
2859			current_state[current_wan_unit] = nvram_get_int(nvram_state[current_wan_unit]);
2860
2861			if(current_state[current_wan_unit] == WAN_STATE_DISABLED){
2862				//record_wan_state_nvram(current_wan_unit, WAN_STATE_STOPPED, WAN_STOPPED_REASON_MANUAL, -1);
2863
2864				disconn_case[current_wan_unit] = CASE_OTHERS;
2865				conn_state[current_wan_unit] = DISCONN;
2866				set_disconn_count(current_wan_unit, S_IDLE);
2867			}
2868#ifdef RTCONFIG_USB_MODEM
2869			else if(dualwan_unit__usbif(current_wan_unit)
2870					&& (modem_act_reset == 1 || modem_act_reset == 2)
2871					){
2872_dprintf("wanduck(%d): detect the modem to be reset...\n", current_wan_unit);
2873				disconn_case[current_wan_unit] = CASE_OTHERS;
2874				conn_state[current_wan_unit] = DISCONN;
2875				set_disconn_count(current_wan_unit, S_IDLE);
2876			}
2877#endif
2878			else{
2879				if(conn_state[current_wan_unit] == CONNED){
2880#ifdef RTCONFIG_USB_MODEM
2881					if(!(dualwan_unit__usbif(current_wan_unit) && current_state[current_wan_unit] == WAN_STATE_INITIALIZING))
2882#endif
2883						conn_state[current_wan_unit] = if_wan_connected(current_wan_unit);
2884				}
2885
2886				if(other_wan_unit == WAN_FB_UNIT && conn_state[other_wan_unit] == CONNED){
2887					current_state[other_wan_unit] = nvram_get_int(nvram_state[other_wan_unit]);
2888#ifdef RTCONFIG_USB_MODEM
2889					if(!(dualwan_unit__usbif(other_wan_unit) && current_state[other_wan_unit] == WAN_STATE_INITIALIZING))
2890#endif
2891						conn_state[other_wan_unit] = if_wan_connected(other_wan_unit);
2892					csprintf("wanduck: detect the fail-back line(%d)...\n", other_wan_unit);
2893if(test_log)
2894_dprintf("wanduck(%d) fail-back: state %d, state_old %d, changed %d, wan_state %d.\n"
2895		, other_wan_unit, conn_state[other_wan_unit], conn_state_old[other_wan_unit], conn_changed_state[other_wan_unit], current_state[other_wan_unit]);
2896				}
2897			}
2898
2899			wan_sbstate = nvram_get_int(nvram_sbstate[current_wan_unit]);
2900
2901			if(conn_state[current_wan_unit] == PHY_RECONN){
2902				conn_changed_state[current_wan_unit] = PHY_RECONN;
2903
2904				conn_state_old[current_wan_unit] = DISCONN;
2905
2906				// When the current line is re-plugged and the other line has plugged, the count has to be reset.
2907				if(get_dualwan_by_unit(other_wan_unit) != WANS_DUALWAN_IF_NONE && link_wan[other_wan_unit]){
2908					csprintf("# wanduck: set S_COUNT: PHY_RECONN.\n");
2909					set_disconn_count(current_wan_unit, S_COUNT);
2910				}
2911			}
2912#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
2913			else if(wan_sbstate == WAN_STOPPED_REASON_DATALIMIT){
2914				if(conn_state_old[current_wan_unit] == CONNED){
2915					csprintf("wanduck(%d)(fb): detect the data limit.\n", current_wan_unit);
2916					conn_changed_state[current_wan_unit] = C2D;
2917				}
2918				else
2919					conn_changed_state[current_wan_unit] = DISCONN;
2920
2921				conn_state_old[current_wan_unit] = DISCONN;
2922
2923				if(get_dualwan_by_unit(other_wan_unit) != WANS_DUALWAN_IF_NONE
2924						&& link_wan[other_wan_unit]
2925						&& nvram_get_int(nvram_sbstate[other_wan_unit]) != WAN_STOPPED_REASON_DATALIMIT)
2926					set_disconn_count(current_wan_unit, max_disconn_count[current_wan_unit]);
2927				else
2928					set_disconn_count(current_wan_unit, S_IDLE);
2929			}
2930#endif
2931#ifdef RTCONFIG_USB_MODEM
2932			else if(conn_state[current_wan_unit] == SET_PIN){
2933				conn_changed_state[current_wan_unit] = SET_PIN;
2934
2935				conn_state_old[current_wan_unit] = DISCONN;
2936				// The USB modem needs the PIN code to unlock.
2937				set_disconn_count(current_wan_unit, S_IDLE);
2938			}
2939			else if(conn_state[current_wan_unit] == SET_USBSCAN){
2940				conn_changed_state[current_wan_unit] = C2D;
2941
2942				conn_state_old[current_wan_unit] = DISCONN;
2943				// The USB modem is scanning the stations.
2944				set_disconn_count(current_wan_unit, S_IDLE);
2945			}
2946#if 0
2947#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
2948			else if(dualwan_unit__usbif(current_wan_unit) && wan_sbstate == WAN_STOPPED_REASON_DATALIMIT){
2949				if(conn_state_old[current_wan_unit] == CONNED){
2950					csprintf("wanduck(%d)(fb): detect the data limit.\n", current_wan_unit);
2951					conn_changed_state[current_wan_unit] = C2D;
2952				}
2953				else
2954					conn_changed_state[current_wan_unit] = DISCONN;
2955
2956				conn_state_old[current_wan_unit] = DISCONN;
2957				set_disconn_count(current_wan_unit, max_disconn_count[current_wan_unit]);
2958			}
2959#endif
2960#endif
2961#endif
2962			else if(conn_state[current_wan_unit] == CONNED){
2963				if(conn_state_old[current_wan_unit] == DISCONN)
2964					conn_changed_state[current_wan_unit] = D2C;
2965				else
2966					conn_changed_state[current_wan_unit] = CONNED;
2967
2968				conn_state_old[current_wan_unit] = conn_state[current_wan_unit];
2969				set_disconn_count(current_wan_unit, S_IDLE);
2970			}
2971			else if(conn_state[current_wan_unit] == DISCONN){
2972				if(conn_state_old[current_wan_unit] == CONNED)
2973					conn_changed_state[current_wan_unit] = C2D;
2974				else
2975					conn_changed_state[current_wan_unit] = DISCONN;
2976
2977				conn_state_old[current_wan_unit] = conn_state[current_wan_unit];
2978
2979				if(disconn_case[current_wan_unit] == CASE_THESAMESUBNET){
2980					csprintf("# wanduck: set S_IDLE: CASE_THESAMESUBNET.\n");
2981					set_disconn_count(current_wan_unit, S_IDLE);
2982				}
2983#ifdef RTCONFIG_USB_MODEM
2984				// when the other line is modem and not plugged, the current disconnected line would not count.
2985				else if(!link_wan[other_wan_unit] && dualwan_unit__usbif(other_wan_unit))
2986					set_disconn_count(current_wan_unit, S_IDLE);
2987#endif
2988				else if(get_disconn_count(current_wan_unit) == S_IDLE && current_state[current_wan_unit] != WAN_STATE_DISABLED
2989						&& get_dualwan_by_unit(other_wan_unit) != WANS_DUALWAN_IF_NONE
2990						)
2991					set_disconn_count(current_wan_unit, S_COUNT);
2992			}
2993
2994			if(other_wan_unit == WAN_FB_UNIT){
2995				if(conn_state[other_wan_unit] == CONNED
2996						&& get_disconn_count(other_wan_unit) == S_IDLE
2997						)
2998					set_disconn_count(other_wan_unit, S_COUNT);
2999				else if(conn_state[other_wan_unit] == DISCONN)
3000					set_disconn_count(other_wan_unit, S_IDLE);
3001			}
3002			else
3003				set_disconn_count(other_wan_unit, S_IDLE);
3004
3005			if(get_disconn_count(current_wan_unit) != S_IDLE){
3006				if(get_disconn_count(current_wan_unit) < max_disconn_count[current_wan_unit]){
3007					set_disconn_count(current_wan_unit, get_disconn_count(current_wan_unit)+1);
3008					csprintf("# wanduck(%d): wait time for switching: %d/%d.\n", current_wan_unit, get_disconn_count(current_wan_unit)*scan_interval, max_wait_time[current_wan_unit]);
3009				}
3010				else{
3011					csprintf("# wanduck(%d): set S_COUNT: changed_count[] >= max_disconn_count.\n", current_wan_unit);
3012				}
3013			}
3014
3015			if(get_disconn_count(other_wan_unit) != S_IDLE){
3016				if(get_disconn_count(other_wan_unit) < max_fb_count){
3017					set_disconn_count(other_wan_unit, get_disconn_count(other_wan_unit)+1);
3018					csprintf("# wanduck: wait time for returning: %d/%d.\n", get_disconn_count(other_wan_unit)*scan_interval, max_fb_wait_time);
3019				}
3020				else{
3021					csprintf("# wanduck: set S_COUNT: changed_count[] >= max_fb_count.\n");
3022					set_disconn_count(other_wan_unit, S_COUNT);
3023				}
3024			}
3025
3026			record_conn_status(current_wan_unit);
3027		}
3028		else
3029#else // RTCONFIG_DUALWAN
3030		if(sw_mode == SW_MODE_ROUTER
3031#ifdef RTCONFIG_WIRELESSREPEATER
3032				|| sw_mode == SW_MODE_HOTSPOT
3033#endif
3034				){
3035			// To check the phy connection of the standby line.
3036			for(wan_unit = WAN_UNIT_FIRST; wan_unit < WAN_UNIT_MAX; ++wan_unit)
3037				conn_state[wan_unit] = if_wan_phyconnected(wan_unit);
3038
3039			current_wan_unit = wan_primary_ifunit();
3040			other_wan_unit = get_next_unit(current_wan_unit);
3041
3042			current_state[current_wan_unit] = nvram_get_int(nvram_state[current_wan_unit]);
3043
3044			if(current_state[current_wan_unit] == WAN_STATE_DISABLED){
3045				//record_wan_state_nvram(current_wan_unit, WAN_STATE_STOPPED, WAN_STOPPED_REASON_MANUAL, -1);
3046				update_wan_leds(current_wan_unit);
3047
3048				disconn_case[current_wan_unit] = CASE_OTHERS;
3049				conn_state[current_wan_unit] = DISCONN;
3050				set_disconn_count(current_wan_unit, S_IDLE);
3051			}
3052#ifdef RTCONFIG_USB_MODEM
3053			else if(dualwan_unit__usbif(current_wan_unit)
3054					&& (modem_act_reset == 1 || modem_act_reset == 2)
3055					){
3056_dprintf("wanduck(%d): detect the modem to be reset...\n", current_wan_unit);
3057				disconn_case[current_wan_unit] = CASE_OTHERS;
3058				conn_state[current_wan_unit] = DISCONN;
3059				set_disconn_count(current_wan_unit, S_IDLE);
3060			}
3061#endif
3062			else{
3063#if !defined(RTN14U) && !defined(RTAC1200GP)
3064				conn_state[current_wan_unit] = if_wan_phyconnected(current_wan_unit);
3065#endif
3066				if(conn_state[current_wan_unit] == CONNED){
3067#ifdef RTCONFIG_USB_MODEM
3068					if(!(dualwan_unit__usbif(current_wan_unit) && current_state[current_wan_unit] == WAN_STATE_INITIALIZING))
3069#endif
3070						conn_state[current_wan_unit] = if_wan_connected(current_wan_unit);
3071				}
3072			}
3073
3074			wan_sbstate = nvram_get_int(nvram_sbstate[current_wan_unit]);
3075
3076			if(conn_state[current_wan_unit] == PHY_RECONN){
3077				conn_changed_state[current_wan_unit] = PHY_RECONN;
3078
3079				conn_state_old[current_wan_unit] = DISCONN;
3080
3081				// When the current line is re-plugged and the other line has plugged, the count has to be reset.
3082				if(link_wan[other_wan_unit]){
3083					csprintf("# wanduck: set S_COUNT: PHY_RECONN.\n");
3084					set_disconn_count(current_wan_unit, S_COUNT);
3085				}
3086			}
3087#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
3088			else if(wan_sbstate == WAN_STOPPED_REASON_DATALIMIT){
3089				if(conn_state_old[current_wan_unit] == CONNED){
3090					csprintf("wanduck(usb): detect the data limit.\n");
3091					conn_changed_state[current_wan_unit] = C2D;
3092				}
3093				else
3094					conn_changed_state[current_wan_unit] = DISCONN;
3095
3096				conn_state_old[current_wan_unit] = DISCONN;
3097
3098				if(get_dualwan_by_unit(other_wan_unit) != WANS_DUALWAN_IF_NONE
3099						&& link_wan[other_wan_unit]
3100						&& nvram_get_int(nvram_sbstate[other_wan_unit]) != WAN_STOPPED_REASON_DATALIMIT)
3101					set_disconn_count(current_wan_unit, max_disconn_count[current_wan_unit]);
3102				else
3103					set_disconn_count(current_wan_unit, S_IDLE);
3104			}
3105#endif
3106#ifdef RTCONFIG_USB_MODEM
3107			else if(conn_state[current_wan_unit] == SET_PIN){
3108				conn_changed_state[current_wan_unit] = SET_PIN;
3109
3110				conn_state_old[current_wan_unit] = DISCONN;
3111				// The USB modem needs the PIN code to unlock.
3112				set_disconn_count(current_wan_unit, S_IDLE);
3113			}
3114			else if(conn_state[current_wan_unit] == SET_USBSCAN){
3115				conn_changed_state[current_wan_unit] = C2D;
3116
3117				conn_state_old[current_wan_unit] = DISCONN;
3118				// The USB modem is scanning the stations.
3119				set_disconn_count(current_wan_unit, S_IDLE);
3120			}
3121#if 0
3122#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
3123			else if(dualwan_unit__usbif(current_wan_unit) && wan_sbstate == WAN_STOPPED_REASON_DATALIMIT){
3124				if(conn_state_old[current_wan_unit] == CONNED){
3125					csprintf("wanduck(usb): detect the data limit.\n");
3126					conn_changed_state[current_wan_unit] = C2D;
3127				}
3128				else
3129					conn_changed_state[current_wan_unit] = DISCONN;
3130
3131				conn_state_old[current_wan_unit] = DISCONN;
3132				set_disconn_count(current_wan_unit, max_disconn_count[current_wan_unit]);
3133			}
3134#endif
3135#endif
3136#endif
3137			else if(conn_state[current_wan_unit] == CONNED){
3138				if(conn_state_old[current_wan_unit] == DISCONN)
3139					conn_changed_state[current_wan_unit] = D2C;
3140				else
3141					conn_changed_state[current_wan_unit] = CONNED;
3142
3143				conn_state_old[current_wan_unit] = conn_state[current_wan_unit];
3144
3145#ifdef RTCONFIG_DSL /* Paul add 2013/7/29, for Non-DualWAN 3G/4G WAN -> DSL WAN, auto Fail-Back feature */
3146				if (nvram_match("dsltmp_adslsyncsts","up") && current_wan_unit == WAN_UNIT_SECOND){
3147					csprintf("\n# wanduck: adslsync up.\n");
3148					set_disconn_count(current_wan_unit, S_IDLE);
3149					link_wan[current_wan_unit] = DISCONN;
3150					conn_state[current_wan_unit] = DISCONN;
3151					usb_switched_back_dsl = 1;
3152					max_disconn_count[current_wan_unit] = 1;
3153				}
3154				else
3155					set_disconn_count(current_wan_unit, S_IDLE);
3156#else
3157				set_disconn_count(current_wan_unit, S_IDLE);
3158#endif
3159			}
3160			else if(conn_state[current_wan_unit] == DISCONN){
3161				if(conn_state_old[current_wan_unit] == CONNED)
3162					conn_changed_state[current_wan_unit] = C2D;
3163				else
3164					conn_changed_state[current_wan_unit] = DISCONN;
3165
3166				conn_state_old[current_wan_unit] = conn_state[current_wan_unit];
3167
3168				if(disconn_case[current_wan_unit] == CASE_THESAMESUBNET){
3169					csprintf("# wanduck: set S_IDLE: CASE_THESAMESUBNET.\n");
3170					set_disconn_count(current_wan_unit, S_IDLE);
3171				}
3172#ifdef RTCONFIG_USB_MODEM
3173				// when the other line is modem and not plugged, the current disconnected line would not count.
3174				else if(!link_wan[other_wan_unit] && dualwan_unit__usbif(other_wan_unit))
3175					set_disconn_count(current_wan_unit, S_IDLE);
3176				else if(get_disconn_count(current_wan_unit) == S_IDLE && current_state[current_wan_unit] != WAN_STATE_DISABLED)
3177					set_disconn_count(current_wan_unit, S_COUNT);
3178#else
3179				else
3180					set_disconn_count(current_wan_unit, S_IDLE);
3181#endif
3182			}
3183
3184			if(get_disconn_count(current_wan_unit) != S_IDLE){
3185				if(get_disconn_count(current_wan_unit) < max_disconn_count[current_wan_unit]){
3186					set_disconn_count(current_wan_unit, get_disconn_count(current_wan_unit)+1);
3187					csprintf("# wanduck(%d): wait time for switching: %d/%d.\n", current_wan_unit, get_disconn_count(current_wan_unit)*scan_interval, max_wait_time[current_wan_unit]);
3188				}
3189				else{
3190					csprintf("# wanduck(%d): set S_COUNT: changed_count[] >= max_disconn_count.\n", current_wan_unit);
3191				}
3192			}
3193
3194			record_conn_status(current_wan_unit);
3195		}
3196		else
3197#endif // RTCONFIG_DUALWAN
3198		{ // sw_mode == SW_MODE_AP, SW_MODE_REPEATER.
3199			current_wan_unit = WAN_UNIT_FIRST;
3200			conn_state[current_wan_unit] = if_wan_phyconnected(current_wan_unit);
3201
3202			if(conn_state[current_wan_unit] == DISCONN){
3203				if(conn_state_old[current_wan_unit] == CONNED)
3204					conn_changed_state[current_wan_unit] = C2D;
3205				else
3206					conn_changed_state[current_wan_unit] = DISCONN;
3207			}
3208			else{
3209				if(conn_state_old[current_wan_unit] == DISCONN)
3210					conn_changed_state[current_wan_unit] = D2C;
3211				else
3212					conn_changed_state[current_wan_unit] = CONNED;
3213			}
3214
3215			conn_state_old[current_wan_unit] = conn_state[current_wan_unit];
3216		}
3217if(test_log)
3218_dprintf("wanduck(%d)(all   end): state %d, state_old %d, changed %d, wan_state %d.\n"
3219		, current_wan_unit, conn_state[current_wan_unit], conn_state_old[current_wan_unit], conn_changed_state[current_wan_unit], current_state[current_wan_unit]);
3220
3221#ifdef RTCONFIG_DUALWAN
3222		if(sw_mode == SW_MODE_ROUTER && !strcmp(dualwan_mode, "lb")){
3223#ifdef RTCONFIG_DSL	//TODO: general case
3224			int internet_led = 0;
3225			for(wan_unit = WAN_UNIT_FIRST; wan_unit < WAN_UNIT_MAX; ++wan_unit){
3226				if(is_wan_connect(wan_unit))	//since not update current_state[wan_unit] in USB modem case
3227					internet_led = 1;
3228			}
3229			if(internet_led) {
3230#if defined(RTCONFIG_WPS_ALLLED_BTN)
3231				if(nvram_match("AllLED", "1"))
3232					led_control(LED_WAN, LED_ON);
3233				else
3234					led_control(LED_WAN, LED_OFF);
3235#else
3236				led_control(LED_WAN, LED_ON);
3237#endif
3238			}
3239			else {
3240				led_control(LED_WAN, LED_OFF);
3241			}
3242#endif
3243			if(!rule_setup && (cross_state == DISCONN || isFirstUse)){
3244				if(isFirstUse)
3245					csprintf("\n# LB: Enable direct rule(isFirstUse)\n");
3246				else
3247					csprintf("\n# LB: Enable direct rule\n");
3248				rule_setup = 1;
3249_dprintf("nat_rule: stop_nat_rules 5.\n");
3250				stop_nat_rules();
3251			}
3252			else if(rule_setup && cross_state == CONNED && !isFirstUse){
3253				csprintf("\n# LB: Disable direct rule\n");
3254				rule_setup = 0;
3255_dprintf("nat_rule: start_nat_rules 5.\n");
3256				start_nat_rules();
3257			}
3258		}
3259		else
3260#endif
3261#ifdef RTCONFIG_WIRELESSREPEATER
3262		if(sw_mode == SW_MODE_REPEATER){
3263#ifdef RTCONFIG_RESTRICT_GUI
3264			char word[PATH_MAX], *next_word;
3265#endif
3266
3267			if(!got_notify)
3268				; // do nothing.
3269			else if(conn_changed_state[current_wan_unit] == DISCONN || conn_changed_state[current_wan_unit] == C2D || isFirstUse){
3270				//if(rule_setup == 0){
3271					if(conn_changed_state[current_wan_unit] == DISCONN)
3272						csprintf("\n# mode(%d): Enable direct rule(DISCONN)\n", sw_mode);
3273					else if(conn_changed_state[current_wan_unit] == C2D)
3274						csprintf("\n# mode(%d): Enable direct rule(C2D)\n", sw_mode);
3275					else
3276						csprintf("\n# mode(%d): Enable direct rule(isFirstUse)\n", sw_mode);
3277					rule_setup = 1;
3278
3279					eval("ebtables", "-t", "broute", "-F");
3280					eval("ebtables", "-t", "filter", "-F");
3281					// Drop the DHCP server from PAP.
3282					eval("ebtables", "-t", "filter", "-A", "FORWARD", "-i", nvram_safe_get(wlc_nvname("ifname")), "-j", "DROP");
3283					f_write_string("/proc/net/dnsmqctrl", "", 0, 0);
3284
3285#ifdef RTCONFIG_RESTRICT_GUI
3286					if(nvram_get_int("fw_restrict_gui")){
3287						foreach(word, nvram_safe_get("lan_ifnames"), next_word){
3288							if(!strncmp(word, "vlan", 4))
3289								continue;
3290
3291							eval("ebtables", "-t", "broute", "-A", "BROUTING", "-i", word, "-j", "mark", "--mark-set", BIT_RES_GUI, "--mark-target", "ACCEPT");
3292						}
3293
3294						repeater_filter_setting(0);
3295					}
3296#endif
3297_dprintf("nat_rule: stop_nat_rules 6.\n");
3298					stop_nat_rules();
3299				//}
3300				got_notify = 0;
3301			}
3302			else{
3303				//if(rule_setup == 1 && !isFirstUse)
3304				if(!isFirstUse)
3305				{
3306					csprintf("\n# mode(%d): Disable direct rule(CONNED)\n", sw_mode);
3307					rule_setup = 0;
3308					eval("ebtables", "-t", "broute", "-F");
3309					eval("ebtables", "-t", "filter", "-F");
3310
3311#ifdef RTCONFIG_RESTRICT_GUI
3312					if(nvram_get_int("fw_restrict_gui")){
3313						foreach(word, nvram_safe_get("lan_ifnames"), next_word){
3314							if(!strncmp(word, "vlan", 4))
3315								continue;
3316
3317							eval("ebtables", "-t", "broute", "-A", "BROUTING", "-i", word, "-j", "mark", "--mark-set", BIT_RES_GUI, "--mark-target", "CONTINUE");
3318						}
3319
3320						repeater_filter_setting(1);
3321					}
3322#endif
3323
3324					eval("ebtables", "-t", "broute", "-A", "BROUTING", "-d", "00:E0:11:22:33:44", "-j", "redirect", "--redirect-target", "DROP");
3325					sprintf(domain_mapping, "%x %s", inet_addr(nvram_safe_get("lan_ipaddr")), DUT_DOMAIN_NAME);
3326					f_write_string("/proc/net/dnsmqctrl", domain_mapping, 0, 0);
3327#ifdef RTCONFIG_REDIRECT_DNAME
3328					eval("ebtables", "-t", "broute", "-A", "BROUTING", "-p", "ipv4", "--ip-proto", "udp", "--ip-dport", "53", "-j", "redirect", "--redirect-target", "DROP");
3329#endif
3330_dprintf("nat_rule: start_nat_rules 6.\n");
3331					start_nat_rules();
3332				}
3333
3334				got_notify = 0;
3335			}
3336		}
3337		else
3338#endif // RTCONFIG_WIRELESSREPEATER
3339		if(sw_mode == SW_MODE_AP){
3340#ifdef RTCONFIG_REDIRECT_DNAME
3341			if (conn_changed_state[current_wan_unit] == C2D) {
3342				csprintf("\n# AP mode: Enable direct rule(C2D)\n");
3343				eval("ebtables", "-t", "broute", "-F");
3344				eval("ebtables", "-t", "filter", "-F");
3345				redirect_setting();
3346				eval("iptables-restore", "/tmp/redirect_rules");
3347			}
3348			else if (conn_changed_state[current_wan_unit] == D2C) {
3349				csprintf("\n# AP mode: Disable direct rule(D2C)\n");
3350				eval("ebtables", "-t", "broute", "-F");
3351				eval("ebtables", "-t", "filter", "-F");
3352				eval("ebtables", "-t", "broute", "-I", "BROUTING", "-p", "ipv4", "--ip-proto", "udp", "--ip-dport", "53", "-j", "redirect", "--redirect-target", "DROP");
3353				redirect_nat_setting();
3354				eval("iptables-restore", NAT_RULES);
3355			}
3356#else
3357			; // do nothing.
3358#endif
3359
3360#ifdef RTCONFIG_RESTRICT_GUI
3361			if(conn_changed_state[current_wan_unit] == D2C){
3362				if(nvram_get_int("fw_restrict_gui")){
3363					char word[PATH_MAX], *next_word;
3364
3365					foreach(word, nvram_safe_get("lan_ifnames"), next_word){
3366						if(!strncmp(word, "vlan", 4))
3367							continue;
3368
3369						eval("ebtables", "-t", "broute", "-I", "BROUTING", "-i", word, "-j", "mark", "--mark-set", BIT_RES_GUI, "--mark-target", "CONTINUE");
3370					}
3371
3372					repeater_filter_setting(0);
3373				}
3374			}
3375#endif
3376		}
3377		else if(conn_changed_state[current_wan_unit] == C2D || (conn_changed_state[current_wan_unit] == CONNED && isFirstUse)){
3378			if(rule_setup == 0){
3379				if(conn_changed_state[current_wan_unit] == C2D){
3380#if defined(RTCONFIG_WPS_ALLLED_BTN) || defined(RTCONFIG_DSL)
3381					led_control(LED_WAN, LED_OFF);
3382#elif defined(RTAC68U) || defined(RTAC87U) || defined(RTAC3200) || defined(RTAC88U) || defined(RTAC3100) || defined(RTAC5300)|| defined(RTAC5300R)
3383					if(
3384#ifdef RTAC68U
3385						!strcmp(get_productid(), "RT-AC66U V2")
3386#else
3387						1
3388#endif // RTAC68U
3389#ifdef RTCONFIG_DUALWAN
3390						&& (strcmp(dualwan_mode, "lb") == 0 ||
3391							 strcmp(dualwan_mode, "fb") == 0 ||
3392							 strcmp(dualwan_mode, "fo") == 0)
3393#endif // RTCONFIG_DUALWAN
3394					){
3395						logmessage("DualWAN", "skip single wan wan_led_control - WANRED off\n");
3396						if(nvram_match("AllLED", "1")){
3397							led_control(LED_WAN, LED_ON);
3398							disable_wan_wled();
3399						}
3400					}
3401#endif
3402					csprintf("\n# Enable direct rule(C2D)......\n");
3403				}
3404				else
3405					csprintf("\n# Enable direct rule(isFirstUse)\n");
3406				rule_setup = 1;
3407
3408				handle_wan_line(current_wan_unit, rule_setup);
3409
3410				if((conn_changed_state[current_wan_unit] == C2D)
3411#ifdef RTCONFIG_DUALWAN
3412						&& strcmp(dualwan_mode, "off")
3413#endif
3414						){
3415#ifdef RTCONFIG_USB_MODEM
3416					// the current line is USB and be plugged off.
3417					if(!link_wan[current_wan_unit] && dualwan_unit__usbif(current_wan_unit)){
3418						clean_modem_state(2);
3419						if(get_dualwan_by_unit(other_wan_unit) != WANS_DUALWAN_IF_NONE){
3420							csprintf("\n# wanduck(C2D): Modem was plugged off and try to Switch the other line.\n");
3421							switch_wan_line(other_wan_unit, 0);
3422						}
3423						else if(current_state[current_wan_unit] != WAN_STATE_INITIALIZING){
3424							csprintf("wanduck3: stop_wan_if %d.\n", current_wan_unit);
3425							snprintf(cmd, 32, "stop_wan_if %d", current_wan_unit);
3426							notify_rc(cmd);
3427						}
3428
3429#ifdef RTCONFIG_DSL /* Paul add 2013/7/29, for Non-DualWAN 3G/4G WAN -> DSL WAN, auto Fail-Back feature */
3430#ifndef RTCONFIG_DUALWAN
3431						if(nvram_match("dsltmp_adslsyncsts","up") && usb_switched_back_dsl == 1){
3432							csprintf("\n# wanduck: usb_switched_back_dsl: 1.\n");
3433							link_wan[WAN_UNIT_SECOND] = CONNED;
3434							max_disconn_count[WAN_UNIT_SECOND] = max_wait_time[WAN_UNIT_SECOND]/scan_interval;
3435							usb_switched_back_dsl = 0;
3436						}
3437#endif
3438#endif
3439					}
3440					else
3441#endif // RTCONFIG_USB_MODEM
3442					// C2D: Try to prepare the backup line.
3443					if(link_wan[other_wan_unit] == 1 && get_wan_state(other_wan_unit) != WAN_STATE_CONNECTED){
3444						csprintf("\n# wanduck(C2D): Try to prepare the backup line.\n");
3445						memset(cmd, 0, 32);
3446						sprintf(cmd, "restart_wan_if %d", other_wan_unit);
3447						notify_rc_and_wait(cmd);
3448					}
3449				}
3450			}
3451		}
3452		else if(conn_changed_state[current_wan_unit] == D2C || conn_changed_state[current_wan_unit] == CONNED){
3453			if(rule_setup == 1 && !isFirstUse){
3454#if defined(RTCONFIG_WPS_ALLLED_BTN)
3455				if(nvram_match("AllLED", "1"))
3456					led_control(LED_WAN, LED_ON);
3457				else
3458					led_control(LED_WAN, LED_OFF);
3459#elif defined(DSL_N55U) || defined(DSL_N55U_B)
3460				led_control(LED_WAN, LED_ON);
3461#elif defined(RTAC68U) || defined(RTAC87U) || defined(RTAC3200) || defined(RTAC88U) || defined(RTAC3100) || defined(RTAC5300)|| defined(RTAC5300R)
3462				if(nvram_match("AllLED", "1")
3463#ifdef RTAC68U
3464					&& !strcmp(get_productid(), "RT-AC66U V2")
3465#endif
3466				){
3467					led_control(LED_WAN, LED_OFF);
3468					enable_wan_wled();
3469				}
3470#endif
3471				csprintf("\n# Disable direct rule(D2C)......\n");
3472				rule_setup = 0;
3473				handle_wan_line(current_wan_unit, rule_setup);
3474			}
3475		}
3476		/*
3477		 * when all lines are plugged in and the currect line is disconnected over max_wait_time seconds,
3478		 * switch the connect to the other line.
3479		 */
3480		else if(conn_changed_state[current_wan_unit] == DISCONN){
3481			if(get_dualwan_by_unit(other_wan_unit) != WANS_DUALWAN_IF_NONE
3482					&& (get_disconn_count(current_wan_unit) >= max_disconn_count[current_wan_unit]
3483#ifdef RTCONFIG_USB_MODEM
3484							|| (!link_wan[current_wan_unit] && dualwan_unit__usbif(current_wan_unit)
3485#ifdef RTCONFIG_INTERNAL_GOBI
3486									&& strcmp(usb_if, "")
3487#endif
3488									)
3489#endif
3490							)
3491					)
3492			{
3493				csprintf("# wanduck(%d): Switching the connect to the %d WAN line...\n", current_wan_unit, get_next_unit(current_wan_unit));
3494				set_disconn_count(current_wan_unit, S_IDLE);;
3495				if(!link_wan[current_wan_unit] && dualwan_unit__usbif(current_wan_unit))
3496					switch_wan_line(other_wan_unit, 0);
3497				else
3498					switch_wan_line(other_wan_unit, 1);
3499			}
3500		}
3501		// phy connected -> disconnected -> connected
3502		else if(conn_changed_state[current_wan_unit] == PHY_RECONN){
3503#ifdef RTCONFIG_USB_MODEM
3504			if(dualwan_unit__usbif(current_wan_unit)){
3505				if(current_state[current_wan_unit] == WAN_STATE_INITIALIZING){
3506					if(!strcmp(modem_type, "qmi")){
3507						csprintf("wanduck(%d): Sleep 1 seconds to wait QMI modem nodes.\n", current_wan_unit);
3508						sleep(1);
3509					}
3510					handle_wan_line(current_wan_unit, 0);
3511				}
3512				else
3513					csprintf("wanduck(%d): the modem had been run...\n", current_wan_unit);
3514			}
3515			else
3516#endif
3517				handle_wan_line(current_wan_unit, 0);
3518
3519			conn_changed_state[current_wan_unit] = conn_state[current_wan_unit];
3520		}
3521
3522#ifdef RTCONFIG_DUALWAN
3523		if(!strcmp(dualwan_mode, "fb") && other_wan_unit == WAN_FB_UNIT && conn_state[other_wan_unit] == CONNED
3524				&& get_disconn_count(other_wan_unit) >= max_fb_count
3525				){
3526			csprintf("# wanduck: returning to the primary WAN line(%d)...\n", other_wan_unit);
3527			rule_setup = 1;
3528			handle_wan_line(other_wan_unit, rule_setup);
3529			switch_wan_line(other_wan_unit, 0);
3530		}
3531		// hot-standby: Try to prepare the backup line.
3532		else if(!strcmp(dualwan_mode, "fo") || !strcmp(dualwan_mode, "fb")){
3533			if(nvram_get_int("wans_standby") == 1 && link_wan[other_wan_unit] == 1 && get_wan_state(other_wan_unit) == WAN_STATE_INITIALIZING){
3534				csprintf("\n# wanduck(hot-standby): Try to prepare the backup line.\n");
3535				memset(cmd, 0, 32);
3536				sprintf(cmd, "restart_wan_if %d", other_wan_unit);
3537				notify_rc_and_wait(cmd);
3538			}
3539		}
3540#if defined(RTAC68U) || defined(RTAC87U) || defined(RTAC3200) || defined(RTAC88U) || defined(RTAC3100) || defined(RTAC5300)|| defined(RTAC5300R)
3541
3542		if (strcmp(dualwan_wans, "wan none")) {
3543			if(nvram_match("AllLED", "1")
3544#ifdef RTAC68U
3545				&& !strcmp(get_productid(), "RT-AC66U V2")
3546#endif
3547			){
3548				link_status = 0;
3549				for (u = WAN_UNIT_FIRST; !link_status && u < WAN_UNIT_MAX; ++u) {
3550					if(conn_state[u] == CONNED)
3551						link_status++;
3552				}
3553
3554				if(link_status) {
3555					if(wanred_led_status != 2 ){
3556						led_control(LED_WAN, LED_OFF);
3557						enable_wan_wled();
3558						wanred_led_status = 2;
3559					}
3560				}else{
3561					if(wanred_led_status != 1 ){
3562						led_control(LED_WAN, LED_ON);
3563						disable_wan_wled();
3564						wanred_led_status = 1;
3565					}
3566				}
3567			}
3568		}
3569#endif
3570#endif
3571#ifdef RTCONFIG_QTN
3572		if (nvram_get_int("ntp_ready") == 1 && nvram_get_int("qtn_ready") == 1){
3573			if (nvram_get_int("qtn_ntp_ready") == 0){
3574				time(&qtn_now);
3575				qtn_tm = localtime(&qtn_now);
3576				snprintf(time_string, sizeof(time_string), "%02d%02d%02d%02d%04d",
3577						qtn_tm->tm_mon+1, qtn_tm->tm_mday, qtn_tm->tm_hour, qtn_tm->tm_min, qtn_tm->tm_year+1900);
3578				eval("qcsapi_sockrpc", "run_script", "router_command.sh", "sync_time", time_string);
3579				nvram_set_int("qtn_ntp_ready", 1);
3580			}
3581		}
3582#endif
3583
3584		start_demand_ppp(current_wan_unit, 1);
3585
3586WANDUCK_SELECT:
3587		if((nready = select(maxfd+1, &rset, NULL, NULL, &tval)) <= 0)
3588			continue;
3589
3590
3591		if(FD_ISSET(dns_sock, &rset)){
3592			run_dns_serv(dns_sock);
3593			if(--nready <= 0)
3594				continue;
3595		}
3596		else if(FD_ISSET(http_sock, &rset)){
3597			if((cur_sockfd = accept(http_sock, (struct sockaddr *)&cliaddr, (socklen_t *)&clilen)) <= 0){
3598				perror("http accept");
3599				continue;
3600			}
3601
3602			for(fd_i = 0; fd_i < MAX_USER; ++fd_i){
3603				if(client[fd_i].sfd < 0){
3604					client[fd_i].sfd = cur_sockfd;
3605					client[fd_i].type = T_HTTP;
3606					break;
3607				}
3608			}
3609
3610			if(fd_i == MAX_USER){
3611				csprintf("# wanduck servs full\n");
3612				close(cur_sockfd);
3613				continue;
3614			}
3615
3616			FD_SET(cur_sockfd, &allset);
3617			if(cur_sockfd > maxfd)
3618				maxfd = cur_sockfd;
3619			if(fd_i > maxi)
3620				maxi = fd_i;
3621
3622			if(--nready <= 0)
3623				continue;	// no more readable descriptors
3624		}
3625
3626		// polling
3627		for(fd_i = 0; fd_i <= maxi; ++fd_i){
3628			if((sockfd = client[fd_i].sfd) < 0)
3629				continue;
3630
3631			if(FD_ISSET(sockfd, &rset)){
3632				int nread;
3633				ioctl(sockfd, FIONREAD, &nread);
3634				if(nread == 0){
3635					close_socket(sockfd, T_HTTP);
3636					continue;
3637				}
3638				if(fcntl(sockfd, F_SETFL, fcntl(sockfd, F_GETFL, 0)|O_NONBLOCK) < 0){
3639					_dprintf("wanduck set http req [%d] nonblock fail !\n", sockfd);
3640					continue;
3641				}
3642
3643				cur_sockfd = sockfd;
3644
3645				run_http_serv(sockfd);
3646
3647				if(--nready <= 0)
3648					break;
3649			}
3650		}
3651	}
3652
3653	csprintf("# wanduck exit error\n");
3654	exit(1);
3655}
3656