Example #1
0
void start_jffs2(void)
{
	if (!nvram_match("jffs2_on", "1")) {
		notice_set("jffs", "");
		return;
	}

	int format = 0;
	char s[256];
	int size;
	int part;
	const char *p;
	struct statfs sf;
	int model = 0;

	if (!wait_action_idle(10)) return;

	if (!mtd_getinfo(JFFS2_PARTITION, &part, &size)) return;

	model = get_model();
_dprintf("*** jffs2: %d, %d\n", part, size);
	if (nvram_match("jffs2_format", "1")) {
		nvram_set("jffs2_format", "0");
		if( (model==MODEL_RTAC56U || model==MODEL_RTAC56S || model==MODEL_RTAC68U || model==MODEL_RTAC87U) ^ (!mtd_erase(JFFS_NAME)) ){
                        error("formatting");
                        return;
		}
		
		format = 1;
	}

	sprintf(s, "%d", size);
	p = nvram_get("jffs2_size");
	if ((p == NULL) || (strcmp(p, s) != 0)) {
		if (format) {
			nvram_set("jffs2_size", s);
			nvram_commit_x();
		}
		else if ((p != NULL) && (*p != 0)) {
			error("verifying known size of");
			return;
		}
	}

	if (statfs("/jffs", &sf) == 0) { 
		switch(model) {
			case MODEL_RTAC56S: 
			case MODEL_RTAC56U: 
			case MODEL_RTAC68U: 
			case MODEL_RTAC87U: 
			case MODEL_RTN65U:
			case MODEL_RTN14U: // it should be better to use LINUX_KERNEL_VERSION >= KERNEL_VERSION(2,6,36)
			{
				if (sf.f_type != 0x73717368 /* squashfs */) {
					// already mounted
					notice_set("jffs", format ? "Formatted" : "Loaded");
					return;
				}
				break;
			}
			default:
			{
	                        if (sf.f_type != 0x71736873 /* squashfs */) {
        	                        // already mounted
                	                notice_set("jffs", format ? "Formatted" : "Loaded");
                        	        return;
				}
				break;
			}
		}
	}
	if (nvram_get_int("jffs2_clean_fs")) {
		if (!mtd_unlock(JFFS2_PARTITION)) {
			error("unlocking");
			return;
		}
	}
	modprobe(JFFS_NAME);
	sprintf(s, MTD_BLKDEV(%d), part);

	if (mount(s, "/jffs", JFFS_NAME, MS_NOATIME, "") != 0) {
                if( (get_model()==MODEL_RTAC56U || get_model()==MODEL_RTAC56S || get_model()==MODEL_RTAC68U || get_model()==MODEL_RTAC87U) ^ (!mtd_erase(JFFS_NAME)) ){
                        error("formatting");
                        return;
                }

		format = 1;
		if (mount(s, "/jffs", JFFS_NAME, MS_NOATIME, "") != 0) {
			_dprintf("*** jffs2 2-nd mount error\n");
			//modprobe_r(JFFS_NAME);
			error("mounting");
			return;
		}
	}

#ifdef TEST_INTEGRITY
	int test;

	if (format) {
		if (f_write("/jffs/.tomato_do_not_erase", &size, sizeof(size), 0, 0) != sizeof(size)) {
			stop_jffs2(0);
			error("setting integrity test for");
			return;
		}
	}
	if ((f_read("/jffs/.tomato_do_not_erase", &test, sizeof(test)) != sizeof(test)) || (test != size)) {
		stop_jffs2(0);
		error("testing integrity of");
		return;
	}
#endif

	if (nvram_get_int("jffs2_clean_fs")) {
		_dprintf("Clean /jffs/*\n");
		system("rm -fr /jffs/*");
		nvram_unset("jffs2_clean_fs");
		nvram_commit_x();
	}

	notice_set("jffs", format ? "Formatted" : "Loaded");

	if (((p = nvram_get("jffs2_exec")) != NULL) && (*p != 0)) {
		chdir("/jffs");
		system(p);
		chdir("/");
	}
	run_userfile("/jffs", ".asusrouter", "/jffs", 3);

}
Example #2
0
char *processPacket(int sockfd, char *pdubuf)
{
    IBOX_COMM_PKT_HDR	*phdr;
    IBOX_COMM_PKT_HDR_EX *phdr_ex;
    IBOX_COMM_PKT_RES_EX *phdr_res;
    PKT_GET_INFO *ginfo;
//    PKT_GET_INFO_STA *stainfo;
//    PKT_GET_INFO_EX1 *cmd;					
//    PKT_GET_INFO_EX1 *res;
//    PKT_GET_INFO_SITES *res_sites;
//    PKT_GET_INFO_PROFILE *cmd_profiles, *res_profiles;

#ifdef WAVESERVER	// eric++
    int fail = 0;
    pid_t pid;
    DIR *dir;
    int fd, ret, bytes;
    unsigned char tmp_buf[15];	// /proc/XXXXXX
    WS_INFO_T *wsinfo;
#endif
//#ifdef WL700G
    STORAGE_INFO_T *st;
//#endif
//    int i;
    char ftype[8], prinfo[128];	/* get disk type */
    int free_space;
#ifdef RTCONFIG_WIRELESSREPEATER
    char tmp[100], prefix[] = "wlXXXXXXXXXXXXXX";
#endif

    phdr = (IBOX_COMM_PKT_HDR *)pdubuf;  
    phdr_res = (IBOX_COMM_PKT_RES_EX *)pdubuf_res;
    
//    fprintf(stderr,"Get: %x %x %x\n", phdr->ServiceID, phdr->PacketType, phdr->OpCode);

    if (phdr->ServiceID==NET_SERVICE_ID_IBOX_INFO &&
	phdr->PacketType==NET_PACKET_TYPE_CMD)
    {	    
	if (phdr->OpCode!=NET_CMD_ID_GETINFO && phdr->OpCode!=NET_CMD_ID_GETINFO_MANU&&
	    phdr_res->OpCode==phdr->OpCode &&
	    phdr_res->Info==phdr->Info)
	{	
		// if transaction id is equal to the transaction id of the last response message, just re-send message again;
		return pdubuf_res;
	}	
	
	phdr_res->ServiceID=NET_SERVICE_ID_IBOX_INFO;
	phdr_res->PacketType=NET_PACKET_TYPE_RES;
	phdr_res->OpCode=phdr->OpCode;

	if (phdr->OpCode!=NET_CMD_ID_GETINFO && phdr->OpCode!=NET_CMD_ID_GETINFO_MANU)
	{
		phdr_ex = (IBOX_COMM_PKT_HDR_EX *)pdubuf;	
		
		// Check Mac Address
		if (memcpy(phdr_ex->MacAddress, mac, 6)==0)
		{
			_dprintf("Mac Error %2x%2x%2x%2x%2x%2x\n",
				(unsigned char)phdr_ex->MacAddress[0],
				(unsigned char)phdr_ex->MacAddress[1],
				(unsigned char)phdr_ex->MacAddress[2],
				(unsigned char)phdr_ex->MacAddress[3],
				(unsigned char)phdr_ex->MacAddress[4],
				(unsigned char)phdr_ex->MacAddress[5]
				);
			return NULL;
		}
		
		// Check Password
		//if (strcmp(phdr_ex->Password, "admin")!=0)
		//{
		//	phdr_res->OpCode = phdr->OpCode | NET_RES_ERR_PASSWORD;
		//	_dprintf("Password Error %s\n", phdr_ex->Password);	
		//	return NULL;
		//}
		phdr_res->Info = phdr_ex->Info;
		memcpy(phdr_res->MacAddress, phdr_ex->MacAddress, 6);
	}

	switch(phdr->OpCode)
	{
		case NET_CMD_ID_GETINFO_MANU:
//		case NET_CMD_ID_GETINFO:
		     _dprintf("NET CMD GETINFO_MANU\n");	// tmp test
		     ginfo=(PKT_GET_INFO *)(pdubuf_res+sizeof(IBOX_COMM_PKT_RES));
		     memset(ginfo, 0, sizeof(ginfo));
#if 0
#ifdef PRNINFO
		     readPrnID(ginfo->PrinterInfo);
#else
		     memset(ginfo->PrinterInfo, 0, sizeof(ginfo->PrinterInfo));
#endif
#else
			if (strlen(nvram_safe_get("u2ec_mfg")) && strlen(nvram_safe_get("u2ec_device")))
			{
				if (strstr(nvram_safe_get("u2ec_device"), nvram_safe_get("u2ec_mfg")))
					sprintf(ginfo->PrinterInfo, "%s", nvram_safe_get("u2ec_device"));
				else
					sprintf(ginfo->PrinterInfo, "%s %s", nvram_safe_get("u2ec_mfg"), nvram_safe_get("u2ec_device"));
			}
#endif
		     /* get disk type */
#ifdef RTCONFIG_WIRELESSREPEATER
			if (nvram_get_int("sw_mode") == SW_MODE_REPEATER)
			{
				snprintf(prefix, sizeof(prefix), "wl%d.1_", nvram_get_int("wlc_band"));
				strcpy(ssid_g, nvram_safe_get(strcat_r(prefix, "ssid", tmp)));
			}
			else
#endif
			strcpy(ssid_g, nvram_safe_get("wl0_ssid"));
		     strcpy(productid_g, get_productid());
		     strcpy(ginfo->SSID, ssid_g);
		     strcpy(ginfo->NetMask, get_lan_netmask());
		     strcpy(ginfo->ProductID, productid_g);	// disable for tmp
		     strcpy(ginfo->FirmwareVersion, firmver_g);	// disable for tmp
		     memcpy(ginfo->MacAddress, mac, 6);
#ifdef WCLIENT
		     ginfo->OperationMode = OPERATION_MODE_WB;
		     ginfo->Regulation = 0xff;
#endif
	#ifdef WAVESERVER
	     st = (STORAGE_INFO_T *) (pdubuf_res + sizeof (IBOX_COMM_PKT_RES) + sizeof (PKT_GET_INFO) + sizeof(WS_INFO_T));
	#else
	     st = (STORAGE_INFO_T *) (pdubuf_res + sizeof (IBOX_COMM_PKT_RES) + sizeof (PKT_GET_INFO));
	#endif
	//printf("get storage status(1)\n");	// tmp test
		     getStorageStatus(st);
//#endif /* #ifdef WL700G */
 		     /* Disable  WSC functions for MFG test*/
		     nvram_set("asus_mfg", "1");
/*
		     nvram_set("wsc_config_state", "1");
		     system("killall wsccmd");
		     system("killall wsc");
		     system("killall upnp");
		     system("killall ntp");
	 	     system("killall ntpclient");
		     system("killall lld2d");
*/
		     sendInfo(sockfd, pdubuf_res);
		     return pdubuf_res;

		case NET_CMD_ID_GETINFO:
			_dprintf("NET CMD GETINFO\n");
		     ginfo=(PKT_GET_INFO *)(pdubuf_res+sizeof(IBOX_COMM_PKT_RES));
		     memset(ginfo, 0, sizeof(ginfo));
#if 0
#ifdef PRNINFO
    		     readPrnID(ginfo->PrinterInfo);
#else
		     memset(ginfo->PrinterInfo, 0, sizeof(ginfo->PrinterInfo));
#endif
#else
			if (strlen(nvram_safe_get("u2ec_mfg")) && strlen(nvram_safe_get("u2ec_device")))
			{
				if (strstr(nvram_safe_get("u2ec_device"), nvram_safe_get("u2ec_mfg")))
					sprintf(ginfo->PrinterInfo, "%s", nvram_safe_get("u2ec_device"));
				else
					sprintf(ginfo->PrinterInfo, "%s %s", nvram_safe_get("u2ec_mfg"), nvram_safe_get("u2ec_device"));
			}
#endif
#ifdef RTCONFIG_WIRELESSREPEATER
			if (nvram_get_int("sw_mode") == SW_MODE_REPEATER)
			{
				snprintf(prefix, sizeof(prefix), "wl%d.1_", nvram_get_int("wlc_band"));
				strcpy(ssid_g, nvram_safe_get(strcat_r(prefix, "ssid", tmp)));
			}
			else
#endif
			strcpy(ssid_g, nvram_safe_get("wl0_ssid"));
		     strcpy(productid_g, get_productid());
   		     strcpy(ginfo->SSID, ssid_g);
		     strcpy(ginfo->NetMask, get_lan_netmask());
		     strcpy(ginfo->ProductID, productid_g);	// disable for tmp
		     strcpy(ginfo->FirmwareVersion, firmver_g); // disable for tmp
		     memcpy(ginfo->MacAddress, mac, 6);
#ifdef WCLIENT
		     ginfo->OperationMode = OPERATION_MODE_WB;
		     ginfo->Regulation = 0xff;
#endif

#ifdef WAVESERVER    // eric++
	     	     // search /tmp/waveserver and get information
	     	     wsinfo = (WS_INFO_T*) (pdubuf_res + sizeof (IBOX_COMM_PKT_RES) + sizeof (PKT_GET_INFO));

	     	     fd = open (WS_INFO_FILENAME, O_RDONLY);
	     	     if (fd != -1)	{
				bytes = sizeof (WS_INFO_T);
				while (bytes > 0)	{
			    	ret = read (fd, wsinfo, bytes); 
		    		if (ret > 0)			{ bytes -= ret;		} 
					else if (ret < 0)		{ fail++; break;	} 
					else if (ret == 0)		{ fail++; break;	}
		 		} /* while () */
			} else {
				fail++;
			}

			if (fail == 0 && bytes == 0)	{
				ret = read (fd, &pid, sizeof (pid_t));
				if (ret == sizeof (pid_t))	{
			    	sprintf (tmp_buf, "/proc/%d", pid);
			    	dir = opendir (tmp_buf);
			    	if (dir == NULL)	{	// file exist, but the process had been killed
		    		    fail++;
				    }
				    closedir (dir);
				} else {	// file not found or error occurred
					fail++;
				}
	   		}

			if (fail != 0)	{
		    		memset (wsinfo, 0, sizeof (WS_INFO_T));
			}
#endif /* #ifdef WAVESERVER */
	#ifdef WAVESERVER
	     		st = (STORAGE_INFO_T *) (pdubuf_res + sizeof (IBOX_COMM_PKT_RES) + sizeof (PKT_GET_INFO) + sizeof(WS_INFO_T));
	#else
	     		st = (STORAGE_INFO_T *) (pdubuf_res + sizeof (IBOX_COMM_PKT_RES) + sizeof (PKT_GET_INFO));
	#endif
		  	getStorageStatus(st);
			sendInfo(sockfd, pdubuf_res);
			return pdubuf_res;		     	

		case NET_CMD_ID_GETINFO_EX2:
		     _dprintf("\n we got case GETINFO_EX2\n");	// tmp test
		     ginfo=(PKT_GET_INFO *)(pdubuf_res+sizeof(IBOX_COMM_PKT_RES));
		     memset(ginfo, 0, sizeof(ginfo));
		     memset(ginfo->PrinterInfo, 0, sizeof(ginfo->PrinterInfo));

		     /* get disk type */
		     memset(ftype, 0, sizeof(ftype));
		     memset(prinfo, 0, sizeof(prinfo));
		     free_space = get_ftype(ftype);
		     _dprintf("get ftpye is %s, free = %d\n", ftype, free_space);
		     sprintf(prinfo, "%s:%d!$", ftype, free_space);
		     memcpy(ginfo->PrinterInfo, prinfo, strlen(prinfo));

		     sendInfo(sockfd, pdubuf_res);
		     return pdubuf_res;		     	
#ifdef WCLIENT	
		case NET_CMD_ID_GETINFO_EX:
		     cmd = (PKT_GET_INFO_EX1 *)(pdubuf+sizeof(IBOX_COMM_PKT_HDR_EX));	
		     res = (PKT_GET_INFO_EX1 *)(pdubuf_res+sizeof(IBOX_COMM_PKT_RES_EX));
		     stainfo = (PKT_GET_INFO_STA *)(pdubuf_res+sizeof(IBOX_COMM_PKT_RES_EX)+sizeof(PKT_GET_INFO_EX1));
				
		     if (cmd->FieldID!=FIELD_GENERAL_CURRENT_STA) return NULL;
		     res->FieldCount=1;
		     res->FieldID=FIELD_GENERAL_CURRENT_STA;

		     memcpy(stainfo, &stainfo_g, sizeof(stainfo_g));
		     stainfo->connectionStatus = sta_status();
		     _dprintf("GetSTA: %s\n", stainfo->ssid);
			
		     sendInfo(sockfd, pdubuf_res);
		     return pdubuf_res;
		case NET_CMD_ID_SETINFO:				
		     cmd=(PKT_GET_INFO_EX1 *)(pdubuf+sizeof(IBOX_COMM_PKT_HDR_EX));			
		     stainfo = (PKT_GET_INFO_STA *)(pdubuf+sizeof(IBOX_COMM_PKT_HDR_EX)+sizeof(PKT_GET_INFO_EX1));
		     _dprintf("SSID: %s\n", stainfo->ssid);
		     sendInfo(sockfd, pdubuf_res);
		     return pdubuf_res;
		case NET_CMD_ID_GETINFO_SITES:				
		     cmd=(PKT_GET_INFO_EX1 *)(pdubuf+sizeof(IBOX_COMM_PKT_HDR_EX));	
		     res_sites = (PKT_GET_INFO_SITES *)(pdubuf_res+sizeof(IBOX_COMM_PKT_RES_EX));
		     sta_start_scanning();
		     //sta_count_reset();
		     sleep(2);	
		     wl_scan_results();

		     _dprintf("Get INFO %d\n", sites_g_count);

		     res_sites->Count = sites_g_count;
	
		     for (i=0;i<res_sites->Count&&i<MAX_SITE_NUMBER;i++)
		     {
			 memcpy(&res_sites->Sites[i%8], &sites_g[i], sizeof(SITES));				 
			 if (i%8==0&&i!=0)
			 {
			 	res_sites->Index = i/8;
		     		sendInfo(sockfd, pdubuf_res);
			 } 	
		     }
		     if (i%8!=0)
		     {
			 res_sites->Index = i/8;
		     	 sendInfo(sockfd, pdubuf_res);
			 _dprintf("Send:%d %d\n", res_sites->Index, res_sites->Count);
		     }	
		     return pdubuf_res;
		case NET_CMD_ID_GETINFO_PROF:		     
		     cmd_profiles = (PKT_GET_INFO_PROFILE *)(pdubuf+sizeof(IBOX_COMM_PKT_HDR_EX));	
		     res_profiles = (PKT_GET_INFO_PROFILE *)(pdubuf_res+sizeof(IBOX_COMM_PKT_RES_EX));
		     res_profiles->StartIndex = cmd_profiles->StartIndex;
		     res_profiles->Count = cmd_profiles->Count;
		     for (i=0;i<cmd_profiles->Count;i++)
		     {
			 memcpy(&res_profiles->p.Profiles[i], &profiles_g[cmd_profiles->StartIndex+i], sizeof(PROFILES));
		     }
		     sendInfo(sockfd, pdubuf_res);
		     return pdubuf_res;
		case NET_CMD_ID_SETINFO_PROF:
		     cmd_profiles =(PKT_GET_INFO_PROFILE *)(pdubuf+sizeof(IBOX_COMM_PKT_HDR_EX));	
		     res_profiles = (PKT_GET_INFO_SITES *)(pdubuf_res+sizeof(IBOX_COMM_PKT_RES_EX));

		     if (cmd_profiles->Count==0)
		     {
			 if (cmd_profiles->StartIndex == 0xff) // Save to file
			 {
			 }
			 else 
			 {
				 scan_g_type = cmd_profiles->p.ProfileControl.ButtonType;
				 scan_g_mode = cmd_profiles->p.ProfileControl.ButtonMode;
				 stainfo_g.profileCount = cmd_profiles->p.ProfileControl.ProfileCount;

				 sta_start_connecting_one(&profiles_g[cmd_profiles->StartIndex]);
				 //printf("set: %d %d\n", cmd_profiles->StartIndex, stainfo_g.profileCount);
				
				 profiles_g_count = stainfo_g.profileCount;
				 wl_write_profile();				 
			 }
		     }		
		     else
		     {	 	
		     	 for (i=0;i<cmd_profiles->Count;i++)
		     	 {
				memcpy(&profiles_g[cmd_profiles->StartIndex + i], &cmd_profiles->p.Profiles[i], sizeof(PROFILES));
		     	 }
		     }	 	
		     sendInfo(sockfd, pdubuf_res);
		     return pdubuf_res;
#endif
		case NET_CMD_ID_MANU_CMD:
		{
		     #define MAXSYSCMD 256
		     char cmdstr[MAXSYSCMD];
		     PKT_SYSCMD *syscmd;
		     PKT_SYSCMD_RES *syscmd_res;
		     FILE *fp;

printf("1. NET_CMD_ID_MANU_CMD:\n");
_dprintf("2. NET_CMD_ID_MANU_CMD:\n");
fprintf(stderr, "3. NET_CMD_ID_MANU_CMD:\n");

		     syscmd = (PKT_SYSCMD *)(pdubuf+sizeof(IBOX_COMM_PKT_HDR_EX));
		     syscmd_res = (PKT_SYSCMD_RES *)(pdubuf_res+sizeof(IBOX_COMM_PKT_RES_EX));

		     if (syscmd->len>=MAXSYSCMD) syscmd->len=MAXSYSCMD;
		     syscmd->cmd[syscmd->len]=0;
		     syscmd->len=strlen(syscmd->cmd);
		     fprintf(stderr,"system cmd: %d %s\n", syscmd->len, syscmd->cmd);
#if 0
		     if (!strcmp(syscmd->cmd, "GetAliveUsbDeviceInfo"))
		     {
		     	// response format: "USB device name","current status of the device","IP of cccupied user"
			if (nvram_match("u2ec_device", ""))
				sprintf(syscmd_res->res, "\"%s\",\"%s\"", "", "");
			else if (nvram_invmatch("u2ec_busyip", ""))
//				sprintf(syscmd_res->res, "\"%s\",\"%s\",\"%s\"", nvram_safe_get("u2ec_device"), "Busy", nvram_safe_get("u2ec_busyip"));
				sprintf(syscmd_res->res, "\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"", ssid_g, productid_g, nvram_safe_get("u2ec_device"), "Busy", nvram_safe_get("u2ec_busyip"));
			else
//				sprintf(syscmd_res->res, "\"%s\",\"%s\"", nvram_safe_get("u2ec_device"), "Idle");
				sprintf(syscmd_res->res, "\"%s\",\"%s\",\"%s\",\"%s\"", ssid_g, productid_g, nvram_safe_get("u2ec_device"), "Idle");
			syscmd_res->len = strlen(syscmd_res->res);
			_dprintf("%d %s\n", syscmd_res->len, syscmd_res->res);
//			kill_pidfile_s("/var/run/usdsvr_broadcast.pid", SIGUSR1);
			sendInfo(sockfd, pdubuf_res);
		     }
		     else if (!strncmp(syscmd->cmd, "ClientPostMsg ", 14))
		     {
			char userip[16];
		     	char usermsg[256];
		     	char *p;
		     	int flag_invalid = 0;

			/* format: ClientPostMsg"Occupied User IP","ClientMsg" */
			memset(userip, 0x0, 16);
			memset(usermsg, 0x0, 256);
			strncpy(userip, syscmd->cmd + 15, 16);	// skip "ClientPostMsg \""

			if (p = strchr(userip, '"'))
				*p = '\0';
			else			// invalid format
			{
				flag_invalid = 1;
				strcpy(userip, "255.255.255.255");
			}

			if (!flag_invalid)	// skip "ClientPostMsg\"Occupied User IP\",\""
			{
				strcpy(usermsg, syscmd->cmd + 15 + strlen(userip) + 3);
				if (strlen(usermsg) > 1)
					usermsg[strlen(usermsg) - 1] = '\0';
			}
			else
				strcpy(usermsg, "invalid message format!");

			if (!strcmp(userip, "255.255.255.255"))
			{
				nvram_set("u2ec_msg_broadcast", usermsg);
				kill_pidfile_s("/var/run/usdsvr_broadcast.pid", SIGUSR2);
			}
			else
			{
				nvram_set("u2ec_clntip_unicast", userip);
				nvram_set("u2ec_msg_unicast", usermsg);
				kill_pidfile_s("/var/run/usdsvr_unicast.pid", SIGTSTP);
			}

//			strcpy(syscmd_res->res, usermsg);
//		     	syscmd_res->len = strlen(syscmd_res->res);
//		     	_dprintf("client ip: %s\n", userip);
//			_dprintf("%d %s\n", syscmd_res->len, syscmd_res->res);
//			sendInfo(sockfd, pdubuf_res);
		     }
		     else
#endif
		     {
			sprintf(cmdstr, "%s > /tmp/syscmd.out", syscmd->cmd);
			system(cmdstr);

			fprintf(stderr,"rund: %s\n", cmdstr);
			fp = fopen("/tmp/syscmd.out", "r");

			if (fp!=NULL)
			{
				syscmd_res->len = fread(syscmd_res->res, 1, sizeof(syscmd_res->res), fp);
				fclose(fp);
			}
			else syscmd_res->len=0;

			fprintf(stderr,"%d %s\n", syscmd_res->len, syscmd_res->res);
			/* repeat 3 times for MFG by Yen*/
			sendInfo(sockfd, pdubuf_res);
			sendInfo(sockfd, pdubuf_res);
			sendInfo(sockfd, pdubuf_res);
			if(strstr(syscmd->cmd, "Commit")) {
				int x=0;
				while(x<7) {
					sendInfo(sockfd, pdubuf_res);
					x++;
				}
			}
			/* end of MFG */
			fprintf(stderr,"\nSendInfo 3 times!\n");
		     }
	 	     return pdubuf_res;
		}
#ifdef BTN_SETUP // This option can not co-exist with WCLIENT
		case NET_CMD_ID_SETKEY_EX:
		{
		     #define MAXSYSCMD 256
		     char cmdstr[MAXSYSCMD];
		     PKT_SET_INFO_GW_QUICK_KEY *pkey;
		     PKT_SET_INFO_GW_QUICK_KEY *pkey_res;

		     if (!is_setup_mode(BTNSETUP_START)) return NULL;
		     pkey=(PKT_SET_INFO_GW_QUICK_KEY *)(pdubuf+sizeof(IBOX_COMM_PKT_HDR_EX));
		     pkey_res = (PKT_SET_INFO_GW_QUICK_KEY *)(pdubuf_res+sizeof(IBOX_COMM_PKT_RES_EX));

#ifdef ENCRYPTION
		     if (pkey->KeyLen==0) return NULL;

#else
		     pkey_res->KeyLen=0;
#endif
		     sprintf(cmdstr, "%2x%2x%2x%2x%2x%2x\n",
				(unsigned char)phdr_ex->MacAddress[0],
				(unsigned char)phdr_ex->MacAddress[1],
				(unsigned char)phdr_ex->MacAddress[2],
				(unsigned char)phdr_ex->MacAddress[3],
				(unsigned char)phdr_ex->MacAddress[4],
				(unsigned char)phdr_ex->MacAddress[5]
				);
		     nvram_set("bs_mac", cmdstr);
		     sprintf(cmdstr, "Set MAC %s", cmdstr);
		     syslog(LOG_NOTICE, cmdstr);
		     sendInfo(sockfd, pdubuf_res);
		     return pdubuf_res;
		}
		case NET_CMD_ID_QUICKGW_EX:
		{
		     #define MAXSYSCMD 64
		     char cmdstr[MAXSYSCMD];
		     PKT_SET_INFO_GW_QUICK *gwquick;
		     PKT_SET_INFO_GW_QUICK *gwquick_res;

		     if (!is_setup_mode(BTNSETUP_DATAEXCHANGE)) return NULL;
		     gwquick=(PKT_SET_INFO_GW_QUICK *)(pdubuf+sizeof(IBOX_COMM_PKT_HDR_EX));
		     gwquick_res = (PKT_SET_INFO_GW_QUICK *)(pdubuf_res+sizeof(IBOX_COMM_PKT_RES_EX));

#ifdef ENCRYPTION
		     if (gwquick->QuickFlag&QFCAP_ENCRYPTION)
		     {
			   // DECRYPTION first
		     }
		     else return NULL	
#endif

		     bs_put_setting(gwquick);

		     if (!(gwquick->QuickFlag&QFCAP_WIRELESS)) // get setting
		     	 bs_get_setting(gwquick_res);
		     else memcpy(gwquick_res, gwquick, sizeof(PKT_SET_INFO_GW_QUICK));

#ifdef ENCRYPTION
		     // ENCRYPTION first
		     gwquick_res->QuickFlag = (QFCAP_ENCRYPTION|QFCAP_WIRELESS);
#else
		     gwquick_res->QuickFlag = (QFCAP_WIRELESS);
#endif	
		     sendInfo(sockfd, pdubuf_res);
		     return pdubuf_res;
		}
#endif
		default:
			return NULL;	
	}
    }
    return NULL;
}
Example #3
0
int main(int argc, char **argv)
{
	char *base;
	int f;

	/*
		Make sure std* are valid since several functions attempt to close these
		handles. If nvram_*() runs first, nvram=0, nvram gets closed. - zzz
	*/
	if ((f = open("/dev/null", O_RDWR)) < 3) {
		dup(f);
		dup(f);
	}
	else {
		close(f);
	}

	base = strrchr(argv[0], '/');
	base = base ? base + 1 : argv[0];

#if 0
	if (strcmp(base, "rc") == 0) {
		if (argc < 2) return 1;
		if (strcmp(argv[1], "start") == 0) return kill(1, SIGUSR2);
		if (strcmp(argv[1], "stop") == 0) return kill(1, SIGINT);
		if (strcmp(argv[1], "restart") == 0) return kill(1, SIGHUP);
		++argv;
		--argc;
		base = argv[0];
	}
#endif

#if defined(DEBUG_NOISY)
	if (nvram_match("debug_logrc", "1")) {
		int i;

		cprintf("[rc %d] ", getpid());
		for (i = 0; i < argc; ++i) {
			cprintf("%s ", argv[i]);
		}
		cprintf("\n");

	}
#endif

#if defined(DEBUG_NOISY)
	if (nvram_match("debug_ovrc", "1")) {
		char tmp[256];
		char *a[32];

		realpath(argv[0], tmp);
		if ((strncmp(tmp, "/tmp/", 5) != 0) && (argc < 32)) {
			sprintf(tmp, "%s%s", "/tmp/", base);
			if (f_exists(tmp)) {
				cprintf("[rc] override: %s\n", tmp);
				memcpy(a, argv, argc * sizeof(a[0]));
				a[argc] = 0;
				a[0] = tmp;
				execvp(tmp, a);
				exit(0);
			}
		}
	}
#endif

	const applets_t *a;
	for (a = applets; a->name; ++a) {
		if (strcmp(base, a->name) == 0) {
			openlog(base, LOG_PID, LOG_USER);
			return a->main(argc, argv);
		}
	}


	if(!strcmp(base, "restart_wireless")){
		printf("restart wireless...\n");
		restart_wireless();
		return 0;
	}
#ifdef RTCONFIG_USB
	else if(!strcmp(base, "get_apps_name")){
		if(argc != 2){
			printf("Usage: get_apps_name [File name]\n");
			return 0;
		}

		return get_apps_name(argv[1]);
	}
	else if(!strcmp(base, "asus_sd")){
		if(argc != 3){
			printf("Usage: asus_sd [device_name] [action]\n");
			return 0;
		}

		return asus_sd(argv[1], argv[2]);
	}
	else if(!strcmp(base, "asus_lp")){
		if(argc != 3){
			printf("Usage: asus_lp [device_name] [action]\n");
			return 0;
		}

		return asus_lp(argv[1], argv[2]);
	}
	else if(!strcmp(base, "asus_sg")){
		if(argc != 3){
			printf("Usage: asus_sg [device_name] [action]\n");
			return 0;
		}

		return asus_sg(argv[1], argv[2]);
	}
	else if(!strcmp(base, "asus_sr")){
		if(argc != 3){
			printf("Usage: asus_sr [device_name] [action]\n");
			return 0;
		}

		return asus_sr(argv[1], argv[2]);
	}
	else if(!strcmp(base, "asus_tty")){
		if(argc != 3){
			printf("Usage: asus_tty [device_name] [action]\n");
			return 0;
		}

		return asus_tty(argv[1], argv[2]);
	}
	else if(!strcmp(base, "asus_usbbcm")){
		if(argc != 3){
			printf("Usage: asus_usbbcm [device_name] [action]\n");
			return 0;
		}

		return asus_usbbcm(argv[1], argv[2]);
	}
	else if(!strcmp(base, "asus_usb_interface")){
		if(argc != 3){
			printf("Usage: asus_usb_interface [device_name] [action]\n");
			return 0;
		}

		return asus_usb_interface(argv[1], argv[2]);
	}
#endif
	else if(!strcmp(base, "run_app_script")){
		if(argc != 3){
			printf("Usage: run_app_script [Package name | allpkg] [APP action]\n");
			return 0;
		}

		if(!strcmp(argv[1], "allpkg"))
			return run_app_script(NULL, argv[2]);
		else
			return run_app_script(argv[1], argv[2]);
	}
	else if(!strcmp(base, "ATE")) {
		if( argc == 2 || argc == 3 || argc == 4) {
			asus_ate_command(argv[1], argv[2], argv[3]);
		}
		else
			printf("ATE_ERROR\n");
                return 0;
	}
#ifdef RTCONFIG_DSL
	else if(!strcmp(base, "gen_ralink_config")){
		if(argc != 3){
			printf("Usage: gen_ralink_config [band] [is_iNIC]\n");
			return 0;
		}
		return gen_ralink_config(atoi(argv[1]), atoi(argv[2]));
	}
#endif
	else if(!strcmp(base, "run_telnetd")) {
		run_telnetd();
		return 0;
	}
#if defined(RTCONFIG_PPTPD) || defined(RTCONFIG_ACCEL_PPTPD)
	else if(!strcmp(base, "run_pptpd")) {
		start_pptpd();
		return 0;
	}
#endif
#ifdef RTCONFIG_PARENTALCTRL
	else if(!strcmp(base, "pc")) {
		pc_main(argc, argv);
		return 0;
	}
#endif
#ifdef RTCONFIG_WIRELESSREPEATER
	else if (!strcmp(base, "wlcscan")) {
		return wlcscan_main();
	}
	else if (!strcmp(base, "wlcconnect")) {
		return wlcconnect_main();
	}
	else if (!strcmp(base, "setup_dnsmq")) {
		if(argc != 2)
			return 0;

		return setup_dnsmq(atoi(argv[1]));
	}
#endif
#ifdef RTCONFIG_BCMWL6
#ifdef ACS_ONCE
        else if (!strcmp(base, "acsd_restart_wl")) {
		restart_wireless_acsd();
		return 0;
        }
#endif
#endif
	else if (!strcmp(base, "add_multi_routes")) {
		return add_multi_routes();
	}
#ifndef OVERWRITE_DNS
	else if (!strcmp(base, "add_ns")) {
		return add_ns(argv[1]);
	}
	else if (!strcmp(base, "del_ns")) {
		return del_ns(argv[1]);
	}
#endif
	else if (!strcmp(base, "led_ctrl")) {
		return(led_control(atoi(argv[1]), atoi(argv[2])));
	}
	else if (!strcmp(base, "free_caches")) {
		int c;
		unsigned int test_num;
		char *set_value = NULL;
		int clean_time = 1;
		int threshold = 0;

		if(argc){
			while((c = getopt(argc, argv, "c:w:t:")) != -1){
				switch(c){
					case 'c': // set the clean-cache mode: 0~3.
						test_num = strtol(optarg, NULL, 10);
        		if(test_num == LONG_MIN || test_num == LONG_MAX){
        			_dprintf("ERROR: unknown value %s...\n", optarg);
							return 0;
						}

						if(test_num < 0 || test_num > 3){
							_dprintf("ERROR: the value %s was over the range...\n", optarg);
							return 0;
						}

						set_value = optarg;

						break;
					case 'w': // set the waited time for cleaning.
						test_num = strtol(optarg, NULL, 10);
        		if(test_num <= 0 || test_num == LONG_MIN || test_num == LONG_MAX){
        			_dprintf("ERROR: unknown value %s...\n", optarg);
							return 0;
						}

						clean_time = test_num;

						break;
					case 't': // set the waited time for cleaning.
						test_num = strtol(optarg, NULL, 10);
        		if(test_num < 0 || test_num == LONG_MIN || test_num == LONG_MAX){
        			_dprintf("ERROR: unknown value %s...\n", optarg);
							return 0;
						}

						threshold = test_num;

						break;
					default:
						fprintf(stderr, "Usage: free_caches [ -c clean_mode ] [ -w clean_time ] [ -t threshold ]\n");
						break;
				}
			}
		}

		if(!set_value)
			set_value = FREE_MEM_PAGE;

		free_caches(set_value, clean_time, threshold);

		return 0;
	}
	printf("Unknown applet: %s\n", base);
	return 0;
}
Example #4
0
static int ntpsync_main(int argc, char **argv)
{
	char *servers, *t, *p;
	char *addr[10];
	char *ips;
	char *nvkiss;
	int count;
	int i;
	struct hostent *he;
	struct in_addr ia;
	int retries;
	int nu;
	char s[512];
	time_t tt;
	struct tm *tms;
	enum { USER, INIT, CRON } mode;

	nu = nvram_get_int("ntp_updates");

	mode = USER;
	if (argc == 2) {
		if (strcmp(argv[1], "--cron") == 0) {		// try for a few minutes
			if (nu <= 0) {
				eval("cru", "d", "ntpsync");
				return 0;
			}
			mode = CRON;
		}
		else if (strcmp(argv[1], "--init") == 0) {	// try forever, schedule cron job
			if (fork() != 0) return 0;
			mode = INIT;
		}
		else {
			return 1;
		}
	}
	else if (argc != 1) {
		return 1;
	}

	_dprintf("[ntpsync %ld] start\n", get_uptime());

	if ((get_wan_proto() != WP_DISABLED) && (mode != INIT) &&
		(!check_wanup()) && (nvram_match("ntp_tdod", "0"))) {
		_dprintf("WAN is down, not updating.");
		return 1;
	}

	srand(time(0));
	retries = 0;

	while (1) {
		_dprintf("[ntpsync %ld] while\n", get_uptime());

		count = 0;

		servers = p = strdup(nvram_safe_get("ntp_server"));

		if (!servers) {
			printf("Not enough memory\n");
			return 1;
		}
		while ((count < 10) && ((t = strsep(&p, " ")) != NULL)) {
			if (*t != 0) addr[count++] = t;
		}
		if (count == 0) addr[count++] = "pool.ntp.org";

		while (count > 0) {
			i = (rand() % count);
			_dprintf("[ntpsync] i=%d addr=%s\n", i, addr[i]);

			if ((he = gethostbyname(addr[i])) != NULL) {
				memcpy(&ia, he->h_addr_list[0], sizeof(ia));
				ips = inet_ntoa(ia);
				_dprintf("ip = %s\n", ips);

				nvkiss = nvram_safe_get("ntp_kiss");
				if (find_word(nvkiss, ips)) {
					_dprintf("kiss: %s\n", ips);
				}
				else {
					switch (ntpc(ia)) {
					case 0:
						_dprintf("[ntpsync] %ld OK\n", get_uptime());
						if (mode == INIT) {
							tt = time(0);
							if ((nu > 0) && ((tms = localtime(&tt)) != NULL)) {

								// add some randomness to make the servers happier / avoid the xx:00 rush
								sprintf(s, "%d ", (tms->tm_min + 20 + (rand() % 20)) % 60);

								// schedule every nu hours
								for (i = 0; i < 24; ++i) {
									if ((i % nu) == 0) sprintf(s + strlen(s), "%s%d", i ? "," : "", (i + tms->tm_hour + 1)  % 24);
								}
								strcat(s, " * * * ntpsync --cron");
								eval("cru", "a", "ntpsync", s);
							}
						}

						// make sure access restriction is ok
						eval("rcheck");
						_dprintf("[ntpsync] %ld exit\n", get_uptime());
						return 0;
					case 2:
						while ((nvkiss) && (strlen(nvkiss) > 128)) nvkiss = strchr(nvkiss + 1, ' ');
						if (nvkiss) strlcpy(s, nvkiss, sizeof(s));
							else s[0] = 0;
						add_word(s, ips, sizeof(s));
						nvram_set("ntp_kiss", s);
						syslog(LOG_WARNING, "Received a kiss of death packet from %s (%s).", addr[i], ips);
						break;
					}
				}
			}

			addr[i] = addr[--count];
		}
		free(servers);

		if (mode == USER) break;
		if ((mode == CRON) && (retries == 5)) break;

		if (++retries > 300) retries = 300;		// 5m
		_dprintf("[ntpsync %ld] sleep=%d\n", get_uptime(), retries);
		sleep(retries);
	}

	_dprintf("[ntpsync] %ld exit\n", get_uptime());
	return 1;
}
Example #5
0
void sta_start_scanning_profile(int is_next)
{
	int i, j, cand=-1, cand_rssi=-248, pref;
	char ssid[33], ssids[33];
	
	ssid[32] = ssids[32] = 0;

	if (is_next) sta_scan++;
	else sta_scan = 0;

	pref = atoi(nvram_safe_get("wlp_pref_x"));
		
	// scan each entry in profiles actively
	for (i=0;i<profiles_g_count;i++)
	{
		memcpy(ssid, profiles_g[i].ssid, 32);
		ssid[32] = 0;
		_dprintf("find: %s %d %d\n", ssid, profiles_g[i].wep, profiles_g[i].wepkeylen);
		doSystem("wl scan %s", ssid);
		sleep(1);
		wl_scan_results();

		for (j=0;j<sites_g_count;j++)
		{
			memcpy(ssids, sites_g[j].SSID, 32);

			_dprintf("scaned: %s %d\n", ssids, sites_g[j].RSSI);
			
			if (!strcmp(ssid, ssids) && 
				sites_g[j].RSSI>cand_rssi &&
				cand != pref)
			{
				cand = i;
				cand_rssi = sites_g[j].RSSI;
				break;
			}
		}
	}	

	if (cand==-1)
	{
		for (i=0;i<profiles_g_count;i++)
		{
			if (profiles_g[i].mode == STATION_MODE_ADHOC)
			{
				cand = i;
				break;
			}	
		}
	}

	if (cand!=-1)
	{	
		_dprintf("connect to one : %d\n", cand);	
		sta_start_connecting_one(&profiles_g[cand]);
	}
	else if (sta_scan<3) // totally, 3 chances to try
	{
		_dprintf("try : %d\n", sta_scan);	
		time(&sta_timer);
		sta_state = STA_STATE_SCANNING_PROFILE;
		sta_status_report(sta_state, 0);
	}
	else if (nvram_match("wlp_beap_x", "1")) sta_start_being_ap();
	else sta_start_scanning();
}
Example #6
0
static void wo_tomato(char *url)
{
	char *v;
	int i;
	int ajax;
	int nvset;
	const char *red;
	int commit;

//	_dprintf("tomato.cgi\n");

	red = webcgi_safeget("_redirect", "");
	if (!*red) send_header(200, NULL, mime_html, 0);

	commit = atoi(webcgi_safeget("_commit", "1"));
	ajax = atoi(webcgi_safeget("_ajax", "0"));

	nvset = atoi(webcgi_safeget("_nvset", "1"));
	if (nvset) {
		if (!save_variables(0)) {
			if (ajax) {
				web_printf("@msg:%s", resmsg_get());
			}
			else {
				parse_asp("error.asp");
			}
			return;
		}
		commit = save_variables(1) && commit;

		resmsg_set("設定已儲存.");
	}

	rboot = atoi(webcgi_safeget("_reboot", "0"));
	if (rboot) {
		parse_asp("reboot.asp");
	}
	else {
		if (ajax) {
			web_printf("@msg:%s", resmsg_get());
		}
		else if (atoi(webcgi_safeget("_moveip", "0"))) {
			parse_asp("saved-moved.asp");
		}
		else if (!*red) {
			parse_asp("saved.asp");
		}
	}

	if (commit) {
		_dprintf("commit from tomato.cgi\n");
		if (!nvram_match("debug_nocommit", "1")) {
			nvram_commit();
		}
	}

	if ((v = webcgi_get("_service")) != NULL) {
		if (!*red) {
			if (ajax) web_printf(" 某些服務已重新啟動...");
			web_close();
		}
		sleep(1);

		if (*v == '*') {
			kill(1, SIGHUP);
		}
		else if (*v != 0) {
			exec_service(v);
		}
	}

	for (i = atoi(webcgi_safeget("_sleep", "0")); i > 0; --i) sleep(1);

	if (*red) redirect(red);

	if (rboot) {
		web_close();
		sleep(1);
		kill(1, SIGTERM);
	}
}
Example #7
0
int exec_for_host(int host, int obsolete, uint flags, host_exec func)
{
	DIR *usb_dev_disc;
	char ptname[32];/* Will be: discDN_PN	 					*/
	char dsname[16];/* Will be: discDN	 					*/
	int host_no;	/* SCSI controller/host # */
	struct dirent *dp;
	FILE *prt_fp;
	int siz;
	char line[256];
	int result = 0;
#ifdef LINUX26
	int ret;
	char hostbuf[16], device_path[PATH_MAX], linkbuf[PATH_MAX], *h;
#else
	char link[256];	/* Will be: ../scsi/host#/bus0/target0/lun#  that bfr links to. */
			/* When calling the func, will be: /dev/discs/disc#/part#	*/
	char bfr[256];	/* Will be: /dev/discs/disc#					*/
	char bfr2[128];	/* Will be: /dev/discs/disc#/disc     for the BLKRRPART.	*/
	char *cp;
	int len;
	int disc_num;	/* Disc # */
	int part_num;	/* Parition # */
	char *mp;	/* Ptr to after any leading ../ path */
#endif

	_dprintf("exec_for_host(%d, %d, %d, %d)\n", host, obsolete, flags, func);
	if (!func)
		return 0;

	flags |= EFH_1ST_HOST;

#ifdef LINUX26
	/* /sys/bus/scsi/devices/X:X:X:X/block:sdX doesn't exist in kernel 3.0
	 * 1. Enumerate sub-directory, DIR, of /sys/block.
	 * 2. Skip ., .., loop*, mtdblock*, ram*, etc.
	 * 3. read DIR/device link. Check whether X:X:X:X exist. e.g.
	 *    56U: ../../devices/platform/rt3xxx-ehci/usb1/1-1/1-1:1.0/host1/target1:0:0/1:0:0:0
	 *    65U: ../../devices/pci0000:00/0000:00:00.0/0000:01:00.0/usb1/1-2/1-2:1.0/host1/target1:0:0/1:0:0:0
	 * 4. If yes, DIR would be sda, sdb, etc.
	 * 5. Search DIR in /proc/partitions.
	 */
	sprintf(hostbuf, "%d:", host);
	if (!(usb_dev_disc = opendir("/sys/block")))
		return 0;
	while ((dp = readdir(usb_dev_disc))) {
		if (!strncmp(dp->d_name, "loop", 4) ||
		    !strncmp(dp->d_name, "mtdblock", 8) ||
		    !strncmp(dp->d_name, "ram", 3) ||
		    !strcmp(dp->d_name, ".") ||
		    !strcmp(dp->d_name, "..")
		   )
			continue;
		snprintf(device_path, sizeof(device_path), "/sys/block/%s/device", dp->d_name);
		if (readlink(device_path, linkbuf, sizeof(linkbuf)) == -1)
			continue;
		h = strstr(linkbuf, "/host");
		if (!h)	continue;
		if ((ret = sscanf(h, "/host%*d/target%*d:%*d:%*d/%d:%*d:%*d:%*d", &host_no)) != 1) {
			_dprintf("%s(): sscanf can't distinguish host_no from [%s]. ret %d\n", __func__, linkbuf, ret);
			continue;
		}
		if (host >= 0 && host != host_no)
			continue;
		snprintf(dsname, sizeof(dsname), dp->d_name);
		siz = strlen(dsname);
		flags |= EFH_1ST_DISC;
		if (!(prt_fp = fopen("/proc/partitions", "r")))
			continue;
		while (fgets(line, sizeof(line) - 2, prt_fp)) {
			if (sscanf(line, " %*s %*s %*s %s", ptname) != 1)
				continue;

			if (!strncmp(ptname, dsname, siz)) {
				if (!strcmp(ptname, dsname) && !is_no_partition(dsname))
					continue;
				sprintf(line, "/dev/%s", ptname);
				result = (*func)(line, host_no, dsname, ptname, flags) || result;
				flags &= ~(EFH_1ST_HOST | EFH_1ST_DISC);
			}
		}
		fclose(prt_fp);
	}
	closedir(usb_dev_disc);

#else	/* !LINUX26 */

	if ((usb_dev_disc = opendir(DEV_DISCS_ROOT))) {
		while ((dp = readdir(usb_dev_disc))) {
			sprintf(bfr, "%s/%s", DEV_DISCS_ROOT, dp->d_name);
			if (strncmp(dp->d_name, "disc", 4) != 0)
				continue;

			disc_num = atoi(dp->d_name + 4);
			len = readlink(bfr, link, sizeof(link) - 1);
			if (len < 0)
				continue;

			link[len] = 0;
			cp = strstr(link, "/scsi/host");
			if (!cp)
				continue;

			host_no = atoi(cp + 10);
			if (host >= 0 && host_no != host)
				continue;

			/* We have found a disc that is on this controller.
			 * Loop thru all the partitions on this disc.
			 * The new way, reading thru /proc/partitions.
			 */
			mp = link;
			if ((cp = strstr(link, "../")) != NULL)
				mp = cp + 3;
			siz = strlen(mp);

			flags |= EFH_1ST_DISC;
			if (func && (prt_fp = fopen("/proc/partitions", "r"))) {
				while (fgets(line, sizeof(line) - 2, prt_fp)) {
					if (sscanf(line, " %*s %*s %*s %s", bfr2) == 1 &&
					    strncmp(bfr2, mp, siz) == 0)
					{
						if ((cp = strstr(bfr2, "/part"))) {
							part_num = atoi(cp + 5);
							sprintf(line, "%s/part%d", bfr, part_num);
							sprintf(dsname, "disc%d", disc_num);
							sprintf(ptname, "disc%d_%d", disc_num, part_num);
						}
						else if ((cp = strstr(bfr2, "/disc"))) {
							*(++cp) = 0;
							if (!is_no_partition(bfr2))
								continue;
							sprintf(line, "%s/disc", bfr);
							sprintf(dsname, "disc%d", disc_num);
							strcpy(ptname, dsname);
						}
						else {
							continue;
						}
						result = (*func)(line, host_no, dsname, ptname, flags) || result;
						flags &= ~(EFH_1ST_HOST | EFH_1ST_DISC);
					}
				}
				fclose(prt_fp);
			}
		}
		closedir(usb_dev_disc);
	}

#endif	/* LINUX26 */

	return result;
}
Example #8
0
static int load_history(const char *fname) {
	_dprintf("%s: fname=%s\n", __FUNCTION__, fname);
	return load_history_to_tree(fname);
}
Example #9
0
ej_lan_ipv6_network_array(int eid, webs_t wp, int argc, char_t **argv)
{
    FILE *fp;
    char buf[64+32+8192+1];
    char *hostname, *macaddr, ipaddrs[8192+1];
    char ipv6_dns_str[1024];
    char *wan_type, *wan_dns, *p;
    int service, i, ret = 0;

    ret += websWrite(wp, "var ipv6cfgarray = [");

    if (!(ipv6_enabled() && is_routing_enabled())) {
        ret += websWrite(wp, "[]];\n");
        ret += websWrite(wp, "var ipv6clientarray = [");
        ret += websWrite(wp, "[]];\n");
        return ret;
    }

    service = get_ipv6_service();
    switch (service) {
    case IPV6_NATIVE_DHCP:
        wan_type = "Native with DHCP-PD";
        break;
    case IPV6_6TO4:
        wan_type = "Tunnel 6to4";
        break;
    case IPV6_6IN4:
        wan_type = "Tunnel 6in4";
        break;
    case IPV6_6RD:
        wan_type = "Tunnel 6rd";
        break;
    case IPV6_MANUAL:
        wan_type = "Static";
        break;
    default:
        wan_type = "Disabled";
        break;
    }

    ret += websWrite(wp, "[\"IPv6 Connection Type\",\"%s\"],", wan_type);

    ret += websWrite(wp, "[\"WAN IPv6 Address\",\"%s\"],",
                     getifaddr((char *) get_wan6face(), AF_INET6, GIF_PREFIXLEN) ? : nvram_safe_get("ipv6_rtr_addr"));


    ret += websWrite(wp, "[\"WAN IPv6 Gateway\",\"%s\"],",
                     ipv6_gateway_address() ? : "");

    ret += websWrite(wp, "[\"LAN IPv6 Address\",\"%s/%d\"],",
                     nvram_safe_get("ipv6_rtr_addr"), nvram_get_int("ipv6_prefix_length"));

    ret += websWrite(wp, "[\"LAN IPv6 Link-Local Address\",\"%s\"],",
                     getifaddr(nvram_safe_get("lan_ifname"), AF_INET6, GIF_LINKLOCAL | GIF_PREFIXLEN) ? : "");

    if (service == IPV6_NATIVE_DHCP) {
        ret += websWrite(wp, "[\"DHCP-PD\",\"%s\"],",
                         nvram_get_int("ipv6_dhcp_pd") ? "Enabled" : "Disabled");
    }

    ret += websWrite(wp, "[\"LAN IPv6 Prefix\",\"%s/%d\"],",
                     nvram_safe_get("ipv6_prefix"), nvram_get_int("ipv6_prefix_length"));

    if (service == IPV6_NATIVE_DHCP &&
            nvram_get_int("ipv6_dnsenable")) {
        wan_dns = nvram_safe_get("ipv6_get_dns");
    } else {
        char nvname[sizeof("ipv6_dnsXXX")];
        char *next = ipv6_dns_str;

        ipv6_dns_str[0] = '\0';
        for (i = 1; i <= 3; i++) {
            snprintf(nvname, sizeof(nvname), "ipv6_dns%d", i);
            wan_dns = nvram_safe_get(nvname);
            if (*wan_dns)
                next += sprintf(next, *ipv6_dns_str ? " %s" : "%s", wan_dns);
        }
        wan_dns = ipv6_dns_str;
    }

    ret += websWrite(wp, "[\"DNS Address\",\"%s\"],", wan_dns);
    ret += websWrite(wp, "[]];\n");

    ret += websWrite(wp, "var ipv6clientarray = [");

    /* Refresh lease file to get actual expire time */
    killall("dnsmasq", SIGUSR2);
    usleep(100 * 1000);

    get_ipv6_client_info();
    get_ipv6_client_list();

    if ((fp = fopen(IPV6_CLIENT_LIST, "r")) == NULL) {
        _dprintf("can't open %s: %s", IPV6_CLIENT_LIST, strerror(errno));
        return ret;
    }

    while (fgets(buf, sizeof(buf), fp) != NULL) {
        char *ptr = buf;

        ptr = strsep(&ptr, "\n");
        hostname = strsep(&ptr, " ");
        macaddr = strsep(&ptr, " ");
        if (!macaddr || *macaddr == '\0' ||
                !ptr || *ptr == '\0')
            continue;

        if (strlen(hostname) > 32)
            sprintf(hostname + 29, "...");

        ipaddrs[0] = '\0';
        p = ipaddrs;
        while (ptr && *ptr) {
            char *next = strsep(&ptr, ",\n");
            if (next && *next)
                p += snprintf(p, sizeof(ipaddrs) + ipaddrs - p, "%s%s", *ipaddrs ? ", " : "", next);
        }

        ret += websWrite(wp, "[\"%s\", \"%s\", \"%s\"],",
                         hostname, macaddr, ipaddrs);
    }
    fclose(fp);

    ret += websWrite(wp, "[]];\n");
    return ret;
}
Example #10
0
static void save(int quick) {
	int i;
	int n;
	int b;
	char hgz[256];
	char tmp[256];
	char bak[256];
	char bkp[256];
	time_t now;
	struct tm *tms;
	static int lastbak = -1;

	_dprintf("%s: quick=%d\n", __FUNCTION__, quick);

	f_write("/var/lib/misc/cstats-stime", &save_utime, sizeof(save_utime), 0, 0);

	n = save_history_from_tree(history_fn);
	_dprintf("%s: saved %d records from tree on file %s\n", __FUNCTION__, n, history_fn);

	_dprintf("%s: write source=%s\n", __FUNCTION__, save_path);
	f_write_string(source_fn, save_path, 0, 0);

	if (quick) {
		return;
	}

	sprintf(hgz, "%s.gz", history_fn);

	if (save_path[0] != 0) {
		strcpy(tmp, save_path);
		strcat(tmp, ".tmp");

		for (i = 15; i > 0; --i) {
			if (!wait_action_idle(10)) {
				_dprintf("%s: busy, not saving\n", __FUNCTION__);
			}
			else {
				_dprintf("%s: cp %s %s\n", __FUNCTION__, hgz, tmp);
				if (eval("cp", hgz, tmp) == 0) {
					_dprintf("%s: copy ok\n", __FUNCTION__);

					if (!nvram_match("rstats_bak", "0")) {
						now = time(0);
						tms = localtime(&now);
						if (lastbak != tms->tm_yday) {
							strcpy(bak, save_path);
							n = strlen(bak);
							if ((n > 3) && (strcmp(bak + (n - 3), ".gz") == 0)) n -= 3;
//							sprintf(bak + n, "_%d.bak", ((tms->tm_yday / 7) % 3) + 1);
//							if (eval("cp", save_path, bak) == 0) lastbak = tms->tm_yday;
							strcpy(bkp, bak);
							for (b = HI_BACK-1; b > 0; --b) {
								sprintf(bkp + n, "_%d.bak", b + 1);
								sprintf(bak + n, "_%d.bak", b);
								rename(bak, bkp);
							}
							if (eval("cp", "-p", save_path, bak) == 0) lastbak = tms->tm_yday;
						}
					}

					_dprintf("%s: rename %s %s\n", __FUNCTION__, tmp, save_path);
					if (rename(tmp, save_path) == 0) {
						_dprintf("%s: rename ok\n", __FUNCTION__);
						break;
					}
				}
			}

			// might not be ready
			sleep(3);
			if (gotterm) break;
		}
	}
}
Example #11
0
static int load_history_to_tree(const char *fname) {
	int n;
	FILE *f;
	char s[256];
	Node tmp;
	Node *ptr;
	char *exclude;

	exclude = nvram_safe_get("cstats_exclude");
	_dprintf("%s: cstats_exclude='%s'\n", __FUNCTION__, exclude);
	_dprintf("%s: fname=%s\n", __FUNCTION__, fname);
	unlink(uncomp_fn);

	n = -1;	// Initial value, will be returned if we failed to parse a data file
	sprintf(s, "gzip -dc %s > %s", fname, uncomp_fn);
	if (system(s) == 0) {
		if ((f = fopen(uncomp_fn, "rb")) != NULL) {
			n = 0;	// Initial counter
			while (fread(&tmp, sizeof(Node), 1, f) > 0) {
				if ((find_word(exclude, tmp.ipaddr))) {
					_dprintf("%s: not loading excluded ip '%s'\n", __FUNCTION__, tmp.ipaddr);
					continue;
				}

				if (tmp.id == CURRENT_ID) {
					_dprintf("%s: found data for ip %s\n", __FUNCTION__, tmp.ipaddr);

					ptr = TREE_FIND(&tree, _Node, linkage, &tmp);
					if (ptr) {
						_dprintf("%s: removing/reloading new data for ip %s\n", __FUNCTION__, ptr->ipaddr);
						TREE_REMOVE(&tree, _Node, linkage, ptr);
						free(ptr);
						ptr = NULL;
					}

					TREE_INSERT(&tree, _Node, linkage, Node_new(tmp.ipaddr));

					ptr = TREE_FIND(&tree, _Node, linkage, &tmp);

					memcpy(ptr->daily, &tmp.daily, sizeof(data_t) * MAX_NDAILY);
					ptr->dailyp = tmp.dailyp;
					memcpy(ptr->monthly, &tmp.monthly, sizeof(data_t) * MAX_NMONTHLY);
					ptr->monthlyp = tmp.monthlyp;

					ptr->utime = tmp.utime;
#ifdef SPEED_SUPPORT
					memcpy(ptr->speed, &tmp.speed, sizeof(uint64_t) * MAX_NSPEED * MAX_COUNTER);
					ptr->tail = tmp.tail;
#endif
					memcpy(ptr->last, &tmp.last, sizeof(uint64_t) * MAX_COUNTER);
//					ptr->sync = tmp.sync;
					ptr->sync = -1;

					if (ptr->utime > current_uptime) {
						ptr->utime = current_uptime;
						ptr->sync = 1;
					}

					++n;
				} else {
					_dprintf("%s: data for ip '%s' version %d not loaded (current version is %d)\n", __FUNCTION__, tmp.ipaddr, tmp.id, CURRENT_ID);
				}
			}

		fclose(f);
		}
	}
	else {
		_dprintf("%s: %s != 0\n", __FUNCTION__, s);
	}
	unlink(uncomp_fn);

	if (n == -1)
		_dprintf("%s: Failed to parse the data file!\n", __FUNCTION__);
	else
		_dprintf("%s: Loaded %d records\n", __FUNCTION__, n);

	return n;
}
Example #12
0
int
checkcrc(char *fname)
{
	int ifd = -1;
	uint32_t checksum;
	struct stat sbuf;
	unsigned char *ptr = NULL;
	image_header_t *hdr;
	char *imagefile;
	int ret = -1;
	int len;

	imagefile = fname;
//	fprintf(stderr, "img file: %s\n", imagefile);

	ifd = open(imagefile, O_RDONLY|O_BINARY);

	if (ifd < 0) {
		_dprintf("Can't open %s: %s\n",
			imagefile, strerror(errno));
		goto checkcrc_end;
	}

	/* We're a bit of paranoid */
#if defined(_POSIX_SYNCHRONIZED_IO) && !defined(__sun__) && !defined(__FreeBSD__)
	(void) fdatasync (ifd);
#else
	(void) fsync (ifd);
#endif
	if (fstat(ifd, &sbuf) < 0) {
		_dprintf("Can't stat %s: %s\n",
			imagefile, strerror(errno));
		goto checkcrc_fail;
	}

	ptr = (unsigned char *)mmap(0, sbuf.st_size,
				    PROT_READ, MAP_SHARED, ifd, 0);
	if (ptr == (unsigned char *)MAP_FAILED) {
		_dprintf("Can't map %s: %s\n",
			imagefile, strerror(errno));
		goto checkcrc_fail;
	}
	hdr = (image_header_t *)ptr;

	/* check image header */
	if(check_imageheader((char*)hdr, (long*)&len) == 0)
	{
		_dprintf("Check image heaer fail !!!\n");
		goto checkcrc_fail;
	}

	len = SWAP_LONG(hdr->ih_size);
	if (sbuf.st_size < (len + sizeof(image_header_t))) {
		_dprintf("Size mismatch %lx/%lx !!!\n", sbuf.st_size, (len + sizeof(image_header_t)));
		goto checkcrc_fail;
	}

	/* check body crc */
	_dprintf("Verifying Checksum ... ");
	checksum = crc_calc(0, (const char *)ptr + sizeof(image_header_t), len);
	if(checksum != SWAP_LONG(hdr->ih_dcrc))
	{
		_dprintf("Bad Data CRC\n");
		goto checkcrc_fail;
	}
	_dprintf("OK\n");

	ret = 0;

	/* We're a bit of paranoid */
checkcrc_fail:
	if(ptr != NULL)
		munmap(ptr, sbuf.st_size);
#if defined(_POSIX_SYNCHRONIZED_IO) && !defined(__sun__) && !defined(__FreeBSD__)
	(void) fdatasync (ifd);
#else
	(void) fsync (ifd);
#endif
	if (close(ifd)) {
		_dprintf("Read error on %s: %s\n",
			imagefile, strerror(errno));
		ret=-1;
	}
checkcrc_end:
	return ret;
}
Example #13
0
static int
add_option (char *p[], int line, int unit)
{
	char buf[32] = {0};
	FILE *fp;
	char file_path[128] ={0};
	char node[MAXLEN_NODE_NAME];

	snprintf(node, sizeof(node), "OpenVPN_Entry%d", unit + CLIENT_IF_START);

	if  (streq (p[0], "dev") && p[1])
	{
		if(!strncmp(p[1], "tun", 3))
			tcapi_set(node, "iface", "tun");
		else if(!strncmp(p[1], "tap", 3))
			tcapi_set(node, "iface", "tap");
	}
	else if  (streq (p[0], "proto") && p[1])
	{
		tcapi_set(node, "proto", p[1]);
	}
	else if  (streq (p[0], "remote") && p[1])
	{
		tcapi_set(node, "addr", p[1]);

		if(p[2])
			tcapi_set(node, "port", p[2]);
		else
			tcapi_set(node, "port", "1194");
	}
	else if (streq (p[0], "resolv-retry") && p[1])
	{
		if (streq (p[1], "infinite"))
			tcapi_set(node, "retry", "-1");
		else
			tcapi_set(node, "retry", p[1]);
	}
	else if (streq (p[0], "comp-lzo"))
	{
		sprintf(buf, "vpn_client%d_comp", unit);
		if(p[1])
			tcapi_set(node, "comp", p[1]);
		else
			tcapi_set(node, "comp", "adaptive");
	}
	else if (streq (p[0], "cipher") && p[1])
	{
		tcapi_set(node, "cipher", p[1]);
	}
	else if (streq (p[0], "verb") && p[1])
	{
		tcapi_set(node, "loglevel", p[1]);
	}
	else if  (streq (p[0], "ca") && p[1])
	{
		tcapi_set(node, "crypt", "tls");
		if (streq (p[1], INLINE_FILE_TAG) && p[2])
		{
			sprintf(buf, "vpn_crt_client%d_ca", unit);
#if defined(TCSUPPORT_ADD_JFFS) || defined(TCSUPPORT_SQUASHFS_ADD_YAFFS)
			snprintf(file_path, sizeof(file_path) -1, "%s/%s", OVPN_FS_PATH, buf);
			fp = fopen(file_path, "w");
			if(fp) {
				fprintf(fp, "%s", strstr(p[2], "-----BEGIN"));
				fclose(fp);
			}
			else {
				_dprintf("write %s file to %s failed\n", buf, OVPN_FS_PATH);
				logmessage ("OVPN", "Write CA to filesystem failed");
				return -1;
			}
#else
			tcapi_set(node, buf, strstr(p[2], "-----BEGIN"));
#endif
		}
		else
		{
			return VPN_UPLOAD_NEED_CA_CERT;
		}
	}
	else if  (streq (p[0], "cert") && p[1])
	{
		if (streq (p[1], INLINE_FILE_TAG) && p[2])
		{
			sprintf(buf, "vpn_crt_client%d_crt", unit);
#if defined(TCSUPPORT_ADD_JFFS) || defined(TCSUPPORT_SQUASHFS_ADD_YAFFS)
			snprintf(file_path, sizeof(file_path) -1, "%s/%s", OVPN_FS_PATH, buf);
			fp = fopen(file_path, "w");
			if(fp) {
				fprintf(fp, "%s", strstr(p[2], "-----BEGIN"));
				fclose(fp);
			}
			else {
				_dprintf("write %s file to %s failed\n", buf, OVPN_FS_PATH);
				logmessage ("OVPN", "Write Certificate to filesystem failed");
				return -1;
			}
#else
			tcapi_set(node, buf, strstr(p[2], "-----BEGIN"));
#endif
		}
		else
		{
			return VPN_UPLOAD_NEED_CERT;
		}
	}
	else if  (streq (p[0], "key") && p[1])
	{
		if (streq (p[1], INLINE_FILE_TAG) && p[2])
		{
			sprintf(buf, "vpn_crt_client%d_key", unit);
#if defined(TCSUPPORT_ADD_JFFS) || defined(TCSUPPORT_SQUASHFS_ADD_YAFFS)
			snprintf(file_path, sizeof(file_path) -1, "%s/%s", OVPN_FS_PATH, buf);
			fp = fopen(file_path, "w");
			if(fp) {
				fprintf(fp, "%s", strstr(p[2], "-----BEGIN"));
				fclose(fp);
			}
			else {
				_dprintf("write %s file to %s failed\n", buf, OVPN_FS_PATH);
				logmessage ("OVPN", "Write key to filesystem failed");
				return -1;
			}
#else
			tcapi_set(node, buf, strstr(p[2], "-----BEGIN"));
#endif
		}
		else
		{
			return VPN_UPLOAD_NEED_KEY;
		}
	}
	else if (streq (p[0], "tls-auth") && p[1])
	{
		if (streq (p[1], INLINE_FILE_TAG) && p[2])
		{
			sprintf(buf, "vpn_crt_client%d_static", unit);
#if defined(TCSUPPORT_ADD_JFFS) || defined(TCSUPPORT_SQUASHFS_ADD_YAFFS)
			snprintf(file_path, sizeof(file_path) -1, "%s/%s", OVPN_FS_PATH, buf);
			fp = fopen(file_path, "w");
			if(fp) {
				fprintf(fp, "%s", strstr(p[2], "-----BEGIN"));
				fclose(fp);
			}
			else {
				_dprintf("write %s file to %s failed\n", buf, OVPN_FS_PATH);
				logmessage ("OVPN", "Write static-key to filesystem failed");
				return -1;
			}
#else
			tcapi_set(node, buf, strstr(p[2], "-----BEGIN"));
#endif
			//key-direction
			sprintf(buf, "vpn_crt_client%d_hmac", unit);
			if(tcapi_match(node, "hmac", "-1"))	//default, disable
				tcapi_set(node, "hmac", "2");	//openvpn default value: KEY_DIRECTION_BIDIRECTIONAL
		}
		else
		{
			if(p[2]) {
				tcapi_set(node, "hmac", p[2]);
			}
			return VPN_UPLOAD_NEED_STATIC;
		}
	}
	else if (streq (p[0], "secret") && p[1])
	{
		tcapi_set(node, "crypt", "secret");
		if (streq (p[1], INLINE_FILE_TAG) && p[2])
		{
			sprintf(buf, "vpn_crt_client%d_static", unit);
#if defined(TCSUPPORT_ADD_JFFS) || defined(TCSUPPORT_SQUASHFS_ADD_YAFFS)
			snprintf(file_path, sizeof(file_path) -1, "%s/%s", OVPN_FS_PATH, buf);
			fp = fopen(file_path, "w");
			if(fp) {
				fprintf(fp, "%s", strstr(p[2], "-----BEGIN"));
				fclose(fp);
			}
			else {
				_dprintf("write %s file to %s failed\n", buf, OVPN_FS_PATH);
				logmessage ("OVPN", "Write static-key to filesystem failed");
				return -1;
			}
#else
			tcapi_set(node, buf, strstr(p[2], "-----BEGIN"));
#endif
		}
		else
		{
			return VPN_UPLOAD_NEED_STATIC;
		}
	}
	else if (streq (p[0], "auth-user-pass"))
	{
		tcapi_set(node, "userauth", "1");
	}
	else if (streq (p[0], "tls-remote") && p[1])
	{
		tcapi_set(node, "tlsremote", "1");
		tcapi_set(node, "common_name", p[1]);
	}
	else if (streq (p[0], "key-direction") && p[1])
	{
		tcapi_set(node, "hmac", p[1]);
	}
	else if (streq (p[0], "crl-verify") && p[1])
	{
		if (p[2] && streq(p[2], "dir"))
			;//TODO: not support?
		return VPN_UPLOAD_NEED_CRL;
	}
	else
	{
		if ( streq (p[0], "client")
			|| streq (p[0], "nobind")
			|| streq (p[0], "persist-key")
			|| streq (p[0], "persist-tun")
		) {
			;//ignore
		}
		else {
			add_custom(unit, p);
		}
	}
	return 0;
}
Example #14
0
int rcheck_main(int argc, char *argv[])
{
	char buf[256];
	char *p;
	int sched_begin;
	int sched_end;
	int sched_dow;
	time_t now;
	struct tm *tms;
	int now_dow;
	int now_mins;
	int n;
	int nrule;
	char comp;
	int insch;
	unsigned long long activated;
	int count;
	int radio;
	int r;
#ifdef TCONFIG_IPV6
	int r6;
#endif
#ifdef LINUX26
	int ipt_active;
#endif

	if (!nvram_contains_word("log_events", "acre")) {
		setlogmask(LOG_MASK(LOG_EMERG));	// can't set to 0
	}

	simple_lock("restrictions");

	now = time(0);
	if (now < Y2K) {
		if (!nvram_match("rrules_timewarn", "1")) {
			nvram_set("rrules_timewarn", "1");
			syslog(LOG_INFO, "Time not yet set. Only \"all day, everyday\" restrictions will be activated.");
		}
		now_mins = now_dow = 0;
	}
	else {
		tms = localtime(&now);
		now_dow = 1 << tms->tm_wday;
		now_mins = (tms->tm_hour * 60) + tms->tm_min;
	}

#ifdef LINUX26
	ipt_active = 0;
#endif

	activated = strtoull(nvram_safe_get("rrules_activated"), NULL, 16);
	count = 0;
	radio = foreach_wif(0, NULL, radio_on) ? -1 : -2;
	for (nrule = 0; nrule < MAX_NRULES; ++nrule) {
		sprintf(buf, "rrule%d", nrule);
		if ((p = nvram_get(buf)) == NULL) continue;
		if (sscanf(p, "%d|%d|%d|%d|%c", &n, &sched_begin, &sched_end, &sched_dow, &comp) != 5) continue;
		if (n == 0) continue;

		++count;

		if (now < Y2K) {
			if ((sched_begin >= 0) || (sched_end >= 0) || (sched_dow != 0x7F)) continue;
			insch = 1;
		}
		else {
			insch = in_sched(now_mins, now_dow, sched_begin, sched_end, sched_dow);
		}

#ifdef LINUX26
		if ((insch) && (comp != '~'))
			++ipt_active;
#endif

		n = 1 << nrule;
		if ((insch) == ((activated & n) != 0)) {
			continue;
		}

		syslog(LOG_INFO, "%sctivating rule %d", insch ? "A" : "Dea", nrule);

		if (comp == '~') {
			if ((radio != 0) && (radio != -2)) radio = !insch;
		}
		else {
			sprintf(buf, "r%s%02d", (comp != '|') ? "dev" : "res", nrule);

			r = eval("iptables", "-D", "restrict", "-j", buf);
			if (insch) {
				// ignore error above (if any)

				r = eval("iptables", "-A", "restrict", "-j", buf);
			}

#ifdef TCONFIG_IPV6
			r6 = eval("ip6tables", "-D", "restrict", "-j", buf);
			if (ipv6_enabled()) {
				if (insch) {
					// ignore error above (if any)

					r6 = eval("ip6tables", "-A", "restrict", "-j", buf);
				}
				r |= r6;
			}
#endif

			if (r != 0) {
				syslog(LOG_ERR, "Iptables: %sactivating chain \"%s\" failed. Retrying in 15 minutes.",
					insch ? "" : "de", buf);
				continue;
			}
		}

		if (insch) activated |= n;
			else activated &= ~n;
	}

	sprintf(buf, "%llx", activated);
	nvram_set("rrules_activated", buf);

	if (count > 0) {
		if ((argc != 2) || (strcmp(argv[1], "--cron") != 0)) {
			eval("cru", "a", "rcheck", "*/15 * * * * rcheck --cron");
		}
	}
	else {
		unsched_restrictions();
	}

	if (radio >= 0) {
		nvram_set("rrules_radio", radio ? "0" : "1");
#if 1
		// changed for dual radio support
		_dprintf("%s: radio = %d\n", __FUNCTION__, radio);
		eval("radio", radio ? "on" : "off");
#else
		if (get_radio() != radio) {
			_dprintf("%s: radio = %d\n", __FUNCTION__, radio);
			eval("radio", radio ? "on" : "off");
		}
		else {
			_dprintf("%s: no radio change = %d\n", __FUNCTION__, radio);
		}
#endif
	}

#ifdef LINUX26
	allow_fastnat("restrictions", (ipt_active == 0));
	try_enabling_fastnat();
#endif
	simple_unlock("restrictions");
	return 0;
}
Example #15
0
int start_timemachine()
{
	int ret = 0;
	char cnid_path[80];
	char backup_path[80];
	//char token_path[80];
	char test_log[100];
	char *mount_point_name;

	char prefix[] = "usb_pathXXXXXXXXXXXXXXXXX_", tmp[100];
	char usb1_vid[8], usb1_pid[8], usb1_serial[64];
	char usb2_vid[8], usb2_pid[8], usb2_serial[64];

	snprintf(prefix, sizeof(prefix), "usb_path%s", "1");
	memset(usb1_vid, 0, 8);
	strncpy(usb1_vid, nvram_safe_get(strcat_r(prefix, "_vid", tmp)), 8);
	memset(usb1_pid, 0, 8);
	strncpy(usb1_pid, nvram_safe_get(strcat_r(prefix, "_pid", tmp)), 8);
	memset(usb1_serial, 0, 64);
	strncpy(usb1_serial, nvram_safe_get(strcat_r(prefix, "_serial", tmp)), 8);

	snprintf(prefix, sizeof(prefix), "usb_path%s", "2");
	memset(usb2_vid, 0, 8);
	strncpy(usb2_vid, nvram_safe_get(strcat_r(prefix, "_vid", tmp)), 8);
	memset(usb2_pid, 0, 8);
	strncpy(usb2_pid, nvram_safe_get(strcat_r(prefix, "_pid", tmp)), 8);
	memset(usb2_serial, 0, 64);
	strncpy(usb2_serial, nvram_safe_get(strcat_r(prefix, "_serial", tmp)), 8);

	//clear_timemachine_tokeninfo();
	//find_tokenfile_partition();

	if(!nvram_match("timemachine_enable", "1"))
		return -1;

	if(nvram_safe_get("tm_device_name") == NULL)
	{
		_dprintf("Timemachine: no device name to backup\n");
		logmessage("Timemachine", "no device name to backup");
		return -1;
	}
#if 1
	if(nvram_match("tm_ui_setting", "1")){
		logmessage("Timemachine", "User select disk start TimeMachine");
		mount_point_name = find_mountpoint(nvram_safe_get("tm_device_name"));
		nvram_set("tm_ui_setting", "0");
	}else{
	//check mountpoint exchange or not
	if(!nvram_match("tm_usb_path_vid", "")
		&& (nvram_match("tm_usb_path_vid",usb1_vid)) 
		&& (nvram_match("tm_usb_path_pid",usb1_pid)) 
		&& (nvram_match("tm_usb_path_serial",usb1_serial)))
	{
		sprintf(test_log, "Time Machine interface1 change %s -> %s", nvram_safe_get("tm_device_name"),nvram_safe_get("tm_partition_num"));
		mount_point_name = find_mountpoint(nvram_safe_get("tm_device_name"));
		logmessage("Timemachine", test_log);
	}
	else if(!nvram_match("tm_usb_path_vid", "")
		&& (nvram_match("tm_usb_path_vid",usb2_vid)) 
		&& (nvram_match("tm_usb_path_pid",usb2_pid))
		&& (nvram_match("tm_usb_path_serial",usb2_serial)))
	{
		sprintf(test_log, "tm_device_name interface2 change %s -> %s", nvram_safe_get("tm_device_name"),nvram_safe_get("tm_partition_num"));
		mount_point_name = find_mountpoint(nvram_safe_get("tm_device_name"));
		logmessage("Timemachine", test_log);
	}else{
		logmessage("Timemachine", "No disk to auto start TimeMachine");
		mount_point_name = find_mountpoint(nvram_safe_get("tm_device_name"));
	}
	}
#endif

	if(mount_point_name == NULL)
	{
		_dprintf("Timemachine: can not find the correct mount point name\n");
		logmessage("Timemachine", "can not find the correct mount point name");
		return -1;
	}

	if(!check_if_dir_exist(mount_point_name))
	{
		_dprintf("Timemachine: mount point name doesn't exist\n");
		logmessage("Timemachine", "mount point name doesn't exist");
		return -1;
	}

	// Create directory for use by afpd daemon and configuration file
	//if(!check_if_dir_exist(AFP_LOCK_PATH)) mkdir(AFP_LOCK_PATH, 0777);
	//if(!check_if_dir_exist(AFP_CONFIG_PATH)) mkdir(AFP_CONFIG_PATH, 0777);
	mkdir_if_none(AFP_LOCK_PATH);
	mkdir_if_none(AFP_CONFIG_PATH);

	// Create directory for use by avahi daemon and configuration file
	//if(!check_if_dir_exist(AVAHI_CONFIG_PATH)) mkdir(AVAHI_CONFIG_PATH, 0777);
	//if(!check_if_dir_exist(AVAHI_SERVICES_PATH)) mkdir(AVAHI_SERVICES_PATH, 0777);
	mkdir_if_none(AVAHI_CONFIG_PATH);
	mkdir_if_none(AVAHI_SERVICES_PATH);

	// Create directory for use by cnid_metad and cnid_dbd daemon
	sprintf(cnid_path, "%s/%s", mount_point_name, CNID_DIR_NAME);
	sprintf(backup_path, "%s", mount_point_name);

	//Create token file
	//sprintf(token_path, "%s/%s", mount_point_name, TIMEMACHINE_TOKEN_FILE);
	//if(!check_if_file_exist(token_path))
	//	ret = generate_timemachine_token_file(token_path);

	//if(!check_if_dir_exist(cnid_path)) mkdir(cnid_path, 0777);
	//if(!check_if_dir_exist(backup_path)) mkdir(backup_path, 0777);
	mkdir_if_none(cnid_path);
	//mkdir_if_none(backup_path);

	ret = generate_afp_config(mount_point_name);
	start_afpd();
	start_cnid_metad();
	restart_mdns();

	logmessage("Timemachine", "daemon is started");

	return ret;
}
Example #16
0
/*
 * Called when link comes up
 */
int
ipup_main(int argc, char **argv)
{
	FILE *fp;
	char *wan_ifname = safe_getenv("IFNAME");
	char *wan_linkname = safe_getenv("LINKNAME");
	char tmp[100], prefix[] = "wanXXXXXXXXXX_";
	char buf[256], *value;
	int unit;

	_dprintf("%s():: %s\n", __FUNCTION__, argv[0]);

	/* Get unit from LINKNAME: ppp[UNIT] */
	if ((unit = ppp_linkunit(wan_linkname)) < 0)
		return 0;

	_dprintf("%s: unit=%d ifname=%s\n", __FUNCTION__, unit, wan_ifname);
	snprintf(prefix, sizeof(prefix), "wan%d_", unit);

	/* Stop triggering demand connection */
	if (nvram_get_int(strcat_r(prefix, "pppoe_demand", tmp)))
		nvram_set_int(strcat_r(prefix, "pppoe_demand", tmp), 1);

#ifdef RTCONFIG_USB_MODEM
	// wanX_ifname is used for device for USB Modem
	if ((value = getenv("DEVICE")) &&
	    (isSerialNode(value) || isACMNode(value)))
		nvram_set(strcat_r(prefix, "ifname", tmp), value);
#endif

	/* Touch connection file */
	if (!(fp = fopen(strcat_r("/tmp/ppp/link.", wan_ifname, tmp), "a"))) {
		perror(tmp);
		return errno;
	}
	fclose(fp);

	if ((value = getenv("IPLOCAL"))) {
		if (nvram_invmatch(strcat_r(prefix, "ipaddr", tmp), value))
			ifconfig(wan_ifname, IFUP, "0.0.0.0", NULL);
		_ifconfig(wan_ifname, IFUP, value, "255.255.255.255", getenv("IPREMOTE"));
		nvram_set(strcat_r(prefix, "ipaddr", tmp), value);
		nvram_set(strcat_r(prefix, "netmask", tmp), "255.255.255.255");
	}

	if ((value = getenv("IPREMOTE")))
		nvram_set(strcat_r(prefix, "gateway", tmp), value);

	strcpy(buf, "");
	if ((value = getenv("DNS1")))
		sprintf(buf, "%s", value);
	if ((value = getenv("DNS2")))
		sprintf(buf + strlen(buf), "%s%s", strlen(buf) ? " " : "", value);

	/* empty DNS means they either were not requested or peer refused to send them.
	 * lift up underlying xdns value instead, keeping "dns" filled */
	if (strlen(buf) == 0)
		sprintf(buf, "%s", nvram_safe_get(strcat_r(prefix, "xdns", tmp)));

	nvram_set(strcat_r(prefix, "dns", tmp), buf);

	wan_up(wan_ifname);

	_dprintf("%s:: done\n", __FUNCTION__);
	return 0;
}
Example #17
0
static int add_bandwidth_limiter_rules(char *pcWANIF)
{
	FILE *fn = NULL;
	char *buf, *g, *p;
	char *enable, *addr, *dlc, *upc, *prio;
	char lan_addr[32];
	char addr_new[32];
	int addr_type;

	if ((fn = fopen(mangle_fn, "w")) == NULL) return -2;
	del_iQosRules(); // flush all rules in mangle table

#ifdef RTCONFIG_RALINK
	const char *action = "CONNMARK --set-return";
#else
	const char *action = "MARK --set-mark";
#endif

	/* ASUSWRT
	qos_bw_rulelist :
		enable>addr>DL-Ceil>UL-Ceil>prio
		enable : enable or disable this rule
		addr : (source) IP or MAC or IP-range
		DL-Ceil : the max download bandwidth
		UL-Ceil : the max upload bandwidth
		prio : priority for client
	*/

	memset(lan_addr, 0, sizeof(lan_addr));
	sprintf(lan_addr, "%s/%s", nvram_safe_get("lan_ipaddr"), nvram_safe_get("lan_netmask"));

	fprintf(fn,
		"*mangle\n"
		":PREROUTING ACCEPT [0:0]\n"
		":OUTPUT ACCEPT [0:0]\n"
		);

	g = buf = strdup(nvram_safe_get("qos_bw_rulelist"));
	while (g) {
		if ((p = strsep(&g, "<")) == NULL) break;
		if ((vstrsep(p, ">", &enable, &addr, &dlc, &upc, &prio)) != 5) continue;
		if (!strcmp(enable, "0")) continue;
		memset(addr_new, 0, sizeof(addr_new));
		address_checker(&addr_type, addr, addr_new);
		//_dprintf("[BWLIT] %s: addr_type=%d, addr=%s, add_new=%s, lan_addr=%s\n", __FUNCTION__, addr_type, addr, addr_new, lan_addr);

		if (addr_type == TYPE_IP){
			fprintf(fn,
				"-A POSTROUTING ! -s %s -d %s -j %s %d\n"
				"-A PREROUTING -s %s ! -d %s -j %s %d\n"
				, lan_addr, addr_new, action, atoi(prio)+10
				, addr_new, lan_addr, action, atoi(prio)+10
				);
		}
		else if (addr_type == TYPE_MAC){
			fprintf(fn,
				"-A PREROUTING -m mac --mac-source %s ! -d %s  -j %s %d\n"
				, addr_new, lan_addr, action, atoi(prio)+10
				);
		}
		else if (addr_type == TYPE_IPRANGE){
			fprintf(fn,
				"-A POSTROUTING ! -s %s -m iprange --dst-range %s -j %s %d\n"
				"-A PREROUTING -m iprange --src-range %s ! -d %s -j %s %d\n"
				, lan_addr, addr_new, action, atoi(prio)+10
				, addr_new, lan_addr, action, atoi(prio)+10
				);
		}
	}
	free(buf);

	fprintf(fn, "COMMIT\n");
	fclose(fn);
	chmod(mangle_fn, 0700);
	eval("iptables-restore", (char*)mangle_fn);
	_dprintf("[BWLIT] %s: create rules\n", __FUNCTION__);

	return 0;
}
Example #18
0
File: ppp.c Project: rainkid/bcwifi
int ipup_main(int argc, char **argv)
{
	char *wan_ifname;
	char *value;
	char buf[256];
	const char *p;

	TRACE_PT("begin\n");

	killall("listen", SIGKILL);
	
	if (!wait_action_idle(10)) return -1;

	wan_ifname = safe_getenv("IFNAME");
	if ((!wan_ifname) || (!*wan_ifname)) return -1;
	nvram_set("wan_iface", wan_ifname);	// ppp#

	// ipup receives six arguments:
	//   <interface name>  <tty device>  <speed> <local IP address> <remote IP address> <ipparam>
	//   ppp1 vlan1 0 71.135.98.32 151.164.184.87 0

	f_write_string("/tmp/ppp/link", argv[1], 0, 0);
	
	if ((p = getenv("IPREMOTE"))) {
		nvram_set("wan_gateway_get", p);
		TRACE_PT("IPREMOTE=%s\n", p);
	}

	if ((value = getenv("IPLOCAL"))) {
		_dprintf("IPLOCAL=%s\n", value);

		switch (get_wan_proto()) {
		case WP_PPPOX:	
		case WP_PPPOE:
		case WP_PPP3G:
			nvram_set("wan_ipaddr_buf", nvram_safe_get("wan_ipaddr"));		// store last ip address
			nvram_set("wan_ipaddr", value);
			nvram_set("wan_netmask", "255.255.255.255");
			break;
		case WP_PPTP:
		case WP_L2TP:
			nvram_set("wan_ipaddr_buf", nvram_safe_get("ppp_get_ip"));
			break;
		}

		if (!nvram_match("ppp_get_ip", value)) {
			ifconfig(wan_ifname, IFUP, "0.0.0.0", NULL);
			nvram_set("ppp_get_ip", value);
		}

		_ifconfig(wan_ifname, IFUP, value, "255.255.255.255", (p && (*p)) ? p : NULL);
	}

	buf[0] = 0;
	if ((p = getenv("DNS1")) != NULL) strlcpy(buf, p, sizeof(buf));
	if ((p = getenv("DNS2")) != NULL) {
		if (buf[0]) strlcat(buf, " ", sizeof(buf));
		strlcat(buf, p, sizeof(buf));
	}
	nvram_set("wan_get_dns", buf);
	TRACE_PT("DNS=%s\n", buf);

	if ((value = getenv("AC_NAME"))) nvram_set("ppp_get_ac", value);
	if ((value = getenv("SRV_NAME"))) nvram_set("ppp_get_srv", value);
	if ((value = getenv("MTU"))) nvram_set("wan_run_mtu", value);

	start_wan_done(wan_ifname);

	TRACE_PT("end\n");
	return 0;
}
Example #19
0
void start_jffs2(void)
{
	if (!nvram_match("jffs2_on", "1")) {
		notice_set("jffs", "");
		return;
	}

	int format = 0;
	char s[256];
	int size;
	int part;
	const char *p;
	struct statfs sf;

	if (!wait_action_idle(10)) return;

	if (!mtd_getinfo("jffs2", &part, &size)) return;

_dprintf("*** jffs2: %d, %d\n", part, size);
	if (nvram_match("jffs2_format", "1")) {
		nvram_set("jffs2_format", "0");

		if (!mtd_erase("jffs2")) {
			error("formatting");
			return;
		}

		format = 1;
	}

	sprintf(s, "%d", size);
	p = nvram_get("jffs2_size");
	if ((p == NULL) || (strcmp(p, s) != 0)) {
		if (format) {
			nvram_set("jffs2_size", s);
			nvram_commit_x();
		}
		else if ((p != NULL) && (*p != 0)) {
			error("verifying known size of");
			return;
		}
	}

	if ((statfs("/jffs", &sf) == 0) && (sf.f_type != 0x71736873 /* squashfs */)) {
		// already mounted
		notice_set("jffs", format ? "Formatted" : "Loaded");
		return;
	}
	if (!mtd_unlock("jffs2")) {
		error("unlocking");
		return;
	}
	modprobe(JFFS_NAME);
	sprintf(s, MTD_BLKDEV(%d), part);
	if (mount(s, "/jffs", JFFS_NAME, MS_NOATIME, "") != 0) {
_dprintf("*** jffs2 mount error\n");
		//modprobe_r(JFFS_NAME);
		error("mounting");
		return;
	}
#ifdef TEST_INTEGRITY
	int test;

	if (format) {
		if (f_write("/jffs/.tomato_do_not_erase", &size, sizeof(size), 0, 0) != sizeof(size)) {
			stop_jffs2();
			error("setting integrity test for");
			return;
		}
	}
	if ((f_read("/jffs/.tomato_do_not_erase", &test, sizeof(test)) != sizeof(test)) || (test != size)) {
		stop_jffs2();
		error("testing integrity of");
		return;
	}
#endif

	notice_set("jffs", format ? "Formatted" : "Loaded");

	if (((p = nvram_get("jffs2_exec")) != NULL) && (*p != 0)) {
		chdir("/jffs");
		system(p);
		chdir("/");
	}
	run_userfile("/jffs", ".asusrouter", "/jffs", 3);

	if (!check_if_dir_exist("/jffs/scripts/")) mkdir("/jffs/scripts/", 0755);
	if (!check_if_dir_exist("/jffs/configs/")) mkdir("/jffs/configs/", 0755);

}
Example #20
0
static int mssl_seek(void *cookie, __offmax_t *pos, int whence)
{
	_dprintf("%s()\n", __FUNCTION__);
	errno = EIO;
	return -1;
}
Example #21
0
void start_pptpd(void)
{
	int ret = 0, manual_dns = 0, pptpd_opt = 0;
	FILE *fp;
	char buf[MAXLEN_TCAPI_MSG];
	char lan_ipaddr[16] = {0};

	int pid = getpid();
	_dprintf("start_pptpd: getpid= %d\n", pid);

	//if(getpid() != 1) {
		//notify_rc("start_pptpd");
		//return;
	//}

	if (!tcapi_match(VPN_DATA, "pptpd_enable", "1")) {
		return;
	}
	// cprintf("stop vpn modules\n");
	// stop_vpn_modules ();

	// Create directory for use by pptpd daemon and its supporting files
	mkdir("/tmp/pptpd", 0744);
	cprintf("open options file\n");
	// Create options file that will be unique to pptpd to avoid interference
	// with pppoe and pptp
	fp = fopen("/tmp/pptpd/options.pptpd", "w");
	fprintf(fp, "logfile /var/log/pptpd-pppd.log\n");
	//fprintf(fp, "debug dump logfd 2 nodetach\n");
	if (tcapi_match(VPN_DATA, "pptpd_radius", "1"))
		fprintf(fp, "plugin radius.so\nplugin radattr.so\n"
			"radius-config-file /tmp/pptpd/radius/radiusclient.conf\n");

	//cprintf("check if wan_wins = zero\n");
	//int nowins = 0;

	//if (nvram_match("wan_wins", "0.0.0.0")) {
		//nvram_set("wan_wins", "");
		//nowins = 1;
	//}
	//if (strlen(nvram_safe_get("wan_wins")) == 0)
		//nowins = 1;

	cprintf("write config\n");
	fprintf(fp, "lock\n"
		"name *\n"
		"proxyarp\n"
//		"ipcp-accept-local\n"
//		"ipcp-accept-remote\n"
		"lcp-echo-failure 10\n"
		"lcp-echo-interval 6\n"
		"deflate 0\n" "auth\n" "-chap\n"
		"nomppe-stateful\n");

	pptpd_opt = tcapi_get_int(VPN_DATA, "pptpd_chap");
	fprintf(fp, "%smschap\n", (pptpd_opt == 0 || pptpd_opt & 1) ? "+" : "-");
	fprintf(fp, "%smschap-v2\n", (pptpd_opt == 0 || pptpd_opt & 2) ? "+" : "-");

	pptpd_opt = tcapi_get_int(VPN_DATA, "pptpd_mppe");
	if (pptpd_opt == 0)
		pptpd_opt = 1 | 4 | 8;
	if (pptpd_opt & (1 | 2 | 4)) {
		fprintf(fp, "%s", (pptpd_opt & 8) ? "" : "require-mppe\n");
  		fprintf(fp, "%smppe-128\n", (pptpd_opt & 1) ? "require-" : "no");
  		//fprintf(fp, "%smppe-56\n", (pptpd_opt & 2) ? "require-" : "no");
  		fprintf(fp, "%smppe-40\n", (pptpd_opt & 4) ? "require-" : "no");
	} else
  		fprintf(fp, "nomppe nomppc\n");

	fprintf(fp, "ms-ignore-domain\n"
		"chap-secrets /tmp/pptpd/chap-secrets\n"
		"ip-up-script /tmp/pptpd/ip-up\n"
		"ip-down-script /tmp/pptpd/ip-down\n"
		"mtu %d\n" "mru %d\n",
		tcapi_get_int(VPN_DATA, "pptpd_mtu"),
		tcapi_get_int(VPN_DATA, "pptpd_mru"));

	//WINS Server
	//if (!nowins) {
		//fprintf(fp, "ms-wins %s\n", nvram_safe_get("wan_wins"));
	//}
	memset(buf, 0, sizeof(buf));
	tcapi_get(VPN_DATA, "pptpd_wins1", buf);
	if(strlen(buf)) {
		fprintf(fp, "ms-wins %s\n", buf);
	}
	memset(buf, 0, sizeof(buf));
	tcapi_get(VPN_DATA, "pptpd_wins2", buf);
	if(strlen(buf)) {
		fprintf(fp, "ms-wins %s\n", buf);
	}
	//DNS Server
	memset(buf, 0, sizeof(buf));
	tcapi_get(VPN_DATA, "pptpd_dns1", buf);
	if(strlen(buf)) {
		fprintf(fp, "ms-dns %s\n", buf);
		manual_dns=1;
	}
	memset(buf, 0, sizeof(buf));
	tcapi_get(VPN_DATA, "pptpd_dns2", buf);
	if(strlen(buf)) {
		fprintf(fp, "ms-dns %s\n", buf);
		manual_dns=1;
	}
	tcapi_get("Lan_Entry0", "IP", lan_ipaddr);
	if(!manual_dns && strcmp(lan_ipaddr, ""))
		fprintf(fp, "ms-dns %s\n", lan_ipaddr);

	// force ppp interface starting from 20
	fprintf(fp, "minunit 20\n");

	// Following is all crude and need to be revisited once testing confirms
	// that it does work
	// Should be enough for testing..
	if (tcapi_match(VPN_DATA, "pptpd_radius", "1")) {
		char pptpd_radserver[128] = {0};
		char pptpd_radpass[128] = {0};
		char pptpd_radport[128] = {0};
		char pptpd_acctport[128] = {0};

		if (tcapi_get(VPN_DATA, "pptpd_radserver", pptpd_radserver) == TCAPI_PROCESS_OK
			&& tcapi_get(VPN_DATA, "pptpd_radpass", pptpd_radpass) == TCAPI_PROCESS_OK) {

			fclose(fp);

			mkdir("/tmp/pptpd/radius", 0744);

			if (tcapi_get(VPN_DATA, "pptpd_radport", pptpd_radport) != TCAPI_PROCESS_OK)
				strcpy(pptpd_radport, "radius");

			fp = fopen("/tmp/pptpd/radius/radiusclient.conf", "w");
			fprintf(fp, "auth_order radius\n"
				"login_tries 4\n"
				"login_timeout 60\n"
				"radius_timeout 10\n"
				"nologin /etc/nologin\n"
				"servers /tmp/pptpd/radius/servers\n"
				"dictionary /etc/dictionary\n"
				"seqfile /var/run/radius.seq\n"
				"mapfile /etc/port-id-map\n"
				"radius_retries 3\n"
				"authserver %s:%s\n",
				pptpd_radserver, pptpd_radport);

			if (tcapi_get(VPN_DATA, "pptpd_acctport", pptpd_acctport) != TCAPI_PROCESS_OK)
				strcpy(pptpd_acctport, "radacct");

			fprintf(fp, "acctserver %s:%s\n", pptpd_radserver, pptpd_acctport);
			fclose(fp);

			fp = fopen("/tmp/pptpd/radius/servers", "w");
			fprintf(fp, "%s\t%s\n", pptpd_radserver, pptpd_radpass);
			fclose(fp);

		} else
			fclose(fp);
	} else
		fclose(fp);

	// Create pptpd.conf options file for pptpd daemon
	fp = fopen("/tmp/pptpd/pptpd.conf", "w");
	memset(buf, 0, sizeof(buf));
	fprintf(fp, "bcrelay %s\n", tcapi_get_string(VPN_DATA, "pptpd_broadcast", buf));
	memset(buf, 0, sizeof(buf));
	fprintf(fp, "localip %s\n"
		"remoteip %s\n", lan_ipaddr,
		tcapi_get_string(VPN_DATA, "pptpd_clients", buf));
	fclose(fp);

	// Create ip-up and ip-down scripts that are unique to pptpd to avoid
	// interference with pppoe and pptp
	/*
	 * adjust for tunneling overhead (mtu - 40 byte IP - 108 byte tunnel
	 * overhead)
	 */
	//if (nvram_match("mtu_enable", "1"))
		//mss = atoi(nvram_safe_get("wan_mtu")) - 40 - 108;
	//else
		//mss = 1500 - 40 - 108;
	char bcast[32];

	strcpy(bcast, lan_ipaddr);
	memset(buf, 0, sizeof(buf));
	get_broadcast(bcast, tcapi_get_string("Lan_Entry0", "netmask", buf));

	memset(buf, 0, sizeof(buf));
	tcapi_get(VPN_DATA, "pptpd_ipup_script", buf);
	fp = fopen("/tmp/pptpd/ip-up", "w");
	fprintf(fp, "#!/bin/sh\n" "startservice set_routes\n"	// reinitialize
		"echo $PPPD_PID $1 $5 $6 $PEERNAME >> /tmp/pptp_connected\n"
		"iptables -I FORWARD -i $1 -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu\n"
		"iptables -I INPUT -i $1 -j ACCEPT\n" "iptables -I FORWARD -i $1 -j ACCEPT\n"
		"iptables -t nat -I PREROUTING -i $1 -p udp -m udp --sport 9 -j DNAT --to-destination %s "	// rule for wake on lan over pptp tunnel
		"%s\n", bcast, buf);
	fclose(fp);
	memset(buf, 0, sizeof(buf));
	tcapi_get(VPN_DATA, "pptpd_ipdown_script", buf);
	fp = fopen("/tmp/pptpd/ip-down", "w");
	fprintf(fp, "#!/bin/sh\n" "grep -v $1  /tmp/pptp_connected > /tmp/pptp_connected.new\n"
		"mv /tmp/pptp_connected.new /tmp/pptp_connected\n"
		"iptables -D FORWARD -i $1 -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu\n"
		"iptables -D INPUT -i $1 -j ACCEPT\n"
		"iptables -D FORWARD -i $1 -j ACCEPT\n"
		"iptables -t nat -D PREROUTING -i $1 -p udp -m udp --sport 9 -j DNAT --to-destination %s "	// rule for wake on lan over pptp tunnel
		"%s\n", bcast, buf);
	fclose(fp);
	chmod("/tmp/pptpd/ip-up", 0744);
	chmod("/tmp/pptpd/ip-down", 0744);

	// Exctract chap-secrets from nvram
	write_chap_secret("/tmp/pptpd/chap-secrets");

	chmod("/tmp/pptpd/chap-secrets", 0600);

	// Execute pptpd daemon
	ret =
	    eval("pptpd", "-c", "/tmp/pptpd/pptpd.conf", "-o",
		 "/tmp/pptpd/options.pptpd");

	_dprintf("start_pptpd: ret= %d\n", ret);
	//dd_syslog(LOG_INFO, "pptpd : pptp daemon successfully started\n");
	return;
}
Example #22
0
FILE *ssl_server_fopen(int sd)
{
	_dprintf("%s()\n", __FUNCTION__);
	return _ssl_fopen(sd, 0);
}
Example #23
0
// 0 = ok, 1 = failed, 2 = permanent failure
static int ntpc(struct in_addr addr)
{
	uint32_t packet[12];
	struct timeval txtime;
	struct timeval rxtime;
	struct timeval tv;
	uint32_t u;
	uint32_t txn;
	int fd;
	fd_set fds;
	int len;
	struct sockaddr_in sa;
	char s[64], q[128];
	time_t t;
	time_t ntpt;
	time_t diff;

	memset(&sa, 0, sizeof(sa));
	sa.sin_addr = addr;
	sa.sin_port = htons(123);
	sa.sin_family = AF_INET;

	if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
		printf("Unable to create a socket\n");
		return 1;
	}

	if (connect(fd, (struct sockaddr*)&sa, sizeof(sa)) == -1) {
		printf("Unable to connect\n");
	}
	else {
		memset(&packet, 0, sizeof(packet));
		packet[I_MISC] = htonl((4 << 27) | (3 << 24));	// VN=v4 | mode=3 (client)
//		packet[I_MISC] = htonl((3 << 27) | (3 << 24));	// VN=v3 | mode=3 (client)
		gettimeofday(&txtime, NULL);
		packet[I_TXTIME] = txn = htonl(txtime.tv_sec + TIMEFIX);
		send(fd, packet, sizeof(packet), 0);

		FD_ZERO(&fds);
		FD_SET(fd, &fds);
		tv.tv_sec = 3;	// no more than 3 seconds
		tv.tv_usec = 0;
		if (select(fd + 1, &fds, NULL, NULL, &tv) != 1) {
			printf("Timeout\n");
		}
		else {
			len = recv(fd, packet, sizeof(packet), 0);
			if (len != sizeof(packet)) {
				printf("Invalid packet size\n");
			}
			else {
				gettimeofday(&rxtime, NULL);

				u = ntohl(packet[0]);

				_dprintf("u = 0x%08x\n", u);
				_dprintf("LI = %u\n", u >> 30);
				_dprintf("VN = %u\n", (u >> 27) & 0x07);
				_dprintf("mode = %u\n", (u >> 24) & 0x07);
				_dprintf("stratum = %u\n", (u >> 16) & 0xFF);
				_dprintf("poll interval = %u\n", (u >> 8) & 0xFF);
				_dprintf("precision = %u\n", u & 0xFF);

				if ((u & 0x07000000) != 0x04000000) {	// mode != 4 (server)
					printf("Invalid response\n");
				}
				else {
					close(fd);

					// notes:
					//	- Windows' ntpd returns vn=3, stratum=0

					if ((u & 0x00FF0000) == 0) {			// stratum == 0
						printf("Received stratum=0\n");
						if (!nvram_match("ntp_kiss_ignore", "1")) {
							return 2;
						}
					}

					ntpt = ntohl(packet[I_TXTIME]) - TIMEFIX;
					t = (rxtime.tv_sec - txtime.tv_sec) >> 1;
					diff = (ntpt - rxtime.tv_sec) + t;

					_dprintf("txtime = %ld\n", txtime.tv_sec);
					_dprintf("rxtime = %ld\n", rxtime.tv_sec);
					_dprintf("ntpt   = %ld\n", ntpt);
					_dprintf("rtt/2  = %ld\n", t);
					_dprintf("diff   = %ld\n", diff);

					if (diff != 0) {
						gettimeofday(&tv, NULL);
						tv.tv_sec  += diff;
//						tv.tv_usec = 0;// sorry, I'm not a time geek :P
						settimeofday(&tv, NULL);

						_dprintf("new    = %lu\n", tv.tv_sec);

						strftime(s, sizeof(s), "%a, %d %b %Y %H:%M:%S %z", localtime(&tv.tv_sec));
						sprintf(q, "Time Updated: %s [%s%lds]", s, diff > 0 ? "+" : "", diff);
					}
					else {
						t = time(0);
						strftime(s, sizeof(s), "%a, %d %b %Y %H:%M:%S %z", localtime(&t));
						sprintf(q, "Time: %s, no change was needed.", s);
					}
					printf("\n\n%s\n", q);
					syslog(LOG_INFO, q);
					return 0;
				}
			}
		}
	}

	close(fd);
	return 1;
}
Example #24
0
FILE *ssl_client_fopen(int sd)
{
	_dprintf("%s()\n", __FUNCTION__);
	return _ssl_fopen(sd, 1);
}
Example #25
0
void sta_status_report(int stastate, int refresh)
{

	#define MAXBUF 8192
	FILE *fp;	
	int		result, i;
	int		cmd;
	unsigned char	buf[MAXBUF];

	//printf("report\n");

	if (refresh)
	{
		if (sta_state==STA_STATE_BEING_AP)
			stastate=STA_STATE_BEING_AP;
		else return;
	}

	fp=fopen("/tmp/wlan11b.log", "w+");

	if (fp==NULL) 
	{
		_dprintf("can not open file\n");
		return;
	}

	if (stastate==STA_STATE_STOP)
	{
		fprintf(fp, "Wireless Function is disabled\n");
	}
	else if (stastate==STA_STATE_BEING_AP)
	{
		char *auth[] = {"Open System or Shared Key", 
				"Shared Key",
				"WPA-PSK",
				"WPA",
				"Radius"};
		char *wep[] = {"None", "WEP-64", "WEP-128"};
		char *wpa[] = {"TKIP", "AES"};
		int authidx, encidx;


		fprintf(fp, "Mode: AP\n");
		fprintf(fp, "SSID: %s\n", nvram_safe_get("wl0_ssid"));

		authidx = atoi(nvram_safe_get("wl_authmode_x"));
		encidx = atoi(nvram_safe_get("wl_weptype_x"));

		if (authidx>=5) authidx=0;
		if (encidx>=3) encidx=0;

		fprintf(fp, "Authentication: %s\n", auth[authidx]);

		if (authidx==1)
		{	
			if (authidx<0||encidx>1) encidx=0;
			fprintf(fp, "Encryption: %s\n", wep[encidx+1]);
		}	
		else if (authidx==2)
		{
			if (authidx<0||encidx>1) encidx=0;
			fprintf(fp, "Encryption: %s\n", wpa[encidx]);
		}
		else if (authidx==3) 
		{
			if (authidx<0||encidx>2) encidx=0;
			fprintf(fp, "Encryption: %s\n", wep[encidx]);
		}
		else
		{
			if (authidx<0||encidx>2) encidx=0;
			fprintf(fp, "Encryption: %s\n", wep[encidx]);
		}

		fprintf(fp, "Association List\n");
		fprintf(fp, "------------------------------------\n");

		cmd = WLC_GET_ASSOCLIST;
		*(unsigned int *)buf = 1000;		//query 1000 MAC address

		if ( (result = wl_ioctl("eth2", cmd, buf, MAXBUF)) != 0 ) {
			_dprintf("Fail: cmd=0x%02x (%d)\n", cmd, result);
		}
		else 
		{
			unsigned int	count = *(unsigned int *)buf;
			unsigned int 	j;

			j=0;

			for ( i=0; i< count*6; i++ ) 
			{
				if ((i%6)==0)
				{
					fprintf(fp, "STA%2x:", j++);
				}

				fprintf(fp, "%02x", i, buf[sizeof(unsigned int)+i]);
				if ( (i % 6)==5 )
					fprintf(fp, "\n");
				else
					fprintf(fp, ":");
			}
		}

	}
	else
	{
		if (stastate==STA_STATE_CONNECTED || 
			stastate==STA_STATE_CONNECTING_ONE ||
			stastate==STA_STATE_CONNECTING_PROFILE)
		{
			if (stainfo_g.mode==0)
			{	
				fprintf(fp, "Mode: Infra Structure(STA)\n");
			}
			else
			{
				fprintf(fp, "Mode: Adhoc(STA)\n");
			}

			if (stastate == STA_STATE_CONNECTED)
			 	fprintf(fp, "Status: Associated\n");
			else fprintf(fp, "Status: Connecting\n");
			
			fprintf(fp, "SSID  : %s\n", stainfo_g.ssid); 

			if (stainfo_g.sharedkeyauth)
			{
				fprintf(fp, "Authenication: Shared Key\n");
			}
			else
			{
				fprintf(fp, "Authenication: Open System\n");
			}

			if (stainfo_g.wep == STA_ENCRYPTION_ENABLE)
			{
				if (stainfo_g.wepkeylen==STA_ENCRYPTION_TYPE_WEP128)
				{	
					fprintf(fp, "Encryption: WEP 128 bits\n");
				}
				else
				{
					fprintf(fp, "Encryption: WEP 64 bits\n");
				}
			}
			else
			{	
				fprintf(fp, "Encryption: None\n");
			}
		}
		else if (sta_state==STA_STATE_SCANNING ||
			  sta_state==STA_STATE_SCANNING_PROFILE)
		{
			fprintf(fp, "Mode: Station\n");
			fprintf(fp, "Status: Scanning\n");
		}
	}
	fclose(fp);
}
Example #26
0
static void save(int quick)
{
	int i;
	char *bi, *bo;
	int n;
	int b;
	char hgz[256];
	char tmp[256];
	char bak[256];
	char bkp[256];
	time_t now;
	struct tm *tms;
	static int lastbak = -1;

	//_dprintf("%s: quick=%d\n", __FUNCTION__, quick);

	f_write("/var/lib/misc/rstats-stime", &save_utime, sizeof(save_utime), 0, 0);

	comp(speed_fn, speed, sizeof(speed[0]) * speed_count);

/*
	if ((now = time(0)) < Y2K) {
		_dprintf("%s: time not set\n", __FUNCTION__);
		return;
	}
*/

	comp(history_fn, &history, sizeof(history));

	//_dprintf("%s: write source=%s\n", __FUNCTION__, save_path);
	f_write_string(source_fn, save_path, 0, 0);

	if (quick) {
		return;
	}

	sprintf(hgz, "%s.gz", history_fn);

	if (strcmp(save_path, "*nvram") == 0) {
		if (!wait_action_idle(10)) {
			_dprintf("%s: busy, not saving\n", __FUNCTION__);
			return;
		}

		if ((n = f_read_alloc(hgz, &bi, 20 * 1024)) > 0) {
			if ((bo = malloc(base64_encoded_len(n) + 1)) != NULL) {
				n = base64_encode(bi, bo, n);
				bo[n] = 0;
				nvram_set("rstats_data", bo);
				if (!nvram_match("debug_nocommit", "1")) nvram_commit();

				_dprintf("%s: nvram commit\n", __FUNCTION__);

				free(bo);
			}
		}
		free(bi);
	}
	else if (save_path[0] != 0) {
		strcpy(tmp, save_path);
		strcat(tmp, ".tmp");

		for (i = 15; i > 0; --i) {
			if (!wait_action_idle(10)) {
				_dprintf("%s: busy, not saving\n", __FUNCTION__);
			}
			else {
				_dprintf("%s: cp %s %s\n", __FUNCTION__, hgz, tmp);
				if (eval("cp", hgz, tmp) == 0) {
					_dprintf("%s: copy ok\n", __FUNCTION__);

					if (!nvram_match("rstats_bak", "0")) {
						now = time(0);
						tms = localtime(&now);
						if (lastbak != tms->tm_yday) {
							strcpy(bak, save_path);
							n = strlen(bak);
							if ((n > 3) && (strcmp(bak + (n - 3), ".gz") == 0)) n -= 3;
							strcpy(bkp, bak);
							for (b = HI_BACK-1; b > 0; --b) {
								sprintf(bkp + n, "_%d.bak", b + 1);
								sprintf(bak + n, "_%d.bak", b);
								rename(bak, bkp);
							}
							if (eval("cp", "-p", save_path, bak) == 0) lastbak = tms->tm_yday;
						}
					}

					_dprintf("%s: rename %s %s\n", __FUNCTION__, tmp, save_path);
					if (rename(tmp, save_path) == 0) {
						_dprintf("%s: rename ok\n", __FUNCTION__);
						break;
					}
				}
			}

			// might not be ready
			sleep(3);
			if (gotterm) break;
		}
	}
}
Example #27
0
// used for various testing
static int rctest_main(int argc, char *argv[])
{
	int on;

	if (argc < 3) {
		_dprintf("test what?\n");
	}
	else if (strcmp(argv[1], "rc_service")==0) {
		notify_rc(argv[2]);
	}
	else if(strcmp(argv[1], "get_phy_status")==0) {
		int mask;
		mask = atoi(argv[2]);
		TRACE_PT("debug for phy_status %x\n", get_phy_status(mask));
	}
	else if(strcmp(argv[1], "get_phy_speed")==0) {
		int mask;
		mask = atoi(argv[2]);
		TRACE_PT("debug for phy_speed %x\n", get_phy_speed(mask));
	}
	else if(strcmp(argv[1], "set_phy_ctrl")==0) {
		int mask, ctrl;
		mask = atoi(argv[2]);
		ctrl = atoi(argv[3]);
		TRACE_PT("debug for phy_speed %x\n", set_phy_ctrl(mask, ctrl));
	}
	else if(strcmp(argv[1], "handle_notifications")==0) {
		handle_notifications();
	}
	else if(strcmp(argv[1], "check_action")==0) {
		_dprintf("check: %d\n", check_action());
	}
	else if(strcmp(argv[1], "nvramhex")==0) {
		int i;
		char *nv;

		nv = nvram_safe_get(argv[2]);

		_dprintf("nvram %s(%d): ", nv, strlen(nv));
		for(i=0;i<strlen(nv);i++) {
			_dprintf(" %x", (unsigned char)*(nv+i));
		}
		_dprintf("\n");
	}
	else {
		on = atoi(argv[2]);
		_dprintf("%s %d\n", argv[1], on);

		if (strcmp(argv[1], "vlan") == 0)
		{	
			if(on) start_vlan();
			else stop_vlan();
		}
		else if (strcmp(argv[1], "lan") == 0) {
			if(on) start_lan();
			else stop_lan();
		}
		else if (strcmp(argv[1], "wl") == 0) {
			if(on) 
			{
				start_wl();
				lanaccess_wl();
			}
		}
		else if (strcmp(argv[1], "wan") == 0) {
			if(on) start_wan();
			else stop_wan();
		}
		else if (strcmp(argv[1], "firewall") == 0) {
			//if(on) start_firewall();
			//else stop_firewall();
		}
		else if (strcmp(argv[1], "watchdog") == 0) {
			if(on) start_watchdog();
			else stop_watchdog();
		}
#ifdef RTCONFIG_FANCTRL
		else if (strcmp(argv[1], "phy_tempsense") == 0) {
			if(on) start_phy_tempsense();
			else stop_phy_tempsense();
		}
#endif
#ifdef RTCONFIG_BCMWL6
#ifdef RTCONFIG_PROXYSTA
		else if (strcmp(argv[1], "psta_monitor") == 0) {
			if(on) start_psta_monitor();
			else stop_psta_monitor();
		}
#endif
#endif
		else if (strcmp(argv[1], "qos") == 0) {//qos test
			if(on){
#ifdef RTCONFIG_RALINK
				if (is_module_loaded("hw_nat"))
				{
					modprobe_r("hw_nat");
					sleep(1);
#if 0
					system("echo 0 > /proc/sys/net/ipv4/conf/default/force_igmp_version");
					system("echo 0 > /proc/sys/net/ipv4/conf/all/force_igmp_version");
#endif
				}
#endif
				add_iQosRules(get_wan_ifname(0));
				start_iQos();
			}
			else 
			{
#ifdef RTCONFIG_RALINK
				if (nvram_get_int("hwnat") &&
//					!((nvram_get_int("fw_pt_l2tp") || nvram_get_int("fw_pt_ipsec") || nvram_get_int("wl0_mrate_x") || nvram_get_int("wl1_mrate_x"))) &&
					!is_module_loaded("hw_nat"))
				{
#if 0
					system("echo 2 > /proc/sys/net/ipv4/conf/default/force_igmp_version");
					system("echo 2 > /proc/sys/net/ipv4/conf/all/force_igmp_version");
#endif
					modprobe("hw_nat");
					sleep(1);
				}
#endif
				del_iQosRules();
				stop_iQos();
			}
		}
#ifdef RTCONFIG_WEBDAV
		else if (strcmp(argv[1], "webdav") == 0) {
			if(on)
				start_webdav();
		}
#endif
		else if (strcmp(argv[1], "gpiow") == 0) {
			if(argc>=4) set_gpio(atoi(argv[2]), atoi(argv[3]));
		}
		else if (strcmp(argv[1], "gpior") == 0) {
			_dprintf("%d\n", get_gpio(atoi(argv[2])));
		}
		else if (strcmp(argv[1], "init_switch") == 0) {
			init_switch(on);
		}
		else if (strcmp(argv[1], "set_action") == 0) {
			set_action(on);
		}	
		else {
			printf("what?\n");
		}
	}
	return 0;
}
Example #28
0
int update_dsl_iptv_variables()
{
	char *nv, *nvp, *b;
	char *vpi, *vci, *proto, *encap, *vid;
	int unit = 0;
	char prefix[] = "dslxxx_xxxxxxxx";
	char tmp[64];

	_dprintf("dsltmp_cfg_iptv_pvclist=%s\n", nvram_safe_get("dsltmp_cfg_iptv_pvclist"));

	nvp = nv = strdup(nvram_safe_get("dsltmp_cfg_iptv_pvclist"));
	while(nv && (b = strsep(&nvp, "<")) != NULL){
		if((vstrsep(b, ">", &vpi, &vci, &proto, &encap, &vid) != 5))
			continue;

		unit++;

		_dprintf("vpi=[%s], vci=[%s], proto=[%s], encap=[%s], vid=[%s]\n", vpi, vci, proto, encap, vid);

		if(nvram_match("dsltmp_transmode", "atm")) {
			snprintf(prefix, sizeof(prefix), "dsl%d_", unit);

			nvram_set(strcat_r(prefix, "vpi", tmp), vpi);
			nvram_set(strcat_r(prefix, "vci", tmp), vci);
			nvram_set(strcat_r(prefix, "encap", tmp), encap);
		}
		else {	//ptm
			snprintf(prefix, sizeof(prefix), "dsl8.%d_", unit);

			nvram_set("dslx_transmode", "ptm");
			notify_rc("restart_dsl_setting");
		}

		nvram_set(strcat_r(prefix, "enable", tmp), "1");

		if(!strcmp(proto, "0")) {
			nvram_set(strcat_r(prefix, "proto", tmp), "pppoe");
		}
		else if(!strcmp(proto, "1")) {
			nvram_set(strcat_r(prefix, "proto", tmp), "pppoa");
		}
		else if(!strcmp(proto, "2")) {
			nvram_set(strcat_r(prefix, "proto", tmp), "dhcp");
		}
		else if(!strcmp(proto, "3")) {
			nvram_set(strcat_r(prefix, "proto", tmp), "bridge");
		}
		else if(!strcmp(proto, "4")) {
			nvram_set(strcat_r(prefix, "proto", tmp), "ipoa");
		}
		else {
			nvram_set(strcat_r(prefix, "proto", tmp), "bridge");
		}

		if(strlen(vid)) {
			nvram_set(strcat_r(prefix, "dot1q", tmp), "1");
			nvram_set(strcat_r(prefix, "vid", tmp), vid);
		}
	}
	free(nv);

	if(unit) {
		if(nvram_match("switch_stb_x", "1")
			&& (nvram_get_int("dslx_config_num") > 1)
		) {
			nvram_set("dsltmp_qis_reboot", "0");
		}
		else {
			nvram_set("switch_stb_x", "1");
			nvram_set("wans_lanport", "4");
			nvram_set("dsltmp_qis_reboot", "1");
		}
	}
	else {
		if(nvram_match("switch_stb_x", "0"))  {
			nvram_set("dsltmp_qis_reboot", "0");
		}
		else {
			nvram_set("switch_stb_x", "0");
			nvram_set("dsl1_enable", "0");
			nvram_set("dsl2_enable", "0");
			nvram_set("dsl3_enable", "0");
			nvram_set("dsl4_enable", "0");
			nvram_set("dsl5_enable", "0");
			nvram_set("dsl6_enable", "0");
			nvram_set("dsl7_enable", "0");
#ifdef RTCONFIG_VDSL
			nvram_set("dsl8.1_enable", "0");
			nvram_set("dsl8.2_enable", "0");
			nvram_set("dsl8.3_enable", "0");
			nvram_set("dsl8.4_enable", "0");
			nvram_set("dsl8.5_enable", "0");
			nvram_set("dsl8.6_enable", "0");
			nvram_set("dsl8.7_enable", "0");
#endif
			nvram_set("dsltmp_qis_reboot", "1");
		}
	}

	return 0;
}
Example #29
0
/**
 * debug_dump:
 * @lp: pointer to memory region.
 * @len: length of memory region in bytes.
 * 
 * Writes a dump of a memory region to stdout.  The dump contains a
 * hexadecimal and an ascii representation of the memory region.
 * 
 **/
