1/*
2 * This program is free software; you can redistribute it and/or
3 * modify it under the terms of the GNU General Public License as
4 * published by the Free Software Foundation; either version 2 of
5 * the License, or (at your option) any later version.
6 *
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10 * GNU General Public License for more details.
11 *
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
15 * MA 02111-1307 USA
16 *
17 * Copyright 2004, ASUSTeK Inc.
18 * All Rights Reserved.
19 *
20 * THIS SOFTWARE IS OFFERED "AS IS", AND ASUS GRANTS NO WARRANTIES OF ANY
21 * KIND, EXPRESS OR IMPLIED, BY STATUTE, COMMUNICATION OR OTHERWISE. BROADCOM
22 * SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS
23 * FOR A SPECIFIC PURPOSE OR NONINFRINGEMENT CONCERNING THIS SOFTWARE.
24 *
25 */
26#include <rc.h>
27
28#include <stdio.h>
29#include <time.h>
30#include <sys/time.h>
31#include <unistd.h>
32#include <stdlib.h>
33#include <sys/types.h>
34#include <shutils.h>
35#include <stdarg.h>
36#include <netdb.h>
37#include <arpa/inet.h>
38#ifdef RTCONFIG_RALINK
39#include <ralink.h>
40#endif
41#ifdef RTCONFIG_QCA
42#include <qca.h>
43#endif
44#include <shared.h>
45
46#include <syslog.h>
47#include <bcmnvram.h>
48#include <fcntl.h>
49#include <sys/stat.h>
50#include <math.h>
51#include <string.h>
52#include <sys/wait.h>
53#include <sys/ioctl.h>
54#include <sys/reboot.h>
55#include <sys/sysinfo.h>
56#ifdef RTCONFIG_USER_LOW_RSSI
57#if defined(RTCONFIG_RALINK)
58#include <typedefs.h>
59#else
60#include <wlioctl.h>
61#endif
62#endif
63
64#if defined(RTCONFIG_USB) && defined(RTCONFIG_NOTIFICATION_CENTER)
65#include <libnt.h>
66#endif
67
68
69
70#define BCM47XX_SOFTWARE_RESET	0x40		/* GPIO 6 */
71#define RESET_WAIT		2		/* seconds */
72#define RESET_WAIT_COUNT	RESET_WAIT * 10 /* 10 times a second */
73
74#define TEST_PERIOD		100		/* second */
75#define NORMAL_PERIOD		1		/* second */
76#define URGENT_PERIOD		100 * 1000	/* microsecond */
77#define RUSHURGENT_PERIOD	50 * 1000	/* microsecond */
78
79#define WPS_TIMEOUT_COUNT	121 * 20
80#ifdef RTCONFIG_WPS_LED
81#define WPS_SUCCESS_COUNT	3
82#endif
83#define WPS_WAIT		1		/* seconds */
84#define WPS_WAIT_COUNT		WPS_WAIT * 20	/* 20 times a second */
85
86#ifdef RTCONFIG_WPS_RST_BTN
87#define WPS_RST_DO_WPS_COUNT		( 1*10)	/*  1 seconds */
88#define WPS_RST_DO_RESTORE_COUNT	(10*10)	/* 10 seconds */
89#endif	/* RTCONFIG_WPS_RST_BTN */
90
91#ifdef RTCONFIG_WPS_ALLLED_BTN
92#define WPS_LED_WAIT_COUNT		1
93#endif
94
95//#if defined(RTCONFIG_JFFS2LOG) && defined(RTCONFIG_JFFS2)
96#if defined(RTCONFIG_JFFS2LOG) && (defined(RTCONFIG_JFFS2)||defined(RTCONFIG_BRCM_NAND_JFFS2))
97#define LOG_COMMIT_PERIOD	2		/* 2 x 30 seconds */
98static int log_commit_count = 0;
99#endif
100#if defined(RTCONFIG_USB_MODEM)
101#define LOG_MODEM_PERIOD	20		/* 10 minutes */
102static int log_modem_count = 0;
103#if defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS)
104#define MODEM_FLOW_PERIOD	1
105static int modem_flow_count = 0;
106static int modem_data_save = 0;
107#endif
108#endif
109#if defined(RTCONFIG_TOR) && (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2))
110#define TOR_CHECK_PERIOD	10		/* 10 x 30 seconds */
111unsigned int tor_check_count = 0;
112#endif
113
114static struct itimerval itv;
115/* to check watchdog alive */
116static struct itimerval itv02;
117static int watchdog_period = 0;
118#ifdef RTCONFIG_BCMARM
119static int chkusb3_period = 0;
120static int u3_chk_life = 6;
121#endif
122static int btn_pressed = 0;
123static int btn_count = 0;
124#ifdef BTN_SETUP
125static int btn_pressed_setup = 0;
126static int btn_count_setup = 0;
127static int wsc_timeout = 0;
128static int btn_count_setup_second = 0;
129static int btn_pressed_toggle_radio = 0;
130#endif
131
132#if defined(RTCONFIG_WIRELESS_SWITCH) && defined(RTCONFIG_DSL)
133// for WLAN sw init, only for slide switch
134static int wlan_sw_init = 0;
135#elif defined(RTCONFIG_WIRELESS_SWITCH) && defined(RTCONFIG_QCA)
136static int wifi_sw_old = -1;
137#endif
138#ifdef RTCONFIG_LED_BTN
139static int LED_status_old = -1;
140static int LED_status = -1;
141static int LED_status_changed = 0;
142static int LED_status_first = 1;
143static int LED_status_on = -1;
144#ifdef RTAC87U
145static int LED_switch_count = 0;
146static int BTN_pressed_count = 0;
147#endif
148#endif
149
150#if defined(RTCONFIG_WPS_ALLLED_BTN)
151static int LED_status_old = -1;
152static int LED_status = -1;
153static int LED_status_changed = 0;
154static int LED_status_on = -1;
155static int BTN_pressed_count = 0;
156#endif
157
158static int wlonunit = -1;
159
160extern int g_wsc_configured;
161extern int g_isEnrollee[MAX_NR_WL_IF];
162
163#define REGULAR_DDNS_CHECK	10 //10x30 sec
164static int ddns_check_count = 0;
165static int freeze_duck_count = 0;
166
167/* ErP Test */
168#ifdef RTCONFIG_ERP_TEST
169#define MODE_NORMAL 0
170#define MODE_PWRSAVE 1
171#define NO_ASSOC_CHECK 6 // 6x30 sec
172static int pwrsave_status = MODE_NORMAL;
173static int no_assoc_check = 0;
174#endif
175
176void
177sys_exit()
178{
179	printf("[watchdog] sys_exit");
180	set_action(ACT_REBOOT);
181	kill(1, SIGTERM);
182}
183
184static void
185alarmtimer(unsigned long sec, unsigned long usec)
186{
187	itv.it_value.tv_sec = sec;
188	itv.it_value.tv_usec = usec;
189	itv.it_interval = itv.it_value;
190	setitimer(ITIMER_REAL, &itv, NULL);
191}
192
193/* to check watchdog alive */
194static void
195alarmtimer02(unsigned long sec, unsigned long usec)
196{
197	itv02.it_value.tv_sec = sec;
198	itv02.it_value.tv_usec = usec;
199	itv02.it_interval = itv02.it_value;
200	setitimer(ITIMER_REAL, &itv02, NULL);
201}
202
203extern int no_need_to_start_wps();
204
205void led_control_normal(void)
206{
207#ifdef RTCONFIG_WPS_LED
208	int v = LED_OFF;
209	// the behavior in normal when wps led != power led
210	// wps led = off, power led = on
211
212	if (nvram_match("wps_success", "1"))
213		v = LED_ON;
214	__wps_led_control(v);
215#else
216	led_control(LED_WPS, LED_ON);
217#endif
218	// in case LED_WPS != LED_POWER
219
220#if defined(RTCONFIG_LED_BTN) && defined(RTAC87U)
221	LED_switch_count = nvram_get_int("LED_switch_count");
222	if (nvram_get_int("AllLED") == 0) return;
223#endif
224
225	led_control(LED_POWER, LED_ON);
226
227#if defined(RTN11P) || defined(RTN300)
228	led_control(LED_WPS, LED_ON);	//wps led is also 2g led. and NO power led.
229#else
230	if (nvram_get_int("led_pwr_gpio") != nvram_get_int("led_wps_gpio"))
231		led_control(LED_WPS, LED_OFF);
232#endif
233
234}
235
236void erase_nvram(void)
237{
238	switch (get_model()) {
239		case MODEL_RTAC56S:
240		case MODEL_RTAC56U:
241		case MODEL_RTAC3200:
242		case MODEL_RPAC68U:
243		case MODEL_RTAC68U:
244		case MODEL_DSLAC68U:
245		case MODEL_RTAC87U:
246		case MODEL_RTAC5300:
247		case MODEL_RTAC5300R:
248		case MODEL_RTAC88U:
249		case MODEL_RTAC3100:
250		case MODEL_RTAC1200G:
251		case MODEL_RTAC1200GP:
252			eval("mtd-erase2", "nvram");
253			break;
254		default:
255			eval("mtd-erase","-d","nvram");
256	}
257}
258
259int init_toggle(void)
260{
261	switch (get_model()) {
262		case MODEL_RTAC56S:
263		case MODEL_RTAC56U:
264		case MODEL_RTAC3200:
265		case MODEL_RPAC68U:
266		case MODEL_RTAC68U:
267		case MODEL_DSLAC68U:
268		case MODEL_RTAC87U:
269		case MODEL_RTAC5300:
270		case MODEL_RTAC5300R:
271		case MODEL_RTAC88U:
272		case MODEL_RTAC3100:
273			nvram_set("btn_ez_radiotoggle", "1");
274			return BTN_WIFI_TOG;
275		default:
276			return BTN_WPS;
277	}
278}
279
280void service_check(void)
281{
282	static int boot_ready = 0;
283
284	if (boot_ready > 6)
285		return;
286
287	if (!nvram_match("success_start_service", "1"))
288		return;
289
290	led_control(LED_POWER, ++boot_ready%2);
291}
292
293void btn_check(void)
294{
295	if (nvram_match("asus_mfg", "1"))
296	{
297		//TRACE_PT("asus mfg btn check!!!\n");
298#ifndef RTCONFIG_N56U_SR2
299		if (button_pressed(BTN_RESET))
300		{
301			TRACE_PT("button RESET pressed\n");
302			nvram_set("btn_rst", "1");
303		}
304#endif
305		if (button_pressed(BTN_WPS))
306		{
307			TRACE_PT("button WPS pressed\n");
308			nvram_set("btn_ez", "1");
309		}
310#ifdef RTCONFIG_WIRELESS_SWITCH
311		if (button_pressed(BTN_WIFI_SW))
312		{
313			TRACE_PT("button WIFI_SW pressed\n");
314			nvram_set("btn_wifi_sw", "1");
315		}
316		else
317		{
318			nvram_set("btn_wifi_sw", "0");
319		}
320#endif
321#if defined(RTCONFIG_WIFI_TOG_BTN)
322		if (button_pressed(BTN_WIFI_TOG))
323		{
324			TRACE_PT("button WIFI_TOG pressed\n");
325			nvram_set("btn_wifi_toggle", "1");
326		}
327#endif
328#ifdef RTCONFIG_TURBO
329		if (button_pressed(BTN_TURBO))
330		{
331			TRACE_PT("button TURBO pressed\n");
332			nvram_set("btn_turbo", "1");
333		}
334#endif
335#ifdef RTCONFIG_LED_BTN /* currently for RT-AC68U only */
336#if defined(RTAC3200) || defined(RTAC88U) || defined(RTAC3100) || defined(RTAC5300) || defined(RTAC5300R)
337		if (!button_pressed(BTN_LED))
338#else
339		if (!strcmp(get_productid(), "RT-AC66U V2"))
340			;
341		else if (((!nvram_match("cpurev", "c0") || nvram_get_int("PA") == 5023) && button_pressed(BTN_LED)) ||
342			   (nvram_match("cpurev", "c0") && nvram_get_int("PA") != 5023 && !button_pressed(BTN_LED)))
343#endif
344		{
345			TRACE_PT("button LED pressed\n");
346			nvram_set("btn_led", "1");
347		}
348#if defined(RTAC68U)
349		else if (!nvram_match("cpurev", "c0") || nvram_get_int("PA") == 5023)
350		{
351			TRACE_PT("button LED released\n");
352			nvram_set("btn_led", "0");
353		}
354#endif
355#endif
356#ifdef RTCONFIG_INTERNAL_GOBI
357		if (button_pressed(BTN_LTE))
358		{
359			TRACE_PT("button LTE pressed\n");
360			nvram_set("btn_lte", "1");
361		}
362#endif
363#ifdef RTCONFIG_SWMODE_SWITCH
364#if defined(PLAC66U)
365		if (button_pressed(BTN_SWMODE_SW_ROUTER) != nvram_get_int("swmode_switch"))
366		{
367			TRACE_PT("Switch changeover\n");
368			nvram_set("switch_mode", "1");
369		}
370#endif
371#endif
372
373		return;
374	}
375
376#ifdef BTN_SETUP
377	if (btn_pressed_setup == BTNSETUP_NONE)
378	{
379#endif
380#ifndef RTCONFIG_N56U_SR2
381	if (button_pressed(BTN_RESET))
382#else
383	if (0)
384#endif
385	{
386		TRACE_PT("button RESET pressed\n");
387
388	/*--------------- Add BTN_RST MFG test ------------------------*/
389#ifndef RTCONFIG_WPS_RST_BTN
390#ifdef RTCONFIG_DSL /* Paul add 2013/4/2 */
391			if ((btn_count % 2) == 0)
392				led_control(0, 1);
393			else
394				led_control(0, 0);
395#endif
396#endif	/* ! RTCONFIG_WPS_RST_BTN */
397			if (!btn_pressed)
398			{
399				btn_pressed = 1;
400				btn_count = 0;
401				alarmtimer(0, URGENT_PERIOD);
402			}
403			else
404			{	/* Whenever it is pushed steady */
405#ifdef RTCONFIG_WPS_RST_BTN
406				btn_count++;
407#else	/* ! RTCONFIG_WPS_RST_BTN */
408				if (++btn_count > RESET_WAIT_COUNT)
409				{
410					fprintf(stderr, "You can release RESET button now!\n");
411#if (defined(PLN12) || defined(PLAC56))
412					if (btn_pressed == 1)
413						set_wifiled(5);
414#endif
415					btn_pressed = 2;
416				}
417				if (btn_pressed == 2)
418				{
419#ifdef RTCONFIG_DSL /* Paul add 2013/4/2 */
420					led_control(0, 0);
421					alarmtimer(0, 0);
422					nvram_set("restore_defaults", "1");
423					if (notify_rc_after_wait("resetdefault")) {
424						/* Send resetdefault rc_service failed. */
425						alarmtimer(NORMAL_PERIOD, 0);
426					}
427#else
428				/* 0123456789 */
429				/* 0011100111 */
430					if ((btn_count % 10) < 2 || ((btn_count % 10) > 4 && (btn_count % 10) < 7))
431						led_control(LED_POWER, LED_OFF);
432					else
433						led_control(LED_POWER, LED_ON);
434#endif
435				}
436#endif	/* ! RTCONFIG_WPS_RST_BTN */
437			}
438	}
439#if defined(RTCONFIG_WIRELESS_SWITCH) && defined(RTCONFIG_DSL)
440	else if (button_pressed(BTN_WIFI_SW))
441	{
442		//TRACE_PT("button BTN_WIFI_SW pressed\n");
443			if (wlan_sw_init == 0)
444			{
445				wlan_sw_init = 1;
446/*
447				eval("iwpriv", "ra0", "set", "RadioOn=1");
448				eval("iwpriv", "rai0", "set", "RadioOn=1");
449				TRACE_PT("Radio On\n");
450				nvram_set("wl0_radio", "1");
451				nvram_set("wl1_radio", "1");
452				nvram_commit();
453*/
454			}
455			else
456			{
457				// if wlan switch on , btn reset routine goes here
458				if (btn_pressed == 2)
459				{
460					// IT MUST BE SAME AS BELOW CODE
461					led_control(LED_POWER, LED_OFF);
462					alarmtimer(0, 0);
463					nvram_set("restore_defaults", "1");
464					if (notify_rc_after_wait("resetdefault")) {
465						/* Send resetdefault rc_service failed. */
466						alarmtimer(NORMAL_PERIOD, 0);
467					}
468				}
469
470				if (nvram_match("wl0_HW_switch", "0") || nvram_match("wl1_HW_switch", "0")) {
471					//Ever apply the Wireless-Professional Web GU.
472					//Not affect the status of WiFi interface, so do nothing
473				}
474				else{	//trun on WiFi by HW slash, make sure both WiFi interface enable.
475					if (nvram_match("wl0_radio", "0") || nvram_match("wl1_radio", "0")) {
476						eval("iwpriv", "ra0", "set", "RadioOn=1");
477						eval("iwpriv", "rai0", "set", "RadioOn=1");
478						TRACE_PT("Radio On\n");
479						nvram_set("wl0_radio", "1");
480						nvram_set("wl1_radio", "1");
481
482						nvram_set("wl0_HW_switch", "0");
483						nvram_set("wl1_HW_switch", "0");
484						nvram_commit();
485					}
486				}
487			}
488	}
489#endif	/* RTCONFIG_WIRELESS_SWITCH && RTCONFIG_DSL */
490	else
491	{
492#ifdef RTCONFIG_WPS_RST_BTN
493		if (btn_pressed == 0)
494			;
495		else if (btn_count < WPS_RST_DO_RESTORE_COUNT)
496		{
497			if (btn_count < WPS_RST_DO_RESTORE_COUNT && btn_count >= WPS_RST_DO_WPS_COUNT && nvram_match("btn_ez_radiotoggle", "1"))
498			{
499				radio_switch(0);
500			}
501
502			if (btn_count < WPS_RST_DO_RESTORE_COUNT && btn_count >= WPS_RST_DO_WPS_COUNT
503			   && !no_need_to_start_wps()
504			   && !wps_band_radio_off(get_radio_band(0))
505			   && !wps_band_ssid_broadcast_off(get_radio_band(0))
506			   && nvram_match("btn_ez_radiotoggle", "0")
507			   && !nvram_match("wps_ign_btn", "1")
508			)
509			{
510				btn_pressed_setup = BTNSETUP_DETECT;
511				btn_count_setup = WPS_WAIT_COUNT;	//to trigger WPS
512				alarmtimer(0, RUSHURGENT_PERIOD);
513			}
514			else
515			{
516				btn_pressed_setup = BTNSETUP_NONE;
517				btn_count_setup = 0;
518				alarmtimer(NORMAL_PERIOD, 0);
519			}
520
521			btn_count = 0;
522			btn_pressed = 0;
523			led_control(LED_POWER, LED_ON);
524		}
525		else if (btn_count >= WPS_RST_DO_RESTORE_COUNT)	// to do restore
526#else	/* ! RTCONFIG_WPS_RST_BTN */
527		if (btn_pressed == 1)
528		{
529			btn_count = 0;
530			btn_pressed = 0;
531			led_control(LED_POWER, LED_ON);
532			alarmtimer(NORMAL_PERIOD, 0);
533		}
534		else if (btn_pressed == 2)
535#endif	/* ! RTCONFIG_WPS_RST_BTN */
536		{
537			led_control(LED_POWER, LED_OFF);
538#if (defined(PLN12) || defined(PLAC56))
539			set_wifiled(2);
540#endif
541			alarmtimer(0, 0);
542			nvram_set("restore_defaults", "1");
543			if (notify_rc_after_wait("resetdefault")) {
544				/* Send resetdefault rc_service failed. */
545				alarmtimer(NORMAL_PERIOD, 0);
546			}
547		}
548#if defined(RTCONFIG_WIRELESS_SWITCH) && defined(RTCONFIG_DSL)
549		else
550		{
551			// no button is pressed or released
552			if (wlan_sw_init == 0)
553			{
554				wlan_sw_init = 1;
555				eval("iwpriv", "ra0", "set", "RadioOn=0");
556				eval("iwpriv", "rai0", "set", "RadioOn=0");
557				TRACE_PT("Radio Off\n");
558				nvram_set("wl0_radio", "0");
559				nvram_set("wl1_radio", "0");
560
561				nvram_set("wl0_HW_switch", "1");
562				nvram_set("wl1_HW_switch", "1");
563
564				nvram_commit();
565			}
566			else
567			{
568				if (nvram_match("wl0_radio", "1") || nvram_match("wl1_radio", "1")) {
569					eval("iwpriv", "ra0", "set", "RadioOn=0");
570					eval("iwpriv", "rai0", "set", "RadioOn=0");
571					TRACE_PT("Radio Off\n");
572					nvram_set("wl0_radio", "0");
573					nvram_set("wl1_radio", "0");
574
575					nvram_set("wl0_timesched", "0");
576					nvram_set("wl1_timesched", "0");
577				}
578
579				//indicate use switch HW slash manually.
580				if (nvram_match("wl0_HW_switch", "0") || nvram_match("wl1_HW_switch", "0")) {
581					nvram_set("wl0_HW_switch", "1");
582					nvram_set("wl1_HW_switch", "1");
583				}
584			}
585		}
586#endif	/* RTCONFIG_WIRELESS_SWITCH && RTCONFIG_DSL */
587	}
588
589#ifdef BTN_SETUP
590	}
591
592	if (btn_pressed != 0) return;
593#if defined(CONFIG_BCMWL5) || defined(RTCONFIG_QCA)
594	// wait until wl is ready
595	if (!nvram_get_int("wlready")) return;
596#endif
597
598#if defined(RTCONFIG_WIRELESS_SWITCH) && defined(RTCONFIG_QCA)
599	if (wifi_sw_old != button_pressed(BTN_WIFI_SW))
600	{
601		wifi_sw_old = button_pressed(BTN_WIFI_SW);
602		if (wifi_sw_old != 0 && (!nvram_match("wl0_HW_switch", "0") || !nvram_match("wl1_HW_switch", "0")))
603		{
604			TRACE_PT("button BTN_WIFI_SW pressed: ON\n");
605			nvram_set("wl0_radio", "1");
606			nvram_set("wl1_radio", "1");
607			nvram_set("wl0_HW_switch", "0");	// 0 to be ON
608			nvram_set("wl1_HW_switch", "0");	// 0 to be ON
609			nvram_commit();
610			eval("radio", "on");			// ON
611		}
612		else if (wifi_sw_old == 0 && (!nvram_match("wl0_HW_switch", "1") || !nvram_match("wl1_HW_switch", "1")))
613		{
614			TRACE_PT("button BTN_WIFI_SW released: OFF\n");
615			eval("radio", "off");			// OFF
616			nvram_set("wl0_radio", "0");
617			nvram_set("wl1_radio", "0");
618			nvram_set("wl0_HW_switch", "1");	// 1 to be OFF
619			nvram_set("wl1_HW_switch", "1");	// 1 to be OFF
620			nvram_commit();
621		}
622	}
623#endif	/* RTCONFIG_WIRELESS_SWITCH && RTCONFIG_QCA */
624
625
626#ifndef RTCONFIG_WPS_RST_BTN
627	// independent wifi-toggle btn or Added WPS button radio toggle option
628#if defined(RTCONFIG_WIFI_TOG_BTN)
629	if (button_pressed(BTN_WIFI_TOG))
630#else
631	if (button_pressed(BTN_WPS) && nvram_match("btn_ez_radiotoggle", "1")
632		&& (nvram_get_int("sw_mode") != SW_MODE_REPEATER)) // repeater mode not support HW radio
633#endif
634	{
635		TRACE_PT("button WIFI_TOG pressed\n");
636		if (btn_pressed_toggle_radio == 0) {
637			radio_switch(0);
638			btn_pressed_toggle_radio = 1;
639			return;
640		}
641	}
642	else{
643		btn_pressed_toggle_radio = 0;
644	}
645#endif	/* RTCONFIG_WPS_RST_BTN */
646
647#if defined(RTCONFIG_WPS_ALLLED_BTN)
648	//use wps button to control all led on/off
649	if (nvram_match("btn_ez_mode", "1"))
650	{
651		LED_status_old = LED_status;
652		LED_status = button_pressed(BTN_WPS);
653
654		if (LED_status) {
655			TRACE_PT("button LED pressed\n");
656			++BTN_pressed_count;
657		}
658		else{
659			BTN_pressed_count = 0;
660			LED_status_changed = 0;
661		}
662
663		if (BTN_pressed_count > WPS_LED_WAIT_COUNT && LED_status_changed == 0) {
664			LED_status_changed = 1;
665			LED_status_on = nvram_get_int("AllLED");
666
667			if (LED_status_on)
668				nvram_set_int("AllLED", 0);
669			else
670				nvram_set_int("AllLED", 1);
671			LED_status_on = !LED_status_on;
672
673			if (LED_status_on) {
674				TRACE_PT("LED turn to normal\n");
675				led_control(LED_POWER, LED_ON);
676#if DSL_AC68U
677				char *dslledcmd_argv[] = {"adslate", "led", "normal", NULL};
678				_eval(dslledcmd_argv, NULL, 5, NULL);
679
680				eval("et", "robowr", "0", "0x18", "0x01ff");	// lan/wan ethernet/giga led
681				eval("et", "robowr", "0", "0x1a", "0x01ff");
682				if (wlonunit == -1 || wlonunit == 0) {
683					eval("wl", "ledbh", "10", "7");
684				}
685				if (wlonunit == -1 || wlonunit == 1) {
686					eval("wl", "-i", "eth2", "ledbh", "10", "7");
687					if (nvram_match("wl1_radio", "1")) {
688						nvram_set("led_5g", "1");
689						led_control(LED_5G, LED_ON);
690					}
691				}
692
693				kill_pidfile_s("/var/run/usbled.pid", SIGTSTP); // inform usbled to reset status
694#endif
695#if defined(RTAC1200G) || defined(RTAC1200GP)
696				eval("et", "robowr", "0", "0x18", "0x01ff");	// lan/wan ethernet/giga led
697				eval("et", "robowr", "0", "0x1a", "0x01ff");
698				eval("wl", "-i", "eth1", "ledbh", "3", "7");
699				eval("wl", "-i", "eth2", "ledbh", "11", "7");
700				kill_pidfile_s("/var/run/usbled.pid", SIGTSTP); // inform usbled to reset status
701#endif
702			}
703			else {
704				TRACE_PT("LED turn off\n");
705				setAllLedOff();
706			}
707
708			/* check LED_WAN status */
709			kill_pidfile_s("/var/run/wanduck.pid", SIGUSR2);
710			return;
711		}
712	}
713#endif
714
715#ifdef RTCONFIG_TURBO
716	if (button_pressed(BTN_TURBO))
717	{
718		TRACE_PT("button BTN_TURBO pressed\n");
719	}
720#endif
721#ifdef RTCONFIG_LED_BTN
722	LED_status_old = LED_status;
723	LED_status = button_pressed(BTN_LED);
724
725#if defined(RTAC68U) || defined(RTAC3200) || defined(RTAC88U) || defined(RTAC3100) || defined(RTAC5300) || defined(RTAC5300R)
726#if defined(RTAC68U)
727	if (!strcmp(get_productid(), "RT-AC66U V2"))
728		;
729	else if (nvram_match("cpurev", "c0") && nvram_get_int("PA") != 5023) {
730		if (!LED_status &&
731		    (LED_status != LED_status_old))
732		{
733			LED_status_changed = 1;
734			if (LED_status_first)
735			{
736				LED_status_first = 0;
737				LED_status_on = 0;
738			}
739			else
740				LED_status_on = 1 - LED_status_on;
741		}
742		else
743			LED_status_changed = 0;
744	} else {
745		LED_status_changed = 0;
746		if (LED_status != LED_status_old)
747		{
748			if (LED_status_first)
749			{
750				LED_status_first = 0;
751				LED_status_on = LED_status;
752			}
753			else
754				LED_status_changed = 1;
755		}
756	}
757#elif defined(RTAC3200) || defined(RTAC88U) || defined(RTAC3100) || defined(RTAC5300) || defined(RTAC5300R)
758	if (!LED_status &&
759	    (LED_status != LED_status_old))
760	{
761		LED_status_changed = 1;
762		if (LED_status_first)
763		{
764			LED_status_first = 0;
765			LED_status_on = 0;
766		}
767		else
768			LED_status_on = 1 - LED_status_on;
769	}
770	else
771		LED_status_changed = 0;
772#endif
773
774	if (LED_status_changed)
775	{
776		TRACE_PT("button BTN_LED pressed\n");
777#if 0
778#ifdef RTAC68U
779		if (nvram_get_int("btn_led_mode"))
780			reboot(RB_AUTOBOOT);
781#endif
782#endif
783
784#if defined(RTAC68U)
785		if (((!nvram_match("cpurev", "c0") || nvram_get_int("PA") == 5023) && LED_status == LED_status_on) ||
786		      (nvram_match("cpurev", "c0") && nvram_get_int("PA") != 5023 && LED_status_on))
787#elif defined(RTAC3200) || defined(RTAC88U) || defined(RTAC3100) || defined(RTAC5300) || defined(RTAC5300R)
788		if (LED_status_on)
789#endif
790			nvram_set_int("AllLED", 1);
791		else
792			nvram_set_int("AllLED", 0);
793#if defined(RTAC68U)
794		if (((!nvram_match("cpurev", "c0") || nvram_get_int("PA") == 5023) && LED_status == LED_status_on) ||
795		      (nvram_match("cpurev", "c0") && nvram_get_int("PA") != 5023 && LED_status_on))
796#elif defined(RTAC3200) || defined(RTAC88U) || defined(RTAC3100) || defined(RTAC5300) || defined(RTAC5300R)
797		if (LED_status_on)
798#endif
799		{
800			led_control(LED_POWER, LED_ON);
801
802#if defined(RTAC3200) || defined(RTAC88U) || defined(RTAC3100) || defined(RTAC5300) || defined(RTAC5300R)
803			kill_pidfile_s("/var/run/wanduck.pid", SIGUSR2);
804#else
805#ifdef RTAC68U
806			if (!strcmp(get_productid(), "RT-AC66U V2"))
807				kill_pidfile_s("/var/run/wanduck.pid", SIGUSR2);
808			else
809#endif
810			eval("et", "robowr", "0", "0x18", "0x01ff");
811			eval("et", "robowr", "0", "0x1a", "0x01ff");
812#endif
813
814			if (wlonunit == -1 || wlonunit == 0) {
815#ifdef RTAC68U
816				eval("wl", "ledbh", "10", "7");
817#elif defined(RTAC3200)
818				eval("wl", "-i", "eth2", "ledbh", "10", "7");
819#elif defined(RTAC88U) || defined(RTAC3100) || defined(RTAC5300) || defined(RTAC5300R)
820				eval("wl", "ledbh", "9", "7");
821#endif
822			}
823			if (wlonunit == -1 || wlonunit == 1) {
824#ifdef RTAC68U
825				eval("wl", "-i", "eth2", "ledbh", "10", "7");
826#elif defined(RTAC3200)
827				eval("wl", "ledbh", "10", "7");
828#elif defined(RTAC88U) || defined(RTAC3100) || defined(RTAC5300) || defined(RTAC5300R)
829				eval("wl", "-i", "eth2", "ledbh", "9", "7");
830#endif
831			}
832#if defined(RTAC3200)
833			if (wlonunit == -1 || wlonunit == 2) {
834				eval("wl", "-i", "eth3", "ledbh", "10", "7");
835			}
836#elif defined(RTAC5300) || defined(RTAC5300R)
837			if (wlonunit == -1 || wlonunit == 2) {
838				eval("wl", "-i", "eth3", "ledbh", "9", "7");
839			}
840#endif
841#ifdef RTAC68U
842			if (nvram_match("wl1_radio", "1") &&
843			   (wlonunit == -1 || wlonunit == 1))
844			{
845				nvram_set("led_5g", "1");
846				led_control(LED_5G, LED_ON);
847			}
848#endif
849#ifdef RTCONFIG_TURBO
850			if (nvram_match("wl0_radio", "1") || nvram_match("wl1_radio", "1")
851#ifdef RTAC3200
852				|| nvram_match("wl2_radio", "1")
853#endif
854			)
855				led_control(LED_TURBO, LED_ON);
856#endif
857			kill_pidfile_s("/var/run/usbled.pid", SIGTSTP); // inform usbled to reset status
858		}
859		else
860			setAllLedOff();
861	}
862#elif defined(RTAC87U)
863	if (LED_status)
864		++BTN_pressed_count;
865	else{
866		BTN_pressed_count = 0;
867		LED_status_changed = 0;
868	}
869
870	if (BTN_pressed_count >= LED_switch_count && LED_status_changed == 0) {
871		LED_status_changed = 1;
872		LED_status_on = nvram_get_int("AllLED");
873
874		if (LED_status_on)
875			nvram_set_int("AllLED", 0);
876		else
877			nvram_set_int("AllLED", 1);
878		LED_status_on = !LED_status_on;
879
880		if (LED_status_on) {
881			led_control(LED_POWER, LED_ON);
882#if defined(RTAC3200) || defined(RTAC88U) || defined(RTAC3100) || defined(RTAC5300) || defined(RTAC5300R)
883			eval("et", "-i", "eth0", "robowr", "0", "0x18", "0x01ff");
884			eval("et", "-i", "eth0", "robowr", "0", "0x1a", "0x01ff");
885#else
886			eval("et", "robowr", "0", "0x18", "0x01ff");
887			eval("et", "robowr", "0", "0x1a", "0x01ff");
888#endif
889			qcsapi_wifi_run_script("router_command.sh", "lan4_led_ctrl on");
890
891			if (nvram_match("wl0_radio", "1"))
892				eval("wl", "ledbh", "10", "7");
893			if (nvram_match("wl1_radio", "1")) {
894				qcsapi_wifi_run_script("router_command.sh", "wifi_led_on");
895				qcsapi_led_set(1, 1);
896			}
897
898#ifdef RTCONFIG_EXT_LED_WPS
899			led_control(LED_WPS, LED_OFF);
900#else
901			led_control(LED_WPS, LED_ON);
902#endif
903
904			kill_pidfile_s("/var/run/usbled.pid", SIGTSTP); // inform usbled to reset status
905		}
906		else
907			setAllLedOff();
908
909		/* check LED_WAN status */
910		kill_pidfile_s("/var/run/wanduck.pid", SIGUSR2);
911	}
912#endif
913#endif	/* RTCONFIG_LED_BTN */
914
915#if defined(RTCONFIG_BCMWL6) && defined(RTCONFIG_PROXYSTA)
916	if (psta_exist() || psr_exist())
917		return;
918#endif
919	if (btn_pressed_setup < BTNSETUP_START)
920	{
921#ifdef RTCONFIG_WPS_RST_BTN
922		if (btn_pressed_setup == BTNSETUP_DETECT)
923#else
924		if (button_pressed(BTN_WPS) &&
925		    !no_need_to_start_wps() &&
926		    !wps_band_radio_off(get_radio_band(0)) &&
927		    !wps_band_ssid_broadcast_off(get_radio_band(0)) &&
928#ifndef RTCONFIG_WIFI_TOG_BTN
929		    nvram_match("btn_ez_radiotoggle", "0") &&
930#endif
931#ifdef RTCONFIG_WPS_ALLLED_BTN
932		    nvram_match("btn_ez_mode", "0") &&
933#endif
934		    !nvram_match("wps_ign_btn", "1"))
935#endif	/* ! RTCONFIG_WPS_RST_BTN */
936		{
937			if (nvram_match("wps_enable", "1")) {
938				TRACE_PT("button WPS pressed\n");
939
940				if (btn_pressed_setup == BTNSETUP_NONE)
941				{
942					btn_pressed_setup = BTNSETUP_DETECT;
943					btn_count_setup = 0;
944					alarmtimer(0, RUSHURGENT_PERIOD);
945				}
946				else
947				{	/* Whenever it is pushed steady */
948#if 0
949					if (++btn_count_setup > WPS_WAIT_COUNT)
950#else
951					if (++btn_count_setup)
952#endif
953					{
954						btn_pressed_setup = BTNSETUP_START;
955						btn_count_setup = 0;
956						btn_count_setup_second = 0;
957						nvram_set("wps_ign_btn", "1");
958#ifdef RTCONFIG_WIFI_CLONE
959						if (nvram_get_int("sw_mode") == SW_MODE_ROUTER
960									|| nvram_get_int("sw_mode") == SW_MODE_AP) {
961							nvram_set("wps_enrollee", "1");
962							nvram_set("wps_e_success", "0");
963						}
964#if (defined(PLN12) || defined(PLAC56))
965						set_wifiled(3);
966#endif
967#endif
968#if 0
969						start_wps_pbc(0);	// always 2.4G
970#else
971						kill_pidfile_s("/var/run/wpsaide.pid", SIGTSTP);
972#endif
973						wsc_timeout = WPS_TIMEOUT_COUNT;
974					}
975				}
976			} else {
977				TRACE_PT("button WPS pressed, skip\n");
978			}
979		}
980		else if (btn_pressed_setup == BTNSETUP_DETECT)
981		{
982			btn_pressed_setup = BTNSETUP_NONE;
983			btn_count_setup = 0;
984#ifndef RTCONFIG_WPS_LED
985			wps_led_control(LED_ON);
986#endif
987			alarmtimer(NORMAL_PERIOD, 0);
988		}
989#ifdef RTCONFIG_WPS_LED
990		else
991		{
992			if (nvram_match("wps_success", "1") && ++btn_count_setup_second > WPS_SUCCESS_COUNT) {
993				btn_count_setup_second = 0;
994				nvram_set("wps_success", "0");
995				__wps_led_control(LED_OFF);
996			}
997		}
998#endif
999	}
1000	else
1001	{
1002		if (!nvram_match("wps_ign_btn", "1")) {
1003#ifndef RTCONFIG_WPS_RST_BTN
1004			if (button_pressed(BTN_WPS) &&
1005			    !no_need_to_start_wps() &&
1006			    !wps_band_radio_off(get_radio_band(0)) &&
1007			    !wps_band_ssid_broadcast_off(get_radio_band(0)))
1008			{
1009				/* Whenever it is pushed steady, again... */
1010#if 0
1011				if (++btn_count_setup_second > WPS_WAIT_COUNT)
1012#else
1013				if (++btn_count_setup_second)
1014#endif
1015				{
1016					btn_pressed_setup = BTNSETUP_START;
1017					btn_count_setup_second = 0;
1018					nvram_set("wps_ign_btn", "1");
1019#if 0
1020					start_wps_pbc(0);	// always 2.4G
1021#else
1022					kill_pidfile_s("/var/run/wpsaide.pid", SIGTSTP);
1023#endif
1024					wsc_timeout = WPS_TIMEOUT_COUNT;
1025				}
1026			}
1027#endif	/* ! RTCONFIG_WPS_RST_BTN */
1028
1029			if (is_wps_stopped() || --wsc_timeout == 0)
1030			{
1031				wsc_timeout = 0;
1032
1033				btn_pressed_setup = BTNSETUP_NONE;
1034				btn_count_setup = 0;
1035				btn_count_setup_second = 0;
1036
1037				led_control_normal();
1038
1039				alarmtimer(NORMAL_PERIOD, 0);
1040#if (!defined(W7_LOGO) && !defined(WIFI_LOGO))
1041				stop_wps_method();
1042#endif
1043#ifdef RTCONFIG_WIFI_CLONE
1044				if (nvram_match("wps_e_success", "1")) {
1045#if (defined(PLN12) || defined(PLAC56))
1046					set_wifiled(2);
1047#endif
1048					notify_rc("restart_wireless");
1049				}
1050#if (defined(PLN12) || defined(PLAC56))
1051				else
1052					set_wifiled(1);
1053#endif
1054#endif
1055				return;
1056			}
1057		}
1058
1059		++btn_count_setup;
1060		btn_count_setup = (btn_count_setup % 20);
1061
1062		/* 0123456789 */
1063		/* 1010101010 */
1064		if ((btn_count_setup % 2) == 0 && (btn_count_setup > 10))
1065			wps_led_control(LED_ON);
1066		else
1067			wps_led_control(LED_OFF);
1068	}
1069#endif
1070}
1071
1072#define DAYSTART (0)
1073#define DAYEND (60*60*23 + 60*59 + 60) // 86400
1074static int in_sched(int now_mins, int now_dow, int (*enableTime)[24])
1075{
1076	//cprintf("%s: now_mins=%d sched_begin=%d sched_end=%d sched_begin2=%d sched_end2=%d now_dow=%d sched_dow=%d\n", __FUNCTION__, now_mins, sched_begin, sched_end, sched_begin2, sched_end2, now_dow, sched_dow);
1077	int currentTime;
1078	int x=0,y=0;
1079	int tableTimeStart, tableTimeEnd;
1080	// 8*60*60 = AM0.00~AM8.00
1081	currentTime = (now_mins*60) + now_dow*DAYEND;
1082
1083	for(;x<7;x++)
1084	{
1085		y=0;
1086		for(;y<24;y++)
1087		{
1088			if (enableTime[x][y] == 1)
1089			{
1090				tableTimeStart = x*DAYEND + y*60*60;
1091				tableTimeEnd = x*DAYEND + (y+1)*60*60;
1092
1093				if (y == 23)
1094				tableTimeEnd = tableTimeEnd - 1; //sunday = 0 ~ 86399
1095				//_dprintf("tableTimeStart == %d  %d  %d\n",tableTimeStart,tableTimeEnd,currentTime);
1096
1097				if (tableTimeStart<=currentTime && currentTime < tableTimeEnd)
1098				{
1099					return 1;
1100				}
1101			}
1102		}
1103	}
1104	return 0;
1105
1106}
1107
1108int timecheck_item(char *activeTime)
1109{
1110	int current, active;
1111	int now_dow;
1112	time_t now;
1113	struct tm *tm;
1114	char Date[] = "XX";
1115	char startTime[] = "XX";
1116	char endTime[] = "XX";
1117	int tableAllOn = 0;	// 0: wifi time all off 1: wifi time all on  2: check&calculate wifi open slot
1118	int schedTable[7][24];
1119	int x=0, y=0, z=0;   //for first, second, third loop
1120
1121	/* current router time */
1122	setenv("TZ", nvram_safe_get("time_zone_x"), 1);
1123	time(&now);
1124	tm = localtime(&now);
1125	now_dow = tm->tm_wday;
1126	current = tm->tm_hour * 60 + tm->tm_min; //minutes
1127	//active = 0;
1128
1129//if (current % 60 == 0)   //and apply setting
1130//{
1131	/*initial time table*/
1132	x=0;
1133	for(;x<7;x++)
1134	{
1135		y=0;
1136		for(;y<24;y++)
1137		{
1138			schedTable[x][y]=0;
1139		}
1140	 }
1141
1142	active = 0;
1143	if (activeTime[0] == '0' && activeTime[1] == '0' && activeTime[2] == '0' && activeTime[3] == '0'
1144		&& activeTime[4] == '0' && activeTime[5] == '0')
1145	{
1146		tableAllOn = 1; // all open
1147	}
1148	else if (!strcmp(activeTime, ""))
1149	{
1150		tableAllOn = 0; // all close
1151	}
1152	else
1153	{
1154		tableAllOn = 2;
1155		/* Counting variables quantity*/
1156		x=0;
1157		int schedCount = 1; // how many variables in activeTime	111014<222024<331214 count will be 3
1158		for(;x<strlen(activeTime);x++)
1159		{
1160			if (activeTime[x] == '<')
1161			schedCount++;
1162		}
1163
1164		/* analyze for sched Date, startTime, endTime*/
1165		x=0;
1166		int loopCount=0;
1167		for(;x<schedCount;x++)
1168		{
1169			do
1170			{
1171				if (loopCount < (2 + (7*x)))
1172				{
1173				Date[loopCount-7*x] = activeTime[loopCount];
1174				}
1175				else if (loopCount < (4 + (7*x)))
1176				{
1177				  startTime[loopCount - (2+7*x)] = activeTime[loopCount];
1178				}
1179				else
1180				{
1181				  endTime[loopCount - (4+7*x)] = activeTime[loopCount];
1182					if ((loopCount - (4+7*x)) == 1&& atoi(endTime) == 0) {
1183						endTime[0] = '2';
1184						endTime[1] = '4';
1185						if (Date[1] == '0')
1186						Date[1] = '6';
1187						else
1188						Date[1]=Date[1]-1;
1189					}
1190				}
1191				loopCount++;
1192			}while(activeTime[loopCount] != '<' && loopCount < strlen(activeTime));
1193				loopCount++;
1194				/*Check which time will enable or disable wifi radio*/
1195				int offSet=0;
1196				if (Date[0] == Date[1])
1197				{
1198					z=0;
1199					for(;z<(atoi(endTime) - atoi(startTime));z++)
1200						schedTable[Date[0]-'0'][atoi(startTime)+z] = 1;
1201				}
1202				else
1203				{
1204									z=0;
1205									for(;z<((atoi(endTime) - atoi(startTime))+24*(Date[1] - Date[0]));z++)
1206									{
1207										schedTable[Date[0]-'0'+offSet][(atoi(startTime)+z)%24] = 1;
1208										if ((atoi(startTime)+z)%24 == 23)
1209										{
1210											offSet++;
1211										}
1212									}
1213								}
1214		}//end for loop (schedCount)
1215	}
1216
1217	if (tableAllOn == 0)
1218		active = 0;
1219	else if (tableAllOn == 1)
1220		active = 1;
1221	else
1222		active = in_sched(current, now_dow, schedTable);
1223
1224	//cprintf("[watchdoe] active: %d\n", active);
1225//}//60 sec
1226
1227	return active;
1228
1229}
1230
1231
1232int timecheck_reboot(char *activeSchedule)
1233{
1234	int active, current_time, current_date, Time2Active, Date2Active;
1235	time_t now;
1236	struct tm *tm;
1237	int i;
1238
1239	setenv("TZ", nvram_safe_get("time_zone_x"), 1);
1240
1241	time(&now);
1242	tm = localtime(&now);
1243	current_time = tm->tm_hour * 60 + tm->tm_min;
1244	current_date = 1 << (6-tm->tm_wday);
1245	active = 0;
1246	Time2Active = 0;
1247	Date2Active = 0;
1248
1249	Time2Active = ((activeSchedule[7]-'0')*10 + (activeSchedule[8]-'0'))*60 + ((activeSchedule[9]-'0')*10 + (activeSchedule[10]-'0'));
1250
1251	for(i=0;i<=6;i++) {
1252		Date2Active += (activeSchedule[i]-'0') << (6-i);
1253	}
1254
1255	if ((current_time == Time2Active) && (Date2Active & current_date))	active = 1;
1256
1257	//dbG("[watchdog] current_time=%d, ActiveTime=%d, current_date=%d, ActiveDate=%d, active=%d\n",
1258	//	current_time, Time2Active, current_date, Date2Active, active);
1259
1260	return active;
1261}
1262
1263
1264int svcStatus[12] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
1265
1266/* Check for time-reated service 	*/
1267/* 1. Wireless Radio			*/
1268/* 2. Guess SSID expire time 		*/
1269/* 3. Reboot Schedule			*/
1270//int timecheck(int argc, char *argv[])
1271void timecheck(void)
1272{
1273	int activeNow;
1274	char *schedTime;
1275	char prefix[]="wlXXXXXX_", tmp[100], tmp2[100];
1276	char word[256], *next;
1277	int unit, item;
1278	char *lan_ifname;
1279	char wl_vifs[256], nv[40];
1280	int expire, need_commit = 0;
1281
1282	item = 0;
1283	unit = 0;
1284
1285	if (nvram_match("reload_svc_radio", "1"))
1286	{
1287		nvram_set("reload_svc_radio", "0");
1288
1289		foreach (word, nvram_safe_get("wl_ifnames"), next) {
1290			svcStatus[item] = -1;
1291			item++;
1292			unit++;
1293		}
1294
1295		item = 0;
1296		unit = 0;
1297	}
1298
1299	// radio on/off
1300	if (nvram_match("svc_ready", "1"))
1301	foreach (word, nvram_safe_get("wl_ifnames"), next) {
1302		snprintf(prefix, sizeof(prefix), "wl%d_", unit);
1303
1304		//dbG("[watchdog] timecheck unit=%s radio=%s, timesched=%s\n", prefix, nvram_safe_get(strcat_r(prefix, "radio", tmp)), nvram_safe_get(strcat_r(prefix, "timesched", tmp2))); // radio toggle test
1305		if (nvram_match(strcat_r(prefix, "radio", tmp), "0") ||
1306			nvram_match(strcat_r(prefix, "timesched", tmp2), "0")) {
1307			item++;
1308			unit++;
1309			continue;
1310		}
1311
1312		/*transfer wl_sched NULL value to 000000 value, because
1313		of old version firmware with wrong default value*/
1314		if (!strcmp(nvram_safe_get(strcat_r(prefix, "sched", tmp)), ""))
1315		{
1316			nvram_set(strcat_r(prefix, "sched", tmp),"000000");
1317			//nvram_set("wl_sched", "000000");
1318		}
1319
1320		schedTime = nvram_safe_get(strcat_r(prefix, "sched", tmp));
1321
1322
1323		activeNow = timecheck_item(schedTime);
1324		snprintf(tmp, sizeof(tmp), "%d", unit);
1325
1326
1327		if (svcStatus[item] != activeNow) {
1328			svcStatus[item] = activeNow;
1329			if (activeNow == 1) eval("radio", "on", tmp);
1330			else eval("radio", "off", tmp);
1331		}
1332		item++;
1333		unit++;
1334
1335	}
1336
1337	// guest ssid expire check
1338	if ((nvram_get_int("sw_mode") != SW_MODE_REPEATER) &&
1339		(strlen(nvram_safe_get("wl0_vifs")) || strlen(nvram_safe_get("wl1_vifs")) ||
1340		 strlen(nvram_safe_get("wl2_vifs"))))
1341	{
1342		lan_ifname = nvram_safe_get("lan_ifname");
1343		sprintf(wl_vifs, "%s %s %s", nvram_safe_get("wl0_vifs"), nvram_safe_get("wl1_vifs"), nvram_safe_get("wl2_vifs"));
1344
1345		foreach (word, wl_vifs, next) {
1346			snprintf(nv, sizeof(nv) - 1, "%s_expire_tmp", wif_to_vif (word));
1347			expire = nvram_get_int(nv);
1348
1349			if (expire)
1350			{
1351				if (expire <= 30)
1352				{
1353					nvram_set(nv, "0");
1354					snprintf(nv, sizeof(nv) - 1, "%s_bss_enabled", wif_to_vif (word));
1355					nvram_set(nv, "0");
1356					if (!need_commit) need_commit = 1;
1357#ifdef CONFIG_BCMWL5
1358					eval("wl", "-i", word, "closed", "1");
1359					eval("wl", "-i", word, "bss_maxassoc", "1");
1360					eval("wl", "-i", word, "bss", "down");
1361#endif
1362					ifconfig(word, 0, NULL, NULL);
1363					eval("brctl", "delif", lan_ifname, word);
1364				}
1365				else
1366				{
1367					expire -= 30;
1368					sprintf(tmp, "%d", expire);
1369					nvram_set(nv, tmp);
1370				}
1371			}
1372		}
1373
1374		if (need_commit)
1375		{
1376			need_commit = 0;
1377			nvram_commit();
1378		}
1379	}
1380
1381	#ifdef RTCONFIG_REBOOT_SCHEDULE
1382	/* Reboot Schedule */
1383	char* reboot_schedule;
1384	if (nvram_match("ntp_ready", "1") && nvram_match("reboot_schedule_enable", "1"))
1385	{
1386		//SMTWTFSHHMM
1387		//XXXXXXXXXXX
1388		reboot_schedule = nvram_safe_get("reboot_schedule");
1389		if (strlen(reboot_schedule) == 11 && atoi(reboot_schedule) > 2359)
1390		{
1391			if (timecheck_reboot(reboot_schedule))
1392			{
1393				_dprintf("reboot plan alert...\n");
1394				sleep(1);
1395				eval("reboot");
1396			}
1397		}
1398	}
1399	#endif
1400
1401	return;
1402}
1403
1404#if 0
1405int high_cpu_usage_count = 0;
1406
1407void
1408cpu_usage_monitor()
1409{
1410	cpu_timer = (cpu_timer + 1) % 2;
1411	if (cpu_timer) return;
1412
1413	unsigned int usage = cpu_main(0, NULL, 0);
1414
1415	if (usage >= 95)
1416		high_cpu_usage_count++;
1417	else
1418		high_cpu_usage_count = 0;
1419
1420	if (high_cpu_usage_count >= 5)
1421		sys_exit();
1422}
1423#endif
1424
1425#ifdef RTCONFIG_RALINK
1426int need_restart_wsc = 0;
1427#endif
1428static void catch_sig(int sig)
1429{
1430	if (sig == SIGUSR1)
1431	{
1432		dbG("[watchdog] Handle WPS LED for WPS Start\n");
1433
1434		alarmtimer(NORMAL_PERIOD, 0);
1435
1436		btn_pressed_setup = BTNSETUP_START;
1437		btn_count_setup = 0;
1438		btn_count_setup_second = 0;
1439		wsc_timeout = WPS_TIMEOUT_COUNT;
1440		alarmtimer(0, RUSHURGENT_PERIOD);
1441
1442#if (defined(PLN12) || defined(PLAC56))
1443		set_wifiled(3);
1444#endif
1445	}
1446	else if (sig == SIGUSR2)
1447	{
1448		if (nvram_match("wps_ign_btn", "1")) return;
1449
1450		dbG("[watchdog] Handle WPS LED for WPS Stop\n");
1451
1452		btn_pressed_setup = BTNSETUP_NONE;
1453		btn_count_setup = 0;
1454		btn_count_setup_second = 0;
1455		wsc_timeout = 1;
1456		alarmtimer(NORMAL_PERIOD, 0);
1457
1458#if (defined(PLN12) || defined(PLAC56))
1459		set_wifiled(1);
1460#else
1461		led_control_normal();
1462#endif
1463	}
1464	else if (sig == SIGTSTP)
1465	{
1466		dbG("[watchdog] Reset WPS timeout count\n");
1467
1468		wsc_timeout = WPS_TIMEOUT_COUNT;
1469	}
1470#ifdef RTCONFIG_RALINK
1471	else if (sig == SIGTTIN)
1472	{
1473		wsc_user_commit();
1474		need_restart_wsc = 1;
1475	}
1476#if 0
1477	else if (sig == SIGHUP)
1478	{
1479		switch (get_model()) {
1480		case MODEL_RTN56U:
1481#ifdef RTCONFIG_DSL
1482		case MODEL_DSLN55U:
1483#endif
1484			restart_wireless();
1485			break;
1486		}
1487	}
1488#endif
1489#endif
1490}
1491
1492/* simple traffic-led hints */
1493unsigned long get_devirq_count(char *irqs)
1494{
1495	FILE *f;
1496	char buf[256];
1497	char *irqname, *p;
1498	unsigned long counter1, counter2;
1499
1500	if ((f = fopen("/proc/interrupts", "r")) == NULL) return -1;
1501
1502	fgets(buf, sizeof(buf), f);
1503
1504	counter1=counter2=0;
1505
1506	while (fgets(buf, sizeof(buf), f)) {
1507		if ((p=strchr(buf, ':')) == NULL) continue;
1508		*p = 0;
1509		if ((irqname = strrchr(buf, ' ')) == NULL) irqname = buf;
1510		else ++irqname;
1511
1512		if (strcmp(irqname, irqs)) continue;
1513
1514#ifdef RTCONFIG_BCMSMP
1515		if (sscanf(p+1, "%lu%lu", &counter1, &counter2) != 2) continue;
1516#else
1517		if (sscanf(p+1, "%lu", &counter1) != 1) continue;
1518#endif
1519
1520	}
1521	fclose(f);
1522
1523	return counter1+counter2 > 2 ? counter1+counter2 : 0;
1524}
1525
1526#if !defined(RTCONFIG_BLINK_LED)
1527void fake_dev_led(char *irqs, unsigned int LED_WHICH)
1528{
1529	static unsigned int blink_dev_check = 0;
1530	static unsigned int blink_dev = 0;
1531	static unsigned int data_dev = 0;
1532	unsigned long count_dev;
1533	int i;
1534	static int j;
1535	static int status = -1;
1536	static int status_old;
1537
1538	if (!*irqs || !LED_WHICH)
1539		return;
1540
1541	// check data per 10 count
1542	if ((blink_dev_check%10) == 0) {
1543		count_dev = get_devirq_count(irqs);
1544		if (count_dev && data_dev != count_dev) {
1545			blink_dev = 1;
1546			data_dev = count_dev;
1547		}
1548		else blink_dev = 0;
1549		led_control(LED_WHICH, LED_ON);
1550	}
1551
1552	if (blink_dev) {
1553		j = rand_seed_by_time() % 3;
1554		for(i=0;i<10;i++) {
1555			usleep(33*1000);
1556
1557			status_old = status;
1558			if (((i%2) == 0) && (i > (3 + 2*j)))
1559				status = 0;
1560			else
1561				status = 1;
1562
1563			if (status != status_old)
1564			{
1565				if (status)
1566					led_control(LED_WHICH, LED_ON);
1567				else
1568					led_control(LED_WHICH, LED_OFF);
1569			}
1570		}
1571		led_control(LED_WHICH, LED_ON);
1572	}
1573
1574	blink_dev_check++;
1575}
1576#endif
1577
1578#if defined(RTCONFIG_FAKE_ETLAN_LED)
1579unsigned long get_etlan_count()
1580{
1581	FILE *f;
1582	char buf[256];
1583	char *ifname, *p;
1584	unsigned long counter1, counter2;
1585
1586	if ((f = fopen("/proc/net/dev", "r")) == NULL) return -1;
1587
1588	fgets(buf, sizeof(buf), f);
1589	fgets(buf, sizeof(buf), f);
1590
1591	counter1=counter2=0;
1592
1593	while (fgets(buf, sizeof(buf), f)) {
1594		if ((p=strchr(buf, ':')) == NULL) continue;
1595		*p = 0;
1596		if ((ifname = strrchr(buf, ' ')) == NULL) ifname = buf;
1597		else ++ifname;
1598
1599		if (strcmp(ifname, "vlan1")) continue;
1600
1601		if (sscanf(p+1, "%lu%*u%*u%*u%*u%*u%*u%*u%*u%lu", &counter1, &counter2) != 2) continue;
1602
1603	}
1604	fclose(f);
1605
1606	return counter1;
1607}
1608
1609static int lstatus = 0;
1610static int allstatus = 0;
1611void fake_etlan_led(void)
1612{
1613	static unsigned int blink_etlan_check = 0;
1614	static unsigned int blink_etlan = 0;
1615	static unsigned int data_etlan = 0;
1616	unsigned long count_etlan;
1617	int i;
1618	static int j;
1619	static int status = -1;
1620	static int status_old;
1621
1622	if (nvram_match("AllLED", "0")) {
1623		if (allstatus)
1624			led_control(LED_LAN, LED_OFF);
1625		allstatus = 0;
1626		return;
1627	}
1628	allstatus = 1;
1629
1630	if (!GetPhyStatus(0)) {
1631		if (lstatus)
1632			led_control(LED_LAN, LED_OFF);
1633		lstatus = 0;
1634		return;
1635	}
1636	lstatus = 1;
1637
1638	// check data per 10 count
1639	if ((blink_etlan_check%10) == 0) {
1640		count_etlan = get_etlan_count();
1641		if (count_etlan && data_etlan != count_etlan) {
1642			blink_etlan = 1;
1643			data_etlan = count_etlan;
1644		}
1645		else blink_etlan = 0;
1646		led_control(LED_LAN, LED_ON);
1647	}
1648
1649	if (blink_etlan) {
1650		j = rand_seed_by_time() % 3;
1651		for(i=0;i<10;i++) {
1652			usleep(33*1000);
1653
1654			status_old = status;
1655			if (((i%2) == 0) && (i > (3 + 2*j)))
1656				status = 0;
1657			else
1658				status = 1;
1659
1660			if (status != status_old)
1661			{
1662				if (status)
1663					led_control(LED_LAN, LED_ON);
1664				else
1665					led_control(LED_LAN, LED_OFF);
1666			}
1667		}
1668		led_control(LED_LAN, LED_ON);
1669	}
1670
1671	blink_etlan_check++;
1672}
1673#endif
1674
1675#if defined(RTCONFIG_WLAN_LED) || defined(RTN18U)
1676unsigned long get_2g_count()
1677{
1678	FILE *f;
1679	char buf[256];
1680	char *ifname, *p;
1681	unsigned long counter1, counter2;
1682
1683	if ((f = fopen("/proc/net/dev", "r")) == NULL) return -1;
1684
1685	fgets(buf, sizeof(buf), f);
1686	fgets(buf, sizeof(buf), f);
1687
1688	counter1=counter2=0;
1689
1690	while (fgets(buf, sizeof(buf), f)) {
1691		if ((p=strchr(buf, ':')) == NULL) continue;
1692		*p = 0;
1693		if ((ifname = strrchr(buf, ' ')) == NULL) ifname = buf;
1694		else ++ifname;
1695
1696		if (strcmp(ifname, "eth1")) continue;
1697
1698		if (sscanf(p+1, "%lu%*u%*u%*u%*u%*u%*u%*u%*u%lu", &counter1, &counter2) != 2) continue;
1699
1700	}
1701	fclose(f);
1702
1703	return counter1;
1704}
1705
1706void fake_wl_led_2g(void)
1707{
1708	static unsigned int blink_2g_check = 0;
1709	static unsigned int blink_2g = 0;
1710	static unsigned int data_2g = 0;
1711	unsigned long count_2g;
1712	int i;
1713	static int j;
1714	static int status = -1;
1715	static int status_old;
1716
1717	// check data per 10 count
1718	if ((blink_2g_check%10) == 0) {
1719		count_2g = get_2g_count();
1720		if (count_2g && data_2g != count_2g) {
1721			blink_2g = 1;
1722			data_2g = count_2g;
1723		}
1724		else blink_2g = 0;
1725		led_control(LED_2G, LED_ON);
1726	}
1727
1728	if (blink_2g) {
1729		j = rand_seed_by_time() % 3;
1730		for(i=0;i<10;i++) {
1731			usleep(33*1000);
1732
1733			status_old = status;
1734			if (((i%2) == 0) && (i > (3 + 2*j)))
1735				status = 0;
1736			else
1737				status = 1;
1738
1739			if (status != status_old)
1740			{
1741				if (status)
1742					led_control(LED_2G, LED_ON);
1743				else
1744					led_control(LED_2G, LED_OFF);
1745			}
1746		}
1747		led_control(LED_2G, LED_ON);
1748	}
1749
1750	blink_2g_check++;
1751}
1752#endif	/* RTCONFIG_WLAN_LED */
1753
1754#if defined(RTCONFIG_BRCM_USBAP) || defined(RTAC66U) || defined(BCM4352)
1755unsigned long get_5g_count()
1756{
1757	FILE *f;
1758	char buf[256];
1759	char *ifname, *p;
1760	unsigned long counter1, counter2;
1761
1762	if ((f = fopen("/proc/net/dev", "r")) == NULL) return -1;
1763
1764	fgets(buf, sizeof(buf), f);
1765	fgets(buf, sizeof(buf), f);
1766
1767	counter1=counter2=0;
1768
1769	while (fgets(buf, sizeof(buf), f)) {
1770		if ((p=strchr(buf, ':')) == NULL) continue;
1771		*p = 0;
1772		if ((ifname = strrchr(buf, ' ')) == NULL) ifname = buf;
1773		else ++ifname;
1774
1775		if (strcmp(ifname, "eth2")) continue;
1776
1777		if (sscanf(p+1, "%lu%*u%*u%*u%*u%*u%*u%*u%*u%lu", &counter1, &counter2) != 2) continue;
1778
1779	}
1780	fclose(f);
1781
1782	return counter1;
1783}
1784
1785void fake_wl_led_5g(void)
1786{
1787	static unsigned int blink_5g_check = 0;
1788	static unsigned int blink_5g = 0;
1789	static unsigned int data_5g = 0;
1790	unsigned long count_5g;
1791	int i;
1792	static int j;
1793	static int status = -1;
1794	static int status_old;
1795
1796	// check data per 10 count
1797	if ((blink_5g_check%10) == 0) {
1798		count_5g = get_5g_count();
1799		if (count_5g && data_5g != count_5g) {
1800			blink_5g = 1;
1801			data_5g = count_5g;
1802		}
1803		else blink_5g = 0;
1804		led_control(LED_5G, LED_ON);
1805	}
1806
1807	if (blink_5g) {
1808#if defined(RTAC66U) || defined(BCM4352)
1809		j = rand_seed_by_time() % 3;
1810#endif
1811		for(i=0;i<10;i++) {
1812#if defined(RTAC66U) || defined(BCM4352)
1813			usleep(33*1000);
1814
1815			status_old = status;
1816			if (((i%2) == 0) && (i > (3 + 2*j)))
1817				status = 0;
1818			else
1819				status = 1;
1820
1821			if (status != status_old)
1822			{
1823				if (status)
1824					led_control(LED_5G, LED_ON);
1825				else
1826					led_control(LED_5G, LED_OFF);
1827			}
1828#else
1829			usleep(50*1000);
1830			if (i%2 == 0) {
1831				led_control(LED_5G, LED_OFF);
1832			}
1833			else {
1834				led_control(LED_5G, LED_ON);
1835			}
1836#endif
1837		}
1838		led_control(LED_5G, LED_ON);
1839	}
1840
1841	blink_5g_check++;
1842}
1843#endif
1844
1845static int led_confirmed = 0;
1846extern int led_gpio_table[LED_ID_MAX];
1847
1848int confirm_led()
1849{
1850	if (
1851		1
1852#if defined(RTN53) || defined(RTN18U)
1853		&& led_gpio_table[LED_2G] != 0xff
1854		&& led_gpio_table[LED_2G] != -1
1855#endif
1856#if defined(RTCONFIG_FAKE_ETLAN_LED)
1857		&& led_gpio_table[LED_LAN] != 0xff
1858		&& led_gpio_table[LED_LAN] != -1
1859#endif
1860#if defined(RTCONFIG_USB) && !defined(RTCONFIG_BLINK_LED)
1861#ifdef RTCONFIG_USB_XHCI
1862		&& led_gpio_table[LED_USB3] != 0xff
1863		&& led_gpio_table[LED_USB3] != -1
1864#endif
1865		&& led_gpio_table[LED_USB] != 0xff
1866		&& led_gpio_table[LED_USB] != -1
1867#endif
1868#ifdef RTCONFIG_MMC_LED
1869		&& led_gpio_table[LED_MMC] != 0xff
1870		&& led_gpio_table[LED_MMC] != -1
1871#endif
1872#if defined(RTCONFIG_BRCM_USBAP) || defined(RTAC66U) || defined(BCM4352)
1873		&& led_gpio_table[LED_5G] != 0xff
1874		&& led_gpio_table[LED_5G] != -1
1875#endif
1876#ifdef RTCONFIG_DSL
1877#ifndef RTCONFIG_DUALWAN
1878		&& led_gpio_table[LED_WAN] != 0xff
1879		&& led_gpio_table[LED_WAN] != -1
1880#endif
1881#endif
1882	)
1883		led_confirmed = 1;
1884	else
1885		led_confirmed = 0;
1886
1887	return led_confirmed;
1888}
1889
1890static int swled_alloff_x = 0;
1891static int swled_alloff_counts = 0;
1892
1893void led_check(int sig)
1894{
1895	int all_led;
1896	int turnoff_counts = swled_alloff_counts?:3;
1897
1898	if ((all_led=nvram_get_int("AllLED")) == 0 && swled_alloff_x < turnoff_counts) {
1899		/* turn off again x times in case timing issues */
1900		led_table_ctrl(LED_OFF);
1901		swled_alloff_x++;
1902		_dprintf("force turnoff led table again!\n");
1903		return;
1904	}
1905
1906	if (all_led)
1907		swled_alloff_x = 0;
1908	else
1909		return;
1910
1911	if (!confirm_led()) {
1912		get_gpio_values_once(1);
1913	}
1914
1915#ifdef RTCONFIG_WLAN_LED
1916	if (nvram_contains_word("rc_support", "led_2g"))
1917	{
1918#if defined(RTN53)
1919		if (nvram_get_int("wl0_radio") == 0)
1920			led_control(LED_2G, LED_OFF);
1921		else
1922#endif
1923		fake_wl_led_2g();
1924	}
1925#endif
1926
1927#if defined(RTN18U)
1928	if (nvram_match("bl_version", "1.0.0.0"))
1929		fake_wl_led_2g();
1930#endif
1931
1932#if defined(RTCONFIG_FAKE_ETLAN_LED)
1933	fake_etlan_led();
1934#endif
1935
1936#if defined(RTCONFIG_USB) && !defined(RTCONFIG_BLINK_LED)
1937	char *p1_node, *p2_node, *ehci_ports, *xhci_ports;
1938
1939	/* led indicates which usb port */
1940	switch (get_model()) {
1941		case MODEL_RTAC5300:
1942		case MODEL_RTAC5300R:
1943		case MODEL_RTAC88U:
1944		case MODEL_RTAC3100:
1945		default:
1946			p1_node = nvram_safe_get("usb_path1_node");	// xhci node
1947			p2_node = nvram_safe_get("usb_path2_node");	// ehci node
1948			break;
1949	}
1950
1951	ehci_ports = nvram_safe_get("ehci_ports");
1952	xhci_ports = nvram_safe_get("xhci_ports");
1953
1954#ifdef RTCONFIG_USB_XHCI
1955	if (*p1_node) {
1956		if (strstr(xhci_ports, p1_node))
1957			fake_dev_led(nvram_safe_get("xhci_irq"), LED_USB3);
1958		else if (strstr(ehci_ports, p1_node))
1959			fake_dev_led(nvram_safe_get("ehci_irq"), LED_USB3);
1960	}
1961#endif
1962	if (*p2_node)
1963		fake_dev_led(nvram_safe_get("ehci_irq"), LED_USB);
1964#endif
1965
1966#ifdef RTCONFIG_MMC_LED
1967	if (*nvram_safe_get("usb_path3"))
1968		fake_dev_led(nvram_safe_get("mmc_irq"), LED_MMC);
1969#endif
1970
1971#if defined(RTCONFIG_BRCM_USBAP) || defined(RTAC66U) || defined(BCM4352)
1972#if defined(RTAC66U) || defined(BCM4352)
1973	if (nvram_match("led_5g", "1") &&
1974	   (wlonunit == -1 || wlonunit == 1))
1975#endif
1976	{
1977#if defined(RTN53)
1978		if (nvram_get_int("wl1_radio") == 0)
1979			led_control(LED_5G, LED_OFF);
1980		else
1981#endif
1982		fake_wl_led_5g();
1983	}
1984#endif
1985
1986// it is not really necessary, but if required, add internet led check here
1987// using wan_primary_ifunit() to get current working wan unit wan0 or wan1
1988// using wan0_state_t or wan1_state_t to get status of working wan,
1989//	WAN_STATE_CONNECTED means internet connected
1990//	else means internet disconnted
1991
1992/* Paul add 2012/10/25 */
1993#ifdef RTCONFIG_DSL
1994#ifndef RTCONFIG_DUALWAN
1995if (nvram_match("dsltmp_adslsyncsts","up") && nvram_match("wan0_state_t","2"))
1996	led_DSLWAN();
1997#endif
1998#endif
1999}
2000
2001void led_table_ctrl(int on_off)
2002{
2003	int i;
2004
2005	for(i=0; i < LED_ID_MAX; ++i) {
2006		if (led_gpio_table[i] != 0xff && led_gpio_table[i] != -1) {
2007			led_control(i, on_off);
2008		}
2009	}
2010}
2011
2012/* Paul add 2012/10/25 */
2013#ifdef RTCONFIG_DSL
2014#ifndef RTCONFIG_DUALWAN
2015unsigned long get_dslwan_count()
2016{
2017	FILE *f;
2018	char buf[256];
2019	char *ifname, *p;
2020	unsigned long counter1, counter2;
2021
2022	if ((f = fopen("/proc/net/dev", "r")) == NULL) return -1;
2023
2024	fgets(buf, sizeof(buf), f);
2025	fgets(buf, sizeof(buf), f);
2026
2027	counter1=counter2=0;
2028
2029	while (fgets(buf, sizeof(buf), f)) {
2030		if ((p=strchr(buf, ':')) == NULL) continue;
2031		*p = 0;
2032		if ((ifname = strrchr(buf, ' ')) == NULL) ifname = buf;
2033		else ++ifname;
2034
2035		if (nvram_match("dsl0_proto","pppoe") || nvram_match("dsl0_proto","pppoa"))
2036		{
2037			if (strcmp(ifname, "ppp0")) continue;
2038		}
2039		else //Mer, IPoA
2040		{
2041			if (strcmp(ifname, "eth2.1.1")) continue;
2042		}
2043
2044		if (sscanf(p+1, "%lu%*u%*u%*u%*u%*u%*u%*u%*u%lu", &counter1, &counter2) != 2) continue;
2045	}
2046	fclose(f);
2047
2048	return counter1;
2049}
2050
2051void led_DSLWAN(void)
2052{
2053	static unsigned int blink_dslwan_check = 0;
2054	static unsigned int blink_dslwan = 0;
2055	static unsigned int data_dslwan = 0;
2056	unsigned long count_dslwan;
2057	int i;
2058	static int j;
2059	static int status = -1;
2060	static int status_old;
2061
2062	// check data per 10 count
2063	if ((blink_dslwan_check%10) == 0) {
2064		count_dslwan = get_dslwan_count();
2065		if (count_dslwan && data_dslwan != count_dslwan) {
2066			blink_dslwan = 1;
2067			data_dslwan = count_dslwan;
2068}
2069		else blink_dslwan = 0;
2070		led_control(LED_WAN, LED_ON);
2071	}
2072
2073	if (blink_dslwan) {
2074		j = rand_seed_by_time() % 3;
2075		for(i=0;i<10;i++) {
2076			usleep(33*1000);
2077
2078			status_old = status;
2079			if (((i%2) == 0) && (i > (3 + 2*j)))
2080				status = 0;
2081			else
2082				status = 1;
2083
2084			if (status != status_old)
2085			{
2086				if (status)
2087					led_control(LED_WAN, LED_ON);
2088				else
2089					led_control(LED_WAN, LED_OFF);
2090			}
2091		}
2092		led_control(LED_WAN, LED_ON);
2093	}
2094
2095	blink_dslwan_check++;
2096}
2097#endif
2098#endif
2099
2100#ifdef RTCONFIG_SWMODE_SWITCH
2101// copied from 2.x code
2102int pre_sw_mode=0, sw_mode=0;
2103int flag_sw_mode=0;
2104int tmp_sw_mode=0;
2105int count_stable=0;
2106
2107void swmode_check()
2108{
2109#if defined(PLAC66U)
2110	int pre_sw_mode=nvram_get_int("sw_mode");
2111
2112	if (!button_pressed(BTN_SWMODE_SW_ROUTER))
2113		sw_mode = SW_MODE_ROUTER;
2114	else    sw_mode = SW_MODE_AP;
2115
2116	if ((sw_mode != pre_sw_mode) && !flag_sw_mode) {
2117		if( sw_mode == SW_MODE_ROUTER )
2118			_dprintf("[%s], switch to ROUTER Mode!\n", __FUNCTION__);
2119		else
2120			_dprintf("[%s], switch to AP Mode!\n", __FUNCTION__);
2121
2122		flag_sw_mode=1;
2123		count_stable=0;
2124	}
2125	else if (flag_sw_mode == 1 && nvram_invmatch("asus_mfg", "1")) {
2126		if (sw_mode != pre_sw_mode) {
2127			if (++count_stable>4) { // stable for more than 5 second
2128				fprintf(stderr, "Reboot to switch sw mode ..\n");
2129				flag_sw_mode=0;
2130				/* sw mode changed: restore defaults */
2131				led_control(LED_POWER, LED_OFF);
2132				alarmtimer(0, 0);
2133				nvram_set("restore_defaults", "1");
2134				if (notify_rc_after_wait("resetdefault")) {     /* Send resetdefault rc_service failed. */
2135					alarmtimer(NORMAL_PERIOD, 0);
2136				}
2137			}
2138		}
2139		else flag_sw_mode = 0;
2140	}
2141#else
2142	if (!nvram_get_int("swmode_switch")) return;
2143	pre_sw_mode = sw_mode;
2144
2145	if (button_pressed(BTN_SWMODE_SW_REPEATER))
2146		sw_mode=SW_MODE_REPEATER;
2147	else if (button_pressed(BTN_SWMODE_SW_AP))
2148		sw_mode=SW_MODE_AP;
2149	else sw_mode=SW_MODE_ROUTER;
2150
2151	if (sw_mode != pre_sw_mode) {
2152		if (nvram_get_int("sw_mode") != sw_mode) {
2153			flag_sw_mode=1;
2154			count_stable=0;
2155			tmp_sw_mode=sw_mode;
2156		}
2157		else flag_sw_mode=0;
2158	}
2159	else if (flag_sw_mode == 1 && nvram_invmatch("asus_mfg", "1")) {
2160		if (tmp_sw_mode == sw_mode) {
2161			if (++count_stable>4) // stable for more than 5 second
2162			{
2163				fprintf(stderr, "Reboot to switch sw mode ..\n");
2164				flag_sw_mode=0;
2165				sync();
2166				/* sw mode changed: restore defaults */
2167				nvram_set("nvramver", "0");
2168				nvram_commit();
2169				reboot(RB_AUTOBOOT);
2170			}
2171		}
2172		else flag_sw_mode = 0;
2173	}
2174#endif	/* Model */
2175}
2176#endif	/* RTCONFIG_SWMODE_SWITCH */
2177#ifdef WEB_REDIRECT
2178void wanduck_check(void)
2179{
2180	if ((freeze_duck_count = nvram_get_int("freeze_duck")) > 0)
2181		nvram_set_int("freeze_duck", --freeze_duck_count);
2182}
2183#endif
2184
2185#if (defined(PLN12) || defined(PLAC56) || defined(PLAC66U))
2186static int client_check_cnt = 0;
2187static int no_client_cnt = 0;
2188static int plc_wake = 1;
2189
2190static void client_check(void)
2191{
2192	#define WIFI_STA_LIST_PATH "/tmp/wifi_sta_list"
2193	FILE *fp;
2194	char word[256], *next, ifnames[128];
2195	char buf[512];
2196	int i, n = 0;
2197
2198	if (!nvram_match("plc_ready", "1"))
2199		return;
2200
2201	/* every 2 seconds check */
2202	if (client_check_cnt++ > 0) {
2203		client_check_cnt = 0;
2204		return;
2205	}
2206	//dbg("%s:\n", __func__);
2207
2208	/* check wireless client */
2209	i = 0;
2210	strcpy(ifnames, nvram_safe_get("wl_ifnames"));
2211	foreach(word, ifnames, next) {
2212		doSystem("wlanconfig %s list > %s", get_wifname(i), WIFI_STA_LIST_PATH);
2213
2214		fp = fopen(WIFI_STA_LIST_PATH, "r");
2215		if (!fp) {
2216			dbg("%s: fopen fail\n", __func__);
2217			return;
2218		}
2219		while (fgets(buf, 512, fp) != NULL)
2220			n++;
2221		fclose(fp);
2222		unlink(WIFI_STA_LIST_PATH);
2223
2224		++i;
2225	}
2226
2227	/* check wire port */
2228	if (get_lanports_status())
2229		n++;
2230
2231	if (n == 0)
2232		no_client_cnt++;
2233	else
2234		no_client_cnt = 0;
2235
2236	if (plc_wake == 1 && no_client_cnt >= 5) {
2237		//dbg("%s: trigger Powerline to sleep...\n", __func__);
2238#if defined(PLN12)
2239		doSystem("swconfig dev %s port 1 set power 0", MII_IFNAME);
2240#elif defined(PLAC56)
2241		set_gpio((nvram_get_int("plc_wake_gpio") & 0xff), 1);
2242#else
2243#warning TBD: PL-AC66U...
2244#endif
2245		plc_wake = 0;
2246	}
2247	else if (plc_wake == 0 && no_client_cnt == 0) {
2248		//dbg("%s: trigger Powerline to wake...\n", __func__);
2249#if defined(PLN12)
2250		doSystem("swconfig dev %s port 1 set power 1", MII_IFNAME);
2251#elif defined(PLAC56)
2252		set_gpio((nvram_get_int("plc_wake_gpio") & 0xff), 0);
2253#else
2254#warning TBD: PL-AC66U...
2255#endif
2256		plc_wake = 1;
2257	}
2258
2259	if (no_client_cnt >= 5)
2260		no_client_cnt = 0;
2261}
2262#endif
2263
2264void regular_ddns_check(void)
2265{
2266	struct in_addr ip_addr;
2267	struct hostent *hostinfo;
2268
2269	//_dprintf("regular_ddns_check...\n");
2270
2271	hostinfo = gethostbyname(nvram_get("ddns_hostname_x"));
2272	ddns_check_count = 0;
2273
2274	if (hostinfo) {
2275		ip_addr.s_addr = *(unsigned long *)hostinfo -> h_addr_list[0];
2276		//_dprintf("  %s ?= %s\n", nvram_get("wan0_ipaddr"), inet_ntoa(ip_addr));
2277		if (strcmp(nvram_get("wan0_ipaddr"), inet_ntoa(ip_addr))) {
2278			//_dprintf("WAN IP change!\n");
2279			nvram_set("ddns_update_by_wdog", "1");
2280			//unlink("/tmp/ddns.cache");
2281			logmessage("watchdog", "Hostname/IP mapping error! Restart ddns.");
2282			notify_rc("start_ddns");
2283		}
2284	}
2285	return;
2286}
2287
2288void ddns_check(void)
2289{
2290	//_dprintf("ddns_check... %d\n", ddns_check_count);
2291	if (nvram_match("ddns_enable_x", "1") && is_wan_connect(0))
2292	{
2293		if (pids("ez-ipupdate")) //ez-ipupdate is running!
2294			return;
2295		if (pids("phddns")) //ez-ipupdate is running!
2296			return;
2297
2298		if (nvram_match("ddns_regular_check", "1")&& !nvram_match("ddns_server_x", "WWW.ASUS.COM")) {
2299			int period = nvram_get_int("ddns_regular_period");
2300			if (period < 30) period = 60;
2301			if (ddns_check_count >= (period*2)) {
2302				regular_ddns_check();
2303				ddns_check_count = 0;
2304			return;
2305			}
2306			ddns_check_count++;
2307		}
2308
2309		if ( nvram_match("ddns_updated", "1") ) //already updated success
2310			return;
2311
2312		if ( nvram_match("ddns_server_x", "WWW.ASUS.COM") ) {
2313			if ( !(  !strcmp(nvram_safe_get("ddns_return_code_chk"),"Time-out") ||
2314				!strcmp(nvram_safe_get("ddns_return_code_chk"),"connect_fail") ||
2315				strstr(nvram_safe_get("ddns_return_code_chk"), "-1") ) )
2316				return;
2317		}
2318		else{ //non asusddns service
2319			if ( !strcmp(nvram_safe_get("ddns_return_code_chk"),"auth_fail") )
2320				return;
2321		}
2322		if (internet_ready() == 1) {
2323			nvram_set("ddns_update_by_wdog", "1");
2324			//unlink("/tmp/ddns.cache");
2325			logmessage("watchdog", "start ddns.");
2326			notify_rc("start_ddns");
2327		}
2328	}
2329
2330	return;
2331}
2332
2333void networkmap_check()
2334{
2335	if (!pids("networkmap"))
2336		start_networkmap(0);
2337}
2338
2339void httpd_check()
2340{
2341#ifdef RTCONFIG_HTTPS
2342	int enable = nvram_get_int("http_enable");
2343	if ((enable != 1 && !pids("httpd")) ||
2344	    (enable != 0 && !pids("httpds")))
2345#else
2346	if (!pids("httpd"))
2347#endif
2348	{
2349		logmessage("watchdog", "restart httpd");
2350		stop_httpd();
2351		nvram_set("last_httpd_handle_request", nvram_safe_get("httpd_handle_request"));
2352		nvram_set("last_httpd_handle_request_fromapp", nvram_safe_get("httpd_handle_request_fromapp"));
2353		nvram_commit();
2354		start_httpd();
2355	}
2356}
2357
2358void dnsmasq_check()
2359{
2360	if (!pids("dnsmasq")) {
2361		if (nvram_get_int("asus_mfg") == 1)
2362			return;
2363
2364	if (!is_routing_enabled()
2365#ifdef RTCONFIG_WIRELESSREPEATER
2366		&& nvram_get_int("sw_mode") != SW_MODE_REPEATER
2367#endif
2368	)
2369		return;
2370
2371		start_dnsmasq();
2372		TRACE_PT("watchdog: dnsmasq died. start dnsmasq...\n");
2373	}
2374}
2375#if ! (defined(RTCONFIG_QCA) || defined(RTCONFIG_RALINK))
2376void watchdog_check()
2377{
2378#if defined(RTCONFIG_RALINK) || defined(RTCONFIG_QCA) || defined(RTCONFIG_BCM_7114)
2379	/* Do nothing. */
2380#else
2381	if (!pids("watchdog")) {
2382		if (nvram_get_int("upgrade_fw_status") == FW_INIT) {
2383			logmessage("watchdog02", "no wathdog, restarting");
2384			kill(1, SIGTERM);
2385		}
2386	}
2387	return;
2388#endif
2389}
2390#endif  /* ! (RTCONFIG_QCA || RTCONFIG_RALINK) */
2391
2392#ifdef RTAC87U
2393void qtn_module_check(void)
2394{
2395	int ret;
2396	static int waiting = 0;
2397	static int failed = 0;
2398	const char *src_ip = nvram_safe_get("QTN_RPC_CLIENT");
2399	const char *dst_ip = nvram_safe_get("QTN_RPC_SERVER");
2400
2401	if (nvram_get_int("ATEMODE") == 1)
2402		return;
2403
2404	if(waiting < 2){
2405		waiting++;
2406		return;
2407	}
2408
2409	if (!nvram_get_int("qtn_ready"))
2410		return;
2411
2412	if (nvram_get_int("qtn_diagnostics") == 1)
2413		return;
2414
2415	if(icmp_check(src_ip, dst_ip) == 0 ){
2416		failed++;
2417		if(failed > 2){
2418			logmessage("QTN", "QTN connection lost[%s][%s]", src_ip, dst_ip);
2419			system("reboot &");
2420		}
2421	}
2422	waiting = 0;
2423
2424	return;
2425}
2426
2427#endif
2428
2429//#if defined(RTCONFIG_JFFS2LOG) && defined(RTCONFIG_JFFS2)
2430#if defined(RTCONFIG_JFFS2LOG) && (defined(RTCONFIG_JFFS2)||defined(RTCONFIG_BRCM_NAND_JFFS2))
2431void syslog_commit_check(void)
2432{
2433	struct stat tmp_log_stat, jffs_log_stat;
2434	int tmp_stat, jffs_stat;
2435
2436	tmp_stat = stat("/tmp/syslog.log", &tmp_log_stat);
2437	if (tmp_stat == -1)
2438		return;
2439
2440	if (++log_commit_count >= LOG_COMMIT_PERIOD) {
2441		jffs_stat = stat("/jffs/syslog.log", &jffs_log_stat);
2442		if ( jffs_stat == -1) {
2443			eval("cp", "/tmp/syslog.log", "/tmp/syslog.log-1", "/jffs");
2444			return;
2445		}
2446
2447		if ( tmp_log_stat.st_size > jffs_log_stat.st_size ||
2448		     difftime(tmp_log_stat.st_mtime, jffs_log_stat.st_mtime) > 0)
2449			eval("cp", "/tmp/syslog.log", "/tmp/syslog.log-1", "/jffs");
2450
2451		log_commit_count = 0;
2452	}
2453	return;
2454}
2455#endif
2456
2457#if defined(RTCONFIG_USB_MODEM)
2458void modem_log_check(void) {
2459#define MODEMLOG_FILE "/tmp/usb.log"
2460#define MAX_MODEMLOG_LINE 3
2461	FILE *fp;
2462	char cmd[64], var[16];
2463	int line = 0;
2464
2465	if (++log_modem_count >= LOG_MODEM_PERIOD) {
2466		snprintf(cmd, 64, "cat %s |wc -l", MODEMLOG_FILE);
2467		if ((fp = popen("cat /tmp/usb.log |wc -l", "r")) != NULL) {
2468			var[0] = '\0';
2469			while(fgets(var, 16, fp)) {
2470				line = atoi(var);
2471			}
2472			fclose(fp);
2473
2474			if (line > MAX_MODEMLOG_LINE) {
2475				snprintf(cmd, 64, "cat %s |tail -n %d > %s-1", MODEMLOG_FILE, MAX_MODEMLOG_LINE, MODEMLOG_FILE);
2476				system(cmd);
2477
2478				snprintf(cmd, 64, "mv %s-1 %s", MODEMLOG_FILE, MODEMLOG_FILE);
2479				system(cmd);
2480
2481				snprintf(cmd, 64, "rm -f %s-1", MODEMLOG_FILE);
2482				system(cmd);
2483			}
2484		}
2485
2486		log_modem_count = 0;
2487	}
2488	return;
2489}
2490
2491#if defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS)
2492void modem_flow_check(void) {
2493	time_t now, start, diff_mon;
2494	struct tm tm_now, tm_start;
2495	char timebuf[32];
2496	int day_cycle;
2497	int reset;
2498	int unit;
2499	int data_save_sec = nvram_get_int("modem_bytes_data_save"), count;
2500	int debug = nvram_get_int("modem_bytes_data_cycle_debug");
2501
2502	unit = get_wan_unit(nvram_safe_get("usb_modem_act_dev"));
2503	if (unit == -1)
2504		return;
2505
2506	if (!is_wan_connect(unit))
2507		return;
2508
2509	if (data_save_sec == 0)
2510		data_save_sec = atoi(nvram_default_get("modem_bytes_data_save"));
2511	count = data_save_sec/30;
2512	modem_data_save = (modem_data_save+1)%count;
2513	if (!modem_data_save) {
2514		if (debug == 1)
2515			_dprintf("modem_flow_check: save the data usage.\n");
2516		eval("modem_status.sh", "bytes+");
2517	}
2518
2519	if (++modem_flow_count >= MODEM_FLOW_PERIOD) {
2520		time(&now);
2521		memcpy(&tm_now, localtime(&now), sizeof(struct tm));
2522		if (debug == 1)
2523			_dprintf("modem_flow_check:   now. year %4d, month %2d, day %2d, hour, %2d, minute %2d.\n", tm_now.tm_year+1900, tm_now.tm_mon+1, tm_now.tm_mday, tm_now.tm_hour, tm_now.tm_min);
2524
2525		snprintf(timebuf, 32, "%s", nvram_safe_get("modem_bytes_data_start"));
2526		if (strlen(timebuf) <= 0 || !strcmp(timebuf, "0")) {
2527			snprintf(timebuf, 32, "%d", (int)now);
2528			nvram_set("modem_bytes_data_start", timebuf);
2529			eval("modem_status.sh", "bytes-");
2530		}
2531		start = strtol(nvram_safe_get("modem_bytes_data_start"), NULL, 10);
2532		memcpy(&tm_start, localtime(&start), sizeof(struct tm));
2533		if (debug == 1)
2534			_dprintf("modem_flow_check: start. year %4d, month %2d, day %2d, hour, %2d, minute %2d.\n", tm_start.tm_year+1900, tm_start.tm_mon+1, tm_start.tm_mday, tm_start.tm_hour, tm_start.tm_min);
2535
2536		day_cycle = strtol(nvram_safe_get("modem_bytes_data_cycle"), NULL, 10);
2537		if (debug == 1)
2538			_dprintf("modem_flow_check: cycle=%d.\n", day_cycle);
2539
2540		reset = 0;
2541		if (day_cycle >= 1 && day_cycle <= 31 && tm_now.tm_year+1900 >= 2014) {
2542			if (!start || tm_start.tm_year+1900 < 2014) {
2543				_dprintf("Start the cycle of the data count!\n");
2544				reset = 1;
2545			}
2546			else{
2547				if (tm_now.tm_mday == day_cycle) {
2548					// ex: day_cycle=20, start=2015/2/15 or 2014/4/30, now=2015/3/20. it should be reset by 2015/3/20, but in fact didn't yet.
2549					if (tm_now.tm_mday != tm_start.tm_mday || tm_now.tm_mon != tm_start.tm_mon || tm_now.tm_year != tm_start.tm_year)
2550						reset = 1;
2551				}
2552				else if (tm_now.tm_year != tm_start.tm_year) {
2553					reset = 1;
2554				}
2555				else if (tm_now.tm_mon < tm_start.tm_mon) {
2556					diff_mon = tm_now.tm_mon+12-tm_start.tm_mon;
2557					// ex: over 2 months. it should be reset, but in fact didn't yet.
2558					if (diff_mon > 1)
2559						reset = 1;
2560					else if (diff_mon == 1) {
2561						// ex: day_cycle=20, start=12/15, now=1/2. it should be reset by 12/20, but in fact didn't yet.
2562						// tm_start.tm_mday >= day_cycle: it had been reset.
2563						if (tm_start.tm_mday < day_cycle)
2564							reset = 1;
2565						// ex: day_cycle=20, start=12/25, now=1/21. it should be reset by 1/20, but in fact didn't yet.
2566						// tm_now.tm_mday < day_cycle: it didn't need to be reset.
2567						// tm_now.tm_mday == day_cycle: it had been reset by the above codes.
2568						else if (tm_now.tm_mday > day_cycle)
2569							reset = 1;
2570					}
2571				}
2572				else if (tm_now.tm_mon > tm_start.tm_mon) {
2573					diff_mon = tm_now.tm_mon-tm_start.tm_mon;
2574					// ex: over 2 months. it should be reset, but in fact didn't yet.
2575					if (diff_mon > 1)
2576						reset = 1;
2577					else if (diff_mon == 1) {
2578						// ex: day_cycle=31, start=2/28, now=3/1. it should be reset by 2/28(31?), but in fact didn't yet.
2579						// tm_start.tm_mday >= day_cycle: it had been reset.
2580						if (tm_start.tm_mday < day_cycle)
2581							reset = 1;
2582						// ex: day_cycle=20, start=2/25, now=3/21. it should be reset by 3/20, but in fact didn't yet.
2583						// tm_now.tm_mday < day_cycle: it didn't need to be reset.
2584						// tm_now.tm_mday == day_cycle: it had been reset by the above codes.
2585						else if (tm_now.tm_mday > day_cycle)
2586							reset = 1;
2587					}
2588				}
2589				else{ // tm_now.tm_mon == tm_start.tm_mon
2590					// ex: day_cycle=20, start=2/15, now=2/28. it should be reset by 2/20, but in fact didn't yet.
2591					// tm_now.tm_mday < day_cycle: it didn't need to be reset.
2592					// tm_now.tm_mday == day_cycle: it had been reset by the above codes.
2593					// tm_start.tm_mday >= day_cycle: it had been reset.
2594					if (tm_now.tm_mday > day_cycle && tm_start.tm_mday < day_cycle)
2595						reset = 1;
2596				}
2597			}
2598		}
2599
2600		if (reset) {
2601			snprintf(timebuf, 32, "%d", (int)now);
2602			nvram_set("modem_bytes_data_start", timebuf);
2603			eval("modem_status.sh", "bytes-");
2604		}
2605
2606		modem_flow_count = 0;
2607	}
2608	return;
2609}
2610#endif
2611#endif
2612
2613#if defined(RTCONFIG_USB) && defined(RTCONFIG_NOTIFICATION_CENTER)
2614static void ntevent_disk_usage_check(){
2615	char str[32];
2616	int ntevent_firstdisk = nvram_get_int("ntevent_firstdisk");
2617	int ntevent_nodiskuse_sec = nvram_get_int("ntevent_nodiskuse_sec");
2618	int ntevent_nodiskuse = nvram_get_int("ntevent_nodiskuse");
2619	int link_internet = nvram_get_int("link_internet");
2620	time_t now;
2621	unsigned long timestamp;
2622
2623	if(ntevent_nodiskuse_sec <= 0){
2624		ntevent_nodiskuse_sec = 86400*3;
2625		nvram_set("ntevent_nodiskuse_sec", "259200");
2626		nvram_commit();
2627	}
2628
2629	if(link_internet == 2 && !ntevent_nodiskuse && !ntevent_firstdisk){
2630		time(&now);
2631		snprintf(str, 32, "%s", nvram_safe_get("ntevent_nodiskuse_start"));
2632		if(strlen(str) > 0){
2633			timestamp = strtoll(str, (char **) NULL, 10);
2634			if(now-timestamp > ntevent_nodiskuse_sec){
2635				snprintf(str, 32, "0x%x", HINT_USB_CHECK_EVENT);
2636				eval("Notify_Event2NC", str, "");
2637				nvram_set("ntevent_nodiskuse", "1");
2638				nvram_commit();
2639			}
2640		}
2641		else{
2642			snprintf(str, 32, "%lu", now);
2643			nvram_set("ntevent_nodiskuse_start", str);
2644			nvram_commit();
2645		}
2646	}
2647}
2648#endif
2649
2650static void auto_firmware_check()
2651{
2652#ifdef RTCONFIG_FORCE_AUTO_UPGRADE
2653	static int period = -1;
2654	static int bootup_check = 0;
2655#else
2656	static int period = 5757;
2657	static int bootup_check = 1;
2658#endif
2659	static int periodic_check = 0;
2660	int cycle_manual = nvram_get_int("fw_check_period");
2661	int cycle = (cycle_manual > 1) ? cycle_manual : 5760;
2662	time_t now;
2663	struct tm *tm;
2664	static int rand_hr, rand_min;
2665
2666	if (!nvram_get_int("ntp_ready"))
2667		return;
2668
2669#ifdef RTCONFIG_FORCE_AUTO_UPGRADE
2670	setenv("TZ", nvram_safe_get("time_zone_x"), 1);
2671	time(&now);
2672	tm = localtime(&now);
2673	if ((tm->tm_hour >= 2) && (tm->tm_hour <= 6))	// 2 am to 6 am
2674		periodic_check = 1;
2675	else
2676		periodic_check = 0;
2677#else
2678	if (!bootup_check && !periodic_check)
2679	{
2680		time(&now);
2681		tm = localtime(&now);
2682
2683		if ((tm->tm_hour == (2 + rand_hr)) &&	// every 48 hours at 2 am + random offset
2684		    (tm->tm_min == rand_min))
2685		{
2686			periodic_check = 1;
2687			period = -1;
2688		}
2689	}
2690#endif
2691
2692#if defined(RTAC68U)
2693	else if (After(get_blver(nvram_safe_get("bl_version")), get_blver("2.1.2.1")) && !nvram_get_int("PA") && !nvram_match("cpurev", "c0"))
2694	{
2695		periodic_check = 1;
2696		nvram_set_int("fw_check_period", 10);
2697	}
2698#endif
2699
2700	if (bootup_check || periodic_check)
2701#ifdef RTCONFIG_FORCE_AUTO_UPGRADE
2702		period = (period + 1) % 20;
2703#else
2704		period = (period + 1) % cycle;
2705#endif
2706	else
2707		return;
2708
2709	if (!period)
2710	{
2711		if (bootup_check)
2712		{
2713			bootup_check = 0;
2714			rand_hr = rand_seed_by_time() % 4;
2715			rand_min = rand_seed_by_time() % 60;
2716		}
2717
2718		eval("/usr/sbin/webs_update.sh");
2719#ifdef RTCONFIG_DSL
2720		eval("/usr/sbin/notif_update.sh");
2721#endif
2722
2723		if (nvram_get_int("webs_state_update") &&
2724		    !nvram_get_int("webs_state_error") &&
2725		    strlen(nvram_safe_get("webs_state_info")))
2726		{
2727			dbg("retrieve firmware information\n");
2728
2729#if defined(RTAC68U) || defined(RTCONFIG_FORCE_AUTO_UPGRADE)
2730#if defined(RTAC68U)
2731			if (!After(get_blver(nvram_safe_get("bl_version")), get_blver("2.1.2.1")) || nvram_get_int("PA") || nvram_match("cpurev", "c0"))
2732				return;
2733#endif
2734
2735			if (nvram_get("login_ip") && !nvram_match("login_ip", ""))
2736				return;
2737
2738			if (nvram_match("x_Setting", "0"))
2739				return;
2740
2741			if (!nvram_get_int("webs_state_flag"))
2742			{
2743				dbg("no need to upgrade firmware\n");
2744				return;
2745			}
2746
2747//#ifdef RTCONFIG_FORCE_AUTO_UPGRADE
2748//			stop_httpd();
2749//#endif
2750//
2751			nvram_set_int("auto_upgrade", 1);
2752
2753			eval("/usr/sbin/webs_upgrade.sh");
2754
2755			if (nvram_get_int("webs_state_error"))
2756			{
2757				dbg("error execute upgrade script\n");
2758				goto ERROR;
2759			}
2760
2761#ifndef RTCONFIG_FORCE_AUTO_UPGRADE
2762			nvram_set("restore_defaults", "1");
2763			ResetDefault();
2764#endif
2765
2766#ifdef RTCONFIG_DUAL_TRX
2767			int count = 80;
2768#else
2769			int count = 50;
2770#endif
2771			while ((count-- > 0) && (nvram_get_int("webs_state_upgrade") == 1))
2772			{
2773				dbg("reboot count down: %d\n", count);
2774				sleep(1);
2775			}
2776
2777			reboot(RB_AUTOBOOT);
2778#endif
2779		}
2780		else
2781			dbg("could not retrieve firmware information!\n");
2782#if defined(RTAC68U) || defined(RTCONFIG_FORCE_AUTO_UPGRADE)
2783ERROR:
2784		nvram_set_int("auto_upgrade", 0);
2785#endif
2786	}
2787}
2788
2789#if 0
2790#ifdef RTCONFIG_PUSH_EMAIL
2791#define PM_CONTENT "/tmp/push_mail"
2792#define PM_CONFIGURE "/etc/email/email.conf"
2793#define PM_WEEKLY 1
2794#define PM_MONTHLY 2
2795void SendOutMail(void) {
2796	FILE *fp;
2797	char tmp[1024]={0}, buf[1024]={0};
2798	char tmp_sender[64]={0}, tmp_titile[64]={0}, tmp_attachment[64]={0};
2799
2800#if 0
2801	fp = fopen(PM_CONTENT, "w");
2802	if (fp) {
2803		fputs(" Push Mail Service!!! ", fp);
2804		fclose(fp);
2805	}
2806#else
2807	getlogbyinterval(PM_CONTENT, 0, 0);
2808
2809	if (f_size(PM_CONTENT) <= 0) {
2810		cprintf("No notified log.\n");
2811		return;
2812	}
2813#endif
2814
2815	/* write the configuration file.*/
2816	system("mkdir /etc/email");
2817	fp = fopen(PM_CONFIGURE,"w");
2818	if (fp == NULL) {
2819		cprintf("create configuration file fail.\n");
2820		return;
2821	}
2822
2823	/*SMTP_SERVER*/
2824	sprintf(tmp,"SMTP_SERVER = '%s'\n", nvram_safe_get("PM_SMTP_SERVER"));
2825	strcat(buf, tmp);
2826	/*SMTP_PORT*/
2827	sprintf(tmp,"SMTP_PORT = '%s'\n", nvram_safe_get("PM_SMTP_PORT"));
2828	strcat(buf, tmp);
2829	/*MY_NAME*/
2830	sprintf(tmp,"MY_NAME = '%s'\n", nvram_safe_get("PM_MY_NAME"));
2831	strcat(buf, tmp);
2832	/*MY_EMAIL*/
2833	sprintf(tmp,"MY_EMAIL = '%s'\n", nvram_safe_get("PM_MY_EMAIL"));
2834	strcat(buf, tmp);
2835	/*USE_TLS*/
2836	sprintf(tmp,"USE_TLS = '%s'\n", nvram_safe_get("PM_USE_TLS"));
2837	strcat(buf, tmp);
2838	/*SMTP_AUTH*/
2839	sprintf(tmp,"SMTP_AUTH = '%s'\n", nvram_safe_get("PM_SMTP_AUTH"));
2840	strcat(buf, tmp);
2841	/*SMTP_AUTH_USER*/
2842	sprintf(tmp,"SMTP_AUTH_USER = '%s'\n", nvram_safe_get("PM_SMTP_AUTH_USER"));
2843	strcat(buf, tmp);
2844	/*SMTP_AUTH_PASS*/
2845	sprintf(tmp,"SMTP_AUTH_PASS = '%s'\n", nvram_safe_get("PM_SMTP_AUTH_PASS"));
2846	strcat(buf, tmp);
2847
2848	fputs(buf,fp);
2849	fclose(fp);
2850
2851	/* issue command line to trigger eMail*/
2852	sprintf(tmp_sender, "Administrator");
2853	sprintf(tmp_titile, "RT-N16");
2854	sprintf(tmp_attachment, "/tmp/syslog.log");
2855	sprintf(tmp,"cat %s | email -V -n \"%s\" -s \"%s\" %s -a \"%s\"", PM_CONTENT, tmp_sender, tmp_titile, nvram_safe_get("PM_target"), tmp_attachment);
2856	system(tmp);
2857}
2858
2859void save_next_time(struct tm *tm) {
2860	nvram_set_int("PM_mon", tm->tm_mon);
2861	nvram_set_int("PM_day", tm->tm_mday);
2862	nvram_set_int("PM_hour", tm->tm_hour);
2863}
2864
2865int nexthour = 0;
2866int nextday = 0;
2867int nextmonth = 0;
2868void schedule_mail(int interval, struct tm *tm) {
2869	if (nextday == 0) {
2870		cprintf("Schedule the next report.!!!\n");
2871		tm->tm_mday += interval;
2872		mktime(tm);
2873		nextmonth = tm->tm_mon;
2874		nextday = tm->tm_mday;
2875		nexthour = tm->tm_hour;
2876
2877		save_next_time(tm);
2878	}
2879	else{
2880		if ((tm->tm_mon == nextmonth) && (tm->tm_mday == nextday) && (tm->tm_hour == nexthour)) {
2881			tm->tm_mday += interval;
2882			mktime(tm);
2883			nextmonth = tm->tm_mon;
2884			nextday = tm->tm_mday;
2885			nexthour = tm->tm_hour;
2886			save_next_time(tm);
2887
2888			cprintf("Sending Push Mail Service out!!!\n");
2889			SendOutMail();
2890		}
2891	}
2892}
2893
2894void push_mail(void)
2895{
2896	static int count =0;	//for debug
2897	time_t now;
2898	struct tm *tm;
2899	int tmpfreq = 0;
2900	//char tmp[32]={0};
2901
2902	//tcapi_get("PushMail_Entry", "PM_enable", tmp);
2903	if (nvram_get_int("PM_enable") == 0) {
2904		return;
2905	}
2906
2907	/* reset the Push Mail Service */
2908	//tcapi_get("PushMail_Entry", "PM_restart", tmp);
2909	if (nvram_get_int("PM_restart") == 1) {
2910		nexthour = 0;
2911		nextday = 0;
2912		nextmonth = 0;
2913		//tcapi_set("PushMail_Entry", "PM_restart", "0");
2914		nvram_set_int("PM_restart", 0);
2915	}
2916
2917	//tcapi_get("PushMail_Entry", "PM_freq", tmp);
2918	tmpfreq=nvram_get_int("PM_freq");
2919
2920	time(&now);
2921	tm = localtime(&now);
2922
2923	if (tmpfreq == PM_MONTHLY) { /* Monthly report */
2924		schedule_mail(30, tm);
2925	}
2926	else if (tmpfreq == PM_WEEKLY) {	/* Weekly report */
2927		schedule_mail(7, tm);
2928	}
2929	else{	/* Daily report */
2930		schedule_mail(1, tm);
2931	}
2932
2933	//debug.javi
2934	//tcapi_get("PushMail_Entry", "PM_debug", tmp);
2935	if (nvram_get_int("PM_debug") == 1) {
2936		if ((count %10) == 0) {
2937			cprintf("year=%d, month=%d, day=%d, wday=%d, hour=%d, min=%d, sec=%d\n",(tm->tm_year+1900), tm->tm_mon, tm->tm_mday, tm->tm_wday, tm->tm_hour, tm->tm_min, tm->tm_sec);
2938			cprintf("tmpfreq =%d, nextmonth =%d, nextday=%d nexthour=%d\n", tmpfreq, nextmonth , nextday, nexthour);
2939			cprintf("\n");
2940		}
2941		count ++;
2942	}
2943	//debug.javi
2944}
2945#endif
2946#endif
2947
2948
2949#if defined(RTCONFIG_USER_LOW_RSSI) && !defined(RTCONFIG_BCMARM)
2950#define ETHER_ADDR_STR_LEN	18
2951
2952typedef struct wl_low_rssi_count{
2953	char	wlif[32];
2954	int	lowc;
2955}wl_lowr_count_t;
2956
2957#define		WLLC_SIZE	2
2958static wl_lowr_count_t wllc[WLLC_SIZE];
2959
2960void init_wllc(void)
2961{
2962	char wlif[128], *next;
2963	int idx=0;
2964
2965	memset(wllc, 0, sizeof(wllc));
2966
2967	foreach (wlif, nvram_safe_get("wl_ifnames"), next)
2968	{
2969		strncpy(wllc[idx].wlif, wlif, 32);
2970		wllc[idx].lowc = 0;
2971
2972		idx++;
2973	}
2974}
2975
2976#if defined(RTCONFIG_RALINK)
2977/* Defined in router/rc/sysdeps/ralink/ralink.c */
2978#elif defined(RTCONFIG_QCA)
2979/* Defined in router/rc/sysdeps/qca/qca.c */
2980#else
2981#define	MAX_STA_COUNT	128
2982void rssi_check_unit(int unit)
2983{
2984	int lrsi = 0, lrc = 0;
2985
2986	scb_val_t scb_val;
2987	char ea[ETHER_ADDR_STR_LEN];
2988	int i, ii;
2989	char tmp[128], prefix[] = "wlXXXXXXXXXX_";
2990	char *name;
2991	int val = 0;
2992	char name_vif[] = "wlX.Y_XXXXXXXXXX";
2993	struct maclist *mac_list;
2994	int mac_list_size;
2995
2996	snprintf(prefix, sizeof(prefix), "wl%d_", unit);
2997
2998	lrc = nvram_get_int(strcat_r(prefix, "lrc", tmp));
2999	if (!lrc) lrc = 2;
3000	if (!(lrsi = nvram_get_int(strcat_r(prefix, "user_rssi", tmp))))
3001		return;
3002
3003#if defined(RTCONFIG_BCMWL6) && defined(RTCONFIG_PROXYSTA)
3004	if (psta_exist_except(unit) || psr_exist_except(unit))
3005	{
3006		dbg("%s radio is disabled\n",
3007			nvram_match(strcat_r(prefix, "nband", tmp), "1") ? "5 GHz" : "2.4 GHz");
3008		return;
3009	}
3010	else if (is_psta(unit) || is_psr(unit))
3011	{
3012		dbg("skip interface %s under psta or psr mode\n", nvram_safe_get(strcat_r(prefix, "ifname", tmp)));
3013		return;
3014	}
3015#endif
3016	name = nvram_safe_get(strcat_r(prefix, "ifname", tmp));
3017	wl_ioctl(name, WLC_GET_RADIO, &val, sizeof(val));
3018	val &= WL_RADIO_SW_DISABLE | WL_RADIO_HW_DISABLE;
3019
3020	if (val)
3021	{
3022		dbg("%s radio is disabled\n",
3023			nvram_match(strcat_r(prefix, "nband", tmp), "1") ? "5 GHz" : "2.4 GHz");
3024		return;
3025	}
3026
3027#ifdef RTCONFIG_WIRELESSREPEATER
3028	if ((nvram_get_int("sw_mode") == SW_MODE_REPEATER)
3029		&& (nvram_get_int("wlc_band") == unit))
3030	{
3031		sprintf(name_vif, "wl%d.%d", unit, 1);
3032		name = name_vif;
3033	}
3034#endif
3035
3036	/* buffers and length */
3037	mac_list_size = sizeof(mac_list->count) + MAX_STA_COUNT * sizeof(struct ether_addr);
3038	mac_list = malloc(mac_list_size);
3039
3040	if (!mac_list)
3041		goto exit;
3042
3043	memset(mac_list, 0, mac_list_size);
3044
3045	/* query wl for authenticated sta list */
3046	strcpy((char*) mac_list, "authe_sta_list");
3047	if (wl_ioctl(name, WLC_GET_VAR, mac_list, mac_list_size))
3048		goto exit;
3049
3050	for (i = 0; i < mac_list->count; i ++) {
3051		memcpy(&scb_val.ea, &mac_list->ea[i], ETHER_ADDR_LEN);
3052
3053		if (wl_ioctl(name, WLC_GET_RSSI, &scb_val, sizeof(scb_val_t)))
3054			continue;
3055
3056		ether_etoa((void *)&mac_list->ea[i], ea);
3057
3058		_dprintf("rssi chk.1. wlif (%s), chk ea=%s, rssi=%d(%d), lowr_cnt=%d, lrc=%d\n", name, ea, scb_val.val, lrsi, wllc[unit].lowc, lrc);
3059
3060		if (scb_val.val < lrsi) {
3061			_dprintf("rssi chk.2. low rssi: ea=%s, lowc=%d(%d)\n", ea, wllc[unit].lowc, lrc);
3062			if (++wllc[unit].lowc > lrc) {
3063				_dprintf("rssi chk.3. deauth ea=%s\n", ea);
3064
3065				scb_val.val = 8;	// reason code: Disassociated because sending STA is leaving BSS
3066				wllc[unit].lowc = 0;
3067
3068				if (wl_ioctl(name, WLC_SCB_DEAUTHENTICATE_FOR_REASON, &scb_val, sizeof(scb_val_t)))
3069					continue;
3070			}
3071		} else
3072			wllc[unit].lowc = 0;
3073	}
3074
3075	for (i = 1; i < 4; i++) {
3076#ifdef RTCONFIG_WIRELESSREPEATER
3077		if ((nvram_get_int("sw_mode") == SW_MODE_REPEATER)
3078			&& (unit == nvram_get_int("wlc_band")) && (i == 1))
3079			break;
3080#endif
3081		sprintf(prefix, "wl%d.%d_", unit, i);
3082		if (nvram_match(strcat_r(prefix, "bss_enabled", tmp), "1"))
3083		{
3084			sprintf(name_vif, "wl%d.%d", unit, i);
3085
3086			memset(mac_list, 0, mac_list_size);
3087
3088			/* query wl for authenticated sta list */
3089			strcpy((char*) mac_list, "authe_sta_list");
3090			if (wl_ioctl(name_vif, WLC_GET_VAR, mac_list, mac_list_size))
3091				goto exit;
3092
3093			for (ii = 0; ii < mac_list->count; ii ++) {
3094				memcpy(&scb_val.ea, &mac_list->ea[ii], ETHER_ADDR_LEN);
3095
3096				if (wl_ioctl(name_vif, WLC_GET_RSSI, &scb_val, sizeof(scb_val_t)))
3097					continue;
3098
3099				ether_etoa((void *)&mac_list->ea[ii], ea);
3100
3101				_dprintf("rssi chk.1. wlif (%s), chk ea=%s, rssi=%d(%d), lowr_cnt=%d, lrc=%d\n", name_vif, ea, scb_val.val, lrsi, wllc[unit].lowc, lrc);
3102
3103				if (scb_val.val < lrsi) {
3104					_dprintf("rssi chk.2. low rssi: ea=%s, lowc=%d(%d)\n", ea, wllc[unit].lowc, lrc);
3105					if (++wllc[unit].lowc > lrc) {
3106						_dprintf("rssi chk.3. deauth ea=%s\n", ea);
3107
3108						scb_val.val = 8;	// reason code: Disassociated because sending STA is leaving BSS
3109						wllc[unit].lowc = 0;
3110
3111						if (wl_ioctl(name_vif, WLC_SCB_DEAUTHENTICATE_FOR_REASON, &scb_val, sizeof(scb_val_t)))
3112							continue;
3113					}
3114				} else
3115					wllc[unit].lowc = 0;
3116			}
3117		}
3118	}
3119
3120	/* error/exit */
3121exit:
3122	if (mac_list) free(mac_list);
3123
3124	return;
3125}
3126#endif
3127void rssi_check()
3128{
3129	int ii = 0;
3130	char nv_param[NVRAM_MAX_PARAM_LEN];
3131	char *temp;
3132
3133	if (!nvram_get_int("wlready"))
3134		return;
3135
3136	for (ii = 0; ii < DEV_NUMIFS; ii++) {
3137		sprintf(nv_param, "wl%d_unit", ii);
3138		temp = nvram_get(nv_param);
3139
3140		if (temp && strlen(temp) > 0)
3141			rssi_check_unit(ii);
3142	}
3143}
3144#endif
3145
3146#ifdef RTCONFIG_TOR
3147#if (defined(RTCONFIG_JFFS2)||defined(RTCONFIG_BRCM_NAND_JFFS2))
3148static void Tor_microdes_check() {
3149
3150	FILE *f;
3151	char buf[256];
3152	char *ifname, *p;
3153	unsigned long counter1, counter2;
3154	struct stat tmp_db_stat, jffs_db_stat;
3155	int tmp_stat, jffs_stat;
3156
3157	if (++tor_check_count >= TOR_CHECK_PERIOD) {
3158		tor_check_count = 0;
3159
3160		jffs_stat = stat("/jffs/.tordb/cached-microdesc-consensus", &jffs_db_stat);
3161		if (jffs_stat != -1) {
3162			return;
3163		}
3164
3165		tmp_stat = stat("/tmp/.tordb/cached-microdesc-consensus", &tmp_db_stat);
3166		if (tmp_stat == -1) {
3167			return;
3168		}
3169
3170		if ((f = fopen("/tmp/torlog", "r")) == NULL) return -1;
3171
3172		while (fgets(buf, sizeof(buf), f)) {
3173			if ((p=strstr(buf, "now have enough directory")) == NULL) continue;
3174			*p = 0;
3175			eval("cp", "-rf", "/tmp/.tordb", "/jffs/.tordb");
3176			break;
3177		}
3178		fclose(f);
3179	}
3180
3181	return;
3182}
3183#endif
3184#endif
3185
3186#ifdef RTCONFIG_ERP_TEST
3187static void ErP_Test() {
3188	int i;
3189	int unit = 0;
3190	char nv_param[NVRAM_MAX_PARAM_LEN];
3191	char *temp, *name;
3192	char tmp[128], prefix[] = "wlXXXXXXXXXX_";
3193	int val = 0;
3194	struct maclist *mac_list;
3195	int mac_list_size;
3196	char name_vif[] = "wlX.Y_XXXXXXXXXX";
3197	char ifname[32];
3198	char *next;
3199	int assoc_count = 0;
3200
3201	if (!nvram_get_int("wlready"))
3202		return;
3203
3204_dprintf("### ErP Check... ###\n");
3205	for (unit = 0; unit < DEV_NUMIFS; unit++) {
3206		sprintf(nv_param, "wl%d_unit", unit);
3207		temp = nvram_get(nv_param);
3208
3209		if (temp && strlen(temp) > 0) {
3210
3211			snprintf(prefix, sizeof(prefix), "wl%d_", unit);
3212			name = nvram_safe_get(strcat_r(prefix, "ifname", tmp));
3213			wl_ioctl(name, WLC_GET_RADIO, &val, sizeof(val));
3214			val &= WL_RADIO_SW_DISABLE | WL_RADIO_HW_DISABLE;
3215
3216			if (val)
3217			{
3218				dbg("%s radio is disabled\n",
3219				nvram_match(strcat_r(prefix, "nband", tmp), "1") ? "5 GHz" : "2.4 GHz");
3220				continue;
3221			}
3222
3223			/* buffers and length */
3224			mac_list_size = sizeof(mac_list->count) + 128 * sizeof(struct ether_addr);
3225			mac_list = malloc(mac_list_size);
3226
3227			if (!mac_list)
3228				goto exit;
3229
3230			memset(mac_list, 0, mac_list_size);
3231
3232			/* query wl for authenticated sta list */
3233			strcpy((char*) mac_list, "authe_sta_list");
3234			if (wl_ioctl(name, WLC_GET_VAR, mac_list, mac_list_size))
3235				goto exit;
3236
3237			if (mac_list->count) {
3238				assoc_count += mac_list->count;
3239				break;
3240			}
3241
3242			for (i = 1; i < 4; i++) {
3243				sprintf(prefix, "wl%d.%d_", unit, i);
3244				if (nvram_match(strcat_r(prefix, "bss_enabled", tmp), "1")) {
3245					sprintf(name_vif, "wl%d.%d", unit, i);
3246
3247					memset(mac_list, 0, mac_list_size);
3248
3249					/* query wl for authenticated sta list */
3250					strcpy((char*) mac_list, "authe_sta_list");
3251					if (wl_ioctl(name_vif, WLC_GET_VAR, mac_list, mac_list_size))
3252						goto exit;
3253
3254					if (mac_list->count) {
3255						assoc_count += mac_list->count;
3256						break;
3257					}
3258				}
3259			}
3260		}
3261	}//end unit for loop
3262
3263	if (assoc_count) {
3264		//Back to Normal
3265		if (pwrsave_status == MODE_PWRSAVE) {
3266			_dprintf("ErP: Back to normal mode\n");
3267			no_assoc_check = 0;
3268
3269			eval("wl", "-i", "eth2", "radio", "on"); // Turn on 5G-1 radio
3270
3271			foreach(ifname, nvram_safe_get("wl_ifnames"), next) {
3272				eval("wl", "-i", ifname, "txchain", "0xf");
3273				eval("wl", "-i", ifname, "rxchain", "0xf");
3274				eval("wl", "-i", ifname, "down");
3275				eval("wl", "-i", ifname, "up");
3276			}
3277
3278			pwrsave_status = MODE_NORMAL;
3279		}
3280	}
3281	else {
3282		//No sta assoc. Enter PWESAVE Mode
3283		if (pwrsave_status == MODE_NORMAL) {
3284			no_assoc_check++;
3285			_dprintf("ErP: no_assoc_check = %d\n", no_assoc_check);
3286
3287			if (no_assoc_check >= NO_ASSOC_CHECK) {
3288				_dprintf("ErP: Enter Power Save Mode\n");
3289				foreach(ifname, nvram_safe_get("wl_ifnames"), next) {
3290					eval("wl", "-i", ifname, "txchain", "0x1");
3291					eval("wl", "-i", ifname, "rxchain", "0x1");
3292					eval("wl", "-i", ifname, "down");
3293					eval("wl", "-i", ifname, "up");
3294				}
3295
3296				eval("wl", "-i", "eth2", "radio", "off"); // Turn off 5G-1 radio
3297
3298				no_assoc_check = 0;
3299				pwrsave_status = MODE_PWRSAVE;
3300			}
3301		}
3302	}
3303
3304	/* error/exit */
3305exit:
3306	if (mac_list) free(mac_list);
3307
3308	return;
3309}
3310#endif
3311
3312
3313#if 0
3314static time_t	tt=0, tt_old=0;
3315static int 	bcnt=0;
3316void
3317period_chk_cnt()
3318{
3319	time(&tt);
3320	if (!tt_old)
3321		tt_old = tt;
3322
3323	++bcnt;
3324	if (tt - tt_old > 9 && tt - tt_old < 15) {
3325		if (bcnt > 15) {
3326			char buf[5];
3327			_dprintf("\n\n\n!! >>> rush cpu count %d in 10 secs<<<\n\n\n", bcnt);
3328			sprintf(buf, "%d", bcnt);
3329			nvram_set("cpurush", buf);
3330		}
3331		tt_old = tt;
3332		bcnt = 0;
3333	} else if (tt - tt_old >= 15) {
3334		tt = tt_old = bcnt = 0;
3335	}
3336}
3337#endif
3338
3339/* wathchdog is runned in NORMAL_PERIOD, 1 seconds
3340 * check in each NORMAL_PERIOD
3341 *	1. button
3342 *
3343 * check in each NORAML_PERIOD*10
3344 *
3345 *	1. time-dependent service
3346 */
3347
3348void watchdog(int sig)
3349{
3350#if 0
3351	period_chk_cnt();
3352#endif
3353	/* handle button */
3354	btn_check();
3355
3356	if (nvram_match("asus_mfg", "0")
3357#if defined(RTCONFIG_LED_BTN) || defined(RTCONFIG_WPS_ALLLED_BTN)
3358		&& nvram_get_int("AllLED")
3359#endif
3360	)
3361	service_check();
3362
3363	/* some io func will delay whole process in urgent mode, move this to sw_devled process */
3364	//led_check();
3365
3366#ifdef RTCONFIG_RALINK
3367	if (need_restart_wsc) {
3368		char word[256], *next, ifnames[128];
3369
3370		strcpy(ifnames, nvram_safe_get("wl_ifnames"));
3371		foreach (word, ifnames, next) {
3372			eval("iwpriv", word, "set", "WscConfMode=0");
3373		}
3374
3375		need_restart_wsc = 0;
3376		start_wsc_pin_enrollee();
3377	}
3378#endif
3379#ifdef RTCONFIG_SWMODE_SWITCH
3380	swmode_check();
3381#endif
3382#ifdef WEB_REDIRECT
3383	wanduck_check();
3384#endif
3385
3386	/* if timer is set to less than 1 sec, then bypass the following */
3387	if (itv.it_value.tv_sec == 0) return;
3388
3389#if (defined(PLN12) || defined(PLAC56) || defined(PLAC66U))
3390	client_check();
3391#endif
3392
3393	if (!nvram_match("asus_mfg", "0")) return;
3394
3395	watchdog_period = (watchdog_period + 1) % 30;
3396
3397#ifdef RTCONFIG_BCMARM
3398	if (u3_chk_life < 20) {
3399		chkusb3_period = (chkusb3_period + 1) % u3_chk_life;
3400		if (!chkusb3_period && nvram_match("usb_usb3", "1") && nvram_match("usb_path1_speed", "12")
3401				&& strcmp(nvram_safe_get("usb_path1"), "printer")
3402				&& strcmp(nvram_safe_get("usb_path1"), "modem")
3403				) {
3404			_dprintf("force reset usb pwr\n");
3405			stop_usb_program(1);
3406			sleep(1);
3407			set_pwr_usb(0);
3408			sleep(3);
3409			set_pwr_usb(1);
3410			u3_chk_life *= 2;
3411		}
3412	}
3413#endif
3414
3415#ifdef BTN_SETUP
3416	if (btn_pressed_setup >= BTNSETUP_START) return;
3417#endif
3418
3419	if (watchdog_period) return;
3420
3421#ifdef CONFIG_BCMWL5
3422	if (factory_debug())
3423#else
3424	if (IS_ATE_FACTORY_MODE())
3425#endif
3426		return;
3427
3428#if defined(RTCONFIG_USER_LOW_RSSI) && !defined(RTCONFIG_BCMARM)
3429	rssi_check();
3430#endif
3431
3432	/* check for time-related services */
3433	timecheck();
3434#if 0
3435	cpu_usage_monitor();
3436#endif
3437	ddns_check();
3438	networkmap_check();
3439	httpd_check();
3440	dnsmasq_check();
3441#ifdef RTAC87U
3442	qtn_module_check();
3443#endif
3444//#if defined(RTCONFIG_JFFS2LOG) && defined(RTCONFIG_JFFS2)
3445#if defined(RTCONFIG_JFFS2LOG) && (defined(RTCONFIG_JFFS2)||defined(RTCONFIG_BRCM_NAND_JFFS2))
3446	syslog_commit_check();
3447#endif
3448#if defined(RTCONFIG_USB_MODEM)
3449	modem_log_check();
3450#if defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2) || defined(RTCONFIG_UBIFS)
3451	modem_flow_check();
3452#endif
3453#endif
3454	auto_firmware_check();
3455
3456#ifdef RTCONFIG_BWDPI
3457	auto_sig_check();	// libbwdpi.so
3458	sqlite_db_check();	// libbwdpi.so
3459#endif
3460
3461#ifdef RTCONFIG_PUSH_EMAIL
3462	alert_mail_service();
3463#endif
3464
3465	check_hour_monitor_service();
3466
3467#if defined(RTCONFIG_TOR) && (defined(RTCONFIG_JFFS2) || defined(RTCONFIG_BRCM_NAND_JFFS2))
3468	if (nvram_get_int("Tor_enable"))
3469		Tor_microdes_check();
3470#endif
3471
3472#ifdef RTCONFIG_ERP_TEST
3473	ErP_Test();
3474#endif
3475
3476#if defined(RTCONFIG_USB) && defined(RTCONFIG_NOTIFICATION_CENTER)
3477	ntevent_disk_usage_check();
3478#endif
3479
3480	return;
3481}
3482
3483#if ! (defined(RTCONFIG_QCA) || defined(RTCONFIG_RALINK))
3484void watchdog02(int sig)
3485{
3486	watchdog_check();
3487	return;
3488}
3489#endif  /* ! (RTCONFIG_QCA || RTCONFIG_RALINK) */
3490
3491int
3492watchdog_main(int argc, char *argv[])
3493{
3494	FILE *fp;
3495
3496	/* write pid */
3497	if ((fp = fopen("/var/run/watchdog.pid", "w")) != NULL)
3498	{
3499		fprintf(fp, "%d", getpid());
3500		fclose(fp);
3501	}
3502
3503#ifdef RTCONFIG_SWMODE_SWITCH
3504	pre_sw_mode=nvram_get_int("sw_mode");
3505#endif
3506
3507	if (mediabridge_mode())
3508		wlonunit = nvram_get_int("wlc_band");
3509
3510#ifdef RTCONFIG_RALINK
3511	doSystem("iwpriv %s set WatchdogPid=%d", WIF_2G, getpid());
3512#if defined(RTCONFIG_HAS_5G)
3513	doSystem("iwpriv %s set WatchdogPid=%d", WIF_5G, getpid());
3514#endif	/* RTCONFIG_HAS_5G */
3515#endif	/* RTCONFIG_RALINK */
3516
3517	/* set the signal handler */
3518	signal(SIGCHLD, chld_reap);
3519	signal(SIGUSR1, catch_sig);
3520	signal(SIGUSR2, catch_sig);
3521	signal(SIGTSTP, catch_sig);
3522	signal(SIGALRM, watchdog);
3523#ifdef RTCONFIG_RALINK
3524	signal(SIGTTIN, catch_sig);
3525#if 0
3526	switch (get_model()) {
3527	case MODEL_RTN56U:
3528#ifdef RTCONFIG_DSL
3529	case MODEL_DSLN55U:
3530#endif
3531	signal(SIGHUP, catch_sig);
3532	break;
3533	}
3534#endif
3535#endif
3536
3537#ifdef RTCONFIG_DSL //Paul add 2012/6/27
3538	nvram_set("dsltmp_syncloss", "0");
3539	nvram_set("dsltmp_syncloss_apply", "0");
3540#endif
3541	nvram_unset("wps_ign_btn");
3542
3543	if (!pids("ots"))
3544		start_ots();
3545
3546	setenv("TZ", nvram_safe_get("time_zone_x"), 1);
3547
3548	_dprintf("TZ watchdog\n");
3549	/* set timer */
3550	alarmtimer(NORMAL_PERIOD, 0);
3551
3552	led_control_normal();
3553
3554	/* Most of time it goes to sleep */
3555	while (1)
3556	{
3557		pause();
3558	}
3559
3560	return 0;
3561}
3562
3563#if ! (defined(RTCONFIG_QCA) || defined(RTCONFIG_RALINK))
3564/* to check watchdog alive */
3565int watchdog02_main(int argc, char *argv[])
3566{
3567	FILE *fp;
3568	/* write pid */
3569	if ((fp = fopen("/var/run/watchdog02.pid", "w")) != NULL) {
3570		fprintf(fp, "%d", getpid());
3571		fclose(fp);
3572	}
3573	/* set the signal handler */
3574	signal(SIGALRM, watchdog02);
3575
3576	/* set timer */
3577	alarmtimer02(10, 0);
3578	/* Most of time it goes to sleep */
3579	while(1) {
3580		pause();
3581	}
3582	return 0;
3583}
3584#endif	/* ! (RTCONFIG_QCA || RTCONFIG_RALINK) */
3585
3586/* to control misc dev led */
3587int sw_devled_main(int argc, char *argv[])
3588{
3589	FILE *fp;
3590
3591	/* write pid */
3592	if ((fp = fopen("/var/run/sw_devled.pid", "w")) != NULL) {
3593		fprintf(fp, "%d", getpid());
3594		fclose(fp);
3595	}
3596
3597	swled_alloff_counts = nvram_get_int("offc");
3598
3599	/* set the signal handler */
3600	signal(SIGALRM, led_check);
3601
3602	/* set timer */
3603	alarmtimer(NORMAL_PERIOD, 0);
3604
3605	/* Most of time it goes to sleep */
3606	while(1) {
3607		pause();
3608	}
3609	return 0;
3610}
3611