1/*
2 * Copyright 2004, ASUSTek Inc.
3 * All Rights Reserved.
4 * 
5 * THIS SOFTWARE IS OFFERED "AS IS", AND ASUS GRANTS NO WARRANTIES OF ANY
6 * KIND, EXPRESS OR IMPLIED, BY STATUTE, COMMUNICATION OR OTHERWISE. BROADCOM
7 * SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS
8 * FOR A SPECIFIC PURPOSE OR NONINFRINGEMENT CONCERNING THIS SOFTWARE.
9 *
10 * $Id: services_ex.c,v 1.14 2009/03/03 02:39:54 james26_jang Exp $
11 */
12
13#ifdef ASUS_EXT
14#include <stdio.h>
15#include <stdlib.h>
16#include <string.h>
17#include <signal.h>
18#include <unistd.h>
19#include <errno.h>
20#include <sys/fcntl.h>
21#include <dirent.h>
22#include <sys/mount.h>
23#include <bcmnvram.h>
24#include <netconf.h>
25#include <shutils.h>
26#include <rc.h>
27#include <syslog.h>
28#include "iboxcom.h"
29#include "lp.h"
30#include <sys/vfs.h>
31#include <sys/types.h>
32#include <sys/stat.h>
33
34#ifdef WCN
35#include "ILibParsers.h"
36#include <wlutils.h>
37#endif // WCN
38
39#ifdef DLM
40#include <asm/page.h>
41#include <sys/swap.h>
42#include <sys/sysinfo.h>
43#include <stdarg.h>	// 2008.02 James.
44
45void start_apps();
46void stop_apps();
47void run_ftpsamba();
48void stop_ftpsamba();
49void stop_samba();
50void stop_ftp();
51void stop_dms();
52void write_disc_status();
53void get_first_partition(char *);
54#endif // DLM
55
56void wfc_parser(const char *);
57void char_to_ascii(char *, char *);
58
59/*// for stop_cdrom {
60#include <sys/ioctl.h>
61#include <linux/cdrom.h>
62// for stop_cdrom }//*/
63// for eject_scsi {
64#include <scsi/scsi.h>
65#include <scsi/scsi_ioctl.h>
66// for eject_scsi {
67
68#define logs(s) syslog(LOG_NOTICE, s)
69
70#ifdef USB_SUPPORT
71
72#ifdef WSC/* Cherry Cho added in 2008/4/8. */
73extern int wsc_restart;
74#endif // WSC
75
76#ifdef DLM
77/* CRC lookup table */
78static unsigned long crcs[256]={ 0x00000000,0x77073096,0xEE0E612C,0x990951BA,
790x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,
800x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,0x1DB71064,0x6AB020F2,
810xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,
820x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
830x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,
840xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,
850xDCD60DCF,0xABD13D59,0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,
860x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,
870x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,0x76DC4190,0x01DB7106,0x98D220BC,
880xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,
890x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,0x6B6B51F4,
900x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,
910x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,
920xFBD44C65,0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,
930xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,
940x33031DE5,0xAA0A4C5F,0xDD0D7CC9,0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,
950x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,
960xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,0xEDB88320,0x9ABFB3B6,
970x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,
980x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
990xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,
1000x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,
1010x17B7BE43,0x60B08ED5,0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,
1020xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,
1030xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,0xCB61B38C,0xBC66831A,0x256FD2A0,
1040x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,
1050x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,0x9B64C2B0,
1060xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,
1070x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,
1080x0BDBDF21,0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,
1090x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,
1100xF862AE69,0x616BFFD3,0x166CCF45,0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,
1110xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,
1120x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,0xBDBDF21C,0xCABAC28A,
1130x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,
1140xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D};
115#endif // DLM
116
117enum
118{
119	WEB_NONE = 0,
120	WEB_PWCWEB,
121	WEB_OVWEB,
122	WEB_AUDIO,
123	USB_PRINTER, //2008.05 James.
124	MASS_STORAGE //2008.03.13 Yau add
125#ifdef CDMA
126	, USB_ACM	// HSDPA
127#endif // CDMA
128} WEBTYPE;
129
130char *PWCLIST[] = {"471","69a","46d","55d","41e","4cc","d81", NULL};
131char *OVLIST[] = {"5a9","813","b62", NULL};
132
133#endif // USB_SUPPORT
134
135char buf_g[512];
136char usb1[128];
137char usb2[128];
138
139void diag_PaN(void)
140{
141	FILE *fp;
142//	char *token;
143//    	char                                mfr[32];
144//    	char                                model[64];
145//    	int                                 fd;
146//	int  i = 0;
147        
148//    	struct parport_splink_device_info   prn_info;
149
150	/* dump pci device */
151	fp=fopen("/proc/pci", "r");
152	if (fp!=NULL)
153	{
154		while(fgets(buf_g, sizeof(buf_g), fp))
155		{
156			if(strstr(buf_g, "PCI device"))
157				fprintf(stderr, buf_g);
158		}
159		fclose(fp);
160	}
161
162
163#ifdef RT2400_SUPPORT
164	if (nvram_match("nobr", "1"))
165		fprintf(stderr, "dumping 0x4301 for manu.\n");
166#endif // RT2400_SUPPORT
167
168#ifdef USB_SUPPORT
169	/*if (nvram_match("usb_device", "1"))
170	{
171		fprintf(stderr, "new USB device\r\n");
172	}//*/
173#endif // USB_SUPPORT
174
175#ifdef PRINTER_SUPPORT
176#ifdef PARPORT_SUPPORT	
177    if( (fd=open("/dev/lp0", O_RDWR)) < 0 ) //Someone is opening the lp0
178    {
179        fp=fopen("/proc/sys/dev/parport/parport0/devices/lp/deviceid","r");
180
181        if( fp != NULL)
182        {    
183            while ( fgets(buf_g, sizeof(buf_g), fp) != NULL )  
184            {
185                if(buf_g[0] == '\n')
186                {
187                    continue;
188                }
189                if(strncmp(buf_g , "Model: " , strlen("Model: ")) == 0)
190                {
191                    token = buf_g + strlen("Model: ");
192		    sprintf(buf_g, "PARPORT: %s", token);
193		    fprintf(stderr, "%s\r\n", buf_g);
194		    //logmessage("PARPORT", buf_g);
195                }                
196	    }	
197	    fclose(fp);
198	}
199	//else logmessage("NO", "No printer found");
200    }
201    else
202    {
203        if( ioctl(fd, LPGETID, &prn_info) <0 )
204        {
205	    //logmessage("PaN", "No printer found");
206            //PRINT("ioctl error\n");
207        }
208        else
209        {
210            memccpy(mfr , prn_info.mfr , 1 , 32);
211            memccpy(model , prn_info.model , 1 , 32);
212        
213            sprintf(buf_g, "PARPORT: %s", model);
214	    fprintf(stderr, "%s\r\n", buf_g);
215            //logmessage("PARPORT", buf_g);
216        }
217	close(fd);
218   }
219#endif // PARPORT_SUPPORT
220#endif // PRINTER_SUPPORT
221   fprintf(stderr, "echo for PaN ::: &&&PaN\r\n");
222}
223
224int
225start_dhcpd(void)
226{
227	FILE *fp;
228	char *dhcpd_argv[] = {"udhcpd", "/tmp/udhcpd.conf", NULL, NULL};
229	char *slease = "/tmp/udhcpd-br0.sleases";
230	pid_t pid;
231
232	if (nvram_match("router_disable", "1") || nvram_invmatch("lan_proto", "dhcp"))
233		return 0;
234
235	dprintf("%s %s %s %s\n",
236		nvram_safe_get("lan_ifname"),
237		nvram_safe_get("dhcp_start"),
238		nvram_safe_get("dhcp_end"),
239		nvram_safe_get("lan_lease"));
240
241	if (!(fp = fopen("/tmp/udhcpd-br0.leases", "a"))) {
242		perror("/tmp/udhcpd-br0.leases");
243		return errno;
244	}
245	fclose(fp);
246
247	/* Write configuration file based on current information */
248	if (!(fp = fopen("/tmp/udhcpd.conf", "w"))) {
249		perror("/tmp/udhcpd.conf");
250		return errno;
251	}
252	
253	fprintf(fp, "pidfile /var/run/udhcpd-br0.pid\n");
254	fprintf(fp, "start %s\n", nvram_safe_get("dhcp_start"));
255	fprintf(fp, "end %s\n", nvram_safe_get("dhcp_end"));
256	fprintf(fp, "interface %s\n", nvram_safe_get("lan_ifname"));
257	fprintf(fp, "remaining yes\n");
258	fprintf(fp, "lease_file /tmp/udhcpd-br0.leases\n");
259	fprintf(fp, "option subnet %s\n", nvram_safe_get("lan_netmask"));
260	
261	if (nvram_invmatch("dhcp_gateway_x",""))
262	    fprintf(fp, "option router %s\n", nvram_safe_get("dhcp_gateway_x"));	else	
263	    fprintf(fp, "option router %s\n", nvram_safe_get("lan_ipaddr"));	
264	
265	if (nvram_invmatch("dhcp_dns1_x",""))		
266		fprintf(fp, "option dns %s\n", nvram_safe_get("dhcp_dns1_x"));		
267	fprintf(fp, "option dns %s\n", nvram_safe_get("lan_ipaddr"));
268	fprintf(fp, "option lease %s\n", nvram_safe_get("dhcp_lease"));
269
270	if (nvram_invmatch("dhcp_wins_x",""))		
271		fprintf(fp, "option wins %s\n", nvram_safe_get("dhcp_wins_x"));		
272	if (nvram_invmatch("lan_domain", ""))
273		fprintf(fp, "option domain %s\n", nvram_safe_get("lan_domain"));
274	fclose(fp);
275
276	
277	if (nvram_match("dhcp_static_x","1"))
278	{	
279		write_static_leases(slease);
280		dhcpd_argv[2] = slease;
281	}
282	else
283	{
284		dhcpd_argv[2] = NULL;
285	}
286
287	_eval(dhcpd_argv, NULL, 0, &pid);
288
289
290	dprintf("done\n");
291	return 0;
292}
293
294int
295stop_dhcpd(void)
296{
297//	char sigusr1[] = "-XX";
298	int ret;
299
300/*
301* Process udhcpd handles two signals - SIGTERM and SIGUSR1
302*
303*  - SIGUSR1 saves all leases in /tmp/udhcpd.leases
304*  - SIGTERM causes the process to be killed
305*
306* The SIGUSR1+SIGTERM behavior is what we like so that all current client
307* leases will be honorred when the dhcpd restarts and all clients can extend
308* their leases and continue their current IP addresses. Otherwise clients
309* would get NAK'd when they try to extend/rebind their leases and they 
310* would have to release current IP and to request a new one which causes 
311* a no-IP gap in between.
312*/
313	ret = eval("killall", "udhcpd");
314
315	dprintf("done\n");
316	return ret;
317}
318
319int
320start_dns(void)
321{
322	FILE *fp;
323	char *dproxy_argv[] = {"dproxy", "-d", "-c", "/tmp/dproxy.conf", NULL};
324	pid_t pid;
325	char word[100];
326	int ret, active;
327
328	if (nvram_match("router_disable", "1"))
329		return 0;
330
331
332	/* Create resolv.conf with empty nameserver list */
333	if (!(fp = fopen("/tmp/resolv.conf", "r")))
334	{
335		if (!(fp = fopen("/tmp/resolv.conf", "w"))) 
336		{
337			perror("/tmp/resolv.conf");
338			return errno;
339		}
340		else fclose(fp);
341	}
342	else fclose(fp);
343
344	if (!(fp = fopen("/tmp/dproxy.conf", "w"))) {
345		perror("/tmp/dproxy.conf");
346		return errno;
347	}
348	
349	fprintf(fp, "name_server=140.113.1.1\n");
350	fprintf(fp, "ppp_detect=no\n");
351	fprintf(fp, "purge_time=1200\n");
352	fprintf(fp, "deny_file=/tmp/dproxy.deny\n");
353	fprintf(fp, "cache_file=/tmp/dproxy.cache\n");
354	fprintf(fp, "hosts_file=/tmp/hosts\n");
355	fprintf(fp, "dhcp_lease_file=\n");
356	fprintf(fp, "ppp_dev=/var/run/ppp0.pid\n");
357	fclose(fp);
358
359	// if user want to set dns server by himself
360	if (nvram_invmatch("wan_dnsenable_x", "1"))	
361	{
362		/* Write resolv.conf with upstream nameservers */
363		if (!(fp = fopen("/tmp/resolv.conf", "w"))) {
364			perror("/tmp/resolv.conf");
365			return errno;
366		}
367	
368		if (nvram_invmatch("wan_dns1_x",""))
369			fprintf(fp, "nameserver %s\n", nvram_safe_get("wan_dns1_x"));
370		if (nvram_invmatch("wan_dns2_x",""))
371			fprintf(fp, "nameserver %s\n", nvram_safe_get("wan_dns2_x"));
372		fclose(fp);
373	}
374
375	active = timecheck_item(nvram_safe_get("url_date_x"), 
376				nvram_safe_get("url_time_x"));
377
378	if (nvram_match("url_enable_x", "1") && active) 
379	{
380		int i;
381		
382		if (!(fp = fopen("/tmp/dproxy.deny", "w"))) {
383			perror("/tmp/dproxy.deny");
384			return errno;
385		}
386
387		for(i=0; i<atoi(nvram_safe_get("url_num_x")); i++) {
388			sprintf(word, "url_keyword_x%d", i);
389			fprintf(fp, "%s\n", nvram_safe_get(word));
390		}
391	
392		fclose(fp);	
393	}
394	else unlink("/tmp/dproxy.deny");
395
396
397	if (!(fp = fopen("/tmp/hosts", "w"))) {
398		perror("/tmp/hosts");
399		return errno;
400	}
401
402	fprintf(fp, "127.0.0.1 localhost.localdomain localhost\n");
403	fprintf(fp, "%s	my.router\n", nvram_safe_get("lan_ipaddr"));
404	fprintf(fp, "%s	my.%s\n", nvram_safe_get("lan_ipaddr"), nvram_safe_get("productid"));
405	
406	if (nvram_invmatch("lan_hostname", ""))
407	{
408		fprintf(fp, "%s %s.%s %s\n", nvram_safe_get("lan_ipaddr"),
409					nvram_safe_get("lan_hostname"),
410					nvram_safe_get("lan_domain"),
411					nvram_safe_get("lan_hostname"));
412	}	
413	fclose(fp);	
414		
415	_eval(dproxy_argv, NULL, 0, &pid);
416
417	dprintf("done\n");
418	return ret;
419}	
420
421int
422stop_dns(void)
423{
424	int ret = eval("killall", "dproxy");
425	unlink("/tmp/dproxy.deny");		
426	dprintf("done\n");
427	return ret;
428}
429
430int
431ddns_updated_main(int argc, char *argv[])
432{
433	FILE *fp;
434	char buf[64], *ip;
435
436	if (!(fp=fopen("/tmp/ddns.cache", "r"))) return 0;
437	
438	fgets(buf, sizeof(buf), fp);
439	fclose(fp);
440
441	if (!(ip=strchr(buf, ','))) return 0;
442	
443	nvram_set("ddns_cache", buf);
444	nvram_set("ddns_ipaddr", ip+1);
445	nvram_set("ddns_status", "1");
446	nvram_commit();
447
448	logmessage("ddns", "ddns update ok");
449
450	dprintf("done\n");
451
452	return 0;
453}
454	
455
456int 
457start_ddns(void)
458{
459	FILE *fp;
460//	char buf[64];
461	char *wan_ip, *ddns_cache;
462	char server[32];
463	char user[32];
464	char passwd[32];
465	char host[64];
466	char service[32];
467	char usrstr[64];
468	char wan_ifname[16];
469	int  wild=nvram_match("ddns_wildcard_x", "1");
470	char *dproxy_argv[] = {"dproxy", "-d", "-c", "/tmp/dproxy.conf", NULL};
471	pid_t pid;
472
473
474	if (nvram_match("router_disable", "1")) return -1;
475	
476	if (nvram_invmatch("ddns_enable_x", "1")) return -1;
477
478	if ((wan_ip = nvram_safe_get("wan_ipaddr_t"))==NULL) return -1;
479
480	if (nvram_match("ddns_ipaddr", wan_ip)) return -1;
481
482	if (inet_addr(wan_ip)==inet_addr(nvram_safe_get("ddns_ipaddr"))) return -1;
483
484	// TODO : Check /tmp/ddns.cache to see current IP in DDNS
485	// update when,
486	// 	1. if ipaddr!= ipaddr in cache
487	// 	
488        // update
489	// * nvram ddns_cache, the same with /tmp/ddns.cache
490
491	if ((fp=fopen("/tmp/ddns.cache", "r"))==NULL && 
492	     (ddns_cache=nvram_get("ddns_cache"))!=NULL)
493	{
494		if ((fp = fopen("/tmp/ddns.cache", "w+"))!=NULL)
495		{
496			fprintf(fp, "%s", ddns_cache);
497			fclose(fp);
498		}
499	}
500
501	/* Clean DNS cache */
502	//eval("rm", "-rf", "/tmp/dproxy.cache");
503	unlink("/tmp/dproxy.cache");	// 2008.08 James.
504//	eval("dproxy", "-d", "-c", "/tmp/dproxy.conf");
505//	_eval(dproxy_argv, NULL, 0, &pid);
506
507	strcpy(server, nvram_safe_get("ddns_server_x"));
508	strcpy(user, nvram_safe_get("ddns_username_x"));
509	strcpy(passwd, nvram_safe_get("ddns_passwd_x"));
510	strcpy(host, nvram_safe_get("ddns_hostname_x"));
511	strcpy(service, "");
512
513	if (strcmp(server, "WWW.DYNDNS.ORG")==0)
514		strcpy(service, "dyndns");			
515	else if (strcmp(server, "WWW.DYNDNS.ORG(CUSTOM)")==0)
516		strcpy(service, "dyndns");			
517	else if (strcmp(server, "WWW.DYNDNS.ORG(STATIC)")==0)
518		strcpy(service, "dyndns");			
519	else if (strcmp(server, "WWW.TZO.COM")==0)
520		strcpy(service, "tzo");			
521	else if (strcmp(server, "WWW.ZONEEDIT.COM")==0)
522		strcpy(service, "zoneedit");
523	else if (strcmp(server, "WWW.JUSTLINUX.COM")==0)
524		strcpy(service, "justlinux");
525	else if (strcmp(server, "WWW.EASYDNS.COM")==0)
526		strcpy(service, "easydns");
527#ifdef ASUS_DDNS //2007.03.20 Yau add
528        else if (strcmp(server, "WWW.ASUS.COM")==0)
529                strcpy(service, "dyndns");
530#endif // ASUS_DDNS
531	else strcpy(service, "dyndns");
532
533	sprintf(usrstr, "%s:%s", user, passwd);
534
535#ifdef CDMA // HSDPA
536	if(strcmp(nvram_safe_get("hsdpa_product"), "") != 0)
537		strcpy(wan_ifname, "ppp0");
538	else
539#endif
540	if (nvram_match("wan_proto", "pppoe") || nvram_match("wan_proto", "pptp") || nvram_match("wan_proto", "l2tp"))
541	{
542		strcpy(wan_ifname, nvram_safe_get("wan0_pppoe_ifname"));
543	}
544	else
545	{
546		strcpy(wan_ifname, nvram_safe_get("wan0_ifname"));
547	}	
548
549	dprintf("wan_ifname: %s\n\n\n\n", wan_ifname);
550
551#ifdef ASUS_DDNS //2007.03.20 Yau add
552        if (strcmp(server, "WWW.ASUS.COM")==0)
553	{
554                char *ddns_argv[] = {"ez-ipupdate",
555		"-h", host,
556		"-s", "ns1.asuscomm.com",
557                "-S", service,
558		"-D", 
559                "-i", wan_ifname,
560                "-A", "1",
561                NULL};
562                pid_t pid;
563                                                                                                                                              
564                dprintf("ddns update %s %s\n", server, service);
565
566                eval("killall", "ez-ipupdate");
567                _eval(ddns_argv, NULL, 0, &pid);
568	}
569	else
570#endif // ASUS_DDNS. End of Yau add
571	if (strlen(service)>0)
572	{
573		char *ddns_argv[] = {"ez-ipupdate", 
574		"-S", service,
575	        "-i", wan_ifname,
576 		"-u", usrstr,
577		"-h", host,
578		"-e", "/sbin/ddns_updated",
579		"-b", "/tmp/ddns.cache",
580		wild ? "-w" : NULL,
581		NULL};	
582		pid_t pid;
583
584		dprintf("ddns update %s %s\n", server, service);
585		nvram_unset("ddns_cache");
586		nvram_unset("ddns_ipaddr");
587		nvram_unset("ddns_status");
588
589		eval("killall", "ez-ipupdate");
590		_eval(ddns_argv, NULL, 0, &pid);
591	}
592	return 0;
593}
594
595int 
596stop_ddns(void)
597{
598	int ret = eval("killall", "ez-ipupdate");
599
600	dprintf("done\n");
601	return ret;
602}
603
604int 
605start_logger(void)
606{		
607	pid_t pid;
608
609	if (nvram_match("router_disable", "1"))
610		return 0;
611
612	if (nvram_invmatch("log_ipaddr", ""))
613	{
614		char *syslogd_argv[] = {"syslogd", "-m", "0", "-t", nvram_safe_get("time_zone_x"), "-O", "/tmp/syslog.log", "-R", nvram_safe_get("log_ipaddr"), "-L", NULL};
615#ifdef KERNEL_DBG
616		char *klogd_argv[] = {"klogd", "-d", NULL};
617#else // KERNEL_DBG
618		char *klogd_argv[] = {"klogd", NULL};
619#endif // KERNEL_DBG
620
621		_eval(syslogd_argv, NULL, 0, &pid);
622		_eval(klogd_argv, NULL, 0, &pid);
623	}
624	else
625	{
626		char *syslogd_argv[] = {"syslogd", "-m", "0", "-t", nvram_safe_get("time_zone_x"), "-O", "/tmp/syslog.log", NULL};
627
628#ifdef KERNEL_DBG
629		char *klogd_argv[] = {"klogd", "-d", NULL};
630#else // KERNEL_DBG
631		char *klogd_argv[] = {"klogd", NULL};
632#endif // KERNEL_DBG
633
634		_eval(syslogd_argv, NULL, 0, &pid);
635		_eval(klogd_argv, NULL, 0, &pid);
636	}
637	// remote log not easy to ok
638	sleep(1);
639	return 0;
640}
641
642int
643stop_logger(void)
644{
645	int ret1 = eval("killall", "klogd");
646	int ret2 = eval("killall", "syslogd");
647
648	dprintf("done\n");
649	return (ret1|ret2);
650}
651
652int 
653start_misc(void)
654{ 
655	char *infosvr_argv[] = {"infosvr", "br0", NULL};
656	char *ots_argv[] = {"ots", NULL};	// 2008.01 James. For communicating to utility.
657	char *watchdog_argv[] = {"watchdog", NULL};
658	char *utelnetd_argv[] = {"utelnetd", NULL};
659	pid_t pid;
660
661	_eval(infosvr_argv, NULL, 0, &pid);
662
663	_eval(ots_argv, NULL, 0, &pid);	// 2008.01 James. For communicating to utility.
664
665	_eval(watchdog_argv, NULL, 0, &pid);
666
667	if(!strcmp(nvram_safe_get("telnet_down"), "0"))
668		_eval(utelnetd_argv, NULL, 0, &pid);
669
670	/* adjust some special parameters here */
671	/* tx power */
672#if 0
673#ifndef WL500GPV2
674	/* adjust some special parameters here */
675	/* tx power */
676	if (nvram_match("wl_radio_power_x", "0"))
677	{
678		eval("wl", "txpwr1", "-o", "-q", "14");
679	}
680	else if (nvram_match("wl_radio_power_x", "1"))
681        {
682                eval("wl", "txpwr1", "-o", "-q", "15");
683        }
684	else if (nvram_match("wl_radio_power_x", "2"))
685        {
686                eval("wl", "txpwr1", "-o", "-q", "20");
687        }
688	else if (nvram_match("wl_radio_power_x", "3"))
689        {
690                eval("wl", "txpwr1", "-o", "-q", "22");
691        }
692	else if (nvram_match("wl_radio_power_x", "4"))
693        {
694                eval("wl", "txpwr1", "-o", "-q", "23");
695        }
696	else if (nvram_match("wl_radio_power_x", "5"))
697        {
698                eval("wl", "txpwr1", "-o", "-q", "25");
699        }
700	else if (nvram_match("wl_radio_power_x", "6"))
701        {
702                eval("wl", "txpwr1", "-o", "-q", "30");
703        }
704	else if (nvram_match("wl_radio_power_x", "7"))
705        {
706                eval("wl", "txpwr1", "-o", "-q", "35");
707        }
708	else if (nvram_match("wl_radio_power_x", "8"))
709        {
710                eval("wl", "txpwr1", "-o", "-q", "40");
711        }
712	else if (nvram_match("wl_radio_power_x", "9"))
713        {
714                eval("wl", "txpwr1", "-o", "-q", "45");
715        }
716	else if (nvram_match("wl_radio_power_x", "10"))
717        {
718                eval("wl", "txpwr1", "-o", "-q", "50");
719        }	
720#endif // WL500GPV2
721#endif // 0
722	// for all product, fix antdiv
723	eval("wl", "antdiv", "0");
724	eval("wl", "txant", "0");
725
726#ifdef CDMA // HSDPA {
727	if(nvram_match("hsdpa_enable", "1"))
728	{
729		char *AT_argv[] = {"AT", NULL};	
730		//_eval(AT_argv, NULL, 0, &pid);
731
732	}
733#endif // CDMA // HSDPA }
734
735	if (nvram_match("wl_radio_x", "0"))
736		wl_led_ctrl(0);
737
738	return 0;
739}
740
741int
742stop_misc(void)
743{
744	int ret1 = eval("killall", "infosvr");
745	
746	eval("killall", "ots");
747	eval("killall", "utelnetd");
748	
749	eval("killall", "watchdog");
750	//eval("rm", "-f", "/var/run/watchdog.pid");	// 2007.11 James.
751	unlink("/var/run/watchdog.pid");	// 2008.08 James.
752	
753	eval("killall", "ntp");
754
755	dprintf("done\n");
756	return(ret1);
757}
758
759int
760stop_misc_no_watchdog(void)
761{
762	int ret1 = eval("killall", "infosvr");
763	eval("killall", "ntp");
764
765	dprintf("done\n");
766	return(ret1);
767}
768
769
770#ifndef USB_SUPPORT
771int start_usb(void)
772{
773	return 0;
774}
775
776int stop_usb(void)
777{
778	return 0;
779}
780
781int hotplug_usb(void)
782{
783	return 0;
784}
785#else // USB_SUPPORT
786int 
787start_usb(void)
788{
789	eval("insmod", "usbcore");
790	eval("insmod", "usb-ohci");
791	eval("insmod", "ehci-hcd");
792
793	eval("mount", "-t", "usbdevfs", "none", "/proc/bus/usb/");
794
795#ifdef U2EC
796	char *u2ec_argv[] = {"u2ec", NULL};
797	pid_t pid_u2ec;
798	_eval(u2ec_argv, NULL, 0, &pid_u2ec);
799#else // U2EC
800	semaphore_create();
801	nvram_set("MFP_busy", "0");
802#endif // U2EC
803
804#ifdef PRINTER_SUPPORT
805#ifdef PARPORT_SUPPORT	
806	symlink("/dev/printers/0", "/dev/lp0");
807	symlink("/dev/lp0", "/tmp/lp0");
808	eval("insmod", "parport.o");
809	eval("insmod", "parport_splink.o");
810	eval("insmod", "lp.o");
811#endif // PARPORT_SUPPORT
812	eval("insmod", "printer.o");
813	mkdir("/var/state", 0777);
814	mkdir("/var/state/parport", 0777);
815	mkdir("/var/state/parport/svr_statue", 0777);
816	{
817		char *lpd_argv[]={"lpd", NULL};
818		pid_t pid;
819
820		sleep(2);
821		_eval(lpd_argv, ">/dev/null", 0, &pid);
822	}
823#endif // PRINTER_SUPPORT
824
825#ifdef MASSSTORAGE_SUPPORT
826	if (nvram_invmatch("usb_ftpenable_x", "0"))
827	{
828		eval("insmod", "scsi_mod.o");
829		eval("insmod", "sd_mod.o");
830		sleep(1);	// 2008.06 James. For some flashes, must delay for detecting.
831		eval("insmod", "usb-storage.o");
832		eval("insmod", "cdrom", "autoclose=0", "autoeject=1", "lockdoor=0", "check_media_type=1");
833		eval("insmod", "sr_mod");
834		umask(0000);			// added by Jiahao for WL500gP
835		mkdir("/tmp/harddisk", 0777);
836	}	
837#endif // MASSSTORAGE_SUPPORT
838
839#ifdef AUDIO_SUPPORT
840	eval("insmod", "soundcore.o");
841	eval("insmod", "audio.o");
842	start_audio();
843#endif // AUDIO_SUPPORT
844
845#ifdef WEBCAM_SUPPORT	
846	if (nvram_invmatch("usb_webenable_x", "0"))
847	{	
848		eval("insmod", "videodev.o");
849
850		// link video 
851		symlink("/dev/v4l/video0", "/dev/video");
852		start_rcamd();
853	}
854#endif // WEBCAM_SUPPORT
855
856#ifdef CDMA
857	eval("insmod", "acm.o");
858//	eval("insmod", "usbserial.o", "vendor=0x1165", "product=0x0001");
859//        eval("insmod", "usbserial.o", "vendor=0x1a8d", "product=0x1002"); //Huawei E220 // HSDPA
860//      eval("insmod", "usbserial.o", "vendor=0x0b05", "product=0x0302"); //Bandluxe C100
861//      eval("insmod", "usbserial.o", "vendor=0x0bb4", "product=0x00ce"); //ASUS T500
862//      eval("insmod", "usbserial.o", "vendor=0x0421", "product=0x04f0"); //Nokia 95
863//      eval("insmod", "usbserial.o", "vendor=0x0fce", "product=0xd039"); //SE K800
864#endif // CDMA
865
866	return 0;	// 2007.11 James.
867}
868
869int
870stop_usb(void)
871{
872#ifdef MASSSTORAGE_SUPPORT
873	if (nvram_invmatch("usb_ftpenable_x", "0"))
874	{
875#ifdef DLM
876		eval("killall", "snarf");
877		eval("killall", "ctorrent");
878		eval("killall", "rtorrent");
879		eval("killall", "giftd");
880		eval("killall", "dmathined");
881		eval("killall", "dms");
882		eval("killall", "-SIGKILL", "nmbd");
883		eval("killall", "-SIGKILL", "smbd");
884		eval("killall", "-SIGKILL", "vsftpd");
885#endif // DLM
886		eval("rmmod", "sr_mod");
887		eval("rmmod", "cdrom");
888		eval("rmmod", "usb-storage");
889		eval("rmmod", "sd_mod");
890		eval("rmmod", "scsi_mod");
891	}
892#endif // MASSSTORAGE_SUPPORT
893
894#ifdef PRINTER_SUPPORT
895	eval("killall", "lpd");
896	eval("rmmod", "printer");
897#ifdef PARPORT_SUPPORT
898	eval("rmmod", "lp.o");
899	eval("rmmod", "parport_splink.o");
900	eval("rmmod", "parport.o");
901#endif // PARPORT_SUPPORT
902#endif // PRINTER_SUPPORT
903
904#ifdef AUDIO_SUPPORT
905	eval("rmmod", "audio");
906	eval("rmmod", "soundcore");
907	stop_audio();
908#endif // AUDIO_SUPPORT
909
910#ifdef WEBCAM_SUPPORT
911	if (nvram_invmatch("usb_webenable_x", "0"))
912	{
913		stop_rcamd();
914		eval("killall", "rcamd");
915		eval("killall", "sendmail");
916		eval("rmmod", "pwc");
917		eval("rmmod", "ov511_decomp");
918		eval("rmmod", "ov518_decomp");
919		eval("rmmod", "ov51x");
920		eval("rmmod", "i2c-core");
921		eval("rmmod", "videodev");
922	}
923#endif // WEBCAM_SUPPORT
924
925#ifdef CDMA // HSDPA
926	eval("rmmod", "acm");
927#endif // CDMA // HSDPA
928
929	eval("rmmod", "ehci-hcd");
930	eval("rmmod", "usb-ohci");
931	eval("rmmod", "usbcore");
932
933	return 0;	// 2007.11 James.
934}
935
936void start_script(int *new_disc)	// added by Jiahao for WL500gP
937{
938	char nvram_str[32];
939	int i=0;
940#ifdef DLM
941	char run_path[64];
942	char runbuf[256];
943	int run_count=0;
944#endif // DLM
945#ifdef WCN
946	char run_path_wcn[64];
947	int disc_index=0;
948	int j=0;
949	int wcn_count=0;
950#endif // WCN
951
952	for(i=0;i<2;i++)
953	{
954		if ( *(new_disc+i)==1 )
955		{
956#ifdef DLM
957			memset(nvram_str, 0, sizeof(nvram_str));
958			sprintf(nvram_str, "usb_disc%d_path0", i);
959			memset(run_path, 0, sizeof(run_path));
960			strcpy(run_path, nvram_safe_get(nvram_str));
961#endif // DLM
962
963#ifdef WCN
964			memset(run_path_wcn, 0, sizeof(run_path_wcn));
965			sprintf(nvram_str, "usb_disc%d_index", i);
966			disc_index=atoi(nvram_safe_get(nvram_str));
967			for (j=0; j<disc_index; j++)
968			{
969				sprintf(nvram_str, "usb_disc%d_path%d", i, j);
970				sprintf(run_path_wcn, "%s/smrtntky/wsetting.wfc", nvram_safe_get(nvram_str));
971				if (check_if_file_exist(run_path_wcn)==1)
972				{
973					memset(run_path_wcn, 0, sizeof(run_path_wcn));
974					strcpy(run_path_wcn, nvram_safe_get(nvram_str));
975					wcn_count++;
976					break;
977				}
978				else
979					memset(run_path_wcn, 0, sizeof(run_path_wcn));
980			}
981#endif // WCN
982		}
983		else
984			continue;
985#ifdef WCN
986		if (wcn_count==1 && nvram_invmatch("wsc_config_state", "1") &&
987		    !nvram_match("x_Setting", "1"))/* Cherry Cho modified in 2007/4/13. */
988			wfc_parser(run_path_wcn);
989#endif // WCN
990#ifdef DLM
991		if (strcmp(run_path, "")!=0)
992		{
993			if (strlen(nvram_safe_get("run_prog"))==0)
994				continue;
995
996			memset(runbuf, 0, sizeof(runbuf));
997			sprintf(runbuf, "%s/%s", run_path, nvram_safe_get("run_prog"));
998			if (check_if_file_exist(runbuf)==1 && run_count==0)
999			{
1000				run_count++;
1001				logmessage("USB storage", "execute the user specified script");
1002				eval(runbuf);
1003			}
1004		}
1005#endif // DLM
1006	}
1007}
1008
1009#ifdef DLM
1010void write_ftpd_conf()
1011{
1012	FILE *fp;
1013	char user[64], user1[64], password[64], path[64];
1014	char tmpstr[64];
1015	char rright[384], wright[384], maxuser[16];
1016	int snum, unum, i, j;
1017	char *test_path=(char *)malloc(64);
1018	char *tmp1=NULL;
1019	char root_path[64];
1020
1021	/* write /etc/vsftpd.conf */
1022	fp=fopen("/tmp/vsftpd.conf", "w");
1023	if (fp==NULL) return;
1024// 2007.11 James {
1025	// new vsftpd
1026	if(nvram_match("st_ftp_mode", "2"))
1027		fprintf(fp, "anonymous_enable=NO\n");
1028	else{
1029		fprintf(fp, "anonymous_enable=YES\n");
1030		fprintf(fp, "anon_upload_enable=YES\n");
1031		fprintf(fp, "anon_mkdir_write_enable=YES\n");
1032		fprintf(fp, "anon_other_write_enable=YES\n");
1033	}
1034	
1035	// old vsftpd
1036	/*fprintf(fp, "anonymous_enable=YES\n");
1037	fprintf(fp, "anon_upload_enable=YES\n");
1038	fprintf(fp, "anon_mkdir_write_enable=YES\n");
1039	fprintf(fp, "anon_other_write_enable=YES\n");//*/
1040// 2007.11 James }
1041	fprintf(fp, "nopriv_user=root\n");
1042	fprintf(fp, "write_enable=YES\n");
1043	fprintf(fp, "local_enable=YES\n");
1044	fprintf(fp, "chroot_local_user=YES\n");
1045	fprintf(fp, "local_umask=000\n");
1046	fprintf(fp, "dirmessage_enable=NO\n");
1047	fprintf(fp, "xferlog_enable=NO\n");
1048	fprintf(fp, "syslog_enable=NO\n");
1049	fprintf(fp, "connect_from_port_20=YES\n");
1050	fprintf(fp, "listen=YES\n");
1051	fprintf(fp, "pasv_enable=YES\n");
1052	fprintf(fp, "ssl_enable=NO\n");
1053	fprintf(fp, "tcp_wrappers=NO\n");
1054	strcpy(maxuser, nvram_safe_get("st_max_user"));
1055	fprintf(fp, "max_clients=%s\n", maxuser);
1056	fprintf(fp, "ftp_username=anonymous\n");
1057	fprintf(fp, "ftpd_banner=Welcome to the %s FTP service.\n", nvram_safe_get("computer_name"));//2006_07_03_Roly modify WL500gp to WL500W
1058//#ifdef LANGUAGE_TW
1059	fprintf(fp, "enable_iconv=YES\n");
1060	if(nvram_match("ftp_lang", "TW")){
1061		fprintf(fp, "remote_charset=cp950\n");
1062	}
1063	else if(nvram_match("ftp_lang", "CN")){
1064		fprintf(fp, "remote_charset=cp936\n");
1065	}
1066	/*else if(nvram_match("ftp_lang", "KR")){
1067		fprintf(fp, "remote_charset=cp949\n");
1068	}//*/
1069//#endif
1070// 2008.04 James. {
1071/*#ifdef LANGUAGE_KR
1072	fprintf(fp, "enable_iconv=YES\n");
1073	fprintf(fp, "remote_charset=cp949\n");
1074#endif
1075#ifdef LANGUAGE_JP
1076	fprintf(fp, "enable_iconv=YES\n");
1077	fprintf(fp, "remote_charset=cp932\n");
1078#endif//*/
1079	/*else if(nvram_match("ftp_lang", "JP")){
1080		fprintf(fp, "remote_charset=cp932\n");
1081	}//*/
1082// 2008.04 James. }
1083	fclose(fp);
1084
1085	get_first_partition(test_path);
1086	nvram_set("first_partition", test_path);
1087	free(test_path);
1088}
1089
1090int
1091start_ftpd()	// added by Jiahao for WL500gP
1092{
1093	int ret=0;
1094	
1095	//if (nvram_match("st_ftp_modex", "0")) return 0;
1096
1097	//eval("killall", "-SIGKILL", "vsftpd");
1098	stop_ftp();	// 2007.10 James.
1099	write_ftpd_conf();
1100
1101	//if (nvram_match("st_ftp_modex", "1"))
1102	if(nvram_match("st_ftp_mode", "1"))	// 2007.10 James
1103		//printf("ftp mode: login to first partition\n");
1104		printf("ftp mode: anonymous login...\n");	// 2007.11 James.
1105	//else if (nvram_match("st_ftp_modex", "2"))
1106	else if(nvram_match("st_ftp_mode", "2"))	// 2007.10 James
1107		//printf("ftp mode: login to first matched shared node\n");
1108		printf("ftp mode: account login...\n");	// 2007.11 James.
1109	
1110	// Can't use eval() here
1111	ret=system("/sbin/vsftpd&");	// 2007.10 James. chang the absolute path.
1112	if(!ret)
1113	{
1114		logmessage("FTP Server", "daemon is started");
1115		return 0;
1116	}
1117	else
1118		return 1;
1119}
1120
1121int
1122test_user(char *target, char *pattern)	// added by Jiahao for WL500gP
1123{
1124	char s[384];
1125	char p[32];
1126	char *start;
1127	char *pp;
1128	strcpy(s, target);
1129	strcpy(p, pattern);
1130	start = s;
1131	while (pp=strchr(start, ';'))
1132	{
1133		*pp='\0';
1134		if(! strcmp(start, p))
1135			return 1;
1136		start=pp+1;
1137	}
1138	return 0;
1139}
1140#endif // DLM
1141
1142#ifdef WEBCAM_SUPPORT
1143int
1144hotplug_usb_webcam(char *product, int webflag)
1145{
1146	char *rcamd_argv[]={"rcamd", 
1147				"-p", nvram_safe_get("usb_webactivex_x"),
1148				"-s", "0",
1149				"-z", nvram_safe_get("time_zone_x"),
1150				"-a", nvram_safe_get("usb_websecurity_x"),
1151				NULL, NULL,	// Model -t
1152				NULL, NULL,	// Record Time -r
1153				NULL, NULL, 	// Image Size -f
1154				NULL, NULL, 	// Sense Vlaue -m 
1155				NULL, NULL, 	// Sense Limit -c
1156				NULL, NULL,
1157				NULL};
1158	char **arg;
1159	pid_t pid;
1160
1161	if (nvram_match("usb_webenable_x", "0") || strlen(product)==0 || webflag==0) return;
1162	for (arg = rcamd_argv; *arg; arg++);
1163	
1164	if (webflag == WEB_PWCWEB)
1165	{
1166		eval("insmod", "pwc.o", "power_save=0");
1167		nvram_set("usb_webdriver_x", "0");
1168
1169		*arg++ = "-t";
1170		*arg++ = "0";
1171	}
1172	else
1173	{
1174		eval("insmod", "i2c-core.o");
1175		eval("insmod", "ov51x.o");
1176		eval("insmod", "ov511_decomp.o");
1177		eval("insmod", "ov518_decomp.o");
1178		nvram_set("usb_webdriver_x", "1");
1179
1180		if (strstr(product, "8519"))
1181		{
1182			*arg++ = "-t";
1183			*arg++ = "2";
1184		}
1185		else
1186		{			
1187			*arg++ = "-t";
1188			*arg++ = "1";
1189		}
1190	}
1191
1192	// start web cam
1193	if (nvram_match("usb_webmode_x", "0")) // ActiveX only
1194	{
1195		*arg++ = "-r";
1196		*arg++ = "60";
1197	}
1198	else 
1199	{
1200		*arg++ = "-r";
1201		*arg++ = "0";
1202	}
1203		
1204	// image size
1205	if (nvram_match("usb_webimage_x", "0"))
1206	{
1207		*arg++ = "-f";
1208		if (webflag==WEB_PWCWEB) *arg++="320x240";
1209		else *arg++="640x480";
1210	}
1211	else if (nvram_match("usb_webimage_x", "1"))
1212	{
1213		*arg++ = "-f";
1214		*arg++="320x240";
1215	}
1216	else if (nvram_match("usb_webimage_x", "2"))
1217	{
1218		*arg++ = "-f";
1219		if (webflag==WEB_PWCWEB) *arg++="160x120";
1220		else *arg++="176x144";
1221	}
1222	else
1223	{
1224		*arg++ = "-f";
1225		*arg++ = "80x60";
1226	}
1227
1228
1229	if (nvram_match("usb_websense_x", "0"))
1230	{	
1231		*arg++ = "-m";
1232		*arg++ = "150";
1233		*arg++ = "-c";
1234		*arg++ = "100";
1235	}
1236	else if (nvram_match("usb_websense_x", "1"))
1237	{
1238		*arg++ = "-m";
1239		*arg++ = "100";
1240		*arg++ = "-c";
1241		*arg++ = "100";
1242	}
1243	else
1244	{	
1245		*arg++ = "-m";
1246		*arg++ = "50";
1247		*arg++ = "-c";
1248		*arg++ = "100";
1249	}
1250	
1251
1252	//*arg++="-d";
1253	//*arg++="7";
1254	mkdir("/tmp/webcam", 0777);	
1255	chdir("/tmp/webcam");
1256
1257	symlink("/www/Advanced_ShowTime_Widzard.asp", "/tmp/webcam/index.asp");
1258	symlink("/www/Advanced_ShowTime_Widzard.asp", "/tmp/webcam/ShowWebCam.asp");
1259	symlink("/www/ShowWebCamPic.asp", "/tmp/webcam/ShowWebCamPic.asp");
1260	symlink("/www/graph", "/tmp/webcam/graph");
1261	symlink("/www/general.js", "/tmp/webcam/general.js");
1262	symlink("/www/overlib.js", "/tmp/webcam/overlib.js");
1263	symlink("/www/style.css", "/tmp/webcam/style.css");
1264	symlink("/www/netcam_mfc_activeX.cab", "/tmp/webcam/netcam_mfc_activeX.cab");
1265	symlink("/var/tmp/display.jpg", "/tmp/webcam/display.jpg");
1266
1267	//char *httpd_argv[]={"httpd", 
1268	//			nvram_safe_get("wan0_ifname"), 
1269	//			nvram_safe_get("usb_webhttpport_x"),
1270	//			NULL};
1271	//_eval(httpd_argv, NULL, 0, &pid);
1272	eval("httpd", nvram_safe_get("wan0_ifname"), nvram_safe_get("usb_webhttpport_x"));
1273	chdir("/");
1274	_eval(rcamd_argv, ">/dev/null", 0, NULL);
1275
1276	return 0;
1277}
1278
1279int
1280remove_webcam_main(int webflag)
1281{
1282	if (webflag == WEB_PWCWEB)
1283	{
1284		eval("rmmod", "pwc");
1285	}
1286	else
1287	{
1288		eval("rmmod", "i2c-core");
1289		eval("rmmod", "ov511_decomp");
1290		eval("rmmod", "ov518_decomp");
1291		eval("rmmod", "ov51x");
1292	}
1293	nvram_set("usb_webdriver_x", "");
1294	return 0;
1295}
1296
1297
1298int
1299remove_usb_webcam(char *product, int webflag)
1300{
1301	char pidfile[32];
1302	sprintf(pidfile, "/var/run/httpd-%s.pid", nvram_safe_get("usb_webhttpport_x"));
1303
1304	kill_pidfile(pidfile);
1305	kill_pidfile("/var/run/rcamd.pid");
1306
1307	if (webflag == WEB_PWCWEB)
1308	{
1309		eval("rmmod", "pwc");
1310	}
1311	else
1312	{
1313		eval("rmmod", "i2c-core");
1314		eval("rmmod", "ov511_decomp");
1315		eval("rmmod", "ov518_decomp");
1316		eval("rmmod", "ov51x");
1317	}
1318	nvram_set("usb_webdriver_x", "");
1319
1320	return 0;
1321}
1322
1323
1324int
1325start_rcamd(void)
1326{
1327	char *rcamd_argv[] = {"rcamdmain", NULL};
1328	pid_t pid;
1329
1330	_eval(rcamd_argv, NULL, 0, &pid);
1331	return 0;
1332}
1333
1334int
1335stop_rcamd(void)
1336{
1337	int ret = eval("killall", "rcamdmain");
1338	return ret;	// 2007.11 James.
1339}
1340#endif // WEBCAM_SUPPORT
1341
1342/* remove usb mass storage */
1343int
1344remove_usb_mass(char *product)
1345{
1346	nvram_set("usb_storage_device_remove", "");	// 2007.12 James.
1347	
1348// 2007.12 James {
1349#ifdef DLM
1350	char *message;
1351	unsigned int len = 0;
1352	int result = 0;
1353	
1354printf("\n*** start to umount disk! ***\n");
1355// 2008.06 James. {
1356	umount_disc_parts_rc(1);
1357	umount_disc_parts_rc(2);
1358	
1359	nvram_set("usb_disc0_pid", "");
1360	nvram_set("usb_disc0_safely_removed", "0");
1361	nvram_set("usb_disc1_pid", "");
1362	nvram_set("usb_disc1_safely_removed", "0");
1363// 2008.06 James. }
1364	
1365	sync();	// 2008.04 James.
1366	
1367	result = eval("rmmod", "cdrom");
1368	
1369printf("\n*** start to rmmod usb-storage! ***\n");
1370	//result = system("rmmod usb-storage");
1371	result = eval("/sbin/rmmod", "usb-storage");	// 2008.04 James.
1372	
1373printf("\n*** start to insmod usb-storage! ***\n");
1374	//result = system("insmod usb-storage");
1375	result = eval("/sbin/insmod", "usb-storage");	// 2008.04 James.
1376	
1377	result = eval("/sbin/insmod", "cdrom");
1378	
1379printf("\n*** start to mount the plugged disk! ***\n");
1380	if((strlen(nvram_safe_get("usb_disc0_port")) > 0 && strcmp(nvram_safe_get("usb_disc0_safely_removed"), "1"))
1381			|| (strlen(nvram_safe_get("usb_disc1_port")) > 0 && strcmp(nvram_safe_get("usb_disc1_safely_removed"), "1"))
1382			)
1383		hotplug_usb_mass("");
1384#endif // DLM
1385// 2007.12 James }
1386	return 0;
1387}
1388
1389int
1390remove_storage_main(void)
1391{
1392	remove_usb_mass(NULL);
1393	return 0;
1394}
1395
1396#define MOUNT_VAL_FAIL 	0
1397#define MOUNT_VAL_RONLY	1
1398#define MOUNT_VAL_RW 	2
1399
1400int
1401mount_r(char *usb_part, char *usb_file_part)
1402{
1403	char msg[64];
1404// 2007.12 James {
1405	if(!mount(usb_part, usb_file_part, "ext3", MS_SYNCHRONOUS, NULL)) 
1406	{
1407		chmod(usb_file_part, 0777);
1408		sprintf(msg, "ext3 fs mounted to %s\n", usb_file_part);		
1409		logmessage("USB storage", msg);
1410		printf("ext3 fs mounted to %s\n", usb_file_part);
1411		eval("/sbin/test_of_var_files_in_mount_path", usb_file_part);
1412		return MOUNT_VAL_RW;
1413	}
1414// 2007.12 James }
1415	if(!mount(usb_part, usb_file_part, "ext2", MS_SYNCHRONOUS, NULL)) 
1416	{
1417		chmod(usb_file_part, 0777);
1418		sprintf(msg, "ext2 fs mounted to %s\n", usb_file_part);		
1419#ifdef DLM
1420		logmessage("USB storage", msg);
1421#endif // DLM
1422		printf("ext2 fs mounted to %s\n", usb_file_part);
1423		eval("/sbin/test_of_var_files_in_mount_path", usb_file_part);	// 2007.12. James.
1424		return MOUNT_VAL_RW;
1425	}
1426/*	marked by Jiahao for WL500gP
1427#ifdef LANGUAGE_EN
1428	if(!mount(usb_part, usb_file_part, "vfat", MS_SYNCHRONOUS, NULL)) 
1429	{
1430		sprintf(msg, "vfat fs mounted to %s\n", usb_file_part);		
1431		logmessage("USB storage", msg);
1432		printf("vfat fs mounted to %s\n", usb_file_part);
1433		return MOUNT_VAL_RW;
1434	}
1435#endif
1436#ifdef LANGUAGE_TW
1437	if(!mount(usb_part, usb_file_part, "vfat", MS_SYNCHRONOUS, "codepage=950,iocharset=cp950")) 
1438	{
1439		umask(0022);
1440		sprintf(msg, "vfat fs mounted to %s\n", usb_file_part);		
1441		logmessage("USB storage", msg);
1442		printf("vfat fs mounted to %s\n", usb_file_part);
1443		return MOUNT_VAL_RW;
1444	}
1445#endif
1446#ifdef LANGUAGE_CN
1447	if(!mount(usb_part, usb_file_part, "vfat", MS_SYNCHRONOUS, "codepage=936,iocharset=cp936")) 
1448	{
1449		umask(0022);
1450		sprintf(msg, "vfat fs mounted to %s\n", usb_file_part);		
1451		logmessage("USB storage", msg);
1452		printf("vfat fs mounted to %s\n", usb_file_part);
1453		return MOUNT_VAL_RW;
1454	}
1455#endif
1456#ifdef LANGUAGE_KR
1457	if(!mount(usb_part, usb_file_part, "vfat", MS_SYNCHRONOUS, "codepage=949,iocharset=cp949")) 
1458	{
1459		umask(0022);
1460		sprintf(msg, "vfat fs mounted to %s\n", usb_file_part);		
1461		logmessage("USB storage", msg);
1462		printf("vfat fs mounted to %s\n", usb_file_part);
1463		return MOUNT_VAL_RW;
1464	}
1465#endif
1466#ifdef LANGUAGE_JP
1467	if(!mount(usb_part, usb_file_part, "vfat", MS_SYNCHRONOUS, "codepage=932,iocharset=cp932")) 
1468	{
1469		umask(0022);
1470		sprintf(msg, "vfat fs mounted to %s\n", usb_file_part);		
1471		logmessage("USB storage", msg);
1472		printf("vfat fs mounted to %s\n", usb_file_part);
1473		return MOUNT_VAL_RW;
1474	}
1475#endif
1476*/
1477	// added by Jiahao for WL500gP
1478	
1479	if(!mount(usb_part, usb_file_part, "vfat", MS_SYNCHRONOUS, "utf8=1,umask=0000,mode=0777")) 
1480	{
1481		sprintf(msg, "vfat fs mounted to %s\n", usb_file_part);		
1482#ifdef DLM
1483		logmessage("USB storage", msg);
1484#endif // DLM
1485		printf("vfat fs mounted to %s\n", usb_file_part);
1486		eval("/sbin/test_of_var_files_in_mount_path", usb_file_part);	// 2007.12. James.
1487		return MOUNT_VAL_RW;
1488	}
1489	if(!mount(usb_part, usb_file_part, "msdos", MS_SYNCHRONOUS, "utf8=1,umask=0000,mode=0777"))
1490	{
1491		sprintf(msg, "msdos fs mounted to %s\n", usb_file_part);	
1492#ifdef DLM
1493		logmessage("USB storage", msg);
1494#endif // DLM
1495		printf("msdoc fs mounted to %s\n", usb_file_part);
1496		eval("/sbin/test_of_var_files_in_mount_path", usb_file_part);	// 2007.12. James.
1497		return MOUNT_VAL_RW;
1498	}
1499	if(!mount(usb_part, usb_file_part, "ntfs", MS_SYNCHRONOUS, "utf8=1,umask=0000"))
1500	{
1501		sprintf(msg, "ntfs(ro) fs mounted to %s\n", usb_file_part);	
1502#ifdef DLM
1503		logmessage("USB storage", msg);
1504#endif // DLM
1505		printf("ntfs fs mounted to %s\n", usb_file_part);
1506		return MOUNT_VAL_RONLY;
1507	}
1508/*	marked by Jiahao for WL500gP
1509#ifdef LANGUAGE_EN
1510	if(!mount(usb_part, usb_file_part, "ntfs", MS_SYNCHRONOUS, NULL))
1511	{
1512		sprintf(msg, "ntfs(ro) fs mounted to %s\n", usb_file_part);	
1513		logmessage("USB storage", msg);
1514		printf("ntfs fs mounted to %s\n", usb_file_part);
1515		return MOUNT_VAL_RONLY;
1516	}
1517#endif
1518#ifdef LANGUAGE_TW
1519	if(!mount(usb_part, usb_file_part, "ntfs", MS_SYNCHRONOUS, "iocharset=cp932"))
1520	{
1521		sprintf(msg, "ntfs(ro) fs mounted to %s\n", usb_file_part);	
1522		logmessage("USB storage", msg);
1523		printf("ntfs fs mounted to %s\n", usb_file_part);
1524		return MOUNT_VAL_RONLY;
1525	}
1526#endif
1527#ifdef LANGUAGE_CN
1528	if(!mount(usb_part, usb_file_part, "ntfs", MS_SYNCHRONOUS, "iocharset=cp936"))
1529	{
1530		sprintf(msg, "ntfs(ro) fs mounted to %s\n", usb_file_part);	
1531		logmessage("USB storage", msg);
1532		printf("ntfs fs mounted to %s\n", usb_file_part);
1533		return MOUNT_VAL_RONLY;
1534	}
1535#endif
1536#ifdef LANGUAGE_KR
1537	if(!mount(usb_part, usb_file_part, "ntfs", MS_SYNCHRONOUS, "iocharset=cp949"))
1538	{
1539		sprintf(msg, "ntfs(ro) fs mounted to %s\n", usb_file_part);	
1540		logmessage("USB storage", msg);
1541		printf("ntfs fs mounted to %s\n", usb_file_part);
1542		return MOUNT_VAL_RONLY;
1543	}
1544#endif
1545#ifdef LANGUAGE_JP
1546	if(!mount(usb_part, usb_file_part, "ntfs", MS_SYNCHRONOUS, "iocharset=cp950"))
1547	{
1548		sprintf(msg, "ntfs(ro) fs mounted to %s\n", usb_file_part);	
1549		logmessage("USB storage", msg);
1550		printf("ntfs fs mounted to %s\n", usb_file_part);
1551		return MOUNT_VAL_RONLY;
1552	}
1553#endif
1554*/
1555	return MOUNT_VAL_FAIL;
1556}
1557
1558#ifdef DLM
1559int calc_crc32( const char *fname, unsigned long *crc ) {
1560    FILE *in;           /* input file */
1561    unsigned char buf[BUFSIZ]; /* pointer to the input buffer */
1562    size_t i, j;        /* buffer positions*/
1563    int k;              /* generic integer */
1564    unsigned long tmpcrc=0xFFFFFFFF;
1565
1566    /* open file */
1567    if((in = fopen(fname, "rb")) == NULL) return -1;
1568
1569    /* loop through the file and calculate CRC */
1570    while( (i=fread(buf, 1, BUFSIZ, in)) != 0 ){
1571        for(j=0; j<i; j++){
1572            k=(tmpcrc ^ buf[j]) & 0x000000FFL;
1573            tmpcrc=((tmpcrc >> 8) & 0x00FFFFFFL) ^ crcs[k];
1574        }
1575    }
1576    fclose(in);
1577    *crc=~tmpcrc; /* postconditioning */
1578    return 0;
1579}
1580
1581// judge if the existed application files are correct.
1582int
1583ckeck_apps_completeness(const char *dirname)
1584{
1585	FILE *fp=NULL;
1586	FILE *fp2=NULL;
1587	char line[256];
1588	char line2[256];
1589	char listfilename[64]="/apps/list";
1590	char crcfilename[64]="/apps/crc";
1591	char appsdir[64];
1592	char tmp[256];
1593	char crc_str[9];
1594	unsigned long crc;
1595	
1596	memset(appsdir, 0, sizeof(appsdir));
1597	sprintf(appsdir, "%s%s", dirname, "/.apps");
1598
1599	if ((fp=fopen(listfilename, "r"))==NULL)
1600	{
1601		printf("Cannot find %s.\n", listfilename);
1602		printf("Make sure it's available.\n");
1603		return 0;
1604	}
1605	
1606	if ((fp2=fopen(crcfilename, "r"))==NULL)
1607	{
1608		printf("Cannot find %s.\n", crcfilename);
1609		printf("Make sure it's available.\n");
1610		fclose(fp);
1611		return 0;
1612	}
1613	
1614	printf("starting to check apps files.\n");
1615	while (!feof(fp))
1616	{
1617		if (fgets(line,sizeof(line),fp)==NULL) break;	/* end-of-file */
1618		if (strlen(line)<3) continue;			/* line empty */
1619
1620		memset(tmp, 0, sizeof(tmp));
1621		sprintf(tmp, "%s%s", appsdir, line+1);		/* file path */
1622		tmp[strlen(tmp)-1]='\0';
1623		printf("FILE: %s\n", tmp);
1624		if(calc_crc32(tmp, &crc) != 0)
1625		{
1626			printf("Error reading file %s.\n", tmp);
1627			sprintf(tmp, "rm -rf %s", appsdir);
1628			system(tmp);
1629			fclose(fp);
1630			fclose(fp2);
1631			return 0;
1632		}
1633		
1634		if (fgets(line2,sizeof(line2),fp2)==NULL)
1635		{
1636			sprintf(tmp, "rm -rf %s", appsdir);
1637			system(tmp);
1638			fclose(fp);
1639			fclose(fp2);
1640			return 0;
1641		}
1642		memset(crc_str, 0, sizeof(crc_str));
1643		sprintf(crc_str, "%08lX", crc);
1644		printf("CRC32 now: %s\n", crc_str);
1645
1646		line2[strlen(line2)-1]='\0';
1647		printf("CRC32 org: %s\n", line2);
1648		
1649		if(strcmp(crc_str, line2)!=0)
1650		{
1651			sprintf(tmp, "rm -rf %s", appsdir);
1652			system(tmp);
1653			fclose(fp);
1654			fclose(fp2);
1655			return 0;
1656		}
1657	}
1658
1659	fclose(fp);
1660	fclose(fp2);
1661	return 1;
1662}
1663
1664// judge if there are application files.
1665int
1666ckeck_apps_completeness_pre(const char *dirname)
1667{
1668	FILE *fp=NULL;
1669	FILE *fp2=NULL;
1670	char line[256];
1671	char line2[256];
1672	char listfilename[64]="/apps/list";
1673	char crcfilename[64]="/apps/crc";
1674	char appsdir[64];
1675	char tmp[256];
1676	unsigned long crc;
1677	
1678	memset(appsdir, 0, sizeof(appsdir));
1679	sprintf(appsdir, "%s%s", dirname, "/.apps");
1680
1681	if ((fp=fopen(listfilename, "r"))==NULL)
1682	{
1683		printf("Cannot find %s.\n", listfilename);
1684		printf("Make sure it's available.\n");
1685		
1686		return 0;
1687	}
1688
1689	while (!feof(fp))
1690	{
1691		if (fgets(line,sizeof(line),fp)==NULL) break;	/* end-of-file */
1692		if (strlen(line)<3) continue;			/* line empty */
1693
1694		sprintf(tmp, "%s%s", appsdir, line+1);		/* file path */
1695		tmp[strlen(tmp)-1]='\0';
1696
1697		if((fp2 = fopen(tmp, "rb")) == NULL)
1698		{
1699			printf("Error reading file %s.\n", tmp);
1700			memset(tmp, 0, sizeof(tmp));
1701			sprintf(tmp, "rm -rf %s", appsdir);
1702			system(tmp);
1703			fclose(fp);
1704			
1705			return 0;
1706		}
1707		fclose(fp2);
1708	}
1709
1710	fclose(fp);
1711	
1712	return 1;
1713}
1714#endif // DLM
1715
1716#ifdef WCN
1717char ibuf2[8192];
1718
1719int
1720channels_in_country(char *abbrev, int channels[])
1721{
1722	int i, j, unit;
1723	wl_channels_in_country_t *cic = (wl_channels_in_country_t *)ibuf2;
1724	char tmp[100], prefix[] = "wlXXXXXXXXXX_";
1725	char *name;
1726	channel_info_t ci;
1727
1728	if ((unit = atoi(nvram_safe_get("wl_unit"))) < 0)
1729		return -1;
1730
1731	snprintf(prefix, sizeof(prefix), "wl%d_", unit);
1732	name = nvram_safe_get(strcat_r(prefix, "ifname", tmp));
1733
1734	i = 0;
1735	channels[i++] = 0;
1736	channels[i] = -1;
1737
1738	if (strlen(abbrev)==0) return 0;
1739
1740	cic->buflen = sizeof(ibuf2);
1741	strcpy(cic->country_abbrev, abbrev);
1742	cic->band = WLC_BAND_2G;
1743	cic->count = 0;
1744
1745	if (wl_ioctl(name, WLC_GET_CHANNELS_IN_COUNTRY, cic, cic->buflen) == 0)
1746	{
1747		if (cic->count == 0)
1748			return 0;
1749
1750		for(j = 0; j < cic->count; j++)
1751		{
1752			channels[i++] = cic->channel[j];
1753		}
1754
1755		channels[i] = -1;
1756	}
1757	return cic->count;
1758}
1759
1760int
1761channels_in_country_asus(char *abbrev, int channels[])
1762{
1763	int i, j;
1764	wl_channels_in_country_t *cic = (wl_channels_in_country_t *)ibuf2;
1765	char var[256], *next;
1766	int log_level, log_drop, log_accept;
1767
1768	i=0;
1769	
1770	if (nvram_match("wl_chan_list", "")) {
1771		for(i=0;i<14;i++)
1772		{
1773			channels[i] = i+1;
1774			channels[i+1] = -1;
1775		}	
1776	}
1777	else {
1778		foreach(var, nvram_safe_get("wl_chan_list"), next) {
1779			channels[i]=atoi(var);
1780			channels[i+1]=-1;
1781			i++;
1782		}
1783	}
1784	return i;
1785}
1786
1787int
1788get_wl_channels()
1789{
1790	int i, channels[32];
1791
1792	if (!channels_in_country(nvram_safe_get("wl_country_code"), channels))
1793	{
1794		channels_in_country_asus(nvram_safe_get("wl_country_code"), channels);
1795	}
1796
1797	i = 0;
1798	while(channels[i]!=-1)
1799		i++;
1800		
1801	return i-1;
1802}
1803
1804int parseXMLtext(char *dst, const char *src)
1805{
1806	char tmpstr[6];
1807	int len=0;
1808	int i=0;
1809	int dstlen=0;
1810
1811	memset(dst, 0, sizeof(dst));
1812	len=strlen(src);
1813
1814	for( i=0; i<len; i++ )
1815	{
1816		if ( (len-i)>=4 )
1817		{
1818			memset(tmpstr, 0, sizeof(tmpstr));
1819			memcpy(tmpstr, src+i, 4);
1820			if ( memcmp(tmpstr, "&gt;", 4)==0 )	// '>'
1821			{
1822				memset(dst+dstlen, 62, 1);
1823				dstlen++;
1824				i+=3;
1825				continue;
1826			}
1827			else if ( memcmp(tmpstr, "&lt;", 4)==0 )	// '<'
1828			{
1829				memset(dst+dstlen, 60, 1);
1830				dstlen++;
1831				i+=3;
1832				continue;
1833			}
1834		}
1835		if ( (len-i)>=5 )
1836		{
1837			memset(tmpstr, 0, sizeof(tmpstr));
1838			memcpy(tmpstr, src+i, 5);
1839			if ( memcmp(tmpstr, "&amp;", 5)==0 )	// '&'
1840			{
1841				memset(dst+dstlen, 38, 1);
1842				dstlen++;
1843				i+=4;
1844				continue;
1845			}
1846		}
1847		memset(dst+dstlen, src[i], 1);
1848		dstlen++;
1849	}
1850	dst[dstlen]=0;
1851	return dstlen;
1852}
1853
1854#define TYPE_configId 1
1855#define TYPE_configAuthorId 2
1856#define TYPE_configAuthor 3
1857#define TYPE_ssid 4
1858#define TYPE_connectionType 5
1859#define TYPE_authentication 6
1860#define TYPE_encryption 7
1861#define TYPE_networkKey 8
1862#define TYPE_keyProvidedAutomatically 9
1863#define TYPE_ieee802Dot1xEnabled 10
1864#define TYPE_eapMethod 11
1865#define TYPE_channel2Dot4 12
1866#define TYPE_channel5Dot0 13
1867#define TYPE_deviceMode 14
1868#define TYPE_timeToLive 15
1869#define TYPE_configHash 16
1870#define TYPE_keyIndex 17
1871
1872void
1873wfc_parser(const char *run_path)
1874{
1875//	if (nvram_invmatch("wcn_enable_x", "1"))
1876//		return;
1877
1878	if (strcmp(run_path, "")==0)
1879		return;
1880
1881	char *p_Value = NULL;
1882	int p_ValueLength = 0;
1883	int bufferLength = 0;
1884	char wfc_path[64];
1885	memset(wfc_path, 0, sizeof(wfc_path));
1886	sprintf(wfc_path, "%s/SMRTNTKY/WSETTING.WFC", run_path);
1887
1888	if (check_if_file_exist(wfc_path)==0)
1889		return;
1890
1891	char *buffer = ILibReadFileFromDisk(wfc_path, &bufferLength);
1892	int offset = 0;
1893	struct ILibXMLNode *xnode = ILibParseXML(buffer,offset,bufferLength);
1894	struct ILibXMLNode *root = xnode;
1895	int i=0;
1896	int t_configId=0;
1897	int t_configAuthorId=0;
1898	int t_configAuthor=0;
1899	int t_ssid=0;
1900	int t_connectionType=0;
1901	int t_authentication=0;
1902	int t_encryption=0;
1903	int t_networkKey=0;
1904	int t_keyProvidedAutomatically=0;
1905	int t_ieee802Dot1xEnabled=0;
1906	int t_eapMethod=0;
1907	int t_channel2Dot4=0;
1908	int t_channel5Dot0=0;
1909	int t_deviceMode=0;
1910	int t_timeToLive=0;
1911	int t_configHash=0;
1912	int t_keyIndex=0;
1913	int t_primaryProfile=0;
1914	int t_optionalProfile=0;
1915	int elementType=0;
1916	char str_configError[256+1];
1917	char str_configId[36+1];
1918	char str_configAuthorId[36+1];
1919	char str_configAuthor[128+1];
1920	char str_ssid[32*5+1];
1921	char str_connectionType[4+1];
1922	char str_authentication[8+1];
1923	char str_encryption[4+1];
1924	char str_networkKey[63*5+1];
1925	char str_keyProvidedAutomatically[1+1];
1926	char str_ieee802Dot1xEnabled[1+1];
1927	char str_eapMethod[17+1];
1928	char str_channel2Dot4[2+1];
1929	char str_channel5Dot0[3+1];
1930	char str_deviceMode[14+1];
1931	char str_timeToLive[5+1];
1932	char str_configHash[20+1];
1933	char str_keyIndex[1+1];
1934	long int long_temp=0;
1935	char **endptr=NULL;
1936	char tmpstr[3];
1937	char tmpstr2[27];
1938	char tmpstr3[32*3+1];
1939	int tmp=0;
1940	int tmp2=0;
1941	int wep_type=0;
1942	FILE *fp=NULL;
1943	char MACpostfix[8+1];
1944	char deviceCFG_path[64];
1945	int reboot_wcn=0;
1946
1947	memset(str_configError, 0, sizeof(str_configError));
1948	memset(str_configId, 0, sizeof(str_configId));
1949	memset(str_configAuthorId, 0, sizeof(str_configAuthorId));
1950	memset(str_configAuthor, 0, sizeof(str_configAuthor));
1951	memset(str_ssid, 0, sizeof(str_ssid));
1952	memset(str_connectionType, 0, sizeof(str_connectionType));
1953	memset(str_authentication, 0, sizeof(str_authentication));
1954	memset(str_encryption, 0, sizeof(str_encryption));
1955	memset(str_networkKey, 0, sizeof(str_networkKey));
1956	memset(str_keyProvidedAutomatically, 0, sizeof(str_keyProvidedAutomatically));
1957	memset(str_ieee802Dot1xEnabled, 0, sizeof(str_ieee802Dot1xEnabled));
1958	memset(str_eapMethod, 0, sizeof(str_eapMethod));
1959	memset(str_channel2Dot4, 0, sizeof(str_channel2Dot4));
1960	memset(str_channel5Dot0, 0, sizeof(str_channel5Dot0));
1961	memset(str_deviceMode, 0, sizeof(str_deviceMode));
1962	memset(str_timeToLive, 0, sizeof(str_timeToLive));
1963	memset(str_configHash, 0, sizeof(str_configHash));
1964	memset(str_keyIndex, 0, sizeof(str_keyIndex));
1965
1966	if(ILibProcessXMLNodeList(root)!=0)
1967	{
1968		/* The XML is not well formed! */
1969		strcpy(str_configError, "Invalid WCN-UFD XML");
1970		printf("%s\n", str_configError);
1971		logmessage("WCN-UFD", str_configError);
1972		goto end1;
1973	}
1974
1975	while(xnode!=NULL)
1976	{
1977		if( xnode->StartTag!=0 )
1978		{
1979			if(xnode->NameLength==8 && memcmp("configId", xnode->Name, xnode->NameLength)==0)
1980			// type="fc:str36"
1981			{
1982				elementType=TYPE_configId;
1983				if (++t_configId>1)
1984					goto end2;
1985			}
1986			else if(xnode->NameLength==14 && memcmp("configAuthorId", xnode->Name, xnode->NameLength)==0)
1987			// type="fc:str36"
1988			{
1989				elementType=TYPE_configAuthorId;
1990				if (++t_configAuthorId>1)
1991					goto end2;
1992			}
1993			else if(xnode->NameLength==12 && memcmp("configAuthor", xnode->Name, xnode->NameLength)==0)
1994			// type="fc:strMax128"
1995			{
1996				elementType=TYPE_configAuthor;
1997				if (++t_configAuthor>1)
1998					goto end2;
1999			}
2000			else if(xnode->NameLength==4 && memcmp("ssid", xnode->Name, xnode->NameLength)==0)
2001			// type="fc:strMax32"
2002			{
2003				elementType=TYPE_ssid;
2004				if (++t_ssid>1)
2005					goto end2;
2006			}
2007			else if(xnode->NameLength==14 && memcmp("connectionType", xnode->Name, xnode->NameLength)==0)
2008			// base="xs:string"
2009			{
2010				elementType=TYPE_connectionType;
2011				if (++t_connectionType>1)
2012					goto end2;
2013			}
2014			else if(xnode->NameLength==14 && memcmp("authentication", xnode->Name, xnode->NameLength)==0)
2015			// base="xs:string"
2016			{
2017				elementType=TYPE_authentication;
2018				if (++t_authentication>1)
2019					goto end2;
2020			}
2021			else if(xnode->NameLength==10 && memcmp("encryption", xnode->Name, xnode->NameLength)==0)
2022			// base="xs:string"
2023			{
2024				elementType=TYPE_encryption;
2025				if (++t_encryption>1)
2026					goto end2;
2027			}
2028			else if(xnode->NameLength==10 && memcmp("networkKey", xnode->Name, xnode->NameLength)==0)
2029			// type="fc:strMin5Max64"
2030			{
2031				elementType=TYPE_networkKey;
2032				if (++t_networkKey>1)
2033					goto end2;
2034			}
2035			else if(xnode->NameLength==24 && memcmp("keyProvidedAutomatically", xnode->Name, xnode->NameLength)==0)
2036			// type="xs:boolean"
2037			{
2038				elementType=TYPE_keyProvidedAutomatically;
2039				if (++t_keyProvidedAutomatically>1)
2040					goto end2;
2041			}
2042			else if(xnode->NameLength==19 && memcmp("ieee802Dot1xEnabled", xnode->Name, xnode->NameLength)==0)
2043			// type="xs:boolean"
2044			{
2045				elementType=TYPE_ieee802Dot1xEnabled;
2046				if (++t_ieee802Dot1xEnabled>1)
2047					goto end2;
2048			}
2049			/*
2050			The following elements are included in the schema but are not supported in the Windows XP SP2 release of the wizard.
2051			*/
2052			else if(xnode->NameLength==9 && memcmp("eapMethod", xnode->Name, xnode->NameLength)==0)
2053			// base="xs:string"
2054			{
2055				elementType=TYPE_eapMethod;
2056				if (++t_eapMethod>1)
2057					goto end2;
2058			}
2059			else if(xnode->NameLength==12 && memcmp("channel2Dot4", xnode->Name, xnode->NameLength)==0)
2060			// type="xs:positiveInteger"
2061			{
2062				elementType=TYPE_channel2Dot4;
2063				if (++t_channel2Dot4>1)
2064					goto end2;
2065			}
2066			else if(xnode->NameLength==12 && memcmp("channel5Dot0", xnode->Name, xnode->NameLength)==0)
2067			// type="xs:positiveInteger"
2068			{
2069				elementType=TYPE_channel5Dot0;
2070				if (++t_channel5Dot0>1)
2071					goto end2;
2072			}
2073			else if(xnode->NameLength==10 && memcmp("deviceMode", xnode->Name, xnode->NameLength)==0)
2074			// base="xs:string"
2075			{
2076				elementType=TYPE_deviceMode;
2077				if (++t_deviceMode>1)
2078					goto end2;
2079			}
2080			else if(xnode->NameLength==10 && memcmp("timeToLive", xnode->Name, xnode->NameLength)==0)
2081			// type="xs:positiveInteger"
2082			{
2083				elementType=TYPE_timeToLive;
2084				if (++t_timeToLive>1)
2085					goto end2;
2086			}
2087			else if(xnode->NameLength==10 && memcmp("configHash", xnode->Name, xnode->NameLength)==0)
2088			// type="fc:str20"
2089			{
2090				elementType=TYPE_configHash;
2091				if (++t_configHash>1)
2092					goto end2;
2093			}
2094			else if(xnode->NameLength==8 && memcmp("keyIndex", xnode->Name, xnode->NameLength)==0)
2095			// type="xs:positiveInteger"
2096			{
2097				elementType=TYPE_keyIndex;
2098				if (++t_keyIndex>1)
2099					goto end2;
2100			}
2101			else if(xnode->NameLength==14 && memcmp("primaryProfile", xnode->Name, xnode->NameLength)==0)
2102			// type="fc:profileInstance"
2103			{
2104				if (++t_primaryProfile>1)
2105					goto end2;
2106				else
2107					goto next_loop;
2108			}
2109			else if(xnode->NameLength==15 && memcmp("optionalProfile", xnode->Name, xnode->NameLength)==0)
2110			// type="fc:profileInstance"
2111			{
2112				if (++t_optionalProfile>32)
2113					goto end2;
2114				else
2115					goto next_loop;
2116			}
2117			else
2118			{
2119				goto next_loop;
2120			}
2121
2122//			printf("%d\n", ++i);
2123			xnode->Name[xnode->NameLength]=0;
2124			printf("Name: %s\n", xnode->Name);
2125			p_ValueLength = ILibReadInnerXML(xnode,&p_Value);
2126			p_Value[p_ValueLength]=0;
2127			printf("Value %s\n\n", p_Value);
2128
2129			if (elementType==TYPE_configId)
2130			{
2131				if (p_ValueLength!=36)
2132					goto end2;
2133
2134   				for( i=0; i<p_ValueLength; i++ )
2135         				if( p_Value[i]<' ' || p_Value[i] >'~') 
2136         					goto end2;
2137
2138				if (strcasecmp(nvram_safe_get("wl_configId"), p_Value)==0)
2139				{
2140					printf("have been configured using this WCN-UFD configuration file already\n");
2141					logmessage("WCN-UFD", "have been configured using this WCN-UFD configuration file already");
2142					goto end0;
2143				}
2144
2145				strcpy(str_configId, p_Value);
2146			}
2147			else if (elementType==TYPE_configAuthorId)
2148			{
2149				if (p_ValueLength!=36)
2150					goto end2;
2151
2152   				for( i=0; i<p_ValueLength; i++ )
2153         				if( p_Value[i]<' ' || p_Value[i] >'~') 
2154         					goto end2;
2155
2156				strcpy(str_configAuthorId, p_Value);
2157			}
2158			else if (elementType==TYPE_configAuthor)
2159			{
2160				if (p_ValueLength>128 || p_ValueLength==0)
2161					goto end2;
2162
2163   				for( i=0; i<p_ValueLength; i++ )
2164         				if( p_Value[i]<' ' || p_Value[i] >'~') 
2165         					goto end2;
2166
2167				strcpy(str_configAuthor, p_Value);
2168			}
2169			else if (elementType==TYPE_ssid)
2170			{
2171				if (p_ValueLength>32*5 || p_ValueLength==0)
2172					goto end2;
2173
2174   				for( i=0; i<p_ValueLength; i++ )
2175         				if( p_Value[i]<' ' || p_Value[i] >'~') 
2176         					goto end2;
2177
2178				tmp=parseXMLtext(tmpstr3, p_Value);
2179				if (tmp>32 || tmp==0)
2180					goto end2;
2181
2182				strcpy(str_ssid, tmpstr3);
2183			}
2184
2185			else if (elementType==TYPE_connectionType)
2186			{
2187				if (p_ValueLength==4 && strncasecmp("IBSS", p_Value, 4)==0)
2188					strcpy(str_connectionType, "IBSS");
2189				else if (p_ValueLength==3 && strncasecmp("ESS", p_Value, 3)==0)
2190					strcpy(str_connectionType, "ESS");
2191				else
2192					goto end2;
2193			}
2194			else if (elementType==TYPE_authentication)
2195			{
2196				if (p_ValueLength==4 && strncasecmp("open", p_Value, 4)==0)
2197					strcpy(str_authentication, "open");
2198				else if (p_ValueLength==6 && strncasecmp("shared", p_Value, 6)==0)
2199					strcpy(str_authentication, "shared");
2200				else if (p_ValueLength==8 && strncasecmp("WPA-NONE", p_Value, 8)==0)
2201				{
2202//					strcpy(str_authentication, "WPA-NONE");
2203					printf("aaa\n");
2204					goto end3;
2205				}
2206				else if (p_ValueLength==3 && strncasecmp("WPA", p_Value, 3)==0)
2207					strcpy(str_authentication, "WPA");
2208				else if (p_ValueLength==6 && strncasecmp("WPAPSK", p_Value, 6)==0)
2209					strcpy(str_authentication, "WPAPSK");
2210				else if (p_ValueLength==4 && strncasecmp("WPA2", p_Value, 4)==0)
2211					strcpy(str_authentication, "WPA2");
2212				else if (p_ValueLength==7 && strncasecmp("WPA2PSK", p_Value, 7)==0)
2213					strcpy(str_authentication, "WPA2PSK");
2214				else
2215					goto end2;
2216			}
2217			else if (elementType==TYPE_encryption)
2218			{
2219				if (	p_ValueLength!=3 &&
2220					p_ValueLength!=4
2221				   )
2222					goto end2;
2223					
2224				if (p_ValueLength==4 && strncasecmp("none", p_Value, 4)==0)
2225					strcpy(str_encryption, "none");
2226				else if (p_ValueLength==3 && strncasecmp("WEP", p_Value, 3)==0)
2227					strcpy(str_encryption, "WEP");
2228				else if (p_ValueLength==4 && strncasecmp("TKIP", p_Value, 4)==0)
2229					strcpy(str_encryption, "TKIP");
2230				else if (p_ValueLength==3 && strncasecmp("AES", p_Value, 3)==0)
2231					strcpy(str_encryption, "AES");
2232				else
2233					goto end2;
2234			}
2235			else if (elementType==TYPE_networkKey)
2236			{
2237				if (p_ValueLength>63*5 || (p_ValueLength<5 && p_ValueLength!=0))
2238					goto end2;
2239
2240   				for( i=0; i<p_ValueLength; i++ )
2241         				if( p_Value[i]<' ' || p_Value[i] >'~') 
2242         					goto end2;
2243
2244				tmp=parseXMLtext(tmpstr3, p_Value);
2245				if (tmp>64 || (tmp<5 && tmp!=0))
2246					goto end2;
2247
2248				strcpy(str_networkKey, tmpstr3);
2249			}
2250			else if (elementType==TYPE_keyProvidedAutomatically)
2251			{
2252				if (p_ValueLength==1 && strncasecmp("0", p_Value, 1)==0)
2253					strcpy(str_keyProvidedAutomatically, "0");
2254				else if (p_ValueLength==1 && strncasecmp("1", p_Value, 1)==0)
2255					strcpy(str_keyProvidedAutomatically, "1");
2256				else
2257					goto end2;
2258			}
2259			else if (elementType==TYPE_ieee802Dot1xEnabled)
2260			{
2261				if (p_ValueLength==1 && strncasecmp("0", p_Value, 1)==0)
2262					strcpy(str_ieee802Dot1xEnabled, "0");
2263				else if (p_ValueLength==1 && strncasecmp("1", p_Value, 1)==0)
2264					strcpy(str_ieee802Dot1xEnabled, "1");
2265				else
2266					goto end2;
2267			}
2268			else if (elementType==TYPE_eapMethod)
2269			{
2270				if (p_ValueLength==7 && strncasecmp("EAP-TLS", p_Value, 7)==0)
2271					strcpy(str_eapMethod, "EAP-TLS");
2272				else if (p_ValueLength==12 && strncasecmp("PEAP-EAP-TLS", p_Value, 12)==0)
2273					strcpy(str_eapMethod, "PEAP-EAP-TLS");
2274				else if (p_ValueLength==17 && strncasecmp("PEAP-EAP-MSCHAPv2", p_Value, 17)==0)
2275					strcpy(str_eapMethod, "PEAP-EAP-MSCHAPv2");
2276				else
2277					goto end2;					
2278			}
2279			else if (elementType==TYPE_channel2Dot4)
2280			{		
2281				if (p_ValueLength==1 && strncasecmp("0", p_Value, 1)==0)
2282					strcpy(str_channel2Dot4, "0");
2283				else if (p_ValueLength==1 && strncasecmp("1", p_Value, 1)==0)
2284					strcpy(str_channel2Dot4, "1");
2285				else if (p_ValueLength==1 && strncasecmp("2", p_Value, 1)==0)
2286					strcpy(str_channel2Dot4, "2");
2287				else if (p_ValueLength==1 && strncasecmp("3", p_Value, 1)==0)
2288					strcpy(str_channel2Dot4, "3");
2289				else if (p_ValueLength==1 && strncasecmp("4", p_Value, 1)==0)
2290					strcpy(str_channel2Dot4, "4");
2291				else if (p_ValueLength==1 && strncasecmp("5", p_Value, 1)==0)
2292					strcpy(str_channel2Dot4, "5");
2293				else if (p_ValueLength==1 && strncasecmp("6", p_Value, 1)==0)
2294					strcpy(str_channel2Dot4, "6");
2295				else if (p_ValueLength==1 && strncasecmp("7", p_Value, 1)==0)
2296					strcpy(str_channel2Dot4, "7");
2297				else if (p_ValueLength==1 && strncasecmp("8", p_Value, 1)==0)
2298					strcpy(str_channel2Dot4, "8");
2299				else if (p_ValueLength==1 && strncasecmp("9", p_Value, 1)==0)
2300					strcpy(str_channel2Dot4, "9");
2301				else if (p_ValueLength==2 && strncasecmp("10", p_Value, 2)==0)
2302					strcpy(str_channel2Dot4, "10");
2303				else if (p_ValueLength==2 && strncasecmp("11", p_Value, 2)==0)
2304					strcpy(str_channel2Dot4, "11");
2305				else if (p_ValueLength==2 && strncasecmp("12", p_Value, 2)==0)
2306					strcpy(str_channel2Dot4, "12");
2307				else if (p_ValueLength==2 && strncasecmp("13", p_Value, 2)==0)
2308					strcpy(str_channel2Dot4, "13");
2309				else if (p_ValueLength==2 && strncasecmp("14", p_Value, 2)==0)
2310					strcpy(str_channel2Dot4, "14");
2311				else
2312					goto end2;
2313			}
2314			else if (elementType==TYPE_channel5Dot0)
2315			{
2316				if (p_ValueLength==1 && strncasecmp("0", p_Value, 1)==0)
2317					strcpy(str_channel5Dot0, "0");
2318				else if (p_ValueLength==2 && strncasecmp("36", p_Value, 2)==0)
2319					strcpy(str_channel5Dot0, "36");
2320				else if (p_ValueLength==2 && strncasecmp("40", p_Value, 2)==0)
2321					strcpy(str_channel5Dot0, "40");
2322				else if (p_ValueLength==2 && strncasecmp("44", p_Value, 2)==0)
2323					strcpy(str_channel5Dot0, "44");
2324				else if (p_ValueLength==2 && strncasecmp("48", p_Value, 2)==0)
2325					strcpy(str_channel5Dot0, "48");
2326				else if (p_ValueLength==2 && strncasecmp("52", p_Value, 2)==0)
2327					strcpy(str_channel5Dot0, "52");
2328				else if (p_ValueLength==2 && strncasecmp("56", p_Value, 2)==0)
2329					strcpy(str_channel5Dot0, "56");
2330				else if (p_ValueLength==2 && strncasecmp("60", p_Value, 2)==0)
2331					strcpy(str_channel5Dot0, "60");
2332				else if (p_ValueLength==3 && strncasecmp("149", p_Value, 3)==0)
2333					strcpy(str_channel5Dot0, "149");
2334				else if (p_ValueLength==3 && strncasecmp("153", p_Value, 3)==0)
2335					strcpy(str_channel5Dot0, "153");
2336				else if (p_ValueLength==3 && strncasecmp("157", p_Value, 3)==0)
2337					strcpy(str_channel5Dot0, "157");
2338				else if (p_ValueLength==3 && strncasecmp("161", p_Value, 3)==0)
2339					strcpy(str_channel5Dot0, "161");
2340				else
2341					goto end2;
2342			}
2343			else if (elementType==TYPE_deviceMode)
2344			{
2345				if (p_ValueLength==14 && strncasecmp("infrastructure", p_Value, 14)==0)
2346					strcpy(str_deviceMode, "infrastructure");
2347				else if (p_ValueLength==6 && strncasecmp("bridge", p_Value, 6)==0)
2348					strcpy(str_deviceMode, "bridge");
2349				else if (p_ValueLength==8 && strncasecmp("repeater", p_Value, 8)==0)
2350					strcpy(str_deviceMode, "repeater");
2351				else if (p_ValueLength==7 && strncasecmp("station", p_Value, 7)==0)
2352					strcpy(str_deviceMode, "station");
2353				else
2354					goto end2;
2355			}
2356			else if (elementType==TYPE_timeToLive)
2357			{
2358				if (p_ValueLength>5 || p_ValueLength==0)
2359					goto end2;
2360
2361				long_temp=strtol(p_Value, endptr, 10);
2362				if (	(long_temp>(long int)86400) ||
2363					(long_temp<(long int)0) ||
2364					(long_temp==LONG_MAX) ||
2365					(long_temp==LONG_MIN) ||
2366					(endptr!=NULL)
2367				   )
2368					goto end2;
2369				else
2370					sprintf(str_timeToLive, "%d", (int)long_temp);
2371			}
2372			else if (elementType==TYPE_configHash)
2373			{
2374				if (p_ValueLength!=20)
2375					goto end2;
2376
2377   				for( i=0; i<p_ValueLength; i++ )
2378         				if(	p_Value[i]<'0' ||
2379         					(p_Value[i] >'9' && p_Value[i]<'A') ||
2380         					(p_Value[i]>'F' && p_Value[i]<'a') ||
2381         					p_Value[i] >'f'
2382         				  )
2383         					goto end2;
2384
2385				strcpy(str_configHash, p_Value);
2386			}
2387			else if (elementType==TYPE_keyIndex)
2388			{
2389				if (p_ValueLength!=1)
2390					goto end2;
2391
2392				if (p_ValueLength==1 && strncasecmp("1", p_Value, 1)==0)
2393					strcpy(str_keyIndex, "1");
2394				else if (p_ValueLength==1 && strncasecmp("2", p_Value, 1)==0)
2395					strcpy(str_keyIndex, "2");
2396				else if (p_ValueLength==1 && strncasecmp("3", p_Value, 1)==0)
2397					strcpy(str_keyIndex, "3");
2398				else if (p_ValueLength==1 && strncasecmp("4", p_Value, 1)==0)
2399					strcpy(str_keyIndex, "4");
2400				else
2401					goto end2;
2402			}
2403			else
2404				goto end2;
2405		}
2406next_loop:
2407//		xnode = xnode->Peer;
2408		xnode = xnode->Next;
2409	}
2410
2411	if(	t_configId==0 ||
2412		t_configAuthorId==0 ||
2413		t_configAuthor==0 ||
2414		t_ssid==0 ||
2415		t_connectionType==0 ||
2416		t_authentication==0 ||
2417		t_encryption==0 ||
2418		t_networkKey==0 ||
2419		t_keyProvidedAutomatically==0 ||
2420		t_ieee802Dot1xEnabled==0 ||
2421		t_primaryProfile==0
2422	)
2423	{
2424		strcpy(str_configError, "lack essential WCN-UFD XML element");
2425		printf("%s\n", str_configError);
2426		logmessage("WCN-UFD", str_configError);
2427		goto end1;
2428	}
2429
2430	if (t_channel5Dot0==1 && strcmp(str_channel5Dot0, "0")!=0)
2431	{
2432		printf("xxx\n");
2433		goto end3;
2434	}
2435
2436	if (atoi(str_channel2Dot4) > get_wl_channels())
2437	{
2438		printf("yyy\n");
2439		goto end3;
2440	}
2441
2442	if (strcmp(str_encryption, "none")==0 && strcmp(str_authentication, "open")!=0)
2443	{
2444		printf("bbb\n");
2445		goto end3;
2446	}
2447
2448	if (strcmp(str_keyProvidedAutomatically, "0")==0)
2449	{
2450		if (	strcmp(str_authentication, "WPA")==0 ||
2451			strcmp(str_authentication, "WPA2")==0
2452		   )
2453		{
2454			printf("ccc1\n");
2455			goto end3;
2456		}
2457	}
2458	else
2459	{
2460		if (	strcmp(str_ieee802Dot1xEnabled, "1")==0 ||
2461			strcmp(str_encryption, "WEP")!=0
2462		   )
2463			printf("ccc2\n");
2464			goto end3;
2465	}
2466
2467	if (strcmp(str_ieee802Dot1xEnabled, "1")==0)
2468	{
2469		if (	strcmp(str_encryption, "WEP")!=0 ||
2470			(strcmp(str_encryption, "WEP")==0 && (strcmp(str_keyIndex, "1")==0 || strcmp(str_keyIndex, "4")==0)) ||
2471			(strcmp(str_authentication, "WPA")!=0 && strcmp(str_authentication, "WPA2")!=0)
2472		   )
2473		{
2474			printf("ddd\n");
2475			goto end3;
2476		}
2477	}
2478
2479	if (strcmp(str_encryption, "none")==0 || strcmp(str_encryption, "WEP")==0)
2480	{
2481		if (	strcmp(str_authentication, "WPAPSK")==0 ||
2482			strcmp(str_authentication, "WPA2PSK")==0 ||
2483			strcmp(str_authentication, "WPA")==0 ||
2484			strcmp(str_authentication, "WPA2")==0
2485		   )
2486		{
2487			printf("eee\n");
2488			goto end3;
2489		}
2490	}
2491
2492	if (strcmp(str_encryption, "TKIP")==0 || strcmp(str_encryption, "AES")==0)
2493	{
2494		if (	strcmp(str_authentication, "open")==0 ||
2495			strcmp(str_authentication, "shared")==0 ||
2496			strcmp(str_ieee802Dot1xEnabled, "1")==0
2497		   )
2498		{
2499			printf("fff\n");
2500			goto end3;
2501		}
2502	}
2503	
2504	if (	//(strcmp(str_authentication, "WPAPSK")==0 && strcmp(str_encryption, "AES")==0) ||
2505		//(strcmp(str_authentication, "WPA2PSK")==0 && strcmp(str_encryption, "TKIP")==0) ||
2506		(strcmp(str_authentication, "WPA")==0 && strcmp(str_encryption, "AES")==0) ||
2507		(strcmp(str_authentication, "WPA2")==0 && strcmp(str_encryption, "TKIP")==0)
2508	   )
2509	{
2510		printf("ggg\n");
2511		goto end3;
2512	}
2513
2514	if (	strcmp(str_authentication, "shared")==0 ||
2515		strcmp(str_authentication, "WPAPSK")==0 ||
2516		strcmp(str_authentication, "WPA2PSK")==0 ||
2517		strcmp(str_authentication, "WPA")==0 ||
2518		strcmp(str_authentication, "WPA2")==0 ||
2519		strcmp(str_ieee802Dot1xEnabled, "1")==0 ||
2520		(strcmp(str_authentication, "open")==0 && strcmp(str_encryption, "WEP")==0)
2521	   )
2522	{
2523		if (strlen(str_networkKey)==0)
2524		{
2525			printf("no network key\n");
2526			logmessage("WCN-UFD", "no network key");
2527			goto end1;
2528		}
2529	}
2530
2531	if (	(strcmp(str_authentication, "open")==0 && strcmp(str_encryption, "WEP")==0) ||
2532		strcmp(str_authentication, "shared")==0 ||
2533		strcmp(str_ieee802Dot1xEnabled, "1")==0
2534	   )
2535	{		
2536		if (	strlen(str_networkKey)==10 ||
2537			strlen(str_networkKey)==26
2538		   )
2539		{
2540			for( i=0; i<strlen(str_networkKey); i++ )
2541         			if (	str_networkKey[i]<'0' ||
2542         				(str_networkKey[i]>'9' && str_networkKey[i]<'A') ||
2543         				(str_networkKey[i]>'F' && str_networkKey[i]<'a') ||
2544         				str_networkKey[i]>'f'
2545         			   )
2546				{
2547					strcpy(str_configError, "invalid wireless network key");
2548					printf("%s\n", str_configError);
2549					logmessage("WCN-UFD", str_configError);
2550
2551					goto end1;
2552				}
2553			for( i=0; i<strlen(str_networkKey); i++ )
2554				str_networkKey[i]=toupper(str_networkKey[i]);
2555		}
2556		else if (	strlen(str_networkKey)==5 ||
2557				strlen(str_networkKey)==13
2558			)
2559		{
2560			tmp=strlen(str_networkKey)*2;
2561			memset(tmpstr2, 0, 27);
2562			for( i=0; i<strlen(str_networkKey); i++ )
2563			{
2564				memset(tmpstr, 0, 3);
2565				sprintf(tmpstr, "%X", str_networkKey[i]);
2566				memcpy(&tmpstr2[2*i], tmpstr, 2);
2567			}
2568			memcpy(str_networkKey, tmpstr2, 2*tmp);
2569		}
2570		else
2571		{
2572			strcpy(str_configError, "invalid wireless network key length");
2573			printf("%s\n", str_configError);
2574			logmessage("WCN-UFD", str_configError);
2575			goto end1;
2576		}
2577	}
2578	else if (	strcmp(str_authentication, "WPAPSK")==0 ||
2579			strcmp(str_authentication, "WPA2PSK")==0
2580		)
2581	{
2582		if (strlen(str_networkKey)==64)
2583		{
2584			for( i=0; i<strlen(str_networkKey); i++ )
2585         			if (	str_networkKey[i]<'0' ||
2586         				(str_networkKey[i]>'9' && str_networkKey[i]<'A') ||
2587         				(str_networkKey[i]>'F' && str_networkKey[i]<'a') ||
2588         				str_networkKey[i]>'f'
2589         			   )
2590				{
2591					strcpy(str_configError, "invalid wireless network key");
2592					printf("%s\n", str_configError);
2593					logmessage("WCN-UFD", str_configError);
2594
2595					goto end1;
2596				}
2597			for( i=0; i<strlen(str_networkKey); i++ )
2598				str_networkKey[i]=toupper(str_networkKey[i]);
2599
2600/*
2601			for( i=0; i<64; i+=2 )
2602			{
2603				memset(tmpstr, 0, sizeof(tmpstr));
2604				tmpstr[0]=str_networkKey[i];
2605				tmp=(int)strtol(tmpstr, endptr, 16);
2606
2607				memset(tmpstr, 0, sizeof(tmpstr));
2608				tmpstr[0]=str_networkKey[i+1];
2609				tmp2=(int)strtol(tmpstr, endptr, 16);
2610
2611				tmp2=tmp*16+tmp2;
2612				str_networkKey[i/2]=tmp2;
2613			}
2614			str_networkKey[32]=0;
2615*/
2616		}
2617	}
2618
2619	printf("%d, %s\n", t_configId, str_configId);
2620	printf("%d, %s\n", t_configAuthorId, str_configAuthorId);
2621	printf("%d, %s\n", t_configAuthor, str_configAuthor);
2622	printf("%d, %s\n", t_ssid, str_ssid);
2623	printf("%d, %s\n", t_connectionType, str_connectionType);
2624	printf("%d, %s\n", t_authentication, str_authentication);
2625	printf("%d, %s\n", t_encryption, str_encryption);
2626	printf("%d, %s\n", t_networkKey, str_networkKey);
2627	printf("%d, %s\n", t_keyProvidedAutomatically, str_keyProvidedAutomatically);
2628	printf("%d, %s\n", t_ieee802Dot1xEnabled, str_ieee802Dot1xEnabled);
2629	printf("%d\n", t_primaryProfile);
2630	printf("***************************************\n");
2631	printf("*** following elements are optional ***\n");
2632	printf("%d, %s\n", t_eapMethod, str_eapMethod);
2633	printf("%d, %s\n", t_channel2Dot4, str_channel2Dot4);
2634	printf("%d, %s\n", t_channel5Dot0, str_channel5Dot0);
2635	printf("%d, %s\n", t_deviceMode, str_deviceMode);
2636	printf("%d, %s\n", t_timeToLive, str_timeToLive);
2637	printf("%d, %s\n", t_configHash, str_configHash);
2638	printf("%d, %s\n", t_keyIndex, str_keyIndex);
2639	printf("%d\n\n", t_optionalProfile);
2640
2641	nvram_set("wl_configId", str_configId);
2642	nvram_set("wl_ssid", str_ssid);
2643	memset(tmpstr3, 0, sizeof(tmpstr3));
2644	char_to_ascii(tmpstr3, str_ssid);
2645	nvram_set("wl_ssid2", tmpstr3);
2646
2647	if (t_channel2Dot4==1)
2648	{
2649		nvram_set("wl_channel", str_channel2Dot4);
2650	}
2651
2652	if (strcmp(str_ieee802Dot1xEnabled, "1")==0)
2653	{
2654		nvram_set("wl_auth_mode", "radius");
2655	}
2656	else if (strcmp(str_authentication, "open")==0)
2657	{
2658		nvram_set("wl_auth_mode", "open");
2659	}
2660	else if (strcmp(str_authentication, "shared")==0)
2661	{
2662		nvram_set("wl_auth_mode", "shared");
2663	}
2664	else if (strcmp(str_authentication, "WPAPSK")==0
2665			|| strcmp(str_authentication, "WPA2PSK")==0)
2666	{
2667		nvram_set("wl_auth_mode", "psk");
2668// 2008.07 James. {
2669		/*if (strcmp(str_authentication, "WPAPSK")==0)
2670			nvram_set("wl_wpa_mode", "1");
2671		else
2672			nvram_set("wl_wpa_mode", "2");
2673		nvram_set("wl_crypto", "tkip+aes");//*/
2674		if (strcmp(str_authentication, "WPAPSK")==0){
2675			nvram_set("wl_wpa_mode", "1");
2676			nvram_set("wl_crypto", "tkip");
2677		}
2678		else{
2679			nvram_set("wl_wpa_mode", "2");
2680			nvram_set("wl_crypto", "aes");
2681		}
2682// 2008.07 James. }
2683/*
2684		if (strcmp(str_encryption, "TKIP")==0)
2685			nvram_set("wl_crypto", "tkip");
2686		else if (strcmp(str_encryption, "AES")==0)
2687			nvram_set("wl_crypto", "aes");
2688*/
2689	}
2690	else if (strcmp(str_authentication, "WPA")==0)
2691	{
2692		nvram_set("wl_auth_mode", "wpa");
2693		nvram_set("wl_crypto", "tkip");
2694	}
2695	else if (strcmp(str_authentication, "WPA2")==0)
2696	{
2697		nvram_set("wl_auth_mode", "wpa2");
2698		nvram_set("wl_crypto", "aes");
2699	}
2700
2701	if (strcmp(str_encryption, "TKIP")==0 || strcmp(str_encryption, "AES")==0)
2702	{
2703		nvram_set("wl_wpa_psk", str_networkKey);
2704		nvram_set("wl_wep_x", "0");
2705	}
2706	else if (strcmp(str_encryption, "WEP")==0)
2707	{
2708		if (strlen(str_networkKey)==10)
2709		{
2710			nvram_set("wl_wep_x", "1");
2711			nvram_set("wl_key1", "6565656565");
2712			nvram_set("wl_key2", "8383838383");
2713			nvram_set("wl_key3", "8585858585");
2714			nvram_set("wl_key4", "8383838383");
2715		}
2716		else if (strlen(str_networkKey)==26)
2717		{
2718			nvram_set("wl_wep_x", "2");
2719			nvram_set("wl_key1", "65656565656565656565656565");
2720			nvram_set("wl_key2", "83838383838383838383838383");
2721			nvram_set("wl_key3", "85858585858585858585858585");
2722			nvram_set("wl_key4", "83838383838383838383838383");
2723		}
2724
2725		if (t_keyIndex==0)
2726		{
2727			nvram_set("wl_key", "1");
2728			nvram_set("wl_key1", str_networkKey);
2729		}
2730		else
2731		{
2732			nvram_set("wl_key", str_keyIndex);
2733			memset(tmpstr2, 0, sizeof(tmpstr2));
2734			sprintf(tmpstr2, "wl_key%s", str_keyIndex);
2735			nvram_set(tmpstr2, str_networkKey);
2736		}
2737	}
2738	else
2739	{
2740		nvram_set("wl_wep_x", "0");
2741		nvram_set("wl_key1", "");
2742		nvram_set("wl_key2", "");
2743		nvram_set("wl_key3", "");
2744		nvram_set("wl_key4", "");
2745		nvram_set("wl_wpa_psk", "");
2746	}
2747
2748	if (t_timeToLive==1)
2749	{
2750		nvram_set("wl_wpa_gtk_rekey", str_timeToLive);
2751	}
2752	
2753	reboot_wcn=1;
2754
2755	goto end1;
2756end3:
2757	strcpy(str_configError, "unsupported WCN-UFD XML element value");
2758	printf("%s\n", str_configError);
2759	logmessage("WCN-UFD", str_configError);
2760	goto end1;
2761end2:
2762	strcpy(str_configError, "Invalid WCN-UFD XML element");
2763	printf("%s\n", str_configError);
2764	logmessage("WCN-UFD", str_configError);
2765end1:
2766	memset(MACpostfix, 0, sizeof(MACpostfix));
2767	memset(deviceCFG_path, 0, sizeof(deviceCFG_path));
2768	memset(tmpstr2, 0, sizeof(tmpstr2));
2769	strcpy(tmpstr2, nvram_safe_get("et0macaddr")+6);
2770	tmpstr2[2]=0;
2771	tmpstr2[5]=0;
2772	tmpstr2[8]=0;
2773	sprintf(MACpostfix, "%s%s%s%s", tmpstr2, tmpstr2+3, tmpstr2+6, tmpstr2+9);
2774	for( i=0; i<strlen(MACpostfix); i++ )
2775		MACpostfix[i]=toupper(MACpostfix[i]);
2776	sprintf(deviceCFG_path, "%s/SMRTNTKY/DEVICE/%s.WFC", run_path, MACpostfix);
2777	fp=fopen(deviceCFG_path, "w");
2778
2779	if (fp!=NULL)
2780	{
2781		fprintf(fp, "<?xml version=\"1.0\"?>\n");
2782		fprintf(fp, "<device xmlns=\"http://www.microsoft.com/provisioning/DeviceProfile/2004\">\n");
2783		fprintf(fp, "\t<configId>%s</configId>\n", str_configId);
2784		if (strlen(str_configError)!=0)
2785			fprintf(fp, "\t<configError>%s</configError>\n", str_configError);
2786		fprintf(fp, "\t<manufacturer>ASUSTeK</manufacturer>\n");
2787		fprintf(fp, "\t<manufacturerURL>http://www.asus.com/</manufacturerURL>\n");
2788		fprintf(fp, "\t<modelName>%s</modelName>\n", nvram_safe_get("productid"));
2789		memset(tmpstr2, 0, sizeof(tmpstr2));
2790		strcpy(tmpstr2, nvram_safe_get("et0macaddr"));
2791		for( i=0; i<strlen(tmpstr2); i++ )
2792			tmpstr2[i]=toupper(tmpstr2[i]);
2793		fprintf(fp, "\t<serialNumber>%s</serialNumber>\n", tmpstr2);
2794		fprintf(fp, "\t<firmwareVersion>%s</firmwareVersion>\n", nvram_safe_get("firmver"));
2795		fprintf(fp, "\t<deviceType>Access_Point</deviceType>\n");
2796		fprintf(fp, "</device>\n");
2797		fclose(fp);
2798	}
2799end0:
2800	ILibDestructXMLNodeList(root);
2801// 2007.12 James {
2802	//umount_disc_parts_rc(0);
2803	//umount_disc_parts_rc(1);
2804// 2007.12 James }
2805	
2806	if (reboot_wcn==1){
2807		nvram_set("reboot_WCN", "2");
2808		nvram_set("x_Setting", "1");/* Cherry Cho added in 2007/4/13. */
2809		system("killall wsccmd");
2810	}
2811}
2812
2813void char_to_ascii(char *output, char *input)// Transfer Char to ASCII
2814{                                                   // Cherry_Cho added in 2006/9/29
2815        int i;
2816        char tmp[10];
2817        char *ptr;
2818                                                                                                               
2819        ptr = output;
2820                                                                                                               
2821        for( i=0; i<strlen(input); i++ )
2822        {
2823                if((input[i]>='0' && input[i] <='9')
2824                   ||(input[i]>='A' && input[i]<='Z')
2825                   ||(input[i] >='a' && input[i]<='z')
2826                   || input[i] == '!' || input[i] == '*'
2827                   || input[i] == '(' || input[i] == ')'
2828                   || input[i] == '_' || input[i] == '-'
2829                   || input[i] == "'" || input[i] == '.')
2830                {
2831                        *ptr = input[i];
2832                        ptr ++;
2833                }
2834                else
2835                {
2836                        sprintf(tmp, "%%%.02X", input[i]);
2837                        strcpy(ptr, tmp);
2838                        ptr += 3;
2839                }
2840        }
2841                                                                                                               
2842        *ptr = '\0';
2843                                                                                                               
2844}
2845
2846#endif // WCN
2847
2848/* insert usb mass storage */
2849int
2850hotplug_usb_mass(char *product)	// modified by Jiahao for WL500gP
2851{	
2852	DIR *dir_to_open, *dir_of_usb, *usb_dev_disc, *usb_dev_part;
2853	char usb_disc[128], usb_part[128], usb_file_part[128];
2854	char usb_disc_mount_path[128], usb_disc_mount_path2[128], tmp[32];
2855	char usb_disc_fs_path[128];
2856	int n=0, m=0, p=0;
2857	struct dirent *dp, *dp_disc, **dpopen;
2858	char tmpstr[128], test_path[128];
2859	int i, j;
2860	FILE *fp;
2861	int ret=0;
2862	int apps_comp=0;
2863	int apps_status=0;
2864	int apps_disk_free=0;
2865	int apps_comp_pre=0;
2866	int new_disc[2];
2867	new_disc[0]=0;
2868	new_disc[1]=0;
2869#ifdef DLM
2870	char *buf=NULL;
2871	int buflen=0;
2872	struct sysinfo info;
2873#endif // DLM
2874	char dev_real_path[PATH_MAX];	// 2007.11 James.
2875	
2876	nvram_set("usb_storage_device", "");	// 2007.12 James.
2877	
2878	if(nvram_match("hsdpa_enable", "1")
2879			&& eject_scsi("/dev/cdroms/cdrom0")){
2880logmessage("USB Storage", "Succeed to remove the CD-ROM device.");
2881		return 0;
2882	}
2883logmessage("USB Storage", "Fail to remove the CD-ROM device.");
2884	dir_to_open=dir_of_usb=usb_dev_disc=usb_dev_part=NULL;
2885	strcpy(tmp, "");
2886
2887#ifdef DLM
2888	nvram_set("usb_storage_busy", "1");
2889	nvram_set("apps_status_checked", "0");
2890
2891	if (	nvram_match("eject_from_web", "1") &&
2892		(nvram_invmatch("usb_disc0_dev", "") || nvram_invmatch("usb_disc1_dev", ""))
2893	   )
2894		goto eject;
2895#endif // DLM
2896
2897	if (nvram_match("usb_ftpenable_x", "0")) return 0;
2898
2899	// Mount USB to system
2900	if((usb_dev_disc = opendir("/dev/discs")))
2901	{
2902		while(usb_dev_disc && (dp=readdir(usb_dev_disc)))
2903		{
2904			if(!strncmp(dp->d_name, "..", NAME_MAX) || !strncmp(dp->d_name, ".", NAME_MAX) /*|| !strncmp(dp->d_name, "disc0", NAME_MAX)*/)
2905				continue;
2906
2907			sprintf(usb_disc, "/dev/discs/%s", dp->d_name);
2908// 2007.11 James {
2909			realpath(usb_disc, dev_real_path);
2910			memset(usb_disc, 0, sizeof(usb_disc));
2911			strcpy(usb_disc, dev_real_path);
2912// 2007.11 James }
2913			if (nvram_match("usb_disc0_dev", usb_disc))
2914				continue;
2915			if (nvram_match("usb_disc1_dev", usb_disc))
2916				continue;
2917
2918			//logs(usb_disc);
2919			if((usb_dev_part = opendir(usb_disc)))
2920			{
2921				m = 0;	// part count of each disc
2922				while(usb_dev_part && (dp_disc=readdir(usb_dev_part)) && (m<7))
2923				{	
2924					//logs(dp_disc->d_name);
2925					if(	!strncmp(dp_disc->d_name, "..", NAME_MAX) ||
2926						!strncmp(dp_disc->d_name, ".", NAME_MAX) ||
2927						!strncmp(dp_disc->d_name, "disc", NAME_MAX) ||
2928						!strncmp(dp_disc->d_name, "generic", NAME_MAX)
2929					  )
2930						continue;
2931
2932					if (m==0)
2933					{
2934						sprintf(tmpstr, nvram_get("usb_disc1_dev"));
2935						sprintf(test_path, nvram_get("usb_disc0_dev"));
2936
2937						if (nvram_match("usb_disc0_dev", "") && strcmp(usb_disc, tmpstr)!=0)
2938						{
2939							nvram_set("usb_disc0_dev", usb_disc);
2940							nvram_set("usb_disc0_safely_removed", "0");	// 2008.06 James.
2941							new_disc[0]=1;
2942						}
2943						else if (nvram_match("usb_disc1_dev", "") && strcmp(usb_disc, test_path)!=0)
2944						{
2945							nvram_set("usb_disc1_dev", usb_disc);
2946							nvram_set("usb_disc1_safely_removed", "0");	// 2008.06 James.
2947							new_disc[1]=1;
2948						}
2949					}
2950
2951					sprintf(usb_part, "/dev/discs/%s/%s", dp->d_name, dp_disc->d_name);
2952					realpath(usb_part, dev_real_path);	// 2007.11 James.
2953					if (n==0) {
2954						sprintf(usb_file_part, "/tmp/harddisk");
2955						mkdir_if_none(usb_file_part);
2956					}
2957					sprintf(usb_file_part, "/tmp/harddisk/part%d", n);
2958					while (check_if_dir_exist(usb_file_part)==1)
2959						sprintf(usb_file_part, "/tmp/harddisk/part%d", ++n);
2960					mkdir_if_none(usb_file_part);
2961#ifdef MOUNTALL
2962					//eval("mount", usb_part, usb_file_part);
2963					eval("mount", dev_real_path, usb_file_part);	// 2007.11 James.
2964					printf("mountall\n");
2965#else // MOUNTALL
2966					//if (mount_r(usb_part, usb_file_part))
2967					if(mount_r(dev_real_path, usb_file_part))	// 2007.11 James.
2968					{
2969						if (strcmp(usb_disc, nvram_safe_get("usb_disc0_dev"))==0)
2970						{
2971							j=atoi(nvram_safe_get("usb_disc0_index"));
2972							sprintf(usb_disc_mount_path, "usb_disc0_path%d", j);
2973							sprintf(usb_disc_mount_path2, "usb_disc0_index");
2974							sprintf(usb_disc_fs_path, "usb_disc0_fs_path%d", j);
2975						}
2976						else if (strcmp(usb_disc, nvram_safe_get("usb_disc1_dev"))==0)
2977						{
2978							j=atoi(nvram_safe_get("usb_disc1_index"));
2979							sprintf(usb_disc_mount_path, "usb_disc1_path%d", j);
2980							sprintf(usb_disc_mount_path2, "usb_disc1_index");
2981							sprintf(usb_disc_fs_path, "usb_disc1_fs_path%d", j);
2982						}
2983						nvram_set(usb_disc_mount_path, usb_file_part);
2984						//nvram_set(usb_disc_fs_path, usb_part);
2985						nvram_set(usb_disc_fs_path, dev_real_path);	// 2007.11 James.
2986						sprintf(usb_disc_mount_path, "%d", ++j);
2987						nvram_set(usb_disc_mount_path2, usb_disc_mount_path);
2988						n++;
2989						m++;
2990						p++;
2991					}
2992					else
2993					{
2994						rmdir(usb_file_part);
2995						//printf("mount %s failed\n", usb_part);
2996						printf("mount %s failed\n", dev_real_path);	// 2007.11 James.
2997					}
2998#endif // MOUNTALL
2999				}
3000
3001				if (!m) // There is no other partition
3002				{
3003					sprintf(usb_part, "/dev/discs/%s/disc", dp->d_name);
3004					realpath(usb_part, dev_real_path);	// 2007.11 James.
3005					if (n==0) 
3006					{
3007						sprintf(usb_file_part, "/tmp/harddisk");
3008						mkdir_if_none(usb_file_part);
3009					}
3010					sprintf(usb_file_part, "/tmp/harddisk/part%d", n);
3011					while (check_if_dir_exist(usb_file_part)==1)
3012						sprintf(usb_file_part, "/tmp/harddisk/part%d", ++n);
3013					mkdir_if_none(usb_file_part);
3014					
3015#ifdef MOUNTALL
3016					//eval("mount", usb_part, usb_file_part);
3017					eval("mount", dev_real_path, usb_file_part);	// 2007.11 James.
3018#else // MOUNTALL
3019					//if(mount_r(usb_part, usb_file_part))
3020					if(mount_r(dev_real_path, usb_file_part))	// 2007.11 James.
3021					{
3022						
3023						sprintf(tmpstr, nvram_get("usb_disc1_dev"));
3024						sprintf(test_path, nvram_get("usb_disc0_dev"));
3025
3026						if (nvram_match("usb_disc0_dev", "") && strcmp(usb_disc, tmpstr)!=0)
3027						{
3028							nvram_set("usb_disc0_dev", usb_disc);
3029							new_disc[0]=1;
3030						}
3031						else if (nvram_match("usb_disc1_dev", "") && strcmp(usb_disc, test_path)!=0)
3032						{
3033							nvram_set("usb_disc1_dev", usb_disc);
3034							new_disc[1]=1;
3035						}
3036
3037						//if (strncmp(usb_part, nvram_safe_get("usb_disc0_dev"), 16)==0)
3038						if(!strncmp(usb_part, nvram_safe_get("usb_disc0_dev"), 33))	// 2007.11 James.
3039						{
3040							nvram_set("usb_disc0_path0", usb_file_part);
3041							//nvram_set("usb_disc0_fs_path0", usb_part);
3042							nvram_set("usb_disc0_fs_path0", dev_real_path);	// 2007.11 James.
3043							nvram_set("usb_disc0_index", "1");
3044						}
3045						//else if (strncmp(usb_part, nvram_safe_get("usb_disc1_dev"), 16)==0)
3046						else if(!strncmp(usb_part, nvram_safe_get("usb_disc1_dev"), 33))	// 2007.11 James.
3047						{
3048							nvram_set("usb_disc1_path0", usb_file_part);
3049							//nvram_set("usb_disc1_fs_path0", usb_part);
3050							nvram_set("usb_disc1_fs_path0", dev_real_path);	// 2007.11 James.
3051							nvram_set("usb_disc1_index", "1");
3052						}
3053						n++;
3054						p++;
3055					}
3056					else
3057					{
3058						rmdir(usb_file_part);
3059						//printf("mount %s failed\n", usb_part);
3060						printf("mount %s failed\n", dev_real_path);	// 2007.11 James.
3061					}
3062#endif // MOUNTALL
3063				}
3064				
3065				printf("\n\n**********************************************\n");
3066				write_disc_status();
3067				printf("**********************************************\n\n");
3068			}
3069		}
3070	}
3071#ifdef DLM
3072eject:
3073	if(p
3074			|| (nvram_match("eject_from_web", "1")
3075				&& (nvram_invmatch("usb_disc0_dev", "") || nvram_invmatch("usb_disc1_dev", "")))
3076			)// if any usb mass storage device newly mounted at this time
3077	{
3078		nvram_set("eject_from_web", "0");
3079		
3080		strcpy(test_path, "");
3081		
3082		if(nvram_invmatch("usb_disc0_dev", "") && (nvram_match("apps_dlx", "0") || check_disk_free_GE_1G(nvram_safe_get("usb_disc0_path0")) == 2))
3083		{
3084			strcpy(test_path, nvram_safe_get("usb_disc0_path0"));
3085		}
3086		else if ( nvram_invmatch("usb_disc1_dev", "") && (nvram_match("apps_dlx", "0")||check_disk_free_GE_1G(nvram_safe_get("usb_disc1_path0"))==2) )
3087		{
3088			strcpy(test_path, nvram_safe_get("usb_disc1_path0"));
3089		}
3090		else if ( nvram_invmatch("usb_disc0_dev", "") )
3091		{
3092			strcpy(test_path, nvram_safe_get("usb_disc0_path0"));
3093		}
3094		else if ( nvram_invmatch("usb_disc1_dev", "") )
3095		{
3096			strcpy(test_path, nvram_safe_get("usb_disc1_path0"));
3097		}
3098
3099		strcpy(tmp, test_path);
3100
3101		if(nvram_match("swap_on", "0") && nvram_match("apps_dlx", "1")
3102				&& (apps_comp_pre = ckeck_apps_completeness_pre(tmp)) == 1)
3103		{
3104			if(strcmp(test_path, "") != 0)
3105			{
3106				memset(tmpstr, 0, sizeof(tmpstr));
3107				sprintf(tmpstr, "%s/swap", test_path);
3108				unlink(tmpstr);
3109				memset(tmpstr, 0, sizeof(tmpstr));
3110				sprintf(tmpstr, "%s/.swap", test_path);
3111				unlink(tmpstr);
3112				
3113				ret = check_disk_free_GE_1G(test_path);
3114				
3115				if(ret==2)
3116				{
3117					if(strcmp(test_path, nvram_safe_get("usb_disc0_path0")) == 0)
3118						nvram_set("apps_dms_usb_port_x2", nvram_safe_get("usb_disc0_port"));
3119					else if (strcmp(test_path, nvram_safe_get("usb_disc1_path0")) == 0)
3120						nvram_set("apps_dms_usb_port_x2", nvram_safe_get("usb_disc1_port"));
3121					
3122					sysinfo(&info);
3123					if((info.freeram+info.bufferram) >= 1024*1024*2)
3124						buflen = 1024*1024*2;
3125					else if((info.freeram+info.bufferram) >= 1024*1024*1.6)
3126						buflen = 1024*1024*1.6;
3127					else if((info.freeram+info.bufferram) >= 1024*1024*1)
3128						buflen = 1024*1024*1;
3129					else if((info.freeram+info.bufferram) >= 1024*1024*0.8)
3130						buflen = 1024*1024*0.8;
3131					else
3132						buflen = 1024*1024*0.5;
3133					buf = malloc(buflen);
3134					for(i = 0; i < buflen; i++)
3135						buf[i]='\n';
3136					
3137					fp = fopen(tmpstr, "a");
3138					if(fp != NULL)
3139					{
3140						for(i = 0; i < (1024*1024*32/buflen); i++)
3141							fprintf(fp, "%s", buf);
3142						free(buf);
3143						fclose(fp);
3144						
3145						/*memset(test_path, 0, sizeof(test_path));
3146						sprintf(test_path, "mkswap %s", tmpstr);
3147						system(test_path);
3148						
3149						memset(test_path, 0, sizeof(test_path));
3150						sprintf(test_path, "swapon %s", tmpstr);
3151						system(test_path);//*/
3152						eval("/sbin/mkswap", tmpstr);
3153						
3154						swapon(tmpstr, 0);	// 2008.04 James.
3155						
3156						logmessage("USB storage", "32MB swap file is added");
3157						nvram_set("swap_on", "1");
3158						nvram_set("swap_file", tmpstr);	// 2008.06 James.
3159					}
3160				}
3161				else if (ret==1)
3162					logmessage("USB storage", "The swap file is not added for free space is less than 33MB");
3163				else if (ret==3)
3164					logmessage("USB storage", "The swap file is not added for partition size is less than 1024MB");
3165				else if (ret==0)
3166					logmessage("USB storage", "The swap file is not added for unknown reasons");
3167			}
3168		}
3169		
3170		start_script(new_disc); // Move ahead to speed up WCN
3171		if(!nvram_match("reboot_WCN", "2"))
3172			run_ftpsamba();
3173		
3174//		if (nvram_match("apps_dmsx", "1"))
3175//			exec_dms();
3176		
3177		apps_disk_free = check_disk_free_apps(tmp, apps_comp);
3178		if(apps_disk_free == 1)
3179			nvram_set("apps_disk_free", "1");
3180		else
3181			nvram_set("apps_disk_free", "0");
3182/*
3183		if((apps_comp_pre==1) &&
3184		   nvram_match("apps_running", "0") &&
3185		   (nvram_match("apps_dlx", "1")||nvram_match("apps_dmsx", "1"))
3186		  )
3187*/
3188		//if(nvram_match("apps_running", "0") &&
3189		if(strcmp(nvram_safe_get("apps_running"), "1") != 0
3190				&& !nvram_match("reboot_WCN", "2")
3191				&& ((apps_comp_pre == 1 && nvram_match("apps_dlx", "1")) || nvram_match("apps_dmsx", "1"))
3192				)
3193		{
3194			if (strcmp(tmp, "")!=0)
3195			{
3196				apps_comp=ckeck_apps_completeness(tmp);
3197				if (apps_comp==1)
3198					nvram_set("apps_comp", "1");
3199				else
3200				{
3201					nvram_set("apps_comp", "0");
3202					if ( strcmp(nvram_get("swap_on"), "1")==0)
3203					{
3204						printf("try to swapoff swap file.\n");
3205						if (strcmp(tmp, "")!=0)
3206						{
3207							memset(tmpstr, 0, sizeof(tmpstr));
3208							sprintf(tmpstr, "%s/.swap", tmp);
3209							swapoff(tmpstr);
3210							sleep(1);
3211							if (swap_check()==1)
3212							{
3213								logmessage("USB storage", "swapoff unsuccessfully");
3214								nvram_set("swapoff_failed", "1");
3215								unlink(tmpstr);
3216								nvram_set("reboot", "1");
3217							}
3218							else
3219							{
3220								logmessage("USB storage", "swapoff successfully");
3221								nvram_set("swap_on", "0");
3222								nvram_set("swap_file", "");	// 2008.06 James.
3223								nvram_set("swapoff_failed", "0");
3224								nvram_set("apps_dms_usb_port_x2", "-1");
3225								unlink(tmpstr);
3226							}
3227						}
3228					}
3229				}
3230
3231				if (nvram_match("apps_dlx", "0") || 
3232				    (nvram_match("apps_dlx", "1") && ret==2) ||
3233				    (nvram_match("apps_dmsx", "1") && !(nvram_match("apps_dlx", "1") && ret==2))
3234				   )
3235				{
3236					if ((apps_comp==1 && apps_disk_free==1) || nvram_match("apps_dmsx", "1"))
3237					{
3238
3239						if (strcmp(tmp, nvram_safe_get("usb_disc0_path0"))==0)
3240							nvram_set("apps_dms_usb_port_x", nvram_safe_get("usb_disc0_port"));
3241						else if (strcmp(tmp, nvram_safe_get("usb_disc1_path0"))==0)
3242							nvram_set("apps_dms_usb_port_x", nvram_safe_get("usb_disc1_port"));
3243
3244						start_apps();
3245						//nvram_set("apps_running", "1");
3246					}
3247				}
3248				else
3249				{
3250					fprintf(stderr, "skip running DMS & DM for no swap file\n");
3251					logmessage("Media Server", "daemon is not started for no swap file");
3252					logmessage("Download Master", "daemon is not started for no swap file");
3253				}
3254			}
3255			else
3256				fprintf(stderr, "skip running DMS & DM for mismatching\n");
3257		}
3258		else
3259			fprintf(stderr, "skip running DMS & DM\n");
3260	}
3261
3262	nvram_set("usb_storage_busy", "0");
3263	nvram_set("apps_status_checked", "1");
3264#else // DLM
3265	if (p)	// if any usb mass storage device newly mounted at this time
3266	{
3267		start_script(new_disc);
3268	}
3269#endif // DLM
3270
3271#ifdef USBCOPY_SUPPORT
3272	n = 1;
3273	if((dir_to_open = opendir("/tmp/harddisk")))
3274	{
3275		while(dir_to_open && (dp=readdir(dir_to_open)))
3276		{
3277			if(!strncmp(dp->d_name, "..", NAME_MAX) || !strncmp(dp->d_name, ".", NAME_MAX) || !strncmp(dp->d_name, "part", 4))
3278				continue;
3279			sprintf(usb_part, "/tmp/harddisk/%s", dp->d_name);
3280			if(scandir(usb_part, &dpopen, 0, alphasort) <= 2)
3281				continue;
3282			while(1)
3283			{
3284				sprintf(path_copy_to, "/tmp/harddisk/part1/USBpart%03d", n);
3285				if(!opendir(path_copy_to))
3286				{
3287					if(mkdir(path_copy_to, 0777))
3288					{
3289						perror("error on creating usb directory");
3290					}
3291					eval("echo", path_copy_to);
3292					break;
3293				}
3294				else
3295					n++;
3296			}
3297			if((dir_of_usb = opendir(usb_part)))
3298			{
3299				while(dir_of_usb && (dp_disc=readdir(dir_of_usb)))
3300				{
3301					if(!strncmp(dp_disc->d_name, "..", NAME_MAX) || !strncmp(dp_disc->d_name, ".", NAME_MAX))
3302						continue;
3303					sprintf(path_to_copy, "/tmp/harddisk/%s/%s", dp->d_name, dp_disc->d_name);
3304					eval("cp", "-Rf", path_to_copy, path_copy_to);
3305					sync();
3306				}
3307			}
3308			n++;
3309		}
3310	}
3311#endif // USBCOPY_SUPPORT
3312
3313	if(usb_dev_disc)
3314		closedir(usb_dev_disc);
3315	if(usb_dev_part)
3316		closedir(usb_dev_part);
3317	if(dir_to_open)
3318		closedir(dir_to_open);
3319
3320	return 0;
3321}
3322
3323#ifdef CDMA // HSDPA {
3324int hsdpa_detect(void)
3325{
3326	int f;
3327	int ret=-1;
3328	extern int errno;
3329
3330	if((f=open("/dev/ttyACM0", O_WRONLY))!=-1)
3331	{
3332csprintf("--- hsdpa_detect: Detect as ACM! ---\n");
3333		close(f);
3334		ret=0;
3335	}
3336	else if((f=open("/dev/ttyUSB0", O_WRONLY))!=-1)
3337	{
3338csprintf("--- hsdpa_detect: Detect as USB! ---\n");
3339		close(f);
3340		ret=1;
3341	}
3342	else
3343	{
3344csprintf("--- hsdpa_detect: Detect as not HSDPA! ---\n");
3345	}
3346	return ret;
3347}
3348
3349int hotplug_hsdpa(char *product)
3350{
3351	char tmp[100];
3352	char vid[32];
3353	char pid[32];
3354	char *ptr1, *ptr2;
3355	int combo;
3356	
3357	strcpy(tmp, product);
3358	ptr1=strchr(tmp, '/');
3359	*ptr1=0;	
3360	sprintf(vid, "vendor=0x%s", tmp);
3361	ptr2=strchr(ptr1+1, '/');
3362	*ptr2=0;
3363	sprintf(pid, "product=0x%s", ptr1+1);
3364	
3365	//logmessage("Add USB Device VID", vid);
3366	//logmessage("Add USB Device PID", pid);
3367	
3368	//if(interface)
3369	//	logmessage("Add USB Device INTERFACE", interface);
3370	
3371	if (nvram_match("hsdpa_enable", "0")) return 0;
3372	
3373	//logmessage("Detect HSDPA", product);
3374	
3375	if (nvram_match("hsdpa_product", ""))
3376	{
3377		//logmessage("HSDPA detected", product);
3378		
3379		eval("rmmod", "usbserial");
3380		eval("insmod", "usbserial.o", vid, pid);
3381		
3382		eval("mknod", "/dev/ttyACM0", "c", "166", "0");
3383		eval("mknod", "/dev/ttyACM1", "c", "166", "1");
3384		
3385		eval("mknod", "/dev/ttyUSB0", "c", "188", "0");
3386		eval("mknod", "/dev/ttyUSB1", "c", "188", "1");
3387		eval("mknod", "/dev/ttyUSB2", "c", "188", "2");
3388		eval("mknod", "/dev/ttyUSB3", "c", "188", "3");
3389		
3390		if(!strncmp(product, "1a8d/", 5)){
3391			logmessage("Add USB Modem", product);
3392			
3393			nvram_set("hsdpa_product", product);
3394			nvram_set("hsdpa_combo", "1");
3395			
3396			nvram_set("got_HSDPA", "1");
3397			nvram_set("hsdpa_ttyUSB_num", "1");
3398			
3399			nvram_set("cdma_down", "1");
3400			
3401			return 1;
3402		}
3403		else if(!strcmp(product, "805/480f/0")){
3404			logmessage("Add USB Modem", product);
3405			
3406			nvram_set("hsdpa_product", product);
3407			nvram_set("hsdpa_combo", "1");
3408			
3409			nvram_set("got_HSDPA", "1");
3410			nvram_set("hsdpa_ttyUSB_num", "3");
3411			
3412			nvram_set("cdma_down", "1");
3413			
3414			return 1;
3415		}
3416		else if((combo = hsdpa_detect()) != -1)
3417		{ 
3418			logmessage("Add USB Modem", product);
3419			
3420			nvram_set("hsdpa_product", product);
3421			if(combo){
3422				nvram_set("hsdpa_combo", "1");
3423				
3424				//nvram_set("got_HSDPA", "0");
3425				nvram_set("hsdpa_ttyUSB_num", "");
3426			}
3427			else
3428				nvram_set("hsdpa_combo", "0");
3429			
3430			// start cdma
3431			nvram_set("cdma_down", "1");
3432			
3433			return 1;
3434		}
3435		else{
3436			eval("rmmod", "usbserial");
3437			
3438			nvram_set("hsdpa_combo", "-1");
3439		}
3440	}
3441	
3442	// skip other interface on the same device
3443	if(nvram_match("hsdpa_product", product)){
3444csprintf("--- hotplug_hsdpa: Found other interface of the HSDPA card! ---\n");
3445		return 1;
3446	}
3447	
3448	return 0;
3449}
3450
3451int unplug_hsdpa(char *product)
3452{
3453	char tmp[100];
3454	char vid[32];
3455	char pid[32];
3456	char *ptr1, *ptr2;
3457	
3458	strcpy(tmp, product);
3459	ptr1=strchr(tmp, '/');
3460	*ptr1=0;	
3461	sprintf(vid, "vendor=0x%s", tmp);
3462	ptr2=strchr(ptr1+1, '/');
3463	*ptr2=0;
3464	sprintf(pid, "product=0x%s", ptr1+1);
3465	
3466	//logmessage("Remove USB Device VID", vid);
3467	//logmessage("Remove USB Device PID", pid);
3468	
3469	//if(interface)
3470	//	logmessage("Remove USB Device INTERFACE", interface);
3471	
3472	if (nvram_match("hsdpa_enable", "0")) return 0;
3473	
3474	if (nvram_match("hsdpa_product", product))
3475	{
3476		logmessage("Remove USB Modem", product);
3477		
3478		eval("rmmod", "usbserial");
3479		nvram_set("hsdpa_product", "");
3480		nvram_set("hsdpa_combo", "-1");
3481		
3482		// stop cdma
3483		nvram_set("cdma_down", "99");
3484		nvram_set("got_HSDPA", "0");
3485		
3486		return 1;
3487	}
3488	
3489	return 0;
3490}	
3491#endif // CDMA // HSDPA }
3492
3493/* plugging or removing usb device */
3494/* usbcore, usb-ohci, usb-ehci, printer are always there */
3495/* usb-storage, sd_mod, scsi_mod, videodev are there if functions are enabled */
3496/* pwc, ov511 i2c, depends on current status */
3497int
3498hotplug_usb(void)
3499{
3500	char *action, *interface, *product, *usb_path;
3501// 2009.05 James. HSDPA {
3502	char *num_interfaces;
3503	int numOfInterfaces;
3504	int isPrinter;
3505// 2009.05 James. HSDPA }
3506	int isweb;
3507	char flag[6];
3508#ifdef U2EC
3509	int u2ec_fifo;
3510#endif // U2EC
3511	char usbpath_nvram[16];
3512	char temp_usbpath_device[16];
3513	
3514	action = getenv("ACTION");
3515	interface = getenv("INTERFACE");
3516	product = getenv("PRODUCT");
3517	usb_path = getenv("USBDEVICE_PATH");
3518// 2009.05 James. HSDPA {
3519	num_interfaces = getenv("NUM_INTERFACES");
3520	num_interfaces = (num_interfaces == NULL || strlen(num_interfaces) <= 0)?"0":num_interfaces;
3521	numOfInterfaces = atoi(num_interfaces);
3522	isPrinter = atoi(getenv("ISPRINTER"));
3523// 2009.05 James. HSDPA }
3524	
3525#ifdef CDMA // HSDPA {
3526	if( !action)
3527#else // CDMA
3528	if( !action || !interface)
3529#endif // CDMA // HSDPA }
3530	{
3531		return EINVAL;
3532	}
3533	
3534	//nvram_set("usb_vidpid", product);
3535	
3536	if(usb_path){
3537		nvram_set("usb_path", usb_path);
3538		
3539		memset(usbpath_nvram, 0, 16);
3540		sprintf(usbpath_nvram, "usb_path%s", usb_path);
3541		
3542		memset(temp_usbpath_device, 0, 16);
3543		strcpy(temp_usbpath_device, nvram_safe_get(usbpath_nvram));
3544	}
3545	
3546	//if(product && strncmp(product, "0/", 2))
3547	if(product
3548// 2009.06 James. {
3549#ifdef WL500GPV2
3550			&& (!strcmp(usb_path, "1.1") || !strcmp(usb_path, "1.2"))
3551#elif WL520GU
3552			&& !strcmp(usb_path, "1")
3553#else
3554			&& strncmp(product, "0/", 2)
3555#endif
3556// 2009.06 James. }
3557			)
3558	{
3559		isweb = WEB_NONE;
3560		
3561#ifdef CDMA // HSDPA {
3562		if(!interface)
3563			goto usbhandler;
3564#endif // CDMA // HSDPA }
3565		
3566		if(!strncmp(interface, "8/", 2) && isPrinter != 1)
3567		{
3568			//logmessage("USB mass storage", "attached");
3569			
3570			isweb = MASS_STORAGE;
3571			goto usbhandler;
3572		}
3573		else if(!strncmp(interface, "7/", 2)) //2008.03.13 Yau add printer log
3574		{
3575// 2008.05 James. {
3576			//logmessage("USB printer", "attached");
3577			
3578			isweb = USB_PRINTER;
3579			goto usbhandler;
3580// 2008.05 James. }
3581		}
3582		else if(!strncmp(interface, "1/1", 3))
3583		{
3584			// if the audio device is the same with web cam,
3585			// just skip it
3586			if(nvram_match("usb_web_device", product)) 
3587				return 0;
3588			
3589			isweb = WEB_AUDIO;
3590			goto usbhandler;
3591		}
3592		else if(!strncmp(interface, "1/", 2))
3593		{
3594			return 0;
3595		}
3596		
3597		int i;
3598		
3599		i = 0;
3600		while(PWCLIST[i] != NULL)
3601		{
3602			if(strstr(product, PWCLIST[i]))
3603			{
3604				isweb = WEB_PWCWEB;
3605				goto usbhandler;
3606			}
3607			++i;
3608		}
3609		
3610		i = 0;
3611		while(OVLIST[i] != NULL)
3612		{
3613			if(strstr(product, OVLIST[i]))
3614			{
3615				isweb = WEB_OVWEB;
3616				goto usbhandler; 
3617			}
3618			++i;
3619		}
3620	}
3621	else
3622		return EINVAL;
3623	
3624usbhandler:
3625csprintf("- hotplug(%d): action=%s, interface=%s, product=%s, usb_path=%s, isPrinter=%d. -\n"
3626		, isweb
3627		, action
3628		, interface
3629		, product
3630		, usb_path
3631		, isPrinter
3632		);
3633	if (strstr(action, "add"))
3634	{
3635logmessage("Add device", "interface=%s, product=%s, usb_path=%s, isPrinter=%d."
3636		, interface
3637		, product
3638		, usb_path
3639		, isPrinter
3640		);
3641		if(isweb == MASS_STORAGE)
3642		{
3643			if(usb_path && strlen(temp_usbpath_device) <= 0){
3644				nvram_set("asus_mfg_flash", "1");
3645				
3646// 2008.06 James. {
3647				if(strlen(nvram_safe_get("usb_disc0_pid")) <= 0){
3648					nvram_set("usb_disc0_pid", product);
3649					nvram_set("usb_disc0_port", usb_path);
3650				}
3651				else if(strlen(nvram_safe_get("usb_disc1_pid")) <= 0){
3652					nvram_set("usb_disc1_pid", product);
3653					nvram_set("usb_disc1_port", usb_path);
3654				}
3655// 2008.06 James. }
3656				
3657				nvram_set("usb_storage_device", product); //watchdog will call hotplug_usb_mass if set
3658				nvram_set(usbpath_nvram, "storage");
3659				logmessage("USB storage", "\"%s\" was plugged in.", product);	// 2008.02 James.
3660			}
3661		}
3662// 2008.05 James. {
3663		else if(isweb == USB_PRINTER)
3664		{
3665			nvram_set("asus_mfg_printer", "1");
3666			
3667			if(nvram_match("usb_printer_device", ""))
3668				logmessage("USB printer", "\"%s\" was plugged in.", product);
3669			nvram_set("usb_printer_device", product);
3670			if(usb_path){
3671				nvram_set(usbpath_nvram, "printer");
3672				nvram_set("usb_path_printer", usb_path);
3673			}
3674		}
3675// 2008.05 James. }
3676		else if(isweb == WEB_AUDIO)
3677		{
3678#ifdef AUDIO_SUPPORT
3679			nvram_set("asus_mfg_audio", "1");
3680			
3681			if (nvram_match("usb_audio_device", ""))
3682				logmessage("USB audio", "attached");
3683			nvram_set("usb_audio_device", product);
3684			if(usb_path){
3685				nvram_set(usbpath_nvram, "audio");
3686				nvram_set("usb_path_audio", usb_path);
3687			}
3688			refresh_wave();
3689#else
3690			;
3691#endif // AUDIO_SUPPORT
3692		}
3693		else if(isweb == WEB_PWCWEB || isweb == WEB_OVWEB)
3694		{
3695#ifdef WEBCAM_SUPPORT
3696			nvram_set("asus_mfg_webcam", "1");
3697			
3698			if (nvram_match("usb_web_device", ""))
3699				logmessage("USB webcam", "attached");
3700
3701			sprintf(flag, "%d", isweb);
3702			nvram_set("usb_web_device", product);
3703			nvram_set("usb_web_flag", flag);
3704			nvram_set("usb_webdriver_x", "");
3705			if(usb_path){
3706				nvram_set(usbpath_nvram, "webcam");
3707				nvram_set("usb_path_webcam", usb_path);
3708			}
3709#else
3710			;
3711#endif // WEBCAM_SUPPORT
3712		}
3713		//else{
3714		else if(isPrinter != 1
3715				&& (strlen(temp_usbpath_device) <= 0
3716						|| !strcmp(temp_usbpath_device, "storage"))
3717				){
3718#ifdef CDMA // HSDPA {
3719			if(hotplug_hsdpa(product)){
3720				nvram_set("usb_hsdpa_device", product);
3721				if(usb_path){
3722					nvram_set(usbpath_nvram, "HSDPA");
3723					nvram_set("usb_path_hsdpa", usb_path);
3724				}
3725				
3726				//return 0;
3727			}
3728#else
3729			;
3730#endif // HSDPA }
3731		}
3732		
3733#ifdef U2EC
3734		u2ec_fifo = open("/tmp/u2ec_fifo", O_WRONLY|O_NONBLOCK);
3735		write(u2ec_fifo, "a", 1);
3736		close(u2ec_fifo);
3737#endif // U2EC
3738	}
3739	else //USB device removed
3740	{
3741logmessage("Remove device", "interface=%s, product=%s, usb_path=%s, isPrinter=%d."
3742		, interface
3743		, product
3744		, usb_path
3745		, isPrinter
3746		);
3747		if(isweb == MASS_STORAGE	// 2008.02 James.
3748				&& numOfInterfaces == 1 // 2009.05 James. HSDPA
3749				&& !strcmp(temp_usbpath_device, "storage")
3750				)
3751		{
3752			logmessage("USB device", "\"%s\" was removed.", product);	// 2008.02 James.
3753			
3754// 2008.06 James. {
3755			if(!strcmp(nvram_safe_get("usb_disc0_pid"), product)
3756					&& !strcmp(nvram_safe_get("usb_disc0_safely_removed"), "1")
3757					&& strlen(nvram_safe_get("usb_disc1_pid")) <= 0){
3758				nvram_set("usb_disc0_pid", "");
3759				nvram_set("usb_disc0_safely_removed", "0");
3760				
3761				//return 0;
3762			}
3763			else if(!strcmp(nvram_safe_get("usb_disc1_pid"), product)
3764					&& !strcmp(nvram_safe_get("usb_disc1_safely_removed"), "1")
3765					&& strlen(nvram_safe_get("usb_disc0_pid")) <= 0){
3766				nvram_set("usb_disc1_pid", "");
3767				nvram_set("usb_disc1_safely_removed", "0");
3768				
3769				//return 0;
3770			}
3771// 2008.06 James. }
3772			
3773#if 0 // 2009.06 James.
3774// 2009.05 James. {
3775#ifdef CDMA // HSDPA {
3776			if(!strncmp(product, "1a8d/", 5)
3777					|| !strncmp(product, "12d1/", 5)
3778					)
3779				;//return 0;
3780			else
3781#endif // HSDPA }
3782// 2009.05 James. }
3783#endif // 2009.06 James.
3784			
3785// 2007.12 James {
3786			//remove_usb_mass(product);
3787			nvram_set("usb_storage_device_remove", product);
3788// 2007.12 James }
3789		}
3790		else if(isweb == USB_PRINTER)
3791		{
3792			logmessage("USB printer", "\"%s\" was removed.", product);
3793			
3794			nvram_set("usb_printer_device", "");
3795			nvram_set("usb_path_printer", "");
3796		}
3797		else if(isweb == WEB_AUDIO)
3798		{
3799#ifdef AUDIO_SUPPORT
3800			logmessage("USB audio", "\"%s\" was removed.", product);
3801			
3802			remove_usb_audio(product);
3803			nvram_set("usb_audio_device", "");
3804			nvram_set("usb_path_audio", "");
3805#else
3806			;
3807#endif // AUDIO_SUPPORT
3808		}
3809		else if(isweb == WEB_PWCWEB || isweb == WEB_OVWEB)
3810		{
3811#ifdef WEBCAM_SUPPORT
3812			if (nvram_invmatch("usb_web_device", ""))
3813			{
3814				logmessage("USB webcam", "\"%s\" was removed.", product);
3815				
3816				remove_usb_webcam(product, isweb);
3817				nvram_set("usb_web_device", "");
3818				nvram_set("usb_web_flag", "");
3819				nvram_set("usb_path_webcam", "");
3820			}
3821#else
3822			;
3823#endif // WEBCAM_SUPPORT
3824		}
3825		//else{
3826		else if(!strcmp(temp_usbpath_device, "HSDPA")){
3827#ifdef CDMA // HSDPA {
3828			if(unplug_hsdpa(product)){
3829				nvram_set("usb_hsdpa_device", "");
3830				nvram_set("usb_path_hsdpa", "");
3831				
3832				//return 0;
3833			}
3834#else
3835			;
3836#endif // HSDPA }
3837		}
3838		
3839#ifdef U2EC
3840		u2ec_fifo = open("/tmp/u2ec_fifo", O_WRONLY|O_NONBLOCK);
3841		write(u2ec_fifo, "r", 1);
3842		close(u2ec_fifo);
3843#endif // U2EC
3844		
3845		if(usb_path)
3846			nvram_set(usbpath_nvram, "");
3847	}
3848	
3849	return 0;
3850}
3851#endif // USB_SUPPORT
3852
3853/* stop necessary services for firmware upgrade */	
3854/* stopservice: for firmware upgarde */
3855/* stopservice 1: for button setup   */
3856int
3857stop_service_main(int type)
3858{
3859	if (type==1)
3860	{
3861		//stop_misc();
3862		//stop_logger();
3863		stop_usb();
3864		stop_nas();
3865		stop_upnp();
3866		//stop_dhcpd();
3867		stop_dns();
3868		stop_httpd();
3869		eval("killall", "udhcpc");
3870		//eval("killall", "infosvr");
3871	}
3872	else
3873	{
3874		if(type==99) stop_misc_no_watchdog();
3875		else stop_misc();
3876		stop_logger();
3877		stop_usb();
3878
3879		//stop_nas();	// mark this for upgrade firmware with wireless.
3880		stop_upnp();
3881		stop_dhcpd();
3882		stop_dns();
3883	}
3884
3885	dprintf("done\n");
3886	return 0;
3887}
3888
3889int service_handle(void)
3890{
3891	char *service;
3892	char tmp[100], *str;
3893	int pid;
3894	char *ping_argv[] = { "ping", "140.113.1.1", NULL};
3895	FILE *fp;
3896
3897	service = nvram_get("rc_service");
3898
3899	if(!service)
3900		kill(1, SIGHUP);
3901
3902	if(strstr(service,"wan_disconnect")!=NULL)
3903	{
3904		cprintf("wan disconnect\n");
3905
3906		logmessage("WAN Connection", "Disconnected manually");
3907
3908#ifdef CDMA // HSDPA test
3909		if(nvram_invmatch("hsdpa_product", "") && nvram_invmatch("hsdpa_combo", "-1")){
3910printf("--- HSDPA test: disconnect! ---\n");
3911			nvram_set("cdma_down", "3");
3912		}
3913		else
3914#endif // CDMA*/
3915		if (nvram_match("wan0_proto", "dhcp")
3916#ifdef BIGPOND
3917				|| nvram_match("wan0_proto", "bigpond")
3918#endif // BIGPOND
3919/*#ifdef CDMA // HSDPA test
3920				//|| nvram_match("wan0_proto_t", "cdma")
3921				|| nvram_invmatch("hsdpa_combo", "-1")
3922#endif // CDMA*/
3923			)
3924		{		
3925			snprintf(tmp, sizeof(tmp), "/var/run/udhcpc%d.pid", 0);
3926			if ((str = file2str(tmp))) {
3927				pid = atoi(str);
3928				free(str);
3929				kill(pid, SIGUSR2);
3930			}
3931		}
3932		else 
3933		{			
3934			stop_wan2();
3935			update_wan_status(0);
3936			sleep(3);
3937		}
3938	}
3939	else if (strstr(service,"wan_connect")!=NULL)
3940	{
3941		cprintf("wan connect\n");
3942		logmessage("WAN Connection", "Connected manually");
3943		setup_ethernet(nvram_safe_get("wan_ifname"));
3944
3945#ifdef CDMA // HSDPA test
3946		if(nvram_invmatch("hsdpa_product", "") && nvram_invmatch("hsdpa_combo", "-1")){
3947printf("--- HSDPA test: connect! ---\n");
3948			nvram_set("cdma_down", "1");
3949		}
3950		else
3951#endif // CDMA*/
3952		if (nvram_match("wan0_proto", "dhcp")
3953#ifdef BIGPOND
3954				|| nvram_match("wan0_proto", "bigpond")
3955#endif // BIGPOND
3956/*#ifdef CDMA // HSDPA test
3957				//|| nvram_match("wan0_proto_t", "cdma")
3958				|| nvram_invmatch("hsdpa_combo", "-1")
3959#endif // CDMA*/
3960			)
3961		{
3962			snprintf(tmp, sizeof(tmp), "/var/run/udhcpc%d.pid", 0);
3963			if ((str = file2str(tmp))) {
3964				pid = atoi(str);
3965				free(str);
3966				kill(pid, SIGUSR1);
3967			}
3968		}
3969		else 
3970		{
3971#ifndef REMOVE
3972			// pppoe or ppptp, check if /tmp/ppp exist
3973			if (nvram_invmatch("wan0_proto", "static") && (fp=fopen("/tmp/ppp/ip-up", "r"))!=NULL)
3974			{
3975				fclose(fp);
3976				_eval(ping_argv, NULL, 0, &pid);
3977			}
3978			else
3979			{
3980				stop_wan();
3981				sleep(3);
3982				start_wan();
3983				sleep(2);
3984				_eval(ping_argv, NULL, 0, &pid);
3985			}
3986#else // REMOVE
3987			stop_wan();
3988			sleep(2);
3989			start_wan();
3990			/* trigger connect */
3991			eval("ntpclient", "-h", "test", "-c", "1");
3992#endif // REMOVE
3993
3994		}
3995	}
3996#ifdef ASUS_DDNS //2007.03.26 Yau add for asus ddns
3997	else if(strstr(service,"ddns_hostname_check") != NULL)
3998	{
3999		char host[64];
4000		char wan_ifname[16];
4001		
4002		strcpy(host, nvram_get("ddns_hostname_x"));
4003#ifdef CDMA // HSDPA
4004		if(strcmp(nvram_safe_get("hsdpa_product"), "") != 0)
4005			strcpy(wan_ifname, "ppp0");
4006		else
4007#endif
4008		if(nvram_match("wan_proto", "pppoe") || nvram_match("wan_proto", "pptp") || nvram_match("wan_proto", "l2tp"))
4009			strcpy(wan_ifname, nvram_get("wan0_pppoe_ifname"));
4010		else
4011			strcpy(wan_ifname, nvram_get("wan0_ifname"));
4012		
4013		char *ddns_argv[] = {"ez-ipupdate",
4014												 "-h", host,
4015												 "-s", "ns1.asuscomm.com",
4016												 "-S", "dyndns",
4017												 "-i", wan_ifname,
4018												 "-A", "1",
4019												 NULL};
4020		pid_t pid;
4021		
4022		//Execute ez-ipupdate then die.
4023		eval("killall", "ez-ipupdate");
4024		_eval(ddns_argv, NULL, 0, &pid);
4025	}
4026#endif // ASUS_DDNS
4027
4028	nvram_unset("rc_service");
4029	return 0;
4030}
4031
4032#ifdef AUDIO_SUPPORT
4033int hotplug_usb_audio(char *product)
4034{					
4035	char *wave_argv[]={"waveserver", NULL};
4036	pid_t pid;
4037
4038	if (strlen(product)==0) return;
4039	return _eval(wave_argv, ">/dev/null", 0, NULL);	// 2007.11 James. add "return"
4040}
4041
4042int remove_usb_audio(char *product)
4043{
4044	return eval("killall", "waveserver");	// 2007.11 James. add "return"
4045}
4046
4047int
4048start_audio(void)
4049{
4050	char *wave_argv[] = {"waveservermain", NULL};
4051	pid_t pid;
4052
4053	_eval(wave_argv, NULL, 0, &pid);
4054	return 0;
4055}
4056
4057int
4058stop_audio(void)
4059{
4060	int ret = eval("killall", "waveserver");
4061	return ret;	// 2007.11 James.
4062}
4063#endif // AUDIO_SUPPORT
4064
4065#ifdef GUEST_ACCOUNT
4066int
4067start_dhcpd_guest(void)
4068{
4069	FILE *fp;
4070	char *dhcpd_argv[] = {"udhcpd", "/tmp/udhcpd1.conf", NULL, NULL};
4071	char *slease = "/tmp/udhcpd-br1.sleases";
4072	pid_t pid;
4073
4074	if (nvram_match("router_disable", "1") || nvram_invmatch("wl_guest_enable", "1") || nvram_invmatch("lan1_proto", "dhcp"))
4075		return 0;
4076
4077	dprintf("%s %s %s %s\n",
4078		nvram_safe_get("lan1_ifname"),
4079		nvram_safe_get("dhcp1_start"),
4080		nvram_safe_get("dhcp1_end"),
4081		nvram_safe_get("lan1_lease"));
4082
4083	if (!(fp = fopen("/tmp/udhcpd-br1.leases", "a"))) {
4084		perror("/tmp/udhcpd-br1.leases");
4085		return errno;
4086	}
4087	fclose(fp);
4088
4089	/* Write configuration file based on current information */
4090	if (!(fp = fopen("/tmp/udhcpd1.conf", "w"))) {
4091		perror("/tmp/udhcpd1.conf");
4092		return errno;
4093	}
4094	
4095	fprintf(fp, "pidfile /var/run/udhcpd-br1.pid\n");
4096	fprintf(fp, "start %s\n", nvram_safe_get("dhcp1_start"));
4097	fprintf(fp, "end %s\n", nvram_safe_get("dhcp1_end"));
4098	fprintf(fp, "interface %s\n", nvram_safe_get("lan1_ifname"));
4099	fprintf(fp, "remaining yes\n");
4100	fprintf(fp, "lease_file /tmp/udhcpd-br1.leases\n");
4101	fprintf(fp, "option subnet %s\n", nvram_safe_get("lan1_netmask"));
4102	fprintf(fp, "option router %s\n", nvram_safe_get("lan1_ipaddr"));	
4103	
4104	if (nvram_invmatch("dhcp_dns1_x",""))		
4105		fprintf(fp, "option dns %s\n", nvram_safe_get("dhcp_dns1_x"));		
4106	fprintf(fp, "option dns %s\n", nvram_safe_get("lan1_ipaddr"));
4107	fprintf(fp, "option lease %s\n", nvram_safe_get("lan1_lease"));
4108
4109	if (nvram_invmatch("dhcp_wins_x",""))		
4110		fprintf(fp, "option wins %s\n", nvram_safe_get("dhcp_wins_x"));		
4111	if (nvram_invmatch("lan_domain", ""))
4112		fprintf(fp, "option domain %s\n", nvram_safe_get("lan_domain"));
4113	fclose(fp);
4114
4115	dhcpd_argv[2] = NULL;
4116	_eval(dhcpd_argv, NULL, 0, &pid);
4117
4118
4119	dprintf("done\n");
4120	return 0;
4121}
4122
4123int
4124stop_dhcpd_guest(void)
4125{
4126	char sigusr1[] = "-XX";
4127	int ret;
4128
4129/*
4130* Process udhcpd handles two signals - SIGTERM and SIGUSR1
4131*
4132*  - SIGUSR1 saves all leases in /tmp/udhcpd.leases
4133*  - SIGTERM causes the process to be killed
4134*
4135* The SIGUSR1+SIGTERM behavior is what we like so that all current client
4136* leases will be honorred when the dhcpd restarts and all clients can extend
4137* their leases and continue their current IP addresses. Otherwise clients
4138* would get NAK'd when they try to extend/rebind their leases and they 
4139* would have to release current IP and to request a new one which causes 
4140* a no-IP gap in between.
4141*/
4142	ret = eval("killall", "udhcpd");
4143
4144	dprintf("done\n");
4145	return ret;
4146}
4147#endif // GUEST_ACCOUNT
4148
4149#ifdef DLM
4150// 2007.11 James. replace this with using eval("/sbin/write_smb_conf") for new samba mode.
4151void write_smb_conf()
4152{
4153	struct dirent *dp;
4154	FILE *fp;
4155	DIR *dir_to_open=NULL;
4156	int n=0, sh_num=0;
4157	char *tmp1=NULL;
4158	char SHMAX[32];
4159	char SMB_SHNAME[64];
4160	char SHNM[16];
4161	char SMB_SHCOMMENT[64];
4162	char SHCM[16];
4163	char SMB_SHPATH[104];
4164	char SHPH[32];
4165	char SHAU[16];
4166	char SMB_SHRRIGHT[384];
4167	char SHRR[384];
4168	char SMB_SHWRIGHT[384];
4169	char SHWR[384];
4170	char SMB_SHACCUSER[384];
4171	
4172// write smb.conf
4173	if((fp=fopen("/tmp/samba/lib/smb.conf", "r")))
4174	{
4175		fclose(fp);
4176		//eval("rm", "-f", "/tmp/samba/lib/smb.conf");
4177		unlink("/tmp/samba/lib/smb.conf");	// 2008.08 James.
4178	}
4179	fp = fopen("/tmp/samba/lib/smb.conf", "w");
4180	fprintf(fp, "[global]\n");
4181	if(nvram_safe_get("st_samba_workgroup"))
4182		fprintf(fp, "workgroup = %s\n", nvram_safe_get("st_samba_workgroup"));
4183	if(nvram_safe_get("computer_name"))
4184		fprintf(fp, "netbios name = %s\n", nvram_safe_get("computer_name"));
4185	fprintf(fp, "server string = WL500g.Premium version 2\n");
4186	eval("mkdir", "-p", "/tmp/var/log/samba");
4187	fprintf(fp, "log file = /tmp/var/log/samba/samba.log\n");
4188	fprintf(fp, "log level = 0\n");
4189	fprintf(fp, "max log size = 5\n");
4190 
4191// share mode
4192	if(!strcmp(nvram_safe_get("st_samba_modex"), "1"))
4193	{
4194		fprintf(fp, "security = SHARE\n");
4195		fprintf(fp, "guest ok = yes\n");
4196		fprintf(fp, "guest only = yes\n");
4197	}
4198	else
4199	{
4200		fprintf(fp, "security = USER\n");
4201		fprintf(fp, "guest ok = no\n");
4202		fprintf(fp, "map to guest = Bad User\n");
4203	}
4204	fprintf(fp, "writeable = yes\n");
4205	fprintf(fp, "directory mode = 0777\n");
4206	fprintf(fp, "create mask = 0777\n");
4207// max users
4208	sprintf(SHMAX, "st_max_user");
4209	if(strcmp(nvram_safe_get(SHMAX), "")!=0)
4210		fprintf(fp, "max connections = %s\n", nvram_safe_get(SHMAX));
4211	fprintf(fp, "encrypt passwords = yes\n");
4212	fprintf(fp, "pam password change = no\n");
4213	fprintf(fp, "obey pam restrictions = no\n");
4214	fprintf(fp, "socket options = TCP_NODELAY SO_KEEPALIVE SO_RCVBUF=16384 SO_SNDBUF=16384\n");
4215	fprintf(fp, "dns proxy = no\n");
4216// share
4217	if(!strcmp(nvram_safe_get("st_samba_modex"), "0") || !strcmp(nvram_safe_get("st_samba_modex"), ""))
4218	{
4219		;
4220	}
4221	else if(!strcmp(nvram_safe_get("st_samba_modex"), "1"))
4222	{
4223		printf("samba mode: share\n");
4224		if(!(dir_to_open = opendir("/tmp/harddisk")))
4225		{
4226			perror("***cannot open /tmp/harddisk\n");
4227			goto confpage;
4228		}
4229		n = 0;
4230		if(dir_to_open)
4231		{
4232			while(dp=readdir(dir_to_open))
4233			{
4234				if(strncmp(dp->d_name, "..", NAME_MAX) != 0 && strncmp(dp->d_name, ".", NAME_MAX) != 0 )
4235				{
4236					sprintf(SMB_SHNAME, "%s", dp->d_name);
4237					sprintf(SMB_SHCOMMENT, "%s", dp->d_name);
4238					sprintf(SMB_SHPATH, "/tmp/harddisk/%s", dp->d_name);
4239					printf("%s\n", SMB_SHPATH);
4240					fprintf(fp, "[%s]\n", SMB_SHNAME);
4241					fprintf(fp, "comment = %s\n", SMB_SHCOMMENT);
4242					fprintf(fp, "path = %s\n", SMB_SHPATH);
4243					fprintf(fp, "guest ok = yes\n");
4244					fprintf(fp, "writeable = yes\n");
4245					fprintf(fp, "directory mode = 0777\n");
4246					fprintf(fp, "create mask = 0777\n");
4247				}
4248			}
4249		}
4250		if(dir_to_open)
4251			closedir(dir_to_open);
4252	}
4253	else // st_samba_mode = 2
4254	{
4255	printf("samba mode: user\n");
4256	n = 0;
4257	sh_num = atoi(nvram_safe_get("sh_num"));
4258	while(n<sh_num)
4259	{
4260		sprintf(SHPH, "sh_path%d", n);
4261		sprintf(SHNM, "sh_name%d", n);
4262		sprintf(SHRR, "sh_rright%d", n);
4263		sprintf(SHWR, "sh_wright%d", n);
4264		sprintf(SHCM, "sh_comment%d", n);
4265		sprintf(SHAU, "sh_acc_user%d", n);
4266		sprintf(SMB_SHPATH, "/tmp/harddisk%s", nvram_safe_get(SHPH));
4267		sprintf(SMB_SHNAME, "%s", nvram_safe_get(SHNM));
4268		sprintf(SMB_SHRRIGHT, "%s", nvram_safe_get(SHRR));
4269		sprintf(SMB_SHWRIGHT, "%s", nvram_safe_get(SHWR));
4270		sprintf(SMB_SHACCUSER, "%s", nvram_safe_get(SHAU));
4271
4272		while(tmp1=strchr(SMB_SHRRIGHT, ';'))
4273			memcpy(tmp1, " ", 1);
4274		memcpy(SMB_SHRRIGHT+strlen(SMB_SHRRIGHT)-1, "\0", 1);
4275		while(tmp1=strchr(SMB_SHWRIGHT, ';'))
4276			memcpy(tmp1, " ", 1);
4277		memcpy(SMB_SHWRIGHT+strlen(SMB_SHWRIGHT)-1, "\0", 1);
4278		while(tmp1=strchr(SMB_SHACCUSER, ';'))
4279			memcpy(tmp1, " ", 1);
4280		memcpy(SMB_SHACCUSER+strlen(SMB_SHACCUSER)-1, "\0", 1);
4281		sprintf(SMB_SHCOMMENT, "%s", nvram_safe_get(SHCM));
4282		// write to conf
4283		if(!strcmp(SMB_SHNAME, ""))
4284		{
4285			goto endloop;
4286		}
4287		if(!(dir_to_open = opendir(SMB_SHPATH)))
4288		{
4289			goto endloop;
4290		}
4291		else
4292			closedir(dir_to_open);
4293		fprintf(fp, "[%s]\n", SMB_SHNAME);
4294		fprintf(fp, "comment = %s\n", SMB_SHCOMMENT);
4295		fprintf(fp, "path = %s\n", SMB_SHPATH);
4296		if(strstr(SMB_SHWRIGHT, "Guest"))
4297		{
4298				fprintf(fp, "guest ok = yes\n");
4299		}
4300		else
4301		{
4302			if(strstr(SMB_SHRRIGHT, "Guest"))
4303			{
4304				fprintf(fp, "guest ok = yes\n");
4305				fprintf(fp, "writeable = no\n");
4306				fprintf(fp, "write list = %s\n", SMB_SHWRIGHT);
4307			}
4308			else
4309			{
4310				if(!strcmp(SMB_SHWRIGHT, "")&&!strcmp(SMB_SHRRIGHT, ""))
4311					fprintf(fp, "valid users = _an_si_un_se_shorti_\n");
4312				else
4313					fprintf(fp, "valid users = %s\n", SMB_SHACCUSER);
4314				fprintf(fp, "writeable = no\n");
4315				fprintf(fp, "write list = %s\n", SMB_SHWRIGHT);
4316				fprintf(fp, "read list = %s\n", SMB_SHRRIGHT);
4317			}
4318		}
4319		fprintf(fp, "directory mode = 0777\n");
4320		fprintf(fp, "create mask = 0777\n");
4321		// write to conf
4322endloop:
4323		n++;
4324	}
4325	}// st_samba_mode = 2
4326confpage:	
4327	fclose(fp);
4328}
4329
4330int
4331start_samba(void)	// added by Jiahao for WL500gP
4332{
4333	FILE *fp;
4334	int n=0, sh_num=0, i;
4335	char *tmp1=NULL, *tmp2=NULL;
4336	int ret1=0, ret2=0;
4337
4338	stop_samba(); // 2007.11 James. for new samba mode
4339	
4340/* write samba configure file*/
4341	//write_smb_conf();
4342	eval("/sbin/write_smb_conf");	// 2007.11 James. for new samba mode
4343
4344/* write /etc/passwd */
4345	if((fp=fopen("/tmp/passwd", "r")))
4346	{
4347		fclose(fp);
4348		//eval("rm", "-f", "/tmp/passwd");
4349		unlink("/tmp/passwd");	// 2008.08 James.
4350	}
4351	fp = fopen("/tmp/passwd", "w");
4352	fprintf(fp, "nobody:x:99:99:::\n");
4353	sh_num = atoi(nvram_safe_get("acc_num"));
4354	tmp1 = (char *)malloc(33);
4355	for(i=0, n=500; i<sh_num; i++, n++)
4356	{
4357		sprintf(tmp1, "acc_username%d", i);
4358		fprintf(fp, "%s:x:%d:%d:::\n", nvram_safe_get(tmp1), n, n);
4359	}
4360	if (tmp1) free(tmp1);
4361	fclose(fp);
4362/* write /etc/group  */
4363	if((fp=fopen("/tmp/group", "r")))
4364	{
4365		fclose(fp);
4366		//eval("rm", "-f", "/tmp/group");
4367		unlink("/tmp/group");	// 2008.08 James.
4368	}
4369	fp = fopen("/tmp/group", "w");
4370	fprintf(fp, "nobody:x:99:\n");
4371	sh_num = atoi(nvram_safe_get("acc_num"));
4372	tmp1 = (char *)malloc(33);
4373	for(i=0, n=500; i<sh_num; i++, n++)
4374	{
4375		sprintf(tmp1, "acc_username%d", i);
4376		fprintf(fp, "%s:x:%d:\n", nvram_safe_get(tmp1), n);
4377	}
4378	if (tmp1) free(tmp1);
4379	fclose(fp);
4380/* write smbpasswd  */
4381	eval("/usr/local/samba/bin/smbpasswd", "-a", "nobody", "\"\"");
4382	sh_num = atoi(nvram_safe_get("acc_num"));
4383	tmp1 = (char *)malloc(33);
4384	tmp2 = (char *)malloc(33);
4385	for(i=0; i<sh_num; i++)
4386	{
4387		sprintf(tmp1, "acc_username%d", i);
4388		sprintf(tmp2, "acc_password%d", i);
4389		sprintf(tmp1, nvram_safe_get(tmp1));
4390		sprintf(tmp2, nvram_safe_get(tmp2));
4391		eval("/usr/local/samba/bin/smbpasswd", "-a", tmp1, tmp2);
4392	}
4393	if (tmp1) free(tmp1);
4394	if (tmp2) free(tmp2);
4395
4396	ret1 = eval("/usr/local/samba/sbin/smbd", "-D", "-s", "/tmp/samba/lib/smb.conf");
4397	ret2 = eval("/usr/local/samba/sbin/nmbd", "-D", "-s", "/tmp/samba/lib/smb.conf");
4398
4399	if(!ret1 && !ret2)
4400	{
4401		//if (nvram_match("st_samba_modex", "1"))
4402		if(nvram_match("st_samba_mode", "1") || nvram_match("st_samba_mode", "3"))	// 2007.11 James.
4403			nvram_set("st_samba_mode_x", "1");
4404		else
4405			nvram_set("st_samba_mode_x", "0");
4406
4407		fprintf(stderr, "Starting samba\n");
4408		logmessage("Samba Server", "daemon is started");
4409		return 0;
4410		
4411	}
4412	else
4413	{
4414		eval("killall", "-SIGKILL", "smbd");
4415		eval("killall", "-SIGKILL", "nmbd");
4416		nvram_set("st_samba_mode_x", "0");	// 2007.11 James.
4417		return 1;
4418	}
4419}
4420#endif // DLM
4421
4422int
4423check_disk_free(char *res, char *diskpath)	// added by Jiahao for WL500gP
4424{
4425	char *sizebuf, *freebuf, *databuf;
4426	struct statfs fsbuf;
4427
4428	if(statfs(diskpath, &fsbuf))
4429	{
4430		perror("*** check_disk_free: statfs fail!");
4431		return 2;
4432	}
4433
4434	sizebuf = malloc(32);
4435	freebuf = malloc(32);
4436	databuf = malloc(64);
4437
4438	sprintf(sizebuf, "%.1f", (double)((double)((double)fsbuf.f_blocks * fsbuf.f_bsize)/(1024*1024)));
4439	sprintf(freebuf, "%.1f", (double)((double)((double)fsbuf.f_bfree * fsbuf.f_bsize)/(1024*1024)));
4440	sprintf(res, "size: %s, free: %s", sizebuf, freebuf);
4441
4442	if(sizebuf) 
4443		free(sizebuf);
4444	if(freebuf) 
4445		free(freebuf);
4446	if(databuf) 
4447		free(databuf);
4448	if(fsbuf.f_bfree == 0)
4449		return 0;
4450	else
4451		return 1;
4452}
4453
4454#ifdef DLM
4455int
4456check_disk_free_GE_1G(char *diskpath)	// added by Jiahao for WL500gP
4457{
4458	struct statfs fsbuf;
4459
4460	if(statfs(diskpath, &fsbuf))
4461	{
4462		perror("*** check_disk_free_GE_1G: statfs fail!");
4463		return 0;
4464	}
4465
4466	if ( (double)((double)((double)fsbuf.f_bfree * fsbuf.f_bsize)/(1024*1024)) < (double)33 )
4467		return 1;
4468	else if ( (double)((double)((double)fsbuf.f_blocks * fsbuf.f_bsize)/(1024*1024)) > (double)512 )
4469		return 2;
4470	else
4471		return 3;
4472}
4473
4474int
4475check_disk_free_apps(char *diskpath, int ac_flag)			// added by Jiahao for WL500gP
4476{
4477	struct statfs fsbuf;
4478
4479	if(statfs(diskpath, &fsbuf))
4480	{
4481		perror("*** check_disk_free_apps: statfs fail!");
4482		return 0;
4483	}
4484
4485	if (ac_flag==1)
4486	{
4487		if (nvram_match("apps_dlx", "0"))
4488			return 1;
4489
4490		if ( (double)((double)((double)fsbuf.f_bfree * fsbuf.f_bsize)/(1024*1024)) < (double)1 )
4491			return 0;
4492		else
4493			return 1;
4494	}
4495	else
4496	{
4497		if ( (double)((double)((double)fsbuf.f_bfree * fsbuf.f_bsize)/(1024*1024)) < (double)5 )
4498			return 0;
4499		else
4500			return 1;
4501	}
4502}
4503#endif // DLM
4504
4505void
4506get_disc_desc(char * vendor_product, int discorder, int discindex) {	// added by Jiahao for WL500gP
4507	FILE* fp;
4508	DIR *dir_to_open, *dir_to_open2;
4509	struct dirent *dp, *dp2;
4510	char str_path[128];
4511	char temp[80];
4512	char temp2[80];
4513	char temp3[32];
4514	char temp4[64];
4515	char temp5[64];
4516	char port[128];
4517	char tempstr[1];
4518	char host[128];
4519	char *p, *p2;
4520	
4521	strcpy(vendor_product, "");
4522	
4523	if( dir_to_open = opendir("/proc/scsi") )
4524	{
4525		while(dp=readdir(dir_to_open))
4526		{
4527			if(	!strncmp(dp->d_name, "..", NAME_MAX)	|| 
4528		           	!strncmp(dp->d_name, ".", NAME_MAX)	||
4529		           	!strncmp(dp->d_name, "sg", NAME_MAX)	||
4530		          	!strncmp(dp->d_name, "scsi", NAME_MAX)	)
4531				continue;
4532			sprintf(str_path, "/proc/scsi/%s", dp->d_name);
4533			if (dir_to_open2 = opendir(str_path))
4534			{
4535				while(dp2=readdir(dir_to_open2))
4536				{
4537					if(	!strncmp(dp2->d_name, "..", NAME_MAX)	|| 
4538		           			!strncmp(dp2->d_name, ".", NAME_MAX)	)
4539						continue;
4540					sprintf(temp3, "/dev/discs/disc%d", discorder);
4541					sprintf(temp5, "../scsi/host%s/bus0/target0/lun0", dp2->d_name);
4542					readlink(temp3, temp4, 64);
4543					if (strncmp(temp5, temp4, 13)!=0)
4544						break;
4545					else
4546					{
4547						if (fp=fopen("/proc/scsi/scsi", "r"))
4548						{
4549							while (fgets(temp,80,fp)!=NULL)
4550							{
4551								if (p=strstr(temp, "Host: scsi"))
4552								{
4553									p+=10;
4554									sprintf(host, p);
4555									memcpy(host+1, "\0", 1);
4556									continue;
4557								}
4558								if (p=strstr(temp, "Vendor: "))
4559								{
4560									if(!strcmp(dp2->d_name, host))
4561									{
4562										sprintf(vendor_product, p);
4563										p2=strstr(temp, "Rev: ");
4564										memcpy(vendor_product+strlen(p)-strlen(p2)-1, "\0", 1);
4565										break;
4566									}
4567								}
4568							}
4569							fclose(fp);
4570						}
4571
4572						sprintf(str_path, "/proc/scsi/%s/%s", dp->d_name, dp2->d_name);
4573						if (fp=fopen(str_path, "r"))
4574						{
4575							while (fgets(temp,80,fp)!=NULL)
4576							{
4577								if (strstr(temp, "Port: "))
4578								{
4579									if (p=strstr(temp, ": "))
4580									{
4581#ifdef DLM
4582										p+=4; //+2 for WL500GP +4 due to Port: 1.2
4583#else // DLM
4584										p+=2;
4585#endif // DLM
4586										sprintf(port, p);
4587										memcpy(port+strlen(port)-1, "\0", 1);
4588										
4589										sprintf(temp2, "usb_disc%d_port", discindex);
4590										nvram_set(temp2, port);
4591										strcpy(tempstr, port);
4592										if (strcmp(tempstr, "1")==0)
4593											sprintf(port, "[USB Lower port]\n");
4594										else
4595											sprintf(port, "[USB Upper port]\n");
4596									}
4597									break;
4598								}
4599							}
4600							fclose(fp);
4601							strcat(port, vendor_product);
4602							strcpy(vendor_product, port);
4603						}
4604						else
4605							strcpy(vendor_product, "");
4606					}
4607				}
4608				closedir(dir_to_open2);
4609			}
4610		}
4611		closedir(dir_to_open);
4612	}
4613}
4614
4615void
4616write_per_disc_status(int disc_index)
4617{
4618	FILE *fp;
4619	char usb_disc_mount_path[128], usb_disc_fs_path[128];
4620	int i, j;
4621	char *temp=(char *)malloc(128);
4622	char disc_dev_str[32];
4623	char disc_idx_str[32];
4624	int disc_order[2];
4625	disc_order[0]=atoi(nvram_get("usb_disc0_dev")+14);
4626	disc_order[1]=atoi(nvram_get("usb_disc1_dev")+14);
4627	
4628	fp = fopen("/tmp/usstatus", "a");
4629	if (fp)
4630	{
4631		sprintf(disc_dev_str, "usb_disc%d_dev", disc_index);
4632		sprintf(disc_idx_str, "usb_disc%d_index", disc_index);
4633		if (nvram_invmatch(disc_dev_str, "") && nvram_invmatch(disc_idx_str, "0"))
4634		{
4635			get_disc_desc(temp, disc_order[disc_index], disc_index);
4636			printf("%s\n", temp);
4637			fprintf(fp, "%s\n", temp);
4638			i=atoi(nvram_safe_get(disc_idx_str));
4639			for(j=0; j<i; j++)
4640			{
4641				sprintf(usb_disc_mount_path, "usb_disc%d_path%d", disc_index, j);
4642				printf("%s ", nvram_safe_get(usb_disc_mount_path));
4643				sprintf(usb_disc_fs_path, "usb_disc%d_fs_path%d", disc_index, j);
4644				printf("%s ", nvram_safe_get(usb_disc_fs_path));					
4645				if (check_disk_free(temp, nvram_safe_get(usb_disc_mount_path))==2)
4646					sprintf(temp, "unknown");
4647				printf("%s\n", temp);
4648				fprintf(fp, "Partition %d: %s\n", j+1, temp);
4649			}
4650		}
4651		else
4652			fprintf(stderr, "skip write usstatus\n");
4653	}
4654	else
4655		fprintf(stderr, "can not open /tmp/usstatus\n");
4656	if (fp)
4657		fclose(fp);
4658}
4659
4660void
4661write_disc_status()	// added by Jiahao for WL500gP
4662{
4663	int disc0_port=atoi(nvram_get("usb_disc0_port"));
4664	unlink("/tmp/usstatus");
4665
4666	if (disc0_port==2)
4667	{
4668		write_per_disc_status(0);
4669		write_per_disc_status(1);
4670	}
4671	else
4672	{
4673		write_per_disc_status(1);
4674		write_per_disc_status(0);
4675	}
4676}
4677
4678int                                     // added by Jiahao for WL500gP
4679check_if_file_exist(char *filename)
4680{
4681        FILE *fp;
4682        fp=fopen(filename, "r");
4683        if(fp)
4684        {
4685                fclose(fp);
4686                return 1;
4687        }
4688        else
4689                return 0;
4690}
4691
4692int                                     // added by Jiahao for WL500gP
4693check_if_dir_exist(char *dir)
4694{
4695        DIR *dp;
4696        if(!(dp=opendir(dir)))
4697                return 0;
4698        closedir(dp);
4699        return 1;
4700}
4701
4702int
4703mkdir_if_none(char *dir)                // added by Jiahao for WL500gP
4704{
4705        DIR *dp;
4706        if(!(dp=opendir(dir)))
4707        {
4708                umask(0000);
4709                mkdir(dir, 0777);
4710//              umask(0022);
4711                return 1;
4712        }
4713        closedir(dp);
4714        return 0;
4715}
4716#ifdef DLM
4717void set_apps_ver()
4718{
4719	nvram_set("apps_ver", "1.00");
4720}
4721
4722void exec_dms()
4723{
4724	char name[32];
4725	char mymac[32];
4726	char path[256];
4727	char tmpstr2[256];
4728	int ret = 0;
4729	
4730	mkdir_if_none("/shares/DMSRoot");
4731	
4732	strcpy(name, nvram_safe_get("computer_name"));
4733	strcpy(mymac, nvram_safe_get("et0macaddr"));
4734	
4735	if(nvram_match("apps_dmsx", "1")){
4736		sprintf(path, "%s", nvram_get("first_partition"));
4737		sprintf(tmpstr2, "dms %s \"%s\" %s &", path, name, mymac);
4738		ret = system(tmpstr2);
4739		if(!ret)
4740			logmessage("Media Server", "daemon is started");
4741	}
4742}
4743
4744void exec_apps()		// added by Jiahao for WL500gP
4745{	
4746	FILE *fp;
4747	
4748	char pool[32];
4749	char share[32];
4750	char rundl[8];
4751	char rundms[8];
4752	char name[32];
4753	char mymac[32];
4754	int cap=0;
4755	int ret=0;
4756
4757	char EXBIN[32]="/.apps/bin";
4758	char test_path[128];
4759
4760	char tmpstr[256];
4761	char tmpstr2[256];
4762	char share_port_from[5];
4763	char share_port_to[5];
4764
4765	if ( nvram_match("apps_dms_usb_port_x", nvram_safe_get("usb_disc0_port")) )
4766	{
4767		strcpy(test_path, nvram_safe_get("usb_disc0_path0"));
4768	}
4769	else if ( nvram_match("apps_dms_usb_port_x", nvram_safe_get("usb_disc1_port")) )
4770	{
4771		strcpy(test_path, nvram_safe_get("usb_disc1_path0"));
4772	}
4773	strcpy(tmpstr, EXBIN);
4774	sprintf(EXBIN, "%s%s", test_path, tmpstr);
4775	
4776	eval("killall", "dms");
4777	eval("killall", "snarf");
4778	eval("killall", "ctorrent");
4779	eval("killall", "rtorrent");
4780	eval("killall", "giftd");
4781	eval("killall", "dmathined");
4782	
4783	nvram_set("dms_running", "0");	// 2007.11 James.
4784	//nvram_set("apps_installed", "0");	// 2007.11 James. set at the end of this function
4785	nvram_set("apps_dl_x", "0");
4786
4787	strcpy(pool, nvram_safe_get("apps_pool"));
4788	strcpy(share, nvram_safe_get("apps_share"));
4789	strcpy(rundl, nvram_safe_get("apps_dlx"));
4790	strcpy(rundms, nvram_safe_get("apps_dmsx"));
4791	strcpy(name, nvram_safe_get("computer_name"));
4792	strcpy(mymac, nvram_safe_get("et0macaddr"));
4793	
4794	strcpy(share_port_from, nvram_get("apps_dl_share_port_from"));
4795	strcpy(share_port_to, nvram_get("apps_dl_share_port_to"));
4796	fp=fopen("/tmp/.prange", "w");
4797	if(fp)
4798	{
4799		fprintf(fp,"%s:%s", share_port_from, share_port_to);
4800		fclose(fp);
4801	}
4802
4803	if (nvram_match("apps_dmsx", "1"))
4804	{
4805//		sprintf(tmpstr2, "%s/dms /shares/DMSRoot %s %s &", EXBIN, name, mymac);
4806		sprintf(tmpstr2, "%s/dms /shares/DMSRoot \"%s\" %s &", "/apps/bin", name, mymac);
4807		ret=system(tmpstr2);
4808		if(!ret){
4809			nvram_set("dms_running", "1");	// 2007.11 James.
4810			logmessage("Media Server", "daemon is started");
4811		}
4812	}
4813	if (nvram_match("apps_dlx", "1") && nvram_match("swap_on", "1") && nvram_match("apps_comp", "1"))
4814	{
4815		sprintf(tmpstr2, "%s/dmex&", EXBIN);
4816		ret=system(tmpstr2);
4817		nvram_set("apps_running", "1");
4818		if(!ret)
4819		{
4820			//nvram_set("apps_dl_x", "1");	// 2008.11 James. set this nvram in dmex.
4821			logmessage("Download Master", "daemon is started");
4822		}
4823	}
4824	
4825	nvram_set("apps_installed", "1");
4826}
4827
4828void start_apps()			// added by Jiahao for WL500gP
4829{
4830	printf("\npreparing to start Download Machine\n");
4831	char pool[32];
4832	char share[32];
4833	char origver[32];
4834	char target_dir[32];
4835	char pool_dir[32];
4836	char EXLIB[32]="/.apps/lib";
4837	char EXBIN[32]="/.apps/bin";
4838	char EXUSR[32]="/.apps/usr";
4839	char EXETC[32];
4840	char NEWVER[8];
4841	char tmpstr[256];
4842	char tmpstr2[256];
4843	char tmpstr3[256];
4844	char tmpstr4[256];
4845
4846	char test_path[128];
4847	char *p;
4848
4849	if ( nvram_match("apps_dms_usb_port_x", nvram_safe_get("usb_disc0_port")) )
4850	{
4851		strcpy(test_path, nvram_safe_get("usb_disc0_path0"));
4852		p=strstr(test_path, "/tmp/harddisk");
4853		p+=5;
4854		nvram_set("apps_pool", p);
4855	}
4856	else if ( nvram_match("apps_dms_usb_port_x", nvram_safe_get("usb_disc1_port")) )
4857	{
4858		strcpy(test_path, nvram_safe_get("usb_disc1_path0"));
4859		p=strstr(test_path, "/tmp/harddisk");
4860		p+=5;
4861		nvram_set("apps_pool", p);
4862	}
4863	
4864	strcpy(tmpstr, EXLIB);
4865	sprintf(EXLIB, "%s%s", test_path, tmpstr);
4866	strcpy(tmpstr, EXBIN);
4867	sprintf(EXBIN, "%s%s", test_path, tmpstr);
4868	strcpy(tmpstr, EXUSR);
4869	sprintf(EXUSR, "%s%s", test_path, tmpstr);
4870
4871	//strcpy(pool, nvram_get("apps_pool"));
4872	strcpy(pool, p);	// 2008.05 James.
4873	strcpy(share, nvram_get("apps_share"));
4874	strcpy(origver, nvram_get("apps_ver"));
4875	sprintf(target_dir, "/shares/%s/%s", pool, share);
4876	sprintf(pool_dir, "/shares/%s", pool);
4877	sprintf(EXETC, "%s/.etc", pool_dir);
4878
4879	eval("rm", "-rf", "/shares/lib");
4880	eval("rm", "-rf", "/shares/bin");
4881	eval("rm", "-rf", "/shares/usr");
4882	eval("rm", "-rf", "/shares/etc");
4883	eval("rm", "-rf", EXETC);
4884
4885	mkdir_if_none(pool_dir);
4886	mkdir_if_none(target_dir);
4887
4888	eval("ln", "-s", EXLIB, "/shares/lib");
4889	eval("ln", "-s", EXBIN, "/shares/bin");
4890	eval("ln", "-s", EXUSR, "/shares/usr");
4891	
4892	set_apps_ver();
4893	sprintf(NEWVER, nvram_safe_get("apps_ver"));
4894
4895	sprintf(tmpstr, "%s/Music", target_dir);
4896	if (mkdir_if_none(tmpstr)==0)
4897		printf("Music DIR exist\n");
4898
4899	sprintf(tmpstr, "%s/Video", target_dir);
4900	if (mkdir_if_none(tmpstr)==0)
4901		printf("Video DIR exist\n");
4902
4903	sprintf(tmpstr, "%s/Photo", target_dir);
4904	if (mkdir_if_none(tmpstr)==0)
4905		printf("PHOTO DIR exist\n");
4906
4907	sprintf(tmpstr, "%s/Download", target_dir);
4908	if (mkdir_if_none(tmpstr)==0)
4909		printf("DOWNLOAD DIR exist\n");
4910
4911	sprintf(tmpstr, "%s/Download/config", target_dir);
4912	mkdir_if_none(tmpstr);
4913	sprintf(tmpstr, "%s/Download/Complete", target_dir);
4914	mkdir_if_none(tmpstr);
4915	sprintf(tmpstr, "%s/Download/InComplete", target_dir);
4916	mkdir_if_none(tmpstr);
4917	sprintf(tmpstr, "%s/Download/.logs", target_dir);
4918	mkdir_if_none(tmpstr);	
4919
4920	eval("rm", "-rf", EXETC);
4921	mkdir_if_none(EXETC);
4922	eval("ln", "-s", EXETC, "/shares/etc");
4923	
4924	if (nvram_match("apps_dlx", "1") && nvram_match("swap_on", "1") && nvram_match("apps_comp", "1"))
4925	{
4926		sprintf(tmpstr, "%s/asus_gift.conf", EXETC);
4927		if (check_if_file_exist(tmpstr)==1)
4928			printf("FILE asus_gift exist\n");
4929		else
4930		{
4931			sprintf(tmpstr, "%s/gift-nasoc/bin/asus_gift.conf", EXUSR);
4932			sprintf(tmpstr2, "cp %s %s/. -f", tmpstr, EXETC);
4933			system(tmpstr2);
4934		}
4935		
4936		sprintf(tmpstr, "%s/.giFT", EXETC);
4937		if (mkdir_if_none(tmpstr)==0)
4938			printf(".giFT DIR exist\n");
4939		else
4940		{
4941			sprintf(tmpstr2, "%s/.", tmpstr);
4942			sprintf(tmpstr4, "cp /shares/usr/.giFT/* %s -f", tmpstr2);
4943			system(tmpstr4);
4944			
4945			sprintf(tmpstr2, "%s/FastTrack", tmpstr);
4946			mkdir_if_none(tmpstr2);
4947			
4948			sprintf(tmpstr3, "%s/.", tmpstr2);
4949			sprintf(tmpstr4, "cp /shares/usr/.giFT/FastTrack/* %s -f", tmpstr3);
4950			system(tmpstr4);
4951			
4952			sprintf(tmpstr2, "%s/OpenFT", tmpstr);
4953			mkdir_if_none(tmpstr2);
4954			
4955			sprintf(tmpstr3, "%s/.", tmpstr2);
4956			sprintf(tmpstr4, "cp /shares/usr/.giFT/OpenFT/* %s -f", tmpstr3);
4957			system(tmpstr4);
4958			
4959			sprintf(tmpstr2, "%s/Gnutella", tmpstr);
4960			mkdir_if_none(tmpstr2);
4961			
4962			sprintf(tmpstr3, "%s/.", tmpstr2);
4963			sprintf(tmpstr4, "cp /shares/usr/.giFT/Gnutella/* %s -f", tmpstr3);
4964			system(tmpstr4);
4965			
4966			sprintf(tmpstr2, "%s/completed", tmpstr);
4967			mkdir_if_none(tmpstr2);
4968			sprintf(tmpstr2, "%s/completed/corrupted", tmpstr);
4969			mkdir_if_none(tmpstr2);
4970			sprintf(tmpstr2, "%s/ui", tmpstr);
4971			mkdir_if_none(tmpstr2);
4972			
4973			sprintf(tmpstr3, "%s/.", tmpstr2);
4974			sprintf(tmpstr4, "cp /shares/usr/.giFT/ui/* %s -f", tmpstr3);
4975			system(tmpstr4);
4976			
4977			sprintf(tmpstr, "%s/giFT", EXETC);
4978			mkdir_if_none(tmpstr);
4979			
4980			sprintf(tmpstr2, "%s/.", tmpstr);
4981			sprintf(tmpstr4, "cp /shares/usr/gift-nasoc/share/giFT/* %s -f", tmpstr2);
4982			system(tmpstr4);
4983			
4984			sprintf(tmpstr2, "%s/FastTrack", tmpstr);
4985			mkdir_if_none(tmpstr2);
4986			sprintf(tmpstr2, "%s/OpenFT", tmpstr);
4987			mkdir_if_none(tmpstr2);		
4988			sprintf(tmpstr2, "%s/Gnutella", tmpstr);
4989			mkdir_if_none(tmpstr2);
4990			sprintf(tmpstr2, "%s/completed", tmpstr);
4991			mkdir_if_none(tmpstr2);
4992			sprintf(tmpstr2, "%s/completed/corrupted", tmpstr);
4993			mkdir_if_none(tmpstr2);
4994			sprintf(tmpstr2, "%s/ui", tmpstr);
4995			mkdir_if_none(tmpstr2);
4996			
4997			sprintf(tmpstr3, "%s/.", tmpstr2);
4998			sprintf(tmpstr4, "cp /shares/usr/gift-nasoc/share/giFT/ui/* %s -f", tmpstr3);
4999			system(tmpstr4);
5000		}
5001		
5002		eval("rm" ,"-rf" ,"/shares/dmathined");
5003		mkdir_if_none("/shares/dmathined");
5004		mkdir_if_none("/shares/dmathined/Download");
5005		
5006		sprintf(tmpstr, "%s/Download/config", target_dir);
5007		eval("ln", "-s", tmpstr, "/shares/dmathined/Download/config");
5008		sprintf(tmpstr, "%s/Download/Complete", target_dir);
5009		eval("ln", "-s", tmpstr, "/shares/dmathined/Download/Complete");
5010		sprintf(tmpstr, "%s/Download/InComplete", target_dir);
5011		eval("ln", "-s", tmpstr, "/shares/dmathined/Download/InComplete");
5012		sprintf(tmpstr, "%s/Download/.logs", target_dir);
5013		eval("ln", "-s", tmpstr, "/shares/dmathined/Download/.logs");
5014	}
5015	
5016	eval("rm" ,"-rf" ,"/shares/DMSRoot");
5017	mkdir_if_none("/shares/DMSRoot");
5018	
5019	sprintf(tmpstr, "%s/Download/Complete", target_dir);
5020	eval("ln", "-s", tmpstr, "/shares/DMSRoot/Download");
5021	sprintf(tmpstr, "%s/Video", target_dir);
5022	eval("ln", "-s", tmpstr, "/shares/DMSRoot/Video");
5023	sprintf(tmpstr, "%s/Music", target_dir);
5024	eval("ln", "-s", tmpstr, "/shares/DMSRoot/Music");
5025	sprintf(tmpstr, "%s/Photo", target_dir);
5026	eval("ln", "-s", tmpstr, "/shares/DMSRoot/Photo");
5027	
5028	eval("/sbin/test_of_var_files_in_mount_path", pool_dir);	// 2008.05 James.
5029	
5030	exec_apps();
5031}
5032
5033void get_first_partition(char *part_path)		// added by Jiahao for WL500gP
5034{
5035	strcpy(part_path, "");
5036	if (nvram_match("usb_disc0_dev", ""))
5037	{
5038		if (nvram_invmatch("usb_disc1_dev", ""))
5039		{
5040			if (nvram_invmatch("usb_disc1_index", "0"))
5041			{
5042				strcpy(part_path, nvram_safe_get("usb_disc1_path0"));
5043			}
5044		}
5045	}
5046	else
5047	{
5048		if (nvram_invmatch("usb_disc0_index", "0"))
5049		{
5050			strcpy(part_path, nvram_safe_get("usb_disc0_path0"));
5051		}
5052	}
5053}
5054
5055// 2007.10 James {
5056void start_usb_apps(){
5057printf("*** start_usb_apps() ***\n");
5058	run_ftpsamba();
5059	start_apps();
5060}
5061
5062void stop_usb_apps(){
5063printf("*** stop_usb_apps() ***\n");
5064	stop_apps();
5065	stop_ftpsamba();
5066	sleep(1);
5067}
5068
5069void stop_apps(){
5070	eval("killall", "snarf");
5071	eval("killall", "ctorrent");
5072	eval("killall", "rtorrent");
5073	eval("killall", "giftd");
5074	eval("killall", "dmathined");
5075	
5076	stop_dms();
5077	
5078	nvram_set("apps_running", "0");
5079	nvram_set("apps_dl_x", "0");
5080	sleep(1);
5081}
5082
5083void stop_ftpsamba(){
5084	stop_ftp();
5085	stop_samba();
5086}
5087
5088void stop_ftp(){
5089	if(nvram_match("ftp_running", "0"))
5090		return ;
5091	
5092	fprintf(stderr, "Stoping vsftpd\n");
5093	
5094	eval("killall", "-SIGKILL", "vsftpd");
5095	//eval("rm", "-f", "/tmp/vsftpd.conf");
5096	unlink("/tmp/vsftpd.conf");
5097	
5098	logmessage("FTP Server", "daemon is stoped");
5099	
5100	nvram_set("ftp_running", "0");
5101}
5102
5103void stop_samba(){
5104	if(nvram_match("samba_running", "0"))
5105		return ;
5106	
5107	fprintf(stderr, "Stoping samba\n");
5108	
5109	eval("killall", "-SIGKILL", "smbd");
5110	eval("killall", "-SIGKILL", "nmbd");
5111	//eval("rm", "-f", "/tmp/samba/lib/smb.conf");
5112	unlink("/tmp/samba/lib/smb.conf");
5113	
5114	logmessage("Samba Server", "daemon is stoped");
5115	
5116	nvram_set("samba_running", "0");
5117	nvram_set("st_samba_mode_x", "0");	// 2007.11 James.
5118}
5119
5120void stop_dms(){
5121	if(nvram_invmatch("dms_running", "1"))
5122		return;
5123	
5124	fprintf(stderr, "Stoping dms\n");
5125	
5126	eval("killall", "dms");
5127	
5128	logmessage("Media Server", "daemon is stoped");
5129	
5130	nvram_set("dms_running", "0");
5131}
5132
5133int run_dms(){
5134	if(nvram_match("dms_running", "0")){
5135		if(start_dms() == 0){
5136			nvram_set("dms_running", "1");
5137		}
5138		
5139		return -1;
5140	}
5141	
5142	return 0;
5143}
5144
5145int start_dms(){
5146	char *DMS_ROOT = "/shares/DMSRoot";
5147	char name[32];
5148	char mymac[32];
5149	char path[256];
5150	char tmpstr2[256];
5151	int ret = 0;
5152	pid_t pid;
5153	char *argvs[5];
5154	
5155	if(nvram_invmatch("apps_dmsx", "1"))
5156		return 0;
5157	
5158	mkdir_if_none(DMS_ROOT);
5159	
5160	strcpy(name, nvram_safe_get("computer_name"));
5161	strcpy(mymac, nvram_safe_get("et0macaddr"));
5162	sprintf(tmpstr2, "/apps/bin/dms %s \"%s\" %s &", DMS_ROOT, name, mymac);
5163	
5164	ret = system(tmpstr2);
5165	if(!ret){
5166		nvram_set("dms_running", "1");	// 2007.11 James.
5167		logmessage("Media Server", "daemon is started");
5168		
5169		return 0;
5170	}
5171	
5172	return 1;
5173}
5174// 2007.10 James }
5175
5176void
5177run_samba()
5178{
5179	if(nvram_match("samba_running", "0"))
5180	{
5181		//if (nvram_invmatch("st_samba_modex", "0"))
5182		if(nvram_invmatch("st_samba_mode", "0"))	// 2007.11 James.
5183		{
5184			fprintf(stderr, "starting samba\n");
5185			if (start_samba()==0)
5186			{
5187				nvram_set("samba_running", "1");
5188			}
5189		}
5190	}
5191	else
5192	{
5193		//if (nvram_invmatch("st_samba_modex", "0"))
5194		if(nvram_invmatch("st_samba_mode", "0"))	// 2007.11 James.
5195		{
5196// 2007.11 James. For new /tmp/passwd and new account. {
5197			//fprintf(stderr, "rewrite conf of samba\n");
5198			//write_smb_conf();
5199			fprintf(stderr, "restarting samba\n");
5200			if(!start_samba())
5201				nvram_set("samba_running", "1");
5202// 2007.11 James. For new /tmp/passwd and new account. }
5203		}
5204	}
5205}
5206
5207void
5208run_ftp()
5209{
5210	if(nvram_match("ftp_running", "0"))
5211	{
5212		//if (nvram_invmatch("st_ftp_modex", "0"))
5213		if (nvram_invmatch("st_ftp_mode", "0"))	// 2007.10 James.
5214		{
5215			fprintf(stderr, "starting vsftpd\n");
5216			if (start_ftpd()==0)
5217			{
5218				nvram_set("ftp_running", "1");
5219			}
5220		}
5221	}
5222	else
5223	{
5224		//if (nvram_invmatch("st_ftp_modex", "0"))
5225		if (nvram_invmatch("st_ftp_mode", "0"))	// 2007.10 James.
5226		{
5227			//fprintf(stderr, "rewrite conf of vsftpd\n");
5228			//write_ftpd_conf();
5229			fprintf(stderr, "restarting ftp\n");
5230			if(!start_ftpd())
5231				nvram_set("ftp_running", "1");
5232		}
5233	}
5234}
5235
5236void
5237run_ftpsamba()
5238{
5239	run_ftp();
5240	run_samba();
5241}
5242
5243int
5244run_apps()
5245{
5246	int apps_comp=0;
5247	int apps_comp_pre=0;
5248	int apps_status=0;
5249	int apps_disk_free=0;
5250	int ret=0, i;
5251	char tmp[32];
5252	char tmpstr[64];
5253	char tmpstr2[64];
5254	FILE *fp;
5255	char *buf=NULL;
5256	int buflen=0;
5257	struct sysinfo info;
5258
5259	nvram_set("usb_storage_busy", "1");
5260	nvram_set("apps_status_checked", "0");
5261
5262	strcpy(tmp, "");
5263	if ( nvram_invmatch("usb_disc0_dev", "") && (nvram_match("apps_dlx", "0")||check_disk_free_GE_1G(nvram_safe_get("usb_disc0_path0"))==2))
5264	{
5265		strcpy(tmp, nvram_safe_get("usb_disc0_path0"));
5266	}
5267	else if ( nvram_invmatch("usb_disc1_dev", "") && (nvram_match("apps_dlx", "0")||check_disk_free_GE_1G(nvram_safe_get("usb_disc1_path0"))==2))
5268	{
5269		strcpy(tmp, nvram_safe_get("usb_disc1_path0"));
5270	}
5271	else if ( nvram_invmatch("usb_disc0_dev", "") )
5272	{
5273		strcpy(tmp, nvram_safe_get("usb_disc0_path0"));
5274	}
5275	else if ( nvram_invmatch("usb_disc1_dev", "") )
5276	{
5277		strcpy(tmp, nvram_safe_get("usb_disc1_path0"));
5278	}
5279	
5280	if (	nvram_match("swap_on", "0") &&
5281		nvram_match("apps_dlx", "1") &&
5282		((apps_comp_pre=ckeck_apps_completeness_pre(tmp))==1)
5283	   )
5284	{
5285		if (strcmp(tmp, "")!=0)
5286		{
5287			memset(tmpstr, 0, sizeof(tmpstr));
5288			sprintf(tmpstr, "%s/swap", tmp);
5289			unlink(tmpstr);
5290			memset(tmpstr, 0, sizeof(tmpstr));
5291			sprintf(tmpstr, "%s/.swap", tmp);
5292			unlink(tmpstr);
5293
5294			ret = check_disk_free_GE_1G(tmp);
5295				
5296			if (ret==2)
5297			{
5298				if(!strcmp(tmp, nvram_safe_get("usb_disc0_path0")))
5299					nvram_set("apps_dms_usb_port_x2", nvram_safe_get("usb_disc0_port"));
5300				else if (!strcmp(tmp, nvram_safe_get("usb_disc1_path0")))
5301					nvram_set("apps_dms_usb_port_x2", nvram_safe_get("usb_disc1_port"));
5302					
5303				sysinfo(&info);
5304				if ((info.freeram + info.bufferram) >= 1024*1024*2)
5305					buflen = 1024*1024*2;
5306				else if ((info.freeram + info.bufferram) >= 1024*1024*1.6)
5307					buflen = 1024*1024*1.6;
5308				else if ((info.freeram + info.bufferram) >= 1024*1024*1)
5309					buflen = 1024*1024*1;
5310				else if ((info.freeram + info.bufferram) >= 1024*1024*0.8)
5311					buflen = 1024*1024*0.8;
5312				else
5313					buflen = 1024*1024*0.5;
5314				buf = malloc(buflen);
5315				for(i=0;i<buflen;i++)
5316					buf[i]='\n';
5317
5318				fp=fopen(tmpstr, "a");
5319				if(fp!=NULL)
5320				{
5321					for(i=0;i<1024*1024*32/buflen;i++)
5322						fprintf(fp, "%s", buf);
5323					free(buf);
5324					fclose(fp);
5325
5326					/*memset(tmpstr2, 0, sizeof(tmpstr2));
5327					sprintf(tmpstr2, "mkswap %s", tmpstr);
5328					system(tmpstr2);
5329
5330					memset(tmpstr2, 0, sizeof(tmpstr2));
5331					sprintf(tmpstr2, "swapon %s", tmpstr);
5332					system(tmpstr2);//*/
5333					eval("/sbin/mkswap", tmpstr);
5334					
5335					swapon(tmpstr, 0);	// 2008.04 James.
5336
5337					logmessage("USB storage", "32MB swap file is added");
5338					nvram_set("swap_on", "1");
5339					nvram_set("swap_file", tmpstr);	// 2008.06 James.
5340				}
5341			}
5342			else if (ret==1)
5343				logmessage("USB storage", "The swap file is not added for free space is less than 33MB");
5344			else if (ret==3)
5345				logmessage("USB storage", "The swap file is not added for partition size is less than 1024MB");
5346			else if (ret==0)
5347				logmessage("USB storage", "The swap file is not added for unknown reasons");
5348		}
5349	}
5350	
5351	apps_disk_free=check_disk_free_apps(tmp, apps_comp);
5352	if (apps_disk_free==1)
5353		nvram_set("apps_disk_free", "1");
5354	else
5355		nvram_set("apps_disk_free", "0");
5356
5357	//if(	nvram_match("apps_running", "0") &&
5358	if(strcmp(nvram_safe_get("apps_running"), "1") != 0 &&	// 2007.11 James.
5359			((apps_comp_pre==1 && nvram_match("apps_dlx", "1")) || nvram_match("apps_dmsx", "1"))
5360			){
5361		if(strcmp(tmp, "") != 0){
5362			apps_comp = ckeck_apps_completeness(tmp);
5363			if(apps_comp == 1)
5364				nvram_set("apps_comp", "1");
5365			else{
5366				nvram_set("apps_comp", "0");
5367				
5368				if(!strcmp(nvram_safe_get("swap_on"), "1")){
5369					printf("try to swapoff swap file.\n");
5370					if(strcmp(tmp, "")){
5371						memset(tmpstr, 0, sizeof(tmpstr));
5372						sprintf(tmpstr, "%s/.swap", tmp);
5373						swapoff(tmpstr);
5374						sleep(1);
5375						if(swap_check() == 1){
5376							logmessage("USB storage", "swapoff unsuccessfully");
5377							nvram_set("swapoff_failed", "1");
5378							unlink(tmpstr);
5379							nvram_set("reboot", "1");
5380						}
5381						else{
5382							logmessage("USB storage", "swapoff successfully");
5383							nvram_set("swap_on", "0");
5384							nvram_set("swap_file", "");	// 2008.06 James.
5385							nvram_set("swapoff_failed", "0");
5386							nvram_set("apps_dms_usb_port_x2", "-1");
5387							unlink(tmpstr);
5388						}
5389					}
5390				}
5391			}
5392			if (nvram_match("apps_dlx", "0") ||
5393			    (nvram_match("apps_dlx", "1") && nvram_match("swap_on", "1") && check_disk_free_GE_1G(tmp)==2) ||
5394			    (nvram_match("apps_dmsx", "1") && !(nvram_match("apps_dlx", "1") && nvram_match("swap_on", "1") && check_disk_free_GE_1G(tmp)==2))
5395			   )
5396			{
5397//				if (apps_comp==1 && apps_disk_free==1)
5398				if ( (apps_comp==1 && apps_disk_free==1) || nvram_match("apps_dmsx", "1"))
5399				{
5400					if (strcmp(tmp, nvram_safe_get("usb_disc0_path0"))==0)
5401						nvram_set("apps_dms_usb_port_x", nvram_safe_get("usb_disc0_port"));
5402					else if (strcmp(tmp, nvram_safe_get("usb_disc1_path0"))==0)
5403						nvram_set("apps_dms_usb_port_x", nvram_safe_get("usb_disc1_port"));
5404
5405					start_apps();
5406					nvram_set("apps_running", "1");
5407				}
5408			}
5409			else
5410			{
5411				fprintf(stderr, "skip running DMS & DM for no swap file or binary completeness issues\n");
5412				logmessage("Media Server", "daemon is not started for no swap file or binary completeness issues");
5413				logmessage("Download Master", "daemon is not started for no swap file or binary completeness issues");
5414			}
5415		}
5416	}	
5417	else
5418		fprintf(stderr, "skip running DMS & DM\n");
5419
5420	nvram_set("usb_storage_busy", "0");
5421	nvram_set("apps_status_checked", "1");
5422	return 0;
5423}
5424
5425int
5426swap_check()
5427{
5428	struct sysinfo info;
5429	
5430	sysinfo(&info);
5431	if(info.totalswap > 0)
5432		return 1;
5433	else
5434		return 0;
5435}
5436#endif // DLM
5437
5438int
5439umount_disc_parts_rc(int usb_port)
5440{	
5441	char nvramstr[32];
5442	char nvramstr2[32];
5443	char nvramstr3[32];
5444	char umount_dir[32];
5445	int disc_index, i;
5446	char tmp[2];
5447	int dev_index=-1;
5448	int count=0;
5449	char test_path[128], tmpstr[128];
5450	int ret=0;
5451#ifdef DLM
5452	int sleep_flag=0;
5453
5454	//if ( strcmp(nvram_safe_get("usb_storage_busy"), "1" )==0 )	// 2007.12 James
5455	//	return;
5456#endif // DLM
5457	
5458	sprintf(tmp, "%d", usb_port);
5459	if(!strcmp(nvram_safe_get("usb_disc0_port"), tmp))
5460		dev_index = 0;
5461	else if(!strcmp(nvram_safe_get("usb_disc1_port"), tmp))
5462		dev_index = 1;
5463	else
5464		return -1;
5465	
5466#ifdef DLM
5467#if 1
5468	if ( (strcmp(nvram_safe_get("apps_running"), "1")==0) && (atoi(nvram_safe_get("apps_dms_usb_port_x"))==usb_port) )
5469	{
5470		sleep_flag=1;
5471
5472		eval("killall", "snarf");
5473		eval("killall", "ctorrent");
5474		eval("killall", "rtorrent");
5475		eval("killall", "giftd");
5476		eval("killall", "dmathined");
5477		//eval("killall", "dms");
5478
5479		//nvram_set("dms_running", "0");	// 2007.11 James.
5480		nvram_set("apps_running", "0");
5481		nvram_set("apps_installed", "0");
5482		nvram_set("apps_dl_x", "0");
5483		nvram_set("apps_status_checked", "0");
5484		nvram_set("apps_disk_free", "0");
5485
5486		/*nvram_set("usb_storage_busy2", "1");
5487		sleep(5);
5488		nvram_set("usb_storage_busy2", "0");*/
5489	}
5490#endif // 1
5491	if(!strcmp(nvram_safe_get("samba_running"), "1")){
5492		eval("killall", "nmbd");
5493		eval("killall", "smbd");
5494		nvram_set("samba_running", "0");
5495		nvram_set("st_samba_mode_x", "0");
5496	}
5497	
5498	if(!strcmp(nvram_safe_get("ftp_running"), "1")){
5499		eval("killall", "vsftpd");
5500		nvram_set("ftp_running", "0");
5501	}
5502	
5503// 2007.11 James. {
5504	if(!strcmp(nvram_safe_get("dms_running"), "1")){
5505		eval("killall", "dms");
5506		nvram_set("dms_running", "0");
5507	}
5508// 2007.11 James. }
5509	
5510	if(sleep_flag == 1)
5511	{
5512		nvram_set("usb_storage_busy2", "1");
5513		for(i = 1; i <= 2; ++i){
5514			printf("Sleep %d second%s...\n", i, ((i == 1)?"":"s"));
5515			sleep(1);
5516		}
5517		nvram_set("usb_storage_busy2", "0");
5518	}
5519	
5520	sync();	// 2008.06 James.
5521	
5522	if(!strcmp(nvram_safe_get("swap_on"), "1") && atoi(nvram_safe_get("apps_dms_usb_port_x2")) == usb_port)
5523	{
5524		strcpy(test_path, "");
5525		if ( strcmp(nvram_safe_get("usb_disc0_port"), nvram_safe_get("apps_dms_usb_port_x2"))==0 )
5526		{
5527			strcpy(test_path, nvram_safe_get("usb_disc0_path0"));
5528		}
5529		else if ( strcmp(nvram_safe_get("usb_disc1_port"), nvram_safe_get("apps_dms_usb_port_x2"))==0 )
5530		{
5531			strcpy(test_path, nvram_safe_get("usb_disc1_path0"));
5532		}
5533		
5534		if(strcmp(test_path, "") != 0)
5535		{
5536			sprintf(tmpstr, "%s/.swap", test_path);
5537			printf("try to swapoff %s.\n", tmpstr);
5538			swapoff(tmpstr);
5539			
5540			//nvram_set("usb_storage_busy2", "1");
5541			sleep(1);
5542			//nvram_set("usb_storage_busy2", "0");
5543			
5544			if (swap_check()==1)
5545			{
5546				logmessage("USB storage", "swapoff unsuccessfully");
5547				nvram_set("swapoff_failed", "1");
5548				//unlink(tmpstr);
5549				return -1;
5550			}
5551			else
5552			{
5553				logmessage("USB storage", "swapoff successfully");
5554				nvram_set("swap_on", "0");
5555				nvram_set("swap_file", "");	// 2008.06 James.
5556				nvram_set("swapoff_failed", "0");
5557				nvram_set("apps_dms_usb_port_x2", "-1");
5558				unlink(tmpstr);
5559			}
5560		}
5561	}
5562#endif // DLM
5563
5564	sprintf(nvramstr, "usb_disc%d_index", dev_index);
5565	disc_index=atoi(nvram_safe_get(nvramstr));
5566	
5567	for (i=disc_index; i>0; i--)
5568	{
5569		sprintf(nvramstr2, "usb_disc%d_path%d", dev_index, i-1);
5570		sprintf(umount_dir, nvram_safe_get(nvramstr2));
5571		sprintf(nvramstr3, "usb_disc%d_fs_path%d", dev_index, i-1);
5572		count=0;
5573		//while((ret=umount(umount_dir)) && (count<2))
5574		while((ret=umount2(umount_dir, MS_NOEXEC | MS_NOSUID | 0x00000002)) && (count<2))	// 0x00000002: MNT_DETACH
5575		{
5576			//sync();	// 2008.04 James.
5577			count++;
5578#ifdef DLM
5579			nvram_set("usb_storage_busy2", "1");
5580#endif // DLM
5581			sleep(1);
5582#ifdef DLM
5583			nvram_set("usb_storage_busy2", "0");
5584#endif // DLM
5585		}
5586		if(!ret)
5587		{
5588			rmdir(umount_dir);
5589			nvram_set(nvramstr3, "");
5590			nvram_set(nvramstr2, "");
5591			sprintf(tmp, "%d", i-1);
5592			nvram_set(nvramstr, tmp);
5593			sprintf(tmpstr, "unmounted %s", umount_dir);
5594			logmessage("USB storage", tmpstr);
5595		}
5596		else
5597			return ret;
5598	}
5599	sprintf(nvramstr, "usb_disc%d_dev", dev_index);
5600	nvram_set(nvramstr, "");
5601	sprintf(nvramstr, "usb_disc%d_port", dev_index);
5602	nvram_set(nvramstr, "0");
5603#ifdef DLM
5604	nvram_set("eject_from_web", "1");
5605#endif // DLM
5606	write_disc_status();
5607	
5608	return 0;
5609}
5610
5611//2008.07.17 Yau add
5612int start_networkmap(void)
5613{
5614	char *networkmap_argv[] = {"networkmap", NULL};
5615	pid_t pid;
5616	
5617	_eval(networkmap_argv, NULL, 0, &pid);
5618	
5619	return 0;
5620}
5621
5622/*int stop_cdrom(const char *dev_name){
5623	int stopfd;
5624	
5625	fprintf(stderr, "Stopping %s ...", dev_name);
5626	if((stopfd = open(dev_name, O_RDONLY | O_NONBLOCK, 0)) >= 0){
5627		fprintf(stderr, "there was a CD-ROM device!\n");
5628#if 1
5629		if(ioctl(stopfd, CDROMSTOP, 0))
5630			fprintf(stderr, "Stopping CD-ROM failed %d\n", errno);
5631		else
5632			fprintf(stderr, "Stopping CD-ROM succeeded\n");
5633#else
5634		if(ioctl(ejectfd, CDROMEJECT, 0))
5635			fprintf(stderr, "Ejecting CD-ROM failed %d\n", errno);
5636		else
5637			fprintf(stderr, "Ejecting CD-ROM succeeded\n");
5638#endif
5639		
5640		close(stopfd);
5641		
5642		return 1;
5643	}
5644	else{
5645		fprintf(stderr, "there wasn't any CD-ROM device!\n");
5646		return 0;
5647	}
5648}//*/
5649
5650int eject_scsi(const char *dev_name){
5651	int ejectfd;
5652	int status;
5653	struct sdata {
5654		int  inlen;
5655		int  outlen;
5656		char cmd[256];
5657	} scsi_cmd;
5658	
5659	csprintf("Ejecting SCSI(%s) of CDROM ...", dev_name);
5660	if((ejectfd = open(dev_name, O_RDONLY|O_NONBLOCK)) == -1){
5661logmessage("USB Storage", "this was not a CD-ROM device.");
5662		csprintf("there wasn't any CD-ROM device!\n");
5663		return 0;
5664	}
5665logmessage("USB Storage", "this was a CD-ROM device.");
5666	csprintf("there was a CD-ROM device!\n");
5667	
5668	/*scsi_cmd.inlen	= 0;
5669	scsi_cmd.outlen = 0;
5670	scsi_cmd.cmd[0] = ALLOW_MEDIUM_REMOVAL;
5671	scsi_cmd.cmd[1] = 0;
5672	scsi_cmd.cmd[2] = 0;
5673	scsi_cmd.cmd[3] = 0;
5674	scsi_cmd.cmd[4] = 0;
5675	scsi_cmd.cmd[5] = 0;
5676	status = ioctl(ejectfd, SCSI_IOCTL_SEND_COMMAND, (void *)&scsi_cmd);
5677	if (status != 0){
5678csprintf("Failed to send ALLOW_MEDIUM_REMOVAL!\n");
5679		close(ejectfd);
5680		return 0;
5681	}//*/
5682
5683	scsi_cmd.inlen	= 0;
5684	scsi_cmd.outlen = 0;
5685	scsi_cmd.cmd[0] = START_STOP;
5686	scsi_cmd.cmd[1] = 0;
5687	scsi_cmd.cmd[2] = 0;
5688	scsi_cmd.cmd[3] = 0;
5689	scsi_cmd.cmd[4] = 1;
5690	scsi_cmd.cmd[5] = 0;
5691	status = ioctl(ejectfd, SCSI_IOCTL_SEND_COMMAND, (void *)&scsi_cmd);
5692	if (status != 0){
5693csprintf("Failed to send first START_STOP!\n");
5694		close(ejectfd);
5695		return 0;
5696	}
5697
5698	scsi_cmd.inlen	= 0;
5699	scsi_cmd.outlen = 0;
5700	scsi_cmd.cmd[0] = START_STOP;
5701	scsi_cmd.cmd[1] = 0;
5702	scsi_cmd.cmd[2] = 0;
5703	scsi_cmd.cmd[3] = 0;
5704	scsi_cmd.cmd[4] = 2;
5705	scsi_cmd.cmd[5] = 0;
5706	status = ioctl(ejectfd, SCSI_IOCTL_SEND_COMMAND, (void *)&scsi_cmd);
5707	if (status != 0){
5708csprintf("Failed to send second START_STOP!\n");
5709		close(ejectfd);
5710		return 0;
5711	}
5712
5713	/* force kernel to reread partition table when new disc inserted */
5714	/*status = ioctl(ejectfd, BLKRRPART);
5715	if (status != 0){
5716csprintf("Failed to send BLKRRPART!\n");
5717	}//*/
5718	
5719	close(ejectfd);
5720	return 1;
5721}
5722#endif // ASUS_EXT
5723