void debug_dump(void*lp, long len)
{
   char * p;
   long i, j, start;
   char Buff[80];
   char stuffBuff[10];
   char tmpBuf[10];
  
   _dprintf("Dump of %ld=%lx bytes\n",len, len);
   start = 0L;
   while (start < len)
   {
    /* start line with pointer position key */
      p = (char*)lp + start;
      sprintf(Buff,"%p: ",p);
  
    /* display each character as hex value */
      for (i=start, j=0; j < 16; p++,i++, j++)
      {
         if (i < len)
         {
            sprintf(tmpBuf,"%X",((int)(*p) & 0xFF));
  
            if (strlen((char *)tmpBuf) < 2)
            {
               stuffBuff[0] = '0';
               stuffBuff[1] = tmpBuf[0];
               stuffBuff[2] = ' ';
               stuffBuff[3] = '\0';
            } else
            {
               stuffBuff[0] = tmpBuf[0];
               stuffBuff[1] = tmpBuf[1];
               stuffBuff[2] = ' ';
               stuffBuff[3] = '\0';
            }
            strcat(Buff, stuffBuff);
         } else
            strcat(Buff," ");
         if (j == 7) /* space between groups of 8 */
            strcat(Buff," ");
      }
  
    /* fill out incomplete lines */
      for(;j<16;j++)
      {
         strcat(Buff,"   ");
         if (j == 7)
            strcat(Buff," ");
      }
      strcat(Buff,"  ");
  
    /* display each character as character value */
      for (i=start,j=0,p=(char*)lp+start;
         (i < len && j < 16); p++,i++, j++)
      {
         if ( ((*p) >= ' ') && ((*p) <= '~') )   /* test displayable */
            sprintf(tmpBuf,"%c", *p);
         else
            sprintf(tmpBuf,"%c", '.');
         strcat(Buff,tmpBuf);
         if (j == 7)   /* space between groups of 8 */
            strcat(Buff," ");
      }
      _dprintf("%s\n", Buff);
      start = i;  /* next line starting byte */
   }
}
Example #30
0
int main(int argc, char **argv)
{
	char *base;
	int f;

	/*
		Make sure std* are valid since several functions attempt to close these
		handles. If nvram_*() runs first, nvram=0, nvram gets closed. - zzz
	*/

	if ((f = open("/dev/null", O_RDWR)) < 0) {
	}
	else if(f < 3) {
		dup(f);
		dup(f);
	}
	else {
		close(f);
	}

	base = strrchr(argv[0], '/');
	base = base ? base + 1 : argv[0];

#if 0
	if (strcmp(base, "rc") == 0) {
		if (argc < 2) return 1;
		if (strcmp(argv[1], "start") == 0) return kill(1, SIGUSR2);
		if (strcmp(argv[1], "stop") == 0) return kill(1, SIGINT);
		if (strcmp(argv[1], "restart") == 0) return kill(1, SIGHUP);
		++argv;
		--argc;
		base = argv[0];
	}
#endif

#ifdef RTCONFIG_RALINK
    if(getpid() != 1)
    {
#endif

#if defined(DEBUG_NOISY)
	if (nvram_match("debug_logrc", "1")) {
		int i;

		cprintf("[rc %d] ", getpid());
		for (i = 0; i < argc; ++i) {
			cprintf("%s ", argv[i]);
		}
		cprintf("\n");

	}
#endif

#if defined(DEBUG_NOISY)
	if (nvram_match("debug_ovrc", "1")) {
		char tmp[256];
		char *a[32];

		realpath(argv[0], tmp);
		if ((strncmp(tmp, "/tmp/", 5) != 0) && (argc < 32)) {
			sprintf(tmp, "%s%s", "/tmp/", base);
			if (f_exists(tmp)) {
				cprintf("[rc] override: %s\n", tmp);
				memcpy(a, argv, argc * sizeof(a[0]));
				a[argc] = 0;
				a[0] = tmp;
				execvp(tmp, a);
				exit(0);
			}
		}
	}
#endif
#ifdef RTCONFIG_RALINK
    }
#endif
	const applets_t *a;
	for (a = applets; a->name; ++a) {
		if (strcmp(base, a->name) == 0) {
			openlog(base, LOG_PID, LOG_USER);
			return a->main(argc, argv);
		}
	}


	if(!strcmp(base, "restart_wireless")){
		printf("restart wireless...\n");
		restart_wireless();
		return 0;
	}
	else if(!strcmp(base, "nvram_erase")){
		erase_nvram();
		return 0;
	}
#ifdef RTCONFIG_USB
	else if(!strcmp(base, "get_apps_name")){
		if(argc != 2){
			printf("Usage: get_apps_name [File name]\n");
			return 0;
		}

		return get_apps_name(argv[1]);
	}
	else if(!strcmp(base, "asus_sd")){
		if(argc != 3){
			printf("Usage: asus_sd [device_name] [action]\n");
			return 0;
		}

		return asus_sd(argv[1], argv[2]);
	}
	else if(!strcmp(base, "asus_lp")){
		if(argc != 3){
			printf("Usage: asus_lp [device_name] [action]\n");
			return 0;
		}

		return asus_lp(argv[1], argv[2]);
	}
	else if(!strcmp(base, "asus_sg")){
		if(argc != 3){
			printf("Usage: asus_sg [device_name] [action]\n");
			return 0;
		}

		return asus_sg(argv[1], argv[2]);
	}
	else if(!strcmp(base, "asus_sr")){
		if(argc != 3){
			printf("Usage: asus_sr [device_name] [action]\n");
			return 0;
		}

		return asus_sr(argv[1], argv[2]);
	}
	else if(!strcmp(base, "asus_tty")){
		if(argc != 3){
			printf("Usage: asus_tty [device_name] [action]\n");
			return 0;
		}

		return asus_tty(argv[1], argv[2]);
	}
	else if(!strcmp(base, "asus_usbbcm")){
		if(argc != 3){
			printf("Usage: asus_usbbcm [device_name] [action]\n");
			return 0;
		}

		return asus_usbbcm(argv[1], argv[2]);
	}
	else if(!strcmp(base, "asus_usb_interface")){
		if(argc != 3){
			printf("Usage: asus_usb_interface [device_name] [action]\n");
			return 0;
		}

		return asus_usb_interface(argv[1], argv[2]);
	}
	else if (!strcmp(base, "usb_notify")) {
#if defined(RTCONFIG_APP_PREINSTALLED) || defined(RTCONFIG_APP_NETINSTALLED)
		usb_notify();
#endif

		return 0;
	}
#if defined(RTCONFIG_APP_PREINSTALLED) || defined(RTCONFIG_APP_NETINSTALLED)
	else if(!strcmp(base, "run_app_script")){
		if(argc != 3){
			printf("Usage: run_app_script [Package name | allpkg] [APP action]\n");
			return 0;
		}

		if(!strcmp(argv[1], "allpkg"))
			return run_app_script(NULL, argv[2]);
		else
			return run_app_script(argv[1], argv[2]);
	}
	else if (!strcmp(base, "chk_app_state")) {
#define PID_FILE "/var/run/chk_app_state.pid"
		FILE *fp;
		char chk_value[4];

		if(f_read_string(PID_FILE, chk_value, 4) > 0
				&& atoi(chk_value) != getpid()){
			_dprintf("Already running!\n");
			return 0;
		}

		if((fp = fopen(PID_FILE, "w")) == NULL){
			_dprintf("Can't open the pid file!\n");
			return 0;
		}

		fprintf(fp, "%d", getpid());
		fclose(fp);

		memset(chk_value, 0, 4);
		strncpy(chk_value, nvram_safe_get("apps_state_switch"), 4);
		if(strcmp(chk_value, "")){
			if(atoi(chk_value) != APPS_SWITCH_FINISHED && !pids("app_switch.sh")){
				_dprintf("Don't have the switch script.\n");
				nvram_set("apps_state_switch", "");
			}

			unlink(PID_FILE);
			return 0;
		}

		memset(chk_value, 0, 4);
		strncpy(chk_value, nvram_safe_get("apps_state_install"), 4);
		if(strcmp(chk_value, "")){
			if(atoi(chk_value) != APPS_INSTALL_FINISHED && !pids("app_install.sh")){
				_dprintf("Don't have the install script.\n");
				nvram_set("apps_state_install", "");
			}

			unlink(PID_FILE);
			return 0;
		}

		memset(chk_value, 0, 4);
		strncpy(chk_value, nvram_safe_get("apps_state_upgrade"), 4);
		if(strcmp(chk_value, "")){
			if(atoi(chk_value) != APPS_UPGRADE_FINISHED && !pids("app_upgrade.sh")){
				_dprintf("Don't have the upgrade script.\n");
				nvram_set("apps_state_upgrade", "");
			}

			unlink(PID_FILE);
			return 0;
		}

		memset(chk_value, 0, 4);
		strncpy(chk_value, nvram_safe_get("apps_state_enable"), 4);
		if(strcmp(chk_value, "")){
			if(atoi(chk_value) != APPS_ENABLE_FINISHED && !pids("app_set_enabled.sh")){
				_dprintf("Don't have the enable script.\n");
				nvram_set("apps_state_enable", "");
			}

			unlink(PID_FILE);
			return 0;
		}

		unlink(PID_FILE);
		return 0;
	}
#endif
#endif
	else if(!strcmp(base, "ATE")) {
		if( argc == 2 || argc == 3 || argc == 4) {
			asus_ate_command(argv[1], argv[2], argv[3]);
		}
		else
			printf("ATE_ERROR\n");
		return 0;
	}
#if defined(RTCONFIG_RALINK)
	else if (!strcmp(base, "FWRITE")) {
		if (argc == 3)
			return FWRITE(argv[1], argv[2]);
		else
		return 0;
	}
	else if (!strcmp(base, "FREAD")) {
		if (argc == 3)
		{
			unsigned int addr;
			int len;
			addr = strtoul(argv[1], NULL, 16);
			if(argv[2][0] == '0' && argv[2][1] == 'x')
				len  = (int) strtoul(argv[2], NULL, 16);
			else
				len  = (int) strtoul(argv[2], NULL, 10);

			if(len > 0)
				return FREAD(addr, len);
		}
		printf("ATE_ERROR\n");
		return 0;
	}
#if defined(RTCONFIG_HAS_5G)
	else if (!strcmp(base, "asuscfe_5g")) {
		if (argc == 2)
			return asuscfe(argv[1], WIF_5G);
		else
			return EINVAL;
	}
#endif	/* RTCONFIG_HAS_5G */
	else if (!strcmp(base, "asuscfe_2g")) {
		if (argc == 2)
			return asuscfe(argv[1], WIF_2G);
		else
			return EINVAL;
	}
	else if (!strcmp(base, "stainfo_2g")) {
		return stainfo(0);
	}
#if defined(RTCONFIG_HAS_5G)
	else if (!strcmp(base, "stainfo_5g")) {
		return stainfo(1);
	}
#endif	/* RTCONFIG_HAS_5G */
#ifdef RTCONFIG_DSL
	else if(!strcmp(base, "gen_ralink_config")){
		if(argc != 3){
			printf("Usage: gen_ralink_config [band] [is_iNIC]\n");
			return 0;
		}
		return gen_ralink_config(atoi(argv[1]), atoi(argv[2]));
	}
#endif
#endif
	else if(!strcmp(base, "run_telnetd")) {
		run_telnetd();
		return 0;
	}
#ifdef RTCONFIG_SSH
	else if(!strcmp(base, "run_sshd")) {
		start_sshd();
		return 0;
	}
#endif
#if defined(RTCONFIG_PPTPD) || defined(RTCONFIG_ACCEL_PPTPD)
	else if(!strcmp(base, "run_pptpd")) {
		start_pptpd();
		return 0;
	}
#endif
#ifdef RTCONFIG_PARENTALCTRL
	else if(!strcmp(base, "pc")) {
		pc_main(argc, argv);
		return 0;
	}
#endif
#if defined(CONFIG_BCMWL5) || (defined(RTCONFIG_RALINK) && defined(RTCONFIG_WIRELESSREPEATER))
	else if (!strcmp(base, "wlcscan")) {
		return wlcscan_main();
	}
#ifdef RTCONFIG_QTN
	else if (!strcmp(base, "start_psta_qtn")) {
		return start_psta_qtn();
	}
	else if (!strcmp(base, "start_ap_qtn")) {
		return start_ap_qtn();
	}
	else if (!strcmp(base, "start_nodfs_scan_qtn")) {
		return start_nodfs_scan_qtn();
	}
	else if (!strcmp(base, "start_qtn_stateless")) {
		return gen_stateless_conf();
	}
	else if (!strcmp(base, "restart_qtn")){
		return reset_qtn(1);
	}
#endif
#endif
#ifdef RTCONFIG_WIRELESSREPEATER
	else if (!strcmp(base, "wlcconnect")) {
		return wlcconnect_main();
	}
	else if (!strcmp(base, "setup_dnsmq")) {
		if(argc != 2)
			return 0;

		return setup_dnsmq(atoi(argv[1]));
	}
#endif
	else if (!strcmp(base, "add_multi_routes")) {
		return add_multi_routes();
	}
	else if (!strcmp(base, "led_ctrl")) {
		if (argc != 3)
			return 0;

		return(led_control(atoi(argv[1]), atoi(argv[2])));
	}

#ifdef RTCONFIG_BCMARM
	/* mtd-erase2 [device] */
	else if (!strcmp(base, "mtd-erase2")) {
		if (argv[1] && ((!strcmp(argv[1], "boot")) ||
				(!strcmp(argv[1], "linux")) ||
				(!strcmp(argv[1], "linux2")) ||
				(!strcmp(argv[1], "rootfs")) ||
				(!strcmp(argv[1], "rootfs2")) ||
				(!strcmp(argv[1], "nvram")))) {
			return mtd_erase(argv[1]);
		} else {
			fprintf(stderr, "usage: mtd-erase2 [device]\n");
			return EINVAL;
		}
	}
	/* mtd-write2 [path] [device] */
	else if (!strcmp(base, "mtd-write2")) {
		if (argc >= 3)
			return mtd_write(argv[1], argv[2]);
		else {
			fprintf(stderr, "usage: mtd-write2 [path] [device]\n");
			return EINVAL;
		}
	}
#endif
	else if(!strcmp(base, "test_endian")){
		int num = 0x04030201;
		char c = *(char *)(&num);

		if(c == 0x04 || c == 0x01){
			if(c == 0x04)
				printf("Big.\n");
			else
				printf("Little.\n");
		}
		else
			printf("test error!\n");

		return 0;
	}
	else if (!strcmp(base, "free_caches")) {
		int c;
		unsigned int test_num;
		char *set_value = NULL;
		int clean_time = 1;
		int threshold = 0;

		if(argc){
			while((c = getopt(argc, argv, "c:w:t:")) != -1){
				switch(c){
					case 'c': // set the clean-cache mode: 0~3.
						test_num = strtol(optarg, NULL, 10);
			if(test_num == LONG_MIN || test_num == LONG_MAX){
				_dprintf("ERROR: unknown value %s...\n", optarg);
							return 0;
						}

						if(test_num < 0 || test_num > 3){
							_dprintf("ERROR: the value %s was over the range...\n", optarg);
							return 0;
						}

						set_value = optarg;

						break;
					case 'w': // set the waited time for cleaning.
						test_num = strtol(optarg, NULL, 10);
			if(test_num < 0 || test_num == LONG_MIN || test_num == LONG_MAX){
				_dprintf("ERROR: unknown value %s...\n", optarg);
							return 0;
						}

						clean_time = test_num;

						break;
					case 't': // set the waited time for cleaning.
						test_num = strtol(optarg, NULL, 10);
			if(test_num < 0 || test_num == LONG_MIN || test_num == LONG_MAX){
				_dprintf("ERROR: unknown value %s...\n", optarg);
							return 0;
						}

						threshold = test_num;

						break;
					default:
						fprintf(stderr, "Usage: free_caches [ -c clean_mode ] [ -w clean_time ] [ -t threshold ]\n");
						break;
				}
			}
		}

		if(!set_value)
			set_value = FREE_MEM_PAGE;

		free_caches(set_value, clean_time, threshold);

		return 0;
	}
#ifdef RTCONFIG_USB_MODEM
	else if(!strcmp(base, "write_3g_ppp_conf")){
		write_3g_ppp_conf();

		return 0;
	}
#endif
	printf("Unknown applet: %s\n", base);
	return 0;
}