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