1/*
2 * Miscellaneous services
3 *
4 * Copyright (C) 2009, Broadcom Corporation. All Rights Reserved.
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
13 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
15 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
16 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 *
18 * $Id: services.c,v 1.100 2010/03/04 09:39:18 Exp $
19 */
20
21#include <stdio.h>
22#include <stdlib.h>
23#include <string.h>
24#include <unistd.h>
25#include <errno.h>
26#include <sys/time.h>
27#include <time.h>
28#include <bcmnvram.h>
29#include <shutils.h>
30#include <sys/types.h>
31#include <dirent.h>
32#include <sys/mount.h>
33#include <sys/vfs.h>
34#include <rc.h>
35#include <arpa/inet.h>
36#include <time.h>
37#include <sys/time.h>
38#include <sys/reboot.h>
39#include <errno.h>
40#include <sys/stat.h>
41#include <sys/utsname.h>
42#include <sys/param.h>
43#include <net/ethernet.h>
44
45#ifdef RTCONFIG_RALINK
46#include <ralink.h>
47#endif
48#ifdef RTCONFIG_QCA
49#include <qca.h>
50#endif
51#include <shared.h>
52#ifdef RTCONFIG_DSL
53#include <dsl-upg.h>
54#endif
55#ifdef RTCONFIG_USB
56#include <disk_io_tools.h>	//mkdir_if_none()
57#else
58#ifdef RTCONFIG_MDNS
59extern int mkdir_if_none(const char *path)
60{
61	DIR *dp;
62	char cmd[PATH_MAX];
63
64	if (!(dp = opendir(path))) {
65		memset(cmd, 0, PATH_MAX);
66		sprintf(cmd, "mkdir -m 0777 -p '%s'", (char *)path);
67		system(cmd);
68		return 1;
69	}
70	closedir(dp);
71
72	return 0;
73}
74#endif
75#endif	/* RTCONFIG_USB */
76
77#ifdef RTCONFIG_QTN
78#include "web-qtn.h"
79#endif
80
81#ifdef RTCONFIG_HTTPS
82#include <errno.h>
83#include <getopt.h>
84#include <openssl/sha.h>
85#include <openssl/evp.h>
86#include <openssl/pem.h>
87#include <openssl/rsa.h>
88#endif
89
90#ifdef RTCONFIG_QCA_PLC_UTILS
91#include <plc_utils.h>
92#endif
93extern char *crypt __P((const char *, const char *)); //should be defined in unistd.h with _XOPEN_SOURCE defined
94#define sin_addr(s) (((struct sockaddr_in *)(s))->sin_addr)
95
96/* The g_reboot global variable is used to skip several unnecessary delay
97 * and redundant steps during reboot / restore to default procedure.
98 */
99int g_reboot = 0;
100
101// Pop an alarm to recheck pids in 500 msec.
102static const struct itimerval pop_tv = { {0,0}, {0, 500 * 1000} };
103
104// Pop an alarm to reap zombies.
105static const struct itimerval zombie_tv = { {0,0}, {307, 0} };
106
107// -----------------------------------------------------------------------------
108
109static const char dmhosts[] = "/etc/hosts.dnsmasq";
110static const char dmresolv[] = "/tmp/resolv.conf";
111static const char dmservers[] = "/tmp/resolv.dnsmasq";
112
113#ifdef RTCONFIG_TOAD
114static void start_toads(void);
115static void stop_toads(void);
116#endif
117
118#ifndef MS_MOVE
119#define MS_MOVE		8192
120#endif
121#ifndef MNT_DETACH
122#define MNT_DETACH	0x00000002
123#endif
124
125#ifdef BCMDBG
126#include <assert.h>
127#else
128#define assert(a)
129#endif
130
131#define logs(s) syslog(LOG_NOTICE, s)
132
133#if 0
134static char
135*make_var(char *prefix, int index, char *name)
136{
137	static char buf[100];
138
139	assert(prefix);
140	assert(name);
141
142	if (index)
143		snprintf(buf, sizeof(buf), "%s%d%s", prefix, index, name);
144	else
145		snprintf(buf, sizeof(buf), "%s%s", prefix, name);
146	return buf;
147}
148
149static int is_wet(int idx, int unit, int subunit, void *param)
150{
151	return nvram_match(wl_nvname("mode", unit, subunit), "wet");
152}
153#endif
154
155#define TMP_ROOTFS_MNT_POINT	"/sysroot"
156/* Build temporarily rootfilesystem
157 * @newroot:	Mount point of new root filesystem.
158 * @return:
159 * 	0:	success
160 *     -1:	mount tmp filesystem fail
161 *     -2:	copy files fail
162 *     -3:	make directory fail
163 *
164 * WARNING
165 * ==========================================================================
166 *  YOU HAVE TO HANDLE THIS FUNCTION VERY CAREFUL.  IF YOU MISS FILE(S) THAT
167 *  ARE NEED BY init PROCESS, e.g. /usr/lib/libnvram.so,
168 *  KERNEL REBOOTS SYSTEM IN 3 SECONDS.  ERROR MESSAGE IS SHOWN BELOW:
169 * ==========================================================================
170 * Image successfully flashed
171 * Kernel panic - not syncing: Attempted to kill init!
172 * Rebooting in 3 seconds..
173 * /sbin/init: can't load library 'libnvram.so'
174 */
175#if defined(RTCONFIG_TEMPROOTFS)
176static int remove_tail_char(char *str, char c)
177{
178	char *p;
179
180	if (!str || *str == '\0' || c == '\0')
181		return -1;
182
183	for (p = str + strlen(str); p >= str && *p == c; p--)
184		*p = '\0';
185	if (p == str)
186		return -2;
187
188	return 0;
189}
190
191/*
192 * @param:	extra parameter of cp command
193 * @dir:	base directory
194 * @files:	files, e.g., "fileA fileB fileC"
195 * @newroot:	new root directory
196 * @return:
197 * 	0:	success
198 *
199 * 1. cp("", "/bin", "fileA fileB fileC", "/sysroot") equals to below commands:
200 *    a. mkdir -p /sysroot/bin
201 *    b. cp -a /bin/fileA /bin/fileB /bin/fileC /sysroot/bin
202 *
203 * 2. cp("L", "/usr/bin", "" or NULL, "/sysroot") equals to below commands:
204 *    a. if [ -e "/sysroot/usr/bin" ] ; then rmdir "/sysroot/usr/bin" ; fi
205 *    b. mkdir -p `dirname /sysroot/usr/bin`
206 *    c. cp -aL /usr/bin /sysroot
207 */
208static int __cp(const char *param, const char *dir, const char *files, const char *newroot)
209{
210	struct stat st;
211	const char *sep = "/";
212	int i, l, len = 0, len2 = 0, mode = 0;	/* copy files and sub-directory */
213	char cmd[2048], *f, *p, *token, *ptr1;
214	char d[PATH_MAX], dest_dir[PATH_MAX];
215	char str1[] = "cp -afXXXXXXXXXXXXXYYY";
216	const char delim[] = " ";
217
218	if (!dir || !newroot || *newroot == '\0')
219		return -1;
220
221	if (!files || *files == '\0')
222		mode = 1;	/* copy a directory recursive */
223
224	if (!param)
225		param = "";
226
227	sprintf(str1, "cp -af%s", param);
228	if (dir && *dir == '/')
229		sep = "";
230	sprintf(dest_dir, "%s", newroot);
231	if (stat(dest_dir, &st) || !S_ISDIR(st.st_mode))
232		return -2;
233
234	switch (mode) {
235	case 0:	/* copy files and sub-directory */
236		if (!(f = strdup(files)))
237			return -3;
238		if (*dir != '\0') {
239			sprintf(dest_dir, "%s%s%s", newroot, sep, dir);
240			if (!d_exists(dest_dir))
241				eval("mkdir", "-p", dest_dir);
242			else if (!S_ISDIR(st.st_mode)) {
243				_dprintf("%s exist and is not a directory!\n", dest_dir);
244				return -4;
245			}
246		}
247
248		strcpy(cmd, str1);
249		len = strlen(cmd);
250		p = cmd + len;
251		len2 = strlen(dest_dir) + 2;	/* leading space + tail NULL */
252		len += len2;
253		for (i = l = 0, token = strtok_r(f, delim, &ptr1);
254			token != NULL;
255			token = strtok_r(NULL, delim, &ptr1), p += l, len += l)
256		{
257			sprintf(d, "%s/%s", dir, token);
258			/* don't check existence if '?' or '*' exist */
259			if (!strchr(d, '?') && !strchr(d, '*') && stat(d, &st) < 0) {
260				_dprintf("%s: %s not exist, skip!\n", __func__, d);
261				l = 0;
262				continue;
263			}
264
265			l = strlen(d) + 1;
266			if ((len + l) < sizeof(cmd)) {
267				strcat(p, " ");
268				strcat(p, d);
269				++i;
270				continue;
271			}
272
273			/* cmd buffer is not enough, flush */
274			strcat(p, " ");
275			strcat(p, dest_dir);
276			system(cmd);
277
278			strcpy(cmd, str1);
279			len = strlen(cmd);
280			p = cmd + len;
281			len += len2;
282
283			strcat(p, " ");
284			strcat(p, d);
285			i = 1;
286		}
287
288		if (i > 0) {
289			strcat(p, " ");
290			strcat(p, dest_dir);
291			system(cmd);
292		}
293		free(f);
294		break;
295	case 1:	/* copy a directory recursive */
296		/* If /newroot/bin exist and is directory, rmdir /newroot/bin.
297		 * If not, /bin would be copied to newroot/bin/bin.
298		 */
299		if (*dir == '\0')
300			return -10;
301
302		sprintf(dest_dir, "%s%s%s", newroot, sep, dir);
303		if (d_exists(dest_dir)) {
304			_dprintf("%s exist, remove it\n", dest_dir);
305			if (rmdir(dest_dir)) {
306				_dprintf("rmdir %s (%s)\n", dest_dir, strerror(errno));
307				return -11;
308			}
309		}
310
311		/* remove tail '/' */
312		strcpy(d, dest_dir);
313		remove_tail_char(d, '/');
314
315		/* make sure parent directory of destination directory exist */
316		p = strrchr(d, '/');
317		if (p && p != d) {
318			*p = '\0';
319			remove_tail_char(d, '/');
320			if (!d_exists(d))
321				eval("mkdir", "-p", d);
322		}
323		sprintf(cmd, "%s %s %s", str1, dir, dest_dir);
324		system(cmd);
325
326		break;
327	default:
328		_dprintf("%s: mode %d is not defined!\n", __func__, mode);
329		return -4;
330	}
331
332	return 0;
333}
334
335/* Build a temporary rootfilesystem.
336 *
337 * If you add new binary to temp. rootfilesystem, check whether it needs another library!
338 * For example, iwpriv needs libiw.so.29, libgcc_s.so.1, and libc.so.0:
339 * $ mipsel-linux-objdump -x bin/iwpriv | grep NEED
340 *   NEEDED               libiw.so.29
341 *   NEEDED               libgcc_s.so.1
342 *   NEEDED               libc.so.0
343 *   VERNEED              0x004008d4
344 *   VERNEEDNUM           0x00000001
345 */
346static int build_temp_rootfs(const char *newroot)
347{
348	int i, r;
349	struct stat st;
350	char d1[PATH_MAX], d2[1024];
351	const char *mdir[] = { "/proc", "/tmp", "/sys", "/usr", "/var", "/var/lock" };
352	const char *bin = "ash busybox cat cp dd df echo grep iwpriv kill ls ps mkdir mount nvram ping sh tar umount uname";
353	const char *sbin = "init rc hotplug2 insmod lsmod modprobe reboot rmmod rtkswitch";
354	const char *lib = "librt*.so* libnsl* libdl* libm* ld-* libiw* libgcc* libpthread* libdisk* libc*";
355	const char *usrbin = "killall";
356#ifdef RTCONFIG_BCMARM
357	const char *usrsbin = "nvram";
358#endif
359	const char *usrlib = "libnvram.so libshared.so libcrypto.so* libbcm*"
360#if defined(RTCONFIG_HTTPS) || defined(RTCONFIG_PUSH_EMAIL)
361			     " libssl*"
362#endif
363		;
364	const char *kmod = "find /lib/modules -name '*.ko'|"
365		"grep '\\("
366#if defined(RTCONFIG_BLINK_LED)
367		"bled\\|"			/* bled.ko */
368		"usbcore\\|"			/* usbcore.ko */
369#if LINUX_KERNEL_VERSION >= KERNEL_VERSION(3,2,0)
370		"usb-common\\|"			/* usb-common.ko, kernel 3.2 or above */
371#endif
372#endif
373		"nvram_linux\\)";		/* nvram_linux.ko */
374
375	if (!newroot || *newroot == '\0')
376		newroot = TMP_ROOTFS_MNT_POINT;
377
378	if ((r = mount("tmpfs", newroot, "tmpfs", MS_NOATIME, "")) != 0)
379		return -1;
380
381	_dprintf("Build temp rootfs\n");
382	__cp("", "/dev", "", newroot);
383	__cp("", "/lib/modules", "modules.dep", newroot);
384	__cp("", "/bin", bin, newroot);
385	__cp("", "/sbin", sbin, newroot);
386	__cp("", "/lib", lib, newroot);
387	__cp("", "/lib", "libcrypt*", newroot);
388	__cp("", "/usr/bin", usrbin, newroot);
389#ifdef RTCONFIG_BCMARM
390	__cp("", "/usr/sbin", usrsbin, newroot);
391#endif
392	__cp("", "/usr/lib", usrlib, newroot);
393	__cp("L", "/etc", "", newroot);		/* don't creat symbolic link (/tmp/etc/foo) that will be broken soon */
394
395#if defined(RTCONFIG_QCA)
396	__cp("", "/sbin", "wlanconfig", newroot);
397	__cp("", "/usr/lib", "libnl-tiny.so", newroot);
398	__cp("", "/usr/sbin", "swconfig", newroot);
399#endif
400
401	/* copy mandatory kernel modules */
402	sprintf(d2, "tar cvf - `%s` | tar xf - -C %s", kmod, newroot);
403	system(d2);
404
405	/* make directory, if not exist */
406	for (i = 0; i < ARRAY_SIZE(mdir); ++i) {
407		sprintf(d1, "%s/%s", newroot, mdir[i]);
408		if (stat(d1, &st) && (r = mkdir(d1, 0755) == -1))
409			return -3;
410	}
411
412	return 0;
413}
414
415/* Switch rootfilesystem to newroot.
416 * @newroot:	Mount point of new root filesystem.
417 * @return:
418 * 	-1:	Not init process.
419 * 	-2:	chdir to newroot fail
420 * 	-3:	Newroot is not a mount point
421 * 	-4:	Move mount point to / fail
422 * 	-5:	exec new init process fail
423 */
424static int switch_root(const char *newroot)
425{
426	int r;
427	dev_t rdev;
428	struct stat st;
429	char *const argv[] = { "/sbin/init", "reboot", NULL };
430
431	if (!newroot || *newroot == '\0')
432		newroot = TMP_ROOTFS_MNT_POINT;
433
434	if (getpid() != 1) {
435		_dprintf("%s: PID != 1\n", __func__);
436		return -1;
437	}
438
439	if (chdir(newroot))
440		return -2;
441	stat("/", &st);
442	rdev = st.st_dev;
443	stat(".", &st);
444	if (rdev == st.st_dev)
445		return -3;
446
447	/* emulate switch_root command */
448	if ((r = mount(".", "/", NULL, MS_MOVE, NULL)) != 0)
449		return -4;
450
451	chroot(".");
452	chdir("/");
453
454	/* WARNING:
455	 * If new rootfilesystem lacks libraries that are need by init process,
456	 * kernel reboots system in 3 seconds.
457	 */
458	if ((r = execv(argv[0], argv)))
459		return -5;
460
461	/* NEVER REACH HERE */
462	return 0;
463}
464#else	/* !RTCONFIG_TEMPROOTFS */
465static inline int build_temp_rootfs(const char *newroot) { return -999; }
466static inline int switch_root(const char *newroot) { return -999; }
467#endif	/* RTCONFIG_TEMPROOTFS */
468
469void setup_passwd(void)
470{
471	create_passwd();
472}
473
474void create_passwd(void)
475{
476	char s[512];
477	char *p;
478	char salt[32];
479	FILE *f;
480	mode_t m;
481	char *http_user;
482
483#ifdef RTCONFIG_SAMBASRV	//!!TB
484	char *smbd_user;
485
486	create_custom_passwd();
487#endif
488#ifdef RTCONFIG_OPENVPN
489	mkdir_if_none("/etc/pam.d");
490	f_write_string("/etc/pam.d/openvpn",
491		"auth required pam_unix.so\n",
492		0, 0644);
493	create_openvpn_passwd();
494#endif
495
496	strcpy(salt, "$1$");
497	f_read("/dev/urandom", s, 6);
498	base64_encode((unsigned char *) s, salt + 3, 6);
499	salt[3 + 8] = 0;
500	p = salt;
501	while (*p) {
502		if (*p == '+') *p = '.';
503		++p;
504	}
505	if (((p = nvram_get("http_passwd")) == NULL) || (*p == 0)) p = "admin";
506
507	if (((http_user = nvram_get("http_username")) == NULL) || (*http_user == 0)) http_user = "admin";
508
509#ifdef RTCONFIG_SAMBASRV	//!!TB
510	if (((smbd_user = nvram_get("smbd_user")) == NULL) || (*smbd_user == 0) || !strcmp(smbd_user, "root"))
511		smbd_user = "nas";
512#endif
513
514	m = umask(0777);
515	if ((f = fopen("/etc/shadow", "w")) != NULL) {
516		p = crypt(p, salt);
517		fprintf(f, "%s:%s:0:0:99999:7:0:0:\n"
518			   "nobody:*:0:0:99999:7:0:0:\n", http_user, p);
519#ifdef RTCONFIG_SAMBASRV	//!!TB
520		fprintf(f, "%s:*:0:0:99999:7:0:0:\n", smbd_user);
521#endif
522
523		fappend(f, "/etc/shadow.custom");
524#ifdef RTCONFIG_OPENVPN
525		fappend(f, "/etc/shadow.openvpn");
526#endif
527		fclose(f);
528	}
529	umask(m);
530	chmod("/etc/shadow", 0600);
531
532#ifdef RTCONFIG_SAMBASRV	//!!TB
533	sprintf(s,
534		"%s:x:0:0:%s:/root:/bin/sh\n"
535		"%s:x:100:100:nas:/dev/null:/dev/null\n"
536		"nobody:x:65534:65534:nobody:/dev/null:/dev/null\n",
537		http_user,
538		http_user,
539		smbd_user);
540#else	//!!TB
541	sprintf(s,
542		"%s:x:0:0:%s:/root:/bin/sh\n"
543		"nobody:x:65534:65534:nobody:/dev/null:/dev/null\n",
544		http_user,
545		http_user);
546#endif	//!!TB
547	f_write_string("/etc/passwd", s, 0, 0644);
548	fappend_file("/etc/passwd", "/etc/passwd.custom");
549#ifdef RTCONFIG_OPENVPN
550	fappend_file("/etc/passwd", "/etc/passwd.openvpn");
551#endif
552
553	sprintf(s,
554		"%s:*:0:\n"
555#ifdef RTCONFIG_SAMBASRV	//!!TB
556		"nas:*:100:\n"
557#endif
558		"nobody:*:65534:\n",
559		http_user);
560	f_write_string("/etc/gshadow", s, 0, 0644);
561	fappend_file("/etc/gshadow", "/etc/gshadow.custom");
562
563	f_write_string("/etc/group",
564		"root:x:0:\n"
565#ifdef RTCONFIG_SAMBASRV	//!!TB
566		"nas:x:100:\n"
567#endif
568		"nobody:x:65534:\n",
569		0, 0644);
570	fappend_file("/etc/group", "/etc/group.custom");
571#ifdef RTCONFIG_OPENVPN
572	fappend_file("/etc/group", "/etc/group.openvpn");
573#endif
574}
575
576#ifdef CONFIG_BCMWL5
577int ate_cond()
578{
579	switch(get_model()){
580		case MODEL_RPAC68U:
581			if (factory_debug())
582				return 0;
583			break;
584		default:
585			break;
586	}
587
588	return 1;
589}
590#endif
591
592void get_dhcp_pool(char **dhcp_start, char **dhcp_end, char *buffer)
593{
594	if (dhcp_start == NULL || dhcp_end == NULL || buffer == NULL)
595		return;
596
597#ifdef RTCONFIG_WIRELESSREPEATER
598	if(nvram_get_int("sw_mode") == SW_MODE_REPEATER && nvram_get_int("wlc_state") != WLC_STATE_CONNECTED){
599		if(nvram_match("lan_proto", "static")) {
600			in_addr_t lan_ipaddr, lan_netmask;
601			char *p = buffer;
602			unsigned char lan1[4], lan2[4];
603			unsigned offset;
604
605			inet_aton(nvram_safe_get("lan_ipaddr") , (struct in_addr*) &lan_ipaddr);
606			inet_aton(nvram_safe_get("lan_netmask"), (struct in_addr*) &lan_netmask);
607//			cprintf("#### lan_ipaddr(%08x) lan_netmask(%08x)\n", lan_ipaddr, lan_netmask);
608
609			//start
610			if ((ntohl(lan_ipaddr & lan_netmask) | 1 ) == ntohl(lan_ipaddr))
611				offset = 2;
612			else
613				offset = 1;
614			*(in_addr_t *) &lan1 = (lan_ipaddr & lan_netmask) | htonl(offset);
615			*dhcp_start = p;
616			p += sprintf(p, "%u.%u.%u.%u", lan1[0], lan1[1], lan1[2], lan1[3]);
617			p += 1;
618
619			//end
620			if ((ntohl(lan_ipaddr & lan_netmask) | 254) == ntohl(lan_ipaddr))
621				offset = 253;
622			else
623				offset = 254;
624			*((in_addr_t *) &lan2) = (lan_ipaddr & lan_netmask) | htonl(offset);
625			*dhcp_end = p;
626			p += sprintf(p, "%u.%u.%u.%u", lan2[0], lan2[1], lan2[2], lan2[3]);
627			p += 1;
628
629//			cprintf("#### dhcp_start(%s) dhcp_end(%s)\n", *dhcp_start, *dhcp_end);
630		} else {
631			*dhcp_start = nvram_default_get("dhcp_start");
632			*dhcp_end = nvram_default_get("dhcp_end");
633		}
634	}
635	else
636#endif
637	{
638		*dhcp_start = nvram_safe_get("dhcp_start");
639		*dhcp_end = nvram_safe_get("dhcp_end");
640	}
641}
642
643#if 0
644int get_dhcpd_lmax()
645{
646	unsigned int lstart, lend, lip;
647	int dhlease_size, invalid_ipnum, except_lanip;
648	char *dhcp_start, *dhcp_end, *lan_netmask, *lan_ipaddr;
649	char buffer[64];
650
651	get_dhcp_pool(&dhcp_start, &dhcp_end, buffer);
652#ifdef RTCONFIG_WIRELESSREPEATER
653	if(nvram_get_int("sw_mode") == SW_MODE_REPEATER && nvram_get_int("wlc_state") != WLC_STATE_CONNECTED){
654		lan_netmask = nvram_default_get("lan_netmask");
655		lan_ipaddr = nvram_default_get("lan_ipaddr");
656	}
657	else
658#endif
659	{
660		lan_netmask = nvram_safe_get("lan_netmask");
661		lan_ipaddr = nvram_safe_get("lan_ipaddr");
662	}
663
664	lstart = htonl(inet_addr(dhcp_start)) & ~htonl(inet_addr(lan_netmask));
665	lend = htonl(inet_addr(dhcp_end)) & ~htonl(inet_addr(lan_netmask));
666	lip = htonl(inet_addr(lan_ipaddr)) & ~htonl(inet_addr(lan_netmask));
667
668	dhlease_size = lend - lstart + 1;
669	invalid_ipnum = dhlease_size / 256 * 2;
670	except_lanip = (lip >= lstart && lip <= lend)? 1:0;
671	dhlease_size -= invalid_ipnum + except_lanip;
672
673	return dhlease_size;
674}
675#endif
676
677void stop_hour_monitor_service()
678{
679	//logmessage("hour monitor", "stop_hour_monitor_service");
680	killall("hour_monitor", SIGTERM);
681}
682
683void start_hour_monitor_service()
684{
685	char *cmd[] = {"hour_monitor", NULL};
686	int pid;
687
688	if(nvram_get_int("sw_mode") != SW_MODE_ROUTER)
689		return;
690
691	if (!nvram_get_int("ntp_ready"))
692		return;
693
694	if(!pids("hour_monitor")){
695	//logmessage("hour monitor", "start again due to not pid");
696		_eval(cmd, NULL, 0, &pid);
697	}
698}
699
700void check_hour_monitor_service()
701{
702	if(hour_monitor_function_check()) start_hour_monitor_service();
703}
704
705#ifdef RTCONFIG_DHCP_OVERRIDE
706static int chk_same_subnet(char *ip1, char *ip2, char *sub)
707{
708	unsigned int addr1, addr2, submask;
709
710	if (!*ip1 || !*ip2 || !*sub)
711		return 0;
712
713	addr1 = ntohl(inet_addr(ip1));
714	addr2 = ntohl(inet_addr(ip2));
715	submask = ntohl(inet_addr(sub));
716
717	return (addr1 & submask) == (addr2 & submask);
718}
719
720static void simple_dhcp_range(char *ip, char *dip1, char *dip2, char *mask)
721{
722	struct in_addr ina;
723	unsigned int new_start, new_end, lmask;
724
725	new_start = (ntohl(inet_addr(ip)) & (lmask = ntohl(inet_addr(mask)))) + 1;
726	new_end = ntohl(inet_addr(ip)) & (lmask = ntohl(inet_addr(mask))) | ~(lmask) - 1;
727
728	ina.s_addr = htonl(new_start);
729	strcpy(dip1, inet_ntoa(ina));
730	ina.s_addr = htonl(new_end);
731	strcpy(dip2, inet_ntoa(ina));
732}
733
734static int chk_valid_startend(char *ip, char *ip1, char *ip2, char *sub)
735{
736	int result1, result2;
737
738	result1 = chk_same_subnet(ip, ip1, sub);
739	result2 = chk_same_subnet(ip, ip2, sub);
740
741	if (!result1 || !result2) {
742		simple_dhcp_range(ip, ip1, ip2, sub);
743		return 0;
744	}
745	return 1;
746}
747
748static void link_down(void)
749{
750	char word[256], *next, ifnames[128];
751
752	/* link down LAN ports */
753	eval("rtkswitch", "15");
754
755	/* ifconfig down wireless */
756	strcpy(ifnames, nvram_safe_get("wl_ifnames"));
757	foreach (word, ifnames, next)
758		ifconfig(word, 0, NULL, NULL);
759}
760
761static void link_up(void)
762{
763	char word[256], *next, ifnames[128];
764
765	/* link up LAN ports */
766	eval("rtkswitch", "14");
767
768	/* ifconfig up wireless */
769	strcpy(ifnames, nvram_safe_get("wl_ifnames"));
770	foreach (word, ifnames, next)
771		ifconfig(word, IFUP, NULL, NULL);
772}
773
774int restart_dnsmasq(int need_link_DownUp)
775{
776	if (need_link_DownUp) {
777#if (defined(PLN12) || defined(PLAC56) || defined(PLAC66))
778		nvram_set("plc_ready", "0");
779#endif
780		link_down();
781		sleep(9);
782	}
783
784	stop_dnsmasq();
785	sleep(1);
786	start_dnsmasq();
787
788	if (need_link_DownUp) {
789		link_up();
790#if (defined(PLN12) || defined(PLAC56) || defined(PLAC66))
791		nvram_set("plc_ready", "1");
792#endif
793	}
794
795	return 0;
796}
797#endif
798
799void start_dnsmasq(void)
800{
801	FILE *fp;
802	char *lan_ifname, *lan_ipaddr;
803	char *value;
804	int /*i,*/ have_dhcp = 0;
805
806	TRACE_PT("begin\n");
807
808	if (getpid() != 1) {
809		notify_rc("start_dnsmasq");
810		return;
811	}
812
813	stop_dnsmasq();
814
815	lan_ifname = nvram_safe_get("lan_ifname");
816#ifdef RTCONFIG_WIRELESSREPEATER
817	if (nvram_get_int("sw_mode") == SW_MODE_REPEATER && nvram_get_int("wlc_state") != WLC_STATE_CONNECTED && !nvram_match("lan_proto", "static")) {
818		lan_ipaddr = nvram_default_get("lan_ipaddr");
819	} else
820#endif
821	{
822		lan_ipaddr = nvram_safe_get("lan_ipaddr");
823	}
824
825	/* write /etc/hosts */
826	if ((fp = fopen("/etc/hosts", "w")) != NULL) {
827		/* loclhost ipv4 */
828		fprintf(fp, "127.0.0.1 localhost.localdomain localhost\n");
829		fprintf(fp, "%s %s\n", lan_ipaddr, DUT_DOMAIN_NAME);
830		fprintf(fp, "%s %s\n", lan_ipaddr, OLD_DUT_DOMAIN_NAME1);
831		fprintf(fp, "%s %s\n", lan_ipaddr, OLD_DUT_DOMAIN_NAME2);
832		/* productid/samba name */
833		if (is_valid_hostname(value = nvram_safe_get("computer_name")) ||
834		    is_valid_hostname(value = get_productid()))
835			fprintf(fp, "%s %s.%s %s\n", lan_ipaddr,
836				    value, nvram_safe_get("lan_domain"), value);
837		/* lan hostname.domain hostname */
838		if (nvram_invmatch("lan_hostname", "")) {
839			fprintf(fp, "%s %s.%s %s\n", lan_ipaddr,
840				    nvram_safe_get("lan_hostname"),
841				    nvram_safe_get("lan_domain"),
842				    nvram_safe_get("lan_hostname"));
843		}
844#ifdef RTCONFIG_IPV6
845		if (ipv6_enabled()) {
846			/* localhost ipv6 */
847			fprintf(fp, "::1 localhost6.localdomain6 localhost6\n");
848			/* lan6 hostname.domain hostname */
849			value = (char*) ipv6_router_address(NULL);
850			if (*value && nvram_invmatch("lan_hostname", "")) {
851				fprintf(fp, "%s %s.%s %s\n", value,
852					    nvram_safe_get("lan_hostname"),
853					    nvram_safe_get("lan_domain"),
854					    nvram_safe_get("lan_hostname"));
855			}
856		}
857#endif
858		fclose(fp);
859	} else
860		perror("/etc/hosts");
861
862
863#ifdef RTCONFIG_REDIRECT_DNAME
864	if (nvram_get_int("sw_mode") == SW_MODE_AP) {
865#ifdef RTCONFIG_DHCP_OVERRIDE
866		if (nvram_match("dhcp_enable_x", "1") && nvram_match("dnsqmode", "2")
867#ifdef RTCONFIG_DEFAULT_AP_MODE
868				&& !nvram_match("ate_flag", "1")
869#endif
870		) {
871			if ((fp = fopen("/etc/dnsmasq.conf", "w+")) != NULL) {
872				/* DHCP range */
873				char dhcp_start[16], dhcp_end[16], lan_netmask[16];
874
875				strcpy(dhcp_start, nvram_safe_get("dhcp_start"));
876				strcpy(dhcp_end, nvram_safe_get("dhcp_end"));
877				strcpy(lan_netmask, nvram_safe_get("lan_netmask"));
878
879				if (!chk_valid_startend(lan_ipaddr, dhcp_start, dhcp_end, lan_netmask)) {
880					dbg("reset DHCP range: %s ~ %s\n", dhcp_start, dhcp_end);
881					nvram_set("dhcp_start", dhcp_start);
882					nvram_set("dhcp_end", dhcp_end);
883				}
884
885				fprintf(fp, "interface=%s\n", nvram_safe_get("lan_ifname"));
886				fprintf(fp, "dhcp-range=lan,%s,%s,%s,%ss\n",
887								dhcp_start,
888								dhcp_end,
889								lan_netmask,
890								nvram_safe_get("dhcp_lease"));
891				fprintf(fp, "dhcp-leasefile=/tmp/dnsmasq.leases\n");
892				/* Gateway */
893				fprintf(fp, "dhcp-option=lan,3,%s\n", lan_ipaddr);
894				/* Faster for moving clients, if authoritative */
895				fprintf(fp, "dhcp-authoritative\n");
896				/* caching */
897				fprintf(fp, "cache-size=1500\n"
898					    "no-negcache\n");
899				fclose(fp);
900			}
901			else
902				perror("/etc/dnsmasq.conf");
903		}
904		else
905			unlink("/etc/dnsmasq.conf");
906#endif
907
908		eval("dnsmasq", "--log-async");
909	}
910#endif
911	if (!is_routing_enabled()
912#ifdef RTCONFIG_WIRELESSREPEATER
913	 && nvram_get_int("sw_mode") != SW_MODE_REPEATER
914#endif
915	) return;
916
917	// we still need dnsmasq in wet
918	//if (foreach_wif(1, NULL, is_wet)) return;
919
920	if ((fp = fopen("/etc/dnsmasq.conf", "w")) == NULL)
921		return;
922
923	fprintf(fp, "pid-file=/var/run/dnsmasq.pid\n"
924		    "user=nobody\n"
925		    "bind-dynamic\n"		// listen only on interface & lo
926		);
927
928#if defined(RTCONFIG_REDIRECT_DNAME)
929	if(nvram_get_int("sw_mode") != SW_MODE_REPEATER)
930#endif
931	{
932		fprintf(fp,"interface=%s\n",		// dns & dhcp on LAN interface
933			lan_ifname);
934#if defined(RTCONFIG_PPTPD) || defined(RTCONFIG_ACCEL_PPTPD)
935		if (is_routing_enabled())
936		fprintf(fp, "interface=%s\n"		// dns on VPN clients interfaces
937		    	"no-dhcp-interface=%s\n",	// no dhcp for VPN clients
938			"ppp1*", "ppp1*");
939#endif
940	}
941
942#ifdef  __CONFIG_NORTON__
943	/* TODO: dnsmasq doesn't support a single hostname across multiple interfaces */
944	if (nvram_get_int("nga_enable"))
945		fprintf(fp, "interface-name=norton.local,%s\n", lan_ifname);
946#endif /* __CONFIG_NORTON__ */
947
948#ifdef RTCONFIG_YANDEXDNS
949	if (nvram_get_int("yadns_enable_x") && nvram_get_int("yadns_mode") != YADNS_DISABLED) {
950		fprintf(fp, "no-resolv\n");	// no resolv
951	} else
952#endif
953	fprintf(fp, "resolv-file=%s\n",		// the real stuff is here
954		dmresolv);
955
956	fprintf(fp, "servers-file=%s\n"		// additional servers list
957		    "no-poll\n"			// don't poll resolv file
958		    "no-negcache\n"		// don't cace nxdomain
959		    "cache-size=%u\n"		// dns cache size
960		    "min-port=%u\n",		// min port used for random src port
961		dmservers, 1500, nvram_get_int("dns_minport") ? : 4096);
962
963	/* lan domain */
964	value = nvram_safe_get("lan_domain");
965	if (*value) {
966		fprintf(fp, "domain=%s\n"
967			    "expand-hosts\n", value);	// expand hostnames in hosts file
968	}
969
970	if (
971		(is_routing_enabled() && nvram_get_int("dhcp_enable_x"))
972#ifdef RTCONFIG_WIRELESSREPEATER
973	 || (nvram_get_int("sw_mode") == SW_MODE_REPEATER && nvram_get_int("wlc_state") != WLC_STATE_CONNECTED)
974#endif
975	) {
976		char *dhcp_start, *dhcp_end;
977		int dhcp_lease;
978		char buffer[64];
979#if defined(RTCONFIG_TR069) && !defined(RTCONFIG_TR181)
980		unsigned char hwaddr[6];
981#endif
982
983		have_dhcp |= 1; /* DHCPv4 */
984
985		get_dhcp_pool(&dhcp_start, &dhcp_end, buffer);
986#ifdef RTCONFIG_WIRELESSREPEATER
987		if(nvram_get_int("sw_mode") == SW_MODE_REPEATER && nvram_get_int("wlc_state") != WLC_STATE_CONNECTED){
988			dhcp_lease = atoi(nvram_default_get("dhcp_lease"));
989		}
990		else
991#endif
992		{
993			dhcp_lease = nvram_get_int("dhcp_lease");
994		}
995
996		if (dhcp_lease <= 0)
997			dhcp_lease = 86400;
998
999		/* LAN range */
1000		if (*dhcp_start && *dhcp_end) {
1001			fprintf(fp, "dhcp-range=lan,%s,%s,%s,%ds\n",
1002				dhcp_start, dhcp_end, nvram_safe_get("lan_netmask"), dhcp_lease);
1003		} else {
1004			/* compatibility */
1005			char lan[24];
1006			int start = nvram_get_int("dhcp_start");
1007			int count = nvram_get_int("dhcp_num");
1008
1009			strlcpy(lan, lan_ipaddr, sizeof(lan));
1010			if ((value = strrchr(lan, '.')) != NULL) *(value + 1) = 0;
1011
1012			fprintf(fp, "dhcp-range=lan,%s%d,%s%d,%s,%ds\n",
1013				lan, start, lan, start + count - 1, nvram_safe_get("lan_netmask"), dhcp_lease);
1014		}
1015
1016		/* Gateway, if not set, force use lan ipaddr to avoid repeater issue */
1017		value = nvram_safe_get("dhcp_gateway_x");
1018		value = (*value && inet_addr(value)) ? value : lan_ipaddr;
1019		fprintf(fp, "dhcp-option=lan,3,%s\n", value);
1020
1021		/* DNS server and additional router address */
1022		value = nvram_safe_get("dhcp_dns1_x");
1023		if (*value && inet_addr(value))
1024			fprintf(fp, "dhcp-option=lan,6,%s,0.0.0.0\n", value);
1025
1026		/* LAN Domain */
1027		value = nvram_safe_get("lan_domain");
1028		if (*value)
1029			fprintf(fp, "dhcp-option=lan,15,%s\n", value);
1030
1031		/* WINS server */
1032		value = nvram_safe_get("dhcp_wins_x");
1033		if (*value && inet_addr(value)) {
1034			fprintf(fp, "dhcp-option=lan,44,%s\n"
1035			/*	    "dhcp-option=lan,46,8\n"*/, value);
1036		}
1037#ifdef RTCONFIG_SAMBASRV
1038		/* Samba will serve as a WINS server */
1039		else if (nvram_get_int("smbd_enable") && nvram_invmatch("lan_domain", "") && nvram_get_int("smbd_wins")) {
1040			fprintf(fp, "dhcp-option=lan,44,0.0.0.0\n"
1041			/*	    "dhcp-option=lan,46,8\n"*/);
1042		}
1043#endif
1044		/* Shut up WPAD info requests */
1045		fprintf(fp, "dhcp-option=lan,252,\"\\n\"\n");
1046
1047#if defined(RTCONFIG_TR069) && !defined(RTCONFIG_TR181)
1048		if (ether_atoe(get_lan_hwaddr(), hwaddr)) {
1049			snprintf(buffer, sizeof(buffer), "%02X%02X%02X", hwaddr[0], hwaddr[1], hwaddr[2]);
1050			fprintf(fp, "dhcp-option-force=cpewan-id,vi-encap:%d,%d,\"%s\"\n",
1051				3561, 4, buffer);
1052			snprintf(buffer, sizeof(buffer), "%02X%02X%02X%02X%02X%02X",
1053				 hwaddr[0], hwaddr[1], hwaddr[2], hwaddr[3], hwaddr[4], hwaddr[5]);
1054			fprintf(fp, "dhcp-option-force=cpewan-id,vi-encap:%d,%d,\"%s\"\n",
1055				3561, 5, buffer);
1056			fprintf(fp, "dhcp-option-force=cpewan-id,vi-encap:%d,%d,\"%s\"\n",
1057				3561, 6, nvram_safe_get("productid"));
1058		}
1059#endif
1060	}
1061
1062#ifdef RTCONFIG_IPV6
1063	if (ipv6_enabled()
1064#ifdef RTCONFIG_6RELAYD
1065		&& get_ipv6_service() != IPV6_PASSTHROUGH
1066#endif
1067		&& is_routing_enabled()) {
1068		struct in6_addr addr;
1069		int ra_lifetime, dhcp_lifetime;
1070		int service, stateful, dhcp_start, dhcp_end;
1071
1072		service = get_ipv6_service();
1073		stateful = (service == IPV6_NATIVE_DHCP || service == IPV6_MANUAL) ?
1074			nvram_get_int(ipv6_nvname("ipv6_autoconf_type")) : 0;
1075		ra_lifetime = 600; /* 10 minutes for now */
1076		dhcp_lifetime = nvram_get_int(ipv6_nvname("ipv6_dhcp_lifetime"));
1077		if (dhcp_lifetime <= 0)
1078			dhcp_lifetime = 86400;
1079
1080		if (nvram_get_int(ipv6_nvname("ipv6_radvd"))) {
1081			fprintf(fp, "ra-param=%s,%d,%d\n"
1082				    "enable-ra\n"
1083				    "quiet-ra\n",
1084				lan_ifname, 10, ra_lifetime);
1085		}
1086
1087		/* LAN prefix or range */
1088		if (stateful) {
1089			/* TODO: rework WEB UI to specify ranges without prefix
1090			 * TODO: add size checking, now range takes all of 16 bit */
1091			dhcp_start = (inet_pton(AF_INET6, nvram_safe_get(ipv6_nvname("ipv6_dhcp_start")), &addr) > 0) ?
1092			    ntohs(addr.s6_addr16[7]) : 0x1000;
1093			dhcp_end = (inet_pton(AF_INET6, nvram_safe_get(ipv6_nvname("ipv6_dhcp_end")), &addr) > 0) ?
1094			    ntohs(addr.s6_addr16[7]) : 0x2000;
1095			fprintf(fp, "dhcp-range=lan,::%04x,::%04x,constructor:%s,%d\n",
1096				(dhcp_start < dhcp_end) ? dhcp_start : dhcp_end,
1097				(dhcp_start < dhcp_end) ? dhcp_end : dhcp_start,
1098				lan_ifname, dhcp_lifetime);
1099			have_dhcp |= 2; /* DHCPv6 */
1100		} else if (nvram_get_int(ipv6_nvname("ipv6_radvd"))) {
1101			fprintf(fp, "dhcp-range=lan,::,constructor:%s,ra-stateless,%d,%d\n",
1102				lan_ifname, 64, ra_lifetime);
1103			have_dhcp |= 2; /* DHCPv6 */
1104		}
1105
1106#ifdef RTCONFIG_YANDEXDNS
1107		if (nvram_get_int("yadns_enable_x")) {
1108			unsigned char ea[ETHER_ADDR_LEN];
1109			char *name, *mac, *mode, *enable, *server[2];
1110			char *nv, *nvp, *b;
1111			int i, count, dnsmode, defmode = nvram_get_int("yadns_mode");
1112
1113			for (dnsmode = YADNS_FIRST; dnsmode < YADNS_COUNT; dnsmode++) {
1114				if (dnsmode == defmode)
1115					continue;
1116				count = get_yandex_dns(AF_INET6, dnsmode, server, sizeof(server)/sizeof(server[0]));
1117				if (count <= 0)
1118					continue;
1119				fprintf(fp, "dhcp-option=yadns%u,option6:23", dnsmode);
1120				for (i = 0; i < count; i++)
1121					fprintf(fp, ",[%s]", server[i]);
1122				fprintf(fp, "\n");
1123			}
1124
1125			/* DNS server per client */
1126			nv = nvp = strdup(nvram_safe_get("yadns_rulelist"));
1127			while (nv && (b = strsep(&nvp, "<")) != NULL) {
1128				if (vstrsep(b, ">", &name, &mac, &mode, &enable) < 3)
1129					continue;
1130				if (enable && atoi(enable) == 0)
1131					continue;
1132				if (!*mac || !*mode || !ether_atoe(mac, ea))
1133					continue;
1134				dnsmode = atoi(mode);
1135				/* Skip incorrect and default levels */
1136				if (dnsmode < YADNS_FIRST || dnsmode >= YADNS_COUNT || dnsmode == defmode)
1137					continue;
1138				fprintf(fp, "dhcp-host=%s,set:yadns%u\n", mac, dnsmode);
1139			}
1140			free(nv);
1141		}
1142#endif /* RTCONFIG_YANDEXDNS */
1143
1144		/* DNS server */
1145		fprintf(fp, "dhcp-option=lan,option6:23,[::]\n");
1146
1147		/* LAN Domain */
1148		value = nvram_safe_get("lan_domain");
1149		if (*value)
1150			fprintf(fp, "dhcp-option=lan,option6:24,%s\n", value);
1151	}
1152#endif
1153
1154	if (have_dhcp) {
1155#if 0	//this would limit the total count of dhcp client (including dhcp pool and manually assigned static IP).
1156		/* Maximum leases */
1157		if ((i = get_dhcpd_lmax()) > 0)
1158			fprintf(fp, "dhcp-lease-max=%d\n", i);
1159#endif
1160
1161		/* Faster for moving clients, if authoritative */
1162		if (nvram_get_int("dhcpd_auth") >= 0)
1163			fprintf(fp, "dhcp-authoritative\n");
1164#ifdef RTCONFIG_MULTICAST_IPTV
1165		/* Rawny: Add vendor class ID and DNS info for Movistar IPTV */
1166		if (nvram_get_int("switch_stb_x") > 6 &&
1167		    nvram_match("switch_wantag", "movistar")) {
1168			fprintf(fp, "dhcp-vendorclass=ial,IAL\n");
1169			fprintf(fp, "dhcp-option=ial,6,172.26.23.3\n");
1170			fprintf(fp, "dhcp-option=ial,240,:::::239.0.2.10:22222:v6.0:239.0.2.30:22222\n");
1171		}
1172#endif
1173	} else
1174		fprintf(fp, "no-dhcp-interface=%s\n", lan_ifname);
1175
1176	/* Static IP MAC binding */
1177	if (nvram_match("dhcp_static_x","1")) {
1178		fprintf(fp, "read-ethers\n");
1179		write_static_leases("/etc/ethers");
1180	}
1181#ifdef RTCONFIG_FINDASUS
1182	fprintf(fp, "address=/findasus.local/%s\n", lan_ipaddr);
1183#endif
1184#ifdef RTCONFIG_OPENVPN
1185	write_vpn_dnsmasq_config(fp);
1186#endif
1187
1188#ifdef RTCONFIG_PORT_BASED_VLAN
1189	/* Write dhcpd config for vlan's subnet */
1190	vlan_subnet_dnsmasq_conf(fp);
1191#endif
1192
1193	fclose(fp);
1194
1195	/* Create resolv.conf with empty nameserver list */
1196	f_write(dmresolv, NULL, 0, FW_APPEND, 0666);
1197	/* Create resolv.dnsmasq with empty server list */
1198	f_write(dmservers, NULL, 0, FW_APPEND, 0666);
1199
1200#if (defined(RTCONFIG_TR069) && !defined(RTCONFIG_TR181))
1201	eval("dnsmasq", "--log-async", "-6", "/sbin/dhcpc_lease");
1202#else
1203	eval("dnsmasq", "--log-async");
1204#endif
1205
1206	TRACE_PT("end\n");
1207}
1208
1209void stop_dnsmasq(void)
1210{
1211	TRACE_PT("begin\n");
1212
1213	if (getpid() != 1) {
1214		notify_rc("stop_dnsmasq");
1215		return;
1216	}
1217
1218	killall_tk("dnsmasq");
1219
1220	TRACE_PT("end\n");
1221}
1222
1223void reload_dnsmasq(void)
1224{
1225	/* notify dnsmasq */
1226	kill_pidfile_s("/var/run/dnsmasq.pid", SIGHUP);
1227}
1228
1229#ifdef RTCONFIG_IPV6
1230void add_ip6_lanaddr(void)
1231{
1232	char ip[INET6_ADDRSTRLEN + 4];
1233	const char *p;
1234
1235	p = ipv6_router_address(NULL);
1236	if (*p) {
1237		snprintf(ip, sizeof(ip), "%s/%d", p, nvram_get_int(ipv6_nvname("ipv6_prefix_length")) ? : 64);
1238		eval("ip", "-6", "addr", "add", ip, "dev", nvram_safe_get("lan_ifname"));
1239		if (!nvram_match(ipv6_nvname("ipv6_rtr_addr"), (char*)p))
1240			nvram_set(ipv6_nvname("ipv6_rtr_addr"), (char*)p);
1241	}
1242
1243	switch (get_ipv6_service()) {
1244	case IPV6_NATIVE_DHCP:
1245		if (nvram_get_int(ipv6_nvname("ipv6_dhcp_pd")))
1246			break;
1247		/* fall through */
1248#ifdef RTCONFIG_6RELAYD
1249	case IPV6_PASSTHROUGH:
1250#endif
1251	case IPV6_MANUAL:
1252		p = ipv6_prefix(NULL);
1253		if (*p && !nvram_match(ipv6_nvname("ipv6_prefix"), (char*)p))
1254			nvram_set(ipv6_nvname("ipv6_prefix"), (char*)p);
1255		break;
1256	}
1257}
1258
1259void start_ipv6_tunnel(void)
1260{
1261	char ip[INET6_ADDRSTRLEN + 4];
1262	char router[INET6_ADDRSTRLEN + 1];
1263	struct in_addr addr4;
1264	struct in6_addr addr;
1265	char *wanip, *mtu, *tun_dev, *gateway;
1266	int service;
1267
1268	// for one wan only now
1269	service = get_ipv6_service();
1270	tun_dev = (char*)get_wan6face();
1271	wanip = (char*)get_wanip();
1272
1273	mtu = (nvram_get_int(ipv6_nvname("ipv6_tun_mtu")) > 0) ? nvram_safe_get(ipv6_nvname("ipv6_tun_mtu")) : "1480";
1274	modprobe("sit");
1275
1276	eval("ip", "tunnel", "add", tun_dev, "mode", "sit",
1277		"remote", (service == IPV6_6IN4) ? nvram_safe_get(ipv6_nvname("ipv6_tun_v4end")) : "any",
1278		"local", wanip,
1279		"ttl", nvram_safe_get(ipv6_nvname("ipv6_tun_ttl")));
1280	eval("ip", "link", "set", tun_dev, "mtu", mtu, "up");
1281
1282	switch (service) {
1283	case IPV6_6TO4: {
1284		int prefixlen = 16;
1285		int mask4size = 0;
1286
1287		/* address */
1288		addr4.s_addr = 0;
1289		memset(&addr, 0, sizeof(addr));
1290		inet_aton(wanip, &addr4);
1291		addr.s6_addr16[0] = htons(0x2002);
1292		ipv6_mapaddr4(&addr, prefixlen, &addr4, mask4size);
1293		//addr.s6_addr16[7] |= htons(0x0001);
1294		inet_ntop(AF_INET6, &addr, ip, sizeof(ip));
1295		snprintf(ip, sizeof(ip), "%s/%d", ip, prefixlen);
1296
1297		/* gateway */
1298		snprintf(router, sizeof(router), "::%s", nvram_safe_get(ipv6_nvname("ipv6_relay")));
1299		gateway = router;
1300
1301		add_ip6_lanaddr();
1302		break;
1303	}
1304	case IPV6_6RD: {
1305		int prefixlen = nvram_get_int(ipv6_nvname("ipv6_6rd_prefixlen"));
1306		int mask4size = nvram_get_int(ipv6_nvname("ipv6_6rd_ip4size"));
1307		char brprefix[sizeof("255.255.255.255/32")];
1308
1309		/* 6rd domain */
1310		addr4.s_addr = 0;
1311		if (mask4size) {
1312			inet_aton(wanip, &addr4);
1313			addr4.s_addr &= htonl(0xffffffffUL << (32 - mask4size));
1314		} else	addr4.s_addr = 0;
1315		snprintf(ip, sizeof(ip), "%s/%d", nvram_safe_get(ipv6_nvname("ipv6_6rd_prefix")), prefixlen);
1316		snprintf(brprefix, sizeof(brprefix), "%s/%d", inet_ntoa(addr4), mask4size);
1317		eval("ip", "tunnel", "6rd", "dev", tun_dev,
1318		     "6rd-prefix", ip, "6rd-relay_prefix", brprefix);
1319
1320		/* address */
1321		addr4.s_addr = 0;
1322		memset(&addr, 0, sizeof(addr));
1323		inet_aton(wanip, &addr4);
1324		inet_pton(AF_INET6, nvram_safe_get(ipv6_nvname("ipv6_6rd_prefix")), &addr);
1325		ipv6_mapaddr4(&addr, prefixlen, &addr4, mask4size);
1326		//addr.s6_addr16[7] |= htons(0x0001);
1327		inet_ntop(AF_INET6, &addr, ip, sizeof(ip));
1328		snprintf(ip, sizeof(ip), "%s/%d", ip, prefixlen);
1329
1330		/* gateway */
1331		snprintf(router, sizeof(router), "::%s", nvram_safe_get(ipv6_nvname("ipv6_6rd_router")));
1332		gateway = router;
1333
1334		add_ip6_lanaddr();
1335		break;
1336	}
1337	default:
1338		/* address */
1339		snprintf(ip, sizeof(ip), "%s/%d",
1340			nvram_safe_get(ipv6_nvname("ipv6_tun_addr")),
1341			nvram_get_int(ipv6_nvname("ipv6_tun_addrlen")) ? : 64);
1342
1343		/* gateway */
1344		gateway = nvram_safe_get(ipv6_nvname("ipv6_tun_peer"));
1345		if (gateway && *gateway)
1346			eval("ip", "-6", "route", "add", gateway, "dev", tun_dev, "metric", "1");
1347	}
1348
1349	eval("ip", "-6", "addr", "add", ip, "dev", tun_dev);
1350	eval("ip", "-6", "route", "del", "::/0");
1351
1352	if (gateway && *gateway)
1353		eval("ip", "-6", "route", "add", "::/0", "via", gateway, "dev", tun_dev, "metric", "1");
1354	else	eval("ip", "-6", "route", "add", "::/0", "dev", tun_dev, "metric", "1");
1355}
1356
1357void stop_ipv6_tunnel(void)
1358{
1359	int service = get_ipv6_service();
1360
1361	if (service == IPV6_6TO4 || service == IPV6_6RD || service == IPV6_6IN4) {
1362		eval("ip", "tunnel", "del", (char *)get_wan6face());
1363	}
1364	if (service == IPV6_6TO4 || service == IPV6_6RD) {
1365		// get rid of old IPv6 address from lan iface
1366		eval("ip", "-6", "addr", "flush", "dev", nvram_safe_get("lan_ifname"), "scope", "global");
1367		nvram_set(ipv6_nvname("ipv6_rtr_addr"), "");
1368		nvram_set(ipv6_nvname("ipv6_prefix"), "");
1369	}
1370	modprobe_r("sit");
1371}
1372
1373void start_ipv6(void)
1374{
1375	int service = get_ipv6_service();
1376
1377	// Check if turned on
1378	switch (service) {
1379	case IPV6_NATIVE_DHCP:
1380		nvram_set(ipv6_nvname("ipv6_prefix"), "");
1381		if (nvram_get_int(ipv6_nvname("ipv6_dhcp_pd"))) {
1382			nvram_set(ipv6_nvname("ipv6_prefix_length"), "");
1383			nvram_set(ipv6_nvname("ipv6_rtr_addr"), "");
1384		} else {
1385			nvram_set_int(ipv6_nvname("ipv6_prefix_length"), 64);
1386			add_ip6_lanaddr();
1387		}
1388		nvram_set(ipv6_nvname("ipv6_get_dns"), "");
1389		nvram_set(ipv6_nvname("ipv6_get_domain"), "");
1390		break;
1391#ifdef RTCONFIG_6RELAYD
1392        case IPV6_PASSTHROUGH:
1393		nvram_set(ipv6_nvname("ipv6_prefix"), "");
1394		nvram_set(ipv6_nvname("ipv6_rtr_addr"), "::1");
1395		nvram_set_int(ipv6_nvname("ipv6_prefix_length"), 64);
1396		add_ip6_lanaddr();
1397		nvram_set(ipv6_nvname("ipv6_get_dns"), "");
1398		nvram_set(ipv6_nvname("ipv6_get_domain"), "");
1399		break;
1400#endif
1401	case IPV6_6IN4:
1402		nvram_set(ipv6_nvname("ipv6_rtr_addr"), "");
1403		nvram_set(ipv6_nvname("ipv6_prefix_length"), nvram_safe_get(ipv6_nvname("ipv6_prefix_length_s")));
1404		nvram_set(ipv6_nvname("ipv6_prefix"), nvram_safe_get(ipv6_nvname("ipv6_prefix_s")));
1405		/* fall through */
1406	case IPV6_MANUAL:
1407		nvram_set(ipv6_nvname("ipv6_rtr_addr"), nvram_safe_get(ipv6_nvname("ipv6_rtr_addr_s")));
1408		nvram_set(ipv6_nvname("ipv6_prefix_length"), nvram_safe_get(ipv6_nvname("ipv6_prefix_length_s")));
1409		add_ip6_lanaddr();
1410		break;
1411	case IPV6_6TO4:
1412	case IPV6_6RD:
1413		nvram_set(ipv6_nvname("ipv6_prefix"), "");
1414		nvram_set(ipv6_nvname("ipv6_prefix_length"), "");
1415		nvram_set(ipv6_nvname("ipv6_rtr_addr"), "");
1416		break;
1417	}
1418}
1419
1420void stop_ipv6(void)
1421{
1422	char *lan_ifname = nvram_safe_get("lan_ifname");
1423	char *wan_ifname = (char *) get_wan6face();
1424
1425#ifdef RTCONFIG_6RELAYD
1426	stop_6relayd();
1427#endif
1428	stop_dhcp6c();
1429	stop_ipv6_tunnel();
1430
1431	eval("ip", "-6", "addr", "flush", "scope", "global", "dev", lan_ifname);
1432	eval("ip", "-6", "addr", "flush", "scope", "global", "dev", wan_ifname);
1433	eval("ip", "-6", "route", "flush", "scope", "global");
1434	eval("ip", "-6", "neigh", "flush", "dev", lan_ifname);
1435}
1436
1437#ifdef RTCONFIG_6RELAYD
1438void stop_6relayd(void)
1439{
1440	killall_tk("6relayd");
1441}
1442
1443int start_6relayd(void)
1444{
1445	char *wan_ifname = (char *) get_wan6face();
1446	char tmp[INET6_ADDRSTRLEN + 2], tmp2[32];
1447
1448	if (get_ipv6_service() != IPV6_PASSTHROUGH)
1449		return 0;
1450
1451	if (!wan_ifname || *wan_ifname == '\0')
1452		return -1;
1453
1454	stop_6relayd();
1455
1456	return eval("6relayd", "-R", "relay", "-D", "server", "-N", strcat_r("-n", nvram_safe_get("ipv6_get_dns"), tmp), wan_ifname, strcat_r("~", nvram_safe_get("lan_ifname"), tmp2));
1457}
1458#endif
1459#endif
1460
1461// -----------------------------------------------------------------------------
1462
1463int no_need_to_start_wps(void)
1464{
1465	int i, j, wps_band, multiband = get_wps_multiband();
1466	char tmp[100], tmp2[100], prefix[] = "wlXXXXXXXXXXXXXX", prefix_mssid[] = "wlXXXXXXXXXX_mssid_";
1467	char word[256], *next, ifnames[128];
1468	int c = 0, ret = 0;
1469
1470#ifdef RTCONFIG_DSL
1471	if (nvram_match("asus_mfg", "1")) /* Paul add 2012/12/13 */
1472		return 0;
1473#endif
1474	if ((nvram_get_int("sw_mode") != SW_MODE_ROUTER) &&
1475		(nvram_get_int("sw_mode") != SW_MODE_AP))
1476		return 1;
1477
1478	i = 0;
1479	wps_band = nvram_get_int("wps_band");
1480	strcpy(ifnames, nvram_safe_get("wl_ifnames"));
1481	foreach (word, ifnames, next) {
1482		if (i >= MAX_NR_WL_IF)
1483			break;
1484		if (!multiband && wps_band != i) {
1485			++i;
1486			continue;
1487		}
1488		++c;
1489		snprintf(prefix, sizeof(prefix), "wl%d_", i);
1490		if ((nvram_match(strcat_r(prefix, "auth_mode_x", tmp), "open") &&
1491		     nvram_get_int(strcat_r(prefix, "wep_x", tmp2))) ||
1492		     nvram_match(strcat_r(prefix, "auth_mode_x", tmp), "shared") ||
1493		     strstr(nvram_safe_get(strcat_r(prefix, "auth_mode_x", tmp)), "wpa") ||
1494		     nvram_match(strcat_r(prefix, "auth_mode_x", tmp), "radius"))
1495			ret++;
1496#ifdef RTCONFIG_RALINK
1497		if (nvram_match("wl_mssid", "1"))
1498#endif
1499		for (j = 1; j < MAX_NO_MSSID; j++) {
1500			sprintf(prefix_mssid, "wl%d.%d_", wps_band, j);
1501			if (!nvram_match(strcat_r(prefix_mssid, "bss_enabled", tmp), "1"))
1502				continue;
1503			++c;
1504			if ((nvram_match(strcat_r(prefix, "auth_mode_x", tmp), "open") &&
1505			     nvram_get_int(strcat_r(prefix, "wep_x", tmp2))) ||
1506			     nvram_match(strcat_r(prefix_mssid, "auth_mode_x", tmp), "shared") ||
1507			     strstr(nvram_safe_get(strcat_r(prefix_mssid, "auth_mode_x", tmp)), "wpa") ||
1508			     nvram_match(strcat_r(prefix_mssid, "auth_mode_x", tmp), "radius"))
1509				ret++;
1510		}
1511
1512		i++;
1513	}
1514
1515	if (multiband && ret < c)
1516		ret = 0;
1517
1518	return ret;
1519}
1520
1521/* @wps_band:	if wps_band < 0 and RTCONFIG_WPSMULTIBAND is defined, check radio of all band */
1522int wps_band_radio_off(int wps_band)
1523{
1524	int i, c = 0, ret = 0;
1525	char tmp[100], prefix[] = "wlXXXXXXXXXXXXXX";
1526	char word[256], *next, ifnames[128];
1527
1528	i = 0;
1529	strcpy(ifnames, nvram_safe_get("wl_ifnames"));
1530	foreach (word, ifnames, next) {
1531		if (i >= MAX_NR_WL_IF)
1532			break;
1533		if (wps_band >= 0 && wps_band != i) {
1534			++i;
1535			continue;
1536		}
1537		++c;
1538		snprintf(prefix, sizeof(prefix), "wl%d_", i);
1539		if (nvram_match(strcat_r(prefix, "radio", tmp), "0"))
1540			ret++;
1541
1542		i++;
1543	}
1544
1545	if (wps_band < 0 && ret < c)
1546		ret = 0;
1547
1548	return ret;
1549}
1550
1551/* @wps_band:	if wps_band < 0 and RTCONFIG_WPSMULTIBAND is defined, check ssid broadcast status of all band */
1552int wps_band_ssid_broadcast_off(int wps_band)
1553{
1554	int i, c = 0, ret = 0;
1555	char tmp[100], prefix[] = "wlXXXXXXXXXXXXXX";
1556	char word[256], *next, ifnames[128];
1557
1558	i = 0;
1559	strcpy(ifnames, nvram_safe_get("wl_ifnames"));
1560	foreach (word, ifnames, next) {
1561		if (i >= MAX_NR_WL_IF)
1562			break;
1563		if (wps_band >= 0 && wps_band != i) {
1564			++i;
1565			continue;
1566		}
1567		++c;
1568		snprintf(prefix, sizeof(prefix), "wl%d_", i);
1569		if (nvram_match(strcat_r(prefix, "closed", tmp), "1"))
1570			ret++;
1571
1572		i++;
1573	}
1574
1575	if (wps_band < 0 && ret < c)
1576		ret = 0;
1577
1578	return ret;
1579}
1580
1581int
1582wl_wpsPincheck(char *pin_string)
1583{
1584	unsigned long PIN = strtoul(pin_string, NULL, 10);
1585	unsigned long int accum = 0;
1586	unsigned int len = strlen(pin_string);
1587
1588	if (len != 4 && len != 8)
1589		return 	-1;
1590
1591	if (len == 8) {
1592		accum += 3 * ((PIN / 10000000) % 10);
1593		accum += 1 * ((PIN / 1000000) % 10);
1594		accum += 3 * ((PIN / 100000) % 10);
1595		accum += 1 * ((PIN / 10000) % 10);
1596		accum += 3 * ((PIN / 1000) % 10);
1597		accum += 1 * ((PIN / 100) % 10);
1598		accum += 3 * ((PIN / 10) % 10);
1599		accum += 1 * ((PIN / 1) % 10);
1600
1601		if (0 == (accum % 10))
1602			return 0;
1603	}
1604	else if (len == 4)
1605		return 0;
1606
1607	return -1;
1608}
1609
1610int
1611start_wps_pbc(int unit)
1612{
1613	if (wps_band_radio_off(get_radio_band(unit))) return 1;
1614
1615	if (wps_band_ssid_broadcast_off(get_radio_band(unit))) return 1;
1616
1617	if (!no_need_to_start_wps() && nvram_match("wps_enable", "0"))
1618	{
1619		nvram_set("wps_enable", "1");
1620#ifdef CONFIG_BCMWL5
1621#ifdef RTCONFIG_BCMWL6
1622		restart_wireless();
1623		int delay_count = 10;
1624		while ((delay_count-- > 0) && !nvram_get_int("wlready"))
1625			sleep(1);
1626#else
1627		restart_wireless();
1628#endif
1629#else
1630		stop_wps();
1631#if !defined(RTCONFIG_WPSMULTIBAND)
1632		nvram_set_int("wps_band", unit);
1633#endif
1634		start_wps();
1635#endif
1636	}
1637
1638#if !defined(RTCONFIG_WPSMULTIBAND)
1639	nvram_set_int("wps_band", unit);
1640#endif
1641	nvram_set("wps_sta_pin", "00000000");
1642
1643	return start_wps_method();
1644}
1645
1646int
1647start_wps_pin(int unit)
1648{
1649	if (!strlen(nvram_safe_get("wps_sta_pin"))) return 0;
1650
1651	if (wl_wpsPincheck(nvram_safe_get("wps_sta_pin"))) return 0;
1652
1653	nvram_set_int("wps_band", unit);
1654
1655	return start_wps_method();
1656}
1657
1658#ifdef RTCONFIG_WPS
1659int
1660stop_wpsaide()
1661{
1662	if (pids("wpsaide"))
1663		killall("wpsaide", SIGTERM);
1664
1665	return 0;
1666}
1667
1668int
1669start_wpsaide()
1670{
1671	char *wpsaide_argv[] = {"wpsaide", NULL};
1672	pid_t pid;
1673	int ret = 0;
1674
1675	stop_wpsaide();
1676
1677	ret = _eval(wpsaide_argv, NULL, 0, &pid);
1678	return ret;
1679}
1680#endif
1681
1682extern int restore_defaults_g;
1683
1684int
1685start_wps(void)
1686{
1687#ifdef RTCONFIG_WPS
1688#ifdef CONFIG_BCMWL5
1689	char *wps_argv[] = {"/bin/wps_monitor", NULL};
1690	pid_t pid;
1691#endif
1692	if (wps_band_radio_off(get_radio_band(nvram_get_int("wps_band"))))
1693		return 1;
1694
1695	if (no_need_to_start_wps() ||
1696	    wps_band_ssid_broadcast_off(get_radio_band(nvram_get_int("wps_band"))))
1697		nvram_set("wps_enable", "0");
1698
1699	if (nvram_match("wps_restart", "1")) {
1700		nvram_set("wps_restart", "0");
1701	}
1702	else {
1703		nvram_set("wps_restart", "0");
1704		nvram_set("wps_proc_status", "0");
1705	}
1706
1707	nvram_set("wps_sta_pin", "00000000");
1708	if (nvram_match("w_Setting", "1"))
1709		nvram_set("lan_wps_oob", "disabled");
1710	else
1711		nvram_set("lan_wps_oob", "enabled");
1712#ifdef CONFIG_BCMWL5
1713	killall_tk("wps_monitor");
1714	killall_tk("wps_ap");
1715	killall_tk("wps_enr");
1716	unlink("/tmp/wps_monitor.pid");
1717#endif
1718	if (nvram_match("wps_enable", "1"))
1719	{
1720#ifdef CONFIG_BCMWL5
1721		nvram_set("wl_wps_mode", "enabled");
1722#ifdef CONFIG_BCMWL5
1723		if (!restore_defaults_g)
1724#endif
1725		_eval(wps_argv, NULL, 0, &pid);
1726#elif defined RTCONFIG_RALINK
1727		start_wsc_pin_enrollee();
1728		if (f_exists("/var/run/watchdog.pid"))
1729		{
1730			doSystem("iwpriv %s set WatchdogPid=`cat %s`", WIF_2G, "/var/run/watchdog.pid");
1731#if defined(RTCONFIG_HAS_5G)
1732			doSystem("iwpriv %s set WatchdogPid=`cat %s`", WIF_5G, "/var/run/watchdog.pid");
1733#endif	/* RTCONFIG_HAS_5G */
1734		}
1735#endif
1736	}
1737#ifdef CONFIG_BCMWL5
1738	else
1739		nvram_set("wl_wps_mode", "disabled");
1740#endif
1741#else
1742	/* if we don't support WPS, make sure we unset any remaining wl_wps_mode */
1743	nvram_unset("wl_wps_mode");
1744#endif /* RTCONFIG_WPS */
1745	return 0;
1746}
1747
1748int
1749stop_wps(void)
1750{
1751	int ret = 0;
1752#ifdef RTCONFIG_WPS
1753#ifdef CONFIG_BCMWL5
1754	killall_tk("wps_monitor");
1755	killall_tk("wps_ap");
1756#elif defined RTCONFIG_RALINK
1757	stop_wsc_both();
1758#endif
1759#endif /* RTCONFIG_WPS */
1760	return ret;
1761}
1762
1763/* check for dual band case */
1764void
1765reset_wps(void)
1766{
1767#ifdef CONFIG_BCMWL5
1768//	int unit;
1769//	char prefix[]="wlXXXXXX_", tmp[100];
1770
1771	stop_wps_method();
1772
1773	stop_wps();
1774
1775//	snprintf(prefix, sizeof(prefix), "wl%s_", nvram_safe_get("wps_band"));
1776//	nvram_set(strcat_r(prefix, "wps_config_state", tmp), "0");
1777
1778	nvram_set("w_Setting", "0");
1779
1780//	start_wps();
1781	restart_wireless_wps();
1782#elif defined (RTCONFIG_RALINK) || defined (RTCONFIG_QCA)
1783	wps_oob_both();
1784#endif
1785}
1786
1787#ifdef RTCONFIG_HSPOT
1788void
1789stop_hspotap(void)
1790{
1791	killall_tk("hspotap");
1792}
1793
1794int
1795start_hspotap(void)
1796{
1797	char *hs_argv[] = {"/bin/hspotap", NULL};
1798	pid_t pid;
1799
1800	if (!check_if_file_exist("/bin/hspotap")) return 0;
1801
1802	stop_hspotap();
1803
1804	_eval(hs_argv, NULL, 0, &pid);
1805
1806	return 0;
1807}
1808#endif
1809
1810#ifdef CONFIG_BCMWL5
1811#ifdef BCM_ASPMD
1812int
1813start_aspmd(void)
1814{
1815        int ret = eval("/usr/sbin/aspmd");
1816
1817        return ret;
1818}
1819
1820int
1821stop_aspmd(void)
1822{
1823        int ret = eval("killall", "aspmd");
1824
1825        return ret;
1826}
1827#endif /* BCM_ASPMD */
1828
1829#if defined(BCM_EVENTD)
1830int start_eventd(void)
1831{
1832        int ret = 0;
1833        char *ssd_argv[] = {"/usr/sbin/eventd", NULL};
1834        pid_t pid;
1835
1836        if (nvram_match("eventd_enable", "1"))
1837                ret = _eval(ssd_argv, NULL, 0, &pid);
1838
1839        return ret;
1840}
1841
1842int stop_eventd(void)
1843{
1844        int ret = eval("killall", "eventd");
1845
1846        return ret;
1847}
1848#endif /* BCM_EVENTD */
1849
1850int
1851start_eapd(void)
1852{
1853	int ret = 0;
1854
1855	stop_eapd();
1856
1857	if (!restore_defaults_g) {
1858#ifdef RTCONFIG_PORT_BASED_VLAN
1859		change_lan_ifnames();
1860#endif
1861		ret = eval("/bin/eapd");
1862	}
1863
1864	return ret;
1865}
1866
1867void
1868stop_eapd(void)
1869{
1870	killall_tk("eapd");
1871}
1872#endif
1873
1874#if defined(BCM_DCS)
1875int
1876start_dcsd(void)
1877{
1878	int ret = eval("/usr/sbin/dcsd");
1879
1880	return ret;
1881}
1882
1883void
1884stop_dcsd(void)
1885{
1886	killall_tk("dcsd");
1887}
1888#endif /* BCM_DCS */
1889
1890#ifdef RTCONFIG_BCM_7114
1891void
1892start_dfs()
1893{
1894	int unit = 0;
1895	char word[256], *next;
1896	char tmp[128], prefix[] = "wlXXXXXXXXXX_";
1897
1898	if (!nvram_match("wl1_country_code", "E0") && !nvram_match("wl1_country_code", "JP") && !nvram_match("wl1_country_code", "AU"))
1899		return ;
1900
1901	foreach (word, nvram_safe_get("wl_ifnames"), next) {
1902		snprintf(prefix, sizeof(prefix), "wl%d_", unit);
1903		if (nvram_match(strcat_r(prefix, "nband", tmp), "1"))
1904		{
1905			eval("wl", "-i", word, "down");
1906			eval("wl", "-i", word, "spect", "1");
1907			eval("wl", "-i", word, "up");
1908		}
1909		unit++;
1910	}
1911}
1912#endif
1913//2008.10 magic{
1914int start_networkmap(int bootwait)
1915{
1916	char *networkmap_argv[] = {"networkmap", NULL, NULL};
1917	pid_t pid;
1918
1919	//if (!is_routing_enabled())
1920	//	return 0;
1921
1922#ifdef CONFIG_BCMWL5
1923	if(ate_cond() == 0)
1924		return 0;
1925#endif
1926
1927	stop_networkmap();
1928
1929	if (bootwait)
1930		networkmap_argv[1] = "--bootwait";
1931
1932#ifdef RTCONFIG_UPNPC
1933	start_miniupnpc();
1934#endif
1935#ifdef RTCONFIG_BONJOUR
1936	start_netmonitor();
1937#endif
1938	_eval(networkmap_argv, NULL, 0, &pid);
1939
1940	return 0;
1941}
1942
1943//2008.10 magic}
1944
1945void stop_networkmap(void)
1946{
1947	killall_tk("networkmap");
1948#ifdef RTCONFIG_BONJOUR
1949	stop_netmonitor();
1950#endif
1951#ifdef RTCONFIG_UPNPC
1952	stop_miniupnpc();
1953#endif
1954}
1955
1956#ifdef RTCONFIG_JFFS2USERICON
1957void stop_lltdc(void)
1958{
1959	if (pids("lld2c"))
1960		killall_tk("lld2c");
1961}
1962
1963int start_lltdc(void)
1964{
1965	char *lld2c_argv[] = {"lld2c", "br0", NULL};
1966	pid_t pid;
1967
1968	if (pids("lld2c"))
1969		return 0;
1970
1971	_eval(lld2c_argv, NULL, 0, &pid);
1972
1973	return 0;
1974}
1975#endif
1976
1977#ifdef RTCONFIG_UPNPC
1978void stop_miniupnpc(void)
1979{
1980	if (pids("miniupnpc"))
1981		killall_tk("miniupnpc");
1982}
1983
1984int start_miniupnpc(void)
1985{
1986	if (pids("miniupnpc"))
1987		return 0;
1988
1989	return xstart("miniupnpc", "-m", "br0", "-t");
1990}
1991#endif
1992
1993#ifdef RTCONFIG_BONJOUR
1994void stop_netmonitor(void)
1995{
1996	if (pids("mDNSNetMonitor"))
1997		killall_tk("mDNSNetMonitor");
1998}
1999
2000int start_netmonitor(void)
2001{
2002	char *netmonitor_argv[] = {"mDNSNetMonitor", NULL};
2003	pid_t pid;
2004
2005	if (pids("mDNSNetMonitor"))
2006		return 0;
2007
2008	_eval(netmonitor_argv, NULL, 0, &pid);
2009
2010	return 0;
2011}
2012#endif
2013
2014#ifdef RTCONFIG_LLDP
2015int start_lldpd(void)
2016{
2017	char *lldpd_argv[] = {"lldpd", nvram_safe_get("lan_ifname"), NULL};
2018	pid_t pid;
2019
2020	_eval(lldpd_argv, NULL, 0, &pid);
2021
2022	return 0;
2023}
2024#endif
2025// -----------------------------------------------------------------------------
2026#ifdef LINUX26
2027
2028static pid_t pid_hotplug2 = -1;
2029
2030void start_hotplug2(void)
2031{
2032	stop_hotplug2();
2033
2034	f_write_string("/proc/sys/kernel/hotplug", "", FW_NEWLINE, 0);
2035	xstart("hotplug2", "--persistent", "--no-coldplug");
2036	// FIXME: Don't remember exactly why I put "sleep" here -
2037	// but it was not for a race with check_services()... - TB
2038	sleep(1);
2039
2040	if (!nvram_contains_word("debug_norestart", "hotplug2")) {
2041		pid_hotplug2 = -2;
2042	}
2043}
2044
2045void stop_hotplug2(void)
2046{
2047	pid_hotplug2 = -1;
2048	killall_tk("hotplug2");
2049}
2050
2051#endif	/* LINUX26 */
2052
2053
2054void
2055stop_infosvr()
2056{
2057	killall_tk("infosvr");
2058}
2059
2060int
2061start_infosvr()
2062{
2063	char *infosvr_argv[] = {"/usr/sbin/infosvr", "br0", NULL};
2064	pid_t pid;
2065
2066	return _eval(infosvr_argv, NULL, 0, &pid);
2067}
2068
2069#ifdef RTCONFIG_RALINK
2070int
2071exec_8021x_start(int band, int is_iNIC)
2072{
2073	char tmp[100], prefix[] = "wlXXXXXXX_";
2074	char *str;
2075	int flag_8021x = 0;
2076	int i;
2077
2078	if (nvram_get_int("sw_mode") == SW_MODE_REPEATER && nvram_get_int("wlc_band") == band)
2079		return 0;
2080
2081	for (i = 0; i < MAX_NO_MSSID; i++)
2082	{
2083		if (i)
2084		{
2085			sprintf(prefix, "wl%d.%d_", band, i);
2086
2087			if (!nvram_match(strcat_r(prefix, "bss_enabled", tmp), "1"))
2088				continue;
2089		}
2090		else
2091			sprintf(prefix, "wl%d_", band);
2092
2093		str = nvram_safe_get(strcat_r(prefix, "auth_mode_x", tmp));
2094
2095		if(str && strlen(str) > 0)
2096		{
2097			if (    !strcmp(str, "radius") ||
2098				!strcmp(str, "wpa") ||
2099				!strcmp(str, "wpa2") ||
2100				!strcmp(str, "wpawpa2") )
2101			{ //need daemon
2102				flag_8021x = 1;
2103				break;
2104			}
2105		}
2106	}
2107
2108	if(flag_8021x)
2109	{
2110		if (is_iNIC)
2111			return xstart("rtinicapd");
2112		else
2113			return xstart("rt2860apd");
2114	}
2115	return 0;
2116}
2117
2118int
2119start_8021x(void)
2120{
2121	char word[256], *next;
2122
2123	foreach (word, nvram_safe_get("wl_ifnames"), next) {
2124		if (!strcmp(word, WIF_2G))
2125		{
2126			if (!strncmp(word, "rai", 3))	// iNIC
2127				exec_8021x_start(0, 1);
2128			else
2129				exec_8021x_start(0, 0);
2130		}
2131#if defined(RTCONFIG_HAS_5G)
2132		else if (!strcmp(word, WIF_5G))
2133		{
2134			if (!strncmp(word, "rai", 3))	// iNIC
2135				exec_8021x_start(1, 1);
2136			else
2137				exec_8021x_start(1, 0);
2138		}
2139#endif	/* RTCONFIG_HAS_5G */
2140	}
2141
2142	return 0;
2143}
2144
2145int
2146exec_8021x_stop(int band, int is_iNIC)
2147{
2148		if (is_iNIC)
2149			return killall("rtinicapd", SIGTERM);
2150		else
2151			return killall("rt2860apd", SIGTERM);
2152}
2153
2154int
2155stop_8021x(void)
2156{
2157	char word[256], *next;
2158
2159	foreach (word, nvram_safe_get("wl_ifnames"), next) {
2160		if (!strcmp(word, WIF_2G))
2161		{
2162			if (!strncmp(word, "rai", 3))	// iNIC
2163				exec_8021x_stop(0, 1);
2164			else
2165				exec_8021x_stop(0, 0);
2166		}
2167#if defined(RTCONFIG_HAS_5G)
2168		else if (!strcmp(word, WIF_5G))
2169		{
2170			if (!strncmp(word, "rai", 3))	// iNIC
2171				exec_8021x_stop(1, 1);
2172			else
2173				exec_8021x_stop(1, 0);
2174		}
2175#endif	/* RTCONFIG_HAS_5G */
2176	}
2177
2178	return 0;
2179}
2180#endif
2181
2182void write_static_leases(char *file)
2183{
2184	FILE *fp;
2185	char *nv, *nvp, *b;
2186	char *mac, *ip;
2187
2188	fp=fopen(file, "w");
2189
2190	if (fp==NULL) return;
2191
2192	nv = nvp = strdup(nvram_safe_get("dhcp_staticlist"));
2193
2194	if(nv) {
2195	while ((b = strsep(&nvp, "<")) != NULL) {
2196		if((vstrsep(b, ">", &mac, &ip)!=2)) continue;
2197		if(strlen(mac)==0||strlen(ip)==0) continue;
2198		fprintf(fp, "%s %s\n", mac, ip);
2199	}
2200	free(nv);
2201	}
2202	fclose(fp);
2203}
2204
2205int
2206ddns_updated_main(int argc, char *argv[])
2207{
2208	FILE *fp;
2209	char buf[64], *ip;
2210
2211	if (!(fp=fopen("/tmp/ddns.cache", "r"))) return 0;
2212
2213	fgets(buf, sizeof(buf), fp);
2214	fclose(fp);
2215
2216	if (!(ip=strchr(buf, ','))) return 0;
2217
2218	nvram_set("ddns_cache", buf);
2219	nvram_set("ddns_ipaddr", ip+1);
2220	nvram_set("ddns_status", "1");
2221	nvram_set("ddns_server_x_old", nvram_safe_get("ddns_server_x"));
2222	nvram_set("ddns_hostname_old", nvram_safe_get("ddns_hostname_x"));
2223	nvram_set("ddns_updated", "1");
2224
2225	logmessage("ddns", "ddns update ok");
2226
2227	_dprintf("done\n");
2228
2229	return 0;
2230}
2231
2232// TODO: handle wan0 only now
2233int
2234start_ddns(void)
2235{
2236	FILE *fp;
2237	FILE *time_fp;
2238	char *wan_ip, *wan_ifname;
2239//	char *ddns_cache;
2240	char *server;
2241	char *user;
2242	char *passwd;
2243	char *host;
2244	char *service;
2245	char usrstr[64];
2246	int wild = nvram_get_int("ddns_wildcard_x");
2247	int unit, asus_ddns = 0;
2248	char tmp[32], prefix[] = "wanXXXXXXXXXX_";
2249	time_t now;
2250
2251	if (!is_routing_enabled()) {
2252		_dprintf("return -1\n");
2253		return -1;
2254	}
2255	if (nvram_invmatch("ddns_enable_x", "1"))
2256		return -1;
2257
2258	unit = wan_primary_ifunit();
2259	snprintf(prefix, sizeof(prefix), "wan%d_", unit);
2260
2261	wan_ip = nvram_safe_get(strcat_r(prefix, "ipaddr", tmp));
2262	wan_ifname = get_wan_ifname(unit);
2263
2264	if (!wan_ip || strcmp(wan_ip, "") == 0 || !inet_addr(wan_ip)) {
2265		logmessage("ddns", "WAN IP is empty.");
2266		return -1;
2267	}
2268
2269#if 0 //Move the ddns check mechanism to UI
2270	if(!nvram_match("ddns_update_by_wdog", "1")) {
2271		if ((inet_addr(wan_ip) == inet_addr(nvram_safe_get("ddns_ipaddr"))) &&
2272		    (strcmp(nvram_safe_get("ddns_server_x"), nvram_safe_get("ddns_server_x_old")) == 0) &&
2273		    (strcmp(nvram_safe_get("ddns_hostname_x"), nvram_safe_get("ddns_hostname_old")) == 0) &&
2274		    (nvram_match("ddns_updated", "1"))) {
2275			nvram_set("ddns_return_code", "no_change");
2276			logmessage("ddns", "IP address, server and hostname have not changed since the last update.");
2277			_dprintf("IP address, server and hostname have not changed since the last update.");
2278			return -1;
2279		}
2280
2281		// TODO : Check /tmp/ddns.cache to see current IP in DDNS
2282		// update when,
2283		// 	1. if ipaddr!= ipaddr in cache
2284		//
2285		// update
2286		// * nvram ddns_cache, the same with /tmp/ddns.cache
2287
2288		if (	(!nvram_match("ddns_server_x_old", "") &&
2289			strcmp(nvram_safe_get("ddns_server_x"), nvram_safe_get("ddns_server_x_old"))) ||
2290			(!nvram_match("ddns_hostname_x_old", "") &&
2291			strcmp(nvram_safe_get("ddns_hostname_x"), nvram_safe_get("ddns_hostname_x_old")))
2292		) {
2293			logmessage("ddns", "clear ddns cache file for server/hostname change");
2294			unlink("/tmp/ddns.cache");
2295		}
2296		else if (!(fp = fopen("/tmp/ddns.cache", "r")) && (ddns_cache = nvram_get("ddns_cache"))) {
2297			if ((fp = fopen("/tmp/ddns.cache", "w+"))) {
2298				fprintf(fp, "%s", ddns_cache);
2299				fclose(fp);
2300			}
2301		}
2302	}
2303	else
2304		nvram_unset("ddns_update_by_wdog");
2305#endif
2306
2307	server = nvram_safe_get("ddns_server_x");
2308	user = nvram_safe_get("ddns_username_x");
2309	passwd = nvram_safe_get("ddns_passwd_x");
2310	host = nvram_safe_get("ddns_hostname_x");
2311	unlink("/tmp/ddns.cache");
2312
2313	if (strcmp(server, "WWW.DYNDNS.ORG")==0)
2314		service = "dyndns";
2315	else if (strcmp(server, "WWW.DYNDNS.ORG(CUSTOM)")==0)
2316		service = "dyndns-custom";
2317	else if (strcmp(server, "WWW.DYNDNS.ORG(STATIC)")==0)
2318		service = "dyndns-static";
2319	else if (strcmp(server, "WWW.TZO.COM")==0)
2320		service = "tzo";
2321	else if (strcmp(server, "WWW.ZONEEDIT.COM")==0)
2322		service = "zoneedit";
2323	else if (strcmp(server, "WWW.JUSTLINUX.COM")==0)
2324		service = "justlinux";
2325	else if (strcmp(server, "WWW.EASYDNS.COM")==0)
2326		service = "easydns";
2327	else if (strcmp(server, "WWW.DNSOMATIC.COM")==0)
2328		service = "dnsomatic";
2329	else if (strcmp(server, "WWW.TUNNELBROKER.NET")==0)
2330		service = "heipv6tb";
2331	else if (strcmp(server, "WWW.NO-IP.COM")==0)
2332		service = "noip";
2333	else if (strcmp(server, "WWW.SELFHOST.DE") == 0)
2334		service = "selfhost";
2335	else if (strcmp(server, "WWW.ASUS.COM")==0) {
2336		service = "dyndns", asus_ddns = 1;
2337	}
2338	else if (strcmp(server, "WWW.GOOGLE-DDNS.COM")==0)
2339                service = "dyndns", asus_ddns=3;
2340	else if (strcmp(server, "WWW.ORAY.COM")==0) {
2341		service = "peanuthull", asus_ddns = 2;
2342	} else {
2343		logmessage("start_ddns", "Error ddns server name: %s\n", server);
2344		return 0;
2345	}
2346
2347	snprintf(usrstr, sizeof(usrstr), "%s:%s", user, passwd);
2348
2349	_dprintf("start_ddns update %s %s\n", server, service);
2350
2351	nvram_set("ddns_return_code", "ddns_query");
2352
2353	if (pids("ez-ipupdate")) {
2354		killall("ez-ipupdate", SIGINT);
2355		sleep(1);
2356	}
2357	if (pids("phddns")) {
2358		killall("phddns", SIGINT);
2359		sleep(1);
2360	}
2361
2362	nvram_unset("ddns_cache");
2363	nvram_unset("ddns_ipaddr");
2364	nvram_unset("ddns_status");
2365	nvram_unset("ddns_updated");
2366
2367       	_dprintf("asus_ddns : %d\n",asus_ddns);
2368#if 1
2369       	if(3 == asus_ddns)
2370	{
2371		if((time_fp=fopen("/tmp/ddns.cache","w")))
2372		{
2373			fprintf(time_fp,"%ld,%s",time(&now),wan_ip);
2374			fclose(time_fp);
2375		}
2376        	//_dprintf("run ddns-start.sh\n");
2377               	eval("ddns-start.sh",user,passwd,host);
2378               	//eval("ddns-start.sh",host,passwd);
2379
2380       	}
2381#endif
2382        else if (asus_ddns == 2) { //Peanuthull DDNS
2383		if( (fp = fopen("/etc/phddns.conf", "w")) != NULL ) {
2384			fprintf(fp, "[settings]\n");
2385			fprintf(fp, "szHost = phddns60.oray.net\n");
2386			fprintf(fp, "szUserID = %s\n", user);
2387			fprintf(fp, "szUserPWD = %s\n", passwd);
2388			fprintf(fp, "nicName = %s\n", wan_ifname);
2389			fprintf(fp, "szLog = /var/log/phddns.log\n");
2390			fclose(fp);
2391
2392			eval("phddns", "-c", "/etc/phddns.conf", "-d");
2393		}
2394	}
2395	else if (asus_ddns == 1) {
2396		char *nserver = nvram_invmatch("ddns_serverhost_x", "") ?
2397			nvram_safe_get("ddns_serverhost_x") :
2398			"nwsrv-ns1.asus.com";
2399		eval("ez-ipupdate",
2400		     "-S", service, "-i", wan_ifname, "-h", host,
2401		     "-A", "2", "-s", nserver,
2402		     "-e", "/sbin/ddns_updated", "-b", "/tmp/ddns.cache");
2403	} else if (*service) {
2404		eval("ez-ipupdate",
2405		     "-S", service, "-i", wan_ifname, "-h", host,
2406		     "-u", usrstr, wild ? "-w" : "",
2407		     "-e", "/sbin/ddns_updated", "-b", "/tmp/ddns.cache");
2408	}
2409
2410	return 0;
2411}
2412
2413void
2414stop_ddns(void)
2415{
2416	if (pids("ez-ipupdate"))
2417		killall("ez-ipupdate", SIGINT);
2418	if (pids("phddns"))
2419		killall("phddns", SIGINT);
2420}
2421
2422int
2423asusddns_reg_domain(int reg)
2424{
2425	FILE *fp;
2426	char *wan_ip, *wan_ifname;
2427	char *ddns_cache;
2428	char *nserver;
2429	int unit;
2430	char tmp[32], prefix[] = "wanXXXXXXXXXX_";
2431
2432	if (!is_routing_enabled()) {
2433		_dprintf("return -1\n");
2434		return -1;
2435	}
2436
2437	if (reg) { //0:Aidisk, 1:Advanced Setting
2438		if (nvram_invmatch("ddns_enable_x", "1"))
2439			return -1;
2440	}
2441
2442	unit = wan_primary_ifunit();
2443	snprintf(prefix, sizeof(prefix), "wan%d_", unit);
2444
2445	wan_ip = nvram_safe_get(strcat_r(prefix, "ipaddr", tmp));
2446	wan_ifname = get_wan_ifname(unit);
2447
2448	if (!wan_ip || strcmp(wan_ip, "") == 0 || !inet_addr(wan_ip)) {
2449		logmessage("asusddns", "WAN IP is empty.");
2450		return -1;
2451	}
2452
2453	// TODO : Check /tmp/ddns.cache to see current IP in DDNS,
2454	// update when ipaddr!= ipaddr in cache.
2455	// nvram ddns_cache, the same with /tmp/ddns.cache
2456
2457	if ((inet_addr(wan_ip) == inet_addr(nvram_safe_get("ddns_ipaddr"))) &&
2458		(strcmp(nvram_safe_get("ddns_server_x"), nvram_safe_get("ddns_server_x_old")) == 0) &&
2459		(strcmp(nvram_safe_get("ddns_hostname_x"), nvram_safe_get("ddns_hostname_old")) == 0)) {
2460		nvram_set("ddns_return_code", "no_change");
2461		logmessage("asusddns", "IP address, server and hostname have not changed since the last update.");
2462		return -1;
2463	}
2464
2465	if (	(!nvram_match("ddns_server_x_old", "") &&
2466		strcmp(nvram_safe_get("ddns_server_x"), nvram_safe_get("ddns_server_x_old"))) ||
2467		(!nvram_match("ddns_hostname_x_old", "") &&
2468		strcmp(nvram_safe_get("ddns_hostname_x"), nvram_safe_get("ddns_hostname_x_old")))
2469	) {
2470		logmessage("asusddns", "clear ddns cache file for server/hostname change");
2471		unlink("/tmp/ddns.cache");
2472	}
2473	else if (!(fp = fopen("/tmp/ddns.cache", "r")) && (ddns_cache = nvram_get("ddns_cache"))) {
2474		if ((fp = fopen("/tmp/ddns.cache", "w+"))) {
2475			fprintf(fp, "%s", ddns_cache);
2476			fclose(fp);
2477		}
2478	}
2479
2480	nvram_set("ddns_return_code", "ddns_query");
2481
2482	if (pids("ez-ipupdate"))
2483	{
2484		killall("ez-ipupdate", SIGINT);
2485		sleep(1);
2486	}
2487
2488	nserver = nvram_invmatch("ddns_serverhost_x", "") ?
2489		    nvram_safe_get("ddns_serverhost_x") :
2490		    "nwsrv-ns1.asus.com";
2491
2492	eval("ez-ipupdate",
2493	     "-S", "dyndns", "-i", wan_ifname, "-h", nvram_safe_get("ddns_hostname_x"),
2494	     "-A", "1", "-s", nserver,
2495	     "-e", "/sbin/ddns_updated", "-b", "/tmp/ddns.cache");
2496
2497	return 0;
2498}
2499
2500void
2501stop_syslogd(void)
2502{
2503#if defined(RTCONFIG_JFFS2LOG) && (defined(RTCONFIG_JFFS2)||defined(RTCONFIG_BRCM_NAND_JFFS2))
2504	int running = pids("syslogd");
2505#endif
2506
2507	killall_tk("syslogd");
2508
2509#if defined(RTCONFIG_JFFS2LOG) && (defined(RTCONFIG_JFFS2)||defined(RTCONFIG_BRCM_NAND_JFFS2))
2510	if (running)
2511		eval("cp", "/tmp/syslog.log", "/tmp/syslog.log-1", "/jffs");
2512#endif
2513}
2514
2515void
2516stop_klogd(void)
2517{
2518	killall_tk("klogd");
2519}
2520
2521int
2522start_syslogd(void)
2523{
2524	int argc;
2525	char syslog_path[PATH_MAX];
2526	char syslog_addr[sizeof("255.255.255.255:65535")];
2527	char *syslogd_argv[] = {"/sbin/syslogd",
2528		"-m", "0",				/* disable marks */
2529		"-S",					/* small log */
2530//		"-D",					/* suppress dups */
2531		"-O", syslog_path,			/* /tmp/syslog.log or /jffs/syslog.log */
2532		NULL, NULL,				/* -s log_size */
2533		NULL, NULL,				/* -l log_level */
2534		NULL, NULL,				/* -R log_ipaddr[:port] */
2535		NULL,					/* -L log locally too */
2536		NULL
2537	};
2538
2539	snprintf(syslog_path, sizeof(syslog_path), "%s", get_syslog_fname(0));
2540	for (argc = 0; syslogd_argv[argc]; argc++);
2541
2542	if (nvram_invmatch("log_size", "")) {
2543		syslogd_argv[argc++] = "-s";
2544		syslogd_argv[argc++] = nvram_safe_get("log_size");
2545	}
2546	if (nvram_invmatch("log_level", "")) {
2547		syslogd_argv[argc++] = "-l";
2548		syslogd_argv[argc++] = nvram_safe_get("log_level");
2549	}
2550	if (nvram_invmatch("log_ipaddr", "")) {
2551		char *addr = nvram_safe_get("log_ipaddr");
2552		int port = nvram_get_int("log_port");
2553
2554		if (port) {
2555			snprintf(syslog_addr, sizeof(syslog_addr), "%s:%d", addr, port);
2556			addr = syslog_addr;
2557		}
2558		syslogd_argv[argc++] = "-R";
2559		syslogd_argv[argc++] = addr;
2560		syslogd_argv[argc++] = "-L";
2561	}
2562
2563//#if defined(RTCONFIG_JFFS2LOG) && defined(RTCONFIG_JFFS2)
2564#if defined(RTCONFIG_JFFS2LOG) && (defined(RTCONFIG_JFFS2)||defined(RTCONFIG_BRCM_NAND_JFFS2))
2565	eval("touch", "-c", "/jffs/syslog.log", "/jffs/syslog.log-1");
2566	eval("cp", "/jffs/syslog.log", "/jffs/syslog.log-1", "/tmp");
2567#endif
2568
2569	// TODO: make sure is it necessary?
2570	//time_zone_x_mapping();
2571	//setenv("TZ", nvram_safe_get("time_zone_x"), 1);
2572
2573	return _eval(syslogd_argv, NULL, 0, NULL);
2574}
2575
2576int
2577start_klogd(void)
2578{
2579	int argc;
2580	char *klogd_argv[] = {"/sbin/klogd",
2581		NULL, NULL,				/* -c console_loglevel */
2582		NULL
2583	};
2584
2585	for (argc = 0; klogd_argv[argc]; argc++);
2586
2587	if (nvram_invmatch("console_loglevel", "")) {
2588		klogd_argv[argc++] = "-c";
2589		klogd_argv[argc++] = nvram_safe_get("console_loglevel");
2590	}
2591
2592	return _eval(klogd_argv, NULL, 0, NULL);
2593}
2594
2595int
2596start_logger(void)
2597{
2598_dprintf("%s:\n", __FUNCTION__);
2599	start_syslogd();
2600	start_klogd();
2601
2602#if defined(DUMP_PREV_OOPS_MSG) && defined(RTCONFIG_BCMARM)
2603#if defined(RTAC88U) || defined(RTAC3100) || defined(RTAC5300)|| defined(RTAC5300R)
2604	eval("et", "dump", "oops");
2605#else
2606	eval("et", "dump_oops");
2607#endif
2608#endif
2609
2610	return 0;
2611}
2612
2613#ifdef RTCONFIG_BCMWL6
2614int
2615wl_igs_enabled(void)
2616{
2617	int i;
2618	char tmp[100], prefix[] = "wlXXXXXXXXXXXXXX";
2619	char word[256], *next, ifnames[128];
2620
2621	i = 0;
2622	strcpy(ifnames, nvram_safe_get("wl_ifnames"));
2623	foreach (word, ifnames, next) {
2624		if (i >= MAX_NR_WL_IF)
2625			break;
2626
2627		snprintf(prefix, sizeof(prefix), "wl%d_", i);
2628		if (nvram_match(strcat_r(prefix, "radio", tmp), "1") &&
2629		    nvram_match(strcat_r(prefix, "igs", tmp), "1"))
2630			return 1;
2631
2632		i++;
2633	}
2634
2635	return 0;
2636}
2637
2638void
2639start_igmp_proxy(void)
2640{
2641	/* Start IGMP Proxy in Router mode only */
2642#if 0
2643	if (nvram_get_int("sw_mode") == SW_MODE_ROUTER)
2644		eval("igmp", nvram_get("wan_ifname"));
2645	else
2646#endif
2647	if (nvram_get_int("sw_mode") == SW_MODE_AP)
2648	{
2649		if (nvram_get_int("emf_enable") || wl_igs_enabled()) {
2650			/* Start IGMP proxy in AP mode */
2651			eval("igmp", nvram_get("lan_ifname"));
2652		}
2653	}
2654}
2655
2656void
2657stop_igmp_proxy(void)
2658{
2659	killall_tk("igmp");
2660}
2661
2662void
2663stop_acsd(void)
2664{
2665	killall_tk("acsd");
2666}
2667
2668int
2669start_acsd()
2670{
2671	int ret = 0;
2672
2673	if(nvram_match("nowl", "1")) return 0;
2674
2675#ifdef RTCONFIG_PROXYSTA
2676	if (psta_exist())
2677		return 0;
2678#endif
2679
2680	stop_acsd();
2681
2682	if (!restore_defaults_g && strlen(nvram_safe_get("acs_ifnames")))
2683		ret = eval("/usr/sbin/acsd");
2684
2685	return ret;
2686}
2687#endif
2688
2689void
2690stop_misc(void)
2691{
2692	fprintf(stderr, "stop_misc()\n");
2693
2694	if (pids("infosvr"))
2695		killall_tk("infosvr");
2696
2697#ifdef RTCONFIG_SMALL_FW_UPDATE
2698	if (pids("watchdog02"))
2699		killall_tk("watchdog02");
2700#endif
2701#ifdef SW_DEVLED
2702	if (pids("sw_devled"))
2703		killall_tk("sw_devled");
2704#endif
2705	if (pids("watchdog")
2706#if defined(RTAC68U) || defined(RTCONFIG_FORCE_AUTO_UPGRADE)
2707		&& !nvram_get_int("auto_upgrade")
2708#endif
2709	)
2710		killall_tk("watchdog");
2711
2712#ifdef RTCONFIG_FANCTRL
2713	if (pids("phy_tempsense"))
2714		killall_tk("phy_tempsense");
2715#endif
2716#ifdef RTCONFIG_BCMWL6
2717#ifdef RTCONFIG_PROXYSTA
2718	if (pids("psta_monitor"))
2719		killall_tk("psta_monitor");
2720#endif
2721#ifdef RTCONFIG_IPERF
2722	if (pids("monitor"))
2723		killall_tk("monitor");
2724#endif
2725#endif
2726#ifdef RTCONFIG_QTN
2727	if (pids("qtn_monitor"))
2728		killall_tk("qtn_monitor");
2729#endif
2730	if (pids("ntp"))
2731		killall_tk("ntp");
2732	if (pids("ntpclient"))
2733		killall_tk("ntpclient");
2734
2735#ifdef RTCONFIG_BCMWL6
2736#ifdef BCM_ASPMD
2737	stop_aspmd();
2738#endif
2739	stop_acsd();
2740#ifdef BCM_BSD
2741	stop_bsd();
2742#endif
2743#ifdef BCM_SSD
2744	stop_ssd();
2745#endif
2746#if defined(RTCONFIG_DHDAP)
2747	stop_dhd_monitor();
2748#endif
2749	stop_igmp_proxy();
2750#ifdef RTCONFIG_HSPOT
2751	stop_hspotap();
2752#endif
2753#endif
2754	stop_wps();
2755#ifdef RTCONFIG_BCMWL6
2756#endif
2757	stop_upnp();
2758	stop_lltd();
2759	stop_rstats();
2760#ifdef RTCONFIG_DSL
2761	stop_spectrum(); //Ren
2762#endif //For DSL-N55U
2763	stop_networkmap();
2764}
2765
2766void
2767stop_misc_no_watchdog(void)
2768{
2769	_dprintf("done\n");
2770}
2771
2772int
2773chpass(char *user, char *pass)
2774{
2775//	FILE *fp;
2776
2777	if (!user)
2778		user = "admin";
2779
2780	if (!pass)
2781		pass = "admin";
2782/*
2783	if ((fp = fopen("/etc/passwd", "a")))
2784	{
2785		fprintf(fp, "%s::0:0::/:\n", user);
2786		fclose(fp);
2787	}
2788
2789	if ((fp = fopen("/etc/group", "a")))
2790	{
2791		fprintf(fp, "%s:x:0:%s\n", user, user);
2792		fclose(fp);
2793	}
2794*/
2795	eval("chpasswd.sh", user, pass);
2796	return 0;
2797}
2798
2799void
2800set_hostname(void)
2801{
2802	FILE *fp;
2803	const char *p;
2804
2805	if ((p = get_productid()) != NULL && (*p) != '\0')
2806	{
2807		if ((fp=fopen("/proc/sys/kernel/hostname", "w+")))
2808		{
2809			fputs(p, fp);
2810			fclose(fp);
2811		}
2812	}
2813}
2814
2815int
2816_start_telnetd(int force)
2817{
2818	char *telnetd_argv[] = { "telnetd",
2819		NULL, NULL,	/* -b address */
2820		NULL };
2821	int index = 1;
2822
2823	if (!force) {
2824		if (!nvram_get_int("telnetd_enable"))
2825			return 0;
2826
2827		if (getpid() != 1) {
2828			notify_rc("start_telnetd");
2829			return 0;
2830		}
2831	}
2832
2833	if (pids("telnetd"))
2834		killall_tk("telnetd");
2835
2836	set_hostname();
2837	setup_passwd();
2838	//chpass(nvram_safe_get("http_username"), nvram_safe_get("http_passwd"));	// vsftpd also needs
2839
2840	if (is_routing_enabled()) {
2841		telnetd_argv[index++] = "-b";
2842		telnetd_argv[index++] = nvram_safe_get("lan_ipaddr");
2843	}
2844
2845	return _eval(telnetd_argv, NULL, 0, NULL);
2846}
2847
2848int
2849start_telnetd(void)
2850{
2851	return _start_telnetd(0);
2852}
2853
2854void
2855stop_telnetd(void)
2856{
2857	if (getpid() != 1) {
2858		notify_rc("stop_telnetd");
2859		return;
2860	}
2861
2862	if (pids("telnetd"))
2863		killall_tk("telnetd");
2864}
2865
2866void
2867start_httpd(void)
2868{
2869	char *httpd_argv[] = { "httpd",
2870	/*	"-p", nvram_safe_get("http_lanport"),*/
2871		NULL, NULL,	/* -i ifname */
2872		NULL };
2873	int httpd_index = 1;
2874#ifdef RTCONFIG_HTTPS
2875	char *https_argv[] = { "httpds", "-s",
2876		"-p", nvram_safe_get("https_lanport"),
2877		NULL, NULL,	/* -i ifname */
2878		NULL };
2879	int https_index = 4;
2880	int enable;
2881#endif
2882	char *cur_dir;
2883	pid_t pid;
2884#ifdef DEBUG_RCTEST
2885	char *httpd_dir;
2886#endif
2887
2888	if (getpid() != 1) {
2889		notify_rc("start_httpd");
2890		return;
2891	}
2892
2893	cur_dir = getcwd(NULL, 0);
2894#ifdef DEBUG_RCTEST // Left for UI debug
2895	httpd_dir = nvram_safe_get("httpd_dir");
2896	if(strlen(httpd_dir)) chdir(httpd_dir);
2897	else
2898#endif
2899	chdir("/www");
2900
2901	if (is_routing_enabled()) {
2902		httpd_argv[httpd_index++] = "-i";
2903		httpd_argv[httpd_index++] = nvram_safe_get("lan_ifname");
2904#ifdef RTCONFIG_HTTPS
2905		https_argv[https_index++] = "-i";
2906		https_argv[https_index++] = nvram_safe_get("lan_ifname");
2907#endif
2908	}
2909
2910#ifdef RTCONFIG_HTTPS
2911	enable = nvram_get_int("http_enable");
2912	if (enable != 0) {
2913		logmessage(LOGNAME, "start httpd - SSL");
2914		_eval(https_argv, NULL, 0, &pid);
2915	}
2916	if (enable != 1)
2917#endif
2918	{
2919		logmessage(LOGNAME, "start httpd");
2920		_eval(httpd_argv, NULL, 0, &pid);
2921	}
2922
2923	chdir(cur_dir ? : "/");
2924	free(cur_dir);
2925}
2926
2927void
2928stop_httpd(void)
2929{
2930	if (getpid() != 1) {
2931		notify_rc("stop_httpd");
2932		return;
2933	}
2934
2935	if (pids("httpd"))
2936		killall_tk("httpd");
2937#ifdef RTCONFIG_HTTPS
2938	if (pids("httpds"))
2939		killall_tk("httpds");
2940#endif
2941}
2942
2943//////////vvvvvvvvvvvvvvvvvvvvvjerry5 2009.07
2944void
2945stop_rstats(void)
2946{
2947	if (pids("rstats"))
2948		killall_tk("rstats");
2949}
2950
2951void
2952start_rstats(int new)
2953{
2954	if (!is_routing_enabled()) return;
2955
2956	stop_rstats();
2957	if (new) xstart("rstats", "--new");
2958	else xstart("rstats");
2959}
2960
2961void
2962restart_rstats()
2963{
2964	if (nvram_match("rstats_bak", "1"))
2965	{
2966		nvram_set("rstats_path", "*nvram");
2967		if (nvram_match("rstats_new", "1"))
2968		{
2969			start_rstats(1);
2970			nvram_set("rstats_new", "0");
2971		}
2972		else
2973			start_rstats(0);
2974	}
2975	else
2976	{
2977		nvram_set("rstats_path", "");
2978		start_rstats(0);
2979	}
2980}
2981////////^^^^^^^^^^^^^^^^^^^jerry5 2009.07
2982
2983//Ren.B
2984#ifdef RTCONFIG_DSL
2985void stop_spectrum(void)
2986{
2987	if (getpid() != 1) {
2988		notify_rc("stop_spectrum");
2989		return;
2990	}
2991
2992	if (pids("spectrum"))
2993		killall_tk("spectrum");
2994}
2995
2996void start_spectrum(void)
2997{
2998	if (getpid() != 1) {
2999		notify_rc("start_spectrum");
3000		return;
3001	}
3002
3003	stop_spectrum();
3004	xstart("spectrum");
3005}
3006#endif
3007//Ren.E
3008
3009// TODO: so far, support wan0 only
3010
3011void start_upnp(void)
3012{
3013	FILE *f;
3014	char tmp[100], prefix[sizeof("wanXXXXXXXXXX_")];
3015	char et0macaddr[18];
3016	char *proto, *port, *lport, *dstip, *desc;
3017	char *nv, *nvp, *b;
3018	int upnp_enable, upnp_mnp_enable, upnp_port;
3019	int unit, i, httpx_port;
3020#if defined(RTCONFIG_APP_PREINSTALLED) || defined(RTCONFIG_APP_NETINSTALLED)
3021	FILE *ifp = NULL;
3022	char tmpstr[80];
3023	int statDownloadMaster = 0;
3024#endif
3025
3026	if (getpid() != 1) {
3027		notify_rc("start_upnp");
3028		return;
3029	}
3030
3031	if (!is_routing_enabled())
3032		return;
3033
3034	unit = wan_primary_ifunit();
3035	snprintf(prefix, sizeof(prefix), "wan%d_", unit);
3036
3037	upnp_enable = nvram_get_int("upnp_enable");
3038	upnp_mnp_enable = nvram_get_int("upnp_mnp");
3039
3040	if (nvram_get_int(strcat_r(prefix, "upnp_enable", tmp))) {
3041		mkdir("/etc/upnp", 0777);
3042		if (f_exists("/etc/upnp/config.alt")) {
3043			xstart("miniupnpd", "-f", "/etc/upnp/config.alt");
3044		} else {
3045			if ((f = fopen("/etc/upnp/config", "w")) != NULL) {
3046				char *lanip = nvram_safe_get("lan_ipaddr");
3047				char *lanmask = nvram_safe_get("lan_netmask");
3048
3049				upnp_port = nvram_get_int("upnp_port");
3050				if (upnp_port < 0 || upnp_port > 65535)
3051					upnp_port = 0;
3052
3053#if defined(RTCONFIG_RGMII_BRCM5301X) || defined(RTCONFIG_QCA)
3054				strcpy(et0macaddr, nvram_safe_get("lan_hwaddr"));
3055#elif defined(RTCONFIG_GMAC3)
3056				if (nvram_match("gmac3_enable", "1"))
3057					strcpy(et0macaddr, nvram_safe_get("et2macaddr"));
3058				else
3059					strcpy(et0macaddr, nvram_safe_get("et0macaddr"));
3060#else
3061				strcpy(et0macaddr, nvram_safe_get("et0macaddr"));
3062#endif
3063				if (strlen(et0macaddr))
3064					for (i = 0; i < strlen(et0macaddr); i++)
3065						et0macaddr[i] = tolower(et0macaddr[i]);;
3066
3067				fprintf(f,
3068					"ext_ifname=%s\n"
3069					"listening_ip=%s/%s\n"
3070					"port=%d\n"
3071					"enable_upnp=%s\n"
3072					"enable_natpmp=%s\n"
3073					"secure_mode=%s\n"
3074					"upnp_forward_chain=FUPNP\n"
3075					"upnp_nat_chain=VUPNP\n"
3076					"notify_interval=%d\n"
3077					"system_uptime=yes\n"
3078					"friendly_name=%s\n"
3079					"model_number=%s.%s\n"
3080					"serial=%s\n"
3081					"lease_file=%s\n",
3082					get_wan_ifname(wan_primary_ifunit()),
3083					lanip, lanmask,
3084					upnp_port,
3085					upnp_enable ? "yes" : "no",	// upnp enable
3086					upnp_mnp_enable ? "yes" : "no",	// natpmp enable
3087					nvram_get_int("upnp_secure") ? "yes" : "no",	// secure_mode (only forward to self)
3088					nvram_get_int("upnp_ssdp_interval"),
3089					get_productid(),
3090					rt_version, rt_serialno,
3091					nvram_get("serial_no") ? : et0macaddr,
3092					"/tmp/upnp.leases");
3093
3094				if (nvram_get_int("upnp_clean")) {
3095					int interval = nvram_get_int("upnp_clean_interval");
3096					if (interval < 60)
3097						interval = 60;
3098					fprintf(f,
3099						"clean_ruleset_interval=%d\n"
3100						"clean_ruleset_threshold=%d\n",
3101						interval,
3102						nvram_get_int("upnp_clean_threshold"));
3103				} else
3104					fprintf(f,"clean_ruleset_interval=%d\n", 0);
3105
3106				// Empty parameters are not included into XML service description
3107				fprintf(f, "presentation_url=");
3108#ifdef RTCONFIG_HTTPS
3109				if (nvram_get_int("http_enable") == 1) {
3110					fprintf(f, "%s://%s:%d/\n", "https", lanip, nvram_get_int("https_lanport") ? : 443);
3111				} else
3112#endif
3113				{
3114					fprintf(f, "%s://%s:%d/\n", "http", lanip, /*nvram_get_int("http_lanport") ? :*/ 80);
3115				}
3116
3117				char uuid[45];
3118				f_read_string("/proc/sys/kernel/random/uuid", uuid, sizeof(uuid));
3119				fprintf(f, "uuid=%s\n", uuid);
3120
3121				if (is_nat_enabled() && nvram_match("vts_enable_x", "1")) {
3122					nvp = nv = strdup(nvram_safe_get("vts_rulelist"));
3123					while (nv && (b = strsep(&nvp, "<")) != NULL) {
3124						char *portv, *portp, *c;
3125
3126						if ((vstrsep(b, ">", &desc, &port, &dstip, &lport, &proto) != 5))
3127							continue;
3128
3129						// Handle port1,port2,port3 format
3130						portp = portv = strdup(port);
3131						while (portv && (c = strsep(&portp, ",")) != NULL) {
3132							if (strcmp(proto, "TCP") == 0 || strcmp(proto, "BOTH") == 0) {
3133								fprintf(f, "deny %s 0.0.0.0/0 0-65535\n", c);
3134
3135								int local_ftpport = nvram_get_int("vts_ftpport");
3136								if (!strcmp(c, "21") && local_ftpport != 0 && local_ftpport != 21)
3137									fprintf(f, "deny %d 0.0.0.0/0 0-65535\n", local_ftpport);
3138							}
3139							if (strcmp(proto, "UDP") == 0 || strcmp(proto, "BOTH") == 0)
3140								fprintf(f, "deny %s 0.0.0.0/0 0-65535\n", c);
3141						}
3142						free(portv);
3143					}
3144					free(nv);
3145				}
3146
3147				if (nvram_get_int("misc_http_x")) {
3148#ifdef RTCONFIG_HTTPS
3149					int enable = nvram_get_int("http_enable");
3150					if (enable != 0) {
3151						httpx_port = nvram_get_int("misc_httpsport_x") ? : 8443;
3152						fprintf(f, "deny %d 0.0.0.0/0 0-65535\n", httpx_port);
3153					}
3154					if (enable != 1)
3155#endif
3156					{
3157						httpx_port = nvram_get_int("misc_httpport_x") ? : 8080;
3158						fprintf(f, "deny %d 0.0.0.0/0 0-65535\n", httpx_port);
3159					}
3160				}
3161
3162#ifdef RTCONFIG_WEBDAV
3163				if (nvram_match("enable_webdav", "1") && nvram_match("webdav_aidisk", "1")) {
3164					httpx_port = nvram_get_int("webdav_https_port");
3165					if (!httpx_port || httpx_port > 65535)
3166						httpx_port = 443;
3167					fprintf(f, "deny %d 0.0.0.0/0 0-65535\n", httpx_port);
3168
3169					httpx_port = nvram_get_int("webdav_http_port");
3170					if (!httpx_port || httpx_port > 65535)
3171						httpx_port = 8082;
3172					fprintf(f, "deny %d 0.0.0.0/0 0-65535\n", httpx_port);
3173				}
3174#endif
3175
3176#if defined(RTCONFIG_APP_PREINSTALLED) || defined(RTCONFIG_APP_NETINSTALLED)
3177				ifp = fopen("/opt/lib/ipkg/status", "r");
3178				if (ifp) {
3179					while (fgets(tmpstr, 80, ifp)) {
3180						if (strstr(tmpstr, "downloadmaster")) {
3181							statDownloadMaster = 1; //installed
3182							break;
3183						}
3184					}
3185					fclose(ifp);
3186				}
3187
3188				if (statDownloadMaster == 1) {
3189					ifp = fopen("/opt/lib/ipkg/info/downloadmaster.control", "r");
3190					if (ifp) {
3191						while (fgets(tmpstr, 80, ifp)) {
3192							if (strstr(tmpstr, "Enabled") && strstr(tmpstr, "yes")) {
3193								statDownloadMaster = 2; //installed and enabled
3194								break;
3195							}
3196						}
3197						fclose(ifp);
3198					}
3199				}
3200
3201				if (statDownloadMaster == 2) {
3202					// Transmisson
3203					fprintf(f, "deny %d 0.0.0.0/0 0-65535\n", nvram_get_int("trs_peer_port"));
3204					// amuled
3205					fprintf(f, "deny %d 0.0.0.0/0 0-65535\n", 4662);
3206					fprintf(f, "deny %d 0.0.0.0/0 0-65535\n", 4665);
3207					fprintf(f, "deny %d 0.0.0.0/0 0-65535\n", 4672);
3208					// lighttpd
3209					if (nvram_match("gen_http_x", "1"))
3210						fprintf(f, "deny %d 0.0.0.0/0 0-65535\n", nvram_get_int("dm_http_port"));
3211				}
3212#endif
3213
3214				int ports[4];
3215				if ((ports[0] = nvram_get_int("upnp_min_port_int")) > 0 &&
3216				    (ports[1] = nvram_get_int("upnp_max_port_int")) > 0 &&
3217				    (ports[2] = nvram_get_int("upnp_min_port_ext")) > 0 &&
3218				    (ports[3] = nvram_get_int("upnp_max_port_ext")) > 0) {
3219					fprintf(f,
3220						"allow %d-%d %s/%s %d-%d\n",
3221						ports[0], ports[1],
3222						lanip, lanmask,
3223						ports[2], ports[3]
3224					);
3225				}
3226				else {
3227					// by default allow only redirection of ports above 1024
3228					fprintf(f, "allow 1024-65535 %s/%s 1024-65535\n", lanip, lanmask);
3229				}
3230
3231				fappend(f, "/etc/upnp/config.custom");
3232				fprintf(f, "\ndeny 0-65535 0.0.0.0/0 0-65535\n");
3233				fclose(f);
3234				xstart("miniupnpd", "-f", "/etc/upnp/config");
3235			}
3236		}
3237	}
3238}
3239
3240void stop_upnp(void)
3241{
3242	if (getpid() != 1) {
3243		notify_rc("stop_upnp");
3244		return;
3245	}
3246
3247	killall_tk("miniupnpd");
3248}
3249
3250void reload_upnp(void)
3251{
3252	char tmp[100], prefix[sizeof("wanXXXXXXXXXX_")];
3253	int unit;
3254
3255	if (!is_routing_enabled())
3256		return;
3257
3258	unit = wan_primary_ifunit();
3259	snprintf(prefix, sizeof(prefix), "wan%d_", unit);
3260
3261	if (nvram_get_int(strcat_r(prefix, "upnp_enable", tmp)))
3262		killall("miniupnpd", SIGUSR1);
3263}
3264
3265int
3266start_ntpc(void)
3267{
3268	char *ntp_argv[] = {"ntp", NULL};
3269	int pid;
3270
3271	if (pids("ntpclient"))
3272		killall_tk("ntpclient");
3273
3274	if (!pids("ntp"))
3275		_eval(ntp_argv, NULL, 0, &pid);
3276
3277	return 0;
3278}
3279
3280void
3281stop_ntpc(void)
3282{
3283	if (pids("ntpclient"))
3284		killall_tk("ntpclient");
3285}
3286
3287
3288void refresh_ntpc(void)
3289{
3290	setup_timezone();
3291
3292	if (pids("ntpclient"))
3293		killall_tk("ntpclient");
3294
3295	if (!pids("ntp"))
3296	{
3297		stop_ntpc();
3298		start_ntpc();
3299	}
3300	else
3301		kill_pidfile_s("/var/run/ntp.pid", SIGALRM);
3302}
3303
3304int start_lltd(void)
3305{
3306	chdir("/usr/sbin");
3307
3308#ifdef CONFIG_BCMWL5
3309	char *odmpid = nvram_safe_get("odmpid");
3310	int model = get_model();
3311
3312	if (strlen(odmpid) && is_valid_hostname(odmpid))
3313	{
3314		switch (model) {
3315		case MODEL_RTN66U:
3316			eval("lld2d.rtn66r", "br0");
3317			break;
3318		case MODEL_RTAC66U:
3319			if (!strcmp(odmpid, "RT-AC66R"))
3320				eval("lld2d.rtac66r", "br0");
3321			else if (!strcmp(odmpid, "RT-AC66W"))
3322				eval("lld2d.rtac66w", "br0");
3323			else if (!strcmp(odmpid, "RT-AC1750"))
3324				eval("lld2d.rtac1750", "br0");
3325			break;
3326		case MODEL_RTAC68U:
3327			if (!strcmp(odmpid, "RT-AC68P"))
3328				eval("lld2d.rtac68p", "br0");
3329			else if (!strcmp(odmpid, "RT-AC68R"))
3330				eval("lld2d.rtac68r", "br0");
3331			else if (!strcmp(odmpid, "RT-AC68W"))
3332				eval("lld2d.rtac68w", "br0");
3333			else if (!strcmp(odmpid, "RT-AC68RW"))
3334				eval("lld2d.rtac68rw", "br0");
3335			else if (!strcmp(odmpid, "RT-AC1900"))
3336				eval("lld2d.rtac1900", "br0");
3337			else if (!strcmp(odmpid, "RT-AC1900P"))
3338				eval("lld2d.rtac1900p", "br0");
3339			else if (!strcmp(odmpid, "RT-AC66U V2"))
3340				eval("lld2d.rtac66u_v2", "br0");
3341			else if (!strcmp(odmpid, "RT-AC68A"))
3342				eval("lld2d.rtac68a", "br0");
3343			else if (!strcmp(odmpid, "RT-AC68UF"))
3344				eval("lld2d.rtac68ui", "br0");
3345			break;
3346		case MODEL_DSLAC68U:
3347			if (!strcmp(odmpid, "DSL-AC68R"))
3348				eval("lld2d.dslac68r", "br0");
3349			else
3350				eval("lld2d", "br0");
3351			break;
3352		default:
3353			eval("lld2d", "br0");
3354			break;
3355		}
3356	}
3357	else
3358#endif
3359		eval("lld2d", "br0");
3360
3361	chdir("/");
3362
3363	return 0;
3364}
3365
3366void stop_lltd(void)
3367{
3368#ifdef CONFIG_BCMWL5
3369	char *odmpid = nvram_safe_get("odmpid");
3370	int model = get_model();
3371	if (strlen(odmpid) && is_valid_hostname(odmpid))
3372	{
3373		switch (model) {
3374		case MODEL_RTN66U:
3375			killall_tk("lld2d.rtn66r");
3376			break;
3377		case MODEL_RTAC66U:
3378			killall_tk("lld2d.rtac66r");
3379			break;
3380		case MODEL_RTAC68U:
3381			if (!strcmp(odmpid, "RT-AC68P"))
3382				killall_tk("lld2d.rtac68p");
3383			else if (!strcmp(odmpid, "RT-AC68R"))
3384				killall_tk("lld2d.rtac68r");
3385			else if (!strcmp(odmpid, "RT-AC68W"))
3386				killall_tk("lld2d.rtac68w");
3387			else if (!strcmp(odmpid, "RT-AC68RW"))
3388				killall_tk("lld2d.rtac68rw");
3389			else if (!strcmp(odmpid, "RT-AC1900"))
3390				killall_tk("lld2d.rtac1900");
3391			else if (!strcmp(odmpid, "RT-AC1900P"))
3392				killall_tk("lld2d.rtac1900p");
3393			else if (!strcmp(odmpid, "RT-AC66U V2"))
3394				killall_tk("lld2d.rtac66u_v2");
3395			else if (!strcmp(odmpid, "RT-AC68A"))
3396				killall_tk("lld2d.rtac68a");
3397			else if (!strcmp(odmpid, "RT-AC68UF"))
3398				killall_tk("lld2d.rtac68uf");
3399			break;
3400		case MODEL_DSLAC68U:
3401			if (!strcmp(odmpid, "DSL-AC68R"))
3402				killall_tk("lld2d.dslac68r");
3403			else
3404				killall_tk("lld2d");
3405			break;
3406		default:
3407			killall_tk("lld2d");
3408			break;
3409		}
3410	}
3411	else
3412#endif
3413	killall_tk("lld2d");
3414}
3415
3416#if defined(RTCONFIG_MDNS)
3417
3418#define AVAHI_CONFIG_PATH	"/tmp/avahi"
3419#define AVAHI_SERVICES_PATH	"/tmp/avahi/services"
3420#define AVAHI_CONFIG_FN		"avahi-daemon.conf"
3421#define AVAHI_AFPD_SERVICE_FN	"afpd.service"
3422#define AVAHI_ADISK_SERVICE_FN	"adisk.service"
3423#define AVAHI_ITUNE_SERVICE_FN  "mt-daap.service"
3424#define TIMEMACHINE_BACKUP_NAME	"Backups.backupdb"
3425
3426int generate_mdns_config(void)
3427{
3428	FILE *fp;
3429	char avahi_config[80];
3430	char et0macaddr[18];
3431	int ret = 0;
3432
3433	sprintf(avahi_config, "%s/%s", AVAHI_CONFIG_PATH, AVAHI_CONFIG_FN);
3434
3435#if defined(RTCONFIG_RGMII_BRCM5301X) || defined(RTCONFIG_QCA)
3436	strcpy(et0macaddr, nvram_safe_get("lan_hwaddr"));
3437#elif defined(RTCONFIG_GMAC3)
3438	if (nvram_match("gmac3_enable", "1"))
3439		strcpy(et0macaddr, nvram_safe_get("et2macaddr"));
3440	else
3441		strcpy(et0macaddr, nvram_safe_get("et0macaddr"));
3442#else
3443	strcpy(et0macaddr, nvram_safe_get("et0macaddr"));
3444#endif
3445
3446	/* Generate avahi configuration file */
3447	if (!(fp = fopen(avahi_config, "w"))) {
3448		perror(avahi_config);
3449		return -1;
3450	}
3451
3452	/* Set [server] configuration */
3453	fprintf(fp, "[Server]\n");
3454	fprintf(fp, "host-name=%s-%c%c%c%c\n", get_productid(),et0macaddr[12],et0macaddr[13],et0macaddr[15],et0macaddr[16]);
3455#ifdef RTCONFIG_FINDASUS
3456	fprintf(fp, "aliases=findasus,%s\n",get_productid());
3457	fprintf(fp, "aliases_llmnr=findasus,%s\n",get_productid());
3458#else
3459	fprintf(fp, "aliases=%s\n",get_productid());
3460	fprintf(fp, "aliases_llmnr=%s\n",get_productid());
3461#endif
3462	fprintf(fp, "use-ipv4=yes\n");
3463	fprintf(fp, "use-ipv6=no\n");
3464	fprintf(fp, "deny-interfaces=%s\n", nvram_safe_get("wan0_ifname"));
3465	fprintf(fp, "ratelimit-interval-usec=1000000\n");
3466	fprintf(fp, "ratelimit-burst=1000\n");
3467
3468	/* Set [publish] configuration */
3469	fprintf(fp, "\n[publish]\n");
3470	fprintf(fp, "publish-a-on-ipv6=no\n");
3471	fprintf(fp, "publish-aaaa-on-ipv4=no\n");
3472
3473	/* Set [wide-area] configuration */
3474	fprintf(fp, "\n[wide-area]\n");
3475	fprintf(fp, "enable-wide-area=yes\n");
3476
3477	/* Set [rlimits] configuration */
3478	fprintf(fp, "\n[rlimits]\n");
3479	fprintf(fp, "rlimit-core=0\n");
3480	fprintf(fp, "rlimit-data=4194304\n");
3481	fprintf(fp, "rlimit-fsize=0\n");
3482	fprintf(fp, "rlimit-nofile=768\n");
3483	fprintf(fp, "rlimit-stack=4194304\n");
3484	fprintf(fp, "rlimit-nproc=3\n");
3485
3486	fclose(fp);
3487
3488	return ret;
3489}
3490
3491int generate_afpd_service_config(void)
3492{
3493	FILE *fp;
3494	char afpd_service_config[80];
3495	int ret = 0;
3496
3497	sprintf(afpd_service_config, "%s/%s", AVAHI_SERVICES_PATH, AVAHI_AFPD_SERVICE_FN);
3498
3499	/* Generate afpd service configuration file */
3500	if (!(fp = fopen(afpd_service_config, "w"))) {
3501		perror(afpd_service_config);
3502		return -1;
3503	}
3504
3505	fprintf(fp, "<service-group>\n");
3506	fprintf(fp, "<name replace-wildcards=\"yes\">%%h</name>\n");
3507	fprintf(fp, "<service>\n");
3508	fprintf(fp, "<type>_afpovertcp._tcp</type>\n");
3509	fprintf(fp, "<port>548</port>\n");
3510	fprintf(fp, "</service>\n");
3511	fprintf(fp, "<service>\n");
3512	fprintf(fp, "<type>_device-info._tcp</type>\n");
3513	fprintf(fp, "<port>0</port>\n");
3514	fprintf(fp, "<txt-record>model=Xserve</txt-record>\n");
3515	fprintf(fp, "</service>\n");
3516	fprintf(fp, "</service-group>\n");
3517
3518	fclose(fp);
3519
3520	return ret;
3521}
3522
3523int generate_adisk_service_config(void)
3524{
3525	FILE *fp;
3526	char adisk_service_config[80];
3527	int ret = 0;
3528
3529	sprintf(adisk_service_config, "%s/%s", AVAHI_SERVICES_PATH, AVAHI_ADISK_SERVICE_FN);
3530
3531	/* Generate adisk service configuration file */
3532	if (!(fp = fopen(adisk_service_config, "w"))) {
3533		perror(adisk_service_config);
3534		return -1;
3535	}
3536
3537	fprintf(fp, "<service-group>\n");
3538	fprintf(fp, "<name replace-wildcards=\"yes\">%%h</name>\n");
3539	fprintf(fp, "<service>\n");
3540	fprintf(fp, "<type>_adisk._tcp</type>\n");
3541	fprintf(fp, "<port>9</port>\n");
3542	fprintf(fp, "<txt-record>dk0=adVN=%s,adVF=0x81</txt-record>\n", TIMEMACHINE_BACKUP_NAME);
3543	fprintf(fp, "</service>\n");
3544	fprintf(fp, "</service-group>\n");
3545
3546	fclose(fp);
3547
3548	return ret;
3549}
3550
3551int generate_itune_service_config(void)
3552{
3553	FILE *fp;
3554	char itune_service_config[80];
3555	int ret = 0;
3556	char servername[32];
3557
3558	sprintf(itune_service_config, "%s/%s", AVAHI_SERVICES_PATH, AVAHI_ITUNE_SERVICE_FN);
3559
3560	/* Generate afpd service configuration file */
3561	if (!(fp = fopen(itune_service_config, "w"))) {
3562		perror(itune_service_config);
3563		return -1;
3564	}
3565
3566	if (is_valid_hostname(nvram_safe_get("daapd_friendly_name")))
3567		strncpy(servername, nvram_safe_get("daapd_friendly_name"), sizeof(servername));
3568	else
3569		servername[0] = '\0';
3570	if(strlen(servername)==0) strncpy(servername, get_productid(), sizeof(servername));
3571
3572
3573	fprintf(fp, "<service-group>\n");
3574	fprintf(fp, "<name replace-wildcards=\"yes\">%s</name>\n",servername);
3575	fprintf(fp, "<service>\n");
3576	fprintf(fp, "<type>_daap._tcp</type>\n");
3577	fprintf(fp, "<port>3689</port>\n");
3578	fprintf(fp, "<txt-record>txtvers=1 iTShVersion=131073 Version=196610</txt-record>\n");
3579	fprintf(fp, "</service>\n");
3580	fprintf(fp, "</service-group>\n");
3581
3582	fclose(fp);
3583
3584	return ret;
3585}
3586
3587int start_mdns(void)
3588{
3589	char afpd_service_config[80];
3590	char adisk_service_config[80];
3591	char itune_service_config[80];
3592
3593	sprintf(afpd_service_config, "%s/%s", AVAHI_SERVICES_PATH, AVAHI_AFPD_SERVICE_FN);
3594	sprintf(adisk_service_config, "%s/%s", AVAHI_SERVICES_PATH, AVAHI_ADISK_SERVICE_FN);
3595	sprintf(itune_service_config, "%s/%s", AVAHI_SERVICES_PATH, AVAHI_ITUNE_SERVICE_FN);
3596
3597	mkdir_if_none(AVAHI_CONFIG_PATH);
3598	mkdir_if_none(AVAHI_SERVICES_PATH);
3599
3600	generate_mdns_config();
3601
3602	if (pids("afpd") && nvram_match("timemachine_enable", "1"))
3603	{
3604		if (!f_exists(afpd_service_config))
3605			generate_afpd_service_config();
3606		if (!f_exists(adisk_service_config))
3607			generate_adisk_service_config();
3608	}else{
3609		if (f_exists(afpd_service_config)){
3610			unlink(afpd_service_config);
3611		}
3612		if (f_exists(adisk_service_config)){
3613			unlink(adisk_service_config);
3614		}
3615	}
3616
3617	if(nvram_match("daapd_enable", "1") && pids("mt-daapd")){
3618		if (!f_exists(itune_service_config)){
3619			generate_itune_service_config();
3620		}
3621	}else{
3622		if (f_exists(itune_service_config)){
3623			unlink(itune_service_config);
3624		}
3625	}
3626
3627	// Execute avahi_daemon daemon
3628	//xstart("avahi-daemon");
3629	char *avahi_daemon_argv[] = {"avahi-daemon", NULL};
3630	pid_t pid;
3631
3632	return _eval(avahi_daemon_argv, NULL, 0, &pid);
3633}
3634
3635void stop_mdns(void)
3636{
3637	if (pids("avahi-daemon"))
3638		killall("avahi-daemon", SIGTERM);
3639}
3640
3641void restart_mdns(void)
3642{
3643	char afpd_service_config[80];
3644	char itune_service_config[80];
3645	sprintf(afpd_service_config, "%s/%s", AVAHI_SERVICES_PATH, AVAHI_AFPD_SERVICE_FN);
3646	sprintf(itune_service_config, "%s/%s", AVAHI_SERVICES_PATH, AVAHI_ITUNE_SERVICE_FN);
3647
3648	if (nvram_match("timemachine_enable", "1") == f_exists(afpd_service_config)){
3649		if(nvram_match("daapd_enable", "1") == f_exists(itune_service_config)){
3650			unlink(itune_service_config);
3651			generate_itune_service_config();
3652			return;
3653		}
3654	}
3655
3656	stop_mdns();
3657	sleep(2);
3658	start_mdns();
3659}
3660
3661#endif
3662
3663#ifdef  __CONFIG_NORTON__
3664
3665int start_norton(void)
3666{
3667	eval("/opt/nga/init/bootstrap.sh", "start", "rc");
3668
3669	return 0;
3670}
3671
3672int stop_norton(void)
3673{
3674	int ret;
3675
3676	ret = eval("/opt/nga/init/bootstrap.sh", "stop", "rc");
3677
3678	return ret;
3679}
3680
3681#endif /* __CONFIG_NORTON__ */
3682
3683#ifdef RTCONFIG_IXIAEP
3684int
3685stop_ixia_endpoint(void)
3686{
3687	if (pids("endpoint"))
3688		killall_tk("endpoint");
3689	return 0;
3690}
3691
3692int
3693start_ixia_endpoint(void)
3694{
3695	eval("start_endpoint");
3696}
3697#endif
3698
3699#ifdef RTCONFIG_IPERF
3700int
3701stop_iperf(void)
3702{
3703	if (pids("iperf"))
3704		killall_tk("iperf");
3705	return 0;
3706}
3707
3708int
3709start_iperf(void)
3710{
3711	char *iperf_argv[] = {"iperf", "-s", "-w", "1024k", NULL};
3712	pid_t pid;
3713
3714	return _eval(iperf_argv, NULL, 0, &pid);
3715}
3716#endif
3717
3718#ifdef RTCONFIG_QCA_PLC_UTILS
3719int
3720stop_plchost(void)
3721{
3722	if (pids("plchost"))
3723		killall_tk("plchost");
3724	return 0;
3725}
3726
3727int
3728start_plchost(void)
3729{
3730	char *plchost_argv[] = {"/usr/local/bin/plchost", "-i", "br0", "-N", BOOT_NVM_PATH, "-P", BOOT_PIB_PATH, NULL};
3731	pid_t pid;
3732
3733	return _eval(plchost_argv, NULL, 0, &pid);
3734}
3735
3736void
3737reset_plc(void)
3738{
3739	FILE *fp;
3740	int rlen;
3741	char buf[1024], plc_mac[18];
3742
3743	if (nvram_match("plc_ready", "0"))
3744		return;
3745
3746#if defined(PLN12)
3747	if (!get_qca8337_PHY_power(1))
3748		doSystem("swconfig dev %s port 1 set power 1", MII_IFNAME);
3749#elif defined(PLAC56)
3750	int wake_gpio = nvram_get_int("plc_wake_gpio") & 0xff;
3751
3752	if (get_gpio(wake_gpio))
3753		set_gpio(wake_gpio, 0);
3754#endif
3755
3756	memset(plc_mac, 0, sizeof(plc_mac));
3757	strcpy(plc_mac, nvram_safe_get("plc_macaddr"));
3758
3759	while (1) {
3760		fp = popen("/usr/local/bin/plctool -i br0 -I -e", "r");
3761		rlen = fread(buf, 1, sizeof(buf), fp);
3762		pclose(fp);
3763		if (rlen > 1) {
3764			buf[rlen-1] = '\0';
3765			if (strstr(buf, plc_mac))
3766				break;
3767		}
3768		dbg("%s: wait Powerline wake up...\n", __func__);
3769		sleep(1);
3770	}
3771
3772	stop_plchost();
3773	eval("/usr/local/bin/plctool", "-i", "br0", "-R");
3774	nvram_set("plc_ready", "0");
3775}
3776#endif
3777
3778#ifdef RTCONFIG_DHCP_OVERRIDE
3779int
3780stop_detectWAN_arp(void)
3781{
3782	if (pids("detectWAN_arp"))
3783		killall_tk("detectWAN_arp");
3784	return 0;
3785}
3786
3787int
3788start_detectWAN_arp(void)
3789{
3790	char *detectWAN_arp_argv[] = {"detectWAN_arp", NULL};
3791	pid_t pid;
3792
3793	return _eval(detectWAN_arp_argv, NULL, 0, &pid);
3794}
3795#endif
3796
3797#ifdef RTCONFIG_NOTIFICATION_CENTER
3798int
3799start_notification_center(void)
3800{
3801	char *nt_monitor_argv[] = {"nt_monitor", NULL};
3802	pid_t pid;
3803
3804	return _eval(nt_monitor_argv, NULL, 0, &pid);
3805}
3806
3807int
3808stop_notification_center(void)
3809{
3810	eval("kill", "-SIGUSR2", "`cat /tmp/Notification_Center_Monitor.pid`");
3811	return 0;
3812}
3813#endif
3814
3815int
3816start_services(void)
3817{
3818#ifdef __CONFIG_NORTON__
3819	start_norton();
3820#endif /* __CONFIG_NORTON__ */
3821
3822#ifdef RTCONFIG_NOTIFICATION_CENTER
3823	start_notification_center();
3824#endif
3825	start_telnetd();
3826#ifdef RTCONFIG_SSH
3827	start_sshd();
3828#endif
3829#ifdef CONFIG_BCMWL5
3830	start_eapd();
3831	start_nas();
3832#elif defined RTCONFIG_RALINK
3833	start_8021x();
3834#endif
3835	start_wps();
3836#ifdef RTCONFIG_WPS
3837	start_wpsaide();
3838#endif
3839#ifdef RTCONFIG_BCMWL6
3840#ifdef RTCONFIG_HSPOT
3841	start_hspotap();
3842#endif
3843	start_igmp_proxy();
3844#ifdef BCM_BSD
3845	start_bsd();
3846#endif
3847#ifdef BCM_SSD
3848	start_ssd();
3849#endif
3850#if defined(BCM_EVENTD)
3851	start_eventd();
3852#endif
3853
3854#if defined(RTCONFIG_DHDAP)
3855	start_dhd_monitor();
3856#endif
3857	start_acsd();
3858#ifdef BCM_ASPMD
3859	start_aspmd();
3860#endif /* BCM_ASPMD */
3861#endif	// RTCONFIG_BCMWL6
3862	start_dnsmasq();
3863#ifdef RTCONFIG_DHCP_OVERRIDE
3864	start_detectWAN_arp();
3865#endif
3866#if defined(RTCONFIG_MDNS)
3867	start_mdns();
3868#endif
3869	/* Link-up LAN ports after DHCP server ready. */
3870	start_lan_port(0);
3871
3872	start_cifs();
3873	start_httpd();
3874#ifdef RTCONFIG_CROND
3875	start_cron();
3876#endif
3877	start_infosvr();
3878
3879	restart_rstats();
3880#ifdef RTCONFIG_DSL
3881	start_spectrum(); //Ren
3882#endif
3883#ifdef RTCONFIG_TRAFFIC_LIMITER
3884	init_traffic_limiter();
3885#endif
3886	start_watchdog();
3887#ifdef RTAC87U
3888	start_watchdog02();
3889#endif
3890#ifdef SW_DEVLED
3891	start_sw_devled();
3892#endif
3893#ifdef RTCONFIG_DUALWAN
3894	restart_dualwan();
3895#endif
3896#ifdef RTCONFIG_FANCTRL
3897	start_phy_tempsense();
3898#endif
3899#if defined(RTCONFIG_BCMWL6) && defined(RTCONFIG_PROXYSTA)
3900	start_psta_monitor();
3901#endif
3902#if 0
3903	start_lldpd();
3904#else
3905	start_lltd();
3906#endif
3907#ifdef RTCONFIG_TOAD
3908	start_toads();
3909#endif
3910
3911#ifdef RTCONFIG_JFFS2USERICON
3912	start_lltdc();
3913#endif
3914	start_networkmap(1);
3915
3916#if defined(RTCONFIG_PPTPD) || defined(RTCONFIG_ACCEL_PPTPD)
3917	start_pptpd();
3918#endif
3919
3920#ifdef RTCONFIG_USB
3921//	_dprintf("restart_nas_services(%d): test 8.\n", getpid());
3922	//restart_nas_services(0, 1);
3923#ifdef RTCONFIG_DISK_MONITOR
3924	start_diskmon();
3925#endif
3926#endif
3927
3928#ifdef RTCONFIG_WEBDAV
3929	start_webdav();
3930#else
3931	if(f_exists("/opt/etc/init.d/S50aicloud"))
3932		system("sh /opt/etc/init.d/S50aicloud scan");
3933#endif
3934
3935#ifdef RTCONFIG_SNMPD
3936	start_snmpd();
3937#endif
3938
3939#if defined(RTCONFIG_RALINK) && defined(RTCONFIG_WIRELESSREPEATER)
3940	apcli_start();
3941#endif
3942
3943#ifdef RTCONFIG_BWDPI
3944	start_bwdpi_check();
3945#endif
3946	start_hour_monitor_service();
3947
3948#ifdef RTCONFIG_IPERF
3949	start_iperf();
3950	start_monitor();
3951#endif
3952
3953#ifdef RTCONFIG_IXIAEP
3954	start_ixia_endpoint();
3955#endif
3956
3957#ifdef RTCONFIG_INTERNAL_GOBI
3958	start_lteled();
3959#endif
3960
3961#ifdef RTCONFIG_PARENTALCTRL
3962	start_pc_block();
3963#endif
3964
3965#ifdef RTCONFIG_TOR
3966	start_Tor_proxy();
3967#endif
3968
3969#ifdef RTCONFIG_CLOUDCHECK
3970	start_cloudcheck();
3971#endif
3972
3973#ifdef RTCONFIG_QCA_PLC_UTILS
3974	start_plchost();
3975#endif
3976#if ((defined(RTCONFIG_USER_LOW_RSSI) && defined(RTCONFIG_BCMARM)) || defined(RTCONFIG_NEW_USER_LOW_RSSI))
3977	start_roamast();
3978#endif
3979
3980#if defined(RTCONFIG_KEY_GUARD)
3981	start_keyguard();
3982#endif
3983
3984#if 0//defined(RTCONFIG_WTFAST)
3985	start_wtfast();
3986#endif
3987
3988	start_ecoguard();
3989
3990	start_upnp();
3991
3992	return 0;
3993
3994}
3995
3996void
3997stop_logger(void)
3998{
3999	if (pids("klogd"))
4000		killall("klogd", SIGTERM);
4001	if (pids("syslogd"))
4002		killall("syslogd", SIGTERM);
4003}
4004
4005void
4006stop_services(void)
4007{
4008#ifdef RTCONFIG_INTERNAL_GOBI
4009	stop_lteled();
4010#endif
4011
4012	stop_hour_monitor_service();
4013#ifdef RTCONFIG_BWDPI
4014	stop_bwdpi_wred_alive();
4015	stop_bwdpi_check();
4016	stop_dpi_engine_service(1);
4017#endif
4018
4019#ifdef RTCONFIG_IXIAEP
4020	stop_monitor();
4021	stop_ixia_endpoint();
4022#endif
4023
4024#ifdef RTCONFIG_IPERF
4025	stop_iperf();
4026#endif
4027
4028#ifdef RTCONFIG_WEBDAV
4029	stop_webdav();
4030#else
4031	if(f_exists("/opt/etc/init.d/S50aicloud"))
4032		system("sh /opt/etc/init.d/S50aicloud scan");
4033#endif
4034
4035#ifdef RTCONFIG_USB
4036//_dprintf("restart_nas_services(%d): test 9.\n", getpid());
4037	restart_nas_services(1, 0);
4038#ifdef RTCONFIG_DISK_MONITOR
4039	stop_diskmon();
4040#endif
4041#endif
4042	stop_upnp();
4043	stop_lltd();
4044	stop_watchdog();
4045#ifdef RTCONFIG_FANCTRL
4046	stop_phy_tempsense();
4047#endif
4048#ifdef RTCONFIG_BCMWL6
4049	stop_igmp_proxy();
4050#ifdef RTCONFIG_PROXYSTA
4051	stop_psta_monitor();
4052#endif
4053#endif
4054	stop_rstats();
4055#ifdef RTCONFIG_DSL
4056	stop_spectrum(); //Ren
4057#endif
4058	stop_networkmap();
4059	stop_infosvr();
4060#ifdef RTCONFIG_CROND
4061	stop_cron();
4062#endif
4063	stop_httpd();
4064	stop_cifs();
4065#ifdef RTCONFIG_DHCP_OVERRIDE
4066	stop_detectWAN_arp();
4067#endif
4068	stop_dnsmasq();
4069#if defined(RTCONFIG_MDNS)
4070	stop_mdns();
4071#endif
4072#ifdef RTCONFIG_IPV6
4073	/* what? */
4074#endif
4075#ifdef RTCONFIG_BCMWL6
4076#ifdef BCM_ASPMD
4077	stop_aspmd();
4078#endif
4079	stop_acsd();
4080#ifdef BCM_BSD
4081	stop_bsd();
4082#endif
4083#ifdef BCM_SSD
4084	stop_ssd();
4085#endif
4086#if defined(RTCONFIG_DHDAP)
4087	stop_dhd_monitor();
4088#endif
4089	stop_igmp_proxy();
4090#ifdef RTCONFIG_HSPOT
4091	stop_hspotap();
4092#endif
4093#endif
4094#ifdef RTCONFIG_WPS
4095	stop_wpsaide();
4096#endif
4097	stop_wps();
4098#ifdef CONFIG_BCMWL5
4099	stop_nas();
4100	stop_eapd();
4101#elif defined RTCONFIG_RALINK
4102	stop_8021x();
4103#endif
4104#ifdef RTCONFIG_TOAD
4105	stop_toads();
4106#endif
4107	stop_telnetd();
4108#ifdef RTCONFIG_SSH
4109	stop_sshd();
4110#endif
4111
4112#ifdef RTCONFIG_SNMPD
4113	stop_snmpd();
4114#endif
4115
4116#ifdef  __CONFIG_NORTON__
4117	stop_norton();
4118#endif /* __CONFIG_NORTON__ */
4119#ifdef RTCONFIG_QTN
4120	stop_qtn_monitor();
4121#endif
4122
4123#ifdef RTCONFIG_PARENTALCTRL
4124	stop_pc_block();
4125#endif
4126
4127#ifdef RTCONFIG_TOR
4128	stop_Tor_proxy();
4129#endif
4130
4131#ifdef RTCONFIG_CLOUDCHECK
4132	stop_cloudcheck();
4133#endif
4134
4135#ifdef RTCONFIG_TUNNEL
4136	stop_mastiff();
4137#endif
4138
4139#ifdef RTCONFIG_KEY_GUARD
4140	stop_keyguard();
4141#endif
4142}
4143
4144// 2008.10 magic
4145
4146int start_wanduck(void)
4147{
4148	char *argv[] = {"/sbin/wanduck", NULL};
4149	pid_t pid;
4150
4151#if 0
4152	int sw_mode = nvram_get_int("sw_mode");
4153	if(sw_mode != SW_MODE_ROUTER && sw_mode != SW_MODE_REPEATER)
4154		return -1;
4155#endif
4156#ifdef CONFIG_BCMWL5
4157	if(ate_cond() == 0)
4158		return 0;
4159#endif
4160
4161	if(!strcmp(nvram_safe_get("wanduck_down"), "1"))
4162		return 0;
4163
4164	return _eval(argv, NULL, 0, &pid);
4165}
4166
4167void stop_wanduck(void)
4168{
4169	killall("wanduck", SIGTERM);
4170}
4171
4172void
4173stop_watchdog(void)
4174{
4175	killall_tk("watchdog");
4176}
4177
4178#if ! (defined(RTCONFIG_QCA) || defined(RTCONFIG_RALINK))
4179void
4180stop_watchdog02(void)
4181{
4182	/* do nothing */
4183	return;
4184}
4185#endif  /* ! (RTCONFIG_QCA || RTCONFIG_RALINK) */
4186
4187void
4188stop_sw_devled(void)
4189{
4190	killall_tk("sw_devled");
4191	return;
4192}
4193
4194#ifdef RTCONFIG_DUALWAN
4195int restart_dualwan(void)
4196{
4197	char *dualwan_argv[] = {"dualwan", NULL};
4198	pid_t dualpid;
4199
4200	killall("dualwan", SIGTERM);
4201
4202	return _eval(dualwan_argv, NULL, 0, &dualpid);
4203}
4204#endif
4205
4206int
4207start_watchdog(void)
4208{
4209	char *watchdog_argv[] = {"watchdog", NULL};
4210	pid_t whpid;
4211
4212	return _eval(watchdog_argv, NULL, 0, &whpid);
4213}
4214
4215#if ! (defined(RTCONFIG_QCA) || defined(RTCONFIG_RALINK))
4216int
4217start_watchdog02(void)
4218{
4219	char *watchdog_argv[] = {"watchdog02", NULL};
4220	pid_t whpid;
4221
4222	if (pidof("watchdog02") > 0) return -1;
4223
4224	return _eval(watchdog_argv, NULL, 0, &whpid);
4225}
4226#endif  /* ! (RTCONFIG_QCA || RTCONFIG_RALINK) */
4227
4228int
4229start_sw_devled(void)
4230{
4231	char *sw_devled_argv[] = {"sw_devled", NULL};
4232	pid_t whpid;
4233
4234	if (pidof("sw_devled") > 0) return -1;
4235
4236	return _eval(sw_devled_argv, NULL, 0, &whpid);
4237}
4238
4239#ifdef RTCONFIG_DSL
4240#ifdef RTCONFIG_RALINK
4241//Ren.B
4242int check_tc_upgrade(void)
4243{
4244	int ret_val_sep = 0;
4245
4246	TRACE_PT("check_tc_upgrade\n");
4247
4248	ret_val_sep = separate_tc_fw_from_trx();
4249	TRACE_PT("check_tc_upgrade, ret_val_sep=%d\n", ret_val_sep);
4250	if(ret_val_sep)
4251	{
4252		if(check_tc_firmware_crc() == 0)
4253		{
4254			TRACE_PT("check_tc_upgrade ret=1\n");
4255			return 1; //success
4256		}
4257	}
4258	TRACE_PT("check_tc_upgrade ret=0\n");
4259	return 0; //fail
4260}
4261
4262//New version will rename downloaded firmware to /tmp/linux.trx as default.
4263int start_tc_upgrade(void)
4264{
4265	int ret_val_trunc = 0;
4266	int ret_val_comp = 0;
4267
4268	TRACE_PT("start_tc_upgrade\n");
4269
4270	if(check_tc_upgrade())
4271	{
4272		ret_val_trunc = truncate_trx();
4273		TRACE_PT("start_tc_upgrade ret_val_trunc=%d\n", ret_val_trunc);
4274		if(ret_val_trunc)
4275		{
4276			do_upgrade_adsldrv();
4277			ret_val_comp = compare_linux_image();
4278			TRACE_PT("start_tc_upgrade ret_val_comp=%d\n", ret_val_comp);
4279			if (ret_val_comp == 0)
4280			{
4281				// same trx
4282				TRACE_PT("same firmware\n");
4283				unlink("/tmp/linux.trx");
4284			}
4285			else
4286			{
4287				// different trx
4288				TRACE_PT("different firmware\n");
4289			}
4290		}
4291	}
4292	return 0;
4293}
4294//Ren.E
4295#endif
4296#endif
4297
4298#ifdef RTCONFIG_FANCTRL
4299int
4300stop_phy_tempsense()
4301{
4302	if (pids("phy_tempsense")) {
4303		killall_tk("phy_tempsense");
4304	}
4305	return 0;
4306}
4307
4308int
4309start_phy_tempsense()
4310{
4311	char *phy_tempsense_argv[] = {"phy_tempsense", NULL};
4312	pid_t pid;
4313
4314	return _eval(phy_tempsense_argv, NULL, 0, &pid);
4315}
4316#endif
4317
4318#if defined(RTCONFIG_BCMWL6) && defined(RTCONFIG_PROXYSTA)
4319int
4320stop_psta_monitor()
4321{
4322	if (pids("psta_monitor")) {
4323		killall_tk("psta_monitor");
4324	}
4325	return 0;
4326}
4327
4328int
4329start_psta_monitor()
4330{
4331	char *psta_monitor_argv[] = {"psta_monitor", NULL};
4332	pid_t pid;
4333
4334	return _eval(psta_monitor_argv, NULL, 0, &pid);
4335}
4336#endif
4337
4338#ifdef RTCONFIG_IPERF
4339int
4340stop_monitor()
4341{
4342	if (pids("monitor")) {
4343		killall_tk("monitor");
4344	}
4345	return 0;
4346}
4347
4348int
4349start_monitor()
4350{
4351	char *monitor_argv[] = {"monitor", NULL};
4352	pid_t pid;
4353
4354	return _eval(monitor_argv, NULL, 0, &pid);
4355}
4356#endif
4357
4358#ifdef RTCONFIG_QTN
4359int
4360stop_qtn_monitor()
4361{
4362	if (pids("qtn_monitor")) {
4363		killall_tk("qtn_monitor");
4364	}
4365	return 0;
4366}
4367
4368int
4369start_qtn_monitor()
4370{
4371	char *qtn_monitor_argv[] = {"qtn_monitor", NULL};
4372	pid_t pid;
4373
4374	return _eval(qtn_monitor_argv, NULL, 0, &pid);
4375}
4376#endif
4377
4378#ifdef RTCONFIG_USB
4379int
4380start_usbled(void)
4381{
4382	char *usbled_argv[] = {"usbled", NULL};
4383	pid_t whpid;
4384
4385	stop_usbled();
4386	return _eval(usbled_argv, NULL, 0, &whpid);
4387}
4388
4389int
4390stop_usbled(void)
4391{
4392	if (pids("usbled"))
4393		killall("usbled", SIGTERM);
4394
4395	return 0;
4396}
4397#endif
4398
4399#ifdef RTCONFIG_CROND
4400void start_cron(void)
4401{
4402	stop_cron();
4403	eval("crond");
4404}
4405
4406
4407void stop_cron(void)
4408{
4409	killall_tk("crond");
4410}
4411#endif
4412
4413#ifdef RTCONFIG_QUAGGA
4414void stop_quagga(void)
4415{
4416	if (pids("zebra")){
4417		killall("zebra", SIGINT);
4418	}
4419	if (pids("ripd")){
4420		killall("ripd", SIGINT);
4421	}
4422}
4423
4424int start_quagga(void)
4425{
4426	FILE *fp, *fp2;
4427	char *zebra_hostname;
4428	char *zebra_passwd;
4429	char *zebra_enpasswd;
4430	char *rip_hostname;
4431	char *rip_passwd;
4432/*
4433	char *wan_ip, *wan_ifname;
4434	int   unit;
4435	char tmp[32], prefix[] = "wanXXXXXXXXXX_";
4436*/
4437
4438	if (!is_routing_enabled()) {
4439		_dprintf("return -1\n");
4440		return -1;
4441	}
4442	if (nvram_invmatch("quagga_enable", "1"))
4443		return -1;
4444
4445/*
4446	unit = wan_primary_ifunit();
4447	snprintf(prefix, sizeof(prefix), "wan%d_", unit);
4448
4449	wan_ip = nvram_safe_get(strcat_r(prefix, "ipaddr", tmp));
4450	wan_ifname = get_wan_ifname(unit);
4451
4452	if (!wan_ip || strcmp(wan_ip, "") == 0 || !inet_addr(wan_ip)) {
4453		logmessage("quagga", "WAN IP is empty.");
4454		return -1;
4455	}
4456*/
4457	zebra_passwd = nvram_safe_get("zebra_passwd");
4458	zebra_enpasswd = nvram_safe_get("zebra_enpasswd");
4459	rip_passwd = nvram_safe_get("rip_passwd");
4460
4461	zebra_hostname = nvram_safe_get("productid");
4462	rip_hostname = nvram_safe_get("productid");
4463
4464	if (pids("zebra")){
4465		killall("zebra", SIGINT);
4466		sleep(1);
4467	}
4468	if (pids("ripd")){
4469		killall("ripd", SIGINT);
4470		sleep(1);
4471	}
4472	if ((fp = fopen("/etc/zebra.conf", "w"))){
4473		fprintf(fp, "hostname %s\n", zebra_hostname);
4474		fprintf(fp, "password %s\n", zebra_passwd);
4475		fprintf(fp, "enable password %s\n", zebra_enpasswd);
4476		fprintf(fp, "log file /etc/zebra.log\n");
4477		fclose(fp);
4478		eval("zebra", "-d", "-f", "/etc/zebra.conf");
4479	}
4480	if ((fp2 = fopen("/etc/ripd.conf", "w"))){
4481		fprintf(fp2, "hostname %s\n", rip_hostname);
4482		fprintf(fp2, "password %s\n", rip_passwd);
4483		fprintf(fp2, "debug rip events\n");
4484		fprintf(fp2, "debug rip packet\n");
4485		fprintf(fp2, "router rip\n");
4486		fprintf(fp2, " version 2\n");
4487		fprintf(fp2, " network vlan2\n");
4488		fprintf(fp2, " network vlan3\n");
4489		fprintf(fp2, " passive-interface vlan2\n");
4490		fprintf(fp2, " passive-interface vlan3\n");
4491		fprintf(fp2, "log file /etc/ripd.log\n");
4492		fprintf(fp2, "log stdout\n");
4493		fclose(fp2);
4494		eval("ripd", "-d", "-f", "/etc/ripd.conf");
4495	}
4496	return 0;
4497}
4498#endif
4499
4500void start_script(int argc, char *argv[])
4501{
4502	int pid;
4503
4504	argv[argc] = NULL;
4505	_eval(argv, NULL, 0, &pid);
4506
4507}
4508
4509// -----------------------------------------------------------------------------
4510
4511/* -1 = Don't check for this program, it is not expected to be running.
4512 * Other = This program has been started and should be kept running.  If no
4513 * process with the name is running, call func to restart it.
4514 * Note: At startup, dnsmasq forks a short-lived child which forks a
4515 * long-lived (grand)child.  The parents terminate.
4516 * Many daemons use this technique.
4517 */
4518static void _check(pid_t pid, const char *name, void (*func)(void))
4519{
4520	if (pid == -1) return;
4521
4522	if (pidof(name) > 0) return;
4523
4524	syslog(LOG_DEBUG, "%s terminated unexpectedly, restarting.\n", name);
4525	func();
4526
4527	// Force recheck in 500 msec
4528	setitimer(ITIMER_REAL, &pop_tv, NULL);
4529}
4530
4531void check_services(void)
4532{
4533//	TRACE_PT("keep alive\n");
4534
4535	// Periodically reap any zombies
4536	setitimer(ITIMER_REAL, &zombie_tv, NULL);
4537
4538#ifdef LINUX26
4539	_check(pids("hotplug2"), "hotplug2", start_hotplug2);
4540#endif
4541#ifdef RTCONFIG_CROND
4542	_check(pids("crond"), "crond", start_cron);
4543#endif
4544}
4545
4546#define RC_SERVICE_STOP 0x01
4547#define RC_SERVICE_START 0x02
4548
4549void handle_notifications(void)
4550{
4551	char nv[256], nvtmp[32], *cmd[8], *script;
4552	char *nvp, *b, *nvptr;
4553	int action = 0;
4554	int count;
4555	int i;
4556	int unit;
4557
4558	// handle command one by one only
4559	// handle at most 7 parameters only
4560	// maximum rc_service strlen is 256
4561	strcpy(nv, nvram_safe_get("rc_service"));
4562	nvptr = nv;
4563again:
4564	nvp = strsep(&nvptr, ";");
4565
4566	count = 0;
4567	while ((b = strsep(&nvp, " ")) != NULL)
4568	{
4569		_dprintf("cmd[%d]=%s\n", count, b);
4570		cmd[count] = b;
4571		count ++;
4572		if(count == 7) break;
4573	}
4574	cmd[count] = 0;
4575
4576	if(cmd[0]==0 || strlen(cmd[0])==0) {
4577		nvram_set("rc_service", "");
4578		return;
4579	}
4580
4581	if(strncmp(cmd[0], "start_", 6)==0) {
4582		action |= RC_SERVICE_START;
4583		script = &cmd[0][6];
4584	}
4585	else if(strncmp(cmd[0], "stop_", 5)==0) {
4586		action |= RC_SERVICE_STOP;
4587		script = &cmd[0][5];
4588	}
4589	else if(strncmp(cmd[0], "restart_", 8)==0) {
4590		action |= (RC_SERVICE_START | RC_SERVICE_STOP);
4591		script = &cmd[0][8];
4592	}
4593	else {
4594		action = 0;
4595		script = cmd[0];
4596	}
4597
4598	TRACE_PT("running: %d %s\n", action, script);
4599
4600	if (strcmp(script, "reboot") == 0 || strcmp(script,"rebootandrestore")==0) {
4601		g_reboot = 1;
4602
4603#ifdef RTCONFIG_QCA_PLC_UTILS
4604		reset_plc();
4605		sleep(1);
4606#endif
4607
4608		stop_wan();
4609#ifdef RTCONFIG_USB
4610#if defined(RTCONFIG_USB_MODEM) && (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
4611		_dprintf("modem data: save the data during the reboot service\n");
4612		eval("modem_status.sh", "bytes+");
4613#endif
4614
4615		if (get_model() == MODEL_RTN53){
4616			eval("wlconf", "eth2", "down");
4617			modprobe_r("wl_high");
4618		}
4619
4620#if !(defined(RTN56UB1) || defined(RTN56UB2))
4621		stop_usb(0);
4622		stop_usbled();
4623#endif
4624#endif
4625//#if defined(RTCONFIG_JFFS2LOG) && defined(RTCONFIG_JFFS2)
4626#if defined(RTCONFIG_JFFS2LOG) && (defined(RTCONFIG_JFFS2)||defined(RTCONFIG_BRCM_NAND_JFFS2))
4627		eval("cp", "/tmp/syslog.log", "/tmp/syslog.log-1", "/jffs");
4628#endif
4629		if(strcmp(script,"rebootandrestore")==0) {
4630			for(i=1;i<count;i++) {
4631				if(cmd[i]) restore_defaults_module(cmd[i]);
4632			}
4633		}
4634
4635		/* Fall through to signal handler of init process. */
4636	}
4637	else if (strcmp(script, "resetdefault") == 0) {
4638		g_reboot = 1;
4639#ifdef RTCONFIG_DSL
4640		eval("adslate", "sysdefault");
4641#endif
4642		stop_wan();
4643#ifdef RTCONFIG_USB
4644#ifdef RTCONFIG_USB_MODEM
4645#if defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS)
4646		eval("rm", "-rf", "/jffs/sim");
4647#endif
4648#endif
4649
4650		if (get_model() == MODEL_RTN53){
4651			eval("wlconf", "eth2", "down");
4652			modprobe_r("wl_high");
4653		}
4654
4655#if !defined(RTN56UB1) && !defined(RTN56UB2)
4656		stop_usb(0);
4657		stop_usbled();
4658#endif
4659#endif
4660		sleep(3);
4661		nvram_set(ASUS_STOP_COMMIT, "1");
4662		if (nvram_contains_word("rc_support", "nandflash"))	/* RT-AC56S,U/RT-AC68U/RT-N18U */
4663			eval("mtd-erase2", "nvram");
4664		else
4665#if defined(RTAC1200G) || defined(RTAC1200GP)
4666			eval("mtd-erase2", "nvram");
4667#else
4668			eval("mtd-erase", "-d", "nvram");
4669#endif
4670
4671#ifdef RTCONFIG_QCA_PLC_UTILS
4672		reset_plc();
4673		eval("mtd-erase", "-d", "plc");
4674#endif
4675
4676		kill(1, SIGTERM);
4677	}
4678	else if (strcmp(script, "all") == 0) {
4679#ifdef RTCONFIG_QCA_PLC_UTILS
4680		reset_plc();
4681#endif
4682		sleep(2); // wait for all httpd event done
4683		stop_lan_port();
4684		start_lan_port(6);
4685		kill(1, SIGTERM);
4686	}
4687	else if(strcmp(script, "upgrade") == 0) {
4688		if(action&RC_SERVICE_STOP) {
4689#ifdef RTCONFIG_WIRELESSREPEATER
4690		if(nvram_get_int("sw_mode") == SW_MODE_REPEATER)
4691			stop_wlcconnect();
4692#endif
4693
4694			stop_hour_monitor_service();
4695#if defined(RTCONFIG_USB_MODEM) && (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS))
4696			_dprintf("modem data: save the data during upgrading\n");
4697			eval("modem_status.sh", "bytes+");
4698#endif
4699
4700			eval("/sbin/ejusb", "-1", "0");
4701			logmessage("usb", "USB is ejected");
4702		   if(!(nvram_match("webs_state_flag", "1") && nvram_match("webs_state_upgrade", "0")))
4703			stop_wanduck();
4704			stop_wan();
4705
4706			// what process need to stop to free memory or
4707			// to avoid affecting upgrade
4708			stop_misc();
4709			stop_logger();
4710			stop_upnp();
4711#if defined(RTCONFIG_MDNS)
4712			stop_mdns();
4713#endif
4714			stop_all_webdav();
4715#if defined(RTN56U)
4716			stop_if_misc();
4717#endif
4718#ifdef RTCONFIG_USB
4719			/* fix upgrade fail issue : remove wl_high before rmmod ehci_hcd */
4720			if (get_model() == MODEL_RTAC53U){
4721				eval("wlconf", "eth1", "down");
4722				eval("wlconf", "eth2", "down");
4723				modprobe_r("wl_high");
4724				modprobe_r("wl");
4725			}
4726
4727#if !defined(RTN53) && !defined(RTN56UB1) && !defined(RTN56UB2)
4728			stop_usb(0);
4729			stop_usbled();
4730			remove_storage_main(1);
4731			remove_usb_module();
4732#endif
4733
4734#endif
4735			remove_conntrack();
4736			stop_udhcpc(-1);
4737#ifdef RTCONFIG_IPV6
4738#ifdef RTCONFIG_6RELAYD
4739			stop_6relayd();
4740#endif
4741			stop_dhcp6c();
4742#endif
4743
4744#ifdef RTCONFIG_TR069
4745			stop_tr();
4746#endif
4747			stop_jffs2(1);
4748			stop_networkmap();
4749
4750#ifdef RTCONFIG_QCA_PLC_UTILS
4751			reset_plc();
4752#endif
4753			// TODO free necessary memory here
4754		}
4755		if(action & RC_SERVICE_START) {
4756			int sw = 0, r;
4757			char upgrade_file[64] = "/tmp/linux.trx";
4758			char *webs_state_info = nvram_safe_get("webs_state_info");
4759
4760#ifdef RTCONFIG_SMALL_FW_UPDATE
4761			snprintf(upgrade_file,sizeof(upgrade_file),"/tmp/mytmpfs/linux.trx");
4762#endif
4763
4764		#ifdef RTCONFIG_DSL
4765		#ifdef RTCONFIG_RALINK
4766			_dprintf("to do start_tc_upgrade\n");
4767			start_tc_upgrade();
4768		#else
4769			do_upgrade_adsldrv();
4770		#endif
4771		#endif
4772
4773			limit_page_cache_ratio(90);
4774
4775			/* /tmp/linux.trx has the priority */
4776			if (!f_exists(upgrade_file) && strlen(webs_state_info) > 5) {
4777				snprintf(upgrade_file, sizeof(upgrade_file),
4778					"/tmp/%s_%c.%c.%c.%c_%s.trx",
4779					nvram_safe_get("productid"),
4780					webs_state_info[0],
4781					webs_state_info[1],
4782					webs_state_info[2],
4783					webs_state_info[3],
4784					webs_state_info+5);
4785				_dprintf("upgrade file : %s \n", upgrade_file);
4786			}
4787
4788			/* flash it if exists */
4789			if (f_exists(upgrade_file)) {
4790				/* stop wireless here */
4791#ifdef RTCONFIG_SMALL_FW_UPDATE
4792/* TODO should not depend on platform, move to stop_lan_wl()?
4793 * cope with stop_usb() above for BRCM AP dependencies */
4794#ifdef CONFIG_BCMWL5
4795/* TODO should not depend on exact interfaces */
4796				eval("wlconf", "eth1", "down");
4797				eval("wlconf", "eth2", "down");
4798/* TODO fix fini_wl() for BCM USBAP */
4799				modprobe_r("wl_high");
4800				modprobe_r("wl");
4801#ifdef RTCONFIG_USB
4802#if defined(RTN53)
4803				stop_usb(0);
4804				stop_usbled();
4805				remove_storage_main(1);
4806				remove_usb_module();
4807#endif
4808#endif
4809#endif
4810#elif defined(RTCONFIG_TEMPROOTFS)
4811				stop_lan_wl();
4812				stop_dnsmasq();
4813				stop_networkmap();
4814				stop_wpsaide();
4815#endif
4816				if (!(r = build_temp_rootfs(TMP_ROOTFS_MNT_POINT)))
4817					sw = 1;
4818#ifdef RTCONFIG_DUAL_TRX
4819				if (!nvram_match("nflash_swecc", "1"))
4820				{
4821					_dprintf(" Write FW to the 2nd partition.\n");
4822					if (nvram_contains_word("rc_support", "nandflash"))	/* RT-AC56S,U/RT-AC68U/RT-N16UHP */
4823						eval("mtd-write2", upgrade_file, "linux2");
4824					else
4825						eval("mtd-write", "-i", upgrade_file, "-d", "linux2");
4826				}
4827#endif
4828				if (nvram_contains_word("rc_support", "nandflash"))	/* RT-AC56S,U/RT-AC68U/RT-N16UHP */
4829					eval("mtd-write2", upgrade_file, "linux");
4830				else
4831#if defined(RTAC1200G) || defined(RTAC1200GP)
4832					eval("mtd-write2", upgrade_file, "linux");
4833#else
4834					eval("mtd-write", "-i", upgrade_file, "-d", "linux");
4835#endif
4836				/* erase trx and free memory on purpose */
4837				unlink(upgrade_file);
4838				if (sw) {
4839					_dprintf("switch to temp rootfilesystem\n");
4840					if (!(r = switch_root(TMP_ROOTFS_MNT_POINT))) {
4841						/* Do nothing. If switch_root() success, never reach here. */
4842					} else {
4843						kill(1, SIGTERM);
4844					}
4845				} else {
4846					kill(1, SIGTERM);
4847				}
4848			}
4849			else {
4850				// recover? or reboot directly
4851				kill(1, SIGTERM);
4852			}
4853		}
4854	}
4855	else if(strcmp(script, "mfgmode") == 0) {
4856		nvram_set("asus_mfg", "2");
4857		//stop_infosvr(); //ATE need ifosvr
4858		stop_ntpc();
4859#ifdef RTCONFIG_BCMWL6
4860#ifdef BCM_ASPMD
4861		stop_aspmd();
4862#endif
4863		stop_acsd();
4864#ifdef BCM_BSD
4865		stop_bsd();
4866#endif
4867#ifdef BCM_SSD
4868		stop_ssd();
4869#endif
4870#if defined(RTCONFIG_DHDAP)
4871		stop_dhd_monitor();
4872#endif
4873		stop_igmp_proxy();
4874#ifdef RTCONFIG_HSPOT
4875		stop_hspotap();
4876#endif
4877#endif
4878		stop_wpsaide();
4879		stop_wps();
4880		stop_upnp();
4881		stop_lltd();
4882		stop_wanduck();
4883		stop_logger();
4884		stop_dnsmasq();
4885#if defined(RTCONFIG_MDNS)
4886		stop_mdns();
4887#endif
4888		stop_ots();
4889		stop_networkmap();
4890#ifdef RTCONFIG_DISK_MONITOR
4891		stop_diskmon();
4892#endif
4893#ifdef RTCONFIG_BWDPI
4894		stop_bwdpi_check();
4895#endif
4896		stop_ntpc();
4897		stop_udhcpc(-1);
4898#ifdef RTCONFIG_USB
4899		stop_usbled();
4900#endif
4901#ifdef RTCONFIG_USB_PRINTER
4902		stop_lpd();
4903		stop_u2ec();
4904#endif
4905		platform_start_ate_mode();
4906#ifdef RTCONFIG_QCA_PLC_UTILS
4907		ate_ctl_plc_led();
4908#endif
4909#ifdef SW_DEVLED
4910		stop_sw_devled();
4911#endif
4912#if defined(RTCONFIG_CFEZ) && defined(RTCONFIG_BCMARM)
4913		start_envrams();
4914#endif
4915	}
4916	else if (strcmp(script, "allnet") == 0) {
4917		if(action&RC_SERVICE_STOP) {
4918			// including switch setting
4919			// used for system mode change and vlan setting change
4920			sleep(2); // wait for all httpd event done
4921			stop_networkmap();
4922			stop_httpd();
4923			stop_telnetd();
4924#ifdef RTCONFIG_SSH
4925			stop_sshd();
4926#endif
4927			stop_dnsmasq();
4928#if defined(RTCONFIG_MDNS)
4929			stop_mdns();
4930#endif
4931			stop_upnp();
4932			stop_lltd();
4933#ifdef RTCONFIG_BCMWL6
4934#ifdef BCM_ASPMD
4935			stop_aspmd();
4936#endif
4937			stop_acsd();
4938#ifdef BCM_BSD
4939			stop_bsd();
4940#endif
4941#ifdef BCM_SSD
4942			stop_ssd();
4943#endif
4944#if defined(RTCONFIG_DHDAP)
4945			stop_dhd_monitor();
4946#endif
4947			stop_igmp_proxy();
4948#ifdef RTCONFIG_HSPOT
4949			stop_hspotap();
4950#endif
4951#endif
4952			stop_wps();
4953#ifdef CONFIG_BCMWL5
4954			stop_nas();
4955			stop_eapd();
4956#elif defined RTCONFIG_RALINK
4957			stop_8021x();
4958#endif
4959			stop_wan();
4960			stop_lan();
4961#ifdef RTCONFIG_DSL_TCLINUX
4962			stop_dsl();
4963#endif
4964			stop_vlan();
4965
4966
4967			// TODO free memory here
4968		}
4969		if(action & RC_SERVICE_START) {
4970			config_switch();
4971
4972			start_vlan();
4973#ifdef RTCONFIG_DSL_TCLINUX
4974			start_dsl();
4975#endif
4976			start_lan();
4977			start_dnsmasq();
4978#if defined(RTCONFIG_MDNS)
4979			start_mdns();
4980#endif
4981			start_wan();
4982#ifdef RTCONFIG_USB_MODEM
4983			if((unit = get_usbif_dualwan_unit()) >= 0)
4984				start_wan_if(unit);
4985#endif
4986#ifdef CONFIG_BCMWL5
4987			start_eapd();
4988			start_nas();
4989#elif defined RTCONFIG_RALINK
4990			start_8021x();
4991#endif
4992			start_wps();
4993#ifdef RTCONFIG_BCMWL6
4994			start_igmp_proxy();
4995#ifdef BCM_BSD
4996			start_bsd();
4997#endif
4998#ifdef BCM_SSD
4999			start_ssd();
5000#endif
5001#if defined(BCM_EVENTD)
5002			start_eventd();
5003#endif
5004#if defined(RTCONFIG_DHDAP)
5005			start_dhd_monitor();
5006#endif
5007			start_acsd();
5008#ifdef BCM_ASPMD
5009			start_aspmd();
5010#endif
5011#endif
5012			start_lltd();
5013			/* Link-up LAN ports after DHCP server ready. */
5014			start_lan_port(0);
5015
5016			start_upnp();
5017
5018			start_httpd();
5019			start_telnetd();
5020#ifdef RTCONFIG_SSH
5021			start_sshd();
5022#endif
5023			start_networkmap(0);
5024			start_wl();
5025			lanaccess_wl();
5026#ifdef RTCONFIG_BCMWL6
5027#ifdef RTCONFIG_HSPOT
5028			start_hspotap();
5029#endif
5030#endif
5031		}
5032	}
5033	else if (strcmp(script, "net") == 0) {
5034		if(action & RC_SERVICE_STOP) {
5035			sleep(2); // wait for all httpd event done
5036#ifdef RTCONFIG_USB_PRINTER
5037			stop_u2ec();
5038#endif
5039			stop_networkmap();
5040			stop_httpd();
5041			stop_telnetd();
5042#ifdef RTCONFIG_SSH
5043			stop_sshd();
5044#endif
5045			stop_dnsmasq();
5046#if defined(RTCONFIG_MDNS)
5047			stop_mdns();
5048#endif
5049			stop_upnp();
5050			stop_lltd();
5051#ifdef RTCONFIG_BCMWL6
5052#ifdef BCM_ASPMD
5053			stop_aspmd();
5054#endif
5055			stop_acsd();
5056#ifdef BCM_BSD
5057			stop_bsd();
5058#endif
5059#ifdef BCM_SSD
5060			stop_ssd();
5061#endif
5062#if defined(RTCONFIG_DHDAP)
5063			stop_dhd_monitor();
5064#endif
5065			stop_igmp_proxy();
5066#ifdef RTCONFIG_HSPOT
5067			stop_hspotap();
5068#endif
5069#endif
5070			stop_wps();
5071#ifdef CONFIG_BCMWL5
5072			stop_nas();
5073			stop_eapd();
5074#elif defined RTCONFIG_RALINK
5075			stop_8021x();
5076#endif
5077			stop_wan();
5078			stop_lan();
5079			//stop_vlan();
5080
5081			// free memory here
5082		}
5083		if(action & RC_SERVICE_START) {
5084			//start_vlan();
5085			start_lan();
5086			start_dnsmasq();
5087#if defined(RTCONFIG_MDNS)
5088			start_mdns();
5089#endif
5090			start_wan();
5091#ifndef RTCONFIG_INTERNAL_GOBI
5092#ifdef RTCONFIG_USB_MODEM
5093			if((unit = get_usbif_dualwan_unit()) >= 0)
5094				start_wan_if(unit);
5095#endif
5096#endif
5097#ifdef CONFIG_BCMWL5
5098			start_eapd();
5099			start_nas();
5100#elif defined RTCONFIG_RALINK
5101			start_8021x();
5102#endif
5103			start_wps();
5104#ifdef RTCONFIG_BCMWL6
5105			start_igmp_proxy();
5106#ifdef BCM_BSD
5107			start_bsd();
5108#endif
5109#ifdef BCM_SSD
5110			start_ssd();
5111#endif
5112#if defined(BCM_EVENTD)
5113			start_eventd();
5114#endif
5115#if defined(RTCONFIG_DHDAP)
5116			start_dhd_monitor();
5117#endif
5118			start_acsd();
5119#ifdef BCM_ASPMD
5120			start_aspmd();
5121#endif
5122#endif
5123			start_lltd();
5124			/* Link-up LAN ports after DHCP server ready. */
5125			start_lan_port(0);
5126
5127			start_upnp();
5128
5129			start_httpd();
5130			start_telnetd();
5131#ifdef RTCONFIG_SSH
5132			start_sshd();
5133#endif
5134			start_networkmap(0);
5135#ifdef RTCONFIG_USB_PRINTER
5136			start_u2ec();
5137#endif
5138			start_wl();
5139			lanaccess_wl();
5140#ifdef RTCONFIG_BCMWL6
5141#ifdef RTCONFIG_HSPOT
5142			start_hspotap();
5143#endif
5144#endif
5145		}
5146	}
5147	else if (strcmp(script, "net_and_phy") == 0) {
5148		if(action & RC_SERVICE_STOP) {
5149			sleep(2); // wait for all httpd event done
5150
5151#ifdef RTCONFIG_MEDIA_SERVER
5152			force_stop_dms();
5153			stop_mt_daapd();
5154#endif
5155
5156#if defined(RTCONFIG_SAMBASRV) && defined(RTCONFIG_FTP)
5157			stop_ftpd();
5158			stop_samba();
5159#endif
5160
5161#ifdef RTCONFIG_USB_PRINTER
5162			stop_u2ec();
5163#endif
5164			stop_networkmap();
5165			stop_httpd();
5166			stop_telnetd();
5167#ifdef RTCONFIG_SSH
5168			stop_sshd();
5169#endif
5170#ifdef RTCONFIG_DHCP_OVERRIDE
5171			stop_detectWAN_arp();
5172#endif
5173			stop_dnsmasq();
5174#if defined(RTCONFIG_MDNS)
5175			stop_mdns();
5176#endif
5177			//Andy Chiu, 2015/09/16.
5178			stop_upnp();
5179			stop_lltd();
5180#ifdef RTCONFIG_BCMWL6
5181#ifdef BCM_ASPMD
5182			stop_aspmd();
5183#endif
5184			stop_acsd();
5185#ifdef BCM_BSD
5186			stop_bsd();
5187#endif
5188#ifdef BCM_SSD
5189			stop_ssd();
5190#endif
5191#if defined(RTCONFIG_DHDAP)
5192			stop_dhd_monitor();
5193#endif
5194			stop_igmp_proxy();
5195#ifdef RTCONFIG_HSPOT
5196			stop_hspotap();
5197#endif
5198#endif
5199			stop_wps();
5200#ifdef CONFIG_BCMWL5
5201			stop_nas();
5202			stop_eapd();
5203#elif defined RTCONFIG_RALINK
5204			stop_8021x();
5205#endif
5206#if defined(RTCONFIG_PPTPD) || defined(RTCONFIG_ACCEL_PPTPD)
5207			//stop_pptpd();
5208#endif
5209			stop_wan();
5210			stop_lan();
5211			//stop_vlan();
5212			stop_lan_port();
5213
5214			// free memory here
5215		}
5216		if(action & RC_SERVICE_START) {
5217			//start_vlan();
5218			start_lan();
5219			start_dnsmasq();
5220#ifdef RTCONFIG_DHCP_OVERRIDE
5221			start_detectWAN_arp();
5222#endif
5223#if defined(RTCONFIG_MDNS)
5224			start_mdns();
5225#endif
5226			start_wan();
5227#ifdef RTCONFIG_USB_MODEM
5228			if((unit = get_usbif_dualwan_unit()) >= 0)
5229				start_wan_if(unit);
5230#endif
5231#ifdef CONFIG_BCMWL5
5232			start_eapd();
5233			start_nas();
5234#elif defined RTCONFIG_RALINK
5235			start_8021x();
5236#endif
5237#if defined(RTCONFIG_PPTPD) || defined(RTCONFIG_ACCEL_PPTPD)
5238			//start_pptpd();
5239#endif
5240			start_wps();
5241#ifdef RTCONFIG_BCMWL6
5242			start_igmp_proxy();
5243#ifdef BCM_BSD
5244			start_bsd();
5245#endif
5246#ifdef BCM_SSD
5247			start_ssd();
5248#endif
5249#if defined(BCM_EVENTD)
5250			start_eventd();
5251#endif
5252#if defined(RTCONFIG_DHDAP)
5253			start_dhd_monitor();
5254#endif
5255			start_acsd();
5256#ifdef BCM_ASPMD
5257			start_aspmd();
5258#endif
5259#endif
5260			start_lltd();
5261			/* Link-up LAN ports after DHCP server ready. */
5262			start_lan_port(6);
5263
5264			//Andy Chiu, 2015/09/16
5265			start_upnp();
5266
5267			start_httpd();
5268			start_telnetd();
5269#ifdef RTCONFIG_SSH
5270			start_sshd();
5271#endif
5272			start_networkmap(0);
5273#ifdef RTCONFIG_USB_PRINTER
5274			start_u2ec();
5275#endif
5276
5277#if defined(RTCONFIG_SAMBASRV) && defined(RTCONFIG_FTP)
5278			setup_passwd();
5279			start_samba();
5280			start_ftpd();
5281#endif
5282			start_wl();
5283			lanaccess_wl();
5284#ifdef RTCONFIG_BCMWL6
5285#ifdef RTCONFIG_HSPOT
5286			start_hspotap();
5287#endif
5288#endif
5289#ifdef RTCONFIG_MEDIA_SERVER
5290			start_dms();
5291			start_mt_daapd();
5292#endif
5293		}
5294	}
5295#ifdef RTCONFIG_DUALWAN
5296	else if(!strcmp(script, "multipath")){
5297		char mode[4], if_now[16], if_next[16];
5298		int unit;
5299		int unit_now = wan_primary_ifunit();
5300		int unit_next = (unit_now+1)%WAN_UNIT_MAX;
5301		int state_now = is_wan_connect(unit_now);
5302		int state_next = is_wan_connect(unit_next);
5303
5304		snprintf(mode, 4, "%s", nvram_safe_get("wans_mode"));
5305		snprintf(if_now, 16, "%s", get_wan_ifname(unit_now));
5306		snprintf(if_next, 16, "%s", get_wan_ifname(unit_next));
5307_dprintf("multipath(%s): unit_now: (%d, %d, %s), unit_next: (%d, %d, %s).\n", mode, unit_now, state_now, if_now, unit_next, state_next, if_next);
5308
5309		if(!strcmp(mode, "lb")){
5310			if(state_now == 1 && state_next == 1){
5311				wan_up(if_now);
5312			}
5313			else if(state_now == 1 && state_next == 0){
5314				stop_wan_if(unit_next);
5315				start_wan_if(unit_next);
5316			}
5317			else if(state_now == 0 && state_next == 1){
5318				wan_up(if_next);
5319				stop_wan_if(unit_now);
5320				start_wan_if(unit_now);
5321			}
5322			else{ // state_now == 0 && state_next == 0
5323				for(unit = WAN_UNIT_FIRST; unit < WAN_UNIT_MAX; ++unit){
5324					stop_wan_if(unit);
5325					start_wan_if(unit);
5326				}
5327			}
5328		}
5329		else if(!strcmp(mode, "fb")){
5330			if(state_now == 1 && state_next == 1){
5331				if(unit_next == WAN_UNIT_FIRST){
5332					set_wan_primary_ifunit(unit_next);
5333					wan_up(if_next);
5334					stop_wan_if(unit_now);
5335				}
5336				else{ // unit_now == WAN_UNIT_FIRST
5337					wan_up(if_now);
5338					stop_wan_if(unit_next);
5339				}
5340			}
5341			else if(state_now == 1 && state_next == 0){
5342				wan_up(if_now);
5343				if(unit_next == WAN_UNIT_FIRST){
5344					stop_wan_if(unit_next);
5345					start_wan_if(unit_next);
5346				}
5347			}
5348			else if(state_now == 0 && state_next == 1){
5349				set_wan_primary_ifunit(unit_next);
5350				wan_up(if_next);
5351				if(unit_now == WAN_UNIT_FIRST){
5352					stop_wan_if(unit_now);
5353					start_wan_if(unit_now);
5354				}
5355			}
5356			else{ // state_now == 0 && state_next == 0
5357				if(unit_next == WAN_UNIT_FIRST){
5358					set_wan_primary_ifunit(unit_next);
5359					stop_wan_if(unit_next);
5360					start_wan_if(unit_next);
5361				}
5362				else{
5363					stop_wan_if(unit_now);
5364					start_wan_if(unit_now);
5365				}
5366			}
5367		}
5368		else if(!strcmp(mode, "fo")){
5369			if(state_now == 1 && state_next == 1){
5370				wan_up(if_now);
5371				stop_wan_if(unit_next);
5372			}
5373			else if(state_now == 1 && state_next == 0){
5374				wan_up(if_now);
5375			}
5376			else if(state_now == 0 && state_next == 1){
5377				set_wan_primary_ifunit(unit_next);
5378				wan_up(if_next);
5379			}
5380			else{ // state_now == 0 && state_next == 0
5381				stop_wan_if(unit_now);
5382				start_wan_if(unit_now);
5383			}
5384		}
5385	}
5386#endif
5387	else if (strcmp(script, "wireless") == 0) {
5388		if(action&RC_SERVICE_STOP) {
5389#ifdef RTCONFIG_WIRELESSREPEATER
5390			stop_wlcconnect();
5391
5392			kill_pidfile_s("/var/run/wanduck.pid", SIGUSR1);
5393#endif
5394
5395#ifdef RTCONFIG_USB_PRINTER
5396			stop_u2ec();
5397#endif
5398			stop_networkmap();
5399		}
5400		if((action & RC_SERVICE_STOP) && (action & RC_SERVICE_START)) {
5401			// TODO: free memory here
5402			reinit_hwnat(-1);
5403			restart_wireless();
5404		}
5405		if(action & RC_SERVICE_START) {
5406#ifdef RTCONFIG_WIRELESSREPEATER
5407			start_wlcconnect();
5408#endif
5409
5410			start_networkmap(0);
5411#ifdef RTCONFIG_USB_PRINTER
5412			start_u2ec();
5413#endif
5414			start_ecoguard(); //for app eco mode
5415		}
5416	}
5417#ifdef CONFIG_BCMWL5
5418#ifdef RTCONFIG_BCMWL6A
5419	else if (strcmp(script, "clkfreq") == 0) {
5420		dbG("clkfreq: %s\n", nvram_safe_get("clkfreq"));
5421
5422		char *string = nvram_safe_get("clkfreq");
5423		char *cpu, *ddr, buf[100];
5424		unsigned int cpu_clock = 0, ddr_clock = 0;
5425		static unsigned int cpu_clock_table[] = {600, 800, 1000, 1200, 1400, 1600};
5426		static unsigned int ddr_clock_table[] = {333, 389, 400, 533, 666, 775, 800};
5427
5428		if (strchr(string, ','))
5429		{
5430			strncpy(ddr = buf, string, sizeof(buf));
5431			cpu = strsep(&ddr, ",");
5432			cpu_clock=atoi(cpu);
5433			ddr_clock=atoi(ddr);
5434		}
5435		else
5436			cpu_clock=atoi(string);
5437
5438
5439		for (i = 0; i < (sizeof(cpu_clock_table)/sizeof(cpu_clock_table[0])); i++)
5440		{
5441			if (cpu_clock == cpu_clock_table[i])
5442				goto check_ddr_clock;
5443		}
5444		cpu_clock = 800;
5445check_ddr_clock:
5446		for (i = 0; i < (sizeof(ddr_clock_table)/sizeof(ddr_clock_table[0])); i++)
5447		{
5448			if (ddr_clock == ddr_clock_table[i])
5449				goto check_ddr_done;
5450		}
5451		ddr_clock = 533;
5452check_ddr_done:
5453		if (cpu_clock) dbG("target CPU clock: %d\n", cpu_clock);
5454		if (ddr_clock) dbG("target DDR clock: %d\n", ddr_clock);
5455
5456		nvram_unset("sdram_ncdl");
5457		nvram_commit();
5458	}
5459#endif
5460	else if (strcmp(script, "set_wltxpower") == 0) {
5461		switch (get_model()) {
5462		case MODEL_RTAC66U:
5463		case MODEL_RTAC56S:
5464		case MODEL_RTAC56U:
5465		case MODEL_RTAC3200:
5466		case MODEL_RPAC68U:
5467		case MODEL_RTAC68U:
5468		case MODEL_DSLAC68U:
5469		case MODEL_RTAC87U:
5470		case MODEL_RTN12HP:
5471		case MODEL_RTN12HP_B1:
5472		case MODEL_APN12HP:
5473		case MODEL_RTN66U:
5474		case MODEL_RTN18U:
5475		case MODEL_RTAC5300:
5476		case MODEL_RTAC5300R:
5477		case MODEL_RTAC3100:
5478		case MODEL_RTAC88U:
5479		//case MODEL_RTAC1200G:
5480			set_wltxpower();
5481			break;
5482		default:
5483			dbG("\n\tDon't do this!\n\n");
5484			break;
5485		}
5486	}
5487#endif
5488#ifdef RTCONFIG_FANCTRL
5489	else if (strcmp(script, "fanctrl") == 0) {
5490		if((action & RC_SERVICE_STOP)&&(action & RC_SERVICE_START)) restart_fanctrl();
5491	}
5492#endif
5493	else if (strcmp(script, "wan") == 0) {
5494		if(action & RC_SERVICE_STOP)
5495		{
5496			stop_upnp();
5497			stop_wan();
5498		}
5499		if(action & RC_SERVICE_START)
5500		{
5501			start_wan();
5502			start_upnp();
5503		}
5504	}
5505	else if (strcmp(script, "wan_if") == 0) {
5506		_dprintf("%s: wan_if: %s.\n", __FUNCTION__, cmd[1]);
5507		if(cmd[1]) {
5508			if(action & RC_SERVICE_STOP)
5509			{
5510				stop_wan_if(atoi(cmd[1]));
5511#if defined(RTCONFIG_IPV6) && defined(RTCONFIG_DUALWAN)
5512				stop_lan_ipv6();
5513#endif
5514			}
5515			if(action & RC_SERVICE_START)
5516			{
5517#if defined(RTCONFIG_IPV6) && defined(RTCONFIG_DUALWAN)
5518				start_lan_ipv6();
5519#endif
5520#ifdef DSL_AC68U	//Andy Chiu, 2015/09/15.
5521				//Check the vlan config of ethernet wan, reset the config by new vlan id.
5522				check_wan_if(atoi(cmd[1]));
5523
5524#endif
5525				start_wan_if(atoi(cmd[1]));
5526#if defined(RTCONFIG_IPV6) && defined(RTCONFIG_DUALWAN)
5527				restart_dnsmasq_ipv6();
5528#endif
5529			}
5530		}
5531	}
5532#ifdef RTCONFIG_DSL
5533	else if (strcmp(script, "dslwan_if") == 0) {
5534		_dprintf("%s: restart_dslwan_if: %s.\n", __FUNCTION__, cmd[1]);
5535		if(cmd[1]) {
5536			if(action & RC_SERVICE_STOP)
5537			{
5538				stop_wan_if(atoi(cmd[1]));
5539			}
5540			if(action & RC_SERVICE_START)
5541			{
5542				remove_dsl_autodet();
5543				dsl_configure(2);
5544				start_wan_if(atoi(cmd[1]));
5545			}
5546		}
5547	}
5548	else if (strcmp(script, "dsl_wireless") == 0) {
5549		if(action&RC_SERVICE_STOP) {
5550#ifdef RTCONFIG_USB_PRINTER
5551			stop_u2ec();
5552#endif
5553			stop_networkmap();
5554		}
5555		if((action&RC_SERVICE_STOP) && (action & RC_SERVICE_START)) {
5556// qis
5557			remove_dsl_autodet();
5558			stop_wan_if(atoi(cmd[1]));
5559			dsl_configure(2);
5560			start_wan_if(atoi(cmd[1]));
5561			restart_wireless();
5562		}
5563		if(action & RC_SERVICE_START) {
5564			start_networkmap(0);
5565#ifdef RTCONFIG_USB_PRINTER
5566			start_u2ec();
5567#endif
5568		}
5569	}
5570	else if (strcmp(script, "dsl_setting") == 0) {
5571		if((action & RC_SERVICE_STOP) && (action & RC_SERVICE_START)) {
5572			nvram_set("dsltmp_syncloss_apply", "1");
5573			eval("req_dsl_drv", "dslsetting");
5574		}
5575	}
5576#ifdef RTCONFIG_DSL_TCLINUX
5577	else if (strcmp(script, "dsl_autodet") == 0) {
5578		if(action & RC_SERVICE_STOP) stop_dsl_autodet();
5579		if(action & RC_SERVICE_START) start_dsl_autodet();
5580	}
5581	else if (strcmp(script, "dsl_diag") == 0) {
5582		if(action & RC_SERVICE_STOP) stop_dsl_diag();
5583		if(action & RC_SERVICE_START) start_dsl_diag();
5584	}
5585#endif
5586#endif
5587	else if (strcmp(script, "wan_line") == 0) {
5588	_dprintf("%s: restart_wan_line: %s.\n", __FUNCTION__, cmd[1]);
5589		if(cmd[1]) {
5590			int wan_unit = atoi(cmd[1]);
5591			char *current_ifname = get_wan_ifname(wan_unit);
5592
5593			wan_up(current_ifname);
5594		}
5595	}
5596#ifdef CONFIG_BCMWL5
5597	else if (strcmp(script, "nas") == 0) {
5598		if(action & RC_SERVICE_STOP) stop_nas();
5599		if(action & RC_SERVICE_START) {
5600			start_eapd();
5601			start_nas();
5602			start_wps();
5603#ifdef RTCONFIG_BCMWL6
5604			start_igmp_proxy();
5605#ifdef BCM_BSD
5606			start_bsd();
5607#endif
5608#ifdef BCM_SSD
5609			start_ssd();
5610#endif
5611#if defined(BCM_EVENTD)
5612			start_eventd();
5613#endif
5614#if defined(RTCONFIG_DHDAP)
5615			start_dhd_monitor();
5616#endif
5617			start_acsd();
5618#ifdef BCM_ASPMD
5619			start_aspmd();
5620#endif
5621#endif
5622			start_wl();
5623			lanaccess_wl();
5624#ifdef RTCONFIG_BCMWL6
5625#ifdef RTCONFIG_HSPOT
5626			start_hspotap();
5627#endif
5628#endif
5629		}
5630	}
5631#endif
5632#ifdef RTCONFIG_USB
5633	else if (strcmp(script, "nasapps") == 0)
5634	{
5635		if(action&RC_SERVICE_STOP){
5636//_dprintf("restart_nas_services(%d): test 10.\n", getpid());
5637			restart_nas_services(1, 0);
5638		}
5639		if(action&RC_SERVICE_START){
5640			stop_upnp();
5641//_dprintf("restart_nas_services(%d): test 11.\n", getpid());
5642			restart_nas_services(0, 1);
5643			start_upnp();
5644		}
5645	}
5646#if defined(RTCONFIG_SAMBASRV) && defined(RTCONFIG_FTP)
5647	else if (strcmp(script, "ftpsamba") == 0)
5648	{
5649		if(action & RC_SERVICE_STOP) {
5650			stop_ftpd();
5651			stop_samba();
5652		}
5653		if(action & RC_SERVICE_START) {
5654			start_dnsmasq();	// this includes stop_dnsmasq
5655			setup_passwd();
5656			start_samba();
5657			start_ftpd();
5658		}
5659	}
5660#endif
5661#ifdef RTCONFIG_FTP
5662	else if (strcmp(script, "ftpd") == 0)
5663	{
5664		if(action & RC_SERVICE_STOP) stop_ftpd();
5665		if(action & RC_SERVICE_START) start_ftpd();
5666
5667		/* for security concern, even if you stop ftp daemon, it is better to restart firewall to clean FTP port: 21. */
5668		start_firewall(wan_primary_ifunit(), 0);
5669	}
5670	else if (strcmp(script, "ftpd_force") == 0)
5671	{
5672		nvram_set("st_ftp_force_mode", nvram_safe_get("st_ftp_mode"));
5673		nvram_commit();
5674
5675		if(action & RC_SERVICE_STOP) stop_ftpd();
5676		if(action & RC_SERVICE_START) start_ftpd();
5677
5678		/* for security concern, even if you stop ftp daemon, it is better to restart firewall to clean FTP port: 21. */
5679		start_firewall(wan_primary_ifunit(), 0);
5680	}
5681#endif
5682#ifdef RTCONFIG_SAMBASRV
5683	else if (strcmp(script, "samba") == 0)
5684	{
5685		if(action & RC_SERVICE_STOP) stop_samba();
5686		if(action & RC_SERVICE_START) {
5687			start_dnsmasq();	// this includes stop_dnsmasq
5688			start_samba();
5689		}
5690	}
5691	else if (strcmp(script, "samba_force") == 0)
5692	{
5693		nvram_set("st_samba_force_mode", nvram_safe_get("st_samba_mode"));
5694		nvram_commit();
5695
5696		if(action & RC_SERVICE_STOP) stop_samba();
5697		if(action & RC_SERVICE_START) {
5698			start_dnsmasq();	// this includes stop_dnsmasq
5699			start_samba();
5700		}
5701	}
5702#endif
5703#ifdef RTCONFIG_WEBDAV
5704	else if (strcmp(script, "webdav") == 0)
5705	{
5706		if(action & RC_SERVICE_STOP){
5707			stop_webdav();
5708		}
5709		if(action & RC_SERVICE_START) {
5710			stop_upnp();
5711			start_firewall(wan_primary_ifunit(), 0);
5712			start_webdav();
5713			start_upnp();
5714		}
5715	}
5716#else
5717	else if (strcmp(script, "webdav") == 0){
5718		if(f_exists("/opt/etc/init.d/S50aicloud"))
5719			system("sh /opt/etc/init.d/S50aicloud scan");
5720	}
5721	else if (strcmp(script, "setting_webdav") == 0){
5722		if(f_exists("/opt/etc/init.d/S50aicloud"))
5723			system("sh /opt/etc/init.d/S50aicloud restart");
5724	}
5725#endif
5726	else if (strcmp(script, "enable_webdav") == 0)
5727	{
5728		stop_upnp();
5729		stop_ddns();
5730#ifdef RTCONFIG_WEBDAV
5731		stop_webdav();
5732#endif
5733		start_firewall(wan_primary_ifunit(), 0);
5734		start_webdav();
5735		start_ddns();
5736		start_upnp();
5737
5738	}
5739#ifdef RTCONFIG_TUNNEL
5740	else if (strcmp(script, "aae") == 0)
5741	{
5742		if(action&RC_SERVICE_STOP){
5743			stop_mastiff();
5744		}
5745		if(action&RC_SERVICE_START) {
5746			start_mastiff();
5747		}
5748	}
5749#endif
5750
5751//#endif
5752//#ifdef RTCONFIG_CLOUDSYNC
5753	else if (strcmp(script, "cloudsync") == 0)
5754	{
5755#ifdef RTCONFIG_CLOUDSYNC
5756		int fromUI = 0;
5757
5758		if(action & RC_SERVICE_STOP && action & RC_SERVICE_START)
5759			fromUI = 1;
5760
5761		if(action&RC_SERVICE_STOP){
5762			if(cmd[1])
5763				stop_cloudsync(atoi(cmd[1]));
5764			else
5765				stop_cloudsync(-1);
5766		}
5767		if(action & RC_SERVICE_START) start_cloudsync(fromUI);
5768#else
5769		system("sh /opt/etc/init.d/S50smartsync restart");
5770#endif
5771	}
5772#ifdef RTCONFIG_WTFAST
5773	else if (strcmp(script, "wtfast") == 0)
5774	{
5775		if(action & RC_SERVICE_STOP) stop_wtfast();
5776		if(action & RC_SERVICE_START) start_wtfast();
5777	}
5778	else if(strcmp(script, "wtfast_rule") == 0){
5779		//_dprintf("send SIGHUP to wtfast_rule SIGHUP = %d\n", SIGHUP);
5780		killall("wtfslhd", SIGHUP);
5781	}
5782#endif
5783//#endif
5784#ifdef RTCONFIG_USB_PRINTER
5785	else if (strcmp(script, "lpd") == 0)
5786	{
5787		if(action & RC_SERVICE_STOP) stop_lpd();
5788		if(action & RC_SERVICE_START) start_lpd();
5789	}
5790	else if (strcmp(script, "u2ec") == 0)
5791	{
5792		if(action & RC_SERVICE_STOP) stop_u2ec();
5793		if(action & RC_SERVICE_START) start_u2ec();
5794	}
5795#endif
5796#ifdef RTCONFIG_MEDIA_SERVER
5797	else if (strcmp(script, "media") == 0)
5798	{
5799		if(action & RC_SERVICE_STOP) {
5800			force_stop_dms();
5801			stop_mt_daapd();
5802		}
5803		if(action & RC_SERVICE_START) {
5804			start_dms();
5805			start_mt_daapd();
5806		}
5807	}
5808	else if (strcmp(script, "dms") == 0)
5809	{
5810		if(action & RC_SERVICE_STOP) force_stop_dms();
5811		if(action & RC_SERVICE_START) start_dms();
5812	}
5813	else if (strcmp(script, "mt_daapd") == 0)
5814	{
5815		if(action & RC_SERVICE_STOP) stop_mt_daapd();
5816		if(action & RC_SERVICE_START) start_mt_daapd();
5817	}
5818#endif
5819#ifdef RTCONFIG_DISK_MONITOR
5820	else if (strcmp(script, "diskmon")==0)
5821	{
5822		if(action & RC_SERVICE_STOP) stop_diskmon();
5823		if(action & RC_SERVICE_START) start_diskmon();
5824	}
5825	else if (strcmp(script, "diskscan")==0)
5826	{
5827		if(action & RC_SERVICE_START)
5828			kill_pidfile_s("/var/run/disk_monitor.pid", SIGUSR2);
5829	}
5830#endif
5831	else if(!strncmp(script, "apps_", 5))
5832	{
5833		if(action & RC_SERVICE_START) {
5834			if(strcmp(script, "apps_update")==0)
5835				strcpy(nvtmp, "app_update.sh");
5836			else if(strcmp(script, "apps_stop")==0)
5837				strcpy(nvtmp, "app_stop.sh");
5838			else if(strcmp(script, "apps_upgrade")==0)
5839				strcpy(nvtmp, "app_upgrade.sh");
5840			else if(strcmp(script, "apps_install")==0)
5841				strcpy(nvtmp, "app_install.sh");
5842			else if(strcmp(script, "apps_remove")==0)
5843				strcpy(nvtmp, "app_remove.sh");
5844			else if(strcmp(script, "apps_enable")==0)
5845				strcpy(nvtmp, "app_set_enabled.sh");
5846			else if(strcmp(script, "apps_switch")==0)
5847				strcpy(nvtmp, "app_switch.sh");
5848			else if(strcmp(script, "apps_cancel")==0)
5849				strcpy(nvtmp, "app_cancel.sh");
5850			else strcpy(nvtmp, "");
5851
5852			if(strlen(nvtmp) > 0) {
5853				nvram_set("apps_state_autorun", "");
5854				nvram_set("apps_state_install", "");
5855				nvram_set("apps_state_remove", "");
5856				nvram_set("apps_state_switch", "");
5857				nvram_set("apps_state_stop", "");
5858				nvram_set("apps_state_enable", "");
5859				nvram_set("apps_state_update", "");
5860				nvram_set("apps_state_upgrade", "");
5861				nvram_set("apps_state_cancel", "");
5862				nvram_set("apps_state_error", "");
5863
5864				free_caches(FREE_MEM_PAGE, 1, 0);
5865
5866				cmd[0] = nvtmp;
5867				start_script(count, cmd);
5868			}
5869		}
5870	}
5871#ifdef RTCONFIG_USB_MODEM
5872	else if(!strncmp(script, "simauth", 7)){
5873		char *at_cmd[] = {"modem_status.sh", "simauth", NULL};
5874
5875		_eval(at_cmd, NULL, 0, NULL);
5876	}
5877	else if(!strncmp(script, "simpin", 6)){
5878		char pincode[8];
5879		char *at_cmd[] = {"modem_status.sh", "simpin", pincode, NULL};
5880		char *at_cmd2[] = {"modem_status.sh", "simauth", NULL};
5881
5882		if(nvram_get_int("usb_modem_act_sim") == 2){
5883			snprintf(pincode, 8, "%s", cmd[1]);
5884
5885			_eval(at_cmd, ">/tmp/modem_action.ret", 0, NULL);
5886			_eval(at_cmd2, NULL, 0, NULL);
5887		}
5888	}
5889	else if(!strncmp(script, "simpuk", 6)){
5890		char pukcode[10], pincode[8];
5891		char *at_cmd[] = {"modem_status.sh", "simpuk", pukcode, pincode, NULL};
5892		char *at_cmd2[] = {"modem_status.sh", "simauth", NULL};
5893
5894		if(nvram_get_int("usb_modem_act_sim") == 3){
5895			snprintf(pukcode, 10, "%s", cmd[1]);
5896			snprintf(pincode, 8, "%s", cmd[2]);
5897
5898			_eval(at_cmd, ">/tmp/modem_action.ret", 0, NULL);
5899			_eval(at_cmd2, NULL, 0, NULL);
5900		}
5901	}
5902	else if(!strncmp(script, "lockpin", 7)){
5903		char lock[4], pincode[8];
5904		char *at_cmd[] = {"modem_status.sh", "lockpin", lock, pincode, NULL};
5905		char *at_cmd2[] = {"modem_status.sh", "simauth", NULL};
5906
5907		if(nvram_get_int("usb_modem_act_sim") == 1){
5908			snprintf(pincode, 8, "%s", cmd[1]);
5909
5910			if(action & RC_SERVICE_STOP){ // unlock
5911				snprintf(lock, 4, "%s", "0");
5912				_eval(at_cmd, ">/tmp/modem_action.ret", 0, NULL);
5913				_eval(at_cmd2, NULL, 0, NULL);
5914			}
5915			else if(action & RC_SERVICE_START){ // lock
5916				snprintf(lock, 4, "%s", "1");
5917				_eval(at_cmd, ">/tmp/modem_action.ret", 0, NULL);
5918				_eval(at_cmd2, NULL, 0, NULL);
5919			}
5920		}
5921	}
5922	else if(!strncmp(script, "pwdpin", 6)){
5923		char pincode[8], pincode_new[8];
5924		char *at_cmd[] = {"modem_status.sh", "pwdpin", pincode, pincode_new, NULL};
5925		char *at_cmd2[] = {"modem_status.sh", "simauth", NULL};
5926
5927		if(nvram_get_int("usb_modem_act_sim") == 1){
5928			snprintf(pincode, 8, "%s", cmd[1]);
5929			snprintf(pincode_new, 8, "%s", cmd[2]);
5930
5931			_eval(at_cmd, ">/tmp/modem_action.ret", 0, NULL);
5932			_eval(at_cmd2, NULL, 0, NULL);
5933		}
5934	}
5935	else if(!strncmp(script, "modemscan", 9)){
5936		char *at_cmd[] = {"modem_status.sh", "scan", NULL};
5937		int usb_unit;
5938#ifdef RTCONFIG_DUALWAN
5939		char word[256], *next;
5940
5941		usb_unit = 0;
5942		foreach(word, nvram_safe_get("wans_dualwan"), next){
5943			if(!strcmp(word, "usb")){
5944				break;
5945			}
5946
5947			++usb_unit;
5948		}
5949#else
5950		usb_unit = 1;
5951#endif
5952
5953		if(usb_unit != WAN_UNIT_MAX){
5954			nvram_set("usb_modem_act_scanning", "3");
5955
5956			stop_wan_if(usb_unit);
5957			start_wan_if(usb_unit);
5958
5959			_eval(at_cmd, ">/tmp/modem_action.ret", 0, NULL);
5960		}
5961	}
5962	else if(!strncmp(script, "modemsta", 8)){
5963		char isp[32];
5964		char *at_cmd[] = {"modem_status.sh", "station", isp, NULL};
5965
5966		snprintf(isp, 32, "%s", nvram_safe_get("modem_roaming_isp"));
5967
5968		if(strlen(isp) > 0)
5969			_eval(at_cmd, ">/tmp/modem_action.ret", 0, NULL);
5970	}
5971	else if(!strncmp(script, "sendSMS", 7)){
5972		char phone[32], message[PATH_MAX];
5973		char *at_cmd[] = {"modem_status.sh", "send_sms", phone, message, NULL};
5974
5975		snprintf(phone, 32, "%s", nvram_safe_get("modem_sms_phone"));
5976		if(!strcmp(cmd[1], "alert"))
5977			snprintf(message, PATH_MAX, "%s %s bytes.", nvram_safe_get("modem_sms_message1"), nvram_safe_get("modem_bytes_data_warning"));
5978		else
5979			snprintf(message, PATH_MAX, "%s %s bytes.", nvram_safe_get("modem_sms_message2"), nvram_safe_get("modem_bytes_data_limit"));
5980
5981#ifdef RTCONFIG_INTERNAL_GOBI
5982		stop_lteled();
5983#endif
5984		_eval(at_cmd, ">/tmp/modem_action.ret", 0, NULL);
5985#ifdef RTCONFIG_INTERNAL_GOBI
5986		start_lteled();
5987#endif
5988	}
5989#if defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS)
5990	else if(!strncmp(script, "datacount", 9)){
5991		char *at_cmd[] = {"modem_status.sh", "bytes", NULL};
5992
5993		_eval(at_cmd, ">/tmp/modem_action.ret", 0, NULL);
5994	}
5995	else if(!strncmp(script, "resetcount", 10)){
5996		time_t now;
5997		char timebuf[32];
5998		char *at_cmd[] = {"modem_status.sh", "bytes-", NULL};
5999
6000		time(&now);
6001		snprintf(timebuf, 32, "%d", (int)now);
6002		nvram_set("modem_bytes_data_start", timebuf);
6003
6004		_eval(at_cmd, ">/tmp/modem_action.ret", 0, NULL);
6005	}
6006	else if(!strncmp(script, "sim_del", 7)){
6007		char sim_order[32];
6008		char *at_cmd[] = {"modem_status.sh", "imsi_del", sim_order, NULL};
6009
6010		snprintf(sim_order, 32, "%s", cmd[1]);
6011
6012		_eval(at_cmd, ">/tmp/modem_action.ret", 0, NULL);
6013	}
6014	else if(!strncmp(script, "set_dataset", 11)){
6015		char *at_cmd[] = {"modem_status.sh", "set_dataset", NULL};
6016
6017		_eval(at_cmd, ">/tmp/modem_action.ret", 0, NULL);
6018	}
6019#endif
6020#ifdef RTCONFIG_INTERNAL_GOBI
6021	else if(!strncmp(script, "simdetect", 9)){
6022		// Need to reboot after this.
6023		char buf[4];
6024		char *at_cmd1[] = {"modem_status.sh", "simdetect", NULL};
6025		char *at_cmd2[] = {"modem_status.sh", "simdetect", buf, NULL};
6026
6027		if(cmd[1]){
6028			snprintf(buf, 4, "%s", cmd[1]);
6029			_eval(at_cmd2, ">/tmp/modem_action.ret", 0, NULL);
6030		}
6031		else
6032			_eval(at_cmd1, ">/tmp/modem_action.ret", 0, NULL);
6033	}
6034	else if(!strncmp(script, "getband", 7)){
6035		char *at_cmd[] = {"modem_status.sh", "band", NULL};
6036
6037		_eval(at_cmd, ">/tmp/modem_action.ret", 0, NULL);
6038	}
6039	else if(!strncmp(script, "setband", 7)){
6040		char buf[8];
6041		char *at_cmd[] = {"modem_status.sh", "setband", buf, NULL};
6042
6043		snprintf(buf, 8, "%s", nvram_safe_get("modem_lte_band"));
6044		if(strlen(buf) <= 0)
6045			snprintf(buf, 8, "%s", "auto");
6046
6047		_eval(at_cmd, ">/tmp/modem_action.ret", 0, NULL);
6048	}
6049#endif
6050#endif // RTCONFIG_USB_MODEM
6051#endif // RTCONFIG_USB
6052	else if(!strncmp(script, "webs_", 5) || !strncmp(script, "gobi_", 5))
6053	{
6054		if(action & RC_SERVICE_START) {
6055#ifdef DEBUG_RCTEST // Left for UI debug
6056			char *webscript_dir;
6057			webscript_dir = nvram_safe_get("webscript_dir");
6058			if(strlen(webscript_dir))
6059				sprintf(nvtmp, "%s/%s.sh", webscript_dir, script);
6060			else
6061#endif
6062			sprintf(nvtmp, "%s.sh", script);
6063			cmd[0] = nvtmp;
6064			start_script(count, cmd);
6065		}
6066	}
6067	else if (strcmp(script, "ddns") == 0)
6068	{
6069		if(action & RC_SERVICE_STOP) stop_ddns();
6070		if(action & RC_SERVICE_START) start_ddns();
6071	}
6072	else if (strcmp(script, "aidisk_asusddns_register") == 0)
6073	{
6074		asusddns_reg_domain(0);
6075	}
6076	else if (strcmp(script, "adm_asusddns_register") == 0)
6077	{
6078		asusddns_reg_domain(1);
6079	}
6080	else if (strcmp(script, "httpd") == 0)
6081	{
6082		if(action & RC_SERVICE_STOP) stop_httpd();
6083		if(action & RC_SERVICE_START){
6084			start_httpd();
6085#ifdef RTCONFIG_BWDPI
6086			setup_wrs_conf();
6087#endif
6088		}
6089	}
6090	else if (strcmp(script, "telnetd") == 0)
6091	{
6092		if(action & RC_SERVICE_STOP) stop_telnetd();
6093		if(action & RC_SERVICE_START) start_telnetd();
6094	}
6095#ifdef RTCONFIG_SSH
6096	else if (strcmp(script, "sshd") == 0)
6097	{
6098		if(action & RC_SERVICE_STOP) stop_sshd();
6099		if(action & RC_SERVICE_START) start_sshd();
6100	}
6101#endif
6102#ifdef RTCONFIG_IPV6
6103	else if (strcmp(script, "ipv6") == 0) {
6104		if (action & RC_SERVICE_STOP)
6105			stop_ipv6();
6106		if (action & RC_SERVICE_START)
6107			start_ipv6();
6108	}
6109	else if (strcmp(script, "dhcp6c") == 0) {
6110		if (action & RC_SERVICE_STOP) {
6111#ifdef RTCONFIG_6RELAYD
6112			stop_6relayd();
6113#endif
6114			stop_dhcp6c();
6115		}
6116		if (action & RC_SERVICE_START)
6117			start_dhcp6c();
6118	}
6119	else if (strcmp(script, "wan6") == 0) {
6120		if (action & RC_SERVICE_STOP) {
6121			stop_wan6();
6122			stop_ipv6();
6123		}
6124		if (action & RC_SERVICE_START) {
6125			start_ipv6();
6126			// when no option from ipv4, restart wan entirely
6127			if(update_6rd_info()==0)
6128			{
6129				stop_wan_if(wan_primary_ifunit());
6130				start_wan_if(wan_primary_ifunit());
6131			}
6132			else
6133			{
6134				start_wan6();
6135			}
6136		}
6137	}
6138#endif
6139	else if (strcmp(script, "dns") == 0)
6140	{
6141		if(action & RC_SERVICE_START) reload_dnsmasq();
6142	}
6143	else if (strcmp(script, "dnsmasq") == 0)
6144	{
6145		if(action & RC_SERVICE_STOP) stop_dnsmasq();
6146		if(action & RC_SERVICE_START) start_dnsmasq();
6147	}
6148#ifdef RTCONFIG_DHCP_OVERRIDE
6149	else if (strcmp(script, "dhcpd") == 0)
6150	{
6151		if (nvram_match("dhcp_enable_x", "0")) {
6152			// disable dhcp server
6153			if (nvram_match("dnsqmode", "2")) {
6154				nvram_set("dnsqmode", "1");
6155				restart_dnsmasq(0);
6156			}
6157		}
6158		else {
6159			// enable dhcp server
6160			if (nvram_match("dnsqmode", "1")) {
6161				nvram_set("dnsqmode", "2");
6162				restart_dnsmasq(0);
6163			}
6164		}
6165
6166	}
6167#endif
6168	else if (strcmp(script, "upnp") == 0)
6169	{
6170		if(action & RC_SERVICE_STOP) stop_upnp();
6171		if(action & RC_SERVICE_START) start_upnp();
6172	}
6173	else if (strcmp(script, "qos") == 0)
6174	{
6175		if(action&RC_SERVICE_STOP) {
6176			stop_iQos();
6177#ifdef RTCONFIG_BWDPI
6178			stop_dpi_engine_service(0);
6179#endif
6180			del_iQosRules();
6181		}
6182		if(action & RC_SERVICE_START) {
6183			reinit_hwnat(-1);
6184			add_iQosRules(get_wan_ifname(wan_primary_ifunit()));
6185#ifdef RTCONFIG_BWDPI
6186			start_dpi_engine_service();
6187#endif
6188			start_iQos();
6189		}
6190	}
6191#ifdef RTCONFIG_BWDPI
6192	else if (strcmp(script, "wrs") == 0)
6193	{
6194		if(action & RC_SERVICE_STOP) stop_dpi_engine_service(0);
6195		if(action & RC_SERVICE_START) start_dpi_engine_service();
6196	}
6197	else if (strcmp(script, "wrs_force") == 0)
6198	{
6199		if(action & RC_SERVICE_STOP) stop_dpi_engine_service(1);
6200	}
6201	else if (strcmp(script, "sig_check") == 0)
6202	{
6203		if(action & RC_SERVICE_START){
6204			eval("sig_update.sh");
6205			if(nvram_get_int("sig_state_flag")) eval("sig_upgrade.sh", "1");
6206			stop_dpi_engine_service(0);
6207			start_dpi_engine_service();
6208		}
6209	}
6210#endif
6211	else if (strcmp(script, "traffic_analyzer") == 0)
6212	{
6213		// only stop service need to save database
6214		if(action & RC_SERVICE_STOP) hm_traffic_analyzer_save();
6215	}
6216#ifdef RTCONFIG_TRAFFIC_LIMITER
6217	else if (strcmp(script, "reset_traffic_limiter") == 0)
6218	{
6219		hm_traffic_limiter_save();
6220		reset_traffic_limiter_counter(0);
6221	}
6222	else if (strcmp(script, "reset_traffic_limiter_force") == 0)
6223	{
6224		reset_traffic_limiter_counter(1);
6225	}
6226	else if (strcmp(script, "reset_tl_count") == 0)
6227	{
6228		f_write_string("/jffs/tld/tl_count", "0", 0, 0);
6229	}
6230#endif
6231#ifdef RTCONFIG_PUSH_EMAIL
6232	else if (strcmp(script, "send_confirm_mail") == 0)
6233	{
6234		am_send_mail(0x4, NULL);
6235	}
6236#endif
6237	else if (strcmp(script, "logger") == 0)
6238	{
6239		if(action & RC_SERVICE_STOP) stop_logger();
6240		if(action & RC_SERVICE_START) start_logger();
6241	}
6242#ifdef RTCONFIG_CROND
6243	else if (strcmp(script, "crond") == 0)
6244	{
6245		if(action & RC_SERVICE_STOP) stop_cron();
6246		if(action & RC_SERVICE_START) start_cron();
6247	}
6248#endif
6249	else if (strcmp(script, "firewall") == 0)
6250	{
6251		if(action & RC_SERVICE_START)
6252		{
6253//			char wan_ifname[16];
6254
6255			reinit_hwnat(-1);
6256			// multiple instance is handled, but 0 is used
6257			start_default_filter(0);
6258
6259#ifdef WEB_REDIRECT
6260			// handled in start_firewall already
6261			// redirect_setting();
6262#endif
6263
6264#ifdef RTCONFIG_PARENTALCTRL
6265			start_pc_block();
6266#endif
6267
6268			// TODO handle multiple wan
6269			//start_firewall(get_wan_ifname(0, wan_ifname), nvram_safe_get("wan0_ipaddr"), "br0", nvram_safe_get("lan_ipaddr"));
6270			start_firewall(wan_primary_ifunit(), 0);
6271		}
6272	}
6273	else if (strcmp(script, "iptrestore") == 0)
6274	{
6275		// center control for iptable restore, called by process out side of rc
6276		_dprintf("%s: restart_iptrestore: %s.\n", __FUNCTION__, cmd[1]);
6277		if(cmd[1]) {
6278			if(action & RC_SERVICE_START) eval("iptables-restore", cmd[1]);
6279		}
6280	}
6281	else if (strcmp(script, "pppoe_relay") == 0)
6282	{
6283		if(action & RC_SERVICE_STOP) stop_pppoe_relay();
6284		if(action & RC_SERVICE_START) start_pppoe_relay(get_wanx_ifname(wan_primary_ifunit()));
6285	}
6286	else if (strcmp(script, "ntpc") == 0)
6287	{
6288		if(action & RC_SERVICE_STOP) stop_ntpc();
6289		if(action & RC_SERVICE_START) start_ntpc();
6290	}
6291	else if (strcmp(script, "rebuild_cifs_config_and_password") ==0)
6292	{
6293		fprintf(stderr, "rc rebuilding CIFS config and password databases.\n");
6294//		regen_passwd_files(); /* Must be called before regen_cifs_config_file(). */
6295//		regen_cifs_config_file();
6296	}
6297	else if (strcmp(script, "time") == 0)
6298	{
6299		if(action & RC_SERVICE_STOP) {
6300			stop_hour_monitor_service();
6301			stop_telnetd();
6302#ifdef RTCONFIG_SSH
6303			stop_sshd();
6304#endif
6305			stop_logger();
6306			//stop_httpd();
6307		}
6308		if(action & RC_SERVICE_START) {
6309			refresh_ntpc();
6310			start_logger();
6311			start_telnetd();
6312#ifdef RTCONFIG_SSH
6313			start_sshd();
6314#endif
6315			//start_httpd();
6316			start_firewall(wan_primary_ifunit(), 0);
6317			start_hour_monitor_service();
6318		}
6319	}
6320	else if (strcmp(script, "wps_method")==0)
6321	{
6322		if(action & RC_SERVICE_STOP) {
6323			stop_wps_method();
6324			if(!nvram_match("wps_ign_btn", "1"))
6325				kill_pidfile_s("/var/run/watchdog.pid", SIGUSR2);
6326		}
6327		if(action & RC_SERVICE_START) {
6328			if (!wps_band_radio_off(get_radio_band(nvram_get_int("wps_band"))) &&
6329			    !wps_band_ssid_broadcast_off(get_radio_band(nvram_get_int("wps_band")))) {
6330				start_wps_method();
6331				if(!nvram_match("wps_ign_btn", "1"))
6332					kill_pidfile_s("/var/run/watchdog.pid", SIGUSR1);
6333				else
6334					kill_pidfile_s("/var/run/watchdog.pid", SIGTSTP);
6335			}
6336			nvram_unset("wps_ign_btn");
6337		}
6338	}
6339	else if (strcmp(script, "reset_wps")==0)
6340	{
6341		reset_wps();
6342		kill_pidfile_s("/var/run/watchdog.pid", SIGUSR2);
6343	}
6344	else if (strcmp(script, "wps")==0)
6345	{
6346		if(action & RC_SERVICE_STOP) stop_wps();
6347		if(action & RC_SERVICE_START) start_wps();
6348		kill_pidfile_s("/var/run/watchdog.pid", SIGUSR2);
6349	}
6350	else if (strcmp(script, "autodet")==0)
6351	{
6352		if(action & RC_SERVICE_STOP) stop_autodet();
6353		if(action & RC_SERVICE_START) start_autodet();
6354	}
6355#ifdef RTCONFIG_QCA_PLC_UTILS
6356	else if (strcmp(script, "plcdet")==0)
6357	{
6358		if(action & RC_SERVICE_STOP) stop_plcdet();
6359		if(action & RC_SERVICE_START) start_plcdet();
6360	}
6361#endif
6362#if defined(CONFIG_BCMWL5)|| (defined(RTCONFIG_RALINK) && defined(RTCONFIG_WIRELESSREPEATER)) || defined(RTCONFIG_QCA)
6363	else if (strcmp(script, "wlcscan")==0)
6364	{
6365		if(action & RC_SERVICE_STOP) stop_wlcscan();
6366		if(action & RC_SERVICE_START) start_wlcscan();
6367	}
6368#endif
6369#ifdef RTCONFIG_WIRELESSREPEATER
6370	else if (strcmp(script, "wlcconnect")==0)
6371	{
6372		if(action & RC_SERVICE_STOP) stop_wlcconnect();
6373
6374#ifdef WEB_REDIRECT
6375		_dprintf("%s: notify wanduck: wlc_state=%d.\n", __FUNCTION__, nvram_get_int("wlc_state"));
6376		// notify the change to wanduck.
6377		kill_pidfile_s("/var/run/wanduck.pid", SIGUSR1);
6378#endif
6379
6380		if(action & RC_SERVICE_START) {
6381			restart_wireless();
6382			sleep(1);
6383			start_wlcconnect();
6384		}
6385	}
6386	else if (strcmp(script, "wlcmode")==0)
6387	{
6388		if(cmd[1]&& (atoi(cmd[1]) != nvram_get_int("wlc_mode"))) {
6389			nvram_set_int("wlc_mode", atoi(cmd[1]));
6390			if(nvram_match("lan_proto", "dhcp") && atoi(cmd[1])==0) {
6391				nvram_set("lan_ipaddr", nvram_default_get("lan_ipaddr"));
6392			}
6393
6394#if defined(RTCONFIG_SAMBASRV) && defined(RTCONFIG_FTP)
6395			stop_ftpd();
6396			stop_samba();
6397#endif
6398
6399#ifdef RTCONFIG_USB_PRINTER
6400			stop_u2ec();
6401#endif
6402			stop_networkmap();
6403			stop_httpd();
6404			stop_telnetd();
6405#ifdef RTCONFIG_SSH
6406			stop_sshd();
6407#endif
6408			stop_dnsmasq();
6409			stop_lan_wlc();
6410			stop_lan_port();
6411			stop_lan_wlport();
6412			start_lan_wlport();
6413			start_lan_port(8);
6414			start_lan_wlc();
6415			start_dnsmasq();
6416			start_httpd();
6417			start_telnetd();
6418#ifdef RTCONFIG_SSH
6419			start_sshd();
6420#endif
6421			start_networkmap(0);
6422#ifdef RTCONFIG_USB_PRINTER
6423			start_u2ec();
6424#endif
6425
6426#if defined(RTCONFIG_SAMBASRV) && defined(RTCONFIG_FTP)
6427			setup_passwd();
6428			start_samba();
6429			start_ftpd();
6430#endif
6431		}
6432	}
6433#endif
6434	else if (strcmp(script, "restore") == 0) {
6435		if(cmd[1]) restore_defaults_module(cmd[1]);
6436	}
6437	else if (strcmp(script, "chpass") == 0) {
6438			setup_passwd();
6439	}
6440#if RTCONFIG_SPEEDTEST
6441	else if (strcmp(script, "speedtest") == 0) {
6442		wan_bandwidth_detect();
6443	}
6444#endif
6445	// handle button action
6446	else if (strcmp(script, "wan_disconnect")==0) {
6447		logmessage("wan", "disconnected manually");
6448		stop_upnp();
6449		stop_wan();
6450	}
6451	else if (strcmp(script,"wan_connect")==0)
6452	{
6453		logmessage("wan", "connected manually");
6454
6455		rename("/tmp/ppp/log", "/tmp/ppp/log.~");
6456		start_wan();
6457		sleep(2);
6458		// TODO: function to force ppp connection
6459		start_upnp();
6460	}
6461#if defined(RTCONFIG_PPTPD) || defined(RTCONFIG_ACCEL_PPTPD)
6462	else if (strcmp(script, "pptpd") == 0)
6463	{
6464		if (action & RC_SERVICE_STOP)
6465		{
6466			stop_pptpd();
6467		}
6468		if (action & RC_SERVICE_START)
6469		{
6470			start_pptpd();
6471			start_firewall(wan_primary_ifunit(), 0);
6472		}
6473	}
6474#endif
6475
6476#ifdef RTCONFIG_SNMPD
6477	else if (strcmp(script, "snmpd") == 0)
6478	{
6479		if(action & RC_SERVICE_STOP) stop_snmpd();
6480		if(action & RC_SERVICE_START) {
6481			start_snmpd();
6482			start_firewall(wan_primary_ifunit(), 0);
6483		}
6484	}
6485#endif
6486
6487#ifdef RTCONFIG_OPENVPN
6488	else if (strncmp(script, "vpnclient", 9) == 0) {
6489		if (action & RC_SERVICE_STOP) stop_vpnclient(atoi(&script[9]));
6490		if (action & RC_SERVICE_START) start_vpnclient(atoi(&script[9]));
6491	}
6492	else if (strncmp(script, "vpnserver" ,9) == 0) {
6493		if (action & RC_SERVICE_STOP) stop_vpnserver(atoi(&script[9]));
6494		if (action & RC_SERVICE_START) start_vpnserver(atoi(&script[9]));
6495	}
6496#endif
6497#if defined(RTCONFIG_PPTPD) || defined(RTCONFIG_ACCEL_PPTPD)
6498	else if (strcmp(script, "vpnd") == 0)
6499	{
6500		if (action & RC_SERVICE_STOP){
6501			stop_pptpd();
6502		}
6503		if (action & RC_SERVICE_START){
6504			stop_upnp();
6505			start_pptpd();
6506			start_firewall(wan_primary_ifunit(), 0);
6507			start_upnp();
6508		}
6509	}
6510#endif
6511#if defined(RTCONFIG_OPENVPN)
6512	else if (strcmp(script, "openvpnd") == 0)
6513	{
6514		int openvpn_unit = nvram_get_int("vpn_server_unit");
6515		if (action & RC_SERVICE_STOP){
6516			stop_vpnserver(openvpn_unit);
6517		}
6518		if (action & RC_SERVICE_START){
6519 			start_vpnserver(openvpn_unit);
6520 		}
6521 	}
6522 #endif
6523#ifdef RTCONFIG_YANDEXDNS
6524	else if (strcmp(script, "yadns") == 0)
6525	{
6526		if (action & RC_SERVICE_STOP)
6527			stop_dnsmasq();
6528		if (action & RC_SERVICE_START) {
6529			update_resolvconf();
6530			start_dnsmasq();
6531		}
6532		start_firewall(wan_primary_ifunit(), 0);
6533	}
6534#endif
6535#ifdef RTCONFIG_ISP_METER
6536	else if (strcmp(script, "isp_meter") == 0) {
6537		_dprintf("%s: isp_meter: %s\n", __FUNCTION__, cmd[1]);
6538		if(strcmp(cmd[1], "down")==0) {
6539			stop_wan_if(0);
6540			update_wan_state("wan0_", WAN_STATE_STOPPED, WAN_STOPPED_REASON_METER_LIMIT);
6541		}
6542		else if(strcmp(cmd[1], "up")==0) {
6543			_dprintf("notify wan up!\n");
6544			start_wan_if(0);
6545		}
6546	}
6547#endif
6548
6549#ifdef RTCONFIG_TIMEMACHINE
6550	else if (strcmp(script, "timemachine") == 0)
6551	{
6552		if(action & RC_SERVICE_STOP) stop_timemachine();
6553		if(action & RC_SERVICE_START) start_timemachine();
6554	}
6555	else if (strcmp(script, "afpd") == 0)
6556	{
6557		if(action & RC_SERVICE_STOP) stop_afpd();
6558		if(action & RC_SERVICE_START) start_afpd();
6559	}
6560	else if (strcmp(script, "cnid_metad") == 0)
6561	{
6562		if(action & RC_SERVICE_STOP) stop_cnid_metad();
6563		if(action & RC_SERVICE_START) start_cnid_metad();
6564	}
6565#endif
6566#if defined(RTCONFIG_MDNS)
6567	else if (strcmp(script, "mdns") == 0)
6568	{
6569		if(action & RC_SERVICE_STOP) stop_mdns();
6570		if(action & RC_SERVICE_START) start_mdns();
6571	}
6572#endif
6573
6574#ifdef RTCONFIG_PUSH_EMAIL
6575	else if (strcmp(script, "sendmail") == 0)
6576	{
6577		start_DSLsendmail();
6578	}
6579#ifdef RTCONFIG_DSL_TCLINUX
6580	else if (strcmp(script, "DSLsenddiagmail") == 0)
6581	{
6582		start_DSLsenddiagmail();
6583	}
6584#endif
6585#endif
6586
6587#ifdef RTCONFIG_VPNC
6588	else if (strcmp(script, "vpncall") == 0)
6589	{
6590#if defined(RTCONFIG_OPENVPN)
6591		char buf[32] = {0};
6592		int i;
6593		int openvpnc_unit = nvram_get_int("vpn_client_unit");
6594#endif
6595		if (action & RC_SERVICE_STOP){
6596			stop_vpnc();
6597#if defined(RTCONFIG_OPENVPN)
6598			for( i = 1; i <= MAX_OVPN_CLIENT; i++ )
6599			{
6600				sprintf(buf, "vpnclient%d", i);
6601				if ( pidof(buf) >= 0 )
6602				{
6603					stop_vpnclient(i);
6604				}
6605			}
6606#endif
6607		}
6608
6609		if (action & RC_SERVICE_START){
6610#if defined(RTCONFIG_OPENVPN)
6611			if(nvram_match("vpnc_proto", "openvpn")){
6612				start_vpnclient(openvpnc_unit);
6613				stop_vpnc();
6614			}
6615			else{
6616				for( i = 1; i <= MAX_OVPN_CLIENT; i++ )
6617				{
6618					sprintf(buf, "vpnclient%d", i);
6619					if ( pidof(buf) >= 0 )
6620					{
6621						stop_vpnclient(i);
6622					}
6623				}
6624#endif
6625				start_vpnc();
6626#if defined(RTCONFIG_OPENVPN)
6627			}
6628#endif
6629		}
6630	}
6631#endif
6632#ifdef RTCONFIG_TR069
6633	else if (strncmp(script, "tr", 2) == 0) {
6634		if (action & RC_SERVICE_STOP) stop_tr();
6635		if (action & RC_SERVICE_START) start_tr();
6636	}
6637#endif
6638	else if (strcmp(script, "sh") == 0) {
6639		_dprintf("%s: shell: %s\n", __FUNCTION__, cmd[1]);
6640		if(cmd[1]) system(cmd[1]);
6641	}
6642	else if (strcmp(script, "app") == 0) {
6643#if defined(RTCONFIG_APP_PREINSTALLED) || defined(RTCONFIG_APP_NETINSTALLED)
6644		if(action & RC_SERVICE_STOP)
6645			stop_app();
6646#endif
6647	}
6648#ifdef RTCONFIG_USBRESET
6649	else if (strcmp(script, "usbreset") == 0) {
6650#define MAX_USBRESET_NUM 5
6651		char reset_seconds[] = {2, 4, 6, 8, 10};
6652		char *usbreset_active = nvram_safe_get("usbreset_active");
6653		char *usbreset_num = nvram_safe_get("usbreset_num");
6654		char buf[4];
6655		int reset_num = 0;
6656_dprintf("test 1. usbreset_active=%s, usbreset_num=%s.\n", usbreset_active, usbreset_num);
6657
6658		if(strlen(usbreset_num) > 0 && strlen(usbreset_active) > 0 && strcmp(usbreset_active, "0")){
6659			reset_num = atoi(usbreset_num);
6660			if(reset_num < MAX_USBRESET_NUM){
6661				stop_usb_program(1);
6662
6663_dprintf("test 2. turn off the USB power during %d seconds.\n", reset_seconds[reset_num]);
6664				set_pwr_usb(0);
6665				sleep(reset_seconds[reset_num]);
6666
6667				++reset_num;
6668				memset(buf, 0, 4);
6669				sprintf(buf, "%d", reset_num);
6670				nvram_set("usbreset_num", buf);
6671				nvram_set("usbreset_active", "0");
6672
6673				set_pwr_usb(1);
6674			}
6675		}
6676	}
6677#endif
6678#if defined (RTCONFIG_USB_XHCI)
6679#ifdef RTCONFIG_XHCIMODE
6680	else if(!strcmp(script, "xhcimode")){
6681		char param[32];
6682		int usb2enable = nvram_get_int("usb_usb2");
6683		int uhcienable = nvram_get_int("usb_uhci");
6684		int ohcienable = nvram_get_int("usb_ohci");
6685		int i;
6686
6687		_dprintf("xhcimode: stop_usb_program...\n");
6688		stop_usb_program(1);
6689
6690		_dprintf("xhcimode: remove xhci...\n");
6691		modprobe_r(USB30_MOD);
6692
6693		if(usb2enable){
6694			_dprintf("xhcimode: remove ehci...\n");
6695			modprobe_r(USB20_MOD);
6696		}
6697
6698		if(ohcienable){
6699			_dprintf("xhcimode: remove ohci...\n");
6700			modprobe_r(USBOHCI_MOD);
6701		}
6702
6703		if(uhcienable){
6704			_dprintf("xhcimode: remove uhci...\n");
6705			modprobe_r(USBUHCI_MOD);
6706		}
6707
6708		// It's necessary to wait the device being ready.
6709		int sec = nvram_get_int("xhcimode_waitsec");
6710		_dprintf("xhcimode: sleep %d second...\n", sec);
6711		sleep(sec);
6712
6713		memset(param, 0, 32);
6714		sprintf(param, "usb2mode=%s", cmd[1]);
6715		_dprintf("xhcimode: insert xhci %s...\n", param);
6716		modprobe(USB30_MOD, param);
6717
6718		if(usb2enable){
6719			i = nvram_get_int("usb_irq_thresh");
6720			if(i < 0 || i > 6)
6721				i = 0;
6722			memset(param, 0, 32);
6723			sprintf(param, "log2_irq_thresh=%d", i);
6724			_dprintf("xhcimode: insert ehci %s...\n", param);
6725			modprobe(USB20_MOD, param);
6726		}
6727
6728		if(ohcienable){
6729			_dprintf("xhcimode: insert ohci...\n");
6730			modprobe(USBOHCI_MOD);
6731		}
6732
6733		if(uhcienable){
6734			_dprintf("xhcimode: insert uhci...\n");
6735			modprobe(USBUHCI_MOD);
6736		}
6737	}
6738#endif
6739#endif
6740#ifdef RTCONFIG_JFFS2USERICON
6741	else if (strcmp(script, "lltdc") == 0) {
6742		if(action&RC_SERVICE_START) start_lltdc();
6743	}
6744#endif
6745#ifdef RTCONFIG_UPNPC
6746	else if (strcmp(script, "miniupnpc") == 0) {
6747		if(action&RC_SERVICE_STOP) stop_miniupnpc();
6748		if(action&RC_SERVICE_START) start_miniupnpc();
6749	}
6750#endif
6751#ifdef RTCONFIG_TOR
6752	else if (strcmp(script, "tor") == 0)
6753	{
6754		if(action & RC_SERVICE_STOP) stop_Tor_proxy();
6755		if(action & RC_SERVICE_START) start_Tor_proxy();
6756		start_firewall(wan_primary_ifunit(), 0);
6757	}
6758#endif
6759#ifdef RTCONFIG_CLOUDCHECK
6760	else if(!strcmp(script, "cloudcheck")){
6761		if(action & RC_SERVICE_STOP) stop_cloudcheck();
6762		if(action & RC_SERVICE_START) start_cloudcheck();
6763	}
6764#endif
6765#ifdef RTCONFIG_GETREALIP
6766	else if(!strcmp(script, "getrealip")){
6767		char tmp[128], prefix[] = "wlXXXXXXXXXX_";
6768		int wan_unit = atoi(cmd[1]);
6769		char *getip[] = {"getrealip.sh", NULL};
6770		pid_t pid;
6771
6772		snprintf(prefix, sizeof(prefix), "wan%d_", wan_unit);
6773
6774		if(action & RC_SERVICE_STOP){
6775			nvram_set(strcat_r(prefix, "realip_state", tmp), "0");
6776			nvram_set(strcat_r(prefix, "realip_ip", tmp), "");
6777		}
6778		if(action & RC_SERVICE_START){
6779			_eval(getip, ">>/dev/null", 0, &pid);
6780		}
6781	}
6782#endif
6783#ifdef RTCONFIG_QCA_PLC_UTILS
6784	else if (!strcmp(script, "plc_upgrade")) {
6785		if (nvram_match("asus_mfg", "0"))
6786			save_plc_setting();
6787	}
6788#endif
6789#ifdef RTCONFIG_KEY_GUARD
6790	else if (!strcmp(script, "key_guard")) {
6791		start_keyguard();
6792	}
6793#endif
6794	else if (!strcmp(script, "eco_guard")) {
6795		start_ecoguard();
6796	}
6797#ifdef RTCONFIG_QUAGGA
6798	else if (strcmp(script, "quagga") == 0)
6799	{
6800		if(action & RC_SERVICE_STOP) stop_quagga();
6801		if(action & RC_SERVICE_START) start_quagga();
6802	}
6803#endif
6804	else
6805	{
6806		fprintf(stderr,
6807			"WARNING: rc notified of unrecognized event `%s'.\n",
6808					script);
6809	}
6810
6811	if(nvptr){
6812_dprintf("goto again(%d)...\n", getpid());
6813		goto again;
6814	}
6815
6816	nvram_set("rc_service", "");
6817	nvram_set("rc_service_pid", "");
6818_dprintf("handle_notifications() end\n");
6819}
6820
6821#if defined(CONFIG_BCMWL5) || (defined(RTCONFIG_RALINK) && defined(RTCONFIG_WIRELESSREPEATER)) || defined(RTCONFIG_QCA)
6822void
6823start_wlcscan(void)
6824{
6825	if(getpid()!=1) {
6826		notify_rc("start_wlcscan");
6827		return;
6828	}
6829
6830	killall("wlcscan", SIGTERM);
6831
6832	system("wlcscan");
6833}
6834
6835void
6836stop_wlcscan(void)
6837{
6838	if(getpid()!=1) {
6839		notify_rc("stop_wlcscan");
6840		return;
6841	}
6842
6843	killall("wlcscan", SIGTERM);
6844}
6845#endif
6846#ifdef RTCONFIG_WIRELESSREPEATER
6847void
6848start_wlcconnect(void)
6849{
6850	char *wlcconnect_argv[] = {"wlcconnect", NULL};
6851	pid_t pid;
6852
6853	if(nvram_get_int("sw_mode")!=SW_MODE_REPEATER) {
6854		_dprintf("Not repeater mode, do not start_wlcconnect\n");
6855		return;
6856	}
6857
6858	if(getpid()!=1) {
6859		notify_rc("start_wlcconnect");
6860		return;
6861	}
6862
6863	killall("wlcconnect", SIGTERM);
6864
6865	_eval(wlcconnect_argv, NULL, 0, &pid);
6866}
6867
6868void
6869stop_wlcconnect(void)
6870{
6871	if(getpid()!=1) {
6872		notify_rc("stop_wlcconnect");
6873		return;
6874	}
6875
6876	killall("wlcconnect", SIGTERM);
6877}
6878#endif
6879
6880#ifdef RTCONFIG_QCA_PLC_UTILS
6881void
6882start_plcdet(void)
6883{
6884	char *autodet_argv[] = {"autodet_plc", NULL};
6885	pid_t pid;
6886
6887	if(getpid()!=1) {
6888		notify_rc("start_plcdet");
6889		return;
6890	}
6891
6892	killall_tk("autodet_plc");
6893
6894	_eval(autodet_argv, NULL, 0, &pid);
6895
6896	_dprintf("rc: ==> start_plcdet!!!\n");
6897	return;
6898}
6899
6900void
6901stop_plcdet(void)
6902{
6903	if(getpid()!=1) {
6904		notify_rc("stop_plcdet");
6905		return;
6906	}
6907
6908	killall_tk("autodet_plc");
6909	_dprintf("rc: ==> stop_plcdet!!!\n");
6910}
6911#endif
6912
6913void
6914start_autodet(void)
6915{
6916	char *autodet_argv[] = {"autodet", NULL};
6917	pid_t pid;
6918
6919	if(getpid()!=1) {
6920		notify_rc("start_autodet");
6921		return;
6922	}
6923
6924	killall_tk("autodet");
6925
6926	_eval(autodet_argv, NULL, 0, &pid);
6927
6928	return;
6929}
6930
6931void
6932stop_autodet(void)
6933{
6934	if(getpid()!=1) {
6935		notify_rc("stop_autodet");
6936		return;
6937	}
6938
6939	killall_tk("autodet");
6940}
6941
6942// string = S20transmission -> return value = transmission.
6943int get_apps_name(const char *string)
6944{
6945	char *ptr;
6946
6947	if(string == NULL)
6948		return 0;
6949
6950	if((ptr = rindex(string, '/')) != NULL)
6951		++ptr;
6952	else
6953		ptr = (char*) string;
6954	if(ptr[0] != 'S')
6955		return 0;
6956	++ptr; // S.
6957
6958	while(ptr != NULL){
6959		if(isdigit(ptr[0]))
6960			++ptr;
6961		else
6962			break;
6963	}
6964
6965	printf("%s", ptr);
6966
6967	return 1;
6968}
6969
6970int run_app_script(const char *pkg_name, const char *pkg_action)
6971{
6972	char app_name[128];
6973
6974	if(pkg_action == NULL || strlen(pkg_action) <= 0)
6975		return -1;
6976
6977	stop_upnp();
6978	memset(app_name, 0, 128);
6979	if(pkg_name == NULL)
6980		strcpy(app_name, "allpkg");
6981	else
6982		strcpy(app_name, pkg_name);
6983
6984	doSystem("app_init_run.sh %s %s", app_name, pkg_action);
6985
6986	sleep(5);
6987	start_upnp();
6988
6989	return 0;
6990}
6991
6992void start_nat_rules(void)
6993{
6994	int len;
6995	char *fn = NAT_RULES, ln[PATH_MAX];
6996	struct stat s;
6997	int retry;
6998
6999	// all rules applied directly according to currently status, wanduck help to triger those not cover by normal flow
7000 	if(nvram_match("x_Setting", "0")){
7001_dprintf("nat_rule: stop_nat_rules 2.\n");
7002		stop_nat_rules();
7003		return;
7004	}
7005
7006	if(nvram_get_int("nat_state") == NAT_STATE_NORMAL){
7007_dprintf("nat_rule: skip the 2nd start_nat_rules.\n");
7008		return;
7009	}
7010
7011	retry = 1;
7012	while(lstat(NAT_RULES, &s) || !S_ISLNK(s.st_mode) || (len = readlink(NAT_RULES, ln, sizeof(ln))) <= 0){
7013		if(retry > 1){
7014_dprintf("nat_rule: the nat rule file was gone.\n");
7015			return;
7016		}
7017
7018_dprintf("nat_rule: the nat rule file was not ready. wait %d seconds...\n", retry);
7019		sleep(1);
7020		++retry;
7021	}
7022
7023	ln[len] = '\0';
7024	fn = ln;
7025
7026	nvram_set_int("nat_state", NAT_STATE_NORMAL);
7027
7028	_dprintf("%s: apply the nat_rules(%s)!\n", __FUNCTION__, fn);
7029	logmessage("start_nat_rules", "apply the nat_rules(%s)!", fn);
7030
7031	setup_ct_timeout(TRUE);
7032	setup_udp_timeout(TRUE);
7033
7034	eval("iptables-restore", NAT_RULES);
7035
7036	return;
7037}
7038
7039void stop_nat_rules(void)
7040{
7041	if(nvram_match("nat_redirect_enable", "0")) return;
7042
7043	if (nvram_get_int("nat_state")==NAT_STATE_REDIRECT) return ;
7044
7045	nvram_set_int("nat_state", NAT_STATE_REDIRECT);
7046
7047	_dprintf("%s: apply the redirect_rules!\n", __FUNCTION__);
7048	logmessage("stop_nat_rules", "apply the redirect_rules!");
7049
7050	setup_ct_timeout(FALSE);
7051	setup_udp_timeout(FALSE);
7052
7053	eval("iptables-restore", "/tmp/redirect_rules");
7054
7055	return;
7056}
7057
7058#ifdef RTCONFIG_TOAD
7059static void
7060start_toads(void)
7061{
7062	char toad_ifname[16];
7063	char *next;
7064
7065	stop_toads();
7066
7067	foreach(toad_ifname, nvram_safe_get("toad_ifnames"), next) {
7068		eval("/usr/sbin/toad", "-i", toad_ifname);
7069	}
7070}
7071
7072static void
7073stop_toads(void)
7074{
7075	killall_tk("toad");
7076}
7077#endif
7078
7079#if defined(BCM_BSD)
7080int start_bsd(void)
7081{
7082	int ret = 0;
7083
7084	stop_bsd();
7085
7086	if (!nvram_get_int("smart_connect_x"))
7087		ret = -1;
7088	else {
7089#if 0
7090		nvram_unset("bsd_ifnames");
7091#endif
7092		ret = eval("/usr/sbin/bsd");
7093	}
7094
7095	return ret;
7096}
7097
7098void stop_bsd(void)
7099{
7100	killall_tk("bsd");
7101}
7102#endif /* BCM_BSD */
7103
7104#if defined(BCM_SSD)
7105int start_ssd(void)
7106{
7107	int ret = 0;
7108	char *ssd_argv[] = {"/usr/sbin/ssd", NULL};
7109	pid_t pid;
7110
7111	stop_ssd();
7112
7113	if (nvram_match("ssd_enable", "1"))
7114		ret = _eval(ssd_argv, NULL, 0, &pid);
7115
7116	return ret;
7117}
7118
7119void stop_ssd(void)
7120{
7121	killall_tk("ssd");
7122}
7123#endif /* BCM_SSD */
7124
7125#if defined(RTCONFIG_DHDAP)
7126int start_dhd_monitor(void)
7127{
7128	int ret = 0;
7129
7130#if defined(RTCONFIG_BCM7)
7131	return ret;
7132#endif
7133	killall_tk("dhd_monitor");
7134
7135	nvram_set("fast_restart", "1");
7136	ret = eval("/usr/sbin/dhd_monitor");
7137
7138	return ret;
7139}
7140
7141int stop_dhd_monitor(void)
7142{
7143	/* Don't kill dhd_monitor here */
7144	return 0;
7145}
7146#endif /* RTCONFIG_DHDAP */
7147
7148#ifdef RTCONFIG_INTERNAL_GOBI
7149int start_lteled(void)
7150{
7151	char *lteled_argv[] = {"lteled", NULL};
7152	pid_t pid;
7153
7154	stop_lteled();
7155
7156	if(nvram_get_int("lteled_down"))
7157		return 0;
7158
7159	return _eval(lteled_argv, NULL, 0, &pid);
7160}
7161
7162void stop_lteled(void)
7163{
7164	killall_tk("lteled");
7165}
7166#endif	/* RTCONFIG_INTERNAL_GOBI */
7167
7168
7169int
7170firmware_check_main(int argc, char *argv[])
7171{
7172	if(argc!=2)
7173		return -1;
7174
7175	_dprintf("FW: %s\n", argv[1]);
7176
7177#ifdef RTCONFIG_DSL
7178#ifdef RTCONFIG_RALINK
7179#else
7180	int isTcFwExist = 0;
7181	isTcFwExist = separate_tc_fw_from_trx(argv[1]);
7182#endif
7183#endif
7184
7185	if(check_imagefile(argv[1])) {
7186		_dprintf("FW OK\n");
7187		nvram_set("firmware_check", "1");
7188	}
7189	else {
7190		_dprintf("FW Fail\n");
7191		nvram_set("firmware_check", "0");
7192	}
7193
7194#ifdef RTCONFIG_DSL
7195#ifdef RTCONFIG_RALINK
7196#else
7197	if(isTcFwExist) {
7198		if(check_tc_firmware_crc()) // return 0 when pass
7199		{
7200			_dprintf("FW Fail\n");
7201			nvram_set("firmware_check", "0");
7202		}
7203	}
7204#endif
7205#endif
7206
7207	return 0;
7208}
7209
7210#ifdef RTCONFIG_HTTPS
7211int
7212rsasign_check_main(int argc, char *argv[])
7213{
7214	if(argc!=2)
7215		return -1;
7216
7217	_dprintf("rsa fw: %s\n", argv[1]);
7218
7219	if(check_rsasign(argv[1])) {
7220		_dprintf("rsasign check FW OK\n");
7221		nvram_set("rsasign_check", "1");
7222	}
7223	else {
7224		_dprintf("rsasign check FW Fail\n");
7225		nvram_set("rsasign_check", "0");
7226	}
7227	return 0;
7228}
7229#endif
7230
7231#ifdef RTCONFIG_BWDPI
7232int
7233rsasign_sig_check_main(int argc, char *argv[])
7234{
7235	if(argc!=2)
7236		return -1;
7237
7238	_dprintf("rsa fw: %s\n", argv[1]);
7239
7240#ifdef RTCONFIG_HTTPS
7241	if(check_rsasign(argv[1])) {
7242		_dprintf("rsasign check sig OK\n");
7243		nvram_set("bwdpi_rsa_check", "1");
7244	}
7245	else
7246#endif
7247	{
7248		_dprintf("rsasign check sig Fail\n");
7249		nvram_set("bwdpi_rsa_check", "0");
7250	}
7251	return 0;
7252}
7253#endif
7254
7255#ifdef RTCONFIG_DSL_TCLINUX
7256void
7257start_dsl_autodet(void)
7258{
7259	char *autodet_argv[] = {"auto_det", NULL};
7260	pid_t pid;
7261
7262	if(getpid()!=1) {
7263		notify_rc("start_dsl_autodet");
7264		return;
7265	}
7266
7267	killall_tk("auto_det");
7268	nvram_set("dsltmp_adslatequit", "0");
7269	nvram_set("dsltmp_autodet_state", "Detecting");
7270	sleep(1);
7271	_eval(autodet_argv, NULL, 0, &pid);
7272
7273	return;
7274}
7275
7276void
7277stop_dsl_autodet(void)
7278{
7279	if(getpid()!=1) {
7280		notify_rc("stop_dsl_autodet");
7281		return;
7282	}
7283
7284	killall_tk("auto_det");
7285}
7286#endif
7287
7288#ifdef RTCONFIG_HTTPS
7289int check_rsasign(char *fname)
7290{
7291
7292    RSA *rsa_pkey = NULL;
7293    EVP_PKEY *pkey;
7294    EVP_MD_CTX ctx;
7295    unsigned char buffer[16*1024];
7296    size_t len;
7297    unsigned char *sig;
7298    unsigned int siglen;
7299    struct stat stat_buf;
7300
7301	FILE * publicKeyFP;
7302	FILE * dataFileFP;
7303	FILE * sigFileFP;
7304
7305	publicKeyFP = fopen( "/usr/sbin/public.pem", "r" );
7306    	if (publicKeyFP == NULL){
7307    	    _dprintf( "Open publicKeyFP failure\n" );
7308    	    return 0;
7309    	}
7310
7311    if (!PEM_read_RSA_PUBKEY(publicKeyFP, &rsa_pkey, NULL, NULL)) {
7312        _dprintf("Error loading RSA public Key File.\n");
7313        return 0;
7314    }
7315
7316	fclose(publicKeyFP);
7317
7318    pkey = EVP_PKEY_new();
7319    if (!EVP_PKEY_assign_RSA(pkey, rsa_pkey)) {
7320        _dprintf("EVP_PKEY_assign_RSA: failed.\n");
7321        return 0;
7322    }
7323
7324	sigFileFP = fopen( "/tmp/rsasign.bin", "r" );
7325    	if (sigFileFP == NULL){
7326    	    _dprintf( "Open sigFileFP failure\n" );
7327    	    return 0;
7328    	}
7329
7330    /* Read the signature */
7331    if (fstat(fileno(sigFileFP), &stat_buf) == -1) {
7332        _dprintf("Unable to read signature \n");
7333        return 0;
7334    }
7335
7336    siglen = stat_buf.st_size;
7337    sig = (unsigned char *)malloc(siglen);
7338    if (sig == NULL) {
7339        _dprintf("Unable to allocated %d bytes for signature\n",
7340            siglen);
7341        return 0;
7342    }
7343
7344    if ((fread(sig, 1, siglen, sigFileFP)) != siglen) {
7345        _dprintf("Unable to read %d bytes for signature\n",
7346            siglen);
7347        return 0;
7348    }
7349	fclose(sigFileFP);
7350
7351    EVP_MD_CTX_init(&ctx);
7352    if (!EVP_VerifyInit(&ctx, EVP_sha1())) {
7353        _dprintf("EVP_SignInit: failed.\n");
7354        EVP_PKEY_free(pkey);
7355        return 0;
7356    }
7357
7358	dataFileFP = fopen( fname, "r" );
7359    	if (dataFileFP == NULL){
7360    	    _dprintf( "Open dataFileFP failure\n" );
7361    	    return 0;
7362    	}
7363
7364    while ((len = fread(buffer, 1, sizeof buffer, dataFileFP)) > 0) {
7365        if (!EVP_VerifyUpdate(&ctx, buffer, len)) {
7366            _dprintf("EVP_SignUpdate: failed.\n");
7367            EVP_PKEY_free(pkey);
7368            return 0;
7369        }
7370    }
7371
7372    if (ferror(dataFileFP)) {
7373        _dprintf("input file");
7374        EVP_PKEY_free(pkey);
7375        return 0;
7376    }
7377	fclose(dataFileFP);
7378
7379    if (!EVP_VerifyFinal(&ctx, sig, siglen, pkey)) {
7380        _dprintf("EVP_VerifyFinal: failed.\n");
7381        free(sig);
7382        EVP_PKEY_free(pkey);
7383        return 0;
7384    }else
7385	_dprintf("EVP_VerifyFinal: ok.\n");
7386
7387    free(sig);
7388    EVP_PKEY_free(pkey);
7389    return 1;
7390}
7391#endif
7392
7393#ifdef RTCONFIG_PARENTALCTRL
7394void stop_pc_block(void)
7395{
7396	if (pids("pc_block"))
7397		killall("pc_block", SIGTERM);
7398}
7399
7400void start_pc_block(void)
7401{
7402	char *pc_block_argv[] = {"pc_block", NULL};
7403	pid_t pid;
7404
7405	stop_pc_block();
7406
7407	if(nvram_get_int("MULTIFILTER_ALL") !=0 && count_pc_rules() > 0)
7408		_eval(pc_block_argv, NULL, 0, &pid);
7409}
7410#endif
7411
7412#ifdef RTCONFIG_TOR
7413void stop_Tor_proxy(void)
7414{
7415	if (pids("Tor"))
7416		killall("Tor", SIGTERM);
7417	sleep(1);
7418	remove("/tmp/torlog");
7419}
7420
7421void start_Tor_proxy(void)
7422{
7423	FILE *fp;
7424	pid_t pid;
7425	char *Tor_argv[] = { "Tor",
7426		"-f", "/tmp/torrc", "--quiet", NULL};
7427	char *Socksport;
7428	char *Transport;
7429	char *Dnsport;
7430	struct stat mdstat_jffs, mdstat_tmp;
7431	int mdesc_stat_jffs, mdesc_stat_tmp;
7432
7433	stop_Tor_proxy();
7434
7435	if(!nvram_get_int("Tor_enable"))
7436		return;
7437
7438	if ((fp = fopen("/tmp/torrc", "w")) == NULL)
7439		return;
7440
7441#if (defined(RTCONFIG_JFFS2)||defined(RTCONFIG_BRCM_NAND_JFFS2))
7442	mdesc_stat_tmp = stat("/tmp/.tordb/cached-microdesc-consensus", &mdstat_tmp);
7443	if(mdesc_stat_tmp == -1){
7444		mdesc_stat_jffs = stat("/jffs/.tordb/cached-microdesc-consensus", &mdstat_jffs);
7445		if(mdesc_stat_jffs != -1){
7446			_dprintf("Tor: restore microdescriptor directory\n");
7447			eval("cp", "-rf", "/jffs/.tordb", "/tmp/.tordb");
7448			sleep(1);
7449		}
7450	}
7451#endif
7452	if ((Socksport = nvram_get("Tor_socksport")) == NULL)	Socksport = "9050";
7453	if ((Transport = nvram_get("Tor_transport")) == NULL)   Transport = "9040";
7454	if ((Dnsport = nvram_get("Tor_dnsport")) == NULL)   	Dnsport = "9053";
7455
7456	fprintf(fp, "SocksPort %s\n", Socksport);
7457	fprintf(fp, "Log notice file /tmp/torlog\n");
7458	fprintf(fp, "VirtualAddrNetwork 10.192.0.0/10\n");
7459	fprintf(fp, "AutomapHostsOnResolve 1\n");
7460	fprintf(fp, "TransPort %s\n", Transport);
7461	fprintf(fp, "TransListenAddress 192.168.1.1\n");
7462	fprintf(fp, "DNSPort %s\n", Dnsport);
7463	fprintf(fp, "DNSListenAddress 192.168.1.1\n");
7464	fprintf(fp, "RunAsDaemon 1\n");
7465	fprintf(fp, "DataDirectory /tmp/.tordb\n");
7466	fprintf(fp, "AvoidDiskWrites 1\n");
7467	fclose(fp);
7468
7469	_eval(Tor_argv, NULL, 0, &pid);
7470}
7471#endif
7472
7473#ifdef RTCONFIG_CLOUDCHECK
7474void stop_cloudcheck(void){
7475	if(getpid() != 1){
7476		notify_rc("stop_cloudcheck");
7477		return;
7478	}
7479
7480	killall("booster_watchdo", SIGTERM); // only 15 characters can be identified.
7481}
7482
7483void start_cloudcheck(void){
7484	char *cmd[] = {"/bin/booster_watchdog", NULL};
7485	pid_t pid;
7486
7487	if(getpid() != 1){
7488		notify_rc("start_cloudcheck");
7489		return;
7490	}
7491
7492	if(nvram_get_int("enable_cloudcheck") != 1)
7493		return;
7494
7495	_eval(cmd, NULL, 0, &pid);
7496}
7497#endif
7498
7499#if ((defined(RTCONFIG_USER_LOW_RSSI) && defined(RTCONFIG_BCMARM)) || defined(RTCONFIG_NEW_USER_LOW_RSSI))
7500void stop_roamast(void){
7501	if (pids("roamast"))
7502		killall("roamast", SIGTERM);
7503}
7504
7505void start_roamast(void){
7506	char *cmd[] = {"roamast", NULL};
7507	char prefix[] = "wl_XXXXX";
7508	char tmp[32];
7509	pid_t pid;
7510	int i;
7511
7512	stop_roamast();
7513
7514	for (i = 0; i <= DEV_NUMIFS; i++) {
7515		sprintf(prefix, "wl%d_", i);
7516		if( nvram_get_int(strcat_r(prefix, "user_rssi", tmp)) != 0 ) {
7517			_eval(cmd, NULL, 0, &pid);
7518			break;
7519		}
7520	}
7521}
7522#endif
7523
7524#if defined(RTCONFIG_KEY_GUARD)
7525void stop_keyguard(void){
7526	if(pids("keyguard"))
7527		killall("keyguard", SIGTERM);
7528}
7529
7530void start_keyguard(void){
7531	char *cmd[] = {"keyguard", NULL};
7532	pid_t pid;
7533
7534	if(!nvram_get_int("kg_enable")) {
7535		stop_keyguard();
7536		return;
7537	}
7538	else {
7539		if(pids("keyguard"))
7540			killall("keyguard", SIGUSR1);
7541		else
7542			_eval(cmd, NULL, 0, &pid);
7543	}
7544}
7545#endif
7546
7547/* for APP ECO mode changing RF to 1x1 */
7548void start_ecoguard(void){
7549
7550	char *next = NULL;
7551	char ifname[32];
7552
7553	if ( !nvram_get_int("wlready") || nvram_get_int("guard_mode") != 1)	//guard_mode 0:default 1:eco mode
7554		return;
7555	else{
7556		foreach(ifname, nvram_safe_get("wl_ifnames"), next) {
7557#if defined(RTCONFIG_RALINK)
7558#elif defined(RTCONFIG_QCA)
7559#else /* BCM */
7560
7561#if defined(RTCONFIG_QTN)
7562#else
7563		eval("wl", "-i", ifname, "txchain", "1");
7564		eval("wl", "-i", ifname, "rxchain", "1");
7565		eval("wl", "-i", ifname, "down");
7566		eval("wl", "-i", ifname, "up");
7567#endif
7568#endif
7569		}
7570	}
7571}
7572
7573int service_main(int argc, char *argv[])
7574{
7575	if (argc != 2) usage_exit(argv[0], "<action_service>");
7576	notify_rc(argv[1]);
7577	printf("\nDone.\n");
7578	return 0;
7579}
7580