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	if(nvram_match("ftp_lang", "EN"))
1059		fprintf(fp, "enable_iconv=NO\n");
1060	else
1061//#ifdef LANGUAGE_TW
1062	fprintf(fp, "enable_iconv=YES\n");
1063	if(nvram_match("ftp_lang", "TW")){
1064		fprintf(fp, "remote_charset=cp950\n");
1065	}
1066	else if(nvram_match("ftp_lang", "CN")){
1067		fprintf(fp, "remote_charset=cp936\n");
1068	}
1069	/*else if(nvram_match("ftp_lang", "KR")){
1070		fprintf(fp, "remote_charset=cp949\n");
1071	}//*/
1072//#endif
1073// 2008.04 James. {
1074/*#ifdef LANGUAGE_KR
1075	fprintf(fp, "enable_iconv=YES\n");
1076	fprintf(fp, "remote_charset=cp949\n");
1077#endif
1078#ifdef LANGUAGE_JP
1079	fprintf(fp, "enable_iconv=YES\n");
1080	fprintf(fp, "remote_charset=cp932\n");
1081#endif//*/
1082	/*else if(nvram_match("ftp_lang", "JP")){
1083		fprintf(fp, "remote_charset=cp932\n");
1084	}//*/
1085// 2008.04 James. }
1086	fclose(fp);
1087
1088	get_first_partition(test_path);
1089	nvram_set("first_partition", test_path);
1090	free(test_path);
1091}
1092
1093int
1094start_ftpd()	// added by Jiahao for WL500gP
1095{
1096	int ret=0;
1097
1098	//if (nvram_match("st_ftp_modex", "0")) return 0;
1099
1100	//eval("killall", "-SIGKILL", "vsftpd");
1101	stop_ftp();	// 2007.10 James.
1102	write_ftpd_conf();
1103
1104	//if (nvram_match("st_ftp_modex", "1"))
1105	if(nvram_match("st_ftp_mode", "1"))	// 2007.10 James
1106		//printf("ftp mode: login to first partition\n");
1107		printf("ftp mode: anonymous login...\n");	// 2007.11 James.
1108	//else if (nvram_match("st_ftp_modex", "2"))
1109	else if(nvram_match("st_ftp_mode", "2"))	// 2007.10 James
1110		//printf("ftp mode: login to first matched shared node\n");
1111		printf("ftp mode: account login...\n");	// 2007.11 James.
1112
1113	// Can't use eval() here
1114	ret=system("/sbin/vsftpd&");	// 2007.10 James. chang the absolute path.
1115	if(!ret)
1116	{
1117		logmessage("FTP Server", "daemon is started");
1118		return 0;
1119	}
1120	else
1121		return 1;
1122}
1123
1124int
1125test_user(char *target, char *pattern)	// added by Jiahao for WL500gP
1126{
1127	char s[384];
1128	char p[32];
1129	char *start;
1130	char *pp;
1131	strcpy(s, target);
1132	strcpy(p, pattern);
1133	start = s;
1134	while (pp=strchr(start, ';'))
1135	{
1136		*pp='\0';
1137		if(! strcmp(start, p))
1138			return 1;
1139		start=pp+1;
1140	}
1141	return 0;
1142}
1143#endif // DLM
1144
1145#ifdef WEBCAM_SUPPORT
1146int
1147hotplug_usb_webcam(char *product, int webflag)
1148{
1149	char *rcamd_argv[]={"rcamd",
1150				"-p", nvram_safe_get("usb_webactivex_x"),
1151				"-s", "0",
1152				"-z", nvram_safe_get("time_zone_x"),
1153				"-a", nvram_safe_get("usb_websecurity_x"),
1154				NULL, NULL,	// Model -t
1155				NULL, NULL,	// Record Time -r
1156				NULL, NULL, 	// Image Size -f
1157				NULL, NULL, 	// Sense Vlaue -m
1158				NULL, NULL, 	// Sense Limit -c
1159				NULL, NULL,
1160				NULL};
1161	char **arg;
1162	pid_t pid;
1163
1164	if (nvram_match("usb_webenable_x", "0") || strlen(product)==0 || webflag==0) return;
1165	for (arg = rcamd_argv; *arg; arg++);
1166
1167	if (webflag == WEB_PWCWEB)
1168	{
1169		eval("insmod", "pwc.o", "power_save=0");
1170		nvram_set("usb_webdriver_x", "0");
1171
1172		*arg++ = "-t";
1173		*arg++ = "0";
1174	}
1175	else
1176	{
1177		eval("insmod", "i2c-core.o");
1178		eval("insmod", "ov51x.o");
1179		eval("insmod", "ov511_decomp.o");
1180		eval("insmod", "ov518_decomp.o");
1181		nvram_set("usb_webdriver_x", "1");
1182
1183		if (strstr(product, "8519"))
1184		{
1185			*arg++ = "-t";
1186			*arg++ = "2";
1187		}
1188		else
1189		{
1190			*arg++ = "-t";
1191			*arg++ = "1";
1192		}
1193	}
1194
1195	// start web cam
1196	if (nvram_match("usb_webmode_x", "0")) // ActiveX only
1197	{
1198		*arg++ = "-r";
1199		*arg++ = "60";
1200	}
1201	else
1202	{
1203		*arg++ = "-r";
1204		*arg++ = "0";
1205	}
1206
1207	// image size
1208	if (nvram_match("usb_webimage_x", "0"))
1209	{
1210		*arg++ = "-f";
1211		if (webflag==WEB_PWCWEB) *arg++="320x240";
1212		else *arg++="640x480";
1213	}
1214	else if (nvram_match("usb_webimage_x", "1"))
1215	{
1216		*arg++ = "-f";
1217		*arg++="320x240";
1218	}
1219	else if (nvram_match("usb_webimage_x", "2"))
1220	{
1221		*arg++ = "-f";
1222		if (webflag==WEB_PWCWEB) *arg++="160x120";
1223		else *arg++="176x144";
1224	}
1225	else
1226	{
1227		*arg++ = "-f";
1228		*arg++ = "80x60";
1229	}
1230
1231
1232	if (nvram_match("usb_websense_x", "0"))
1233	{
1234		*arg++ = "-m";
1235		*arg++ = "150";
1236		*arg++ = "-c";
1237		*arg++ = "100";
1238	}
1239	else if (nvram_match("usb_websense_x", "1"))
1240	{
1241		*arg++ = "-m";
1242		*arg++ = "100";
1243		*arg++ = "-c";
1244		*arg++ = "100";
1245	}
1246	else
1247	{
1248		*arg++ = "-m";
1249		*arg++ = "50";
1250		*arg++ = "-c";
1251		*arg++ = "100";
1252	}
1253
1254
1255	//*arg++="-d";
1256	//*arg++="7";
1257	mkdir("/tmp/webcam", 0777);
1258	chdir("/tmp/webcam");
1259
1260	symlink("/www/Advanced_ShowTime_Widzard.asp", "/tmp/webcam/index.asp");
1261	symlink("/www/Advanced_ShowTime_Widzard.asp", "/tmp/webcam/ShowWebCam.asp");
1262	symlink("/www/ShowWebCamPic.asp", "/tmp/webcam/ShowWebCamPic.asp");
1263	symlink("/www/graph", "/tmp/webcam/graph");
1264	symlink("/www/general.js", "/tmp/webcam/general.js");
1265	symlink("/www/overlib.js", "/tmp/webcam/overlib.js");
1266	symlink("/www/style.css", "/tmp/webcam/style.css");
1267	symlink("/www/netcam_mfc_activeX.cab", "/tmp/webcam/netcam_mfc_activeX.cab");
1268	symlink("/var/tmp/display.jpg", "/tmp/webcam/display.jpg");
1269
1270	//char *httpd_argv[]={"httpd",
1271	//			nvram_safe_get("wan0_ifname"),
1272	//			nvram_safe_get("usb_webhttpport_x"),
1273	//			NULL};
1274	//_eval(httpd_argv, NULL, 0, &pid);
1275	eval("httpd", nvram_safe_get("wan0_ifname"), nvram_safe_get("usb_webhttpport_x"));
1276	chdir("/");
1277	_eval(rcamd_argv, ">/dev/null", 0, NULL);
1278
1279	return 0;
1280}
1281
1282int
1283remove_webcam_main(int webflag)
1284{
1285	if (webflag == WEB_PWCWEB)
1286	{
1287		eval("rmmod", "pwc");
1288	}
1289	else
1290	{
1291		eval("rmmod", "i2c-core");
1292		eval("rmmod", "ov511_decomp");
1293		eval("rmmod", "ov518_decomp");
1294		eval("rmmod", "ov51x");
1295	}
1296	nvram_set("usb_webdriver_x", "");
1297	return 0;
1298}
1299
1300
1301int
1302remove_usb_webcam(char *product, int webflag)
1303{
1304	char pidfile[32];
1305	sprintf(pidfile, "/var/run/httpd-%s.pid", nvram_safe_get("usb_webhttpport_x"));
1306
1307	kill_pidfile(pidfile);
1308	kill_pidfile("/var/run/rcamd.pid");
1309
1310	if (webflag == WEB_PWCWEB)
1311	{
1312		eval("rmmod", "pwc");
1313	}
1314	else
1315	{
1316		eval("rmmod", "i2c-core");
1317		eval("rmmod", "ov511_decomp");
1318		eval("rmmod", "ov518_decomp");
1319		eval("rmmod", "ov51x");
1320	}
1321	nvram_set("usb_webdriver_x", "");
1322
1323	return 0;
1324}
1325
1326
1327int
1328start_rcamd(void)
1329{
1330	char *rcamd_argv[] = {"rcamdmain", NULL};
1331	pid_t pid;
1332
1333	_eval(rcamd_argv, NULL, 0, &pid);
1334	return 0;
1335}
1336
1337int
1338stop_rcamd(void)
1339{
1340	int ret = eval("killall", "rcamdmain");
1341	return ret;	// 2007.11 James.
1342}
1343#endif // WEBCAM_SUPPORT
1344
1345/* remove usb mass storage */
1346int
1347remove_usb_mass(char *product)
1348{
1349	nvram_set("usb_storage_device_remove", "");	// 2007.12 James.
1350
1351// 2007.12 James {
1352#ifdef DLM
1353	char *message;
1354	unsigned int len = 0;
1355	int result = 0;
1356
1357printf("\n*** start to umount disk! ***\n");
1358// 2008.06 James. {
1359	umount_disc_parts_rc(1);
1360	umount_disc_parts_rc(2);
1361
1362	nvram_set("usb_disc0_pid", "");
1363	nvram_set("usb_disc0_safely_removed", "0");
1364	nvram_set("usb_disc1_pid", "");
1365	nvram_set("usb_disc1_safely_removed", "0");
1366// 2008.06 James. }
1367
1368	sync();	// 2008.04 James.
1369
1370	result = eval("rmmod", "cdrom");
1371
1372printf("\n*** start to rmmod usb-storage! ***\n");
1373	//result = system("rmmod usb-storage");
1374	result = eval("/sbin/rmmod", "usb-storage");	// 2008.04 James.
1375
1376printf("\n*** start to insmod usb-storage! ***\n");
1377	//result = system("insmod usb-storage");
1378	result = eval("/sbin/insmod", "usb-storage");	// 2008.04 James.
1379
1380	result = eval("/sbin/insmod", "cdrom");
1381
1382printf("\n*** start to mount the plugged disk! ***\n");
1383	if((strlen(nvram_safe_get("usb_disc0_port")) > 0 && strcmp(nvram_safe_get("usb_disc0_safely_removed"), "1"))
1384			|| (strlen(nvram_safe_get("usb_disc1_port")) > 0 && strcmp(nvram_safe_get("usb_disc1_safely_removed"), "1"))
1385			)
1386		hotplug_usb_mass("");
1387#endif // DLM
1388// 2007.12 James }
1389	return 0;
1390}
1391
1392int
1393remove_storage_main(void)
1394{
1395	remove_usb_mass(NULL);
1396	return 0;
1397}
1398
1399#define MOUNT_VAL_FAIL 	0
1400#define MOUNT_VAL_RONLY	1
1401#define MOUNT_VAL_RW 	2
1402
1403int
1404mount_r(char *usb_part, char *usb_file_part)
1405{
1406	char msg[64];
1407// 2007.12 James {
1408	if(!mount(usb_part, usb_file_part, "ext3", MS_SYNCHRONOUS, NULL))
1409	{
1410		chmod(usb_file_part, 0777);
1411		sprintf(msg, "ext3 fs mounted to %s\n", usb_file_part);
1412		logmessage("USB storage", msg);
1413		printf("ext3 fs mounted to %s\n", usb_file_part);
1414		eval("/sbin/test_of_var_files_in_mount_path", usb_file_part);
1415		return MOUNT_VAL_RW;
1416	}
1417// 2007.12 James }
1418	if(!mount(usb_part, usb_file_part, "ext2", MS_SYNCHRONOUS, NULL))
1419	{
1420		chmod(usb_file_part, 0777);
1421		sprintf(msg, "ext2 fs mounted to %s\n", usb_file_part);
1422#ifdef DLM
1423		logmessage("USB storage", msg);
1424#endif // DLM
1425		printf("ext2 fs mounted to %s\n", usb_file_part);
1426		eval("/sbin/test_of_var_files_in_mount_path", usb_file_part);	// 2007.12. James.
1427		return MOUNT_VAL_RW;
1428	}
1429/*	marked by Jiahao for WL500gP
1430#ifdef LANGUAGE_EN
1431	if(!mount(usb_part, usb_file_part, "vfat", MS_SYNCHRONOUS, NULL))
1432	{
1433		sprintf(msg, "vfat fs mounted to %s\n", usb_file_part);
1434		logmessage("USB storage", msg);
1435		printf("vfat fs mounted to %s\n", usb_file_part);
1436		return MOUNT_VAL_RW;
1437	}
1438#endif
1439#ifdef LANGUAGE_TW
1440	if(!mount(usb_part, usb_file_part, "vfat", MS_SYNCHRONOUS, "codepage=950,iocharset=cp950"))
1441	{
1442		umask(0022);
1443		sprintf(msg, "vfat fs mounted to %s\n", usb_file_part);
1444		logmessage("USB storage", msg);
1445		printf("vfat fs mounted to %s\n", usb_file_part);
1446		return MOUNT_VAL_RW;
1447	}
1448#endif
1449#ifdef LANGUAGE_CN
1450	if(!mount(usb_part, usb_file_part, "vfat", MS_SYNCHRONOUS, "codepage=936,iocharset=cp936"))
1451	{
1452		umask(0022);
1453		sprintf(msg, "vfat fs mounted to %s\n", usb_file_part);
1454		logmessage("USB storage", msg);
1455		printf("vfat fs mounted to %s\n", usb_file_part);
1456		return MOUNT_VAL_RW;
1457	}
1458#endif
1459#ifdef LANGUAGE_KR
1460	if(!mount(usb_part, usb_file_part, "vfat", MS_SYNCHRONOUS, "codepage=949,iocharset=cp949"))
1461	{
1462		umask(0022);
1463		sprintf(msg, "vfat fs mounted to %s\n", usb_file_part);
1464		logmessage("USB storage", msg);
1465		printf("vfat fs mounted to %s\n", usb_file_part);
1466		return MOUNT_VAL_RW;
1467	}
1468#endif
1469#ifdef LANGUAGE_JP
1470	if(!mount(usb_part, usb_file_part, "vfat", MS_SYNCHRONOUS, "codepage=932,iocharset=cp932"))
1471	{
1472		umask(0022);
1473		sprintf(msg, "vfat fs mounted to %s\n", usb_file_part);
1474		logmessage("USB storage", msg);
1475		printf("vfat fs mounted to %s\n", usb_file_part);
1476		return MOUNT_VAL_RW;
1477	}
1478#endif
1479*/
1480	// added by Jiahao for WL500gP
1481
1482	//if(!mount(usb_part, usb_file_part, "vfat", MS_SYNCHRONOUS, "utf8=1,umask=0000,mode=0777"))
1483	if(!mount(usb_part, usb_file_part, "vfat", MS_NOSUID&MS_NODEV&MS_SYNCHRONOUS, "utf8=1,umask=0000,mode=0777"))
1484	{
1485		sprintf(msg, "vfat fs mounted to %s\n", usb_file_part);
1486#ifdef DLM
1487		logmessage("USB storage", msg);
1488#endif // DLM
1489		printf("vfat fs mounted to %s\n", usb_file_part);
1490		eval("/sbin/test_of_var_files_in_mount_path", usb_file_part);	// 2007.12. James.
1491		return MOUNT_VAL_RW;
1492	}
1493	if(!mount(usb_part, usb_file_part, "msdos", MS_SYNCHRONOUS, "utf8=1,umask=0000,mode=0777"))
1494	{
1495		sprintf(msg, "msdos fs mounted to %s\n", usb_file_part);
1496#ifdef DLM
1497		logmessage("USB storage", msg);
1498#endif // DLM
1499		printf("msdoc fs mounted to %s\n", usb_file_part);
1500		eval("/sbin/test_of_var_files_in_mount_path", usb_file_part);	// 2007.12. James.
1501		return MOUNT_VAL_RW;
1502	}
1503	if(!mount(usb_part, usb_file_part, "ntfs", MS_SYNCHRONOUS, "utf8=1,umask=0000"))
1504	{
1505		sprintf(msg, "ntfs(ro) fs mounted to %s\n", usb_file_part);
1506#ifdef DLM
1507		logmessage("USB storage", msg);
1508#endif // DLM
1509		printf("ntfs fs mounted to %s\n", usb_file_part);
1510		return MOUNT_VAL_RONLY;
1511	}
1512/*	marked by Jiahao for WL500gP
1513#ifdef LANGUAGE_EN
1514	if(!mount(usb_part, usb_file_part, "ntfs", MS_SYNCHRONOUS, NULL))
1515	{
1516		sprintf(msg, "ntfs(ro) fs mounted to %s\n", usb_file_part);
1517		logmessage("USB storage", msg);
1518		printf("ntfs fs mounted to %s\n", usb_file_part);
1519		return MOUNT_VAL_RONLY;
1520	}
1521#endif
1522#ifdef LANGUAGE_TW
1523	if(!mount(usb_part, usb_file_part, "ntfs", MS_SYNCHRONOUS, "iocharset=cp932"))
1524	{
1525		sprintf(msg, "ntfs(ro) fs mounted to %s\n", usb_file_part);
1526		logmessage("USB storage", msg);
1527		printf("ntfs fs mounted to %s\n", usb_file_part);
1528		return MOUNT_VAL_RONLY;
1529	}
1530#endif
1531#ifdef LANGUAGE_CN
1532	if(!mount(usb_part, usb_file_part, "ntfs", MS_SYNCHRONOUS, "iocharset=cp936"))
1533	{
1534		sprintf(msg, "ntfs(ro) fs mounted to %s\n", usb_file_part);
1535		logmessage("USB storage", msg);
1536		printf("ntfs fs mounted to %s\n", usb_file_part);
1537		return MOUNT_VAL_RONLY;
1538	}
1539#endif
1540#ifdef LANGUAGE_KR
1541	if(!mount(usb_part, usb_file_part, "ntfs", MS_SYNCHRONOUS, "iocharset=cp949"))
1542	{
1543		sprintf(msg, "ntfs(ro) fs mounted to %s\n", usb_file_part);
1544		logmessage("USB storage", msg);
1545		printf("ntfs fs mounted to %s\n", usb_file_part);
1546		return MOUNT_VAL_RONLY;
1547	}
1548#endif
1549#ifdef LANGUAGE_JP
1550	if(!mount(usb_part, usb_file_part, "ntfs", MS_SYNCHRONOUS, "iocharset=cp950"))
1551	{
1552		sprintf(msg, "ntfs(ro) fs mounted to %s\n", usb_file_part);
1553		logmessage("USB storage", msg);
1554		printf("ntfs fs mounted to %s\n", usb_file_part);
1555		return MOUNT_VAL_RONLY;
1556	}
1557#endif
1558*/
1559	return MOUNT_VAL_FAIL;
1560}
1561
1562#ifdef DLM
1563int calc_crc32( const char *fname, unsigned long *crc ) {
1564    FILE *in;           /* input file */
1565    unsigned char buf[BUFSIZ]; /* pointer to the input buffer */
1566    size_t i, j;        /* buffer positions*/
1567    int k;              /* generic integer */
1568    unsigned long tmpcrc=0xFFFFFFFF;
1569
1570    /* open file */
1571    if((in = fopen(fname, "rb")) == NULL) return -1;
1572
1573    /* loop through the file and calculate CRC */
1574    while( (i=fread(buf, 1, BUFSIZ, in)) != 0 ){
1575        for(j=0; j<i; j++){
1576            k=(tmpcrc ^ buf[j]) & 0x000000FFL;
1577            tmpcrc=((tmpcrc >> 8) & 0x00FFFFFFL) ^ crcs[k];
1578        }
1579    }
1580    fclose(in);
1581    *crc=~tmpcrc; /* postconditioning */
1582    return 0;
1583}
1584
1585// judge if the existed application files are correct.
1586int
1587ckeck_apps_completeness(const char *dirname)
1588{
1589	FILE *fp=NULL;
1590	FILE *fp2=NULL;
1591	char line[256];
1592	char line2[256];
1593	char listfilename[64]="/apps/list";
1594	char crcfilename[64]="/apps/crc";
1595	char appsdir[64];
1596	char tmp[256];
1597	char crc_str[9];
1598	unsigned long crc;
1599
1600	memset(appsdir, 0, sizeof(appsdir));
1601	sprintf(appsdir, "%s%s", dirname, "/.apps");
1602
1603	if ((fp=fopen(listfilename, "r"))==NULL)
1604	{
1605		printf("Cannot find %s.\n", listfilename);
1606		printf("Make sure it's available.\n");
1607		return 0;
1608	}
1609
1610	if ((fp2=fopen(crcfilename, "r"))==NULL)
1611	{
1612		printf("Cannot find %s.\n", crcfilename);
1613		printf("Make sure it's available.\n");
1614		fclose(fp);
1615		return 0;
1616	}
1617
1618	printf("starting to check apps files.\n");
1619	while (!feof(fp))
1620	{
1621		if (fgets(line,sizeof(line),fp)==NULL) break;	/* end-of-file */
1622		if (strlen(line)<3) continue;			/* line empty */
1623
1624		memset(tmp, 0, sizeof(tmp));
1625		sprintf(tmp, "%s%s", appsdir, line+1);		/* file path */
1626		tmp[strlen(tmp)-1]='\0';
1627		printf("FILE: %s\n", tmp);
1628		if(calc_crc32(tmp, &crc) != 0)
1629		{
1630			printf("Error reading file %s.\n", tmp);
1631			sprintf(tmp, "rm -rf %s", appsdir);
1632			system(tmp);
1633			fclose(fp);
1634			fclose(fp2);
1635			return 0;
1636		}
1637
1638		if (fgets(line2,sizeof(line2),fp2)==NULL)
1639		{
1640			sprintf(tmp, "rm -rf %s", appsdir);
1641			system(tmp);
1642			fclose(fp);
1643			fclose(fp2);
1644			return 0;
1645		}
1646		memset(crc_str, 0, sizeof(crc_str));
1647		sprintf(crc_str, "%08lX", crc);
1648		printf("CRC32 now: %s\n", crc_str);
1649
1650		line2[strlen(line2)-1]='\0';
1651		printf("CRC32 org: %s\n", line2);
1652
1653		if(strcmp(crc_str, line2)!=0)
1654		{
1655			sprintf(tmp, "rm -rf %s", appsdir);
1656			system(tmp);
1657			fclose(fp);
1658			fclose(fp2);
1659			return 0;
1660		}
1661	}
1662
1663	fclose(fp);
1664	fclose(fp2);
1665	return 1;
1666}
1667
1668// judge if there are application files.
1669int
1670ckeck_apps_completeness_pre(const char *dirname)
1671{
1672	FILE *fp=NULL;
1673	FILE *fp2=NULL;
1674	char line[256];
1675	char line2[256];
1676	char listfilename[64]="/apps/list";
1677	char crcfilename[64]="/apps/crc";
1678	char appsdir[64];
1679	char tmp[256];
1680	unsigned long crc;
1681
1682	memset(appsdir, 0, sizeof(appsdir));
1683	sprintf(appsdir, "%s%s", dirname, "/.apps");
1684
1685	if ((fp=fopen(listfilename, "r"))==NULL)
1686	{
1687		printf("Cannot find %s.\n", listfilename);
1688		printf("Make sure it's available.\n");
1689
1690		return 0;
1691	}
1692
1693	while (!feof(fp))
1694	{
1695		if (fgets(line,sizeof(line),fp)==NULL) break;	/* end-of-file */
1696		if (strlen(line)<3) continue;			/* line empty */
1697
1698		sprintf(tmp, "%s%s", appsdir, line+1);		/* file path */
1699		tmp[strlen(tmp)-1]='\0';
1700
1701		if((fp2 = fopen(tmp, "rb")) == NULL)
1702		{
1703			printf("Error reading file %s.\n", tmp);
1704			memset(tmp, 0, sizeof(tmp));
1705			sprintf(tmp, "rm -rf %s", appsdir);
1706			system(tmp);
1707			fclose(fp);
1708
1709			return 0;
1710		}
1711		fclose(fp2);
1712	}
1713
1714	fclose(fp);
1715
1716	return 1;
1717}
1718#endif // DLM
1719
1720#ifdef WCN
1721char ibuf2[8192];
1722
1723int
1724channels_in_country(char *abbrev, int channels[])
1725{
1726	int i, j, unit;
1727	wl_channels_in_country_t *cic = (wl_channels_in_country_t *)ibuf2;
1728	char tmp[100], prefix[] = "wlXXXXXXXXXX_";
1729	char *name;
1730	channel_info_t ci;
1731
1732	if ((unit = atoi(nvram_safe_get("wl_unit"))) < 0)
1733		return -1;
1734
1735	snprintf(prefix, sizeof(prefix), "wl%d_", unit);
1736	name = nvram_safe_get(strcat_r(prefix, "ifname", tmp));
1737
1738	i = 0;
1739	channels[i++] = 0;
1740	channels[i] = -1;
1741
1742	if (strlen(abbrev)==0) return 0;
1743
1744	cic->buflen = sizeof(ibuf2);
1745	strcpy(cic->country_abbrev, abbrev);
1746	cic->band = WLC_BAND_2G;
1747	cic->count = 0;
1748
1749	if (wl_ioctl(name, WLC_GET_CHANNELS_IN_COUNTRY, cic, cic->buflen) == 0)
1750	{
1751		if (cic->count == 0)
1752			return 0;
1753
1754		for(j = 0; j < cic->count; j++)
1755		{
1756			channels[i++] = cic->channel[j];
1757		}
1758
1759		channels[i] = -1;
1760	}
1761	return cic->count;
1762}
1763
1764int
1765channels_in_country_asus(char *abbrev, int channels[])
1766{
1767	int i, j;
1768	wl_channels_in_country_t *cic = (wl_channels_in_country_t *)ibuf2;
1769	char var[256], *next;
1770	int log_level, log_drop, log_accept;
1771
1772	i=0;
1773
1774	if (nvram_match("wl_chan_list", "")) {
1775		for(i=0;i<14;i++)
1776		{
1777			channels[i] = i+1;
1778			channels[i+1] = -1;
1779		}
1780	}
1781	else {
1782		foreach(var, nvram_safe_get("wl_chan_list"), next) {
1783			channels[i]=atoi(var);
1784			channels[i+1]=-1;
1785			i++;
1786		}
1787	}
1788	return i;
1789}
1790
1791int
1792get_wl_channels()
1793{
1794	int i, channels[32];
1795
1796	if (!channels_in_country(nvram_safe_get("wl_country_code"), channels))
1797	{
1798		channels_in_country_asus(nvram_safe_get("wl_country_code"), channels);
1799	}
1800
1801	i = 0;
1802	while(channels[i]!=-1)
1803		i++;
1804
1805	return i-1;
1806}
1807
1808int parseXMLtext(char *dst, const char *src)
1809{
1810	char tmpstr[6];
1811	int len=0;
1812	int i=0;
1813	int dstlen=0;
1814
1815	memset(dst, 0, sizeof(dst));
1816	len=strlen(src);
1817
1818	for( i=0; i<len; i++ )
1819	{
1820		if ( (len-i)>=4 )
1821		{
1822			memset(tmpstr, 0, sizeof(tmpstr));
1823			memcpy(tmpstr, src+i, 4);
1824			if ( memcmp(tmpstr, "&gt;", 4)==0 )	// '>'
1825			{
1826				memset(dst+dstlen, 62, 1);
1827				dstlen++;
1828				i+=3;
1829				continue;
1830			}
1831			else if ( memcmp(tmpstr, "&lt;", 4)==0 )	// '<'
1832			{
1833				memset(dst+dstlen, 60, 1);
1834				dstlen++;
1835				i+=3;
1836				continue;
1837			}
1838		}
1839		if ( (len-i)>=5 )
1840		{
1841			memset(tmpstr, 0, sizeof(tmpstr));
1842			memcpy(tmpstr, src+i, 5);
1843			if ( memcmp(tmpstr, "&amp;", 5)==0 )	// '&'
1844			{
1845				memset(dst+dstlen, 38, 1);
1846				dstlen++;
1847				i+=4;
1848				continue;
1849			}
1850		}
1851		memset(dst+dstlen, src[i], 1);
1852		dstlen++;
1853	}
1854	dst[dstlen]=0;
1855	return dstlen;
1856}
1857
1858#define TYPE_configId 1
1859#define TYPE_configAuthorId 2
1860#define TYPE_configAuthor 3
1861#define TYPE_ssid 4
1862#define TYPE_connectionType 5
1863#define TYPE_authentication 6
1864#define TYPE_encryption 7
1865#define TYPE_networkKey 8
1866#define TYPE_keyProvidedAutomatically 9
1867#define TYPE_ieee802Dot1xEnabled 10
1868#define TYPE_eapMethod 11
1869#define TYPE_channel2Dot4 12
1870#define TYPE_channel5Dot0 13
1871#define TYPE_deviceMode 14
1872#define TYPE_timeToLive 15
1873#define TYPE_configHash 16
1874#define TYPE_keyIndex 17
1875
1876void
1877wfc_parser(const char *run_path)
1878{
1879//	if (nvram_invmatch("wcn_enable_x", "1"))
1880//		return;
1881
1882	if (strcmp(run_path, "")==0)
1883		return;
1884
1885	char *p_Value = NULL;
1886	int p_ValueLength = 0;
1887	int bufferLength = 0;
1888	char wfc_path[64];
1889	memset(wfc_path, 0, sizeof(wfc_path));
1890	sprintf(wfc_path, "%s/SMRTNTKY/WSETTING.WFC", run_path);
1891
1892	if (check_if_file_exist(wfc_path)==0)
1893		return;
1894
1895	char *buffer = ILibReadFileFromDisk(wfc_path, &bufferLength);
1896	int offset = 0;
1897	struct ILibXMLNode *xnode = ILibParseXML(buffer,offset,bufferLength);
1898	struct ILibXMLNode *root = xnode;
1899	int i=0;
1900	int t_configId=0;
1901	int t_configAuthorId=0;
1902	int t_configAuthor=0;
1903	int t_ssid=0;
1904	int t_connectionType=0;
1905	int t_authentication=0;
1906	int t_encryption=0;
1907	int t_networkKey=0;
1908	int t_keyProvidedAutomatically=0;
1909	int t_ieee802Dot1xEnabled=0;
1910	int t_eapMethod=0;
1911	int t_channel2Dot4=0;
1912	int t_channel5Dot0=0;
1913	int t_deviceMode=0;
1914	int t_timeToLive=0;
1915	int t_configHash=0;
1916	int t_keyIndex=0;
1917	int t_primaryProfile=0;
1918	int t_optionalProfile=0;
1919	int elementType=0;
1920	char str_configError[256+1];
1921	char str_configId[36+1];
1922	char str_configAuthorId[36+1];
1923	char str_configAuthor[128+1];
1924	char str_ssid[32*5+1];
1925	char str_connectionType[4+1];
1926	char str_authentication[8+1];
1927	char str_encryption[4+1];
1928	char str_networkKey[63*5+1];
1929	char str_keyProvidedAutomatically[1+1];
1930	char str_ieee802Dot1xEnabled[1+1];
1931	char str_eapMethod[17+1];
1932	char str_channel2Dot4[2+1];
1933	char str_channel5Dot0[3+1];
1934	char str_deviceMode[14+1];
1935	char str_timeToLive[5+1];
1936	char str_configHash[20+1];
1937	char str_keyIndex[1+1];
1938	long int long_temp=0;
1939	char **endptr=NULL;
1940	char tmpstr[3];
1941	char tmpstr2[27];
1942	char tmpstr3[32*3+1];
1943	int tmp=0;
1944	int tmp2=0;
1945	int wep_type=0;
1946	FILE *fp=NULL;
1947	char MACpostfix[8+1];
1948	char deviceCFG_path[64];
1949	int reboot_wcn=0;
1950
1951	memset(str_configError, 0, sizeof(str_configError));
1952	memset(str_configId, 0, sizeof(str_configId));
1953	memset(str_configAuthorId, 0, sizeof(str_configAuthorId));
1954	memset(str_configAuthor, 0, sizeof(str_configAuthor));
1955	memset(str_ssid, 0, sizeof(str_ssid));
1956	memset(str_connectionType, 0, sizeof(str_connectionType));
1957	memset(str_authentication, 0, sizeof(str_authentication));
1958	memset(str_encryption, 0, sizeof(str_encryption));
1959	memset(str_networkKey, 0, sizeof(str_networkKey));
1960	memset(str_keyProvidedAutomatically, 0, sizeof(str_keyProvidedAutomatically));
1961	memset(str_ieee802Dot1xEnabled, 0, sizeof(str_ieee802Dot1xEnabled));
1962	memset(str_eapMethod, 0, sizeof(str_eapMethod));
1963	memset(str_channel2Dot4, 0, sizeof(str_channel2Dot4));
1964	memset(str_channel5Dot0, 0, sizeof(str_channel5Dot0));
1965	memset(str_deviceMode, 0, sizeof(str_deviceMode));
1966	memset(str_timeToLive, 0, sizeof(str_timeToLive));
1967	memset(str_configHash, 0, sizeof(str_configHash));
1968	memset(str_keyIndex, 0, sizeof(str_keyIndex));
1969
1970	if(ILibProcessXMLNodeList(root)!=0)
1971	{
1972		/* The XML is not well formed! */
1973		strcpy(str_configError, "Invalid WCN-UFD XML");
1974		printf("%s\n", str_configError);
1975		logmessage("WCN-UFD", str_configError);
1976		goto end1;
1977	}
1978
1979	while(xnode!=NULL)
1980	{
1981		if( xnode->StartTag!=0 )
1982		{
1983			if(xnode->NameLength==8 && memcmp("configId", xnode->Name, xnode->NameLength)==0)
1984			// type="fc:str36"
1985			{
1986				elementType=TYPE_configId;
1987				if (++t_configId>1)
1988					goto end2;
1989			}
1990			else if(xnode->NameLength==14 && memcmp("configAuthorId", xnode->Name, xnode->NameLength)==0)
1991			// type="fc:str36"
1992			{
1993				elementType=TYPE_configAuthorId;
1994				if (++t_configAuthorId>1)
1995					goto end2;
1996			}
1997			else if(xnode->NameLength==12 && memcmp("configAuthor", xnode->Name, xnode->NameLength)==0)
1998			// type="fc:strMax128"
1999			{
2000				elementType=TYPE_configAuthor;
2001				if (++t_configAuthor>1)
2002					goto end2;
2003			}
2004			else if(xnode->NameLength==4 && memcmp("ssid", xnode->Name, xnode->NameLength)==0)
2005			// type="fc:strMax32"
2006			{
2007				elementType=TYPE_ssid;
2008				if (++t_ssid>1)
2009					goto end2;
2010			}
2011			else if(xnode->NameLength==14 && memcmp("connectionType", xnode->Name, xnode->NameLength)==0)
2012			// base="xs:string"
2013			{
2014				elementType=TYPE_connectionType;
2015				if (++t_connectionType>1)
2016					goto end2;
2017			}
2018			else if(xnode->NameLength==14 && memcmp("authentication", xnode->Name, xnode->NameLength)==0)
2019			// base="xs:string"
2020			{
2021				elementType=TYPE_authentication;
2022				if (++t_authentication>1)
2023					goto end2;
2024			}
2025			else if(xnode->NameLength==10 && memcmp("encryption", xnode->Name, xnode->NameLength)==0)
2026			// base="xs:string"
2027			{
2028				elementType=TYPE_encryption;
2029				if (++t_encryption>1)
2030					goto end2;
2031			}
2032			else if(xnode->NameLength==10 && memcmp("networkKey", xnode->Name, xnode->NameLength)==0)
2033			// type="fc:strMin5Max64"
2034			{
2035				elementType=TYPE_networkKey;
2036				if (++t_networkKey>1)
2037					goto end2;
2038			}
2039			else if(xnode->NameLength==24 && memcmp("keyProvidedAutomatically", xnode->Name, xnode->NameLength)==0)
2040			// type="xs:boolean"
2041			{
2042				elementType=TYPE_keyProvidedAutomatically;
2043				if (++t_keyProvidedAutomatically>1)
2044					goto end2;
2045			}
2046			else if(xnode->NameLength==19 && memcmp("ieee802Dot1xEnabled", xnode->Name, xnode->NameLength)==0)
2047			// type="xs:boolean"
2048			{
2049				elementType=TYPE_ieee802Dot1xEnabled;
2050				if (++t_ieee802Dot1xEnabled>1)
2051					goto end2;
2052			}
2053			/*
2054			The following elements are included in the schema but are not supported in the Windows XP SP2 release of the wizard.
2055			*/
2056			else if(xnode->NameLength==9 && memcmp("eapMethod", xnode->Name, xnode->NameLength)==0)
2057			// base="xs:string"
2058			{
2059				elementType=TYPE_eapMethod;
2060				if (++t_eapMethod>1)
2061					goto end2;
2062			}
2063			else if(xnode->NameLength==12 && memcmp("channel2Dot4", xnode->Name, xnode->NameLength)==0)
2064			// type="xs:positiveInteger"
2065			{
2066				elementType=TYPE_channel2Dot4;
2067				if (++t_channel2Dot4>1)
2068					goto end2;
2069			}
2070			else if(xnode->NameLength==12 && memcmp("channel5Dot0", xnode->Name, xnode->NameLength)==0)
2071			// type="xs:positiveInteger"
2072			{
2073				elementType=TYPE_channel5Dot0;
2074				if (++t_channel5Dot0>1)
2075					goto end2;
2076			}
2077			else if(xnode->NameLength==10 && memcmp("deviceMode", xnode->Name, xnode->NameLength)==0)
2078			// base="xs:string"
2079			{
2080				elementType=TYPE_deviceMode;
2081				if (++t_deviceMode>1)
2082					goto end2;
2083			}
2084			else if(xnode->NameLength==10 && memcmp("timeToLive", xnode->Name, xnode->NameLength)==0)
2085			// type="xs:positiveInteger"
2086			{
2087				elementType=TYPE_timeToLive;
2088				if (++t_timeToLive>1)
2089					goto end2;
2090			}
2091			else if(xnode->NameLength==10 && memcmp("configHash", xnode->Name, xnode->NameLength)==0)
2092			// type="fc:str20"
2093			{
2094				elementType=TYPE_configHash;
2095				if (++t_configHash>1)
2096					goto end2;
2097			}
2098			else if(xnode->NameLength==8 && memcmp("keyIndex", xnode->Name, xnode->NameLength)==0)
2099			// type="xs:positiveInteger"
2100			{
2101				elementType=TYPE_keyIndex;
2102				if (++t_keyIndex>1)
2103					goto end2;
2104			}
2105			else if(xnode->NameLength==14 && memcmp("primaryProfile", xnode->Name, xnode->NameLength)==0)
2106			// type="fc:profileInstance"
2107			{
2108				if (++t_primaryProfile>1)
2109					goto end2;
2110				else
2111					goto next_loop;
2112			}
2113			else if(xnode->NameLength==15 && memcmp("optionalProfile", xnode->Name, xnode->NameLength)==0)
2114			// type="fc:profileInstance"
2115			{
2116				if (++t_optionalProfile>32)
2117					goto end2;
2118				else
2119					goto next_loop;
2120			}
2121			else
2122			{
2123				goto next_loop;
2124			}
2125
2126//			printf("%d\n", ++i);
2127			xnode->Name[xnode->NameLength]=0;
2128			printf("Name: %s\n", xnode->Name);
2129			p_ValueLength = ILibReadInnerXML(xnode,&p_Value);
2130			p_Value[p_ValueLength]=0;
2131			printf("Value %s\n\n", p_Value);
2132
2133			if (elementType==TYPE_configId)
2134			{
2135				if (p_ValueLength!=36)
2136					goto end2;
2137
2138   				for( i=0; i<p_ValueLength; i++ )
2139         				if( p_Value[i]<' ' || p_Value[i] >'~')
2140         					goto end2;
2141
2142				if (strcasecmp(nvram_safe_get("wl_configId"), p_Value)==0)
2143				{
2144					printf("have been configured using this WCN-UFD configuration file already\n");
2145					logmessage("WCN-UFD", "have been configured using this WCN-UFD configuration file already");
2146					goto end0;
2147				}
2148
2149				strcpy(str_configId, p_Value);
2150			}
2151			else if (elementType==TYPE_configAuthorId)
2152			{
2153				if (p_ValueLength!=36)
2154					goto end2;
2155
2156   				for( i=0; i<p_ValueLength; i++ )
2157         				if( p_Value[i]<' ' || p_Value[i] >'~')
2158         					goto end2;
2159
2160				strcpy(str_configAuthorId, p_Value);
2161			}
2162			else if (elementType==TYPE_configAuthor)
2163			{
2164				if (p_ValueLength>128 || p_ValueLength==0)
2165					goto end2;
2166
2167   				for( i=0; i<p_ValueLength; i++ )
2168         				if( p_Value[i]<' ' || p_Value[i] >'~')
2169         					goto end2;
2170
2171				strcpy(str_configAuthor, p_Value);
2172			}
2173			else if (elementType==TYPE_ssid)
2174			{
2175				if (p_ValueLength>32*5 || p_ValueLength==0)
2176					goto end2;
2177
2178   				for( i=0; i<p_ValueLength; i++ )
2179         				if( p_Value[i]<' ' || p_Value[i] >'~')
2180         					goto end2;
2181
2182				tmp=parseXMLtext(tmpstr3, p_Value);
2183				if (tmp>32 || tmp==0)
2184					goto end2;
2185
2186				strcpy(str_ssid, tmpstr3);
2187			}
2188
2189			else if (elementType==TYPE_connectionType)
2190			{
2191				if (p_ValueLength==4 && strncasecmp("IBSS", p_Value, 4)==0)
2192					strcpy(str_connectionType, "IBSS");
2193				else if (p_ValueLength==3 && strncasecmp("ESS", p_Value, 3)==0)
2194					strcpy(str_connectionType, "ESS");
2195				else
2196					goto end2;
2197			}
2198			else if (elementType==TYPE_authentication)
2199			{
2200				if (p_ValueLength==4 && strncasecmp("open", p_Value, 4)==0)
2201					strcpy(str_authentication, "open");
2202				else if (p_ValueLength==6 && strncasecmp("shared", p_Value, 6)==0)
2203					strcpy(str_authentication, "shared");
2204				else if (p_ValueLength==8 && strncasecmp("WPA-NONE", p_Value, 8)==0)
2205				{
2206//					strcpy(str_authentication, "WPA-NONE");
2207					printf("aaa\n");
2208					goto end3;
2209				}
2210				else if (p_ValueLength==3 && strncasecmp("WPA", p_Value, 3)==0)
2211					strcpy(str_authentication, "WPA");
2212				else if (p_ValueLength==6 && strncasecmp("WPAPSK", p_Value, 6)==0)
2213					strcpy(str_authentication, "WPAPSK");
2214				else if (p_ValueLength==4 && strncasecmp("WPA2", p_Value, 4)==0)
2215					strcpy(str_authentication, "WPA2");
2216				else if (p_ValueLength==7 && strncasecmp("WPA2PSK", p_Value, 7)==0)
2217					strcpy(str_authentication, "WPA2PSK");
2218				else
2219					goto end2;
2220			}
2221			else if (elementType==TYPE_encryption)
2222			{
2223				if (	p_ValueLength!=3 &&
2224					p_ValueLength!=4
2225				   )
2226					goto end2;
2227
2228				if (p_ValueLength==4 && strncasecmp("none", p_Value, 4)==0)
2229					strcpy(str_encryption, "none");
2230				else if (p_ValueLength==3 && strncasecmp("WEP", p_Value, 3)==0)
2231					strcpy(str_encryption, "WEP");
2232				else if (p_ValueLength==4 && strncasecmp("TKIP", p_Value, 4)==0)
2233					strcpy(str_encryption, "TKIP");
2234				else if (p_ValueLength==3 && strncasecmp("AES", p_Value, 3)==0)
2235					strcpy(str_encryption, "AES");
2236				else
2237					goto end2;
2238			}
2239			else if (elementType==TYPE_networkKey)
2240			{
2241				if (p_ValueLength>63*5 || (p_ValueLength<5 && p_ValueLength!=0))
2242					goto end2;
2243
2244   				for( i=0; i<p_ValueLength; i++ )
2245         				if( p_Value[i]<' ' || p_Value[i] >'~')
2246         					goto end2;
2247
2248				tmp=parseXMLtext(tmpstr3, p_Value);
2249				if (tmp>64 || (tmp<5 && tmp!=0))
2250					goto end2;
2251
2252				strcpy(str_networkKey, tmpstr3);
2253			}
2254			else if (elementType==TYPE_keyProvidedAutomatically)
2255			{
2256				if (p_ValueLength==1 && strncasecmp("0", p_Value, 1)==0)
2257					strcpy(str_keyProvidedAutomatically, "0");
2258				else if (p_ValueLength==1 && strncasecmp("1", p_Value, 1)==0)
2259					strcpy(str_keyProvidedAutomatically, "1");
2260				else
2261					goto end2;
2262			}
2263			else if (elementType==TYPE_ieee802Dot1xEnabled)
2264			{
2265				if (p_ValueLength==1 && strncasecmp("0", p_Value, 1)==0)
2266					strcpy(str_ieee802Dot1xEnabled, "0");
2267				else if (p_ValueLength==1 && strncasecmp("1", p_Value, 1)==0)
2268					strcpy(str_ieee802Dot1xEnabled, "1");
2269				else
2270					goto end2;
2271			}
2272			else if (elementType==TYPE_eapMethod)
2273			{
2274				if (p_ValueLength==7 && strncasecmp("EAP-TLS", p_Value, 7)==0)
2275					strcpy(str_eapMethod, "EAP-TLS");
2276				else if (p_ValueLength==12 && strncasecmp("PEAP-EAP-TLS", p_Value, 12)==0)
2277					strcpy(str_eapMethod, "PEAP-EAP-TLS");
2278				else if (p_ValueLength==17 && strncasecmp("PEAP-EAP-MSCHAPv2", p_Value, 17)==0)
2279					strcpy(str_eapMethod, "PEAP-EAP-MSCHAPv2");
2280				else
2281					goto end2;
2282			}
2283			else if (elementType==TYPE_channel2Dot4)
2284			{
2285				if (p_ValueLength==1 && strncasecmp("0", p_Value, 1)==0)
2286					strcpy(str_channel2Dot4, "0");
2287				else if (p_ValueLength==1 && strncasecmp("1", p_Value, 1)==0)
2288					strcpy(str_channel2Dot4, "1");
2289				else if (p_ValueLength==1 && strncasecmp("2", p_Value, 1)==0)
2290					strcpy(str_channel2Dot4, "2");
2291				else if (p_ValueLength==1 && strncasecmp("3", p_Value, 1)==0)
2292					strcpy(str_channel2Dot4, "3");
2293				else if (p_ValueLength==1 && strncasecmp("4", p_Value, 1)==0)
2294					strcpy(str_channel2Dot4, "4");
2295				else if (p_ValueLength==1 && strncasecmp("5", p_Value, 1)==0)
2296					strcpy(str_channel2Dot4, "5");
2297				else if (p_ValueLength==1 && strncasecmp("6", p_Value, 1)==0)
2298					strcpy(str_channel2Dot4, "6");
2299				else if (p_ValueLength==1 && strncasecmp("7", p_Value, 1)==0)
2300					strcpy(str_channel2Dot4, "7");
2301				else if (p_ValueLength==1 && strncasecmp("8", p_Value, 1)==0)
2302					strcpy(str_channel2Dot4, "8");
2303				else if (p_ValueLength==1 && strncasecmp("9", p_Value, 1)==0)
2304					strcpy(str_channel2Dot4, "9");
2305				else if (p_ValueLength==2 && strncasecmp("10", p_Value, 2)==0)
2306					strcpy(str_channel2Dot4, "10");
2307				else if (p_ValueLength==2 && strncasecmp("11", p_Value, 2)==0)
2308					strcpy(str_channel2Dot4, "11");
2309				else if (p_ValueLength==2 && strncasecmp("12", p_Value, 2)==0)
2310					strcpy(str_channel2Dot4, "12");
2311				else if (p_ValueLength==2 && strncasecmp("13", p_Value, 2)==0)
2312					strcpy(str_channel2Dot4, "13");
2313				else if (p_ValueLength==2 && strncasecmp("14", p_Value, 2)==0)
2314					strcpy(str_channel2Dot4, "14");
2315				else
2316					goto end2;
2317			}
2318			else if (elementType==TYPE_channel5Dot0)
2319			{
2320				if (p_ValueLength==1 && strncasecmp("0", p_Value, 1)==0)
2321					strcpy(str_channel5Dot0, "0");
2322				else if (p_ValueLength==2 && strncasecmp("36", p_Value, 2)==0)
2323					strcpy(str_channel5Dot0, "36");
2324				else if (p_ValueLength==2 && strncasecmp("40", p_Value, 2)==0)
2325					strcpy(str_channel5Dot0, "40");
2326				else if (p_ValueLength==2 && strncasecmp("44", p_Value, 2)==0)
2327					strcpy(str_channel5Dot0, "44");
2328				else if (p_ValueLength==2 && strncasecmp("48", p_Value, 2)==0)
2329					strcpy(str_channel5Dot0, "48");
2330				else if (p_ValueLength==2 && strncasecmp("52", p_Value, 2)==0)
2331					strcpy(str_channel5Dot0, "52");
2332				else if (p_ValueLength==2 && strncasecmp("56", p_Value, 2)==0)
2333					strcpy(str_channel5Dot0, "56");
2334				else if (p_ValueLength==2 && strncasecmp("60", p_Value, 2)==0)
2335					strcpy(str_channel5Dot0, "60");
2336				else if (p_ValueLength==3 && strncasecmp("149", p_Value, 3)==0)
2337					strcpy(str_channel5Dot0, "149");
2338				else if (p_ValueLength==3 && strncasecmp("153", p_Value, 3)==0)
2339					strcpy(str_channel5Dot0, "153");
2340				else if (p_ValueLength==3 && strncasecmp("157", p_Value, 3)==0)
2341					strcpy(str_channel5Dot0, "157");
2342				else if (p_ValueLength==3 && strncasecmp("161", p_Value, 3)==0)
2343					strcpy(str_channel5Dot0, "161");
2344				else
2345					goto end2;
2346			}
2347			else if (elementType==TYPE_deviceMode)
2348			{
2349				if (p_ValueLength==14 && strncasecmp("infrastructure", p_Value, 14)==0)
2350					strcpy(str_deviceMode, "infrastructure");
2351				else if (p_ValueLength==6 && strncasecmp("bridge", p_Value, 6)==0)
2352					strcpy(str_deviceMode, "bridge");
2353				else if (p_ValueLength==8 && strncasecmp("repeater", p_Value, 8)==0)
2354					strcpy(str_deviceMode, "repeater");
2355				else if (p_ValueLength==7 && strncasecmp("station", p_Value, 7)==0)
2356					strcpy(str_deviceMode, "station");
2357				else
2358					goto end2;
2359			}
2360			else if (elementType==TYPE_timeToLive)
2361			{
2362				if (p_ValueLength>5 || p_ValueLength==0)
2363					goto end2;
2364
2365				long_temp=strtol(p_Value, endptr, 10);
2366				if (	(long_temp>(long int)86400) ||
2367					(long_temp<(long int)0) ||
2368					(long_temp==LONG_MAX) ||
2369					(long_temp==LONG_MIN) ||
2370					(endptr!=NULL)
2371				   )
2372					goto end2;
2373				else
2374					sprintf(str_timeToLive, "%d", (int)long_temp);
2375			}
2376			else if (elementType==TYPE_configHash)
2377			{
2378				if (p_ValueLength!=20)
2379					goto end2;
2380
2381   				for( i=0; i<p_ValueLength; i++ )
2382         				if(	p_Value[i]<'0' ||
2383         					(p_Value[i] >'9' && p_Value[i]<'A') ||
2384         					(p_Value[i]>'F' && p_Value[i]<'a') ||
2385         					p_Value[i] >'f'
2386         				  )
2387         					goto end2;
2388
2389				strcpy(str_configHash, p_Value);
2390			}
2391			else if (elementType==TYPE_keyIndex)
2392			{
2393				if (p_ValueLength!=1)
2394					goto end2;
2395
2396				if (p_ValueLength==1 && strncasecmp("1", p_Value, 1)==0)
2397					strcpy(str_keyIndex, "1");
2398				else if (p_ValueLength==1 && strncasecmp("2", p_Value, 1)==0)
2399					strcpy(str_keyIndex, "2");
2400				else if (p_ValueLength==1 && strncasecmp("3", p_Value, 1)==0)
2401					strcpy(str_keyIndex, "3");
2402				else if (p_ValueLength==1 && strncasecmp("4", p_Value, 1)==0)
2403					strcpy(str_keyIndex, "4");
2404				else
2405					goto end2;
2406			}
2407			else
2408				goto end2;
2409		}
2410next_loop:
2411//		xnode = xnode->Peer;
2412		xnode = xnode->Next;
2413	}
2414
2415	if(	t_configId==0 ||
2416		t_configAuthorId==0 ||
2417		t_configAuthor==0 ||
2418		t_ssid==0 ||
2419		t_connectionType==0 ||
2420		t_authentication==0 ||
2421		t_encryption==0 ||
2422		t_networkKey==0 ||
2423		t_keyProvidedAutomatically==0 ||
2424		t_ieee802Dot1xEnabled==0 ||
2425		t_primaryProfile==0
2426	)
2427	{
2428		strcpy(str_configError, "lack essential WCN-UFD XML element");
2429		printf("%s\n", str_configError);
2430		logmessage("WCN-UFD", str_configError);
2431		goto end1;
2432	}
2433
2434	if (t_channel5Dot0==1 && strcmp(str_channel5Dot0, "0")!=0)
2435	{
2436		printf("xxx\n");
2437		goto end3;
2438	}
2439
2440	if (atoi(str_channel2Dot4) > get_wl_channels())
2441	{
2442		printf("yyy\n");
2443		goto end3;
2444	}
2445
2446	if (strcmp(str_encryption, "none")==0 && strcmp(str_authentication, "open")!=0)
2447	{
2448		printf("bbb\n");
2449		goto end3;
2450	}
2451
2452	if (strcmp(str_keyProvidedAutomatically, "0")==0)
2453	{
2454		if (	strcmp(str_authentication, "WPA")==0 ||
2455			strcmp(str_authentication, "WPA2")==0
2456		   )
2457		{
2458			printf("ccc1\n");
2459			goto end3;
2460		}
2461	}
2462	else
2463	{
2464		if (	strcmp(str_ieee802Dot1xEnabled, "1")==0 ||
2465			strcmp(str_encryption, "WEP")!=0
2466		   )
2467			printf("ccc2\n");
2468			goto end3;
2469	}
2470
2471	if (strcmp(str_ieee802Dot1xEnabled, "1")==0)
2472	{
2473		if (	strcmp(str_encryption, "WEP")!=0 ||
2474			(strcmp(str_encryption, "WEP")==0 && (strcmp(str_keyIndex, "1")==0 || strcmp(str_keyIndex, "4")==0)) ||
2475			(strcmp(str_authentication, "WPA")!=0 && strcmp(str_authentication, "WPA2")!=0)
2476		   )
2477		{
2478			printf("ddd\n");
2479			goto end3;
2480		}
2481	}
2482
2483	if (strcmp(str_encryption, "none")==0 || strcmp(str_encryption, "WEP")==0)
2484	{
2485		if (	strcmp(str_authentication, "WPAPSK")==0 ||
2486			strcmp(str_authentication, "WPA2PSK")==0 ||
2487			strcmp(str_authentication, "WPA")==0 ||
2488			strcmp(str_authentication, "WPA2")==0
2489		   )
2490		{
2491			printf("eee\n");
2492			goto end3;
2493		}
2494	}
2495
2496	if (strcmp(str_encryption, "TKIP")==0 || strcmp(str_encryption, "AES")==0)
2497	{
2498		if (	strcmp(str_authentication, "open")==0 ||
2499			strcmp(str_authentication, "shared")==0 ||
2500			strcmp(str_ieee802Dot1xEnabled, "1")==0
2501		   )
2502		{
2503			printf("fff\n");
2504			goto end3;
2505		}
2506	}
2507
2508	if (	//(strcmp(str_authentication, "WPAPSK")==0 && strcmp(str_encryption, "AES")==0) ||
2509		//(strcmp(str_authentication, "WPA2PSK")==0 && strcmp(str_encryption, "TKIP")==0) ||
2510		(strcmp(str_authentication, "WPA")==0 && strcmp(str_encryption, "AES")==0) ||
2511		(strcmp(str_authentication, "WPA2")==0 && strcmp(str_encryption, "TKIP")==0)
2512	   )
2513	{
2514		printf("ggg\n");
2515		goto end3;
2516	}
2517
2518	if (	strcmp(str_authentication, "shared")==0 ||
2519		strcmp(str_authentication, "WPAPSK")==0 ||
2520		strcmp(str_authentication, "WPA2PSK")==0 ||
2521		strcmp(str_authentication, "WPA")==0 ||
2522		strcmp(str_authentication, "WPA2")==0 ||
2523		strcmp(str_ieee802Dot1xEnabled, "1")==0 ||
2524		(strcmp(str_authentication, "open")==0 && strcmp(str_encryption, "WEP")==0)
2525	   )
2526	{
2527		if (strlen(str_networkKey)==0)
2528		{
2529			printf("no network key\n");
2530			logmessage("WCN-UFD", "no network key");
2531			goto end1;
2532		}
2533	}
2534
2535	if (	(strcmp(str_authentication, "open")==0 && strcmp(str_encryption, "WEP")==0) ||
2536		strcmp(str_authentication, "shared")==0 ||
2537		strcmp(str_ieee802Dot1xEnabled, "1")==0
2538	   )
2539	{
2540		if (	strlen(str_networkKey)==10 ||
2541			strlen(str_networkKey)==26
2542		   )
2543		{
2544			for( i=0; i<strlen(str_networkKey); i++ )
2545         			if (	str_networkKey[i]<'0' ||
2546         				(str_networkKey[i]>'9' && str_networkKey[i]<'A') ||
2547         				(str_networkKey[i]>'F' && str_networkKey[i]<'a') ||
2548         				str_networkKey[i]>'f'
2549         			   )
2550				{
2551					strcpy(str_configError, "invalid wireless network key");
2552					printf("%s\n", str_configError);
2553					logmessage("WCN-UFD", str_configError);
2554
2555					goto end1;
2556				}
2557			for( i=0; i<strlen(str_networkKey); i++ )
2558				str_networkKey[i]=toupper(str_networkKey[i]);
2559		}
2560		else if (	strlen(str_networkKey)==5 ||
2561				strlen(str_networkKey)==13
2562			)
2563		{
2564			tmp=strlen(str_networkKey)*2;
2565			memset(tmpstr2, 0, 27);
2566			for( i=0; i<strlen(str_networkKey); i++ )
2567			{
2568				memset(tmpstr, 0, 3);
2569				sprintf(tmpstr, "%X", str_networkKey[i]);
2570				memcpy(&tmpstr2[2*i], tmpstr, 2);
2571			}
2572			memcpy(str_networkKey, tmpstr2, 2*tmp);
2573		}
2574		else
2575		{
2576			strcpy(str_configError, "invalid wireless network key length");
2577			printf("%s\n", str_configError);
2578			logmessage("WCN-UFD", str_configError);
2579			goto end1;
2580		}
2581	}
2582	else if (	strcmp(str_authentication, "WPAPSK")==0 ||
2583			strcmp(str_authentication, "WPA2PSK")==0
2584		)
2585	{
2586		if (strlen(str_networkKey)==64)
2587		{
2588			for( i=0; i<strlen(str_networkKey); i++ )
2589         			if (	str_networkKey[i]<'0' ||
2590         				(str_networkKey[i]>'9' && str_networkKey[i]<'A') ||
2591         				(str_networkKey[i]>'F' && str_networkKey[i]<'a') ||
2592         				str_networkKey[i]>'f'
2593         			   )
2594				{
2595					strcpy(str_configError, "invalid wireless network key");
2596					printf("%s\n", str_configError);
2597					logmessage("WCN-UFD", str_configError);
2598
2599					goto end1;
2600				}
2601			for( i=0; i<strlen(str_networkKey); i++ )
2602				str_networkKey[i]=toupper(str_networkKey[i]);
2603
2604/*
2605			for( i=0; i<64; i+=2 )
2606			{
2607				memset(tmpstr, 0, sizeof(tmpstr));
2608				tmpstr[0]=str_networkKey[i];
2609				tmp=(int)strtol(tmpstr, endptr, 16);
2610
2611				memset(tmpstr, 0, sizeof(tmpstr));
2612				tmpstr[0]=str_networkKey[i+1];
2613				tmp2=(int)strtol(tmpstr, endptr, 16);
2614
2615				tmp2=tmp*16+tmp2;
2616				str_networkKey[i/2]=tmp2;
2617			}
2618			str_networkKey[32]=0;
2619*/
2620		}
2621	}
2622
2623	printf("%d, %s\n", t_configId, str_configId);
2624	printf("%d, %s\n", t_configAuthorId, str_configAuthorId);
2625	printf("%d, %s\n", t_configAuthor, str_configAuthor);
2626	printf("%d, %s\n", t_ssid, str_ssid);
2627	printf("%d, %s\n", t_connectionType, str_connectionType);
2628	printf("%d, %s\n", t_authentication, str_authentication);
2629	printf("%d, %s\n", t_encryption, str_encryption);
2630	printf("%d, %s\n", t_networkKey, str_networkKey);
2631	printf("%d, %s\n", t_keyProvidedAutomatically, str_keyProvidedAutomatically);
2632	printf("%d, %s\n", t_ieee802Dot1xEnabled, str_ieee802Dot1xEnabled);
2633	printf("%d\n", t_primaryProfile);
2634	printf("***************************************\n");
2635	printf("*** following elements are optional ***\n");
2636	printf("%d, %s\n", t_eapMethod, str_eapMethod);
2637	printf("%d, %s\n", t_channel2Dot4, str_channel2Dot4);
2638	printf("%d, %s\n", t_channel5Dot0, str_channel5Dot0);
2639	printf("%d, %s\n", t_deviceMode, str_deviceMode);
2640	printf("%d, %s\n", t_timeToLive, str_timeToLive);
2641	printf("%d, %s\n", t_configHash, str_configHash);
2642	printf("%d, %s\n", t_keyIndex, str_keyIndex);
2643	printf("%d\n\n", t_optionalProfile);
2644
2645	nvram_set("wl_configId", str_configId);
2646	nvram_set("wl_ssid", str_ssid);
2647	memset(tmpstr3, 0, sizeof(tmpstr3));
2648	char_to_ascii(tmpstr3, str_ssid);
2649	nvram_set("wl_ssid2", tmpstr3);
2650
2651	if (t_channel2Dot4==1)
2652	{
2653		nvram_set("wl_channel", str_channel2Dot4);
2654	}
2655
2656	if (strcmp(str_ieee802Dot1xEnabled, "1")==0)
2657	{
2658		nvram_set("wl_auth_mode", "radius");
2659	}
2660	else if (strcmp(str_authentication, "open")==0)
2661	{
2662		nvram_set("wl_auth_mode", "open");
2663	}
2664	else if (strcmp(str_authentication, "shared")==0)
2665	{
2666		nvram_set("wl_auth_mode", "shared");
2667	}
2668	else if (strcmp(str_authentication, "WPAPSK")==0
2669			|| strcmp(str_authentication, "WPA2PSK")==0)
2670	{
2671		nvram_set("wl_auth_mode", "psk");
2672// 2008.07 James. {
2673		/*if (strcmp(str_authentication, "WPAPSK")==0)
2674			nvram_set("wl_wpa_mode", "1");
2675		else
2676			nvram_set("wl_wpa_mode", "2");
2677		nvram_set("wl_crypto", "tkip+aes");//*/
2678		if (strcmp(str_authentication, "WPAPSK")==0){
2679			nvram_set("wl_wpa_mode", "1");
2680			nvram_set("wl_crypto", "tkip");
2681		}
2682		else{
2683			nvram_set("wl_wpa_mode", "2");
2684			nvram_set("wl_crypto", "aes");
2685		}
2686// 2008.07 James. }
2687/*
2688		if (strcmp(str_encryption, "TKIP")==0)
2689			nvram_set("wl_crypto", "tkip");
2690		else if (strcmp(str_encryption, "AES")==0)
2691			nvram_set("wl_crypto", "aes");
2692*/
2693	}
2694	else if (strcmp(str_authentication, "WPA")==0)
2695	{
2696		nvram_set("wl_auth_mode", "wpa");
2697		nvram_set("wl_crypto", "tkip");
2698	}
2699	else if (strcmp(str_authentication, "WPA2")==0)
2700	{
2701		nvram_set("wl_auth_mode", "wpa2");
2702		nvram_set("wl_crypto", "aes");
2703	}
2704
2705	if (strcmp(str_encryption, "TKIP")==0 || strcmp(str_encryption, "AES")==0)
2706	{
2707		nvram_set("wl_wpa_psk", str_networkKey);
2708		nvram_set("wl_wep_x", "0");
2709	}
2710	else if (strcmp(str_encryption, "WEP")==0)
2711	{
2712		if (strlen(str_networkKey)==10)
2713		{
2714			nvram_set("wl_wep_x", "1");
2715			nvram_set("wl_key1", "6565656565");
2716			nvram_set("wl_key2", "8383838383");
2717			nvram_set("wl_key3", "8585858585");
2718			nvram_set("wl_key4", "8383838383");
2719		}
2720		else if (strlen(str_networkKey)==26)
2721		{
2722			nvram_set("wl_wep_x", "2");
2723			nvram_set("wl_key1", "65656565656565656565656565");
2724			nvram_set("wl_key2", "83838383838383838383838383");
2725			nvram_set("wl_key3", "85858585858585858585858585");
2726			nvram_set("wl_key4", "83838383838383838383838383");
2727		}
2728
2729		if (t_keyIndex==0)
2730		{
2731			nvram_set("wl_key", "1");
2732			nvram_set("wl_key1", str_networkKey);
2733		}
2734		else
2735		{
2736			nvram_set("wl_key", str_keyIndex);
2737			memset(tmpstr2, 0, sizeof(tmpstr2));
2738			sprintf(tmpstr2, "wl_key%s", str_keyIndex);
2739			nvram_set(tmpstr2, str_networkKey);
2740		}
2741	}
2742	else
2743	{
2744		nvram_set("wl_wep_x", "0");
2745		nvram_set("wl_key1", "");
2746		nvram_set("wl_key2", "");
2747		nvram_set("wl_key3", "");
2748		nvram_set("wl_key4", "");
2749		nvram_set("wl_wpa_psk", "");
2750	}
2751
2752	if (t_timeToLive==1)
2753	{
2754		nvram_set("wl_wpa_gtk_rekey", str_timeToLive);
2755	}
2756
2757	reboot_wcn=1;
2758
2759	goto end1;
2760end3:
2761	strcpy(str_configError, "unsupported WCN-UFD XML element value");
2762	printf("%s\n", str_configError);
2763	logmessage("WCN-UFD", str_configError);
2764	goto end1;
2765end2:
2766	strcpy(str_configError, "Invalid WCN-UFD XML element");
2767	printf("%s\n", str_configError);
2768	logmessage("WCN-UFD", str_configError);
2769end1:
2770	memset(MACpostfix, 0, sizeof(MACpostfix));
2771	memset(deviceCFG_path, 0, sizeof(deviceCFG_path));
2772	memset(tmpstr2, 0, sizeof(tmpstr2));
2773	strcpy(tmpstr2, nvram_safe_get("et0macaddr")+6);
2774	tmpstr2[2]=0;
2775	tmpstr2[5]=0;
2776	tmpstr2[8]=0;
2777	sprintf(MACpostfix, "%s%s%s%s", tmpstr2, tmpstr2+3, tmpstr2+6, tmpstr2+9);
2778	for( i=0; i<strlen(MACpostfix); i++ )
2779		MACpostfix[i]=toupper(MACpostfix[i]);
2780	sprintf(deviceCFG_path, "%s/SMRTNTKY/DEVICE/%s.WFC", run_path, MACpostfix);
2781	fp=fopen(deviceCFG_path, "w");
2782
2783	if (fp!=NULL)
2784	{
2785		fprintf(fp, "<?xml version=\"1.0\"?>\n");
2786		fprintf(fp, "<device xmlns=\"http://www.microsoft.com/provisioning/DeviceProfile/2004\">\n");
2787		fprintf(fp, "\t<configId>%s</configId>\n", str_configId);
2788		if (strlen(str_configError)!=0)
2789			fprintf(fp, "\t<configError>%s</configError>\n", str_configError);
2790		fprintf(fp, "\t<manufacturer>ASUSTeK</manufacturer>\n");
2791		fprintf(fp, "\t<manufacturerURL>http://www.asus.com/</manufacturerURL>\n");
2792		fprintf(fp, "\t<modelName>%s</modelName>\n", nvram_safe_get("productid"));
2793		memset(tmpstr2, 0, sizeof(tmpstr2));
2794		strcpy(tmpstr2, nvram_safe_get("et0macaddr"));
2795		for( i=0; i<strlen(tmpstr2); i++ )
2796			tmpstr2[i]=toupper(tmpstr2[i]);
2797		fprintf(fp, "\t<serialNumber>%s</serialNumber>\n", tmpstr2);
2798		fprintf(fp, "\t<firmwareVersion>%s</firmwareVersion>\n", nvram_safe_get("firmver"));
2799		fprintf(fp, "\t<deviceType>Access_Point</deviceType>\n");
2800		fprintf(fp, "</device>\n");
2801		fclose(fp);
2802	}
2803end0:
2804	ILibDestructXMLNodeList(root);
2805// 2007.12 James {
2806	//umount_disc_parts_rc(0);
2807	//umount_disc_parts_rc(1);
2808// 2007.12 James }
2809
2810	if (reboot_wcn==1){
2811		nvram_set("reboot_WCN", "2");
2812		nvram_set("x_Setting", "1");/* Cherry Cho added in 2007/4/13. */
2813		system("killall wsccmd");
2814	}
2815}
2816
2817void char_to_ascii(char *output, char *input)// Transfer Char to ASCII
2818{                                                   // Cherry_Cho added in 2006/9/29
2819        int i;
2820        char tmp[10];
2821        char *ptr;
2822
2823        ptr = output;
2824
2825        for( i=0; i<strlen(input); i++ )
2826        {
2827                if((input[i]>='0' && input[i] <='9')
2828                   ||(input[i]>='A' && input[i]<='Z')
2829                   ||(input[i] >='a' && input[i]<='z')
2830                   || input[i] == '!' || input[i] == '*'
2831                   || input[i] == '(' || input[i] == ')'
2832                   || input[i] == '_' || input[i] == '-'
2833                   || input[i] == "'" || input[i] == '.')
2834                {
2835                        *ptr = input[i];
2836                        ptr ++;
2837                }
2838                else
2839                {
2840                        sprintf(tmp, "%%%.02X", input[i]);
2841                        strcpy(ptr, tmp);
2842                        ptr += 3;
2843                }
2844        }
2845
2846        *ptr = '\0';
2847
2848}
2849
2850#endif // WCN
2851
2852/* insert usb mass storage */
2853int
2854hotplug_usb_mass(char *product)	// modified by Jiahao for WL500gP
2855{
2856	DIR *dir_to_open, *dir_of_usb, *usb_dev_disc, *usb_dev_part;
2857	char usb_disc[128], usb_part[128], usb_file_part[128];
2858	char usb_disc_mount_path[128], usb_disc_mount_path2[128], tmp[32];
2859	char usb_disc_fs_path[128];
2860	int n=0, m=0, p=0;
2861	struct dirent *dp, *dp_disc, **dpopen;
2862	char tmpstr[128], test_path[128];
2863	int i, j;
2864	FILE *fp;
2865	int ret=0;
2866	int apps_comp=0;
2867	int apps_status=0;
2868	int apps_disk_free=0;
2869	int apps_comp_pre=0;
2870	int new_disc[2];
2871	new_disc[0]=0;
2872	new_disc[1]=0;
2873#ifdef DLM
2874	char *buf=NULL;
2875	int buflen=0;
2876	struct sysinfo info;
2877#endif // DLM
2878	char dev_real_path[PATH_MAX];	// 2007.11 James.
2879
2880	nvram_set("usb_storage_device", "");	// 2007.12 James.
2881
2882#ifdef CDMA
2883	if(nvram_match("hsdpa_enable", "1")
2884			&& eject_scsi("/dev/cdroms/cdrom0")){
2885logmessage("USB Storage", "Succeed to remove the CD-ROM device.");
2886		return 0;
2887	}
2888	else
2889logmessage("USB Storage", "Fail to remove the CD-ROM device.");
2890#endif
2891	dir_to_open=dir_of_usb=usb_dev_disc=usb_dev_part=NULL;
2892	strcpy(tmp, "");
2893
2894#ifdef DLM
2895	nvram_set("usb_storage_busy", "1");
2896	nvram_set("apps_status_checked", "0");
2897
2898	if (	nvram_match("eject_from_web", "1") &&
2899		(nvram_invmatch("usb_disc0_dev", "") || nvram_invmatch("usb_disc1_dev", ""))
2900	   )
2901		goto eject;
2902#endif // DLM
2903
2904	if (nvram_match("usb_ftpenable_x", "0")) return 0;
2905
2906	// Mount USB to system
2907	if((usb_dev_disc = opendir("/dev/discs")))
2908	{
2909		while(usb_dev_disc && (dp=readdir(usb_dev_disc)))
2910		{
2911			if(!strncmp(dp->d_name, "..", NAME_MAX) || !strncmp(dp->d_name, ".", NAME_MAX) /*|| !strncmp(dp->d_name, "disc0", NAME_MAX)*/)
2912				continue;
2913
2914			sprintf(usb_disc, "/dev/discs/%s", dp->d_name);
2915// 2007.11 James {
2916			realpath(usb_disc, dev_real_path);
2917			memset(usb_disc, 0, sizeof(usb_disc));
2918			strcpy(usb_disc, dev_real_path);
2919// 2007.11 James }
2920			if (nvram_match("usb_disc0_dev", usb_disc))
2921				continue;
2922			if (nvram_match("usb_disc1_dev", usb_disc))
2923				continue;
2924
2925			//logs(usb_disc);
2926			if((usb_dev_part = opendir(usb_disc)))
2927			{
2928				m = 0;	// part count of each disc
2929				while(usb_dev_part && (dp_disc=readdir(usb_dev_part)) && (m<7))
2930				{
2931					//logs(dp_disc->d_name);
2932					if(	!strncmp(dp_disc->d_name, "..", NAME_MAX) ||
2933						!strncmp(dp_disc->d_name, ".", NAME_MAX) ||
2934						!strncmp(dp_disc->d_name, "disc", NAME_MAX) ||
2935						!strncmp(dp_disc->d_name, "generic", NAME_MAX)
2936					  )
2937						continue;
2938
2939					if (m==0)
2940					{
2941						sprintf(tmpstr, nvram_get("usb_disc1_dev"));
2942						sprintf(test_path, nvram_get("usb_disc0_dev"));
2943
2944						if (nvram_match("usb_disc0_dev", "") && strcmp(usb_disc, tmpstr)!=0)
2945						{
2946							nvram_set("usb_disc0_dev", usb_disc);
2947							nvram_set("usb_disc0_safely_removed", "0");	// 2008.06 James.
2948							new_disc[0]=1;
2949						}
2950						else if (nvram_match("usb_disc1_dev", "") && strcmp(usb_disc, test_path)!=0)
2951						{
2952							nvram_set("usb_disc1_dev", usb_disc);
2953							nvram_set("usb_disc1_safely_removed", "0");	// 2008.06 James.
2954							new_disc[1]=1;
2955						}
2956					}
2957
2958					sprintf(usb_part, "/dev/discs/%s/%s", dp->d_name, dp_disc->d_name);
2959					realpath(usb_part, dev_real_path);	// 2007.11 James.
2960					if (n==0) {
2961						sprintf(usb_file_part, "/tmp/harddisk");
2962						mkdir_if_none(usb_file_part);
2963					}
2964					sprintf(usb_file_part, "/tmp/harddisk/part%d", n);
2965					while (check_if_dir_exist(usb_file_part)==1)
2966						sprintf(usb_file_part, "/tmp/harddisk/part%d", ++n);
2967					mkdir_if_none(usb_file_part);
2968#ifdef MOUNTALL
2969					//eval("mount", usb_part, usb_file_part);
2970					eval("mount", dev_real_path, usb_file_part);	// 2007.11 James.
2971					printf("mountall\n");
2972#else // MOUNTALL
2973					//if (mount_r(usb_part, usb_file_part))
2974					if(mount_r(dev_real_path, usb_file_part))	// 2007.11 James.
2975					{
2976						if (strcmp(usb_disc, nvram_safe_get("usb_disc0_dev"))==0)
2977						{
2978							j=atoi(nvram_safe_get("usb_disc0_index"));
2979							sprintf(usb_disc_mount_path, "usb_disc0_path%d", j);
2980							sprintf(usb_disc_mount_path2, "usb_disc0_index");
2981							sprintf(usb_disc_fs_path, "usb_disc0_fs_path%d", j);
2982						}
2983						else if (strcmp(usb_disc, nvram_safe_get("usb_disc1_dev"))==0)
2984						{
2985							j=atoi(nvram_safe_get("usb_disc1_index"));
2986							sprintf(usb_disc_mount_path, "usb_disc1_path%d", j);
2987							sprintf(usb_disc_mount_path2, "usb_disc1_index");
2988							sprintf(usb_disc_fs_path, "usb_disc1_fs_path%d", j);
2989						}
2990						nvram_set(usb_disc_mount_path, usb_file_part);
2991						//nvram_set(usb_disc_fs_path, usb_part);
2992						nvram_set(usb_disc_fs_path, dev_real_path);	// 2007.11 James.
2993						sprintf(usb_disc_mount_path, "%d", ++j);
2994						nvram_set(usb_disc_mount_path2, usb_disc_mount_path);
2995						n++;
2996						m++;
2997						p++;
2998					}
2999					else
3000					{
3001						rmdir(usb_file_part);
3002						//printf("mount %s failed\n", usb_part);
3003						printf("mount %s failed\n", dev_real_path);	// 2007.11 James.
3004					}
3005#endif // MOUNTALL
3006				}
3007
3008				if (!m) // There is no other partition
3009				{
3010					sprintf(usb_part, "/dev/discs/%s/disc", dp->d_name);
3011					realpath(usb_part, dev_real_path);	// 2007.11 James.
3012					if (n==0)
3013					{
3014						sprintf(usb_file_part, "/tmp/harddisk");
3015						mkdir_if_none(usb_file_part);
3016					}
3017					sprintf(usb_file_part, "/tmp/harddisk/part%d", n);
3018					while (check_if_dir_exist(usb_file_part)==1)
3019						sprintf(usb_file_part, "/tmp/harddisk/part%d", ++n);
3020					mkdir_if_none(usb_file_part);
3021
3022#ifdef MOUNTALL
3023					//eval("mount", usb_part, usb_file_part);
3024					eval("mount", dev_real_path, usb_file_part);	// 2007.11 James.
3025#else // MOUNTALL
3026					//if(mount_r(usb_part, usb_file_part))
3027					if(mount_r(dev_real_path, usb_file_part))	// 2007.11 James.
3028					{
3029
3030						sprintf(tmpstr, nvram_get("usb_disc1_dev"));
3031						sprintf(test_path, nvram_get("usb_disc0_dev"));
3032
3033						if (nvram_match("usb_disc0_dev", "") && strcmp(usb_disc, tmpstr)!=0)
3034						{
3035							nvram_set("usb_disc0_dev", usb_disc);
3036							new_disc[0]=1;
3037						}
3038						else if (nvram_match("usb_disc1_dev", "") && strcmp(usb_disc, test_path)!=0)
3039						{
3040							nvram_set("usb_disc1_dev", usb_disc);
3041							new_disc[1]=1;
3042						}
3043
3044						//if (strncmp(usb_part, nvram_safe_get("usb_disc0_dev"), 16)==0)
3045						if(!strncmp(usb_part, nvram_safe_get("usb_disc0_dev"), 33))	// 2007.11 James.
3046						{
3047							nvram_set("usb_disc0_path0", usb_file_part);
3048							//nvram_set("usb_disc0_fs_path0", usb_part);
3049							nvram_set("usb_disc0_fs_path0", dev_real_path);	// 2007.11 James.
3050							nvram_set("usb_disc0_index", "1");
3051						}
3052						//else if (strncmp(usb_part, nvram_safe_get("usb_disc1_dev"), 16)==0)
3053						else if(!strncmp(usb_part, nvram_safe_get("usb_disc1_dev"), 33))	// 2007.11 James.
3054						{
3055							nvram_set("usb_disc1_path0", usb_file_part);
3056							//nvram_set("usb_disc1_fs_path0", usb_part);
3057							nvram_set("usb_disc1_fs_path0", dev_real_path);	// 2007.11 James.
3058							nvram_set("usb_disc1_index", "1");
3059						}
3060						n++;
3061						p++;
3062					}
3063					else
3064					{
3065						rmdir(usb_file_part);
3066						//printf("mount %s failed\n", usb_part);
3067						printf("mount %s failed\n", dev_real_path);	// 2007.11 James.
3068					}
3069#endif // MOUNTALL
3070				}
3071
3072				printf("\n\n**********************************************\n");
3073				write_disc_status();
3074				printf("**********************************************\n\n");
3075			}
3076		}
3077	}
3078#ifdef DLM
3079eject:
3080	if(p
3081			|| (nvram_match("eject_from_web", "1")
3082				&& (nvram_invmatch("usb_disc0_dev", "") || nvram_invmatch("usb_disc1_dev", "")))
3083			)// if any usb mass storage device newly mounted at this time
3084	{
3085		nvram_set("eject_from_web", "0");
3086
3087		strcpy(test_path, "");
3088
3089		if(nvram_invmatch("usb_disc0_dev", "") && (nvram_match("apps_dlx", "0") || check_disk_free_GE_1G(nvram_safe_get("usb_disc0_path0")) == 2))
3090		{
3091			strcpy(test_path, nvram_safe_get("usb_disc0_path0"));
3092		}
3093		else if ( nvram_invmatch("usb_disc1_dev", "") && (nvram_match("apps_dlx", "0")||check_disk_free_GE_1G(nvram_safe_get("usb_disc1_path0"))==2) )
3094		{
3095			strcpy(test_path, nvram_safe_get("usb_disc1_path0"));
3096		}
3097		else if ( nvram_invmatch("usb_disc0_dev", "") )
3098		{
3099			strcpy(test_path, nvram_safe_get("usb_disc0_path0"));
3100		}
3101		else if ( nvram_invmatch("usb_disc1_dev", "") )
3102		{
3103			strcpy(test_path, nvram_safe_get("usb_disc1_path0"));
3104		}
3105
3106		strcpy(tmp, test_path);
3107
3108		if(nvram_match("swap_on", "0") && nvram_match("apps_dlx", "1")
3109				&& (apps_comp_pre = ckeck_apps_completeness_pre(tmp)) == 1)
3110		{
3111			if(strcmp(test_path, "") != 0)
3112			{
3113				memset(tmpstr, 0, sizeof(tmpstr));
3114				sprintf(tmpstr, "%s/swap", test_path);
3115				unlink(tmpstr);
3116				memset(tmpstr, 0, sizeof(tmpstr));
3117				sprintf(tmpstr, "%s/.swap", test_path);
3118				unlink(tmpstr);
3119
3120				ret = check_disk_free_GE_1G(test_path);
3121
3122				if(ret==2)
3123				{
3124					if(strcmp(test_path, nvram_safe_get("usb_disc0_path0")) == 0)
3125						nvram_set("apps_dms_usb_port_x2", nvram_safe_get("usb_disc0_port"));
3126					else if (strcmp(test_path, nvram_safe_get("usb_disc1_path0")) == 0)
3127						nvram_set("apps_dms_usb_port_x2", nvram_safe_get("usb_disc1_port"));
3128
3129					sysinfo(&info);
3130					if((info.freeram+info.bufferram) >= 1024*1024*2)
3131						buflen = 1024*1024*2;
3132					else if((info.freeram+info.bufferram) >= 1024*1024*1.6)
3133						buflen = 1024*1024*1.6;
3134					else if((info.freeram+info.bufferram) >= 1024*1024*1)
3135						buflen = 1024*1024*1;
3136					else if((info.freeram+info.bufferram) >= 1024*1024*0.8)
3137						buflen = 1024*1024*0.8;
3138					else
3139						buflen = 1024*1024*0.5;
3140					buf = malloc(buflen);
3141					for(i = 0; i < buflen; i++)
3142						buf[i]='\n';
3143
3144					fp = fopen(tmpstr, "a");
3145					if(fp != NULL)
3146					{
3147						for(i = 0; i < (1024*1024*32/buflen); i++)
3148							fprintf(fp, "%s", buf);
3149						free(buf);
3150						fclose(fp);
3151
3152						/*memset(test_path, 0, sizeof(test_path));
3153						sprintf(test_path, "mkswap %s", tmpstr);
3154						system(test_path);
3155
3156						memset(test_path, 0, sizeof(test_path));
3157						sprintf(test_path, "swapon %s", tmpstr);
3158						system(test_path);//*/
3159						eval("/sbin/mkswap", tmpstr);
3160
3161						swapon(tmpstr, 0);	// 2008.04 James.
3162
3163						logmessage("USB storage", "32MB swap file is added");
3164						nvram_set("swap_on", "1");
3165						nvram_set("swap_file", tmpstr);	// 2008.06 James.
3166					}
3167				}
3168				else if (ret==1)
3169					logmessage("USB storage", "The swap file is not added for free space is less than 33MB");
3170				else if (ret==3)
3171					logmessage("USB storage", "The swap file is not added for partition size is less than 1024MB");
3172				else if (ret==0)
3173					logmessage("USB storage", "The swap file is not added for unknown reasons");
3174			}
3175		}
3176
3177		start_script(new_disc); // Move ahead to speed up WCN
3178		if(!nvram_match("reboot_WCN", "2"))
3179			run_ftpsamba();
3180
3181//		if (nvram_match("apps_dmsx", "1"))
3182//			exec_dms();
3183
3184		apps_disk_free = check_disk_free_apps(tmp, apps_comp);
3185		if(apps_disk_free == 1)
3186			nvram_set("apps_disk_free", "1");
3187		else
3188			nvram_set("apps_disk_free", "0");
3189/*
3190		if((apps_comp_pre==1) &&
3191		   nvram_match("apps_running", "0") &&
3192		   (nvram_match("apps_dlx", "1")||nvram_match("apps_dmsx", "1"))
3193		  )
3194*/
3195		//if(nvram_match("apps_running", "0") &&
3196		if(strcmp(nvram_safe_get("apps_running"), "1") != 0
3197				&& !nvram_match("reboot_WCN", "2")
3198				&& ((apps_comp_pre == 1 && nvram_match("apps_dlx", "1")) || nvram_match("apps_dmsx", "1"))
3199				)
3200		{
3201			if (strcmp(tmp, "")!=0)
3202			{
3203				apps_comp=ckeck_apps_completeness(tmp);
3204				if (apps_comp==1)
3205					nvram_set("apps_comp", "1");
3206				else
3207				{
3208					nvram_set("apps_comp", "0");
3209					if ( strcmp(nvram_get("swap_on"), "1")==0)
3210					{
3211						printf("try to swapoff swap file.\n");
3212						if (strcmp(tmp, "")!=0)
3213						{
3214							memset(tmpstr, 0, sizeof(tmpstr));
3215							sprintf(tmpstr, "%s/.swap", tmp);
3216							swapoff(tmpstr);
3217							sleep(1);
3218							if (swap_check()==1)
3219							{
3220								logmessage("USB storage", "swapoff unsuccessfully");
3221								nvram_set("swapoff_failed", "1");
3222								unlink(tmpstr);
3223								nvram_set("reboot", "1");
3224							}
3225							else
3226							{
3227								logmessage("USB storage", "swapoff successfully");
3228								nvram_set("swap_on", "0");
3229								nvram_set("swap_file", "");	// 2008.06 James.
3230								nvram_set("swapoff_failed", "0");
3231								nvram_set("apps_dms_usb_port_x2", "-1");
3232								unlink(tmpstr);
3233							}
3234						}
3235					}
3236				}
3237
3238				if (nvram_match("apps_dlx", "0") ||
3239				    (nvram_match("apps_dlx", "1") && ret==2) ||
3240				    (nvram_match("apps_dmsx", "1") && !(nvram_match("apps_dlx", "1") && ret==2))
3241				   )
3242				{
3243					if ((apps_comp==1 && apps_disk_free==1) || nvram_match("apps_dmsx", "1"))
3244					{
3245
3246						if (strcmp(tmp, nvram_safe_get("usb_disc0_path0"))==0)
3247							nvram_set("apps_dms_usb_port_x", nvram_safe_get("usb_disc0_port"));
3248						else if (strcmp(tmp, nvram_safe_get("usb_disc1_path0"))==0)
3249							nvram_set("apps_dms_usb_port_x", nvram_safe_get("usb_disc1_port"));
3250
3251						start_apps();
3252						//nvram_set("apps_running", "1");
3253					}
3254				}
3255				else
3256				{
3257					fprintf(stderr, "skip running DMS & DM for no swap file\n");
3258					logmessage("Media Server", "daemon is not started for no swap file");
3259					logmessage("Download Master", "daemon is not started for no swap file");
3260				}
3261			}
3262			else
3263				fprintf(stderr, "skip running DMS & DM for mismatching\n");
3264		}
3265		else
3266			fprintf(stderr, "skip running DMS & DM\n");
3267	}
3268
3269	nvram_set("usb_storage_busy", "0");
3270	nvram_set("apps_status_checked", "1");
3271#else // DLM
3272	if (p)	// if any usb mass storage device newly mounted at this time
3273	{
3274		start_script(new_disc);
3275	}
3276#endif // DLM
3277
3278#ifdef USBCOPY_SUPPORT
3279	n = 1;
3280	if((dir_to_open = opendir("/tmp/harddisk")))
3281	{
3282		while(dir_to_open && (dp=readdir(dir_to_open)))
3283		{
3284			if(!strncmp(dp->d_name, "..", NAME_MAX) || !strncmp(dp->d_name, ".", NAME_MAX) || !strncmp(dp->d_name, "part", 4))
3285				continue;
3286			sprintf(usb_part, "/tmp/harddisk/%s", dp->d_name);
3287			if(scandir(usb_part, &dpopen, 0, alphasort) <= 2)
3288				continue;
3289			while(1)
3290			{
3291				sprintf(path_copy_to, "/tmp/harddisk/part1/USBpart%03d", n);
3292				if(!opendir(path_copy_to))
3293				{
3294					if(mkdir(path_copy_to, 0777))
3295					{
3296						perror("error on creating usb directory");
3297					}
3298					eval("echo", path_copy_to);
3299					break;
3300				}
3301				else
3302					n++;
3303			}
3304			if((dir_of_usb = opendir(usb_part)))
3305			{
3306				while(dir_of_usb && (dp_disc=readdir(dir_of_usb)))
3307				{
3308					if(!strncmp(dp_disc->d_name, "..", NAME_MAX) || !strncmp(dp_disc->d_name, ".", NAME_MAX))
3309						continue;
3310					sprintf(path_to_copy, "/tmp/harddisk/%s/%s", dp->d_name, dp_disc->d_name);
3311					eval("cp", "-Rf", path_to_copy, path_copy_to);
3312					sync();
3313				}
3314			}
3315			n++;
3316		}
3317	}
3318#endif // USBCOPY_SUPPORT
3319
3320	if(usb_dev_disc)
3321		closedir(usb_dev_disc);
3322	if(usb_dev_part)
3323		closedir(usb_dev_part);
3324	if(dir_to_open)
3325		closedir(dir_to_open);
3326
3327	return 0;
3328}
3329
3330#ifdef CDMA // HSDPA {
3331int hsdpa_detect(void)
3332{
3333	int f;
3334	int ret=-1;
3335	extern int errno;
3336
3337	if((f=open("/dev/ttyACM0", O_WRONLY))!=-1)
3338	{
3339csprintf("--- hsdpa_detect: Detect as ACM! ---\n");
3340		close(f);
3341		ret=0;
3342	}
3343	else if((f=open("/dev/ttyUSB0", O_WRONLY))!=-1)
3344	{
3345csprintf("--- hsdpa_detect: Detect as USB! ---\n");
3346		close(f);
3347		ret=1;
3348	}
3349	else
3350	{
3351csprintf("--- hsdpa_detect: Detect as not HSDPA! ---\n");
3352	}
3353	return ret;
3354}
3355
3356int hotplug_hsdpa(char *product)
3357{
3358	char tmp[100];
3359	char vid[32];
3360	char pid[32];
3361	char *ptr1, *ptr2;
3362	int combo;
3363
3364	strcpy(tmp, product);
3365	ptr1=strchr(tmp, '/');
3366	*ptr1=0;
3367	sprintf(vid, "vendor=0x%s", tmp);
3368	ptr2=strchr(ptr1+1, '/');
3369	*ptr2=0;
3370	sprintf(pid, "product=0x%s", ptr1+1);
3371
3372	if (nvram_match("hsdpa_enable", "0")) return 0;
3373
3374	if (nvram_match("hsdpa_product", ""))
3375	{
3376		//logmessage("HSDPA detected", product);
3377
3378		eval("rmmod", "usbserial");
3379
3380		eval("mknod", "/dev/ttyACM0", "c", "166", "0");
3381		eval("mknod", "/dev/ttyACM1", "c", "166", "1");
3382		eval("mknod", "/dev/ttyUSB0", "c", "188", "0");
3383		eval("mknod", "/dev/ttyUSB1", "c", "188", "1");
3384		eval("mknod", "/dev/ttyUSB2", "c", "188", "2");
3385		eval("mknod", "/dev/ttyUSB3", "c", "188", "3");
3386
3387		eval("insmod", "usbserial.o", vid, pid);
3388		if(!strncmp(product, "1a8d/", 5)){
3389			logmessage("Add USB Modem", product);
3390
3391			nvram_set("hsdpa_product", product);
3392			nvram_set("hsdpa_combo", "1");
3393
3394			nvram_set("got_HSDPA", "1");
3395			nvram_set("hsdpa_ttyUSB_num", "1");
3396
3397			nvram_set("cdma_down", "1");
3398
3399			return 1;
3400		}
3401		else if(!strcmp(product, "805/480f/0")){
3402			logmessage("Add USB Modem", product);
3403
3404			nvram_set("hsdpa_product", product);
3405			nvram_set("hsdpa_combo", "1");
3406
3407			nvram_set("got_HSDPA", "1");
3408			nvram_set("hsdpa_ttyUSB_num", "3");
3409
3410			nvram_set("cdma_down", "1");
3411
3412			return 1;
3413		}
3414		else if(!strcmp(product, "12d1/1001/0")
3415					|| !strcmp(product, "12d1/1003/0")
3416					){
3417			logmessage("Add USB Modem", product);
3418
3419			nvram_set("hsdpa_product", product);
3420			nvram_set("hsdpa_combo", "1");
3421
3422			nvram_set("got_HSDPA", "1");
3423			nvram_set("hsdpa_ttyUSB_num", "0");
3424
3425			nvram_set("cdma_down", "1");
3426
3427			return 1;
3428		}
3429		else if((combo = hsdpa_detect()) != -1)
3430		{
3431			logmessage("Add USB Modem", product);
3432
3433			nvram_set("hsdpa_product", product);
3434			if(combo){
3435				nvram_set("hsdpa_combo", "1");
3436
3437				//nvram_set("got_HSDPA", "0");
3438				nvram_set("hsdpa_ttyUSB_num", "");
3439			}
3440			else
3441				nvram_set("hsdpa_combo", "0");
3442
3443			// start cdma
3444			nvram_set("cdma_down", "1");
3445
3446			return 1;
3447		}
3448		/*else{
3449			eval("rmmod", "usbserial");
3450csprintf("test 1: vid=%s, pid=%s. ---\n", vid, pid);
3451			nvram_set("hsdpa_combo", "-1");
3452		}//*/
3453	}
3454
3455	// skip other interface on the same device
3456	if(nvram_match("hsdpa_product", product)){
3457csprintf("--- hotplug_hsdpa: Found other interface of the HSDPA card! ---\n");
3458		return 1;
3459	}
3460
3461	return 0;
3462}
3463
3464int unplug_hsdpa(char *product)
3465{
3466	char tmp[100];
3467	char vid[32];
3468	char pid[32];
3469	char *ptr1, *ptr2;
3470
3471	strcpy(tmp, product);
3472	ptr1=strchr(tmp, '/');
3473	*ptr1=0;
3474	sprintf(vid, "vendor=0x%s", tmp);
3475	ptr2=strchr(ptr1+1, '/');
3476	*ptr2=0;
3477	sprintf(pid, "product=0x%s", ptr1+1);
3478
3479	//logmessage("Remove USB Device VID", vid);
3480	//logmessage("Remove USB Device PID", pid);
3481
3482	//if(interface)
3483	//	logmessage("Remove USB Device INTERFACE", interface);
3484
3485	if (nvram_match("hsdpa_enable", "0")) return 0;
3486
3487	if (nvram_match("hsdpa_product", product))
3488	{
3489		logmessage("Remove USB Modem", product);
3490
3491		nvram_set("hsdpa_product", "");
3492		nvram_set("hsdpa_combo", "-1");
3493
3494		// stop cdma
3495		nvram_set("cdma_down", "99");
3496		nvram_set("got_HSDPA", "0");
3497
3498		return 1;
3499	}
3500
3501	return 0;
3502}
3503#endif // CDMA // HSDPA }
3504
3505/* plugging or removing usb device */
3506/* usbcore, usb-ohci, usb-ehci, printer are always there */
3507/* usb-storage, sd_mod, scsi_mod, videodev are there if functions are enabled */
3508/* pwc, ov511 i2c, depends on current status */
3509int
3510hotplug_usb(void)
3511{
3512	char *action, *interface, *product, *usb_path;
3513// 2009.05 James. HSDPA {
3514	char *num_interfaces;
3515	int numOfInterfaces;
3516	int isPrinter;
3517// 2009.05 James. HSDPA }
3518	int isweb;
3519	char flag[6];
3520#ifdef U2EC
3521	int u2ec_fifo;
3522#endif // U2EC
3523	char usbpath_nvram[16];
3524	char temp_usbpath_device[16];
3525
3526	action = getenv("ACTION");
3527	interface = getenv("INTERFACE");
3528	product = getenv("PRODUCT");
3529	usb_path = getenv("USBDEVICE_PATH");
3530// 2009.05 James. HSDPA {
3531	num_interfaces = getenv("NUM_INTERFACES");
3532	num_interfaces = (num_interfaces == NULL || strlen(num_interfaces) <= 0)?"0":num_interfaces;
3533	numOfInterfaces = atoi(num_interfaces);
3534	isPrinter = atoi(getenv("ISPRINTER"));
3535// 2009.05 James. HSDPA }
3536
3537#ifdef CDMA // HSDPA {
3538	if( !action)
3539#else // CDMA
3540	if( !action || !interface)
3541#endif // CDMA // HSDPA }
3542	{
3543		return EINVAL;
3544	}
3545
3546	//nvram_set("usb_vidpid", product);
3547
3548	if(usb_path){
3549		nvram_set("usb_path", usb_path);
3550
3551		memset(usbpath_nvram, 0, 16);
3552		sprintf(usbpath_nvram, "usb_path%s", usb_path);
3553
3554		memset(temp_usbpath_device, 0, 16);
3555		strcpy(temp_usbpath_device, nvram_safe_get(usbpath_nvram));
3556	}
3557
3558	//if(product && strncmp(product, "0/", 2))
3559	if(product
3560// 2009.06 James. {
3561#ifdef WL500GPV2
3562			&& (!strcmp(usb_path, "1.1") || !strcmp(usb_path, "1.2"))
3563#elif WL520GU
3564			&& !strcmp(usb_path, "1")
3565#else
3566			&& strncmp(product, "0/", 2)
3567#endif
3568// 2009.06 James. }
3569			)
3570	{
3571		isweb = WEB_NONE;
3572
3573#ifdef CDMA // HSDPA {
3574		if(!interface)
3575			goto usbhandler;
3576#endif // CDMA // HSDPA }
3577
3578		if(!strncmp(interface, "8/", 2) && isPrinter != 1)
3579		{
3580			//logmessage("USB mass storage", "attached");
3581
3582			isweb = MASS_STORAGE;
3583			goto usbhandler;
3584		}
3585		else if(!strncmp(interface, "7/", 2)) //2008.03.13 Yau add printer log
3586		{
3587// 2008.05 James. {
3588			//logmessage("USB printer", "attached");
3589
3590			isweb = USB_PRINTER;
3591			goto usbhandler;
3592// 2008.05 James. }
3593		}
3594		else if(!strncmp(interface, "1/1", 3))
3595		{
3596			// if the audio device is the same with web cam,
3597			// just skip it
3598			if(nvram_match("usb_web_device", product))
3599				return 0;
3600
3601			isweb = WEB_AUDIO;
3602			goto usbhandler;
3603		}
3604		else if(!strncmp(interface, "1/", 2))
3605		{
3606			return 0;
3607		}
3608
3609		int i;
3610
3611		i = 0;
3612		while(PWCLIST[i] != NULL)
3613		{
3614			if(strstr(product, PWCLIST[i]))
3615			{
3616				isweb = WEB_PWCWEB;
3617				goto usbhandler;
3618			}
3619			++i;
3620		}
3621
3622		i = 0;
3623		while(OVLIST[i] != NULL)
3624		{
3625			if(strstr(product, OVLIST[i]))
3626			{
3627				isweb = WEB_OVWEB;
3628				goto usbhandler;
3629			}
3630			++i;
3631		}
3632	}
3633	else
3634		return EINVAL;
3635
3636usbhandler:
3637csprintf("- hotplug(%d): action=%s, interface=%s, product=%s, usb_path=%s, isPrinter=%d. -\n"
3638		, isweb
3639		, action
3640		, interface
3641		, product
3642		, usb_path
3643		, isPrinter
3644		);
3645	if (strstr(action, "add"))
3646	{
3647logmessage("Add device", "interface=%s, product=%s, usb_path=%s, isPrinter=%d, numOfInterfaces=%d."
3648		, interface
3649		, product
3650		, usb_path
3651		, isPrinter
3652		, numOfInterfaces
3653		);
3654		if(isweb == MASS_STORAGE)
3655		{
3656#ifdef CDMA // HSDPA
3657			if((numOfInterfaces == 1 || numOfInterfaces == 2)
3658					&& (!strcmp(product, "12d1/1001/0")
3659							|| !strcmp(product, "12d1/1003/0"))
3660					){
3661logmessage("Remove module", "ehci-hcd.");
3662				eval("rmmod", "ehci-hcd");
3663logmessage("insert module", "ehci-hcd.");
3664				eval("insmod", "ehci-hcd");
3665				return 0;
3666			}
3667			else
3668#endif // HSDPA
3669			if(usb_path && strlen(temp_usbpath_device) <= 0){
3670				nvram_set("asus_mfg_flash", "1");
3671
3672// 2008.06 James. {
3673				if(strlen(nvram_safe_get("usb_disc0_pid")) <= 0){
3674					nvram_set("usb_disc0_pid", product);
3675					nvram_set("usb_disc0_port", usb_path);
3676				}
3677				else if(strlen(nvram_safe_get("usb_disc1_pid")) <= 0){
3678					nvram_set("usb_disc1_pid", product);
3679					nvram_set("usb_disc1_port", usb_path);
3680				}
3681// 2008.06 James. }
3682
3683				nvram_set("usb_storage_device", product); //watchdog will call hotplug_usb_mass if set
3684				nvram_set(usbpath_nvram, "storage");
3685				logmessage("USB storage", "\"%s\" was plugged in.", product);	// 2008.02 James.
3686			}
3687		}
3688// 2008.05 James. {
3689		else if(isweb == USB_PRINTER)
3690		{
3691			nvram_set("asus_mfg_printer", "1");
3692
3693			if(nvram_match("usb_printer_device", ""))
3694				logmessage("USB printer", "\"%s\" was plugged in.", product);
3695			nvram_set("usb_printer_device", product);
3696			if(usb_path){
3697				nvram_set(usbpath_nvram, "printer");
3698				nvram_set("usb_path_printer", usb_path);
3699			}
3700		}
3701// 2008.05 James. }
3702		else if(isweb == WEB_AUDIO)
3703		{
3704#ifdef AUDIO_SUPPORT
3705			nvram_set("asus_mfg_audio", "1");
3706
3707			if (nvram_match("usb_audio_device", ""))
3708				logmessage("USB audio", "attached");
3709			nvram_set("usb_audio_device", product);
3710			if(usb_path){
3711				nvram_set(usbpath_nvram, "audio");
3712				nvram_set("usb_path_audio", usb_path);
3713			}
3714			refresh_wave();
3715#else
3716			;
3717#endif // AUDIO_SUPPORT
3718		}
3719		else if(isweb == WEB_PWCWEB || isweb == WEB_OVWEB)
3720		{
3721#ifdef WEBCAM_SUPPORT
3722			nvram_set("asus_mfg_webcam", "1");
3723
3724			if (nvram_match("usb_web_device", ""))
3725				logmessage("USB webcam", "attached");
3726
3727			sprintf(flag, "%d", isweb);
3728			nvram_set("usb_web_device", product);
3729			nvram_set("usb_web_flag", flag);
3730			nvram_set("usb_webdriver_x", "");
3731			if(usb_path){
3732				nvram_set(usbpath_nvram, "webcam");
3733				nvram_set("usb_path_webcam", usb_path);
3734			}
3735#else
3736			;
3737#endif // WEBCAM_SUPPORT
3738		}
3739		//else{
3740		else if(isPrinter != 1
3741				&& (strlen(temp_usbpath_device) <= 0
3742						|| !strcmp(temp_usbpath_device, "storage"))
3743				//&& !strcmp(nvram_safe_get("hsdpa_product"), "")
3744				&& strcmp(product, "0/0/0")
3745				){
3746#ifdef CDMA // HSDPA {
3747			if(hotplug_hsdpa(product)){
3748				nvram_set("usb_hsdpa_device", product);
3749				if(usb_path){
3750					nvram_set(usbpath_nvram, "HSDPA");
3751					nvram_set("usb_path_hsdpa", usb_path);
3752				}
3753
3754				//return 0;
3755			}
3756#else
3757			;
3758#endif // HSDPA }
3759		}
3760
3761#ifdef U2EC
3762		u2ec_fifo = open("/tmp/u2ec_fifo", O_WRONLY|O_NONBLOCK);
3763		write(u2ec_fifo, "a", 1);
3764		close(u2ec_fifo);
3765#endif // U2EC
3766	}
3767	else //USB device removed
3768	{
3769logmessage("Remove device", "interface=%s, product=%s, usb_path=%s, isPrinter=%d."
3770		, interface
3771		, product
3772		, usb_path
3773		, isPrinter
3774		);
3775		if(isweb == MASS_STORAGE	// 2008.02 James.
3776				&& numOfInterfaces == 1 // 2009.05 James. HSDPA
3777				&& !strcmp(temp_usbpath_device, "storage")
3778				)
3779		{
3780// 2009.05 James. {
3781#ifdef CDMA // HSDPA {
3782			if(!strncmp(product, "1a8d/", 5)
3783					|| !strncmp(product, "12d1/", 5)
3784					)
3785				;
3786			else{
3787#endif // HSDPA }
3788// 2009.05 James. }
3789
3790			logmessage("USB device", "\"%s\" was removed.", product);	// 2008.02 James.
3791
3792// 2008.06 James. {
3793			if(!strcmp(nvram_safe_get("usb_disc0_pid"), product)
3794					&& !strcmp(nvram_safe_get("usb_disc0_safely_removed"), "1")
3795					&& strlen(nvram_safe_get("usb_disc1_pid")) <= 0){
3796				nvram_set("usb_disc0_pid", "");
3797				nvram_set("usb_disc0_safely_removed", "0");
3798
3799				//return 0;
3800			}
3801			else if(!strcmp(nvram_safe_get("usb_disc1_pid"), product)
3802					&& !strcmp(nvram_safe_get("usb_disc1_safely_removed"), "1")
3803					&& strlen(nvram_safe_get("usb_disc0_pid")) <= 0){
3804				nvram_set("usb_disc1_pid", "");
3805				nvram_set("usb_disc1_safely_removed", "0");
3806
3807				//return 0;
3808			}
3809// 2008.06 James. }
3810
3811// 2007.12 James {
3812			//remove_usb_mass(product);
3813			nvram_set("usb_storage_device_remove", product);
3814// 2007.12 James }
3815
3816// 2009.05 James. {
3817#ifdef CDMA // HSDPA {
3818			}
3819#endif // HSDPA }
3820// 2009.05 James. }
3821		}
3822		else if(isweb == USB_PRINTER)
3823		{
3824			logmessage("USB printer", "\"%s\" was removed.", product);
3825
3826			nvram_set("usb_printer_device", "");
3827			nvram_set("usb_path_printer", "");
3828		}
3829		else if(isweb == WEB_AUDIO)
3830		{
3831#ifdef AUDIO_SUPPORT
3832			logmessage("USB audio", "\"%s\" was removed.", product);
3833
3834			remove_usb_audio(product);
3835			nvram_set("usb_audio_device", "");
3836			nvram_set("usb_path_audio", "");
3837#else
3838			;
3839#endif // AUDIO_SUPPORT
3840		}
3841		else if(isweb == WEB_PWCWEB || isweb == WEB_OVWEB)
3842		{
3843#ifdef WEBCAM_SUPPORT
3844			if (nvram_invmatch("usb_web_device", ""))
3845			{
3846				logmessage("USB webcam", "\"%s\" was removed.", product);
3847
3848				remove_usb_webcam(product, isweb);
3849				nvram_set("usb_web_device", "");
3850				nvram_set("usb_web_flag", "");
3851				nvram_set("usb_path_webcam", "");
3852			}
3853#else
3854			;
3855#endif // WEBCAM_SUPPORT
3856		}
3857		//else{
3858		else if(!strcmp(temp_usbpath_device, "HSDPA")){
3859#ifdef CDMA // HSDPA {
3860			if(unplug_hsdpa(product)){
3861				nvram_set("usb_hsdpa_device", "");
3862				nvram_set("usb_path_hsdpa", "");
3863
3864				//return 0;
3865			}
3866#else
3867			;
3868#endif // HSDPA }
3869		}
3870
3871#ifdef U2EC
3872		u2ec_fifo = open("/tmp/u2ec_fifo", O_WRONLY|O_NONBLOCK);
3873		write(u2ec_fifo, "r", 1);
3874		close(u2ec_fifo);
3875#endif // U2EC
3876
3877		if(usb_path)
3878			nvram_set(usbpath_nvram, "");
3879	}
3880
3881	return 0;
3882}
3883#endif // USB_SUPPORT
3884
3885/* stop necessary services for firmware upgrade */
3886/* stopservice: for firmware upgarde */
3887/* stopservice 1: for button setup   */
3888int
3889stop_service_main(int type)
3890{
3891	if (type==1)
3892	{
3893		//stop_misc();
3894		//stop_logger();
3895		stop_usb();
3896		stop_nas();
3897		stop_upnp();
3898		//stop_dhcpd();
3899		stop_dns();
3900		stop_httpd();
3901		eval("killall", "udhcpc");
3902		//eval("killall", "infosvr");
3903	}
3904	else
3905	{
3906		if(type==99) stop_misc_no_watchdog();
3907		else stop_misc();
3908		stop_logger();
3909		stop_usb();
3910
3911		//stop_nas();	// mark this for upgrade firmware with wireless.
3912		stop_upnp();
3913		stop_dhcpd();
3914		stop_dns();
3915	}
3916
3917	dprintf("done\n");
3918	return 0;
3919}
3920
3921int service_handle(void)
3922{
3923	char *service;
3924	char tmp[100], *str;
3925	int pid;
3926	char *ping_argv[] = { "ping", "140.113.1.1", NULL};
3927	FILE *fp;
3928
3929	service = nvram_get("rc_service");
3930
3931	if(!service)
3932		kill(1, SIGHUP);
3933
3934	if(strstr(service,"wan_disconnect")!=NULL)
3935	{
3936		cprintf("wan disconnect\n");
3937
3938		logmessage("WAN Connection", "Disconnected manually");
3939
3940#ifdef CDMA // HSDPA test
3941		if(nvram_invmatch("hsdpa_product", "") && nvram_invmatch("hsdpa_combo", "-1")){
3942printf("--- HSDPA test: disconnect! ---\n");
3943			nvram_set("cdma_down", "3");
3944		}
3945		else
3946#endif // CDMA*/
3947		if (nvram_match("wan0_proto", "dhcp")
3948#ifdef BIGPOND
3949				|| nvram_match("wan0_proto", "bigpond")
3950#endif // BIGPOND
3951/*#ifdef CDMA // HSDPA test
3952				//|| nvram_match("wan0_proto_t", "cdma")
3953				|| nvram_invmatch("hsdpa_combo", "-1")
3954#endif // CDMA*/
3955			)
3956		{
3957			snprintf(tmp, sizeof(tmp), "/var/run/udhcpc%d.pid", 0);
3958			if ((str = file2str(tmp))) {
3959				pid = atoi(str);
3960				free(str);
3961				kill(pid, SIGUSR2);
3962			}
3963		}
3964		else
3965		{
3966			stop_wan2();
3967			update_wan_status(0);
3968			sleep(3);
3969		}
3970	}
3971	else if (strstr(service,"wan_connect")!=NULL)
3972	{
3973		cprintf("wan connect\n");
3974		logmessage("WAN Connection", "Connected manually");
3975		setup_ethernet(nvram_safe_get("wan_ifname"));
3976
3977#ifdef CDMA // HSDPA test
3978		if(nvram_invmatch("hsdpa_product", "") && nvram_invmatch("hsdpa_combo", "-1")){
3979printf("--- HSDPA test: connect! ---\n");
3980			nvram_set("cdma_down", "1");
3981		}
3982		else
3983#endif // CDMA*/
3984		if (nvram_match("wan0_proto", "dhcp")
3985#ifdef BIGPOND
3986				|| nvram_match("wan0_proto", "bigpond")
3987#endif // BIGPOND
3988/*#ifdef CDMA // HSDPA test
3989				//|| nvram_match("wan0_proto_t", "cdma")
3990				|| nvram_invmatch("hsdpa_combo", "-1")
3991#endif // CDMA*/
3992			)
3993		{
3994			snprintf(tmp, sizeof(tmp), "/var/run/udhcpc%d.pid", 0);
3995			if ((str = file2str(tmp))) {
3996				pid = atoi(str);
3997				free(str);
3998				kill(pid, SIGUSR1);
3999			}
4000		}
4001		else
4002		{
4003#ifndef REMOVE
4004			// pppoe or ppptp, check if /tmp/ppp exist
4005			if (nvram_invmatch("wan0_proto", "static") && (fp=fopen("/tmp/ppp/ip-up", "r"))!=NULL)
4006			{
4007				fclose(fp);
4008				_eval(ping_argv, NULL, 0, &pid);
4009			}
4010			else
4011			{
4012				stop_wan();
4013				sleep(3);
4014				start_wan();
4015				sleep(2);
4016				_eval(ping_argv, NULL, 0, &pid);
4017			}
4018#else // REMOVE
4019			stop_wan();
4020			sleep(2);
4021			start_wan();
4022			/* trigger connect */
4023			eval("ntpclient", "-h", "test", "-c", "1");
4024#endif // REMOVE
4025
4026		}
4027	}
4028#ifdef ASUS_DDNS //2007.03.26 Yau add for asus ddns
4029	else if(strstr(service,"ddns_hostname_check") != NULL)
4030	{
4031		char host[64];
4032		char wan_ifname[16];
4033
4034		strcpy(host, nvram_get("ddns_hostname_x"));
4035#ifdef CDMA // HSDPA
4036		if(strcmp(nvram_safe_get("hsdpa_product"), "") != 0)
4037			strcpy(wan_ifname, "ppp0");
4038		else
4039#endif
4040		if(nvram_match("wan_proto", "pppoe") || nvram_match("wan_proto", "pptp") || nvram_match("wan_proto", "l2tp"))
4041			strcpy(wan_ifname, nvram_get("wan0_pppoe_ifname"));
4042		else
4043			strcpy(wan_ifname, nvram_get("wan0_ifname"));
4044
4045		char *ddns_argv[] = {"ez-ipupdate",
4046												 "-h", host,
4047												 "-s", "ns1.asuscomm.com",
4048												 "-S", "dyndns",
4049												 "-i", wan_ifname,
4050												 "-A", "1",
4051												 NULL};
4052		pid_t pid;
4053
4054		//Execute ez-ipupdate then die.
4055		eval("killall", "ez-ipupdate");
4056		_eval(ddns_argv, NULL, 0, &pid);
4057	}
4058#endif // ASUS_DDNS
4059
4060	nvram_unset("rc_service");
4061	return 0;
4062}
4063
4064#ifdef AUDIO_SUPPORT
4065int hotplug_usb_audio(char *product)
4066{
4067	char *wave_argv[]={"waveserver", NULL};
4068	pid_t pid;
4069
4070	if (strlen(product)==0) return;
4071	return _eval(wave_argv, ">/dev/null", 0, NULL);	// 2007.11 James. add "return"
4072}
4073
4074int remove_usb_audio(char *product)
4075{
4076	return eval("killall", "waveserver");	// 2007.11 James. add "return"
4077}
4078
4079int
4080start_audio(void)
4081{
4082	char *wave_argv[] = {"waveservermain", NULL};
4083	pid_t pid;
4084
4085	_eval(wave_argv, NULL, 0, &pid);
4086	return 0;
4087}
4088
4089int
4090stop_audio(void)
4091{
4092	int ret = eval("killall", "waveserver");
4093	return ret;	// 2007.11 James.
4094}
4095#endif // AUDIO_SUPPORT
4096
4097#ifdef GUEST_ACCOUNT
4098int
4099start_dhcpd_guest(void)
4100{
4101	FILE *fp;
4102	char *dhcpd_argv[] = {"udhcpd", "/tmp/udhcpd1.conf", NULL, NULL};
4103	char *slease = "/tmp/udhcpd-br1.sleases";
4104	pid_t pid;
4105
4106	if (nvram_match("router_disable", "1") || nvram_invmatch("wl_guest_enable", "1") || nvram_invmatch("lan1_proto", "dhcp"))
4107		return 0;
4108
4109	dprintf("%s %s %s %s\n",
4110		nvram_safe_get("lan1_ifname"),
4111		nvram_safe_get("dhcp1_start"),
4112		nvram_safe_get("dhcp1_end"),
4113		nvram_safe_get("lan1_lease"));
4114
4115	if (!(fp = fopen("/tmp/udhcpd-br1.leases", "a"))) {
4116		perror("/tmp/udhcpd-br1.leases");
4117		return errno;
4118	}
4119	fclose(fp);
4120
4121	/* Write configuration file based on current information */
4122	if (!(fp = fopen("/tmp/udhcpd1.conf", "w"))) {
4123		perror("/tmp/udhcpd1.conf");
4124		return errno;
4125	}
4126
4127	fprintf(fp, "pidfile /var/run/udhcpd-br1.pid\n");
4128	fprintf(fp, "start %s\n", nvram_safe_get("dhcp1_start"));
4129	fprintf(fp, "end %s\n", nvram_safe_get("dhcp1_end"));
4130	fprintf(fp, "interface %s\n", nvram_safe_get("lan1_ifname"));
4131	fprintf(fp, "remaining yes\n");
4132	fprintf(fp, "lease_file /tmp/udhcpd-br1.leases\n");
4133	fprintf(fp, "option subnet %s\n", nvram_safe_get("lan1_netmask"));
4134	fprintf(fp, "option router %s\n", nvram_safe_get("lan1_ipaddr"));
4135
4136	if (nvram_invmatch("dhcp_dns1_x",""))
4137		fprintf(fp, "option dns %s\n", nvram_safe_get("dhcp_dns1_x"));
4138	fprintf(fp, "option dns %s\n", nvram_safe_get("lan1_ipaddr"));
4139	fprintf(fp, "option lease %s\n", nvram_safe_get("lan1_lease"));
4140
4141	if (nvram_invmatch("dhcp_wins_x",""))
4142		fprintf(fp, "option wins %s\n", nvram_safe_get("dhcp_wins_x"));
4143	if (nvram_invmatch("lan_domain", ""))
4144		fprintf(fp, "option domain %s\n", nvram_safe_get("lan_domain"));
4145	fclose(fp);
4146
4147	dhcpd_argv[2] = NULL;
4148	_eval(dhcpd_argv, NULL, 0, &pid);
4149
4150
4151	dprintf("done\n");
4152	return 0;
4153}
4154
4155int
4156stop_dhcpd_guest(void)
4157{
4158	char sigusr1[] = "-XX";
4159	int ret;
4160
4161/*
4162* Process udhcpd handles two signals - SIGTERM and SIGUSR1
4163*
4164*  - SIGUSR1 saves all leases in /tmp/udhcpd.leases
4165*  - SIGTERM causes the process to be killed
4166*
4167* The SIGUSR1+SIGTERM behavior is what we like so that all current client
4168* leases will be honorred when the dhcpd restarts and all clients can extend
4169* their leases and continue their current IP addresses. Otherwise clients
4170* would get NAK'd when they try to extend/rebind their leases and they
4171* would have to release current IP and to request a new one which causes
4172* a no-IP gap in between.
4173*/
4174	ret = eval("killall", "udhcpd");
4175
4176	dprintf("done\n");
4177	return ret;
4178}
4179#endif // GUEST_ACCOUNT
4180
4181#ifdef DLM
4182// 2007.11 James. replace this with using eval("/sbin/write_smb_conf") for new samba mode.
4183void write_smb_conf()
4184{
4185	struct dirent *dp;
4186	FILE *fp;
4187	DIR *dir_to_open=NULL;
4188	int n=0, sh_num=0;
4189	char *tmp1=NULL;
4190	char SHMAX[32];
4191	char SMB_SHNAME[64];
4192	char SHNM[16];
4193	char SMB_SHCOMMENT[64];
4194	char SHCM[16];
4195	char SMB_SHPATH[104];
4196	char SHPH[32];
4197	char SHAU[16];
4198	char SMB_SHRRIGHT[384];
4199	char SHRR[384];
4200	char SMB_SHWRIGHT[384];
4201	char SHWR[384];
4202	char SMB_SHACCUSER[384];
4203
4204// write smb.conf
4205	if((fp=fopen("/tmp/samba/lib/smb.conf", "r")))
4206	{
4207		fclose(fp);
4208		//eval("rm", "-f", "/tmp/samba/lib/smb.conf");
4209		unlink("/tmp/samba/lib/smb.conf");	// 2008.08 James.
4210	}
4211	fp = fopen("/tmp/samba/lib/smb.conf", "w");
4212	fprintf(fp, "[global]\n");
4213	if(nvram_safe_get("st_samba_workgroup"))
4214		fprintf(fp, "workgroup = %s\n", nvram_safe_get("st_samba_workgroup"));
4215	if(nvram_safe_get("computer_name"))
4216		fprintf(fp, "netbios name = %s\n", nvram_safe_get("computer_name"));
4217	fprintf(fp, "server string = WL500g.Premium version 2\n");
4218	eval("mkdir", "-p", "/tmp/var/log/samba");
4219	fprintf(fp, "log file = /tmp/var/log/samba/samba.log\n");
4220	fprintf(fp, "log level = 0\n");
4221	fprintf(fp, "max log size = 5\n");
4222
4223// share mode
4224	if(!strcmp(nvram_safe_get("st_samba_modex"), "1"))
4225	{
4226		fprintf(fp, "security = SHARE\n");
4227		fprintf(fp, "guest ok = yes\n");
4228		fprintf(fp, "guest only = yes\n");
4229	}
4230	else
4231	{
4232		fprintf(fp, "security = USER\n");
4233		fprintf(fp, "guest ok = no\n");
4234		fprintf(fp, "map to guest = Bad User\n");
4235	}
4236	fprintf(fp, "writeable = yes\n");
4237	fprintf(fp, "directory mode = 0777\n");
4238	fprintf(fp, "create mask = 0777\n");
4239// max users
4240	sprintf(SHMAX, "st_max_user");
4241	if(strcmp(nvram_safe_get(SHMAX), "")!=0)
4242		fprintf(fp, "max connections = %s\n", nvram_safe_get(SHMAX));
4243	fprintf(fp, "encrypt passwords = yes\n");
4244	fprintf(fp, "pam password change = no\n");
4245	fprintf(fp, "obey pam restrictions = no\n");
4246	fprintf(fp, "socket options = TCP_NODELAY SO_KEEPALIVE SO_RCVBUF=16384 SO_SNDBUF=16384\n");
4247	fprintf(fp, "dns proxy = no\n");
4248// share
4249	if(!strcmp(nvram_safe_get("st_samba_modex"), "0") || !strcmp(nvram_safe_get("st_samba_modex"), ""))
4250	{
4251		;
4252	}
4253	else if(!strcmp(nvram_safe_get("st_samba_modex"), "1"))
4254	{
4255		printf("samba mode: share\n");
4256		if(!(dir_to_open = opendir("/tmp/harddisk")))
4257		{
4258			perror("***cannot open /tmp/harddisk\n");
4259			goto confpage;
4260		}
4261		n = 0;
4262		if(dir_to_open)
4263		{
4264			while(dp=readdir(dir_to_open))
4265			{
4266				if(strncmp(dp->d_name, "..", NAME_MAX) != 0 && strncmp(dp->d_name, ".", NAME_MAX) != 0 )
4267				{
4268					sprintf(SMB_SHNAME, "%s", dp->d_name);
4269					sprintf(SMB_SHCOMMENT, "%s", dp->d_name);
4270					sprintf(SMB_SHPATH, "/tmp/harddisk/%s", dp->d_name);
4271					printf("%s\n", SMB_SHPATH);
4272					fprintf(fp, "[%s]\n", SMB_SHNAME);
4273					fprintf(fp, "comment = %s\n", SMB_SHCOMMENT);
4274					fprintf(fp, "path = %s\n", SMB_SHPATH);
4275					fprintf(fp, "guest ok = yes\n");
4276					fprintf(fp, "writeable = yes\n");
4277					fprintf(fp, "directory mode = 0777\n");
4278					fprintf(fp, "create mask = 0777\n");
4279				}
4280			}
4281		}
4282		if(dir_to_open)
4283			closedir(dir_to_open);
4284	}
4285	else // st_samba_mode = 2
4286	{
4287	printf("samba mode: user\n");
4288	n = 0;
4289	sh_num = atoi(nvram_safe_get("sh_num"));
4290	while(n<sh_num)
4291	{
4292		sprintf(SHPH, "sh_path%d", n);
4293		sprintf(SHNM, "sh_name%d", n);
4294		sprintf(SHRR, "sh_rright%d", n);
4295		sprintf(SHWR, "sh_wright%d", n);
4296		sprintf(SHCM, "sh_comment%d", n);
4297		sprintf(SHAU, "sh_acc_user%d", n);
4298		sprintf(SMB_SHPATH, "/tmp/harddisk%s", nvram_safe_get(SHPH));
4299		sprintf(SMB_SHNAME, "%s", nvram_safe_get(SHNM));
4300		sprintf(SMB_SHRRIGHT, "%s", nvram_safe_get(SHRR));
4301		sprintf(SMB_SHWRIGHT, "%s", nvram_safe_get(SHWR));
4302		sprintf(SMB_SHACCUSER, "%s", nvram_safe_get(SHAU));
4303
4304		while(tmp1=strchr(SMB_SHRRIGHT, ';'))
4305			memcpy(tmp1, " ", 1);
4306		memcpy(SMB_SHRRIGHT+strlen(SMB_SHRRIGHT)-1, "\0", 1);
4307		while(tmp1=strchr(SMB_SHWRIGHT, ';'))
4308			memcpy(tmp1, " ", 1);
4309		memcpy(SMB_SHWRIGHT+strlen(SMB_SHWRIGHT)-1, "\0", 1);
4310		while(tmp1=strchr(SMB_SHACCUSER, ';'))
4311			memcpy(tmp1, " ", 1);
4312		memcpy(SMB_SHACCUSER+strlen(SMB_SHACCUSER)-1, "\0", 1);
4313		sprintf(SMB_SHCOMMENT, "%s", nvram_safe_get(SHCM));
4314		// write to conf
4315		if(!strcmp(SMB_SHNAME, ""))
4316		{
4317			goto endloop;
4318		}
4319		if(!(dir_to_open = opendir(SMB_SHPATH)))
4320		{
4321			goto endloop;
4322		}
4323		else
4324			closedir(dir_to_open);
4325		fprintf(fp, "[%s]\n", SMB_SHNAME);
4326		fprintf(fp, "comment = %s\n", SMB_SHCOMMENT);
4327		fprintf(fp, "path = %s\n", SMB_SHPATH);
4328		if(strstr(SMB_SHWRIGHT, "Guest"))
4329		{
4330				fprintf(fp, "guest ok = yes\n");
4331		}
4332		else
4333		{
4334			if(strstr(SMB_SHRRIGHT, "Guest"))
4335			{
4336				fprintf(fp, "guest ok = yes\n");
4337				fprintf(fp, "writeable = no\n");
4338				fprintf(fp, "write list = %s\n", SMB_SHWRIGHT);
4339			}
4340			else
4341			{
4342				if(!strcmp(SMB_SHWRIGHT, "")&&!strcmp(SMB_SHRRIGHT, ""))
4343					fprintf(fp, "valid users = _an_si_un_se_shorti_\n");
4344				else
4345					fprintf(fp, "valid users = %s\n", SMB_SHACCUSER);
4346				fprintf(fp, "writeable = no\n");
4347				fprintf(fp, "write list = %s\n", SMB_SHWRIGHT);
4348				fprintf(fp, "read list = %s\n", SMB_SHRRIGHT);
4349			}
4350		}
4351		fprintf(fp, "directory mode = 0777\n");
4352		fprintf(fp, "create mask = 0777\n");
4353		// write to conf
4354endloop:
4355		n++;
4356	}
4357	}// st_samba_mode = 2
4358confpage:
4359	fclose(fp);
4360}
4361
4362int
4363start_samba(void)	// added by Jiahao for WL500gP
4364{
4365	FILE *fp;
4366	int n=0, sh_num=0, i;
4367	char *tmp1=NULL, *tmp2=NULL;
4368	int ret1=0, ret2=0;
4369
4370	stop_samba(); // 2007.11 James. for new samba mode
4371
4372/* write samba configure file*/
4373	//write_smb_conf();
4374	eval("/sbin/write_smb_conf");	// 2007.11 James. for new samba mode
4375
4376/* write /etc/passwd */
4377	if((fp=fopen("/tmp/passwd", "r")))
4378	{
4379		fclose(fp);
4380		//eval("rm", "-f", "/tmp/passwd");
4381		unlink("/tmp/passwd");	// 2008.08 James.
4382	}
4383	fp = fopen("/tmp/passwd", "w");
4384	fprintf(fp, "nobody:x:99:99:::\n");
4385	sh_num = atoi(nvram_safe_get("acc_num"));
4386	tmp1 = (char *)malloc(33);
4387	for(i=0, n=500; i<sh_num; i++, n++)
4388	{
4389		sprintf(tmp1, "acc_username%d", i);
4390		fprintf(fp, "%s:x:%d:%d:::\n", nvram_safe_get(tmp1), n, n);
4391	}
4392	if (tmp1) free(tmp1);
4393	fclose(fp);
4394/* write /etc/group  */
4395	if((fp=fopen("/tmp/group", "r")))
4396	{
4397		fclose(fp);
4398		//eval("rm", "-f", "/tmp/group");
4399		unlink("/tmp/group");	// 2008.08 James.
4400	}
4401	fp = fopen("/tmp/group", "w");
4402	fprintf(fp, "nobody:x:99:\n");
4403	sh_num = atoi(nvram_safe_get("acc_num"));
4404	tmp1 = (char *)malloc(33);
4405	for(i=0, n=500; i<sh_num; i++, n++)
4406	{
4407		sprintf(tmp1, "acc_username%d", i);
4408		fprintf(fp, "%s:x:%d:\n", nvram_safe_get(tmp1), n);
4409	}
4410	if (tmp1) free(tmp1);
4411	fclose(fp);
4412/* write smbpasswd  */
4413	eval("/usr/local/samba/bin/smbpasswd", "-a", "nobody", "\"\"");
4414	sh_num = atoi(nvram_safe_get("acc_num"));
4415	tmp1 = (char *)malloc(33);
4416	tmp2 = (char *)malloc(33);
4417	for(i=0; i<sh_num; i++)
4418	{
4419		sprintf(tmp1, "acc_username%d", i);
4420		sprintf(tmp2, "acc_password%d", i);
4421		sprintf(tmp1, nvram_safe_get(tmp1));
4422		sprintf(tmp2, nvram_safe_get(tmp2));
4423		eval("/usr/local/samba/bin/smbpasswd", "-a", tmp1, tmp2);
4424	}
4425	if (tmp1) free(tmp1);
4426	if (tmp2) free(tmp2);
4427
4428	ret1 = eval("/usr/local/samba/sbin/smbd", "-D", "-s", "/tmp/samba/lib/smb.conf");
4429	ret2 = eval("/usr/local/samba/sbin/nmbd", "-D", "-s", "/tmp/samba/lib/smb.conf");
4430
4431	if(!ret1 && !ret2)
4432	{
4433		//if (nvram_match("st_samba_modex", "1"))
4434		if(nvram_match("st_samba_mode", "1") || nvram_match("st_samba_mode", "3"))	// 2007.11 James.
4435			nvram_set("st_samba_mode_x", "1");
4436		else
4437			nvram_set("st_samba_mode_x", "0");
4438
4439		fprintf(stderr, "Starting samba\n");
4440		logmessage("Samba Server", "daemon is started");
4441		return 0;
4442
4443	}
4444	else
4445	{
4446		eval("killall", "-SIGKILL", "smbd");
4447		eval("killall", "-SIGKILL", "nmbd");
4448		nvram_set("st_samba_mode_x", "0");	// 2007.11 James.
4449		return 1;
4450	}
4451}
4452#endif // DLM
4453
4454int
4455check_disk_free(char *res, char *diskpath)	// added by Jiahao for WL500gP
4456{
4457	char *sizebuf, *freebuf, *databuf;
4458	struct statfs fsbuf;
4459
4460	if(statfs(diskpath, &fsbuf))
4461	{
4462		perror("*** check_disk_free: statfs fail!");
4463		return 2;
4464	}
4465
4466	sizebuf = malloc(32);
4467	freebuf = malloc(32);
4468	databuf = malloc(64);
4469
4470	sprintf(sizebuf, "%.1f", (double)((double)((double)fsbuf.f_blocks * fsbuf.f_bsize)/(1024*1024)));
4471	sprintf(freebuf, "%.1f", (double)((double)((double)fsbuf.f_bfree * fsbuf.f_bsize)/(1024*1024)));
4472	sprintf(res, "size: %s, free: %s", sizebuf, freebuf);
4473
4474	if(sizebuf)
4475		free(sizebuf);
4476	if(freebuf)
4477		free(freebuf);
4478	if(databuf)
4479		free(databuf);
4480	if(fsbuf.f_bfree == 0)
4481		return 0;
4482	else
4483		return 1;
4484}
4485
4486#ifdef DLM
4487int
4488check_disk_free_GE_1G(char *diskpath)	// added by Jiahao for WL500gP
4489{
4490	struct statfs fsbuf;
4491
4492	if(statfs(diskpath, &fsbuf))
4493	{
4494		perror("*** check_disk_free_GE_1G: statfs fail!");
4495		return 0;
4496	}
4497
4498	if ( (double)((double)((double)fsbuf.f_bfree * fsbuf.f_bsize)/(1024*1024)) < (double)33 )
4499		return 1;
4500	else if ( (double)((double)((double)fsbuf.f_blocks * fsbuf.f_bsize)/(1024*1024)) > (double)512 )
4501		return 2;
4502	else
4503		return 3;
4504}
4505
4506int
4507check_disk_free_apps(char *diskpath, int ac_flag)			// added by Jiahao for WL500gP
4508{
4509	struct statfs fsbuf;
4510
4511	if(statfs(diskpath, &fsbuf))
4512	{
4513		perror("*** check_disk_free_apps: statfs fail!");
4514		return 0;
4515	}
4516
4517	if (ac_flag==1)
4518	{
4519		if (nvram_match("apps_dlx", "0"))
4520			return 1;
4521
4522		if ( (double)((double)((double)fsbuf.f_bfree * fsbuf.f_bsize)/(1024*1024)) < (double)1 )
4523			return 0;
4524		else
4525			return 1;
4526	}
4527	else
4528	{
4529		if ( (double)((double)((double)fsbuf.f_bfree * fsbuf.f_bsize)/(1024*1024)) < (double)5 )
4530			return 0;
4531		else
4532			return 1;
4533	}
4534}
4535#endif // DLM
4536
4537void
4538get_disc_desc(char * vendor_product, int discorder, int discindex) {	// added by Jiahao for WL500gP
4539	FILE* fp;
4540	DIR *dir_to_open, *dir_to_open2;
4541	struct dirent *dp, *dp2;
4542	char str_path[128];
4543	char temp[80];
4544	char temp2[80];
4545	char temp3[32];
4546	char temp4[64];
4547	char temp5[64];
4548	char port[128];
4549	char tempstr[1];
4550	char host[128];
4551	char *p, *p2;
4552
4553	strcpy(vendor_product, "");
4554
4555	if( dir_to_open = opendir("/proc/scsi") )
4556	{
4557		while(dp=readdir(dir_to_open))
4558		{
4559			if(	!strncmp(dp->d_name, "..", NAME_MAX)	||
4560		           	!strncmp(dp->d_name, ".", NAME_MAX)	||
4561		           	!strncmp(dp->d_name, "sg", NAME_MAX)	||
4562		          	!strncmp(dp->d_name, "scsi", NAME_MAX)	)
4563				continue;
4564			sprintf(str_path, "/proc/scsi/%s", dp->d_name);
4565			if (dir_to_open2 = opendir(str_path))
4566			{
4567				while(dp2=readdir(dir_to_open2))
4568				{
4569					if(	!strncmp(dp2->d_name, "..", NAME_MAX)	||
4570		           			!strncmp(dp2->d_name, ".", NAME_MAX)	)
4571						continue;
4572					sprintf(temp3, "/dev/discs/disc%d", discorder);
4573					sprintf(temp5, "../scsi/host%s/bus0/target0/lun0", dp2->d_name);
4574					readlink(temp3, temp4, 64);
4575					if (strncmp(temp5, temp4, 13)!=0)
4576						break;
4577					else
4578					{
4579						if (fp=fopen("/proc/scsi/scsi", "r"))
4580						{
4581							while (fgets(temp,80,fp)!=NULL)
4582							{
4583								if (p=strstr(temp, "Host: scsi"))
4584								{
4585									p+=10;
4586									sprintf(host, p);
4587									memcpy(host+1, "\0", 1);
4588									continue;
4589								}
4590								if (p=strstr(temp, "Vendor: "))
4591								{
4592									if(!strcmp(dp2->d_name, host))
4593									{
4594										sprintf(vendor_product, p);
4595										p2=strstr(temp, "Rev: ");
4596										memcpy(vendor_product+strlen(p)-strlen(p2)-1, "\0", 1);
4597										break;
4598									}
4599								}
4600							}
4601							fclose(fp);
4602						}
4603
4604						sprintf(str_path, "/proc/scsi/%s/%s", dp->d_name, dp2->d_name);
4605						if (fp=fopen(str_path, "r"))
4606						{
4607							while (fgets(temp,80,fp)!=NULL)
4608							{
4609								if (strstr(temp, "Port: "))
4610								{
4611									if (p=strstr(temp, ": "))
4612									{
4613#ifdef DLM
4614										p+=4; //+2 for WL500GP +4 due to Port: 1.2
4615#else // DLM
4616										p+=2;
4617#endif // DLM
4618										sprintf(port, p);
4619										memcpy(port+strlen(port)-1, "\0", 1);
4620
4621										sprintf(temp2, "usb_disc%d_port", discindex);
4622										nvram_set(temp2, port);
4623										strcpy(tempstr, port);
4624										if (strcmp(tempstr, "1")==0)
4625											sprintf(port, "[USB Lower port]\n");
4626										else
4627											sprintf(port, "[USB Upper port]\n");
4628									}
4629									break;
4630								}
4631							}
4632							fclose(fp);
4633							strcat(port, vendor_product);
4634							strcpy(vendor_product, port);
4635						}
4636						else
4637							strcpy(vendor_product, "");
4638					}
4639				}
4640				closedir(dir_to_open2);
4641			}
4642		}
4643		closedir(dir_to_open);
4644	}
4645}
4646
4647void
4648write_per_disc_status(int disc_index)
4649{
4650	FILE *fp;
4651	char usb_disc_mount_path[128], usb_disc_fs_path[128];
4652	int i, j;
4653	char *temp=(char *)malloc(128);
4654	char disc_dev_str[32];
4655	char disc_idx_str[32];
4656	int disc_order[2];
4657	disc_order[0]=atoi(nvram_get("usb_disc0_dev")+14);
4658	disc_order[1]=atoi(nvram_get("usb_disc1_dev")+14);
4659
4660	fp = fopen("/tmp/usstatus", "a");
4661	if (fp)
4662	{
4663		sprintf(disc_dev_str, "usb_disc%d_dev", disc_index);
4664		sprintf(disc_idx_str, "usb_disc%d_index", disc_index);
4665		if (nvram_invmatch(disc_dev_str, "") && nvram_invmatch(disc_idx_str, "0"))
4666		{
4667			get_disc_desc(temp, disc_order[disc_index], disc_index);
4668			printf("%s\n", temp);
4669			fprintf(fp, "%s\n", temp);
4670			i=atoi(nvram_safe_get(disc_idx_str));
4671			for(j=0; j<i; j++)
4672			{
4673				sprintf(usb_disc_mount_path, "usb_disc%d_path%d", disc_index, j);
4674				printf("%s ", nvram_safe_get(usb_disc_mount_path));
4675				sprintf(usb_disc_fs_path, "usb_disc%d_fs_path%d", disc_index, j);
4676				printf("%s ", nvram_safe_get(usb_disc_fs_path));
4677				if (check_disk_free(temp, nvram_safe_get(usb_disc_mount_path))==2)
4678					sprintf(temp, "unknown");
4679				printf("%s\n", temp);
4680				fprintf(fp, "Partition %d: %s\n", j+1, temp);
4681			}
4682		}
4683		else
4684			fprintf(stderr, "skip write usstatus\n");
4685	}
4686	else
4687		fprintf(stderr, "can not open /tmp/usstatus\n");
4688	if (fp)
4689		fclose(fp);
4690}
4691
4692void
4693write_disc_status()	// added by Jiahao for WL500gP
4694{
4695	int disc0_port=atoi(nvram_get("usb_disc0_port"));
4696	unlink("/tmp/usstatus");
4697
4698	if (disc0_port==2)
4699	{
4700		write_per_disc_status(0);
4701		write_per_disc_status(1);
4702	}
4703	else
4704	{
4705		write_per_disc_status(1);
4706		write_per_disc_status(0);
4707	}
4708}
4709
4710int                                     // added by Jiahao for WL500gP
4711check_if_file_exist(char *filename)
4712{
4713        FILE *fp;
4714        fp=fopen(filename, "r");
4715        if(fp)
4716        {
4717                fclose(fp);
4718                return 1;
4719        }
4720        else
4721                return 0;
4722}
4723
4724int                                     // added by Jiahao for WL500gP
4725check_if_dir_exist(char *dir)
4726{
4727        DIR *dp;
4728        if(!(dp=opendir(dir)))
4729                return 0;
4730        closedir(dp);
4731        return 1;
4732}
4733
4734int
4735mkdir_if_none(char *dir)                // added by Jiahao for WL500gP
4736{
4737        DIR *dp;
4738        if(!(dp=opendir(dir)))
4739        {
4740                umask(0000);
4741                mkdir(dir, 0777);
4742//              umask(0022);
4743                return 1;
4744        }
4745        closedir(dp);
4746        return 0;
4747}
4748#ifdef DLM
4749void set_apps_ver()
4750{
4751	nvram_set("apps_ver", "1.00");
4752}
4753
4754void exec_dms()
4755{
4756	char name[32];
4757	char mymac[32];
4758	char path[256];
4759	char tmpstr2[256];
4760	int ret = 0;
4761
4762	mkdir_if_none("/shares/DMSRoot");
4763
4764	strcpy(name, nvram_safe_get("computer_name"));
4765	strcpy(mymac, nvram_safe_get("et0macaddr"));
4766
4767	if(nvram_match("apps_dmsx", "1")){
4768		sprintf(path, "%s", nvram_get("first_partition"));
4769		sprintf(tmpstr2, "dms %s \"%s\" %s &", path, name, mymac);
4770		ret = system(tmpstr2);
4771		if(!ret)
4772			logmessage("Media Server", "daemon is started");
4773	}
4774}
4775
4776void exec_apps()		// added by Jiahao for WL500gP
4777{
4778	FILE *fp;
4779
4780	char pool[32];
4781	char share[32];
4782	char rundl[8];
4783	char rundms[8];
4784	char name[32];
4785	char mymac[32];
4786	int cap=0;
4787	int ret=0;
4788
4789	char EXBIN[32]="/.apps/bin";
4790	char test_path[128];
4791
4792	char tmpstr[256];
4793	char tmpstr2[256];
4794	char share_port_from[5];
4795	char share_port_to[5];
4796
4797	if ( nvram_match("apps_dms_usb_port_x", nvram_safe_get("usb_disc0_port")) )
4798	{
4799		strcpy(test_path, nvram_safe_get("usb_disc0_path0"));
4800	}
4801	else if ( nvram_match("apps_dms_usb_port_x", nvram_safe_get("usb_disc1_port")) )
4802	{
4803		strcpy(test_path, nvram_safe_get("usb_disc1_path0"));
4804	}
4805	strcpy(tmpstr, EXBIN);
4806	sprintf(EXBIN, "%s%s", test_path, tmpstr);
4807
4808	eval("killall", "dms");
4809	eval("killall", "snarf");
4810	eval("killall", "ctorrent");
4811	eval("killall", "rtorrent");
4812	eval("killall", "giftd");
4813	eval("killall", "dmathined");
4814
4815	nvram_set("dms_running", "0");	// 2007.11 James.
4816	//nvram_set("apps_installed", "0");	// 2007.11 James. set at the end of this function
4817	nvram_set("apps_dl_x", "0");
4818
4819	strcpy(pool, nvram_safe_get("apps_pool"));
4820	strcpy(share, nvram_safe_get("apps_share"));
4821	strcpy(rundl, nvram_safe_get("apps_dlx"));
4822	strcpy(rundms, nvram_safe_get("apps_dmsx"));
4823	strcpy(name, nvram_safe_get("computer_name"));
4824	strcpy(mymac, nvram_safe_get("et0macaddr"));
4825
4826	strcpy(share_port_from, nvram_get("apps_dl_share_port_from"));
4827	strcpy(share_port_to, nvram_get("apps_dl_share_port_to"));
4828	fp=fopen("/tmp/.prange", "w");
4829	if(fp)
4830	{
4831		fprintf(fp,"%s:%s", share_port_from, share_port_to);
4832		fclose(fp);
4833	}
4834
4835	if (nvram_match("apps_dmsx", "1"))
4836	{
4837//		sprintf(tmpstr2, "%s/dms /shares/DMSRoot %s %s &", EXBIN, name, mymac);
4838		sprintf(tmpstr2, "%s/dms /shares/DMSRoot \"%s\" %s &", "/apps/bin", name, mymac);
4839		ret=system(tmpstr2);
4840		if(!ret){
4841			nvram_set("dms_running", "1");	// 2007.11 James.
4842			logmessage("Media Server", "daemon is started");
4843		}
4844	}
4845	if (nvram_match("apps_dlx", "1") && nvram_match("swap_on", "1") && nvram_match("apps_comp", "1"))
4846	{
4847		sprintf(tmpstr2, "%s/dmex&", EXBIN);
4848		ret=system(tmpstr2);
4849		nvram_set("apps_running", "1");
4850		if(!ret)
4851		{
4852			//nvram_set("apps_dl_x", "1");	// 2008.11 James. set this nvram in dmex.
4853			logmessage("Download Master", "daemon is started");
4854		}
4855	}
4856
4857	nvram_set("apps_installed", "1");
4858}
4859
4860void start_apps()			// added by Jiahao for WL500gP
4861{
4862	printf("\npreparing to start Download Machine\n");
4863	char pool[32];
4864	char share[32];
4865	char origver[32];
4866	char target_dir[32];
4867	char pool_dir[32];
4868	char EXLIB[32]="/.apps/lib";
4869	char EXBIN[32]="/.apps/bin";
4870	char EXUSR[32]="/.apps/usr";
4871	char EXETC[32];
4872	char NEWVER[8];
4873	char tmpstr[256];
4874	char tmpstr2[256];
4875	char tmpstr3[256];
4876	char tmpstr4[256];
4877
4878	char test_path[128];
4879	char *p;
4880
4881	if ( nvram_match("apps_dms_usb_port_x", nvram_safe_get("usb_disc0_port")) )
4882	{
4883		strcpy(test_path, nvram_safe_get("usb_disc0_path0"));
4884		p=strstr(test_path, "/tmp/harddisk");
4885		p+=5;
4886		nvram_set("apps_pool", p);
4887	}
4888	else if ( nvram_match("apps_dms_usb_port_x", nvram_safe_get("usb_disc1_port")) )
4889	{
4890		strcpy(test_path, nvram_safe_get("usb_disc1_path0"));
4891		p=strstr(test_path, "/tmp/harddisk");
4892		p+=5;
4893		nvram_set("apps_pool", p);
4894	}
4895
4896	strcpy(tmpstr, EXLIB);
4897	sprintf(EXLIB, "%s%s", test_path, tmpstr);
4898	strcpy(tmpstr, EXBIN);
4899	sprintf(EXBIN, "%s%s", test_path, tmpstr);
4900	strcpy(tmpstr, EXUSR);
4901	sprintf(EXUSR, "%s%s", test_path, tmpstr);
4902
4903	//strcpy(pool, nvram_get("apps_pool"));
4904	strcpy(pool, p);	// 2008.05 James.
4905	strcpy(share, nvram_get("apps_share"));
4906	strcpy(origver, nvram_get("apps_ver"));
4907	sprintf(target_dir, "/shares/%s/%s", pool, share);
4908	sprintf(pool_dir, "/shares/%s", pool);
4909	sprintf(EXETC, "%s/.etc", pool_dir);
4910
4911	eval("rm", "-rf", "/shares/lib");
4912	eval("rm", "-rf", "/shares/bin");
4913	eval("rm", "-rf", "/shares/usr");
4914	eval("rm", "-rf", "/shares/etc");
4915	eval("rm", "-rf", EXETC);
4916
4917	mkdir_if_none(pool_dir);
4918	mkdir_if_none(target_dir);
4919
4920	eval("ln", "-s", EXLIB, "/shares/lib");
4921	eval("ln", "-s", EXBIN, "/shares/bin");
4922	eval("ln", "-s", EXUSR, "/shares/usr");
4923
4924	set_apps_ver();
4925	sprintf(NEWVER, nvram_safe_get("apps_ver"));
4926
4927	sprintf(tmpstr, "%s/Music", target_dir);
4928	if (mkdir_if_none(tmpstr)==0)
4929		printf("Music DIR exist\n");
4930
4931	sprintf(tmpstr, "%s/Video", target_dir);
4932	if (mkdir_if_none(tmpstr)==0)
4933		printf("Video DIR exist\n");
4934
4935	sprintf(tmpstr, "%s/Photo", target_dir);
4936	if (mkdir_if_none(tmpstr)==0)
4937		printf("PHOTO DIR exist\n");
4938
4939	sprintf(tmpstr, "%s/Download", target_dir);
4940	if (mkdir_if_none(tmpstr)==0)
4941		printf("DOWNLOAD DIR exist\n");
4942
4943	sprintf(tmpstr, "%s/Download/config", target_dir);
4944	mkdir_if_none(tmpstr);
4945	sprintf(tmpstr, "%s/Download/Complete", target_dir);
4946	mkdir_if_none(tmpstr);
4947	sprintf(tmpstr, "%s/Download/InComplete", target_dir);
4948	mkdir_if_none(tmpstr);
4949	sprintf(tmpstr, "%s/Download/.logs", target_dir);
4950	mkdir_if_none(tmpstr);
4951
4952	eval("rm", "-rf", EXETC);
4953	mkdir_if_none(EXETC);
4954	eval("ln", "-s", EXETC, "/shares/etc");
4955
4956	if (nvram_match("apps_dlx", "1") && nvram_match("swap_on", "1") && nvram_match("apps_comp", "1"))
4957	{
4958		sprintf(tmpstr, "%s/asus_gift.conf", EXETC);
4959		if (check_if_file_exist(tmpstr)==1)
4960			printf("FILE asus_gift exist\n");
4961		else
4962		{
4963			sprintf(tmpstr, "%s/gift-nasoc/bin/asus_gift.conf", EXUSR);
4964			sprintf(tmpstr2, "cp %s %s/. -f", tmpstr, EXETC);
4965			system(tmpstr2);
4966		}
4967
4968		sprintf(tmpstr, "%s/.giFT", EXETC);
4969		if (mkdir_if_none(tmpstr)==0)
4970			printf(".giFT DIR exist\n");
4971		else
4972		{
4973			sprintf(tmpstr2, "%s/.", tmpstr);
4974			sprintf(tmpstr4, "cp /shares/usr/.giFT/* %s -f", tmpstr2);
4975			system(tmpstr4);
4976
4977			sprintf(tmpstr2, "%s/FastTrack", tmpstr);
4978			mkdir_if_none(tmpstr2);
4979
4980			sprintf(tmpstr3, "%s/.", tmpstr2);
4981			sprintf(tmpstr4, "cp /shares/usr/.giFT/FastTrack/* %s -f", tmpstr3);
4982			system(tmpstr4);
4983
4984			sprintf(tmpstr2, "%s/OpenFT", tmpstr);
4985			mkdir_if_none(tmpstr2);
4986
4987			sprintf(tmpstr3, "%s/.", tmpstr2);
4988			sprintf(tmpstr4, "cp /shares/usr/.giFT/OpenFT/* %s -f", tmpstr3);
4989			system(tmpstr4);
4990
4991			sprintf(tmpstr2, "%s/Gnutella", tmpstr);
4992			mkdir_if_none(tmpstr2);
4993
4994			sprintf(tmpstr3, "%s/.", tmpstr2);
4995			sprintf(tmpstr4, "cp /shares/usr/.giFT/Gnutella/* %s -f", tmpstr3);
4996			system(tmpstr4);
4997
4998			sprintf(tmpstr2, "%s/completed", tmpstr);
4999			mkdir_if_none(tmpstr2);
5000			sprintf(tmpstr2, "%s/completed/corrupted", tmpstr);
5001			mkdir_if_none(tmpstr2);
5002			sprintf(tmpstr2, "%s/ui", tmpstr);
5003			mkdir_if_none(tmpstr2);
5004
5005			sprintf(tmpstr3, "%s/.", tmpstr2);
5006			sprintf(tmpstr4, "cp /shares/usr/.giFT/ui/* %s -f", tmpstr3);
5007			system(tmpstr4);
5008
5009			sprintf(tmpstr, "%s/giFT", EXETC);
5010			mkdir_if_none(tmpstr);
5011
5012			sprintf(tmpstr2, "%s/.", tmpstr);
5013			sprintf(tmpstr4, "cp /shares/usr/gift-nasoc/share/giFT/* %s -f", tmpstr2);
5014			system(tmpstr4);
5015
5016			sprintf(tmpstr2, "%s/FastTrack", tmpstr);
5017			mkdir_if_none(tmpstr2);
5018			sprintf(tmpstr2, "%s/OpenFT", tmpstr);
5019			mkdir_if_none(tmpstr2);
5020			sprintf(tmpstr2, "%s/Gnutella", tmpstr);
5021			mkdir_if_none(tmpstr2);
5022			sprintf(tmpstr2, "%s/completed", tmpstr);
5023			mkdir_if_none(tmpstr2);
5024			sprintf(tmpstr2, "%s/completed/corrupted", tmpstr);
5025			mkdir_if_none(tmpstr2);
5026			sprintf(tmpstr2, "%s/ui", tmpstr);
5027			mkdir_if_none(tmpstr2);
5028
5029			sprintf(tmpstr3, "%s/.", tmpstr2);
5030			sprintf(tmpstr4, "cp /shares/usr/gift-nasoc/share/giFT/ui/* %s -f", tmpstr3);
5031			system(tmpstr4);
5032		}
5033
5034		eval("rm" ,"-rf" ,"/shares/dmathined");
5035		mkdir_if_none("/shares/dmathined");
5036		mkdir_if_none("/shares/dmathined/Download");
5037
5038		sprintf(tmpstr, "%s/Download/config", target_dir);
5039		eval("ln", "-s", tmpstr, "/shares/dmathined/Download/config");
5040		sprintf(tmpstr, "%s/Download/Complete", target_dir);
5041		eval("ln", "-s", tmpstr, "/shares/dmathined/Download/Complete");
5042		sprintf(tmpstr, "%s/Download/InComplete", target_dir);
5043		eval("ln", "-s", tmpstr, "/shares/dmathined/Download/InComplete");
5044		sprintf(tmpstr, "%s/Download/.logs", target_dir);
5045		eval("ln", "-s", tmpstr, "/shares/dmathined/Download/.logs");
5046	}
5047
5048	eval("rm" ,"-rf" ,"/shares/DMSRoot");
5049	mkdir_if_none("/shares/DMSRoot");
5050
5051	sprintf(tmpstr, "%s/Download/Complete", target_dir);
5052	eval("ln", "-s", tmpstr, "/shares/DMSRoot/Download");
5053	sprintf(tmpstr, "%s/Video", target_dir);
5054	eval("ln", "-s", tmpstr, "/shares/DMSRoot/Video");
5055	sprintf(tmpstr, "%s/Music", target_dir);
5056	eval("ln", "-s", tmpstr, "/shares/DMSRoot/Music");
5057	sprintf(tmpstr, "%s/Photo", target_dir);
5058	eval("ln", "-s", tmpstr, "/shares/DMSRoot/Photo");
5059
5060	eval("/sbin/test_of_var_files_in_mount_path", pool_dir);	// 2008.05 James.
5061
5062	exec_apps();
5063}
5064
5065void get_first_partition(char *part_path)		// added by Jiahao for WL500gP
5066{
5067	strcpy(part_path, "");
5068	if (nvram_match("usb_disc0_dev", ""))
5069	{
5070		if (nvram_invmatch("usb_disc1_dev", ""))
5071		{
5072			if (nvram_invmatch("usb_disc1_index", "0"))
5073			{
5074				strcpy(part_path, nvram_safe_get("usb_disc1_path0"));
5075			}
5076		}
5077	}
5078	else
5079	{
5080		if (nvram_invmatch("usb_disc0_index", "0"))
5081		{
5082			strcpy(part_path, nvram_safe_get("usb_disc0_path0"));
5083		}
5084	}
5085}
5086
5087// 2007.10 James {
5088void start_usb_apps(){
5089printf("*** start_usb_apps() ***\n");
5090	run_ftpsamba();
5091	start_apps();
5092}
5093
5094void stop_usb_apps(){
5095printf("*** stop_usb_apps() ***\n");
5096	stop_apps();
5097	stop_ftpsamba();
5098	sleep(1);
5099}
5100
5101void stop_apps(){
5102	eval("killall", "snarf");
5103	eval("killall", "ctorrent");
5104	eval("killall", "rtorrent");
5105	eval("killall", "giftd");
5106	eval("killall", "dmathined");
5107
5108	stop_dms();
5109
5110	nvram_set("apps_running", "0");
5111	nvram_set("apps_dl_x", "0");
5112	sleep(1);
5113}
5114
5115void stop_ftpsamba(){
5116	stop_ftp();
5117	stop_samba();
5118}
5119
5120void stop_ftp(){
5121	if(nvram_match("ftp_running", "0"))
5122		return ;
5123
5124	fprintf(stderr, "Stoping vsftpd\n");
5125
5126	eval("killall", "-SIGKILL", "vsftpd");
5127	//eval("rm", "-f", "/tmp/vsftpd.conf");
5128	unlink("/tmp/vsftpd.conf");
5129
5130	logmessage("FTP Server", "daemon is stoped");
5131
5132	nvram_set("ftp_running", "0");
5133}
5134
5135void stop_samba(){
5136	if(nvram_match("samba_running", "0"))
5137		return ;
5138
5139	fprintf(stderr, "Stoping samba\n");
5140
5141	eval("killall", "-SIGKILL", "smbd");
5142	eval("killall", "-SIGKILL", "nmbd");
5143	//eval("rm", "-f", "/tmp/samba/lib/smb.conf");
5144	unlink("/tmp/samba/lib/smb.conf");
5145
5146	logmessage("Samba Server", "daemon is stoped");
5147
5148	nvram_set("samba_running", "0");
5149	nvram_set("st_samba_mode_x", "0");	// 2007.11 James.
5150}
5151
5152void stop_dms(){
5153	if(nvram_invmatch("dms_running", "1"))
5154		return;
5155
5156	fprintf(stderr, "Stoping dms\n");
5157
5158	eval("killall", "dms");
5159
5160	logmessage("Media Server", "daemon is stoped");
5161
5162	nvram_set("dms_running", "0");
5163}
5164
5165int run_dms(){
5166	if(nvram_match("dms_running", "0")){
5167		if(start_dms() == 0){
5168			nvram_set("dms_running", "1");
5169		}
5170
5171		return -1;
5172	}
5173
5174	return 0;
5175}
5176
5177int start_dms(){
5178	char *DMS_ROOT = "/shares/DMSRoot";
5179	char name[32];
5180	char mymac[32];
5181	char path[256];
5182	char tmpstr2[256];
5183	int ret = 0;
5184	pid_t pid;
5185	char *argvs[5];
5186
5187	if(nvram_invmatch("apps_dmsx", "1"))
5188		return 0;
5189
5190	mkdir_if_none(DMS_ROOT);
5191
5192	strcpy(name, nvram_safe_get("computer_name"));
5193	strcpy(mymac, nvram_safe_get("et0macaddr"));
5194	sprintf(tmpstr2, "/apps/bin/dms %s \"%s\" %s &", DMS_ROOT, name, mymac);
5195
5196	ret = system(tmpstr2);
5197	if(!ret){
5198		nvram_set("dms_running", "1");	// 2007.11 James.
5199		logmessage("Media Server", "daemon is started");
5200
5201		return 0;
5202	}
5203
5204	return 1;
5205}
5206// 2007.10 James }
5207
5208void
5209run_samba()
5210{
5211	if(nvram_match("samba_running", "0"))
5212	{
5213		//if (nvram_invmatch("st_samba_modex", "0"))
5214		if(nvram_invmatch("st_samba_mode", "0"))	// 2007.11 James.
5215		{
5216			fprintf(stderr, "starting samba\n");
5217			if (start_samba()==0)
5218			{
5219				nvram_set("samba_running", "1");
5220			}
5221		}
5222	}
5223	else
5224	{
5225		//if (nvram_invmatch("st_samba_modex", "0"))
5226		if(nvram_invmatch("st_samba_mode", "0"))	// 2007.11 James.
5227		{
5228// 2007.11 James. For new /tmp/passwd and new account. {
5229			//fprintf(stderr, "rewrite conf of samba\n");
5230			//write_smb_conf();
5231			fprintf(stderr, "restarting samba\n");
5232			if(!start_samba())
5233				nvram_set("samba_running", "1");
5234// 2007.11 James. For new /tmp/passwd and new account. }
5235		}
5236	}
5237}
5238
5239void
5240run_ftp()
5241{
5242	if(nvram_match("ftp_running", "0"))
5243	{
5244		//if (nvram_invmatch("st_ftp_modex", "0"))
5245		if (nvram_invmatch("st_ftp_mode", "0"))	// 2007.10 James.
5246		{
5247			fprintf(stderr, "starting vsftpd\n");
5248			if (start_ftpd()==0)
5249			{
5250				nvram_set("ftp_running", "1");
5251			}
5252		}
5253	}
5254	else
5255	{
5256		//if (nvram_invmatch("st_ftp_modex", "0"))
5257		if (nvram_invmatch("st_ftp_mode", "0"))	// 2007.10 James.
5258		{
5259			//fprintf(stderr, "rewrite conf of vsftpd\n");
5260			//write_ftpd_conf();
5261			fprintf(stderr, "restarting ftp\n");
5262			if(!start_ftpd())
5263				nvram_set("ftp_running", "1");
5264		}
5265	}
5266}
5267
5268void
5269run_ftpsamba()
5270{
5271	run_ftp();
5272	run_samba();
5273}
5274
5275int
5276run_apps()
5277{
5278	int apps_comp=0;
5279	int apps_comp_pre=0;
5280	int apps_status=0;
5281	int apps_disk_free=0;
5282	int ret=0, i;
5283	char tmp[32];
5284	char tmpstr[64];
5285	char tmpstr2[64];
5286	FILE *fp;
5287	char *buf=NULL;
5288	int buflen=0;
5289	struct sysinfo info;
5290
5291	nvram_set("usb_storage_busy", "1");
5292	nvram_set("apps_status_checked", "0");
5293
5294	strcpy(tmp, "");
5295	if ( nvram_invmatch("usb_disc0_dev", "") && (nvram_match("apps_dlx", "0")||check_disk_free_GE_1G(nvram_safe_get("usb_disc0_path0"))==2))
5296	{
5297		strcpy(tmp, nvram_safe_get("usb_disc0_path0"));
5298	}
5299	else if ( nvram_invmatch("usb_disc1_dev", "") && (nvram_match("apps_dlx", "0")||check_disk_free_GE_1G(nvram_safe_get("usb_disc1_path0"))==2))
5300	{
5301		strcpy(tmp, nvram_safe_get("usb_disc1_path0"));
5302	}
5303	else if ( nvram_invmatch("usb_disc0_dev", "") )
5304	{
5305		strcpy(tmp, nvram_safe_get("usb_disc0_path0"));
5306	}
5307	else if ( nvram_invmatch("usb_disc1_dev", "") )
5308	{
5309		strcpy(tmp, nvram_safe_get("usb_disc1_path0"));
5310	}
5311
5312	if (	nvram_match("swap_on", "0") &&
5313		nvram_match("apps_dlx", "1") &&
5314		((apps_comp_pre=ckeck_apps_completeness_pre(tmp))==1)
5315	   )
5316	{
5317		if (strcmp(tmp, "")!=0)
5318		{
5319			memset(tmpstr, 0, sizeof(tmpstr));
5320			sprintf(tmpstr, "%s/swap", tmp);
5321			unlink(tmpstr);
5322			memset(tmpstr, 0, sizeof(tmpstr));
5323			sprintf(tmpstr, "%s/.swap", tmp);
5324			unlink(tmpstr);
5325
5326			ret = check_disk_free_GE_1G(tmp);
5327
5328			if (ret==2)
5329			{
5330				if(!strcmp(tmp, nvram_safe_get("usb_disc0_path0")))
5331					nvram_set("apps_dms_usb_port_x2", nvram_safe_get("usb_disc0_port"));
5332				else if (!strcmp(tmp, nvram_safe_get("usb_disc1_path0")))
5333					nvram_set("apps_dms_usb_port_x2", nvram_safe_get("usb_disc1_port"));
5334
5335				sysinfo(&info);
5336				if ((info.freeram + info.bufferram) >= 1024*1024*2)
5337					buflen = 1024*1024*2;
5338				else if ((info.freeram + info.bufferram) >= 1024*1024*1.6)
5339					buflen = 1024*1024*1.6;
5340				else if ((info.freeram + info.bufferram) >= 1024*1024*1)
5341					buflen = 1024*1024*1;
5342				else if ((info.freeram + info.bufferram) >= 1024*1024*0.8)
5343					buflen = 1024*1024*0.8;
5344				else
5345					buflen = 1024*1024*0.5;
5346				buf = malloc(buflen);
5347				for(i=0;i<buflen;i++)
5348					buf[i]='\n';
5349
5350				fp=fopen(tmpstr, "a");
5351				if(fp!=NULL)
5352				{
5353					for(i=0;i<1024*1024*32/buflen;i++)
5354						fprintf(fp, "%s", buf);
5355					free(buf);
5356					fclose(fp);
5357
5358					/*memset(tmpstr2, 0, sizeof(tmpstr2));
5359					sprintf(tmpstr2, "mkswap %s", tmpstr);
5360					system(tmpstr2);
5361
5362					memset(tmpstr2, 0, sizeof(tmpstr2));
5363					sprintf(tmpstr2, "swapon %s", tmpstr);
5364					system(tmpstr2);//*/
5365					eval("/sbin/mkswap", tmpstr);
5366
5367					swapon(tmpstr, 0);	// 2008.04 James.
5368
5369					logmessage("USB storage", "32MB swap file is added");
5370					nvram_set("swap_on", "1");
5371					nvram_set("swap_file", tmpstr);	// 2008.06 James.
5372				}
5373			}
5374			else if (ret==1)
5375				logmessage("USB storage", "The swap file is not added for free space is less than 33MB");
5376			else if (ret==3)
5377				logmessage("USB storage", "The swap file is not added for partition size is less than 1024MB");
5378			else if (ret==0)
5379				logmessage("USB storage", "The swap file is not added for unknown reasons");
5380		}
5381	}
5382
5383	apps_disk_free=check_disk_free_apps(tmp, apps_comp);
5384	if (apps_disk_free==1)
5385		nvram_set("apps_disk_free", "1");
5386	else
5387		nvram_set("apps_disk_free", "0");
5388
5389	//if(	nvram_match("apps_running", "0") &&
5390	if(strcmp(nvram_safe_get("apps_running"), "1") != 0 &&	// 2007.11 James.
5391			((apps_comp_pre==1 && nvram_match("apps_dlx", "1")) || nvram_match("apps_dmsx", "1"))
5392			){
5393		if(strcmp(tmp, "") != 0){
5394			apps_comp = ckeck_apps_completeness(tmp);
5395			if(apps_comp == 1)
5396				nvram_set("apps_comp", "1");
5397			else{
5398				nvram_set("apps_comp", "0");
5399
5400				if(!strcmp(nvram_safe_get("swap_on"), "1")){
5401					printf("try to swapoff swap file.\n");
5402					if(strcmp(tmp, "")){
5403						memset(tmpstr, 0, sizeof(tmpstr));
5404						sprintf(tmpstr, "%s/.swap", tmp);
5405						swapoff(tmpstr);
5406						sleep(1);
5407						if(swap_check() == 1){
5408							logmessage("USB storage", "swapoff unsuccessfully");
5409							nvram_set("swapoff_failed", "1");
5410							unlink(tmpstr);
5411							nvram_set("reboot", "1");
5412						}
5413						else{
5414							logmessage("USB storage", "swapoff successfully");
5415							nvram_set("swap_on", "0");
5416							nvram_set("swap_file", "");	// 2008.06 James.
5417							nvram_set("swapoff_failed", "0");
5418							nvram_set("apps_dms_usb_port_x2", "-1");
5419							unlink(tmpstr);
5420						}
5421					}
5422				}
5423			}
5424			if (nvram_match("apps_dlx", "0") ||
5425			    (nvram_match("apps_dlx", "1") && nvram_match("swap_on", "1") && check_disk_free_GE_1G(tmp)==2) ||
5426			    (nvram_match("apps_dmsx", "1") && !(nvram_match("apps_dlx", "1") && nvram_match("swap_on", "1") && check_disk_free_GE_1G(tmp)==2))
5427			   )
5428			{
5429//				if (apps_comp==1 && apps_disk_free==1)
5430				if ( (apps_comp==1 && apps_disk_free==1) || nvram_match("apps_dmsx", "1"))
5431				{
5432					if (strcmp(tmp, nvram_safe_get("usb_disc0_path0"))==0)
5433						nvram_set("apps_dms_usb_port_x", nvram_safe_get("usb_disc0_port"));
5434					else if (strcmp(tmp, nvram_safe_get("usb_disc1_path0"))==0)
5435						nvram_set("apps_dms_usb_port_x", nvram_safe_get("usb_disc1_port"));
5436
5437					start_apps();
5438					nvram_set("apps_running", "1");
5439				}
5440			}
5441			else
5442			{
5443				fprintf(stderr, "skip running DMS & DM for no swap file or binary completeness issues\n");
5444				logmessage("Media Server", "daemon is not started for no swap file or binary completeness issues");
5445				logmessage("Download Master", "daemon is not started for no swap file or binary completeness issues");
5446			}
5447		}
5448	}
5449	else
5450		fprintf(stderr, "skip running DMS & DM\n");
5451
5452	nvram_set("usb_storage_busy", "0");
5453	nvram_set("apps_status_checked", "1");
5454	return 0;
5455}
5456
5457int
5458swap_check()
5459{
5460	struct sysinfo info;
5461
5462	sysinfo(&info);
5463	if(info.totalswap > 0)
5464		return 1;
5465	else
5466		return 0;
5467}
5468#endif // DLM
5469
5470int
5471umount_disc_parts_rc(int usb_port)
5472{
5473	char nvramstr[32];
5474	char nvramstr2[32];
5475	char nvramstr3[32];
5476	char umount_dir[32];
5477	int disc_index, i;
5478	char tmp[2];
5479	int dev_index=-1;
5480	int count=0;
5481	char test_path[128], tmpstr[128];
5482	int ret=0;
5483#ifdef DLM
5484	int sleep_flag=0;
5485
5486	//if ( strcmp(nvram_safe_get("usb_storage_busy"), "1" )==0 )	// 2007.12 James
5487	//	return;
5488#endif // DLM
5489
5490	sprintf(tmp, "%d", usb_port);
5491	if(!strcmp(nvram_safe_get("usb_disc0_port"), tmp))
5492		dev_index = 0;
5493	else if(!strcmp(nvram_safe_get("usb_disc1_port"), tmp))
5494		dev_index = 1;
5495	else
5496		return -1;
5497
5498#ifdef DLM
5499#if 1
5500	if ( (strcmp(nvram_safe_get("apps_running"), "1")==0) && (atoi(nvram_safe_get("apps_dms_usb_port_x"))==usb_port) )
5501	{
5502		sleep_flag=1;
5503
5504		eval("killall", "snarf");
5505		eval("killall", "ctorrent");
5506		eval("killall", "rtorrent");
5507		eval("killall", "giftd");
5508		eval("killall", "dmathined");
5509		//eval("killall", "dms");
5510
5511		//nvram_set("dms_running", "0");	// 2007.11 James.
5512		nvram_set("apps_running", "0");
5513		nvram_set("apps_installed", "0");
5514		nvram_set("apps_dl_x", "0");
5515		nvram_set("apps_status_checked", "0");
5516		nvram_set("apps_disk_free", "0");
5517
5518		/*nvram_set("usb_storage_busy2", "1");
5519		sleep(5);
5520		nvram_set("usb_storage_busy2", "0");*/
5521	}
5522#endif // 1
5523	if(!strcmp(nvram_safe_get("samba_running"), "1")){
5524		eval("killall", "nmbd");
5525		eval("killall", "smbd");
5526		nvram_set("samba_running", "0");
5527		nvram_set("st_samba_mode_x", "0");
5528	}
5529
5530	if(!strcmp(nvram_safe_get("ftp_running"), "1")){
5531		eval("killall", "vsftpd");
5532		nvram_set("ftp_running", "0");
5533	}
5534
5535// 2007.11 James. {
5536	if(!strcmp(nvram_safe_get("dms_running"), "1")){
5537		eval("killall", "dms");
5538		nvram_set("dms_running", "0");
5539	}
5540// 2007.11 James. }
5541
5542	if(sleep_flag == 1)
5543	{
5544		nvram_set("usb_storage_busy2", "1");
5545		for(i = 1; i <= 2; ++i){
5546			printf("Sleep %d second%s...\n", i, ((i == 1)?"":"s"));
5547			sleep(1);
5548		}
5549		nvram_set("usb_storage_busy2", "0");
5550	}
5551
5552	sync();	// 2008.06 James.
5553
5554	if(!strcmp(nvram_safe_get("swap_on"), "1") && atoi(nvram_safe_get("apps_dms_usb_port_x2")) == usb_port)
5555	{
5556		strcpy(test_path, "");
5557		if ( strcmp(nvram_safe_get("usb_disc0_port"), nvram_safe_get("apps_dms_usb_port_x2"))==0 )
5558		{
5559			strcpy(test_path, nvram_safe_get("usb_disc0_path0"));
5560		}
5561		else if ( strcmp(nvram_safe_get("usb_disc1_port"), nvram_safe_get("apps_dms_usb_port_x2"))==0 )
5562		{
5563			strcpy(test_path, nvram_safe_get("usb_disc1_path0"));
5564		}
5565
5566		if(strcmp(test_path, "") != 0)
5567		{
5568			sprintf(tmpstr, "%s/.swap", test_path);
5569			printf("try to swapoff %s.\n", tmpstr);
5570			swapoff(tmpstr);
5571
5572			//nvram_set("usb_storage_busy2", "1");
5573			sleep(1);
5574			//nvram_set("usb_storage_busy2", "0");
5575
5576			if (swap_check()==1)
5577			{
5578				logmessage("USB storage", "swapoff unsuccessfully");
5579				nvram_set("swapoff_failed", "1");
5580				//unlink(tmpstr);
5581				return -1;
5582			}
5583			else
5584			{
5585				logmessage("USB storage", "swapoff successfully");
5586				nvram_set("swap_on", "0");
5587				nvram_set("swap_file", "");	// 2008.06 James.
5588				nvram_set("swapoff_failed", "0");
5589				nvram_set("apps_dms_usb_port_x2", "-1");
5590				unlink(tmpstr);
5591			}
5592		}
5593	}
5594#endif // DLM
5595
5596	sprintf(nvramstr, "usb_disc%d_index", dev_index);
5597	disc_index=atoi(nvram_safe_get(nvramstr));
5598
5599	for (i=disc_index; i>0; i--)
5600	{
5601		sprintf(nvramstr2, "usb_disc%d_path%d", dev_index, i-1);
5602		sprintf(umount_dir, nvram_safe_get(nvramstr2));
5603		sprintf(nvramstr3, "usb_disc%d_fs_path%d", dev_index, i-1);
5604		count=0;
5605		//while((ret=umount(umount_dir)) && (count<2))
5606		while((ret=umount2(umount_dir, MS_NOEXEC | MS_NOSUID | 0x00000002)) && (count<2))	// 0x00000002: MNT_DETACH
5607		{
5608			//sync();	// 2008.04 James.
5609			count++;
5610#ifdef DLM
5611			nvram_set("usb_storage_busy2", "1");
5612#endif // DLM
5613			sleep(1);
5614#ifdef DLM
5615			nvram_set("usb_storage_busy2", "0");
5616#endif // DLM
5617		}
5618		if(!ret)
5619		{
5620			rmdir(umount_dir);
5621			nvram_set(nvramstr3, "");
5622			nvram_set(nvramstr2, "");
5623			sprintf(tmp, "%d", i-1);
5624			nvram_set(nvramstr, tmp);
5625			sprintf(tmpstr, "unmounted %s", umount_dir);
5626			logmessage("USB storage", tmpstr);
5627		}
5628		else
5629			return ret;
5630	}
5631	sprintf(nvramstr, "usb_disc%d_dev", dev_index);
5632	nvram_set(nvramstr, "");
5633	sprintf(nvramstr, "usb_disc%d_port", dev_index);
5634	nvram_set(nvramstr, "0");
5635#ifdef DLM
5636	nvram_set("eject_from_web", "1");
5637#endif // DLM
5638	write_disc_status();
5639
5640	return 0;
5641}
5642
5643//2008.07.17 Yau add
5644int start_networkmap(void)
5645{
5646	char *networkmap_argv[] = {"networkmap", NULL};
5647	pid_t pid;
5648
5649	_eval(networkmap_argv, NULL, 0, &pid);
5650
5651	return 0;
5652}
5653
5654int eject_cdrom(const char *dev_name){
5655	int stopfd;
5656
5657	csprintf("Stopping CD-ROM(%s) ...", dev_name);
5658	if((stopfd = open(dev_name, O_RDONLY|O_NONBLOCK, 0)) >= 0){
5659		csprintf("there was a CD-ROM device!\n");
5660		if(ioctl(stopfd, CDROMEJECT, 0))
5661			csprintf("Ejecting CD-ROM failed %d\n", errno);
5662		else
5663			csprintf("Ejecting CD-ROM succeeded\n");
5664
5665		close(stopfd);
5666
5667		return 1;
5668	}
5669	else{
5670		csprintf("there wasn't any CD-ROM device!\n");
5671		return 0;
5672	}
5673}
5674
5675int stop_cdrom(const char *dev_name){
5676	int stopfd;
5677
5678	csprintf("Stopping CD-ROM(%s) ...", dev_name);
5679	if((stopfd = open(dev_name, O_RDONLY|O_NONBLOCK, 0)) >= 0){
5680		csprintf("there was a CD-ROM device!\n");
5681		if(ioctl(stopfd, CDROMSTOP, 0))
5682			csprintf("Stopping CD-ROM failed %d\n", errno);
5683		else
5684			csprintf("Stopping CD-ROM succeeded\n");
5685
5686		close(stopfd);
5687
5688		return 1;
5689	}
5690	else{
5691		csprintf("there wasn't any CD-ROM device!\n");
5692		return 0;
5693	}
5694}//*/
5695
5696int eject_scsi(const char *dev_name){
5697	int ejectfd;
5698	int status;
5699	struct sdata {
5700		int  inlen;
5701		int  outlen;
5702		char cmd[256];
5703	} scsi_cmd;
5704
5705	csprintf("Ejecting SCSI(%s) of CDROM ...", dev_name);
5706	if((ejectfd = open(dev_name, O_RDONLY|O_NONBLOCK)) == -1){
5707logmessage("USB Storage", "this was not a CD-ROM device.");
5708		csprintf("there wasn't any CD-ROM device!\n");
5709		return 0;
5710	}
5711logmessage("USB Storage", "this was a CD-ROM device.");
5712	csprintf("there was a CD-ROM device!\n");
5713
5714	/*scsi_cmd.inlen	= 0;
5715	scsi_cmd.outlen = 0;
5716	scsi_cmd.cmd[0] = ALLOW_MEDIUM_REMOVAL;
5717	scsi_cmd.cmd[1] = 0;
5718	scsi_cmd.cmd[2] = 0;
5719	scsi_cmd.cmd[3] = 0;
5720	scsi_cmd.cmd[4] = 0;
5721	scsi_cmd.cmd[5] = 0;
5722	status = ioctl(ejectfd, SCSI_IOCTL_SEND_COMMAND, (void *)&scsi_cmd);
5723	if (status != 0){
5724csprintf("Failed to send ALLOW_MEDIUM_REMOVAL!\n");
5725		close(ejectfd);
5726		return 0;
5727	}//*/
5728
5729	scsi_cmd.inlen	= 0;
5730	scsi_cmd.outlen = 0;
5731	scsi_cmd.cmd[0] = START_STOP;
5732	scsi_cmd.cmd[1] = 0;
5733	scsi_cmd.cmd[2] = 0;
5734	scsi_cmd.cmd[3] = 0;
5735	scsi_cmd.cmd[4] = 1;
5736	scsi_cmd.cmd[5] = 0;
5737	status = ioctl(ejectfd, SCSI_IOCTL_SEND_COMMAND, (void *)&scsi_cmd);
5738	if (status != 0){
5739csprintf("Failed to send first START_STOP!\n");
5740		close(ejectfd);
5741		return 0;
5742	}
5743
5744	scsi_cmd.inlen	= 0;
5745	scsi_cmd.outlen = 0;
5746	scsi_cmd.cmd[0] = START_STOP;
5747	scsi_cmd.cmd[1] = 0;
5748	scsi_cmd.cmd[2] = 0;
5749	scsi_cmd.cmd[3] = 0;
5750	scsi_cmd.cmd[4] = 2;
5751	scsi_cmd.cmd[5] = 0;
5752	status = ioctl(ejectfd, SCSI_IOCTL_SEND_COMMAND, (void *)&scsi_cmd);
5753	if (status != 0){
5754csprintf("Failed to send second START_STOP!\n");
5755		close(ejectfd);
5756		return 0;
5757	}
5758
5759	/* force kernel to reread partition table when new disc inserted */
5760	/*status = ioctl(ejectfd, BLKRRPART);
5761	if (status != 0){
5762csprintf("Failed to send BLKRRPART!\n");
5763	}//*/
5764
5765	close(ejectfd);
5766	return 1;
5767}
5768#endif // ASUS_EXT
5769