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 * Network services
18 *
19 * Copyright 2004, ASUSTeK Inc.
20 * All Rights Reserved.
21 *
22 * THIS SOFTWARE IS OFFERED "AS IS", AND BROADCOM GRANTS NO WARRANTIES OF ANY
23 * KIND, EXPRESS OR IMPLIED, BY STATUTE, COMMUNICATION OR OTHERWISE. BROADCOM
24 * SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS
25 * FOR A SPECIFIC PURPOSE OR NONINFRINGEMENT CONCERNING THIS SOFTWARE.
26 *
27 */
28
29#include <stdio.h>
30#include <stdlib.h>
31#include <errno.h>
32#include <syslog.h>
33#include <ctype.h>
34#include <string.h>
35#include <unistd.h>
36#include <sys/stat.h>
37#include <sys/ioctl.h>
38#include <sys/types.h>
39#include <sys/socket.h>
40#include <net/if.h>
41#include <netinet/in.h>
42#include <arpa/inet.h>
43#include <net/if_arp.h>
44#include <dirent.h>
45#include <linux/sockios.h>
46#include <bcmnvram.h>
47#include <shutils.h>
48#include <wlutils.h>
49#include <rc.h>
50#include <bcmutils.h>
51#include <bcmparams.h>
52#include <net/route.h>
53#include <stdarg.h>
54
55#include <linux/types.h>
56#include <linux/ethtool.h>
57
58#ifdef RTCONFIG_USB
59#include <disk_io_tools.h>
60#ifdef RTCONFIG_USB_MODEM
61#include <usb_info.h>
62#endif
63#endif
64
65#ifdef RTCONFIG_RALINK
66#include <ralink.h>
67#endif
68
69#ifdef RTCONFIG_QCA
70#include <qca.h>
71#endif
72
73
74#define	MAX_MAC_NUM	16
75static int mac_num;
76static char mac_clone[MAX_MAC_NUM][18];
77
78void convert_wan_nvram(char *prefix, int unit);
79
80#if defined(DSL_N55U) || defined(DSL_N55U_B)
81int classATargetTable[]={
82	1,
83	14,
84	27,
85	36,
86	39,
87	42,
88	49,
89	58,
90	59,
91	60,
92	61,
93	101,
94	103,
95	106,
96	110,
97	111,
98	112,
99	113,
100	114,
101	115,
102	116,
103	117,
104	118,
105	119,
106	120,
107	121,
108	122,
109	123,
110	124,
111	125,
112	126,
113	175,
114	180,
115	182,
116	183,
117	202,
118	203,
119	210,
120	211,
121	218,
122	219,
123	220,
124	221,
125	222,
126	223
127};
128
129int isTargetArea()
130{
131	int i;
132	char *ip = get_wanip();
133	int prefixA = inet_network(ip) >> 24;
134_dprintf("==>%s ip: %s, prefix: %d\n", __func__, ip, prefixA);
135	for(i=0; i<sizeof(classATargetTable); i++) {
136		if( prefixA == classATargetTable[i] )
137			return 1;
138	}
139	return 0;
140}
141#endif
142
143#if defined(RTCONFIG_WANRED_LED)
144/**
145 * Use arping to test whether gateway exist or not.
146 * @gw:
147 * @return:
148 * 	0:	success
149 *  otherwise:	fail
150 */
151int test_gateway(char *gw, char *wan_ifname)
152{
153	int ret;
154
155	if (!gw || *gw == '\0')
156		return -1;
157
158	/* If gateway is not available, below statment elapses 3 seconds. */
159	if (!wan_ifname || *wan_ifname == '\0')
160		ret = eval("arping", "-f", "-w", "10", gw);
161	else
162		ret = eval("arping", "-f", "-w", "10", "-I", wan_ifname, gw);
163
164	if (ret)
165		_dprintf("arping %s fail, return %d!!!\n", gw, ret);
166	else
167		_dprintf("arping %s OK\n", gw);
168
169	return ret;
170}
171#endif
172
173#define WAN0_ROUTE_TABLE 100
174#define WAN1_ROUTE_TABLE 200
175
176#define TEMP_ROUTE_FILE "/tmp/route_main"
177
178int copy_routes(int table){
179	char cmd[2048];
180	char *route_buf, *follow_info, line[1024];
181	int len;
182
183	if(table <= 0){
184		snprintf(cmd, 2048, "ip route flush table %d", WAN0_ROUTE_TABLE);
185		system(cmd);
186
187		snprintf(cmd, 2048, "ip route flush table %d", WAN1_ROUTE_TABLE);
188		system(cmd);
189
190		return 0;
191	}
192
193	snprintf(cmd, 2048, "ip route list table main > %s", TEMP_ROUTE_FILE);
194	system(cmd);
195
196	route_buf = read_whole_file(TEMP_ROUTE_FILE);
197	if(route_buf == NULL || strlen(route_buf) <= 0)
198		return -1;
199
200	follow_info = route_buf;
201	while(get_line_from_buffer(follow_info, line, 1024) != NULL) {
202		follow_info += strlen(line);
203
204		if(strncmp(line, "default", 7) == 0 || isspace(line[0]))
205			continue;
206
207		len = strlen(line);
208		line[len-2] = 0;
209
210		snprintf(cmd, 2048, "ip route add table %d %s", table, line);
211		system(cmd);
212	}
213
214	free(route_buf);
215
216	return 0;
217}
218
219/*
220 * the priority of routing rules:
221 * pref 100: user's routes.
222 * pref 200: from wan's ip, from wan's DNS.
223 * pref 300: ISP's routes.
224 * pref 400: to wan's gateway, to wan's DNS.
225 */
226int add_multi_routes(void)
227{
228	int unit;
229	char tmp[100], prefix[] = "wanXXXXXXXXXX_";
230	char wan_proto[32];
231	char wan_ip[32], wan_gate[32];
232	char cmd[2048];
233	char wan_multi_if[WAN_UNIT_MAX][32], wan_multi_gate[WAN_UNIT_MAX][32];
234#ifdef RTCONFIG_DUALWAN
235	int gate_num = 0, wan_weight, table;
236	char cmd2[2048], *ptr;
237	char wan_dns[1024];
238	char wan_multi_ip[WAN_UNIT_MAX][32];
239	char word[64], *next;
240	char *nv, *nvp, *b;
241#endif
242	int debug = nvram_get_int("routes_debug");
243
244	// clean the rules of routing table and re-build them then.
245	system("ip rule flush");
246	system("ip rule add from all lookup main pref 32766");
247	system("ip rule add from all lookup default pref 32767");
248
249	// clean multi route tables and re-build them then.
250	copy_routes(0);
251
252	memset(wan_multi_if, 0, sizeof(char)*WAN_UNIT_MAX*32);
253	memset(wan_multi_gate, 0, sizeof(char)*WAN_UNIT_MAX*32);
254#ifdef RTCONFIG_DUALWAN
255	memset(wan_multi_ip, 0, sizeof(char)*WAN_UNIT_MAX*32);
256#endif
257
258	for(unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit){ // Multipath
259		snprintf(prefix, sizeof(prefix), "wan%d_", unit);
260		strncpy(wan_multi_if[unit], get_wan_ifname(unit), 32);
261		strncpy(wan_ip, nvram_safe_get(strcat_r(prefix, "ipaddr", tmp)), 32);
262		strncpy(wan_gate, nvram_safe_get(strcat_r(prefix, "gateway", tmp)), 32);
263
264		// when wan_down().
265		if(!is_wan_connect(unit))
266			continue;
267
268		if(strlen(wan_gate) <= 0 || !strcmp(wan_gate, "0.0.0.0"))
269			continue;
270
271		if(strlen(wan_ip) <= 0 || !strcmp(wan_ip, "0.0.0.0"))
272			continue;
273
274#ifdef RTCONFIG_DUALWAN
275		++gate_num;
276
277		strcpy(wan_multi_ip[unit], wan_ip);
278#endif
279		strcpy(wan_multi_gate[unit], wan_gate);
280	}
281
282	for(unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit){ // Multipath
283		if(unit != wan_primary_ifunit()
284#ifdef RTCONFIG_DUALWAN
285				&& !nvram_match("wans_mode", "lb")
286#endif
287				)
288			continue;
289
290		snprintf(prefix, sizeof(prefix), "wan%d_", unit);
291		strncpy(wan_proto, nvram_safe_get(strcat_r(prefix, "proto", tmp)), 32);
292
293		// when wan_down().
294		if(!is_wan_connect(unit))
295			continue;
296
297#ifdef RTCONFIG_DUALWAN
298		if(strlen(wan_multi_gate[unit]) <= 0 || !strcmp(wan_multi_gate[unit], "0.0.0.0"))
299			continue;
300
301		if(nvram_match("wans_mode", "lb") && gate_num > 1){
302			if(strlen(wan_multi_ip[unit]) <= 0 || !strcmp(wan_multi_ip[unit], "0.0.0.0"))
303				continue;
304
305			if(unit == WAN_UNIT_SECOND)
306				table = WAN1_ROUTE_TABLE;
307			else
308				table = WAN0_ROUTE_TABLE;
309
310			// set the rules of wan[X]'s ip and gateway for multi routing tables.
311			snprintf(cmd2, 2048, "ip rule del pref 200 from %s table %d 2>/dev/null", wan_multi_ip[unit], table);
312if(debug) printf("test 1. cmd2=%s.\n", cmd2);
313			system(cmd2);
314
315			snprintf(cmd2, 2048, "ip rule add pref 200 from %s table %d", wan_multi_ip[unit], table);
316if(debug) printf("test 2. cmd2=%s.\n", cmd2);
317			system(cmd2);
318
319			snprintf(cmd2, 2048, "ip rule del pref 400 to %s table %d 2>/dev/null", wan_multi_gate[unit], table);
320if(debug) printf("test 3. cmd2=%s.\n", cmd2);
321			system(cmd2);
322
323			snprintf(cmd2, 2048, "ip rule add pref 400 to %s table %d", wan_multi_gate[unit], table);
324if(debug) printf("test 4. cmd2=%s.\n", cmd2);
325			system(cmd2);
326
327			// set the routes for multi routing tables.
328			copy_routes(table);
329
330			snprintf(cmd2, 2048, "ip route replace %s dev %s proto kernel table %d", wan_multi_gate[unit], wan_multi_if[unit], table);
331if(debug) printf("test 5. cmd2=%s.\n", cmd2);
332			system(cmd2);
333
334			snprintf(cmd2, 2048, "ip route replace default via %s dev %s table %d", wan_multi_gate[unit], wan_multi_if[unit], table);
335if(debug) printf("test 6. cmd2=%s.\n", cmd2);
336			system(cmd2);
337
338			if(!strcmp(wan_proto, "pptp") || !strcmp(wan_proto, "l2tp")){
339				snprintf(cmd2, 2048, "ip route del %s dev %s table %d 2>/dev/null", wan_multi_gate[unit], wan_multi_if[unit], table);
340if(debug) printf("test 7. cmd2=%s.\n", cmd2);
341				system(cmd2);
342			}
343
344			// set the static routing rules.
345			if(nvram_match("wans_routing_enable", "1")){
346				char *rfrom, *rto, *rtable_str;
347				int rtable;
348
349				nvp = nv = strdup(nvram_safe_get("wans_routing_rulelist"));
350				while(nv && (b = strsep(&nvp, "<")) != NULL){
351					if((vstrsep(b, ">", &rfrom, &rto, &rtable_str) != 3))
352						continue;
353
354					if(!strcmp(rfrom, "all") && !strcmp(rfrom, rto))
355						continue;
356
357					rtable = atoi(rtable_str);
358
359					if(rtable == WAN_UNIT_FIRST || rtable == WAN0_ROUTE_TABLE)
360						rtable = WAN0_ROUTE_TABLE;
361					else if(rtable == WAN_UNIT_SECOND || rtable == WAN1_ROUTE_TABLE)
362						rtable = WAN1_ROUTE_TABLE;
363					else // incorrect table.
364						continue;
365
366					if(rtable == table){
367						snprintf(cmd2, 2048, "ip rule del pref 100 from %s to %s table %d 2>/dev/null", rfrom, rto, rtable);
368if(debug) printf("test 8. cmd2=%s.\n", cmd2);
369						system(cmd2);
370
371						snprintf(cmd2, 2048, "ip rule add pref 100 from %s to %s table %d", rfrom, rto, rtable);
372if(debug) printf("test 9. cmd2=%s.\n", cmd2);
373						system(cmd2);
374					}
375	 			}
376				free(nv);
377			}
378		}
379		else
380		{
381			snprintf(cmd, 2048, "ip route replace %s dev %s proto kernel", wan_multi_gate[unit], wan_multi_if[unit]);
382if(debug) printf("test 10. cmd=%s.\n", cmd);
383			system(cmd);
384
385			// set the default gateway.
386			snprintf(cmd, 2048, "ip route replace default via %s dev %s", wan_multi_gate[unit], wan_multi_if[unit]);
387if(debug) printf("test 11. cmd=%s.\n", cmd);
388			system(cmd);
389
390			if(!strcmp(wan_proto, "pptp") || !strcmp(wan_proto, "l2tp")){
391				snprintf(cmd, 2048, "ip route del %s dev %s 2>/dev/null", wan_multi_gate[unit], wan_multi_if[unit]);
392if(debug) printf("test 12. cmd=%s.\n", cmd);
393				system(cmd);
394			}
395		}
396
397		if(!nvram_match("wans_mode", "lb") || gate_num <= 1)
398			break;
399#else
400		snprintf(cmd, 2048, "ip route replace %s dev %s proto kernel", wan_multi_gate[unit], wan_multi_if[unit]);
401if(debug) printf("test 10. cmd=%s.\n", cmd);
402		system(cmd);
403
404		// set the default gateway.
405		snprintf(cmd, 2048, "ip route replace default via %s dev %s", wan_multi_gate[unit], wan_multi_if[unit]);
406if(debug) printf("test 11. cmd=%s.\n", cmd);
407		system(cmd);
408
409		if(!strcmp(wan_proto, "pptp") || !strcmp(wan_proto, "l2tp")){
410			snprintf(cmd, 2048, "ip route del %s dev %s 2>/dev/null", wan_multi_gate[unit], wan_multi_if[unit]);
411if(debug) printf("test 12. cmd=%s.\n", cmd);
412			system(cmd);
413		}
414#endif // RTCONFIG_DUALWAN
415	}
416
417#ifdef RTCONFIG_DUALWAN
418	// set the multi default gateway.
419	if(nvram_match("wans_mode", "lb") && gate_num > 1){
420		memset(cmd, 0, 2048);
421		for(unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit){
422			snprintf(prefix, sizeof(prefix), "wan%d_", unit);
423
424			if(unit == WAN_UNIT_SECOND)
425				table = WAN1_ROUTE_TABLE;
426			else
427				table = WAN0_ROUTE_TABLE;
428
429			// move the gateway via VPN+DHCP from the main routing table to the correct one.
430			strcpy(wan_gate, nvram_safe_get(strcat_r(prefix, "xgateway", tmp)));
431			if(strlen(wan_gate) > 0 && strcmp(wan_gate, "0.0.0.0") && strcmp(wan_gate, wan_multi_gate[unit])){
432				snprintf(cmd2, 2048, "ip route del default via %s dev %s 2>/dev/null", wan_gate, get_wanx_ifname(unit));
433if(debug) printf("test 13. cmd2=%s.\n", cmd2);
434				system(cmd2);
435
436				snprintf(cmd2, 2048, "ip route replace default via %s dev %s table %d metric 1", wan_gate, get_wanx_ifname(unit), table);
437if(debug) printf("test 14. cmd2=%s.\n", cmd2);
438				system(cmd2);
439			}
440
441			// set the routing rules of DNS via VPN+DHCP.
442			strncpy(wan_dns, nvram_safe_get(strcat_r(prefix, "xdns", tmp)), 32);
443			if(strlen(wan_dns) > 0){
444				// set the rules for the DNS servers.
445				foreach(word, wan_dns, next) {
446					snprintf(cmd2, 2048, "ip rule del pref 200 from %s table %d 2>/dev/null", word, table);
447if(debug) printf("test 15. cmd2=%s.\n", cmd2);
448					system(cmd2);
449					snprintf(cmd2, 2048, "ip rule add pref 200 from %s table %d", word, table);
450if(debug) printf("test 16. cmd2=%s.\n", cmd2);
451					system(cmd2);
452
453					snprintf(cmd2, 2048, "ip rule del pref 400 to %s table %d 2>/dev/null", word, table);
454if(debug) printf("test 17. cmd2=%s.\n", cmd2);
455					system(cmd2);
456					snprintf(cmd2, 2048, "ip rule add pref 400 to %s table %d", word, table);
457if(debug) printf("test 18. cmd2=%s.\n", cmd2);
458					system(cmd2);
459				}
460			}
461
462			// set the routing rules of DNS.
463			strncpy(wan_dns, nvram_safe_get(strcat_r(prefix, "dns", tmp)), 32);
464			if(strlen(wan_dns) > 0){
465				// set the rules for the DNS servers.
466				foreach(word, wan_dns, next) {
467					snprintf(cmd2, 2048, "ip rule del pref 200 from %s table %d 2>/dev/null", word, table);
468if(debug) printf("test 19. cmd2=%s.\n", cmd2);
469					system(cmd2);
470					snprintf(cmd2, 2048, "ip rule add pref 200 from %s table %d", word, table);
471if(debug) printf("test 20. cmd2=%s.\n", cmd2);
472					system(cmd2);
473
474					snprintf(cmd2, 2048, "ip rule del pref 400 to %s table %d 2>/dev/null", word, table);
475if(debug) printf("test 21. cmd2=%s.\n", cmd2);
476					system(cmd2);
477					snprintf(cmd2, 2048, "ip rule add pref 400 to %s table %d", word, table);
478if(debug) printf("test 22. cmd2=%s.\n", cmd2);
479					system(cmd2);
480				}
481			}
482
483			// set the default gateways with weights in the main routing table.
484			nvp = nv = strdup(nvram_safe_get("wans_lb_ratio"));
485			int i = 0;
486			b = NULL;
487			while(nv && (b = strsep(&nvp, ":")) != NULL){
488				if(i == unit)
489					break;
490
491				++i;
492			}
493
494			if(!b)
495				continue;
496
497			wan_weight = atoi(b);
498			if(wan_weight > 0 && strlen(wan_multi_gate[unit]) > 0){
499				if(strlen(cmd) == 0)
500					strcpy(cmd, "ip route replace default");
501
502				ptr = cmd+strlen(cmd);
503				sprintf(ptr, " nexthop via %s dev %s weight %d", wan_multi_gate[unit], wan_multi_if[unit], wan_weight);
504			}
505
506			if(nv)
507				free(nv);
508		}
509
510		if(strlen(cmd) > 0){
511			for(unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit){
512				snprintf(cmd2, 2048, "ip route replace %s dev %s", wan_multi_gate[unit], wan_multi_if[unit]);
513if(debug) printf("test 23. cmd2=%s.\n", cmd2);
514				system(cmd2);
515			}
516
517if(debug) printf("test 24. cmd=%s.\n", cmd);
518			system(cmd);
519
520			for(unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit){
521				snprintf(prefix, sizeof(prefix), "wan%d_", unit);
522				strncpy(wan_proto, nvram_safe_get(strcat_r(prefix, "proto", tmp)), 32);
523				if(!strcmp(wan_proto, "pptp") || !strcmp(wan_proto, "l2tp")){
524					snprintf(cmd2, 2048, "ip route del %s dev %s 2>/dev/null", wan_multi_gate[unit], wan_multi_if[unit]);
525if(debug) printf("test 25. cmd2=%s.\n", cmd2);
526					system(cmd2);
527				}
528			}
529		}
530	}
531#endif
532
533if(debug) printf("test 26. route flush cache.\n");
534	system("ip route flush cache");
535
536	logmessage("wan", "finish adding multi routes");
537	return 0;
538}
539
540int
541add_routes(char *prefix, char *var, char *ifname)
542{
543	char word[80], *next;
544	char *ipaddr, *netmask, *gateway, *metric;
545	char tmp[100];
546
547	foreach(word, nvram_safe_get(strcat_r(prefix, var, tmp)), next) {
548
549		netmask = word;
550		ipaddr = strsep(&netmask, ":");
551		if (!ipaddr || !netmask)
552			continue;
553		gateway = netmask;
554		netmask = strsep(&gateway, ":");
555		if (!netmask || !gateway)
556			continue;
557		metric = gateway;
558		gateway = strsep(&metric, ":");
559		if (!gateway || !metric)
560			continue;
561
562		/* Incorrect, empty and 0.0.0.0
563		 * probably need to allow empty gateway to set on-link route */
564		if (inet_addr_(gateway) == INADDR_ANY)
565			gateway = nvram_safe_get(strcat_r(prefix, "xgateway", tmp));
566
567		route_add(ifname, atoi(metric) + 1, ipaddr, gateway, netmask);
568	}
569
570	return 0;
571}
572
573static void
574add_dhcp_routes(char *prefix, char *ifname, int metric)
575{
576	char *routes, *tmp;
577	char nvname[sizeof("wanXXXXXXXXXX_routesXXX")];
578	char *ipaddr, *gateway;
579	char netmask[] = "255.255.255.255";
580	struct in_addr mask;
581	int netsize;
582
583	if (nvram_get_int("dr_enable_x") == 0)
584		return;
585
586	/* classful static routes */
587	routes = strdup(nvram_safe_get(strcat_r(prefix, "routes", nvname)));
588	for (tmp = routes; tmp && *tmp; ) {
589		ipaddr  = strsep(&tmp, "/");
590		gateway = strsep(&tmp, " ");
591		if (gateway && inet_addr(ipaddr) != INADDR_ANY)
592			route_add(ifname, metric + 1, ipaddr, gateway, netmask);
593	}
594	free(routes);
595
596	/* ms claseless static routes */
597	routes = strdup(nvram_safe_get(strcat_r(prefix, "routes_ms", nvname)));
598	for (tmp = routes; tmp && *tmp; ) {
599		ipaddr  = strsep(&tmp, "/");
600		netsize = atoi(strsep(&tmp, " "));
601		gateway = strsep(&tmp, " ");
602		if (gateway && netsize > 0 && netsize <= 32 && inet_addr(ipaddr) != INADDR_ANY) {
603			mask.s_addr = htonl(0xffffffff << (32 - netsize));
604			strcpy(netmask, inet_ntoa(mask));
605			route_add(ifname, metric + 1, ipaddr, gateway, netmask);
606		}
607	}
608	free(routes);
609
610	/* rfc3442 classless static routes */
611	routes = strdup(nvram_safe_get(strcat_r(prefix, "routes_rfc", nvname)));
612	for (tmp = routes; tmp && *tmp; ) {
613		ipaddr  = strsep(&tmp, "/");
614		netsize = atoi(strsep(&tmp, " "));
615		gateway = strsep(&tmp, " ");
616		if (gateway && netsize > 0 && netsize <= 32 && inet_addr(ipaddr) != INADDR_ANY) {
617			mask.s_addr = htonl(0xffffffff << (32 - netsize));
618			strcpy(netmask, inet_ntoa(mask));
619			route_add(ifname, metric + 1, ipaddr, gateway, netmask);
620		}
621	}
622	free(routes);
623}
624
625int
626del_routes(char *prefix, char *var, char *ifname)
627{
628	char word[80], *next;
629	char *ipaddr, *netmask, *gateway, *metric;
630	char tmp[100];
631
632	foreach(word, nvram_safe_get(strcat_r(prefix, var, tmp)), next) {
633		_dprintf("%s: %s\n", __FUNCTION__, word);
634
635		netmask = word;
636		ipaddr = strsep(&netmask, ":");
637		if (!ipaddr || !netmask)
638			continue;
639		gateway = netmask;
640		netmask = strsep(&gateway, ":");
641		if (!netmask || !gateway)
642			continue;
643
644		metric = gateway;
645		gateway = strsep(&metric, ":");
646		if (!gateway || !metric)
647			continue;
648
649		if (inet_addr_(gateway) == INADDR_ANY) 	// oleg patch
650			gateway = nvram_safe_get("wan0_xgateway");
651
652		route_del(ifname, atoi(metric) + 1, ipaddr, gateway, netmask);
653	}
654
655	return 0;
656}
657
658#if 0
659#ifdef RTCONFIG_IPV6
660void
661stop_ecmh(void)
662{
663	if (pids("ecmh"))
664	{
665		killall_tk("ecmh");
666		sleep(1);
667	}
668}
669
670void
671start_ecmh(const char *wan_ifname)
672{
673	int service = get_ipv6_service();
674
675	stop_ecmh();
676
677	if (!wan_ifname || (strlen(wan_ifname) <= 0))
678		return;
679
680	if (!nvram_match("mr_enable_x", "1"))
681		return;
682
683	switch (service) {
684	case IPV6_NATIVE_DHCP:
685	case IPV6_MANUAL:
686		eval("/bin/ecmh", "-u", nvram_safe_get("http_username"), "-i", (char*)wan_ifname);
687		break;
688	}
689}
690#endif
691#endif
692
693void
694stop_igmpproxy()
695{
696	if (pids("udpxy"))
697		killall_tk("udpxy");
698	if (pids("igmpproxy"))
699		killall_tk("igmpproxy");
700}
701
702void	// oleg patch , add
703start_igmpproxy(char *wan_ifname)
704{
705	FILE *fp;
706	static char *igmpproxy_conf = "/tmp/igmpproxy.conf";
707	char *altnet = nvram_safe_get("mr_altnet_x");
708
709#ifdef RTCONFIG_DSL
710#ifdef RTCONFIG_DUALWAN
711	if ( nvram_match("wan0_ifname", wan_ifname)
712		&& get_dualwan_primary() == WANS_DUALWAN_IF_DSL) {
713		if (nvram_get_int("dslx_config_num") > 1)
714			wan_ifname = "br1";
715	}
716#else
717	if (nvram_get_int("dslx_config_num") > 1)
718		wan_ifname = "br1";
719#endif
720#endif
721
722#ifdef RTCONFIG_MULTICAST_IPTV
723	if (nvram_get_int("switch_stb_x") > 6 &&
724	    nvram_match("switch_wantag", "movistar") &&
725	    !nvram_match("iptv_ifname", wan_ifname))
726		return;
727#endif
728
729	stop_igmpproxy();
730
731	if (nvram_get_int("udpxy_enable_x")) {
732		_dprintf("start udpxy [%s]\n", wan_ifname);
733		eval("/usr/sbin/udpxy",
734			"-m", wan_ifname,
735			"-p", nvram_safe_get("udpxy_enable_x"),
736			"-B", "65536",
737			"-c", nvram_safe_get("udpxy_clients"),
738			"-a", nvram_get("lan_ifname") ? : "br0");
739	}
740
741	if (!nvram_match("mr_enable_x", "1"))
742		return;
743
744	_dprintf("start igmpproxy [%s]\n", wan_ifname);
745
746	if ((fp = fopen(igmpproxy_conf, "w")) == NULL) {
747		perror(igmpproxy_conf);
748		return;
749	}
750
751	fprintf(fp, "# automagically generated from web settings\n");
752#ifdef RTCONFIG_MULTICAST_IPTV
753	if ( !(nvram_get_int("switch_stb_x") > 6 &&
754		nvram_match("switch_wantag", "movistar")) )
755		fprintf(fp, "quickleave\n\n");
756#else
757		fprintf(fp, "quickleave\n\n");
758#endif
759		fprintf(fp, "phyint %s upstream  ratelimit 0  threshold 1\n"
760		"\taltnet %s\n\n"
761		"phyint %s downstream  ratelimit 0  threshold 1\n\n",
762		wan_ifname,
763		*altnet ? altnet : "0.0.0.0/0",
764		nvram_get("lan_ifname") ? : "br0");
765
766	fclose(fp);
767
768	eval("/usr/sbin/igmpproxy", igmpproxy_conf);
769}
770
771int
772wan_prefix(char *ifname, char *prefix)
773{
774	int unit;
775
776	if ((unit = wan_ifunit(ifname)) < 0 &&
777	    (unit = wanx_ifunit(ifname)) < 0)
778		return -1;
779
780	sprintf(prefix, "wan%d_", unit);
781
782	return unit;
783}
784
785static int
786add_wan_routes(char *wan_ifname)
787{
788	char prefix[] = "wanXXXXXXXXXX_";
789
790	/* Figure out nvram variable name prefix for this i/f */
791	if (wan_prefix(wan_ifname, prefix) < 0)
792		return -1;
793
794	return add_routes(prefix, "route", wan_ifname);
795}
796
797static int
798del_wan_routes(char *wan_ifname)
799{
800	char prefix[] = "wanXXXXXXXXXX_";
801
802	/* Figure out nvram variable name prefix for this i/f */
803	if (wan_prefix(wan_ifname, prefix) < 0)
804#if 0
805		return -1;
806#else
807		sprintf(prefix, "wan%d_", WAN_UNIT_FIRST);
808#endif
809
810	return del_routes(prefix, "route", wan_ifname);
811}
812
813#ifdef QOS
814int enable_qos()
815{
816#if defined (W7_LOGO) || defined (WIFI_LOGO)
817	return 0;
818#endif
819	int qos_userspec_app_en = 0;
820	int rulenum = nvram_get_int("qos_rulenum_x"), idx_class = 0;
821
822	/* Add class for User specify, 10:20(high), 10:40(middle), 10:60(low)*/
823	if (rulenum) {
824		for (idx_class=0; idx_class < rulenum; idx_class++)
825		{
826			if (atoi(Ch_conv("qos_prio_x", idx_class)) == 1)
827			{
828				qos_userspec_app_en = 1;
829				break;
830			}
831			else if (atoi(Ch_conv("qos_prio_x", idx_class)) == 6)
832			{
833				qos_userspec_app_en = 1;
834				break;
835			}
836		}
837	}
838
839	if (	(nvram_match("qos_tos_prio", "1") ||
840		 nvram_match("qos_pshack_prio", "1") ||
841		 nvram_match("qos_service_enable", "1") ||
842		 nvram_match("qos_shortpkt_prio", "1")	) ||
843		(!nvram_match("qos_manual_ubw","0") && *nvram_safe_get("qos_manual_ubw")) ||
844		(rulenum && qos_userspec_app_en)
845	)
846	{
847		fprintf(stderr, "found QoS rulues\n");
848		return 1;
849	}
850	else
851	{
852		fprintf(stderr, "no QoS rulues\n");
853		return 0;
854	}
855}
856#endif
857
858/*
859 * (1) wan[x]_ipaddr_x/wan[x]_netmask_x/wan[x]_gateway_x/...:
860 *    static ip or ip get from dhcp
861 *
862 * (2) wan[x]_xipaddr/wan[x]_xnetmaskwan[x]_xgateway/...:
863 *    ip get from dhcp when proto = l2tp/pptp/pppoe
864 *
865 * (3) wan[x]_ipaddr/wan[x]_netmask/wan[x]_gateway/...:
866 *    always keeps the latest updated ip/netmask/gateway in system
867 *      static: it is the same as (1)
868 *      dhcp:
869 *      	- before getting ip from dhcp server, it is 0.0.0.0
870 *      	- after getting ip from dhcp server, it is updated
871 *      l2tp/pptp/pppoe with static ip:
872 *      	- before getting ip from vpn server, it is the same as (1)
873 *      	- after getting ip from vpn server, it is the one from vpn server
874 *      l2tp/pptp/pppoe with dhcp ip:
875 *      	- before getting ip from dhcp server, it is 0.0.0.0
876 *      	- before getting ip from vpn server, it is the one from vpn server
877 */
878
879void update_wan_state(char *prefix, int state, int reason)
880{
881	char tmp[100], tmp1[100], *ptr;
882
883	_dprintf("%s(%s, %d, %d)\n", __FUNCTION__, prefix, state, reason);
884
885	nvram_set_int(strcat_r(prefix, "state_t", tmp), state);
886	if(state == WAN_STATE_CONNECTED)
887		nvram_set_int(strcat_r(prefix, "sbstate_t", tmp), WAN_STOPPED_REASON_NONE);
888	else
889		nvram_set_int(strcat_r(prefix, "sbstate_t", tmp), reason);
890
891	// 20110610, reset auxstate each time state is changed
892	nvram_set_int(strcat_r(prefix, "auxstate_t", tmp), 0);
893
894	if (state == WAN_STATE_INITIALIZING)
895	{
896		nvram_set(strcat_r(prefix, "proto_t", tmp), nvram_safe_get(strcat_r(prefix, "proto", tmp1)));
897
898		/* reset wanX_* variables */
899		if (!nvram_get_int(strcat_r(prefix, "dhcpenable_x", tmp))) {
900			nvram_set(strcat_r(prefix, "ipaddr", tmp), nvram_safe_get(strcat_r(prefix, "ipaddr_x", tmp1)));
901			nvram_set(strcat_r(prefix, "netmask", tmp), nvram_safe_get(strcat_r(prefix, "netmask_x", tmp1)));
902			nvram_set(strcat_r(prefix, "gateway", tmp), nvram_safe_get(strcat_r(prefix, "gateway_x", tmp1)));
903		}
904		else {
905			nvram_set(strcat_r(prefix, "ipaddr", tmp), "0.0.0.0");
906			nvram_set(strcat_r(prefix, "netmask", tmp), "0.0.0.0");
907			nvram_set(strcat_r(prefix, "gateway", tmp), "0.0.0.0");
908		}
909		nvram_unset(strcat_r(prefix, "domain", tmp));
910		nvram_unset(strcat_r(prefix, "lease", tmp));
911		nvram_unset(strcat_r(prefix, "expires", tmp));
912		nvram_unset(strcat_r(prefix, "routes", tmp));
913		nvram_unset(strcat_r(prefix, "routes_ms", tmp));
914		nvram_unset(strcat_r(prefix, "routes_rfc", tmp));
915
916		/* reset wanX_x* VPN variables */
917		nvram_set(strcat_r(prefix, "xipaddr", tmp), nvram_safe_get(strcat_r(prefix, "ipaddr", tmp1)));
918		nvram_set(strcat_r(prefix, "xnetmask", tmp), nvram_safe_get(strcat_r(prefix, "netmask", tmp1)));
919		nvram_set(strcat_r(prefix, "xgateway", tmp), nvram_safe_get(strcat_r(prefix, "gateway", tmp1)));
920		nvram_unset(strcat_r(prefix, "xdomain", tmp));
921		nvram_unset(strcat_r(prefix, "xlease", tmp));
922		nvram_unset(strcat_r(prefix, "xexpires", tmp));
923		nvram_unset(strcat_r(prefix, "xroutes", tmp));
924		nvram_unset(strcat_r(prefix, "xroutes_ms", tmp));
925		nvram_unset(strcat_r(prefix, "xroutes_rfc", tmp));
926
927		/* reset wanX* dns variables */
928		strcpy(tmp1, "");
929		ptr = nvram_safe_get(strcat_r(prefix, "dns1_x", tmp));
930		if (*ptr && inet_addr_(ptr) != INADDR_ANY)
931			sprintf(tmp1, "%s", ptr);
932		ptr = nvram_safe_get(strcat_r(prefix, "dns2_x", tmp));
933		if (*ptr && inet_addr_(ptr) != INADDR_ANY)
934			sprintf(tmp1 + strlen(tmp1), "%s%s", *tmp1 ? " " : "", ptr);
935
936		/* reset wanX_dns */
937		ptr = !nvram_get_int(strcat_r(prefix, "dnsenable_x", tmp)) ? tmp1 : "";
938		nvram_set(strcat_r(prefix, "dns", tmp), ptr);
939
940		/* reset wanX_xdns VPN */
941		ptr = !nvram_get_int(strcat_r(prefix, "dnsenable_x", tmp)) ? tmp1 : "";
942		nvram_set(strcat_r(prefix, "xdns", tmp), ptr);
943
944#ifdef RTCONFIG_IPV6
945		nvram_set(strcat_r(prefix, "6rd_ip4size", tmp), "");
946		nvram_set(strcat_r(prefix, "6rd_router", tmp), "");
947		nvram_set(strcat_r(prefix, "6rd_prefix", tmp), "");
948		nvram_set(strcat_r(prefix, "6rd_prefixlen", tmp), "");
949#endif
950#ifdef RTCONFIG_TR069
951//		nvram_unset(strcat_r(prefix, "tr_acs_url", tmp));
952//		nvram_unset(strcat_r(prefix, "tr_pvgcode", tmp));
953#endif
954	}
955#if 0
956	else if (state == WAN_STATE_STOPPED) {
957		// Save Stopped Reason
958		// keep ip info if it is stopped from connected
959		nvram_set_int(strcat_r(prefix, "sbstate_t", tmp), reason);
960	}
961#endif
962	else if(state == WAN_STATE_STOPPING){
963		unlink("/tmp/wanstatus.log");
964	}
965
966#if defined(RTCONFIG_WANRED_LED)
967	switch (state) {
968	case WAN_STATE_INITIALIZING:
969	case WAN_STATE_STOPPED:
970	case WAN_STATE_CONNECTING:
971	case WAN_STATE_STOPPING:
972	case WAN_STATE_CONNECTED:
973		/* update WAN LED(s) as soon as possible. */
974		if (strncmp(prefix, "wan", 3) == 0) {
975			int unit = atoi(prefix + 3);
976			update_wan_leds(unit);
977		}
978	}
979#endif
980}
981
982#ifdef RTCONFIG_IPV6
983// for one ipv6 in current stage
984void update_wan6_state(char *prefix, int state, int reason)
985{
986	char tmp[100];
987
988	_dprintf("%s(%s, %d, %d)\n", __FUNCTION__, prefix, state, reason);
989
990	nvram_set_int(strcat_r(prefix, "state_t", tmp), state);
991	nvram_set_int(strcat_r(prefix, "sbstate_t", tmp), 0);
992
993	if (state == WAN_STATE_INITIALIZING)
994	{
995	}
996	else if (state == WAN_STATE_STOPPED) {
997		// Save Stopped Reason
998		// keep ip info if it is stopped from connected
999		nvram_set_int(strcat_r(prefix, "sbstate_t", tmp), reason);
1000	}
1001}
1002#endif
1003
1004// IPOA test case
1005// 111.235.232.137 (gateway)
1006// 111.235.232.138 (ip)
1007// 255.255.255.252 (netmask)
1008
1009// cat /proc/net/arp
1010// arp -na
1011
1012#ifdef RTCONFIG_DSL
1013static int start_ipoa()
1014{
1015	char tc_mac[32];
1016	char ip_addr[32];
1017	char ip_mask[32];
1018	char ip_gateway[32];
1019	int try_cnt;
1020	FILE* fp_dsl_mac;
1021	FILE* fp_log;
1022
1023	int NeighborIpNum;
1024	int i;
1025	int NeiBaseIpNum;
1026	int LastIpNum;
1027	int NetMaskLastIpNum;
1028	char NeighborIpPrefix[32];
1029	int ip_addr_dot_cnt;
1030	char CmdBuf[128];
1031
1032	// mac address is adsl mac
1033	for (try_cnt = 0; try_cnt < 10; try_cnt++)
1034	{
1035		fp_dsl_mac = fopen("/tmp/adsl/tc_mac.txt","r");
1036		if (fp_dsl_mac != NULL)
1037		{
1038			fgets(tc_mac,sizeof(tc_mac),fp_dsl_mac);
1039			fclose(fp_dsl_mac);
1040			break;
1041		}
1042		usleep(1000*1000);
1043	}
1044
1045#ifdef RTCONFIG_DUALWAN
1046	if (get_dualwan_secondary()==WANS_DUALWAN_IF_DSL)
1047	{
1048		strcpy(ip_gateway, nvram_safe_get("wan1_gateway"));
1049		strcpy(ip_addr, nvram_safe_get("wan1_ipaddr"));
1050		strcpy(ip_mask, nvram_safe_get("wan1_netmask"));
1051	}
1052	else
1053	{
1054		strcpy(ip_gateway, nvram_safe_get("wan0_gateway"));
1055		strcpy(ip_addr, nvram_safe_get("wan0_ipaddr"));
1056		strcpy(ip_mask, nvram_safe_get("wan0_netmask"));
1057	}
1058#else
1059	strcpy(ip_gateway, nvram_safe_get("wan0_gateway"));
1060	strcpy(ip_addr, nvram_safe_get("wan0_ipaddr"));
1061	strcpy(ip_mask, nvram_safe_get("wan0_netmask"));
1062#endif
1063
1064	// we only support maximum 256 neighbor host
1065	if (strncmp("255.255.255",ip_mask,11) != 0)
1066	{
1067		fp_log = fopen("/tmp/adsl/ipoa_too_many_neighbors.txt","w");
1068		fputs("ErrorMsg",fp_log);
1069		fclose(fp_log);
1070		return -1;
1071	}
1072
1073//
1074// do not send arp to neighborhood and gateway
1075//
1076
1077	ip_addr_dot_cnt = 0;
1078	for (i=0; i<sizeof(NeighborIpPrefix); i++)
1079	{
1080		if (ip_addr[i] == '.')
1081		{
1082			ip_addr_dot_cnt++;
1083			if (ip_addr_dot_cnt >= 3) break;
1084		}
1085		NeighborIpPrefix[i]=ip_addr[i];
1086	}
1087	NeighborIpPrefix[i] = 0;
1088
1089	LastIpNum = atoi(&ip_addr[i+1]);
1090	NetMaskLastIpNum = atoi(&ip_mask[12]);
1091	NeighborIpNum = ((~NetMaskLastIpNum) + 1)&0xff;
1092	NeiBaseIpNum = LastIpNum & NetMaskLastIpNum;
1093
1094	//
1095	// add gateway host
1096	//
1097#ifdef RTCONFIG_DSL_TCLINUX
1098	eval("arp","-i",nvram_safe_get("wan0_ifname"),"-a",ip_gateway,"-s",tc_mac);
1099#else
1100	eval("arp","-i","br0","-a",ip_gateway,"-s",tc_mac);
1101#endif
1102
1103	// add neighbor hosts
1104	for (i=0; i<NeighborIpNum; i++)
1105	{
1106		sprintf(CmdBuf,"%s.%d",NeighborIpPrefix,i+NeiBaseIpNum);
1107#ifdef RTCONFIG_DSL_TCLINUX
1108		eval("arp","-i",nvram_safe_get("wan0_ifname"),"-a",CmdBuf,"-s",tc_mac);
1109#else
1110		eval("arp","-i","br0","-a",CmdBuf,"-s",tc_mac);
1111#endif
1112	}
1113
1114	return 0;
1115}
1116
1117static int stop_ipoa()
1118{
1119	char ip_addr[32];
1120	char ip_mask[32];
1121	char ip_gateway[32];
1122	FILE* fp_log;
1123
1124	int NeighborIpNum;
1125	int i;
1126	int NeiBaseIpNum;
1127	int LastIpNum;
1128	int NetMaskLastIpNum;
1129	char NeighborIpPrefix[32];
1130	int ip_addr_dot_cnt;
1131	char CmdBuf[128];
1132
1133#ifdef RTCONFIG_DUALWAN
1134		if (get_dualwan_secondary()==WANS_DUALWAN_IF_DSL)
1135		{
1136			strcpy(ip_gateway, nvram_safe_get("wan1_gateway"));
1137			strcpy(ip_addr, nvram_safe_get("wan1_ipaddr"));
1138			strcpy(ip_mask, nvram_safe_get("wan1_netmask"));
1139		}
1140		else
1141		{
1142			strcpy(ip_gateway, nvram_safe_get("wan0_gateway"));
1143			strcpy(ip_addr, nvram_safe_get("wan0_ipaddr"));
1144			strcpy(ip_mask, nvram_safe_get("wan0_netmask"));
1145		}
1146#else
1147		strcpy(ip_gateway, nvram_safe_get("wan0_gateway"));
1148		strcpy(ip_addr, nvram_safe_get("wan0_ipaddr"));
1149		strcpy(ip_mask, nvram_safe_get("wan0_netmask"));
1150#endif
1151
1152	// we only support maximum 256 neighbor host
1153	if (strncmp("255.255.255",ip_mask,11) != 0)
1154	{
1155		fp_log = fopen("/tmp/adsl/ipoa_too_many_neighbors.txt","w");
1156		fputs("ErrorMsg",fp_log);
1157		fclose(fp_log);
1158		return -1;
1159	}
1160
1161	//
1162	// do not send arp to neighborhood and gateway
1163	//
1164
1165	ip_addr_dot_cnt = 0;
1166	for (i=0; i<sizeof(NeighborIpPrefix); i++)
1167	{
1168		if (ip_addr[i] == '.')
1169		{
1170			ip_addr_dot_cnt++;
1171			if (ip_addr_dot_cnt >= 3) break;
1172		}
1173		NeighborIpPrefix[i]=ip_addr[i];
1174	}
1175	NeighborIpPrefix[i] = 0;
1176
1177	LastIpNum = atoi(&ip_addr[i+1]);
1178	NetMaskLastIpNum = atoi(&ip_mask[12]);
1179	NeighborIpNum = ((~NetMaskLastIpNum) + 1)&0xff;
1180	NeiBaseIpNum = LastIpNum & NetMaskLastIpNum;
1181
1182	//
1183	// delete gateway host
1184	//
1185	eval("arp","-d",ip_gateway);
1186
1187	// delete neighbor hosts
1188	for (i=0; i<NeighborIpNum; i++)
1189	{
1190		sprintf(CmdBuf,"%s.%d",NeighborIpPrefix,i+NeiBaseIpNum);
1191		eval("arp","-d",CmdBuf);
1192	}
1193
1194	return 0;
1195}
1196#endif
1197
1198#ifdef RTCONFIG_DUALWAN
1199void check_wan_nvram(void)
1200{
1201	if(nvram_match("wan1_proto", "")) nvram_set("wan1_proto", "dhcp");
1202}
1203#endif
1204
1205#ifdef DSL_AC68U	//Andy Chiu, 2015/09/15
1206#include "interface.h"
1207extern int cur_ewan_vid;
1208
1209int check_wan_if(int unit)
1210{
1211	//check wan mode.
1212	dbG("unit=%d\n", unit);
1213	if(get_wans_dualwan()&WANSCAP_LAN)
1214	{
1215		//check vid
1216		int new_vid;
1217
1218		if(nvram_match("ewan_dot1q", "1"))
1219			new_vid = nvram_get_int("ewan_vid");
1220		else
1221			new_vid = 4;
1222		dbG("cur_vid=%d, new_vid=%d\n", cur_ewan_vid, new_vid);
1223
1224		if(new_vid != cur_ewan_vid)
1225		{
1226			//update port info
1227			char buf[32], wan[32];
1228			const int ports[] = { 0, 1, 2, 3, 4, 5 };
1229			int wan1cfg = nvram_get_int("wans_lanport") + WAN1PORT1 - 1;
1230			snprintf(buf, sizeof(buf), "vlan%dports", cur_ewan_vid);
1231			nvram_unset(buf);
1232			switch_gen_config(wan, ports, wan1cfg, 1, "t");
1233			snprintf(buf, sizeof(buf), "vlan%dports", new_vid);
1234			nvram_set(buf, wan);
1235
1236			//update hwname info
1237			snprintf(buf, sizeof(buf), "vlan%dhwname", cur_ewan_vid);
1238			nvram_unset(buf);
1239			snprintf(buf, sizeof(buf), "vlan%dhwname", new_vid);
1240			nvram_set(buf, "et0");
1241
1242			//generate vlan interfaces
1243			char cur_vif[16], new_vif[16];
1244			sprintf(cur_vif, "vlan%d", cur_ewan_vid);
1245			sprintf(new_vif, "vlan%d", new_vid);
1246
1247			dbG("cur_vif=%s, new_vif=%s\n", cur_vif, new_vif);
1248
1249			char word[256], *next, tmp[256];
1250			//replace old vlan interface by new vlan interface
1251			memset(tmp, 0, 256);
1252			foreach(word, nvram_safe_get("wandevs"), next)
1253			{
1254				sprintf(tmp, "%s %s", tmp, (!strcmp(word, cur_vif))? new_vif: word);
1255			}
1256			dbG("wandevs=%s\n", tmp);
1257			nvram_set("wandevs", tmp);
1258
1259			//replace wan_phy
1260			memset(tmp, 0, 256);
1261			foreach(word, nvram_safe_get("wan_ifnames"), next)
1262			{
1263				sprintf(tmp, "%s %s", tmp, (!strcmp(word, cur_vif))? new_vif: word);
1264			}
1265			dbG("wan_ifnames=%s\n", tmp);
1266			nvram_set("wan_ifnames", tmp);
1267
1268			//check all wan unit.
1269			int unit;
1270			for(unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit)
1271			{
1272				snprintf(buf, sizeof(buf), "wan%d_ifname", unit);
1273				if(nvram_match(buf, cur_vif))
1274				{
1275					dbG("%s=%s\n", buf, new_vif);
1276					nvram_set(buf, new_vif);
1277				}
1278
1279				sprintf(buf, "wan%d_gw_ifname", unit);
1280				if(nvram_match(buf, cur_vif))
1281				{
1282					dbG("%s=%s\n", buf, new_vif);
1283					nvram_set(buf, new_vif);
1284				}
1285			}
1286
1287			//remove old vlan
1288			eval("ifconfig", cur_vif, "down");
1289			eval("vconfig", "rem", cur_vif);
1290
1291			//set new vlan
1292			eval("vconfig", "set_name_type", "VLAN_PLUS_VID_NO_PAD");
1293			snprintf(buf, sizeof(buf), "%d", new_vid);
1294			eval("vconfig", "add", "eth0", buf);
1295			eval("ifconfig", new_vif, "up");
1296			cur_ewan_vid = new_vid;
1297		}
1298		dbG("Set switch\n");
1299		config_switch_dsl_set_lan();
1300	}
1301	return 0;
1302}
1303#endif
1304
1305void
1306start_wan_if(int unit)
1307{
1308#ifdef RTCONFIG_DUALWAN
1309	int wan_type;
1310#endif
1311	char *wan_ifname;
1312	char *wan_proto;
1313	char tmp[100], prefix[] = "wanXXXXXXXXXX_";
1314	char eabuf[32];
1315	int s;
1316	struct ifreq ifr;
1317	pid_t pid;
1318	char usb_node[32], port_path[8];
1319	char nvram_name[32];
1320	int i = 0;
1321#ifdef RTCONFIG_USB_MODEM
1322	char modem_type[32];
1323#ifdef RTCONFIG_USB_BECEEM
1324	unsigned int uvid, upid;
1325#endif
1326#ifdef SET_USB_MODEM_MTU_ETH
1327	int modem_mtu;
1328#endif
1329#endif
1330
1331	TRACE_PT("unit=%d.\n", unit);
1332	snprintf(prefix, sizeof(prefix), "wan%d_", unit);
1333
1334	/* variable should exist? */
1335	if (nvram_match(strcat_r(prefix, "enable", tmp), "0")) {
1336		update_wan_state(prefix, WAN_STATE_DISABLED, 0);
1337		return;
1338	}
1339#ifdef RTCONFIG_USB_MODEM
1340	else if(nvram_get_int("usb_modem_act_scanning") != 0){
1341_dprintf("start_wan_if: USB modem is scanning...\n");
1342		update_wan_state(prefix, WAN_STATE_STOPPED, WAN_STOPPED_REASON_USBSCAN);
1343		return;
1344	}
1345#endif
1346#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
1347	// had detected the DATA limit before.
1348	else if(nvram_get_int(strcat_r(prefix, "sbstate_t", tmp)) == WAN_STOPPED_REASON_DATALIMIT){
1349		TRACE_PT("start_wan_if: Data limit was detected and skip the start_wan_if().\n");
1350		return;
1351	}
1352#endif
1353
1354	update_wan_state(prefix, WAN_STATE_INITIALIZING, 0);
1355
1356#ifdef RTCONFIG_DUALWAN
1357	wan_type = get_dualwan_by_unit(unit);
1358#endif
1359
1360#ifdef RTCONFIG_DUALWAN
1361	if (nvram_get_int("sw_mode") == SW_MODE_ROUTER) {
1362		if (get_wans_dualwan()&WANSCAP_WAN && get_wans_dualwan()&WANSCAP_LAN)
1363			check_wan_nvram();
1364	}
1365#endif
1366
1367#ifdef RTCONFIG_USB_MODEM
1368	if (dualwan_unit__usbif(unit)) {
1369		FILE *fp;
1370
1371		if(is_usb_modem_ready() != 1){ // find_modem_type.sh would be run by is_usb_modem_ready().
1372			TRACE_PT("No USB Modem!\n");
1373			return;
1374		}
1375
1376		TRACE_PT("3g begin.\n");
1377		if(nvram_match("g3err_pin", "1")){
1378			TRACE_PT("3g end: PIN error previously!\n");
1379			update_wan_state(prefix, WAN_STATE_STOPPED, WAN_STOPPED_REASON_PINCODE_ERR);
1380			return;
1381		}
1382
1383		update_wan_state(prefix, WAN_STATE_CONNECTING, 0);
1384
1385		snprintf(modem_type, 32, "%s", nvram_safe_get("usb_modem_act_type"));
1386
1387		if(!strcmp(modem_type, "tty") || !strcmp(modem_type, "qmi") || !strcmp(modem_type, "mbim") || !strcmp(modem_type, "gobi")){
1388			if(!strcmp(nvram_safe_get("usb_modem_act_int"), "")){
1389				if(!strcmp(modem_type, "qmi")){	// e.q. Huawei E398.
1390					TRACE_PT("Sleep 3 seconds to wait modem nodes.\n");
1391					sleep(3);
1392				}
1393				else{
1394					TRACE_PT("Sleep 2 seconds to wait modem nodes.\n");
1395					sleep(2);
1396				}
1397			}
1398
1399			// find the modem node at every start_wan_if() to avoid the incorrct one sometimes.
1400			eval("find_modem_node.sh");
1401		}
1402
1403		if(nvram_get_int("usb_modem_act_reset") == 1){
1404			// need to execute find_modem_xxx.sh again.
1405			TRACE_PT("3g end: Reseting the modem...\n");
1406			return;
1407		}
1408
1409		/* Stop pppd */
1410		stop_pppd(unit);
1411
1412		/* Stop dhcp client */
1413		stop_udhcpc(unit);
1414
1415#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
1416		unsigned long long rx, tx;
1417		unsigned long long total, limit;
1418
1419		rx = strtoull(nvram_safe_get("modem_bytes_rx"), NULL, 10);
1420		tx = strtoull(nvram_safe_get("modem_bytes_tx"), NULL, 10);
1421		limit = strtoull(nvram_safe_get("modem_bytes_data_limit"), NULL, 10);
1422
1423		total = rx+tx;
1424
1425		if(limit > 0 && total >= limit){
1426			TRACE_PT("3g end: Data limit was set: limit %llu, now %llu.\n", limit, total);
1427			update_wan_state(prefix, WAN_STATE_STOPPED, WAN_STOPPED_REASON_DATALIMIT);
1428			return;
1429		}
1430#endif
1431
1432		if(nvram_get_int("stop_conn_3g") == 1){
1433			write_3g_ppp_conf();
1434		}
1435		else if(strcmp(modem_type, "wimax")){
1436			char *modem_argv[] = {"modem_enable.sh", NULL};
1437			char *ptr;
1438			int sim_state;
1439
1440			_eval(modem_argv, ">>/tmp/usb.log", 0, NULL);
1441
1442			if(nvram_match("g3err_pin", "1")){
1443				TRACE_PT("3g end: PIN error!\n");
1444				update_wan_state(prefix, WAN_STATE_STOPPED, WAN_STOPPED_REASON_PINCODE_ERR);
1445				return;
1446			}
1447
1448			ptr = nvram_safe_get("usb_modem_act_sim");
1449			if(strlen(ptr) > 0){
1450				sim_state = atoi(ptr);
1451				if(sim_state == 2 || sim_state == 3){
1452					TRACE_PT("3g end: Need to input PIN or PUK.\n");
1453					update_wan_state(prefix, WAN_STATE_STOPPED, WAN_STOPPED_REASON_PINCODE_ERR);
1454					return;
1455				}
1456				else if(sim_state != 1){
1457					TRACE_PT("3g end: SIM isn't ready.\n");
1458					return;
1459				}
1460			}
1461		}
1462
1463		if((!strcmp(modem_type, "tty") || !strcmp(modem_type, "mbim"))
1464				&& write_3g_ppp_conf()
1465				&& (fp = fopen(PPP_CONF_FOR_3G, "r")) != NULL){
1466			fclose(fp);
1467
1468			// run as ppp proto.
1469			nvram_set(strcat_r(prefix, "proto", tmp), "pppoe");
1470#ifndef RTCONFIG_DUALWAN
1471			nvram_set(strcat_r(prefix, "dhcpenable_x", tmp), "1");
1472			nvram_set(strcat_r(prefix, "vpndhcp", tmp), "0");
1473			nvram_set(strcat_r(prefix, "dnsenable_x", tmp), "1");
1474#endif
1475
1476			char *pppd_argv[] = { "/usr/sbin/pppd", "call", "3g", "nochecktime", NULL};
1477
1478			if(nvram_get_int("stop_conn_3g") != 1)
1479				_eval(pppd_argv, NULL, 0, NULL);
1480			else
1481				TRACE_PT("stop_conn_3g was set.\n");
1482		}
1483		// RNDIS, QMI interface: usbX, Beceem interface: usbbcm -> ethX, gct(mad)wimax: wimaxX.
1484		else{
1485			wan_ifname = nvram_safe_get(strcat_r(prefix, "ifname", tmp));
1486
1487			if(strlen(wan_ifname) <= 0){
1488#ifdef RTCONFIG_USB_BECEEM
1489				snprintf(usb_node, 32, "%s", nvram_safe_get("usb_modem_act_path"));
1490				if(strlen(usb_node) <= 0)
1491					return;
1492
1493				if(get_path_by_node(usb_node, port_path, 8) != NULL){
1494					snprintf(nvram_name, 32, "usb_path%s", port_path);
1495					TRACE_PT("RNDIS/Beceem: start_wan_if.\n");
1496
1497					if(!strcmp(nvram_safe_get(nvram_name), "modem")){
1498						snprintf(nvram_name, 32, "usb_path%s_vid", port_path);
1499						uvid = strtoul(nvram_safe_get(nvram_name), NULL, 16);
1500						snprintf(nvram_name, 32, "usb_path%s_pid", port_path);
1501						upid = strtoul(nvram_safe_get(nvram_name), NULL, 16);
1502
1503						if(is_samsung_dongle(1, uvid, upid)){
1504							modprobe("tun");
1505							sleep(1);
1506
1507							xstart("madwimax");
1508						}
1509						else if(is_gct_dongle(1, uvid, upid)){
1510							modprobe("tun");
1511							sleep(1);
1512
1513							write_gct_conf();
1514
1515							xstart("gctwimax", "-C", WIMAX_CONF);
1516						}
1517					}
1518				}
1519#endif
1520
1521				return;
1522			}
1523
1524#ifdef SET_USB_MODEM_MTU_ETH
1525			modem_mtu = nvram_get_int("modem_mtu");
1526#endif
1527			ifr.ifr_flags = 0;
1528			for (i = 0; i < 3; i++) {
1529				int flags, mtu = 0;
1530
1531				if (_ifconfig_get(wan_ifname, &flags, NULL, NULL, NULL, &mtu) < 0) {
1532					TRACE_PT("Couldn't read the flags of %s!\n", wan_ifname);
1533					update_wan_state(prefix, WAN_STATE_STOPPED, WAN_STOPPED_REASON_SYSTEM_ERR);
1534					return;
1535				}
1536				ifr.ifr_flags = flags;
1537#ifdef SET_USB_MODEM_MTU_ETH
1538				mtu = (modem_mtu >= 576 && modem_mtu < mtu) ? modem_mtu : 0;
1539				if ((flags & IFF_UP) && !mtu)
1540					break;
1541				_ifconfig(wan_ifname, flags | IFUP, NULL, NULL, NULL, mtu);
1542				if ((flags & IFF_UP))
1543					break;
1544#else
1545				if ((flags & IFF_UP))
1546					break;
1547				ifconfig(wan_ifname, flags | IFUP, NULL, NULL);
1548#endif
1549				TRACE_PT("%s: wait %s be up, %d second...!\n", __FUNCTION__, wan_ifname, i);
1550				sleep(1);
1551			};
1552
1553			if (!(ifr.ifr_flags & IFF_UP)) {
1554				TRACE_PT("Interface %s couldn't be up!\n", wan_ifname);
1555				update_wan_state(prefix, WAN_STATE_STOPPED, WAN_STOPPED_REASON_SYSTEM_ERR);
1556				return;
1557			}
1558
1559			// run as dhcp proto.
1560			nvram_set(strcat_r(prefix, "proto", tmp), "dhcp");
1561			nvram_set(strcat_r(prefix, "dhcpenable_x", tmp), "1");
1562			nvram_set(strcat_r(prefix, "dnsenable_x", tmp), "1");
1563
1564			// Android phone, RNDIS, QMI interface, Gobi.
1565			if(!strncmp(wan_ifname, "usb", 3)){
1566				if(nvram_get_int("stop_conn_3g") != 1){
1567#ifdef RTCONFIG_TCPDUMP
1568					char *tcpdump_argv[] = { "/usr/sbin/tcpdump", "-i", wan_ifname, "-nnXw", "/tmp/udhcpc.pcap", NULL};
1569					_eval(tcpdump_argv, NULL, 0, &pid);
1570					sleep(2);
1571#endif
1572					start_udhcpc(wan_ifname, unit, &pid);
1573				}
1574				else
1575					TRACE_PT("stop_conn_3g was set.\n");
1576			}
1577			// Beceem dongle, ASIX USB to RJ45 converter, Huawei E353.
1578			else if(!strncmp(wan_ifname, "eth", 3)){
1579#ifdef RTCONFIG_USB_BECEEM
1580				write_beceem_conf(wan_ifname);
1581#endif
1582
1583				if(nvram_get_int("stop_conn_3g") != 1){
1584					snprintf(usb_node, 32, "%s", nvram_safe_get("usb_modem_act_path"));
1585					if(strlen(usb_node) <= 0)
1586						return;
1587
1588					if(get_path_by_node(usb_node, port_path, 8) == NULL)
1589						return;
1590
1591					snprintf(nvram_name, 32, "usb_path%s_act", port_path);
1592
1593					if(!strcmp(nvram_safe_get(nvram_name), wan_ifname))
1594						start_udhcpc(wan_ifname, unit, &pid);
1595
1596#ifdef RTCONFIG_USB_BECEEM
1597					if(strlen(nvram_safe_get(nvram_name)) <= 0){
1598						char buf[128];
1599
1600						snprintf(buf, 128, "wimaxd -c %s", WIMAX_CONF);
1601						TRACE_PT("%s: cmd=%s.\n", __FUNCTION__, buf);
1602						system(buf);
1603						sleep(3);
1604
1605						TRACE_PT("%s: cmd=wimaxc search.\n", __FUNCTION__);
1606						system("wimaxc search");
1607						TRACE_PT("%s: sleep 10 seconds.\n", __FUNCTION__);
1608						sleep(10);
1609
1610						TRACE_PT("%s: cmd=wimaxc connect.\n", __FUNCTION__);
1611						system("wimaxc connect");
1612					}
1613#endif
1614				}
1615				else
1616					TRACE_PT("stop_conn_3g was set.\n");
1617			}
1618#ifdef RTCONFIG_USB_BECEEM
1619			else if(!strncmp(wan_ifname, "wimax", 5)){
1620				if(nvram_get_int("stop_conn_3g") != 1)
1621					start_udhcpc(wan_ifname, unit, &pid);
1622				else
1623					TRACE_PT("stop_conn_3g was set.\n");
1624			}
1625#endif
1626		}
1627
1628		TRACE_PT("3g end.\n");
1629		return;
1630	}
1631	else
1632#endif
1633	if (dualwan_unit__nonusbif(unit)) {
1634		convert_wan_nvram(prefix, unit);
1635
1636		/* make sure the connection exists and is enabled */
1637		wan_ifname = nvram_safe_get(strcat_r(prefix, "ifname", tmp));
1638		if(strlen(wan_ifname) <= 0)
1639			return;
1640
1641		wan_proto = nvram_get(strcat_r(prefix, "proto", tmp));
1642		if (!wan_proto || !strcmp(wan_proto, "disabled")) {
1643			update_wan_state(prefix, WAN_STATE_DISABLED, 0);
1644			return;
1645		}
1646
1647		/* Set i/f hardware address before bringing it up */
1648		if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
1649			update_wan_state(prefix, WAN_STATE_STOPPED, WAN_STOPPED_REASON_SYSTEM_ERR);
1650			return;
1651		}
1652
1653		strncpy(ifr.ifr_name, wan_ifname, IFNAMSIZ);
1654
1655		/* Since WAN interface may be already turned up (by vlan.c),
1656			if WAN hardware address is specified (and different than the current one),
1657			we need to make it down for synchronizing hwaddr. */
1658		if (ioctl(s, SIOCGIFHWADDR, &ifr)) {
1659			close(s);
1660			update_wan_state(prefix, WAN_STATE_STOPPED, WAN_STOPPED_REASON_SYSTEM_ERR);
1661			return;
1662		}
1663
1664#ifdef RTCONFIG_IPV6
1665		if (get_ipv6_service() == IPV6_NATIVE_DHCP || get_ipv6_service() == IPV6_MANUAL)
1666		{
1667			if (strcmp(wan_proto, "dhcp") && strcmp(wan_proto, "static") &&
1668				nvram_match(ipv6_nvname("ipv6_ifdev"), "ppp"))
1669			{
1670				disable_ipv6(wan_ifname);
1671#if !defined(RTCONFIG_BCMARM) && !defined(RTCONFIG_RALINK) && !defined(RTCONFIG_QCA)
1672				if (with_ipv6_linklocal_addr(wan_ifname))
1673					doSystem("ip -6 addr flush dev %s scope link", wan_ifname);
1674#endif
1675			}
1676			else
1677				enable_ipv6(wan_ifname);
1678		}
1679#endif
1680		ether_atoe((const char *) nvram_safe_get(strcat_r(prefix, "hwaddr", tmp)), (unsigned char *) eabuf);
1681		if ((bcmp(eabuf, ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN)))
1682		{
1683			/* current hardware address is different than user specified */
1684			ifconfig(wan_ifname, 0, NULL, NULL);
1685		}
1686#ifdef RTCONFIG_IPV6
1687#ifdef RTCONFIG_RALINK
1688		if (((get_ipv6_service() == IPV6_NATIVE_DHCP || get_ipv6_service() == IPV6_MANUAL) &&
1689		     strcmp(wan_proto, "dhcp") && strcmp(wan_proto, "static") &&
1690		     nvram_match(ipv6_nvname("ipv6_ifdev"), "eth") &&
1691		     !with_ipv6_linklocal_addr(wan_ifname)) ||
1692			with_ipv6_linklocal_addr(wan_ifname))
1693			ifconfig(wan_ifname, 0, NULL, NULL);
1694#endif
1695#endif
1696		/* Configure i/f only once, specially for wireless i/f shared by multiple connections */
1697		if (ioctl(s, SIOCGIFFLAGS, &ifr)) {
1698			close(s);
1699			update_wan_state(prefix, WAN_STATE_STOPPED, WAN_STOPPED_REASON_SYSTEM_ERR);
1700			return;
1701		}
1702
1703		if (!(ifr.ifr_flags & IFF_UP)) {
1704			fprintf(stderr, "** wan_ifname: %s is NOT UP\n", wan_ifname);
1705
1706			/* Sync connection nvram address and i/f hardware address */
1707			memset(ifr.ifr_hwaddr.sa_data, 0, ETHER_ADDR_LEN);
1708
1709			if (nvram_match(strcat_r(prefix, "hwaddr", tmp), "") ||
1710			    !ether_atoe((const char *) nvram_safe_get(strcat_r(prefix, "hwaddr", tmp)), (unsigned char *) ifr.ifr_hwaddr.sa_data) ||
1711			    !memcmp(ifr.ifr_hwaddr.sa_data, "\0\0\0\0\0\0", ETHER_ADDR_LEN)) {
1712				if (ioctl(s, SIOCGIFHWADDR, &ifr)) {
1713					fprintf(stderr, "ioctl fail. continue\n");
1714					close(s);
1715					update_wan_state(prefix, WAN_STATE_STOPPED, WAN_STOPPED_REASON_SYSTEM_ERR);
1716					return;
1717				}
1718				nvram_set(strcat_r(prefix, "hwaddr", tmp), ether_etoa((unsigned char *) ifr.ifr_hwaddr.sa_data, eabuf));
1719			}
1720			else {
1721				ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER;
1722				ioctl(s, SIOCSIFHWADDR, &ifr);
1723			}
1724
1725			/* Bring up i/f */
1726			ifconfig(wan_ifname, IFUP, NULL, NULL);
1727		}
1728		close(s);
1729
1730		/* Set initial QoS mode again now that WAN port is ready. */
1731#ifdef CONFIG_BCMWL5
1732		set_et_qos_mode();
1733#endif
1734		if (unit == wan_primary_ifunit())
1735			start_pppoe_relay(wan_ifname);
1736
1737		enable_ip_forward();
1738
1739		update_wan_state(prefix, WAN_STATE_CONNECTING, 0);
1740
1741		/*
1742		 * Configure PPPoE connection. The PPPoE client will run
1743		 * ip-up/ip-down scripts upon link's connect/disconnect.
1744		 */
1745		if (strcmp(wan_proto, "pppoe") == 0 ||
1746		    strcmp(wan_proto, "pptp") == 0 ||
1747		    strcmp(wan_proto, "l2tp") == 0) 	// oleg patch
1748		{
1749			char *ipaddr = nvram_safe_get(strcat_r(prefix, "xipaddr", tmp));
1750			char *netmask = nvram_safe_get(strcat_r(prefix, "xnetmask", tmp));
1751			int dhcpenable = nvram_get_int(strcat_r(prefix, "dhcpenable_x", tmp));
1752			int demand = nvram_get_int(strcat_r(prefix, "pppoe_idletime", tmp)) &&
1753					strcmp(wan_proto, "l2tp");	/* L2TP does not support idling */
1754
1755			/* update demand option */
1756			nvram_set_int(strcat_r(prefix, "pppoe_demand", tmp), demand);
1757
1758			if (dhcpenable == 0 &&
1759			    inet_equal(ipaddr, netmask,
1760				       nvram_safe_get("lan_ipaddr"), nvram_safe_get("lan_netmask"))) {
1761				update_wan_state(prefix, WAN_STATE_STOPPED, WAN_STOPPED_REASON_INVALID_IPADDR);
1762				return;
1763			}
1764
1765			/* Bring up WAN interface */
1766			ifconfig(wan_ifname, IFUP, ipaddr, netmask);
1767
1768			/* launch dhcp client and wait for lease forawhile */
1769			if (dhcpenable) {
1770				start_udhcpc(wan_ifname, unit,
1771					(strcmp(wan_proto, "pppoe") == 0) ? &pid : NULL);
1772			} else {
1773				char *gateway = nvram_safe_get(strcat_r(prefix, "xgateway", tmp));
1774
1775				/* start firewall */
1776// TODO: handle different lan_ifname
1777				start_firewall(unit, 0);
1778
1779				/* setup static wan routes via physical device */
1780				add_routes(prefix, "mroute", wan_ifname);
1781
1782				/* and set default route if specified with metric 1 */
1783				if (inet_addr_(gateway) != INADDR_ANY &&
1784				    !nvram_match(strcat_r(prefix, "heartbeat_x", tmp), "")) {
1785					in_addr_t mask = inet_addr(netmask);
1786
1787					/* the gateway is out of the local network */
1788					if ((inet_addr(gateway) & mask) != (inet_addr(ipaddr) & mask))
1789						route_add(wan_ifname, 2, gateway, NULL, "255.255.255.255");
1790
1791					/* default route via default gateway */
1792					route_add(wan_ifname, 2, "0.0.0.0", gateway, "0.0.0.0");
1793				}
1794
1795				/* update resolv.conf */
1796				update_resolvconf();
1797
1798				/* start multicast router on Static+VPN physical interface */
1799				if (unit == wan_primary_ifunit())
1800					start_igmpproxy(wan_ifname);
1801			}
1802
1803			/* launch pppoe client daemon */
1804			start_pppd(unit);
1805
1806			/* ppp interface name is referenced from this point
1807			 * after pppd start before ip-pre-up it will be empty */
1808			wan_ifname = nvram_safe_get(strcat_r(prefix, "pppoe_ifname", tmp));
1809
1810			/* Pretend that the WAN interface is up */
1811			if (demand) {
1812				int timeout = 5;
1813
1814				/* Wait for pppx to be created */
1815				while (timeout--) {
1816					/* ppp interface name is re-referenced from this point */
1817					wan_ifname = nvram_safe_get(strcat_r(prefix, "pppoe_ifname", tmp));
1818					if (*wan_ifname && ifconfig(wan_ifname, IFUP, NULL, NULL) == 0)
1819						break;
1820					_dprintf("%s: wait interface %s up at %d seconds...\n", __FUNCTION__, wan_ifname, timeout);
1821					sleep(1);
1822				}
1823
1824				if (!*wan_ifname) {
1825					_dprintf("%s: no interface of wan_unit %d.\n", __FUNCTION__, unit);
1826					return;
1827				}
1828
1829				/* Retrieve IP info */
1830				if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
1831					update_wan_state(prefix, WAN_STATE_STOPPED, WAN_STOPPED_REASON_SYSTEM_ERR);
1832					return;
1833				}
1834				strncpy(ifr.ifr_name, wan_ifname, IFNAMSIZ);
1835
1836				/* Set temporary IP address */
1837				if (ioctl(s, SIOCGIFADDR, &ifr))
1838					perror(wan_ifname);
1839				nvram_set(strcat_r(prefix, "ipaddr", tmp), inet_ntoa(sin_addr(&ifr.ifr_addr)));
1840				nvram_set(strcat_r(prefix, "netmask", tmp), "255.255.255.255");
1841
1842				/* Set temporary P-t-P address */
1843				if (ioctl(s, SIOCGIFDSTADDR, &ifr))
1844					perror(wan_ifname);
1845				nvram_set(strcat_r(prefix, "gateway", tmp), inet_ntoa(sin_addr(&ifr.ifr_dstaddr)));
1846
1847				close(s);
1848
1849				/*
1850				 * Preset routes so that traffic can be sent to proper pppx even before
1851				 * the link is brought up.
1852				 */
1853				preset_wan_routes(wan_ifname);
1854
1855				/* Trigger it up to obtain PPP DNS early */
1856				start_demand_ppp(unit, 0);
1857			}
1858		}
1859		/*
1860		 * Configure DHCP connection. The DHCP client will run
1861		 * 'udhcpc bound'/'udhcpc deconfig' upon finishing IP address
1862		 * renew and release.
1863		 */
1864		else if (strcmp(wan_proto, "dhcp") == 0)
1865		{
1866			/* Bring up WAN interface */
1867			dbG("ifup:%s\n", wan_ifname);
1868			ifconfig(wan_ifname, IFUP, NULL, NULL);
1869
1870			/* Start pre-authenticator */
1871			dbG("start auth:%d\n", unit);
1872			start_auth(unit, 0);
1873
1874#ifdef RTCONFIG_DSL
1875			nvram_set(strcat_r(prefix, "clientid_type", tmp), nvram_safe_get("dslx_dhcp_clientid_type"));
1876			nvram_set(strcat_r(prefix, "clientid", tmp), nvram_safe_get("dslx_dhcp_clientid"));
1877			nvram_set(strcat_r(prefix, "vendorid", tmp), nvram_safe_get("dslx_dhcp_vendorid"));
1878#endif
1879			/* Start dhcp daemon */
1880			dbG("start udhcpc:%s, %d\n", wan_ifname, unit);
1881			start_udhcpc(wan_ifname, unit, &pid);
1882		}
1883		/* Configure static IP connection. */
1884		else if (strcmp(wan_proto, "static") == 0)
1885		{
1886			if (inet_equal(nvram_safe_get(strcat_r(prefix, "ipaddr", tmp)), nvram_safe_get(strcat_r(prefix, "netmask", tmp)),
1887				       nvram_safe_get("lan_ipaddr"), nvram_safe_get("lan_netmask"))) {
1888				update_wan_state(prefix, WAN_STATE_STOPPED, WAN_STOPPED_REASON_INVALID_IPADDR);
1889				return;
1890			}
1891
1892			/* Assign static IP address to i/f */
1893			ifconfig(wan_ifname, IFUP,
1894					nvram_safe_get(strcat_r(prefix, "ipaddr", tmp)),
1895					nvram_safe_get(strcat_r(prefix, "netmask", tmp)));
1896
1897			/* Start pre-authenticator */
1898			start_auth(unit, 0);
1899
1900#ifdef RTCONFIG_DSL
1901#ifdef RTCONFIG_DUALWAN
1902			if (wan_type == WANS_DUALWAN_IF_DSL)
1903#endif
1904			{
1905				if (nvram_match("dsl0_proto", "ipoa"))
1906					start_ipoa();
1907			}
1908#endif
1909
1910			/* We are done configuration */
1911			wan_up(wan_ifname);
1912		}
1913	}
1914	else
1915#ifdef RTCONFIG_DUALWAN
1916		_dprintf("%s(): Cound't find the type(%d) of unit(%d)!!!\n", __FUNCTION__, wan_type, unit);
1917#else
1918		_dprintf("%s(): Cound't find the wan(%d)!!!\n", __FUNCTION__, unit);
1919#endif
1920
1921	_dprintf("%s(): End.\n", __FUNCTION__);
1922}
1923
1924void
1925stop_wan_if(int unit)
1926{
1927#if defined(RTCONFIG_DSL) && defined(RTCONFIG_DUALWAN)
1928	int wan_type;
1929#endif
1930	char *wan_ifname;
1931	char tmp[100], prefix[] = "wanXXXXXXXXXX_";
1932	char *wan_proto, active_proto[32];
1933#if defined(RTCONFIG_USB_BECEEM)
1934	int i;
1935#endif
1936#ifdef RTCONFIG_USB_BECEEM
1937	unsigned int uvid, upid;
1938#endif
1939	int end_wan_sbstate = WAN_STOPPED_REASON_NONE;
1940
1941	snprintf(prefix, sizeof(prefix), "wan%d_", unit);
1942
1943#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
1944	if(nvram_get_int(strcat_r(prefix, "sbstate_t", tmp)) == WAN_STOPPED_REASON_DATALIMIT)
1945		end_wan_sbstate = WAN_STOPPED_REASON_DATALIMIT;
1946#endif
1947
1948	update_wan_state(prefix, WAN_STATE_STOPPING, end_wan_sbstate);
1949
1950	/* Backup active wan_proto for later restore, if it have been updated by ui */
1951	wan_proto = nvram_safe_get(strcat_r(prefix, "proto", tmp));
1952	strncpy(active_proto, wan_proto, sizeof(active_proto));
1953
1954	/* Set previous wan_proto as active */
1955	wan_proto = nvram_safe_get(strcat_r(prefix, "proto_t", tmp));
1956	if (*wan_proto && strcmp(active_proto, wan_proto) != 0)
1957	{
1958		stop_iQos(); // clean all tc rules
1959		_dprintf("%s %sproto_t=%s\n", __FUNCTION__, prefix, wan_proto);
1960		nvram_set(strcat_r(prefix, "proto", tmp), wan_proto);
1961		nvram_unset(strcat_r(prefix, "proto_t", tmp));
1962	}
1963
1964	// Handel for each interface
1965	if(unit == wan_primary_ifunit()){
1966		killall_tk("stats");
1967		killall_tk("ntpclient");
1968
1969#ifdef RTCONFIG_IPV6
1970		if (!(strcmp(wan_proto, "dhcp") && strcmp(wan_proto, "static") &&
1971			nvram_match(ipv6_nvname("ipv6_ifdev"), "ppp") &&
1972			(get_ipv6_service() == IPV6_NATIVE_DHCP || get_ipv6_service() == IPV6_MANUAL))) {
1973			stop_wan6();
1974		}
1975#endif
1976		/* Shutdown and kill all possible tasks */
1977#if 0
1978		killall_tk("ip-up");
1979		killall_tk("ip-down");
1980		killall_tk("ip-pre-up");
1981#ifdef RTCONFIG_IPV6
1982		killall_tk("ipv6-up");
1983		killall_tk("ipv6-down");
1984#endif
1985		killall_tk("auth-fail");
1986#endif
1987
1988#ifdef RTCONFIG_MULTICAST_IPTV
1989		if (nvram_get_int("switch_stb_x") > 6 &&
1990		    nvram_match("switch_wantag", "movistar") && unit == WAN_UNIT_IPTV)
1991#endif
1992		stop_igmpproxy();
1993	}
1994
1995#ifdef RTCONFIG_VPNC
1996	/* Stop VPN client */
1997	stop_vpnc();
1998#endif
1999
2000	/* Stop l2tp */
2001	if (strcmp(wan_proto, "l2tp") == 0) {
2002		kill_pidfile_tk("/var/run/l2tpd.pid");
2003		usleep(1000*10000);
2004	}
2005
2006	/* Stop pppd */
2007	stop_pppd(unit);
2008
2009	/* Stop post-authenticator */
2010	stop_auth(unit, 1);
2011
2012	/* Stop dhcp client */
2013	stop_udhcpc(unit);
2014
2015	/* Stop pre-authenticator */
2016	stop_auth(unit, 0);
2017
2018	/* Bring down WAN interfaces */
2019	// Does it have to?
2020	wan_ifname = nvram_safe_get(strcat_r(prefix, "ifname", tmp));
2021#ifdef RTCONFIG_USB_MODEM
2022	if(strncmp(wan_ifname, "/dev/tty", 8))
2023#endif
2024	{
2025		if(strlen(wan_ifname) > 0){
2026			ifconfig(wan_ifname, 0, NULL, NULL);
2027#ifdef RTCONFIG_RALINK
2028#elif defined(RTCONFIG_QCA)
2029#else
2030			if(!strncmp(wan_ifname, "eth", 3) || !strncmp(wan_ifname, "vlan", 4))
2031				ifconfig(wan_ifname, IFUP, "0.0.0.0", NULL);
2032#endif
2033		}
2034	}
2035
2036#ifdef RTCONFIG_DSL
2037#ifdef RTCONFIG_DUALWAN
2038	wan_type = get_dualwan_by_unit(unit);
2039	if(wan_type == WANS_DUALWAN_IF_DSL)
2040#endif
2041		if (nvram_match("dsl0_proto", "ipoa"))
2042		{
2043			stop_ipoa();
2044		}
2045#endif
2046
2047#if defined(RTCONFIG_USB_MODEM)
2048	if (dualwan_unit__usbif(unit)) {
2049#if defined(RTCONFIG_USB_BECEEM)
2050		if(is_usb_modem_ready() == 1){
2051			if(pids("wimaxd"))
2052				eval("wimaxc", "disconnect");
2053		}
2054
2055		if(pids("wimaxd")){
2056			killall("wimaxd", SIGTERM);
2057			killall("wimaxd", SIGUSR1);
2058		}
2059
2060		uvid = atoi(nvram_safe_get("usb_modem_act_vid"));
2061		upid = atoi(nvram_safe_get("usb_modem_act_pid"));
2062
2063		if(is_samsung_dongle(1, uvid, upid)){
2064			i = 0;
2065			while(i < 3){
2066				if(pids("madwimax")){
2067					killall_tk("madwimax");
2068					sleep(1);
2069
2070					++i;
2071				}
2072				else
2073					break;
2074			}
2075
2076			modprobe_r("tun");
2077
2078			nvram_set(strcat_r(prefix, "ifname", tmp), "");
2079		}
2080		else if(is_gct_dongle(1, uvid, upid)){
2081			i = 0;
2082			while(i < 3){
2083				if(pids("gctwimax")){
2084					killall_tk("gctwimax");
2085					sleep(1);
2086
2087					++i;
2088				}
2089				else
2090					break;
2091			}
2092			unlink(WIMAX_CONF);
2093
2094			modprobe_r("tun");
2095
2096			nvram_set(strcat_r(prefix, "ifname", tmp), "");
2097		}
2098#endif	/* RTCONFIG_USB_BECEEM */
2099
2100#ifdef RTCONFIG_INTERNAL_GOBI
2101		char *const modem_argv[] = {"modem_stop.sh", NULL};
2102
2103		_eval(modem_argv, ">>/tmp/usb.log", 0, NULL);
2104#endif
2105	}
2106
2107	if(dualwan_unit__usbif(unit))
2108		update_wan_state(prefix, WAN_STATE_INITIALIZING, end_wan_sbstate);
2109	else
2110#endif // RTCONFIG_USB_MODEM
2111		update_wan_state(prefix, WAN_STATE_STOPPED, end_wan_sbstate);
2112
2113	// wait for release finished ?
2114	if (!g_reboot)
2115		sleep(2);
2116
2117	/* Restore active wan_proto value */
2118	_dprintf("%s %sproto=%s\n", __FUNCTION__, prefix, active_proto);
2119	nvram_set(strcat_r(prefix, "proto", tmp), active_proto);
2120}
2121
2122int update_resolvconf(void)
2123{
2124	FILE *fp, *fp_servers;
2125	char tmp[100], prefix[sizeof("wanXXXXXXXXXX_")];
2126	char *wan_dns, *wan_domain, *next;
2127	char domain[64], *next_domain;
2128	int unit, lock;
2129#ifdef RTCONFIG_YANDEXDNS
2130	int yadns_mode = nvram_get_int("yadns_enable_x") ? nvram_get_int("yadns_mode") : YADNS_DISABLED;
2131#endif
2132
2133	lock = file_lock("resolv");
2134
2135	if (!(fp = fopen("/tmp/resolv.conf", "w+"))) {
2136		perror("/tmp/resolv.conf");
2137		goto error;
2138	}
2139	if (!(fp_servers = fopen("/tmp/resolv.dnsmasq", "w+"))) {
2140		perror("/tmp/resolv.dnsmasq");
2141		fclose(fp);
2142		goto error;
2143	}
2144
2145#ifdef RTCONFIG_OPENVPN
2146	if (!write_vpn_resolv(fp)) {
2147#endif
2148	for (unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; unit++) {
2149		char *wan_xdns, *wan_xdomain;
2150
2151	/* TODO: Skip unused wans
2152		if (wan disabled or inactive and it's not ppp with active man)
2153			continue */
2154
2155		snprintf(prefix, sizeof(prefix), "wan%d_", unit);
2156		wan_dns = nvram_safe_get(strcat_r(prefix, "dns", tmp));
2157		wan_xdns = nvram_safe_get(strcat_r(prefix, "xdns", tmp));
2158
2159		if (!*wan_dns && !*wan_xdns)
2160			continue;
2161
2162		foreach(tmp, (*wan_dns ? wan_dns : wan_xdns), next)
2163			fprintf(fp, "nameserver %s\n", tmp);
2164
2165		wan_domain = nvram_safe_get(strcat_r(prefix, "domain", tmp));
2166		foreach(tmp, wan_dns, next) {
2167			foreach(domain, wan_domain, next_domain)
2168				fprintf(fp_servers, "server=/%s/%s\n", domain, tmp);
2169#ifdef RTCONFIG_YANDEXDNS
2170			if (yadns_mode != YADNS_DISABLED)
2171				fprintf(fp_servers, "server=/%s/%s\n", "local", tmp);
2172#endif
2173		}
2174
2175		wan_xdomain = nvram_safe_get(strcat_r(prefix, "xdomain", tmp));
2176		foreach(tmp, wan_xdns, next) {
2177			int new = (find_word(wan_dns, tmp) == NULL);
2178			foreach(domain, wan_xdomain, next_domain) {
2179				if (new || find_word(wan_domain, domain) == NULL)
2180					fprintf(fp_servers, "server=/%s/%s\n", domain, tmp);
2181			}
2182#ifdef RTCONFIG_YANDEXDNS
2183			if (yadns_mode != YADNS_DISABLED && new)
2184				fprintf(fp_servers, "server=/%s/%s\n", "local", tmp);
2185#endif
2186		}
2187	}
2188#ifdef RTCONFIG_OPENVPN
2189	}
2190#endif
2191
2192#ifdef RTCONFIG_YANDEXDNS
2193	if (yadns_mode != YADNS_DISABLED) {
2194		char *server[2];
2195		int count = get_yandex_dns(AF_INET, yadns_mode, server, sizeof(server)/sizeof(server[0]));
2196		for (unit = 0; unit < count; unit++) {
2197			fprintf(fp_servers, "server=%s\n", server[unit]);
2198			fprintf(fp_servers, "server=%s#%u\n", server[unit], YADNS_DNSPORT);
2199		}
2200	}
2201#endif
2202
2203#ifdef RTCONFIG_IPV6
2204	if (ipv6_enabled() &&
2205#ifdef RTCONFIG_6RELAYD
2206		(get_ipv6_service() != IPV6_PASSTHROUGH) &&
2207#endif
2208		is_routing_enabled()) {
2209		char dnsbuf[INET6_ADDRSTRLEN*3 + 3];
2210		struct in6_addr addr;
2211
2212	/* TODO: Skip unconnected wan */
2213
2214		if (get_ipv6_service() == IPV6_NATIVE_DHCP && nvram_get_int(ipv6_nvname("ipv6_dnsenable"))) {
2215			wan_dns = nvram_safe_get(ipv6_nvname("ipv6_get_dns"));
2216			wan_domain = nvram_safe_get(ipv6_nvname("ipv6_get_domain"));
2217		} else {
2218			next = strcpy(dnsbuf, "");
2219			for (unit = 1; unit <= 3; unit++) {
2220				snprintf(tmp, sizeof(tmp), "ipv6_dns%d", unit);
2221				next += snprintf(next, sizeof(dnsbuf) + dnsbuf - next,
2222					    *dnsbuf ? " %s" : "%s", nvram_safe_get(ipv6_nvname(tmp)));
2223			}
2224			wan_dns = dnsbuf;
2225			wan_domain = "";
2226		}
2227
2228		foreach(tmp, wan_dns, next) {
2229			if (inet_pton(AF_INET6, tmp, &addr) <= 0)
2230				continue;
2231			foreach(domain, wan_domain, next_domain)
2232				fprintf(fp_servers, "server=/%s/%s\n", domain, tmp);
2233#ifdef RTCONFIG_YANDEXDNS
2234			if (yadns_mode != YADNS_DISABLED) {
2235				fprintf(fp_servers, "server=/%s/%s\n", "local", tmp);
2236				continue;
2237			}
2238#endif
2239			fprintf(fp_servers, "server=%s\n", tmp);
2240		}
2241
2242#ifdef RTCONFIG_YANDEXDNS
2243		if (yadns_mode != YADNS_DISABLED) {
2244			char *server[2];
2245			int count = get_yandex_dns(AF_INET6, yadns_mode, server, sizeof(server)/sizeof(server[0]));
2246			for (unit = 0; unit < count; unit++) {
2247				fprintf(fp_servers, "server=%s\n", server[unit]);
2248				fprintf(fp_servers, "server=%s#%u\n", server[unit], YADNS_DNSPORT);
2249			}
2250		}
2251#endif
2252	}
2253#endif
2254
2255	fclose(fp);
2256	fclose(fp_servers);
2257	file_unlock(lock);
2258
2259	reload_dnsmasq();
2260
2261	return 0;
2262
2263error:
2264	file_unlock(lock);
2265	return -1;
2266}
2267
2268#ifdef RTCONFIG_IPV6
2269void wan6_up(const char *wan_ifname)
2270{
2271	char addr6[INET6_ADDRSTRLEN + 4];
2272	struct in_addr addr4;
2273	struct in6_addr addr;
2274	char *gateway;
2275	int mtu, service = get_ipv6_service();
2276
2277	if (!wan_ifname || (strlen(wan_ifname) <= 0) ||
2278		(service == IPV6_DISABLED))
2279		return;
2280
2281	switch (service) {
2282	case IPV6_NATIVE_DHCP:
2283#ifdef RTCONFIG_6RELAYD
2284	case IPV6_PASSTHROUGH:
2285#endif
2286		ipv6_sysconf(wan_ifname, "accept_ra", 1);
2287		ipv6_sysconf(wan_ifname, "forwarding", 0);
2288		break;
2289	case IPV6_MANUAL:
2290		ipv6_sysconf(wan_ifname, "accept_ra", 0);
2291		ipv6_sysconf(wan_ifname, "forwarding", 1);
2292		break;
2293	case IPV6_6RD:
2294		update_6rd_info();
2295		break;
2296	}
2297
2298	set_intf_ipv6_dad(wan_ifname, 0, 1);
2299
2300	switch (service) {
2301	case IPV6_NATIVE_DHCP:
2302#ifdef RTCONFIG_6RELAYD
2303	case IPV6_PASSTHROUGH:
2304#endif
2305		start_dhcp6c();
2306		break;
2307	case IPV6_MANUAL:
2308		if (nvram_match(ipv6_nvname("ipv6_ipaddr"), (char*)ipv6_router_address(NULL))) {
2309			dbG("WAN IPv6 address is the same as LAN IPv6 address!\n");
2310			break;
2311		}
2312		snprintf(addr6, sizeof(addr6), "%s/%d", nvram_safe_get(ipv6_nvname("ipv6_ipaddr")), nvram_get_int(ipv6_nvname("ipv6_prefix_len_wan")));
2313		eval("ip", "-6", "addr", "add", addr6, "dev", (char *)wan_ifname);
2314		eval("ip", "-6", "route", "del", "::/0");
2315
2316		gateway = nvram_safe_get(ipv6_nvname("ipv6_gateway"));
2317		if (gateway && gateway) {
2318			eval("ip", "-6", "route", "add", gateway, "dev", (char *)wan_ifname, "metric", "1");
2319			eval("ip", "-6", "route", "add", "::/0", "via", gateway, "dev", (char *)wan_ifname, "metric", "1");
2320		} else	eval("ip", "-6", "route", "add", "::/0", "dev", (char *)wan_ifname, "metric", "1");
2321
2322		/* propagate ipv6 mtu */
2323		mtu = ipv6_getconf(wan_ifname, "mtu");
2324		if (mtu)
2325			ipv6_sysconf(nvram_safe_get("lan_ifname"), "mtu", mtu);
2326		/* workaround to update ndp entry for now */
2327		eval("ping6", "-c", "2", "-I", (char *)wan_ifname, "ff02::1");
2328		eval("ping6", "-c", "2", nvram_safe_get(ipv6_nvname("ipv6_gateway")));
2329
2330		break;
2331	case IPV6_6TO4:
2332	case IPV6_6IN4:
2333	case IPV6_6RD:
2334		stop_ipv6_tunnel();
2335		if (service == IPV6_6TO4) {
2336			int prefixlen = 16;
2337			int mask4size = 0;
2338
2339			/* prefix */
2340			addr4.s_addr = 0;
2341			memset(&addr, 0, sizeof(addr));
2342			inet_aton(get_wanip(), &addr4);
2343			addr.s6_addr16[0] = htons(0x2002);
2344			prefixlen = ipv6_mapaddr4(&addr, prefixlen, &addr4, mask4size);
2345			//addr4.s_addr = htonl(0x00000001);
2346			//prefixlen = ipv6_mapaddr4(&addr, prefixlen, &addr4, (32 - 16));
2347			inet_ntop(AF_INET6, &addr, addr6, sizeof(addr6));
2348			nvram_set(ipv6_nvname("ipv6_prefix"), addr6);
2349			nvram_set_int(ipv6_nvname("ipv6_prefix_length"), prefixlen);
2350
2351			/* address */
2352			addr.s6_addr16[7] |= htons(0x0001);
2353			inet_ntop(AF_INET6, &addr, addr6, sizeof(addr6));
2354			nvram_set(ipv6_nvname("ipv6_rtr_addr"), addr6);
2355		}
2356		else if (service == IPV6_6RD) {
2357			int prefixlen = nvram_get_int(ipv6_nvname("ipv6_6rd_prefixlen"));
2358			int masklen = nvram_get_int(ipv6_nvname("ipv6_6rd_ip4size"));
2359
2360			/* prefix */
2361			addr4.s_addr = 0;
2362			memset(&addr, 0, sizeof(addr));
2363			inet_aton(get_wanip(), &addr4);
2364			inet_pton(AF_INET6, nvram_safe_get(ipv6_nvname("ipv6_6rd_prefix")), &addr);
2365			prefixlen = ipv6_mapaddr4(&addr, prefixlen, &addr4, masklen);
2366			//addr4.s_addr = htonl(0x00000001);
2367			//prefixlen = ipv6_mapaddr4(&addr, prefixlen, &addr4, (32 - 1));
2368			inet_ntop(AF_INET6, &addr, addr6, sizeof(addr6));
2369			nvram_set(ipv6_nvname("ipv6_prefix"), addr6);
2370			nvram_set_int(ipv6_nvname("ipv6_prefix_length"), prefixlen);
2371
2372			/* address */
2373			addr.s6_addr16[7] |= htons(0x0001);
2374			inet_ntop(AF_INET6, &addr, addr6, sizeof(addr6));
2375			nvram_set(ipv6_nvname("ipv6_rtr_addr"), addr6);
2376		}
2377		start_ipv6_tunnel();
2378
2379		/* propagate ipv6 mtu */
2380		mtu = ipv6_getconf(wan_ifname, "mtu");
2381		if (mtu)
2382			ipv6_sysconf(nvram_safe_get("lan_ifname"), "mtu", mtu);
2383		// FIXME: give it a few seconds for DAD completion
2384		sleep(2);
2385		break;
2386	}
2387
2388#if 0
2389	start_ecmh(wan_ifname);
2390#endif
2391}
2392
2393void wan6_down(const char *wan_ifname)
2394{
2395	set_intf_ipv6_dad(wan_ifname, 0, 0);
2396#if 0
2397	stop_ecmh();
2398#endif
2399#ifdef RTCONFIG_6RELAYD
2400	stop_6relayd();
2401#endif
2402	stop_dhcp6c();
2403	stop_ipv6_tunnel();
2404
2405	update_resolvconf();
2406}
2407
2408void start_wan6(void)
2409{
2410	// call wan6_up directly
2411	char tmp[100];
2412	char prefix[] = "wanXXXXXXXXXX_";
2413	char *wan_proto;
2414
2415	snprintf(prefix, sizeof(prefix), "wan%d_", wan_primary_ifunit());
2416	wan_proto = nvram_get(strcat_r(prefix, "proto", tmp));
2417
2418	if (!(strcmp(wan_proto, "dhcp") && strcmp(wan_proto, "static") &&
2419		nvram_match(ipv6_nvname("ipv6_ifdev"), "ppp") &&
2420		(get_ipv6_service() == IPV6_NATIVE_DHCP || get_ipv6_service() == IPV6_MANUAL))) {
2421		wan6_up(get_wan6face());
2422	}
2423}
2424
2425void stop_wan6(void)
2426{
2427	// call wan6_down directly
2428	wan6_down(get_wan6face());
2429}
2430
2431#endif
2432
2433void
2434wan_up(char *wan_ifname)	// oleg patch, replace
2435{
2436	char tmp[100];
2437	char prefix[] = "wanXXXXXXXXXX_";
2438	char prefix_x[] = "wanXXXXXXXXX_";
2439	char *wan_proto, *gateway;
2440	int wan_unit;
2441
2442	_dprintf("%s(%s)\n", __FUNCTION__, wan_ifname);
2443
2444	/* Figure out nvram variable name prefix for this i/f */
2445	if ((wan_unit = wan_ifunit(wan_ifname)) < 0)
2446	{
2447		/* called for dhcp+ppp */
2448		if ((wan_unit = wanx_ifunit(wan_ifname)) < 0)
2449			return;
2450
2451		snprintf(prefix, sizeof(prefix), "wan%d_", wan_unit);
2452		snprintf(prefix_x, sizeof(prefix_x), "wan%d_x", wan_unit);
2453
2454#ifdef RTCONFIG_IPV6
2455		wan_proto = nvram_safe_get(strcat_r(prefix, "proto", tmp));
2456		if (wan_unit == wan_primary_ifunit()) {
2457			if (!(strcmp(wan_proto, "dhcp") && strcmp(wan_proto, "static") &&
2458				nvram_match(ipv6_nvname("ipv6_ifdev"), "ppp") &&
2459				(get_ipv6_service() == IPV6_NATIVE_DHCP || get_ipv6_service() == IPV6_MANUAL))) {
2460				wan6_up(get_wan6face());
2461			}
2462		}
2463#endif
2464
2465		start_firewall(wan_unit, 0);
2466
2467		/* setup static wan routes via physical device */
2468		add_routes(prefix, "mroute", wan_ifname);
2469
2470		/* and one supplied via DHCP */
2471		add_dhcp_routes(prefix_x, wan_ifname, 1);
2472
2473		/* and default route with metric 1 */
2474		gateway = nvram_safe_get(strcat_r(prefix_x, "gateway", tmp));
2475		if (inet_addr_(gateway) != INADDR_ANY) {
2476			char word[100], *next;
2477			in_addr_t addr = inet_addr(nvram_safe_get(strcat_r(prefix_x, "ipaddr", tmp)));
2478			in_addr_t mask = inet_addr(nvram_safe_get(strcat_r(prefix_x, "netmask", tmp)));
2479
2480			/* the gateway is out of the local network */
2481			if ((inet_addr(gateway) & mask) != (addr & mask))
2482				route_add(wan_ifname, 2, gateway, NULL, "255.255.255.255");
2483
2484			/* default route via default gateway */
2485			route_add(wan_ifname, 2, "0.0.0.0", gateway, "0.0.0.0");
2486
2487			/* ... and to dns servers as well for demand ppp to work */
2488			if (nvram_get_int(strcat_r(prefix, "dnsenable_x", tmp))) {
2489				foreach(word, nvram_safe_get(strcat_r(prefix_x, "dns", tmp)), next) {
2490					if ((inet_addr(word) != inet_addr(gateway)) &&
2491					    (inet_addr(word) & mask) != (addr & mask))
2492						route_add(wan_ifname, 2, word, gateway, "255.255.255.255");
2493				}
2494			}
2495		}
2496
2497		update_resolvconf();
2498
2499		/* start multicast router on DHCP+VPN physical interface */
2500		if (wan_unit == wan_primary_ifunit())
2501			start_igmpproxy(wan_ifname);
2502
2503		return;
2504	}
2505
2506	snprintf(prefix, sizeof(prefix), "wan%d_", wan_unit);
2507
2508	wan_proto = nvram_safe_get(strcat_r(prefix, "proto", tmp));
2509	gateway = nvram_safe_get(strcat_r(prefix, "gateway", tmp));
2510	if (inet_addr_(gateway) == INADDR_ANY)
2511		gateway = NULL;
2512
2513	/* Set default route to gateway if specified */
2514	if (strcmp(wan_proto, "dhcp") == 0 || strcmp(wan_proto, "static") == 0) {
2515		/* the gateway is in the local network */
2516		if (gateway &&
2517		    inet_addr_(gateway) != inet_addr_(nvram_safe_get(strcat_r(prefix, "ipaddr", tmp)))) {
2518#ifdef RTCONFIG_MULTICAST_IPTV
2519			/* Rawny: delete gateway route in IPTV(movistar) case to enable QUAGGA */
2520			if (nvram_get_int("switch_stb_x") > 6 &&
2521			    !nvram_match("switch_wantag", "movistar"))
2522#endif
2523			route_add(wan_ifname, 0, gateway, NULL, "255.255.255.255");
2524		}
2525		/* replaced with add_multi_routes()
2526		route_add(wan_ifname, 0, "0.0.0.0", gateway, "0.0.0.0"); */
2527	}
2528
2529	/* hack: avoid routing cycles, when both peer and server has the same IP */
2530	if (strcmp(wan_proto, "pptp") == 0 || strcmp(wan_proto, "l2tp") == 0) {
2531		/* delete gateway route as it's no longer needed */
2532		if (gateway)
2533			route_del(wan_ifname, 0, gateway, "0.0.0.0", "255.255.255.255");
2534	}
2535
2536	/* Install interface dependent static routes */
2537	add_wan_routes(wan_ifname);
2538
2539	nvram_set(strcat_r(prefix, "gw_ifname", tmp), wan_ifname);
2540
2541	/* setup static wan routes via physical device */
2542	if (strcmp(wan_proto, "dhcp") == 0 || strcmp(wan_proto, "static") == 0) {
2543		nvram_set(strcat_r(prefix, "xgateway", tmp), gateway ? : "0.0.0.0");
2544		add_routes(prefix, "mroute", wan_ifname);
2545	}
2546
2547	/* and one supplied via DHCP */
2548	if (strcmp(wan_proto, "dhcp") == 0)
2549		add_dhcp_routes(prefix, wan_ifname, 0);
2550
2551#ifdef RTCONFIG_IPV6
2552	if (wan_unit == wan_primary_ifunit()) {
2553		if (!(strcmp(wan_proto, "dhcp") && strcmp(wan_proto, "static") &&
2554			nvram_match(ipv6_nvname("ipv6_ifdev"), "ppp") &&
2555			(get_ipv6_service() == IPV6_NATIVE_DHCP || get_ipv6_service() == IPV6_MANUAL))) {
2556			wan6_up(get_wan6face());
2557		}
2558	}
2559#endif
2560
2561#ifdef RTCONFIG_MULTICAST_IPTV
2562	if (nvram_get_int("switch_stb_x") > 6 &&
2563	    nvram_match("iptv_ifname", wan_ifname)) {
2564		if (nvram_match("switch_wantag", "maxis_fiber_iptv"))
2565			route_add(wan_ifname, 0, "172.17.90.1", NULL, "255.255.255.255");
2566		start_igmpproxy(wan_ifname);
2567	}
2568#ifdef RTCONFIG_QUAGGA
2569	if (wan_unit == WAN_UNIT_IPTV) {
2570		stop_quagga();
2571		start_quagga();
2572	}
2573#endif
2574#endif
2575
2576#if defined(RTCONFIG_QCA) || \
2577    (defined(RTCONFIG_RALINK) && !defined(RTCONFIG_DSL) && !defined(RTN13U))
2578	reinit_hwnat(wan_unit);
2579#endif
2580
2581#if defined(DSL_N55U) || defined(DSL_N55U_B)
2582	if(nvram_match("wl0_country_code", "GB")) {
2583		if(isTargetArea()) {
2584			system("ATE Set_RegulationDomain_2G SG");
2585			//system("ATE Set_RegulationDomain_5G SG");
2586		}
2587	}
2588#endif
2589
2590#if defined(RTCONFIG_WANRED_LED)
2591	if (!strcmp(wan_proto, "static") && test_gateway(gateway, wan_ifname))
2592		update_wan_state(prefix, WAN_STATE_CONNECTING, 0);
2593	else
2594#endif
2595	/* Set connected state */
2596	update_wan_state(prefix, WAN_STATE_CONNECTED, 0);
2597
2598	// TODO: handle different lan_ifname?
2599	start_firewall(wan_unit, 0);
2600	//start_firewall(wan_ifname, nvram_safe_get(strcat_r(prefix, "ipaddr", tmp)),
2601	//	nvram_safe_get("lan_ifname"), nvram_safe_get("lan_ipaddr"));
2602
2603	/* Start post-authenticator */
2604	start_auth(wan_unit, 1);
2605
2606	/* Add dns servers to resolv.conf */
2607	update_resolvconf();
2608
2609	/* default route via default gateway */
2610	add_multi_routes();
2611
2612#ifdef RTCONFIG_USB_MODEM
2613#ifdef RTCONFIG_INTERNAL_GOBI
2614	if(dualwan_unit__usbif(wan_unit)){
2615		eval("modem_status.sh", "operation");
2616#if defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS)
2617		eval("modem_status.sh", "get_dataset");
2618		eval("modem_status.sh", "bytes");
2619#endif
2620
2621		char start_sec[32], *str = file2str("/proc/uptime");
2622		unsigned int up = atoi(str);
2623
2624		free(str);
2625		snprintf(start_sec, 32, "%u", up);
2626		nvram_set("usb_modem_act_startsec", start_sec);
2627	}
2628#endif
2629#endif
2630
2631#ifdef RTCONFIG_OPENVPN
2632	stop_vpn_eas();
2633#endif
2634
2635	do_dns_detect();
2636
2637	if (wan_unit != wan_primary_ifunit())
2638	{
2639#ifdef RTCONFIG_OPENVPN
2640		start_vpn_eas();
2641#endif
2642		return;
2643	}
2644
2645	/* start multicast router when not VPN */
2646	if (strcmp(wan_proto, "dhcp") == 0 ||
2647	    strcmp(wan_proto, "static") == 0)
2648		start_igmpproxy(wan_ifname);
2649
2650	stop_upnp();
2651	start_upnp();
2652
2653	stop_ddns();
2654	start_ddns();
2655
2656	/* Sync time */
2657	refresh_ntpc();
2658
2659#ifdef RTCONFIG_OPENVPN
2660	start_vpn_eas();
2661#endif
2662#ifdef RTCONFIG_VPNC
2663	if((nvram_match("vpnc_proto", "pptp") || nvram_match("vpnc_proto", "l2tp")) && nvram_match("vpnc_auto_conn", "1"))
2664		start_vpnc();
2665#endif
2666#if defined(RTCONFIG_PPTPD) || defined(RTCONFIG_ACCEL_PPTPD)
2667	if (nvram_match("pptpd_enable", "1")) {
2668		stop_pptpd();
2669		start_pptpd();
2670	}
2671#endif
2672
2673#if defined(RTCONFIG_BLINK_LED)
2674	if(dualwan_unit__usbif(wan_unit)
2675			|| ((nvram_get_int("boardflags") & 0x100) && get_dualwan_by_unit(wan_unit) == WANS_DUALWAN_IF_LAN)
2676			)
2677	{
2678		append_netdev_bled_if("led_wan_gpio", wan_ifname);
2679	}
2680#endif
2681
2682#ifdef RTCONFIG_BWDPI
2683	int debug = nvram_get_int("bwdpi_debug");
2684	int enabled = check_bwdpi_nvram_setting();
2685
2686	if(debug) dbg("[wan up] enabled= %d\n", enabled);
2687
2688	if(enabled){
2689		_dprintf("[%s] do dpi engine service ... \n", __FUNCTION__);
2690		// if Adaptive QoS or AiProtection is enabled
2691		int count = 0;
2692		int val = 0;
2693		while(count < 3){
2694			sleep(1);
2695			val = found_default_route(0);
2696			count++;
2697			if((val == 1) || (count == 3)) break;
2698		}
2699
2700		if(debug) dbg("[wan up] found_default_route result: %d\n", val);
2701
2702		if(val){
2703			// if restart_wan_if, remove dpi engine related
2704			if(f_exists("/dev/detector") || f_exists("/dev/idpfw")){
2705				_dprintf("[%s] stop dpi engine service\n", __FUNCTION__);
2706				stop_dpi_engine_service(0);
2707			}
2708			_dprintf("[%s] start dpi engine service\n", __FUNCTION__);
2709			start_dpi_engine_service();
2710			start_firewall(wan_unit, 0);
2711		}
2712
2713		if(nvram_get_int("qos_enable") == 1 && nvram_get_int("qos_type") != 1){
2714			_dprintf("[wan up] tradtional qos or bandwidth limiter start\n");
2715			start_iQos();
2716		}
2717	}
2718	else{
2719		if(nvram_get_int("qos_enable") == 1 && nvram_get_int("qos_type") != 1){
2720			_dprintf("[wan up] tradtional qos or bandwidth limiter start\n");
2721			start_iQos();
2722		}
2723	}
2724#else
2725	start_iQos();
2726#endif
2727
2728#ifdef RTCONFIG_TR069
2729	start_tr();
2730#endif
2731
2732#ifdef RTCONFIG_GETREALIP
2733#ifdef RTCONFIG_DUALWAN
2734	if(nvram_invmatch("wans_mode", "lb"))
2735#endif
2736	{
2737		char *getip[] = {"getrealip.sh", NULL};
2738		pid_t pid;
2739
2740		//_eval(getip, ">>/tmp/log.txt", 0, &pid);
2741		_eval(getip, ">>/dev/null", 0, &pid);
2742	}
2743#endif
2744
2745#ifdef RTCONFIG_TCPDUMP
2746	eval("killall", "tcpdump");
2747#endif
2748
2749_dprintf("%s(%s): done.\n", __FUNCTION__, wan_ifname);
2750}
2751
2752void
2753wan_down(char *wan_ifname)
2754{
2755	int wan_unit;
2756	char tmp[100], prefix[] = "wanXXXXXXXXXX_";
2757	char *wan_proto, *gateway;
2758	int end_wan_sbstate = WAN_STOPPED_REASON_NONE;
2759
2760	_dprintf("%s(%s)\n", __FUNCTION__, wan_ifname);
2761
2762	/* Skip physical interface of VPN connections */
2763	if ((wan_unit = wan_ifunit(wan_ifname)) < 0)
2764		return;
2765
2766	/* Figure out nvram variable name prefix for this i/f */
2767	if(wan_prefix(wan_ifname, prefix) < 0)
2768		return;
2769
2770	_dprintf("%s(%s): %s.\n", __FUNCTION__, wan_ifname, nvram_safe_get(strcat_r(prefix, "dns", tmp)));
2771
2772#if (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
2773	if(nvram_get_int(strcat_r(prefix, "sbstate_t", tmp)) == WAN_STOPPED_REASON_DATALIMIT)
2774		end_wan_sbstate = WAN_STOPPED_REASON_DATALIMIT;
2775#endif
2776
2777#ifdef RTCONFIG_INTERNAL_GOBI
2778	if(dualwan_unit__usbif(wan_unit))
2779		nvram_unset("usb_modem_act_startsec");
2780#endif
2781
2782#if defined(RTCONFIG_BLINK_LED)
2783	if(dualwan_unit__usbif(wan_unit)
2784			|| ((nvram_get_int("boardflags") & 0x100) && get_dualwan_by_unit(wan_unit) == WANS_DUALWAN_IF_LAN)
2785			)
2786	{
2787		remove_netdev_bled_if("led_wan_gpio", wan_ifname);
2788	}
2789#endif
2790
2791	/* Stop post-authenticator */
2792	stop_auth(wan_unit, 1);
2793
2794	wan_proto = nvram_safe_get(strcat_r(prefix, "proto", tmp));
2795
2796	if (wan_unit == wan_primary_ifunit()) {
2797		/* Stop multicast router when not VPN */
2798		if (strcmp(wan_proto, "dhcp") == 0 ||
2799		    strcmp(wan_proto, "static") == 0) {
2800#ifdef RTCONFIG_MULTICAST_IPTV
2801			if (nvram_get_int("switch_stb_x") > 6 &&
2802			    !nvram_match("switch_wantag", "movistar"))
2803#endif
2804			stop_igmpproxy();
2805		}
2806
2807		/* Remove default route to gateway if specified */
2808		gateway = nvram_safe_get(strcat_r(prefix, "gateway", tmp));
2809		if (inet_addr_(gateway) == INADDR_ANY)
2810			gateway = NULL;
2811		route_del(wan_ifname, 0, "0.0.0.0", gateway, "0.0.0.0");
2812	}
2813
2814	/* Remove interface dependent static routes */
2815	del_wan_routes(wan_ifname);
2816
2817	if (strcmp(wan_proto, "static") == 0)
2818		ifconfig(wan_ifname, IFUP, NULL, NULL);
2819
2820	update_wan_state(prefix, WAN_STATE_DISCONNECTED, end_wan_sbstate);
2821
2822	/* Update resolv.conf
2823	 * Leave as is if no dns servers left for demand to work */
2824	if (*nvram_safe_get(strcat_r(prefix, "xdns", tmp)))
2825		nvram_unset(strcat_r(prefix, "dns", tmp));
2826	update_resolvconf();
2827
2828#ifdef RTCONFIG_DUALWAN
2829	if(nvram_match("wans_mode", "lb"))
2830		add_multi_routes();
2831#endif
2832
2833#ifdef RTCONFIG_GETREALIP
2834#ifdef RTCONFIG_DUALWAN
2835	if(nvram_invmatch("wans_mode", "lb"))
2836#endif
2837	{
2838		nvram_set(strcat_r(prefix, "realip_state", tmp), "0");
2839		nvram_set(strcat_r(prefix, "realip_ip", tmp), "");
2840	}
2841#endif
2842}
2843
2844int
2845wan_ifunit(char *wan_ifname)
2846{
2847	int unit;
2848	char tmp[100], prefix[] = "wanXXXXXXXXXX_";
2849
2850	if ((unit = ppp_ifunit(wan_ifname)) >= 0) {
2851		return unit;
2852	} else {
2853		for (unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; unit++) {
2854			snprintf(prefix, sizeof(prefix), "wan%d_", unit);
2855			if (nvram_match(strcat_r(prefix, "ifname", tmp), wan_ifname) &&
2856			    (nvram_match(strcat_r(prefix, "proto", tmp), "dhcp") ||
2857			     nvram_match(strcat_r(prefix, "proto", tmp), "static")))
2858				return unit;
2859		}
2860#ifdef RTCONFIG_MULTICAST_IPTV
2861		if (nvram_get_int("switch_stb_x") > 6) {
2862			for (unit = WAN_UNIT_IPTV; unit < WAN_UNIT_MULTICAST_IPTV_MAX; unit++) {
2863				snprintf(prefix, sizeof(prefix), "wan%d_", unit);
2864				if (nvram_match(strcat_r(prefix, "ifname", tmp), wan_ifname) &&
2865				    (nvram_match(strcat_r(prefix, "proto", tmp), "dhcp") ||
2866				     nvram_match(strcat_r(prefix, "proto", tmp), "static")))
2867					return unit;
2868			}
2869		}
2870#endif
2871	}
2872
2873	return -1;
2874}
2875
2876int
2877wanx_ifunit(char *wan_ifname)
2878{
2879	int unit;
2880	char tmp[100], prefix[] = "wanXXXXXXXXXX_";
2881
2882	for (unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; unit ++) {
2883		snprintf(prefix, sizeof(prefix), "wan%d_", unit);
2884		if (nvram_match(strcat_r(prefix, "ifname", tmp), wan_ifname) &&
2885		    (nvram_match(strcat_r(prefix, "proto", tmp), "pppoe") ||
2886		     nvram_match(strcat_r(prefix, "proto", tmp), "pptp") ||
2887		     nvram_match(strcat_r(prefix, "proto", tmp), "l2tp")))
2888			return unit;
2889	}
2890#ifdef RTCONFIG_MULTICAST_IPTV
2891	if (nvram_get_int("switch_stb_x") > 6) {
2892		for (unit = WAN_UNIT_IPTV; unit < WAN_UNIT_MULTICAST_IPTV_MAX; unit++) {
2893			snprintf(prefix, sizeof(prefix), "wan%d_", unit);
2894			if (nvram_match(strcat_r(prefix, "ifname", tmp), wan_ifname) &&
2895			    (nvram_match(strcat_r(prefix, "proto", tmp), "pppoe") ||
2896			     nvram_match(strcat_r(prefix, "proto", tmp), "pptp") ||
2897			     nvram_match(strcat_r(prefix, "proto", tmp), "l2tp")))
2898				return unit;
2899		}
2900	}
2901#endif
2902	return -1;
2903}
2904
2905int
2906preset_wan_routes(char *wan_ifname)
2907{
2908	int unit = -1;
2909
2910	if((unit = wan_ifunit(wan_ifname)) < 0)
2911		if((unit = wanx_ifunit(wan_ifname)) < 0)
2912			return -1;
2913
2914	/* Set default route to gateway if specified */
2915	if(unit == wan_primary_ifunit())
2916		route_add(wan_ifname, 0, "0.0.0.0", "0.0.0.0", "0.0.0.0");
2917
2918	/* Install interface dependent static routes */
2919	add_wan_routes(wan_ifname);
2920	return 0;
2921}
2922
2923char *
2924get_lan_ipaddr()
2925{
2926	int s;
2927	struct ifreq ifr;
2928	struct sockaddr_in *inaddr;
2929	struct in_addr ip_addr;
2930
2931	/* Retrieve IP info */
2932	if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0)
2933#if 0
2934		return strdup("0.0.0.0");
2935#else
2936	{
2937		memset(&ip_addr, 0x0, sizeof(ip_addr));
2938		return inet_ntoa(ip_addr);
2939	}
2940#endif
2941
2942	strncpy(ifr.ifr_name, "br0", IFNAMSIZ);
2943	inaddr = (struct sockaddr_in *)&ifr.ifr_addr;
2944	inet_aton("0.0.0.0", &inaddr->sin_addr);
2945
2946	/* Get IP address */
2947	ioctl(s, SIOCGIFADDR, &ifr);
2948	close(s);
2949
2950	ip_addr = ((struct sockaddr_in*)&ifr.ifr_addr)->sin_addr;
2951//	fprintf(stderr, "current LAN IP address: %s\n", inet_ntoa(ip_addr));
2952	return inet_ntoa(ip_addr);
2953}
2954
2955int
2956ppp0_as_default_route()
2957{
2958	int i, n, found;
2959	FILE *f;
2960	unsigned int dest, mask;
2961	char buf[256], device[256];
2962
2963	n = 0;
2964	found = 0;
2965	mask = 0;
2966	device[0] = '\0';
2967
2968	if ((f = fopen("/proc/net/route", "r")) != NULL)
2969	{
2970		while (fgets(buf, sizeof(buf), f) != NULL)
2971		{
2972			if (++n == 1 && strncmp(buf, "Iface", 5) == 0)
2973				continue;
2974
2975			i = sscanf(buf, "%255s %x %*s %*s %*s %*s %*s %x",
2976						device, &dest, &mask);
2977
2978			if (i != 3)
2979				break;
2980
2981			if (device[0] != '\0' && dest == 0 && mask == 0)
2982			{
2983				found = 1;
2984				break;
2985			}
2986		}
2987
2988		fclose(f);
2989
2990		if (found && !strcmp("ppp0", device))
2991			return 1;
2992		else
2993			return 0;
2994	}
2995
2996	return 0;
2997}
2998
2999int
3000found_default_route(int wan_unit)
3001{
3002	int i, n, found;
3003	FILE *f;
3004	unsigned int dest, mask;
3005	char buf[256], device[256];
3006	char *wanif;
3007
3008	if(wan_unit != wan_primary_ifunit())
3009		return 1;
3010
3011	n = 0;
3012	found = 0;
3013	mask = 0;
3014	device[0] = '\0';
3015
3016	if ((f = fopen("/proc/net/route", "r")) != NULL)
3017	{
3018		while (fgets(buf, sizeof(buf), f) != NULL)
3019		{
3020			if (++n == 1 && strncmp(buf, "Iface", 5) == 0)
3021				continue;
3022
3023				i = sscanf(buf, "%255s %x %*s %*s %*s %*s %*s %x",
3024					device, &dest, &mask);
3025
3026			if (i != 3)
3027			{
3028				break;
3029			}
3030
3031			if (device[0] != '\0' && dest == 0 && mask == 0)
3032			{
3033				wanif = get_wan_ifname(wan_unit);
3034				if (!strcmp(wanif, device))
3035				{
3036					found = 1;
3037					break;
3038				}
3039			}
3040		}
3041
3042		fclose(f);
3043
3044		if (found)
3045		{
3046			return 1;
3047		}
3048	}
3049
3050	_dprintf("\nNO default route!!!\n");
3051
3052	return 0;
3053}
3054
3055long print_num_of_connections()
3056{
3057	char buf[256];
3058	char entries[16], others[256];
3059	long num_of_entries;
3060
3061	FILE *fp = fopen("/proc/net/stat/nf_conntrack", "r");
3062	if (!fp) {
3063		fprintf(stderr, "no connection!\n");
3064		return 0;
3065	}
3066
3067	fgets(buf, 256, fp);
3068	fgets(buf, 256, fp);
3069	fclose(fp);
3070
3071	memset(entries, 0x0, 16);
3072	sscanf(buf, "%s %s", entries, others);
3073	num_of_entries = strtoul(entries, NULL, 16);
3074
3075	fprintf(stderr, "connection count: %ld\n", num_of_entries);
3076	return num_of_entries;
3077}
3078
3079void
3080start_wan(void)
3081{
3082#ifdef RTCONFIG_DUALWAN
3083	int unit;
3084#endif
3085
3086#ifdef RTCONFIG_DSL
3087	dsl_configure(1);
3088#endif
3089
3090	if (!is_routing_enabled())
3091		return;
3092
3093	/* Create links */
3094	mkdir("/tmp/ppp", 0777);
3095	mkdir("/tmp/ppp/peers", 0777);
3096	symlink("/sbin/rc", "/tmp/ppp/ip-up");
3097	symlink("/sbin/rc", "/tmp/ppp/ip-down");
3098	symlink("/sbin/rc", "/tmp/ppp/ip-pre-up");
3099#ifdef RTCONFIG_IPV6
3100	symlink("/sbin/rc", "/tmp/ppp/ipv6-up");
3101	symlink("/sbin/rc", "/tmp/ppp/ipv6-down");
3102	symlink("/sbin/rc", "/tmp/dhcp6c");
3103#endif
3104	symlink("/sbin/rc", "/tmp/ppp/auth-fail");
3105#ifdef RTCONFIG_VPNC
3106	symlink("/sbin/rc", "/tmp/ppp/vpnc-ip-up");
3107	symlink("/sbin/rc", "/tmp/ppp/vpnc-ip-down");
3108	symlink("/sbin/rc", "/tmp/ppp/vpnc-ip-pre-up");
3109	symlink("/sbin/rc", "/tmp/ppp/vpnc-auth-fail");
3110#endif
3111	symlink("/sbin/rc", "/tmp/udhcpc");
3112	symlink("/sbin/rc", "/tmp/zcip");
3113#ifdef RTCONFIG_EAPOL
3114	symlink("/sbin/rc", "/tmp/wpa_cli");
3115#endif
3116//	symlink("/dev/null", "/tmp/ppp/connect-errors");
3117
3118	reinit_hwnat(-1);
3119
3120#ifdef RTCONFIG_DUALWAN
3121	/* Start each configured and enabled wan connection and its undelying i/f */
3122	for(unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit){
3123		if(dualwan_unit__nonusbif(unit)){
3124			if(unit == wan_primary_ifunit() || nvram_match("wans_mode", "lb")){
3125				_dprintf("%s: start_wan_if(%d)!\n", __FUNCTION__, unit);
3126				start_wan_if(unit);
3127			}
3128		}
3129	}
3130
3131#ifdef RTCONFIG_MULTICAST_IPTV
3132	/* Start each configured and enabled wan connection and its undelying i/f */
3133	if (nvram_get_int("switch_stb_x") > 6) {
3134		for (unit = WAN_UNIT_IPTV; unit < WAN_UNIT_MULTICAST_IPTV_MAX; ++unit) {
3135			_dprintf("%s: start_wan_if(%d)!\n", __FUNCTION__, unit);
3136			start_wan_if(unit);
3137		}
3138	}
3139#endif
3140#else
3141	_dprintf("%s: start_wan_if(%d)!\n", __FUNCTION__, WAN_UNIT_FIRST);
3142	start_wan_if(WAN_UNIT_FIRST);
3143
3144#ifdef RTCONFIG_USB_MODEM
3145	if(is_usb_modem_ready() == 1 && nvram_get_int("success_start_service") == 1){
3146		_dprintf("%s: start_wan_if(%d)!\n", __FUNCTION__, WAN_UNIT_SECOND);
3147		start_wan_if(WAN_UNIT_SECOND);
3148	}
3149#endif
3150#endif
3151
3152#if LINUX_KERNEL_VERSION >= KERNEL_VERSION(2,6,36)
3153	f_write_string("/proc/sys/net/bridge/bridge-nf-call-iptables", "0", 0, 0);
3154	f_write_string("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "0", 0, 0);
3155#endif
3156
3157	/* Report stats */
3158	if (*nvram_safe_get("stats_server")) {
3159		char *stats_argv[] = { "stats", nvram_safe_get("stats_server"), NULL };
3160		_eval(stats_argv, NULL, 5, NULL);
3161	}
3162}
3163
3164void
3165stop_wan(void)
3166{
3167	int unit;
3168
3169	if (!is_routing_enabled())
3170		return;
3171
3172#ifdef RTCONFIG_RALINK
3173	if (module_loaded("hw_nat"))
3174	{
3175		modprobe_r("hw_nat");
3176		if (!g_reboot)
3177			sleep(1);
3178	}
3179#endif
3180
3181	/* Start each configured and enabled wan connection and its undelying i/f */
3182	for(unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit)
3183		stop_wan_if(unit);
3184
3185#ifdef RTCONFIG_OPENVPN
3186	stop_vpn_eas();
3187#endif
3188#if defined(RTCONFIG_PPTPD) || defined(RTCONFIG_ACCEL_PPTPD)
3189	if (nvram_match("pptpd_enable", "1"))
3190		stop_pptpd();
3191#endif
3192
3193	/* Remove dynamically created links */
3194#ifdef RTCONFIG_EAPOL
3195	unlink("/tmp/wpa_cli");
3196#endif
3197	unlink("/tmp/udhcpc");
3198	unlink("/tmp/zcip");
3199	unlink("/tmp/ppp/ip-up");
3200	unlink("/tmp/ppp/ip-down");
3201	unlink("/tmp/ppp/ip-pre-up");
3202#ifdef RTCONFIG_IPV6
3203	unlink("/tmp/ppp/ipv6-up");
3204	unlink("/tmp/ppp/ipv6-down");
3205	unlink("/tmp/dhcp6c");
3206#endif
3207	unlink("/tmp/ppp/auth-fail");
3208#ifdef RTCONFIG_VPNC
3209	unlink("/tmp/ppp/vpnc-ip-up");
3210	unlink("/tmp/ppp/vpnc-ip-down");
3211	unlink("/tmp/ppp/vpnc-ip-pre-up");
3212	unlink("/tmp/ppp/vpnc-auth-fail");
3213#endif
3214	rmdir("/tmp/ppp");
3215}
3216
3217void convert_wan_nvram(char *prefix, int unit)
3218{
3219	char tmp[100];
3220	char macbuf[32];
3221#if defined(CONFIG_BCMWL5) && defined(RTCONFIG_RGMII_BRCM5301X)
3222	char hwaddr_5g[18];
3223#endif
3224
3225	_dprintf("%s(%s)\n", __FUNCTION__, prefix);
3226
3227	// setup hwaddr
3228	strcpy(macbuf, nvram_safe_get(strcat_r(prefix, "hwaddr_x", tmp)));
3229	if (strlen(macbuf)!=0 && strcasecmp(macbuf, "FF:FF:FF:FF:FF:FF")){
3230		nvram_set(strcat_r(prefix, "hwaddr", tmp), macbuf);
3231		logmessage("wan", "mac clone: [%s] == [%s]\n", tmp, macbuf);
3232	}
3233#ifdef CONFIG_BCMWL5
3234#ifdef RTCONFIG_RGMII_BRCM5301X
3235	else{
3236		/* QTN */
3237		if(strcmp(prefix, "wan1_") == 0){
3238#ifdef RTCONFIG_GMAC3
3239			strcpy(hwaddr_5g, nvram_get_int("gmac3_enable")? nvram_safe_get("et2macaddr"): nvram_safe_get("et1macaddr"));
3240#else
3241			strcpy(hwaddr_5g, nvram_safe_get("et1macaddr"));
3242#endif
3243			inc_mac(hwaddr_5g, 7);
3244			nvram_set(strcat_r(prefix, "hwaddr", tmp), hwaddr_5g);
3245			logmessage("wan", "[%s] == [%s]\n", tmp, hwaddr_5g);
3246		}else{
3247			nvram_set(strcat_r(prefix, "hwaddr", tmp), nvram_safe_get("lan_hwaddr"));
3248			logmessage("wan", "[%s] == [%s]\n", tmp, nvram_safe_get("lan_hwaddr"));
3249		}
3250	}
3251#else
3252	else nvram_set(strcat_r(prefix, "hwaddr", tmp), nvram_safe_get("et0macaddr"));
3253#endif
3254#elif defined(RTCONFIG_QCA)
3255	else nvram_set(strcat_r(prefix, "hwaddr", tmp), nvram_safe_get("et0macaddr"));
3256#elif defined RTCONFIG_RALINK
3257	else nvram_set(strcat_r(prefix, "hwaddr", tmp), nvram_safe_get("et1macaddr"));
3258#endif
3259
3260#ifdef RTCONFIG_MULTICAST_IPTV
3261	if (nvram_get_int("switch_stb_x") > 6 &&
3262	    unit > 9) {
3263		unsigned char ea[6];
3264		ether_atoe(nvram_safe_get("et0macaddr"), ea);
3265		ea[5] = (ea[5] & 0xf0) | ((ea[5] + unit - 9) & 0x0f);
3266		ether_etoa(ea, macbuf);
3267		nvram_set(strcat_r(prefix, "hwaddr", tmp), macbuf);
3268	}
3269#endif
3270	// sync proto
3271	if (nvram_match(strcat_r(prefix, "proto", tmp), "static"))
3272		nvram_set_int(strcat_r(prefix, "dhcpenable_x", tmp), 0);
3273	// backlink unit for ppp
3274	nvram_set_int(strcat_r(prefix, "unit", tmp), unit);
3275}
3276
3277void dumparptable()
3278{
3279	char buf[256];
3280	char ip_entry[32], hw_type[8], flags[8], hw_address[32], mask[32], device[8];
3281	char macbuf[32];
3282
3283	FILE *fp = fopen("/proc/net/arp", "r");
3284	if (!fp) {
3285		fprintf(stderr, "no proc fs mounted!\n");
3286		return;
3287	}
3288
3289	mac_num = 0;
3290
3291	while (fgets(buf, 256, fp) && (mac_num < MAX_MAC_NUM - 2)) {
3292		sscanf(buf, "%s %s %s %s %s %s", ip_entry, hw_type, flags, hw_address, mask, device);
3293
3294		if (!strcmp(device, "br0") && strlen(hw_address)!=0)
3295		{
3296			strcpy(mac_clone[mac_num++], hw_address);
3297		}
3298	}
3299	fclose(fp);
3300
3301	strcpy(macbuf, nvram_safe_get("wan0_hwaddr_x"));
3302
3303	// try pre-set mac
3304	if (strlen(macbuf)!=0 && strcasecmp(macbuf, "FF:FF:FF:FF:FF:FF"))
3305		strcpy(mac_clone[mac_num++], macbuf);
3306
3307	// try original mac
3308#ifdef RTCONFIG_RGMII_BRCM5301X
3309	strcpy(mac_clone[mac_num++], nvram_safe_get("lan_hwaddr"));
3310#else
3311	strcpy(mac_clone[mac_num++], nvram_safe_get("et0macaddr"));
3312#endif
3313
3314	if (mac_num)
3315	{
3316		fprintf(stderr, "num of mac: %d\n", mac_num);
3317		int i;
3318		for (i = 0; i < mac_num; i++)
3319			fprintf(stderr, "mac to clone: %s\n", mac_clone[i]);
3320	}
3321}
3322
3323#ifdef RTCONFIG_QCA_PLC_UTILS
3324#define PLCTOOL_M	"/tmp/plctool-m"
3325int autodet_plc_main(int argc, char *argv[]){
3326	FILE *fd;
3327	char buf[64], *ptr1, *ptr2;
3328	char ifname[8], plc_mac[18], resp_mac[18];
3329	int found = 0, idx = 0, chk = 0, cnt = 0;
3330
3331	memset(ifname, 0, sizeof(ifname));
3332	strcpy(ifname, nvram_safe_get("lan_ifname"));
3333	memset(plc_mac, 0, sizeof(plc_mac));
3334	strcpy(plc_mac, nvram_safe_get("plc_macaddr"));
3335	memset(resp_mac, 0, sizeof(resp_mac));
3336
3337	sprintf(buf, "/usr/local/bin/plctool -i %s -m -e > %s", ifname, PLCTOOL_M);
3338	system(buf);
3339
3340	if ((fd = fopen(PLCTOOL_M, "r")) < 0) {
3341		_dprintf("%s: Can't open %s\n", __func__, PLCTOOL_M);
3342		return -1;
3343	}
3344
3345	// parse content
3346	while (fgets(buf, sizeof(buf), fd) != NULL) {
3347		// check response MAC
3348		if (!found && (ptr1 = strstr(buf, ifname))) {
3349			ptr2 = strstr(buf, " Found ");
3350			if (ptr2) {
3351				idx++;
3352				ptr1 += strlen(ifname) + 1;
3353				strncpy(resp_mac, ptr1, 17);
3354				if (!strncmp(resp_mac, plc_mac, 17))
3355					found = 1;
3356				continue;
3357			}
3358		}
3359
3360		// check amount of member
3361		if (strstr(buf, "network->TEI")) {
3362			idx--;
3363			if (idx == 0) {
3364				cnt++;
3365				chk = 1;
3366			} else
3367				chk = 0;
3368			continue;
3369		}
3370		if (chk && (ptr1 = strstr(buf, "network->STATIONS"))) {
3371			ptr1 += strlen("network->STATIONS") + 3;
3372			cnt += atoi(ptr1);
3373		}
3374	}
3375
3376	fclose(fd);
3377	unlink(PLCTOOL_M);
3378	nvram_set_int("autodet_plc_state" , cnt);
3379
3380	return 0;
3381}
3382#endif
3383
3384int autodet_main(int argc, char *argv[]){
3385	int i;
3386	int unit;
3387	char prefix[]="wanXXXXXX_", tmp[100];
3388	char prefix2[]="autodetXXXXXX_", tmp2[100];
3389	char hwaddr_x[32];
3390	int status;
3391
3392	f_write_string("/tmp/detect_wrong.log", "", 0, 0);
3393	for(unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit){
3394		if(get_dualwan_by_unit(unit) != WANS_DUALWAN_IF_WAN && get_dualwan_by_unit(unit) != WANS_DUALWAN_IF_LAN)
3395			continue;
3396
3397		snprintf(prefix, sizeof(prefix), "wan%d_", unit);
3398		if(unit == WAN_UNIT_FIRST)
3399			snprintf(prefix2, sizeof(prefix2), "autodet_");
3400		else
3401			snprintf(prefix2, sizeof(prefix2), "autodet%d_", unit);
3402
3403		nvram_set_int(strcat_r(prefix2, "state", tmp2), AUTODET_STATE_INITIALIZING);
3404		nvram_set_int(strcat_r(prefix2, "auxstate", tmp2), AUTODET_STATE_INITIALIZING);
3405
3406		// it shouldnot happen, because it is only called in default mode
3407		if(!nvram_match(strcat_r(prefix, "proto", tmp), "dhcp")){
3408			status = discover_all();
3409			if(status == -1)
3410				nvram_set_int(strcat_r(prefix2, "auxstate", tmp2), AUTODET_STATE_FINISHED_NOLINK);
3411			else if(status == 2)
3412				nvram_set_int(strcat_r(prefix2, "auxstate", tmp2), AUTODET_STATE_FINISHED_WITHPPPOE);
3413			else
3414				nvram_set_int(strcat_r(prefix2, "auxstate", tmp2), AUTODET_STATE_FINISHED_OK);
3415
3416			nvram_set_int(strcat_r(prefix2, "state", tmp2), AUTODET_STATE_FINISHED_NODHCP);
3417			continue;
3418		}
3419
3420		// TODO: need every unit of WAN to do the autodet?
3421		if(!get_wanports_status(unit)){
3422			nvram_set_int(strcat_r(prefix2, "state", tmp2), AUTODET_STATE_FINISHED_NOLINK);
3423			continue;
3424		}
3425
3426		if(get_wan_state(unit) == WAN_STATE_CONNECTED){
3427			i = nvram_get_int(strcat_r(prefix, "lease", tmp));
3428
3429			if(i < 60 && is_private_subnet(strcat_r(prefix, "ipaddr", tmp))){
3430				sleep(i);
3431			}
3432			//else{
3433			//	nvram_set_int(strcat_r(prefix2, "state", tmp2), AUTODET_STATE_FINISHED_OK);
3434			//	continue;
3435			//}
3436		}
3437
3438		status = discover_all();
3439
3440		// check for pppoe status only,
3441		if(get_wan_state(unit) == WAN_STATE_CONNECTED){
3442			nvram_set_int(strcat_r(prefix2, "state", tmp2), AUTODET_STATE_FINISHED_OK);
3443			if(status == 2)
3444				nvram_set_int(strcat_r(prefix2, "auxstate", tmp2), AUTODET_STATE_FINISHED_WITHPPPOE);
3445			continue;
3446		}
3447		else if(status == 2){
3448			nvram_set_int(strcat_r(prefix2, "state", tmp2), AUTODET_STATE_FINISHED_WITHPPPOE);
3449			continue;
3450		}
3451
3452		nvram_set_int(strcat_r(prefix2, "state", tmp2), AUTODET_STATE_CHECKING);
3453
3454		dumparptable();
3455
3456		// backup hwaddr_x
3457		strcpy(hwaddr_x, nvram_safe_get(strcat_r(prefix, "hwaddr_x", tmp)));
3458		//nvram_set(strcat_r(prefix, "hwaddr_x", tmp), "");
3459
3460		char *ptr = nvram_safe_get(strcat_r(prefix2, "waitsec", tmp2));
3461		int waitsec = 0;
3462
3463		if(ptr == NULL || strlen(ptr) <= 0)
3464			waitsec = 5;
3465		else
3466			waitsec = atoi(ptr);
3467
3468		i = 0;
3469		while(i < mac_num && get_wan_state(unit) != WAN_STATE_CONNECTED){
3470			if(!(nvram_match("wl0_country_code", "SG"))){ // Singpore do not auto clone
3471				_dprintf("try clone %s\n", mac_clone[i]);
3472				nvram_set(strcat_r(prefix, "hwaddr_x", tmp), mac_clone[i]);
3473			}
3474			char buf[32];
3475			snprintf(buf, 32, "restart_wan_if %d", unit);
3476			notify_rc_and_wait(buf);
3477			_dprintf("%s: wait a IP during %d seconds...\n", __FUNCTION__, waitsec);
3478			int count = 0;
3479			while(count < waitsec && get_wan_state(unit) != WAN_STATE_CONNECTED){
3480				sleep(1);
3481
3482				++count;
3483			}
3484			++i;
3485		}
3486
3487		if(i == mac_num){
3488			nvram_set_int(strcat_r(prefix2, "state", tmp2), AUTODET_STATE_FINISHED_FAIL);
3489			// restore hwaddr_x
3490			nvram_set(strcat_r(prefix, "hwaddr_x", tmp), hwaddr_x);
3491		}
3492		else if(i == mac_num-1){ // OK in original mac
3493			nvram_set_int(strcat_r(prefix2, "state", tmp2), AUTODET_STATE_FINISHED_OK);
3494		}
3495		else{ // OK in cloned mac
3496			nvram_set_int(strcat_r(prefix2, "state", tmp2), AUTODET_STATE_FINISHED_OK);
3497		}
3498		nvram_commit();
3499	}
3500
3501	return 0;
3502}
3503
3504#include <setjmp.h>
3505static sigjmp_buf jmpbuf;
3506
3507void alarm_func(){
3508	siglongjmp(jmpbuf, 1);
3509}
3510
3511#include <netdb.h>
3512
3513struct hostent *timeGethostbyname(const char *domain, int timeout){
3514	struct hostent *ipHostent = NULL;
3515
3516	signal(SIGALRM, alarm_func);
3517
3518	if(sigsetjmp(jmpbuf, 1) != 0){
3519		alarm(0); //timout
3520
3521		signal(SIGALRM, SIG_IGN);
3522
3523		return NULL;
3524	}
3525
3526	alarm(timeout); //setting alarm
3527
3528	ipHostent = gethostbyname(domain);
3529
3530	signal(SIGALRM, SIG_IGN);
3531
3532	return ipHostent;
3533}
3534
3535int do_dns_detect(){
3536	char *test_url = "www.google.com www.baidu.com www.yandex.com";
3537	char word[64], *next;
3538
3539	foreach(word, test_url, next){
3540		if(nvram_get_int("old_resolve") > 0){
3541			_dprintf("do_dns_detect old: %s.\n", word);
3542			if(gethostbyname(word) != NULL){
3543				nvram_set_int("link_internet", 2);
3544				return 1;
3545			}
3546		}
3547		else{
3548			_dprintf("do_dns_detect new: %s.\n", word);
3549			if(timeGethostbyname(word, 2) != NULL){
3550				nvram_set_int("link_internet", 2);
3551				return 1;
3552			}
3553		}
3554	}
3555
3556	_dprintf("do_dns_detect: fail to resolve the dns.\n");
3557	nvram_set_int("link_internet", 1);
3558
3559	return 0;
3560}
3561