Esempio n. 1
0
/* Tc */
static int start_tqos(void)
{
	int i;
	char *buf, *g, *p;
	unsigned int rate;
	unsigned int ceil;
	unsigned int ibw, obw, bw;
	unsigned int mtu;
	FILE *f;
	int x;
	int inuse;
	char s[256];
	int first;
	char burst_root[32];
	char burst_leaf[32];
#ifdef CONFIG_BCMWL5
	char *protocol="802.1q";
#endif

	// judge interface by get_wan_ifname
	// add Qos iptable rules in mangle table,
	// move it to firewall - mangle_setting
	// add_iQosRules(get_wan_ifname(0)); // iptables start

	ibw = strtoul(nvram_safe_get("qos_ibw"), NULL, 10);
	obw = strtoul(nvram_safe_get("qos_obw"), NULL, 10);
	if(ibw==0||obw==0) return -1;

	if((f = fopen(qosfn, "w")) == NULL) return -2;

	fprintf(stderr, "[qos] tc START!\n");

	/* qos_burst */
	i = nvram_get_int("qos_burst0");
	if(i > 0) sprintf(burst_root, "burst %dk", i);
		else burst_root[0] = 0;
	i = nvram_get_int("qos_burst1");

	if(i > 0) sprintf(burst_leaf, "burst %dk", i);
		else burst_leaf[0] = 0;

	/* Egress OBW  -- set the HTB shaper (Classful Qdisc)
	* the BW is set here for each class
	*/

	mtu = strtoul(nvram_safe_get("wan_mtu"), NULL, 10);
	bw = obw;

	/* WAN */
	fprintf(f,
		"#!/bin/sh\n"
		"#LAN/WAN\n"
		"I=%s\n"
		"SFQ=\"sfq perturb 10\"\n"
		"TQA=\"tc qdisc add dev $I\"\n"
		"TCA=\"tc class add dev $I\"\n"
		"TFA=\"tc filter add dev $I\"\n"
#ifdef CLS_ACT
		"DLIF=imq0\n"
		"TQADL=\"tc qdisc add dev $DLIF\"\n"
		"TCADL=\"tc class add dev $DLIF\"\n"
		"TFADL=\"tc filter add dev $DLIF\"\n"
#endif
		"case \"$1\" in\n"
		"start)\n"
		"#LAN/WAN\n"
		"\ttc qdisc del dev $I root 2>/dev/null\n"
		"\t$TQA root handle 1: htb default %u\n"
#ifdef CLS_ACT
		"\ttc qdisc del dev $DLIF root 2>/dev/null\n"
		"\t$TQADL root handle 2: htb default %u\n"
#endif
		"# upload 1:1\n"
		"\t$TCA parent 1: classid 1:1 htb rate %ukbit ceil %ukbit %s\n" ,
			get_wan_ifname(0), // judge WAN interface
			(nvram_get_int("qos_default") + 1) * 10,
#ifdef CLS_ACT
			(nvram_get_int("qos_default") + 1) * 10,
#endif
			bw, bw, burst_root);

	/* LAN protocol: 802.1q */
#ifdef CONFIG_BCMWL5 // TODO: it is only for the case, eth0 as wan, vlanx as lan
	protocol = "802.1q";
	fprintf(f,
		"# download 1:2\n"
		"\t$TCA parent 1: classid 1:2 htb rate 1000000kbit ceil 1000000kbit burst 10000 cburst 10000\n"
		"# 1:60 ALL Download for BCM\n"
		"\t$TCA parent 1:2 classid 1:60 htb rate 1000000kbit ceil 1000000kbit burst 10000 cburst 10000 prio 6\n"
		"\t$TQA parent 1:60 handle 60: pfifo\n"
		"\t$TFA parent 1: prio 6 protocol %s handle 6 fw flowid 1:60\n", protocol
		);
#endif

	inuse = nvram_get_int("qos_inuse");

	g = buf = strdup(nvram_safe_get("qos_orates"));
	for (i = 0; i < 5; ++i) { // 0~4 , 0:highest, 4:lowest

		if ((!g) || ((p = strsep(&g, ",")) == NULL)) break;

		if ((inuse & (1 << i)) == 0){
			fprintf(stderr, "[qos] egress %d doesn't create, inuse=%d\n", i, inuse );
			continue;
		}
		else
			fprintf(stderr, "[qos] egress %d creates\n", i);

		if ((sscanf(p, "%u-%u", &rate, &ceil) != 2) || (rate < 1)) continue;

		if (ceil > 0) sprintf(s, "ceil %ukbit ", calc(bw, ceil));
			else s[0] = 0;
		x = (i + 1) * 10;

		fprintf(f,
			"# egress %d: %u-%u%%\n"
			"\t$TCA parent 1:1 classid 1:%d htb rate %ukbit %s %s prio %d quantum %u\n"
			"\t$TQA parent 1:%d handle %d: $SFQ\n"
			"\t$TFA parent 1: prio %d protocol ip handle %d fw flowid 1:%d\n",
				i, rate, ceil,
				x, calc(bw, rate), s, burst_leaf, (i >= 6) ? 7 : (i + 1), mtu,
				x, x,
				x, i + 1, x);
	}
	free(buf);

	/*
		10000 = ACK
		00100 = RST
		00010 = SYN
		00001 = FIN
	*/

	if (nvram_match("qos_ack", "on")) {
		fprintf(f,
			"\n"
			"\t$TFA parent 1: prio 14 protocol ip u32 "
			"match ip protocol 6 0xff "			// TCP
			"match u8 0x05 0x0f at 0 "			// IP header length
			"match u16 0x0000 0xffc0 at 2 "			// total length (0-63)
			"match u8 0x10 0xff at 33 "			// ACK only
			"flowid 1:10\n");
	}
	if (nvram_match("qos_syn", "on")) {
		fprintf(f,
			"\n"
			"\t$TFA parent 1: prio 15 protocol ip u32 "
			"match ip protocol 6 0xff "			// TCP
			"match u8 0x05 0x0f at 0 "			// IP header length
			"match u16 0x0000 0xffc0 at 2 "			// total length (0-63)
			"match u8 0x02 0x02 at 33 "			// SYN,*
			"flowid 1:10\n");
	}
	if (nvram_match("qos_fin", "on")) {
		fprintf(f,
			"\n"
			"\t$TFA parent 1: prio 17 protocol ip u32 "
			"match ip protocol 6 0xff "			// TCP
			"match u8 0x05 0x0f at 0 "			// IP header length
			"match u16 0x0000 0xffc0 at 2 "			// total length (0-63)
			"match u8 0x01 0x01 at 33 "			// FIN,*
			"flowid 1:10\n");
	}
	if (nvram_match("qos_rst", "on")) {
		fprintf(f,
			"\n"
			"\t$TFA parent 1: prio 19 protocol ip u32 "
			"match ip protocol 6 0xff "			// TCP
			"match u8 0x05 0x0f at 0 "			// IP header length
			"match u16 0x0000 0xffc0 at 2 "			// total length (0-63)
			"match u8 0x04 0x04 at 33 "			// RST,*
			"flowid 1:10\n");
	}
	if (nvram_match("qos_icmp", "on")) {
		fputs("\n\t$TFA parent 1: prio 13 protocol ip u32 match ip protocol 1 0xff flowid 1:10\n", f);
	}

	// ingress
	first = 1;
	bw = ibw;

	if (bw > 0) {
		g = buf = strdup(nvram_safe_get("qos_irates"));
		for (i = 0; i < 5; ++i) { // 0~4 , 0:highest, 4:lowest
			if ((!g) || ((p = strsep(&g, ",")) == NULL)) break;
			if ((inuse & (1 << i)) == 0) continue;
			if ((rate = atoi(p)) < 1) continue;	// 0 = off

			if (first) {
				first = 0;
				fprintf(f,
					"\n"
#if !defined(CLS_ACT)
					"\ttc qdisc del dev $I ingress 2>/dev/null\n"
					"\t$TQA handle ffff: ingress\n"
#endif
					);
			}

			// rate in kb/s
			unsigned int u = calc(bw, rate);

			// burst rate
			unsigned int v = u / 2;
			if (v < 50) v = 50;

#ifdef CLS_ACT
			x = (i + 1) * 10;
			fprintf(f,
				"# ingress %d: %u%%\n"
				"\t$TCADL parent 2:1 classid 2:%d htb rate %ukbit %s prio %d quantum %u\n"
				"\t$TQADL parent 2:%d handle %d: $SFQ\n"
				"\t$TFADL parent 2: prio %d protocol ip handle %d fw flowid 2:%d\n",
					i, rate,
					x, calc(bw, rate), burst_leaf, (i >= 6) ? 7 : (i + 1), mtu,
					x, x,
					x, i + 1, x);
#else
			x = i + 1;
			fprintf(f,
				"# ingress %d: %u%%\n"
				"\t$TFA parent ffff: prio %d protocol ip handle %d"
					" fw police rate %ukbit burst %ukbit drop flowid ffff:%d\n",
					i, rate, x, x, u, v, x);
#endif
		}
		free(buf);
	}

	fputs(
		"\t;;\n"
		"stop)\n"
		"\ttc qdisc del dev $I root 2>/dev/null\n"
#ifdef CLS_ACT
		"\ttc qdisc del dev $DLIF root 2>/dev/null\n"
#else
		"\ttc qdisc del dev $I ingress 2>/dev/null\n"
#endif
		"\t;;\n"
		"*)\n"
		"\t#---------- Upload ----------\n"
		"\ttc -s -d class ls dev $I\n"
		"\ttc -s -d qdisc ls dev $I\n"
		"\techo\n"
#ifdef CLS_ACT
		"\t#--------- Download ---------\n"
		"\ttc -s -d class ls dev $DLIF\n"
		"\ttc -s -d qdisc ls dev $DLIF\n"
		"\techo\n"
#endif
		"esac\n",
		f);

	fclose(f);
	chmod(qosfn, 0700);
	eval((char *)qosfn, "start");

	run_custom_script("qos-start", "init");
	fprintf(stderr,"[qos] tc done!\n");

	return 0;
}
Esempio n. 2
0
const char *default_wanif(void)
{
	return ((strtoul(nvram_safe_get("boardflags"), NULL, 0) & BFL_ENETVLAN) ||
		(check_hw_type() == HW_BCM4712)) ? "vlan1" : "eth1";
}
Esempio n. 3
0
void start_pptp(int status)
{
	int ret;
	FILE *fp;
	char *pptp_argv[] = { "pppd",
		NULL
	};
	char username[80], passwd[80];

	stop_dhcpc();
#ifdef HAVE_PPPOE
	stop_pppoe();
#endif
	stop_vpn_modules();

	snprintf(username, sizeof(username), "%s",
		 nvram_safe_get("ppp_username"));
	snprintf(passwd, sizeof(passwd), "%s", nvram_safe_get("ppp_passwd"));

	if (status != REDIAL) {
		create_pptp_config(nvram_safe_get("pptp_server_name"),
				   username);
		/*
		 * Generate pap-secrets file 
		 */
		if (!(fp = fopen("/tmp/ppp/pap-secrets", "w"))) {
			perror("/tmp/ppp/pap-secrets");
			return;
		}
		fprintf(fp, "\"%s\" * \"%s\" *\n", username, passwd);
		fclose(fp);
		chmod("/tmp/ppp/pap-secrets", 0600);

		/*
		 * Generate chap-secrets file 
		 */
		if (!(fp = fopen("/tmp/ppp/chap-secrets", "w"))) {
			perror("/tmp/ppp/chap-secrets");
			return;
		}
		fprintf(fp, "\"%s\" * \"%s\" *\n", username, passwd);
		fclose(fp);
		chmod("/tmp/ppp/chap-secrets", 0600);

		/*
		 * Enable Forwarding 
		 */
		if ((fp = fopen("/proc/sys/net/ipv4/ip_forward", "r+"))) {
			fputc('1', fp);
			fclose(fp);
		} else
			perror("/proc/sys/net/ipv4/ip_forward");
	}
	char *wan_ifname = nvram_safe_get("wan_ifname");

	if (isClient()) {
		wan_ifname = getSTA();
	}

	nvram_set("pptp_ifname", wan_ifname);
	/*
	 * Bring up WAN interface 
	 */
	if (nvram_match("pptp_use_dhcp", "1")) {
		// pid_t pid;
		// char *wan_ipaddr;
		// char *wan_netmask;
		// char *wan_gateway;

		// char *pptp_server_ip = nvram_safe_get ("pptp_server_ip");
		// char *wan_hostname = nvram_safe_get ("wan_hostname");

		nvram_set("wan_get_dns", "");
		nvram_unset("dhcpc_done");
		//dirty hack
		start_dhcpc(wan_ifname, NULL, NULL, 1);
		int timeout;

		for (timeout = 60; !nvram_match("dhcpc_done", "1") && timeout > 0; --timeout) {	/* wait for info from dhcp server */
			sleep(1);
		}
		stop_dhcpc();	/* we don't need dhcp client anymore */
		create_pptp_config(nvram_safe_get("pptp_server_ip"), username);

	} else {
		ifconfig(wan_ifname, IFUP, nvram_safe_get("wan_ipaddr"),
			 nvram_safe_get("wan_netmask"));
		struct dns_lists *dns_list = NULL;
		dns_to_resolv();
		dns_list = get_dns_list();
		int i = 0;

		if (dns_list) {
			for (i = 0; i < dns_list->num_servers; i++)
				route_add(wan_ifname, 0,
					  dns_list->dns_server[i],
					  nvram_safe_get("pptp_wan_gateway"),
					  "255.255.255.255");
		}
		route_add(wan_ifname, 0, "0.0.0.0",
			  nvram_safe_get("pptp_wan_gateway"), "0.0.0.0");
		char pptpip[64];
		getIPFromName(nvram_safe_get("pptp_server_name"), pptpip);
		route_del(wan_ifname, 0, "0.0.0.0",
			  nvram_safe_get("pptp_wan_gateway"), "0.0.0.0");
		if (dns_list) {
			for (i = 0; i < dns_list->num_servers; i++)
				route_del(wan_ifname, 0,
					  dns_list->dns_server[i],
					  nvram_safe_get("pptp_wan_gateway"),
					  "255.255.255.255");
			free(dns_list);
		}
		
		nvram_set("pptp_server_ip", pptpip);
		if (!nvram_match("pptp_wan_gateway", "0.0.0.0"))
			route_add(wan_ifname, 0,
				  nvram_safe_get("pptp_server_ip"),
				  nvram_safe_get("pptp_wan_gateway"),
				  "255.255.255.255");
	}
	ret = _evalpid(pptp_argv, NULL, 0, NULL);

	if (nvram_match("ppp_demand", "1")) {
		/*
		 * Trigger Connect On Demand if user press Connect button in Status
		 * page 
		 */
		if (nvram_match("action_service", "start_pptp")
		    || nvram_match("action_service", "start_l2tp")) {
			start_force_to_dial();
			// force_to_dial(nvram_safe_get("action_service"));
			nvram_unset("action_service");
		}
		/*
		 * Trigger Connect On Demand if user ping pptp server 
		 */
		else {
			eval("listen", nvram_safe_get("lan_ifname"));
		}
	}
	stop_wland();
	start_wshaper();
	start_wland();
	cprintf("done\n");
	return;
}
Esempio n. 4
0
char *GOZILA_GET(webs_t wp, char *name)
{
	return nvram_match("gozila_action", "1") ? websGetVar(wp, name, NULL) : nvram_safe_get(name);
}
Esempio n. 5
0
void setup_conntrack(void)
{
	unsigned int v[10];
	const char *p;
	int i;
	
	p = nvram_safe_get("ct_tcp_timeout");
	if (sscanf(p, "%u%u%u%u%u%u%u%u%u%u",
		&v[0], &v[1], &v[2], &v[3], &v[4], &v[5], &v[6], &v[7], &v[8], &v[9]) == 10) {	// lightly verify
		f_write_string("/proc/sys/net/ipv4/ip_conntrack_tcp_timeouts", p, 0, 0);
	}
	
	p = nvram_safe_get("ct_udp_timeout");
	if (sscanf(p, "%u%u", &v[0], &v[1]) == 2) {
		f_write_string("/proc/sys/net/ipv4/ip_conntrack_udp_timeouts", p, 0, 0);
	}
	
	p = nvram_safe_get("ct_max");
	i = atoi(p);
	if ((i >= 128) && (i <= 65535)) {
		f_write_string("/proc/sys/net/ipv4/ip_conntrack_max", p, 0, 0);
	}

	if (!nvram_match("nf_pptp", "0")) {
		modprobe("ip_conntrack_proto_gre");
		modprobe("ip_nat_proto_gre");
		modprobe("ip_conntrack_pptp");
		modprobe("ip_nat_pptp");
	}
	else {
		modprobe_r("ip_nat_pptp");
		modprobe_r("ip_conntrack_pptp");
		modprobe_r("ip_nat_proto_gre");
		modprobe_r("ip_conntrack_proto_gre");
	}

	if (!nvram_match("nf_h323", "0")) {
		modprobe("ip_conntrack_h323");
		modprobe("ip_nat_h323");
	}
	else {
		modprobe_r("ip_nat_h323");
		modprobe_r("ip_conntrack_h323");
	}
	
	if (!nvram_match("nf_rtsp", "0")) {
		modprobe("ip_conntrack_rtsp");
		modprobe("ip_nat_rtsp");
	}
	else {
		modprobe_r("ip_nat_rtsp");
		modprobe_r("ip_conntrack_rtsp");
	}

	if (!nvram_match("nf_ftp", "0")) {
		modprobe("ip_conntrack_ftp");
		modprobe("ip_nat_ftp");
	}
	else {
		modprobe_r("ip_nat_ftp");
		modprobe_r("ip_conntrack_ftp");
	}

}
Esempio n. 6
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;
					memcpy(ptr->speed, &tmp.speed, sizeof(uint64_t) * MAX_NSPEED * MAX_COUNTER);
					memcpy(ptr->last, &tmp.last, sizeof(uint64_t) * MAX_COUNTER);
					ptr->tail = tmp.tail;
//					ptr->sync = tmp.sync;
					ptr->sync = -1;

					if (ptr->utime > uptime) {
						ptr->utime = 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;
}
Esempio n. 7
0
static int
qmi_start_network(const char* control_node)
{
	FILE *fp;
	int i, qmi_client_id = -1;
	char *qmi_nets, *pin_code, *usr_name, *usr_pass;
	char clid_cmd[64], auth_cmd[64];

	/* enter PIN-code */
	pin_code = nvram_safe_get("modem_pin");
	if (*pin_code)
		doSystem("/bin/uqmi -d /dev/%s %s %s", control_node, "--verify-pin1", pin_code);

	/* setup network */
	qmi_nets = "all";
	switch (nvram_get_int("modem_nets"))
	{
	case 9:
		qmi_nets = "td-scdma";
		break;
	case 8:
		qmi_nets = "cdma";
		break;
	case 7:
		qmi_nets = "gsm";
		break;
	case 6:
		qmi_nets = "gsm,umts";
		break;
	case 5:
		qmi_nets = "umts,gsm";
		break;
	case 4:
		qmi_nets = "umts";
		break;
	case 3:
		qmi_nets = "lte,umts,gsm";
		break;
	case 2:
		qmi_nets = "lte,umts";
		break;
	case 1:
		qmi_nets = "lte";
		break;
	}
	doSystem("/bin/uqmi -d /dev/%s %s %s", control_node, "--set-network-modes", qmi_nets);

	/* try to use previous client id */
	fp = fopen(QMI_CLIENT_ID, "r");
	if (fp) {
		fscanf(fp, "%d", &qmi_client_id);
		fclose(fp);
	}

	if (qmi_client_id < 0) {
		/* fail, obtain new client id */
		doSystem("/bin/uqmi -d /dev/%s %s %s", control_node, "--get-client-id", "wds");
		fp = fopen(QMI_CLIENT_ID, "r");
		if (fp) {
			fscanf(fp, "%d", &qmi_client_id);
			fclose(fp);
		}
	}

	clid_cmd[0] = 0;
	if (qmi_client_id >= 0)
		snprintf(clid_cmd, sizeof(clid_cmd), " --set-client-id wds,%d", qmi_client_id);

	usr_name = nvram_safe_get("modem_user");
	usr_pass = nvram_safe_get("modem_pass");

	auth_cmd[0] = 0;
	if (*usr_name && *usr_pass)
		snprintf(auth_cmd, sizeof(auth_cmd), " --auth-type both --username \"%s\" --password \"%s\"", usr_name, usr_pass);

	unlink(QMI_HANDLE_OK);
	for (i = 0; i < 3; i++) {
		doSystem("/bin/uqmi -d /dev/%s%s --keep-client-id wds%s --start-network \"%s\"", 
				control_node, clid_cmd, auth_cmd, nvram_safe_get("modem_apn"));
		if (check_if_file_exist(QMI_HANDLE_OK))
			return 0;
		sleep(1);
	}

	return 1;
}
Esempio n. 8
0
void write_nfsd_exports(void)
{
	FILE *procpt, *fp;
	char line[256], devname[32], mpname[128], system_type[16], mount_mode[164], acl_mask[64];
	const char* exports_link = "/etc/storage/exports";
	const char* exports_file = "/etc/exports";
	char *nfsmm, *lan_ipaddr, *lan_netmask;
	unsigned int acl_addr;
	struct in_addr ina;

	unlink(exports_file);

	if (check_if_file_exist(exports_link)) {
		symlink(exports_link, exports_file);
		return;
	}

	fp = fopen(exports_file, "w");
	if (!fp)
		return;

	lan_ipaddr  = nvram_safe_get("lan_ipaddr_t");
	lan_netmask = nvram_safe_get("lan_netmask_t");
	if (!lan_ipaddr || !*lan_ipaddr)
		lan_ipaddr = nvram_safe_get("lan_ipaddr");
	if (!lan_netmask || !*lan_netmask)
		lan_netmask = nvram_safe_get("lan_netmask");
	if (!lan_ipaddr || !*lan_ipaddr)
		lan_ipaddr = "192.168.1.1";
	if (!lan_netmask || !*lan_netmask)
		lan_netmask = "255.255.255.0";

	acl_addr = ntohl(inet_addr(lan_ipaddr));
	acl_addr = acl_addr & ntohl(inet_addr(lan_netmask));

	ina.s_addr = htonl(acl_addr);

	sprintf(acl_mask, "%s/%s", inet_ntoa(ina), lan_netmask);

	fprintf(fp, "# %s\n\n", "auto-created file");

	procpt = fopen("/proc/mounts", "r");
	if (procpt) {
		while (fgets(line, sizeof(line), procpt)) {
			if (sscanf(line, "%31s %127s %15s %163s %*s %*s", devname, mpname, system_type, mount_mode) != 4)
				continue;
			
			if (!strcmp(system_type, "fuseblk"))
				continue;
			
			if (!strncmp(devname, "/dev/sd", 7) && !strncmp(mpname, "/media/", 7)) {
				nfsmm = "rw";
				if (!strncmp(mount_mode, "ro", 2))
					nfsmm = "ro";
				fprintf(fp, "%s    %s(%s,async,insecure,no_root_squash,no_subtree_check)\n", mpname, acl_mask, nfsmm);
			}
		}
		
		fclose(procpt);
	}

	fclose(fp);
}
Esempio n. 9
0
static void 
update_firefly_conf(const char *link_path, const char *conf_path, const char *conf_file)
{
	FILE *fp1, *fp2;
	char tmp1[64], tmp2[64], line[128];

	snprintf(tmp1, sizeof(tmp1), "%s/%s", conf_path, conf_file);

	if (check_if_file_exist(tmp1)) {
		snprintf(tmp2, sizeof(tmp2), "%s/%s.tmp", conf_path, conf_file);
		fp1 = fopen(tmp1, "r");
		if (fp1) {
			fp2 = fopen(tmp2, "w");
			if (fp2) {
				while (fgets(line, sizeof(line), fp1)){
					if (strncmp(line, "web_root", 8) == 0)
						snprintf(line, sizeof(line), "web_root = %s\n", "/usr/share/mt-daapd");
					if (strncmp(line, "port", 4) == 0)
						snprintf(line, sizeof(line), "port = %d\n", 3689);
					else if (strncmp(line, "runas", 5) == 0)
						snprintf(line, sizeof(line), "runas = %s\n", nvram_safe_get("http_username"));
					else if (strncmp(line, "db_type", 7) == 0)
						snprintf(line, sizeof(line), "db_type = %s\n", "sqlite3");
					else if (strncmp(line, "db_parms", 8) == 0)
						snprintf(line, sizeof(line), "db_parms = %s\n", link_path);
					else if (strncmp(line, "plugin_dir", 10) == 0)
						snprintf(line, sizeof(line), "plugin_dir = %s\n", "/usr/lib/mt-daapd");
					fprintf(fp2, "%s", line);
				}
				fclose(fp2);
				fclose(fp1);
				rename(tmp2, tmp1);
			}
			else
				fclose(fp1);
		}
	}
	else {
		fp1 = fopen(tmp1, "w");
		if (fp1) {
			fprintf(fp1, "[general]\n");
			fprintf(fp1, "web_root = %s\n", "/usr/share/mt-daapd");
			fprintf(fp1, "port = %d\n", 3689);
			fprintf(fp1, "runas = %s\n", nvram_safe_get("http_username"));
			fprintf(fp1, "admin_pw = %s\n", nvram_safe_get("http_passwd"));
			fprintf(fp1, "db_type = %s\n", "sqlite3");
			fprintf(fp1, "db_parms = %s\n", link_path);
			fprintf(fp1, "logfile = %s/mt-daapd.log\n", link_path);
			fprintf(fp1, "servername = %s\n", "Firefly on %h");
			fprintf(fp1, "mp3_dir = %s\n", "/media");
			fprintf(fp1, "extensions = %s\n", ".mp3,.m4a,.m4p,.flac,.alac");
			fprintf(fp1, "rescan_interval = %d\n", 300);
			fprintf(fp1, "always_scan = %d\n", 0);
			fprintf(fp1, "scan_type = %d\n", 0);
			fprintf(fp1, "debuglevel = %d\n\n", 0);
			fprintf(fp1, "[scanning]\n");
			fprintf(fp1, "skip_first = %d\n", 1);
			fprintf(fp1, "process_playlists = %d\n", 1);
			fprintf(fp1, "process_itunes = %d\n", 1);
			fprintf(fp1, "process_m3u = %d\n", 1);
			fprintf(fp1, "mp3_tag_codepage = %s\n\n", "WINDOWS-1251");
			fprintf(fp1, "[plugins]\n");
			fprintf(fp1, "plugin_dir = %s\n\n", "/usr/lib/mt-daapd");
			fclose(fp1);
		}
	}
}
Esempio n. 10
0
void
write_vsftpd_conf(void)
{
	FILE *fp;
	int i_maxuser, i_ftp_mode;

	fp=fopen("/etc/vsftpd.conf", "w");
	if (!fp) return;
	
	fprintf(fp, "listen%s=YES\n", 
#if defined (USE_IPV6)
	(get_ipv6_type() != IPV6_DISABLED) ? "_ipv6" :
#endif
	"");
	fprintf(fp, "background=YES\n");
	fprintf(fp, "connect_from_port_20=NO\n");
	fprintf(fp, "pasv_enable=YES\n");
	fprintf(fp, "pasv_min_port=%d\n", 50000);
	fprintf(fp, "pasv_max_port=%d\n", 50100);
	fprintf(fp, "ssl_enable=NO\n");
	fprintf(fp, "tcp_wrappers=NO\n");
	fprintf(fp, "isolate=NO\n");
	fprintf(fp, "isolate_network=NO\n");
	fprintf(fp, "use_sendfile=YES\n");

	i_ftp_mode = nvram_get_int("st_ftp_mode");
	if (i_ftp_mode == 1 || i_ftp_mode == 3) {
		fprintf(fp, "local_enable=%s\n", "NO");
		fprintf(fp, "anonymous_enable=%s\n", "YES");
		if (i_ftp_mode == 1){
			fprintf(fp, "anon_upload_enable=YES\n");
			fprintf(fp, "anon_mkdir_write_enable=YES\n");
			fprintf(fp, "anon_other_write_enable=YES\n");
			fprintf(fp, "anon_umask=000\n");
		}
	}
	else {
		fprintf(fp, "local_enable=%s\n", "YES");
		fprintf(fp, "local_umask=000\n");
		fprintf(fp, "anonymous_enable=%s\n", (i_ftp_mode == 2) ? "NO" : "YES");
	}

	fprintf(fp, "nopriv_user=root\n");
	fprintf(fp, "write_enable=YES\n");
	fprintf(fp, "chroot_local_user=YES\n");
	fprintf(fp, "allow_writable_root=YES\n");
	fprintf(fp, "check_shell=NO\n");
	fprintf(fp, "xferlog_enable=NO\n");
	fprintf(fp, "syslog_enable=%s\n", (nvram_get_int("st_ftp_log") == 0) ? "NO" : "YES");
	fprintf(fp, "force_dot_files=YES\n");
	fprintf(fp, "dirmessage_enable=YES\n");
	fprintf(fp, "hide_ids=YES\n");
	fprintf(fp, "utf8=YES\n");
	fprintf(fp, "idle_session_timeout=%d\n", 600);

	i_maxuser = nvram_get_int("st_max_user");
	if (i_maxuser < 1) i_maxuser = 1;
	if (i_maxuser > MAX_CLIENTS_NUM) i_maxuser = MAX_CLIENTS_NUM;

	fprintf(fp, "max_clients=%d\n", i_maxuser);
	fprintf(fp, "max_per_ip=%d\n", i_maxuser);
	fprintf(fp, "ftpd_banner=Welcome to ASUS %s FTP service.\n", nvram_safe_get("productid"));
	
	fclose(fp);
}
Esempio n. 11
0
int
write_smb_conf(void)
{
	FILE *fp;
	int i_maxuser, i_smb_mode;
	disk_info_t *follow_disk, *disks_info = NULL;
	partition_info_t *follow_partition;

	i_smb_mode = nvram_get_int("st_samba_mode");

	fp = write_smb_conf_header();
	if (!fp)
		return -1;

	/* share mode */
	if (i_smb_mode == 1 || i_smb_mode == 3) {
		char *rootnm = nvram_safe_get("http_username");
		if (!(*rootnm)) rootnm = "admin";
		
		fprintf(fp, "security = %s\n", "SHARE");
		fprintf(fp, "guest ok = %s\n", "yes");
		fprintf(fp, "guest only = yes\n");
		fprintf(fp, "guest account = %s\n", rootnm);
	} else if (i_smb_mode == 4) {
		fprintf(fp, "security = %s\n", "USER");
		fprintf(fp, "guest ok = %s\n", "no");
		fprintf(fp, "map to guest = Bad User\n");
		fprintf(fp, "hide unreadable = yes\n");
	} else {
		goto confpage;
	}

	fprintf(fp, "writeable = yes\n");
	fprintf(fp, "directory mode = 0777\n");
	fprintf(fp, "create mask = 0777\n");
	fprintf(fp, "force directory mode = 0777\n");

	/* max users */
	i_maxuser = nvram_get_int("st_max_user");
	if (i_maxuser < 1) i_maxuser = 1;
	if (i_maxuser > MAX_CLIENTS_NUM) i_maxuser = MAX_CLIENTS_NUM;

	fprintf(fp, "max connections = %d\n", i_maxuser);
	fprintf(fp, "use spnego = no\n");		// ASUS add
	fprintf(fp, "client use spnego = no\n");	// ASUS add
	fprintf(fp, "null passwords = yes\n");		// ASUS add
	fprintf(fp, "strict allocate = no\n");		// ASUS add
	fprintf(fp, "use sendfile = yes\n");
	fprintf(fp, "dos filemode = yes\n");
	fprintf(fp, "dos filetimes = yes\n");
	fprintf(fp, "dos filetime resolution = yes\n");
	fprintf(fp, "\n");

	disks_info = read_disk_data();
	if (!disks_info) {
		goto confpage;
	}

	/* share */
	if (i_smb_mode == 1) {
		for (follow_disk = disks_info; follow_disk != NULL; follow_disk = follow_disk->next) {
			for (follow_partition = follow_disk->partitions; follow_partition != NULL; follow_partition = follow_partition->next) {
				char *mount_folder;
				
				if (follow_partition->mount_point == NULL)
					continue;
				
				mount_folder = strrchr(follow_partition->mount_point, '/')+1;
				
				fprintf(fp, "[%s]\n", mount_folder);
				fprintf(fp, "comment = %s's %s\n", follow_disk->tag, mount_folder);
				fprintf(fp, "path = %s\n", follow_partition->mount_point);
				fprintf(fp, "guest ok = yes\n");
				fprintf(fp, "writeable = yes\n");
				fprintf(fp, "directory mode = 0777\n");
				fprintf(fp, "create mask = 0777\n");
				fprintf(fp, "map archive = no\n");
				fprintf(fp, "map hidden = no\n");
				fprintf(fp, "map read only = no\n");
				fprintf(fp, "map system = no\n");
				fprintf(fp, "store dos attributes = yes\n\n");
			}
		}
	} else if (i_smb_mode == 3) {
		fprintf(fp, "[%s]\n", "Media");
		fprintf(fp, "comment = %s\n", "Root share for all media");
		fprintf(fp, "path = %s\n", POOL_MOUNT_ROOT);
		fprintf(fp, "guest ok = yes\n");
		fprintf(fp, "writeable = yes\n");
		fprintf(fp, "directory mode = 0777\n");
		fprintf(fp, "create mask = 0777\n");
		fprintf(fp, "map archive = no\n");
		fprintf(fp, "map hidden = no\n");
		fprintf(fp, "map read only = no\n");
		fprintf(fp, "map system = no\n");
		fprintf(fp, "store dos attributes = yes\n\n");
	} else {
		int n, acc_num = 0, sh_num=0;
		char **account_list;
		
		// get the account list
		if (get_account_list(&acc_num, &account_list) < 0) {
			usb_dbg("Can't read the account list.\n");
			free_2_dimension_list(&acc_num, &account_list);
			goto confpage;
		}
		
		for (follow_disk = disks_info; follow_disk != NULL; follow_disk = follow_disk->next) {
			for (follow_partition = follow_disk->partitions; follow_partition != NULL; follow_partition = follow_partition->next) {
				if (follow_partition->mount_point == NULL)
					continue;
				
				char **folder_list;
				
				// 1. get the folder list
				if (get_folder_list_in_mount_path(follow_partition->mount_point, &sh_num, &folder_list) < 0) {
					usb_dbg("Can't read the folder list in %s.\n", follow_partition->mount_point);
					free_2_dimension_list(&sh_num, &folder_list);
					continue;
				}
				
				// 2. start to get every share
				for (n = 0; n < sh_num; ++n) {
					int i, right, first;
					char share[256];
					
					memset(share, 0, 256);
					strcpy(share, folder_list[n]);
					
					fclose(fp);
					
					if(check_existed_share(share)){
						i = 1;
						memset(share, 0, 256);
						sprintf(share, "%s(%d)", folder_list[n], i);
						while(check_existed_share(share)){
							++i;
							memset(share, 0, 256);
							sprintf(share, "%s(%d)", folder_list[n], i);
						}
					}
					
					if((fp = fopen(SAMBA_CONF, "a")) == NULL)
						goto confpage;
					fprintf(fp, "[%s]\n", share);
					fprintf(fp, "comment = %s\n", folder_list[n]);
					fprintf(fp, "path = %s/%s\n", follow_partition->mount_point, folder_list[n]);
					fprintf(fp, "writeable = no\n");
					
					fprintf(fp, "valid users = ");
					first = 1;
					for (i = 0; i < acc_num; ++i) {
						right = get_permission(account_list[i], follow_partition->mount_point, folder_list[n], "cifs");
						if (first == 1)
							first = 0;
						else
							fprintf(fp, ", ");
						
						fprintf(fp, "%s", account_list[i]);
					}
					fprintf(fp, "\n");
					
					fprintf(fp, "invalid users = ");
					first = 1;
					for (i = 0; i < acc_num; ++i) {
						right = get_permission(account_list[i], follow_partition->mount_point, folder_list[n], "cifs");
						if (right >= 1)
							continue;
						
						if (first == 1)
							first = 0;
						else
							fprintf(fp, ", ");
						
						fprintf(fp, "%s", account_list[i]);
					}
					fprintf(fp, "\n");
					
					fprintf(fp, "read list = ");
					first = 1;
					for (i = 0; i < acc_num; ++i) {
						right = get_permission(account_list[i], follow_partition->mount_point, folder_list[n], "cifs");
						if (right < 1)
							continue;
						
						if (first == 1)
							first = 0;
						else
							fprintf(fp, ", ");
						
						fprintf(fp, "%s", account_list[i]);
					}
					fprintf(fp, "\n");
					
					fprintf(fp, "write list = ");
					first = 1;
					for (i = 0; i < acc_num; ++i) {
						right = get_permission(account_list[i], follow_partition->mount_point, folder_list[n], "cifs");
						if (right < 2)
							continue;
						
						if (first == 1)
							first = 0;
						else
							fprintf(fp, ", ");
						
						fprintf(fp, "%s", account_list[i]);
					}
					fprintf(fp, "\n");
				}
				
				free_2_dimension_list(&sh_num, &folder_list);
			}
		}
		
		free_2_dimension_list(&acc_num, &account_list);
	}

confpage:
	fclose(fp);
	free_disk_data(disks_info);
	return 0;
}
Esempio n. 12
0
void start_sysinit(void)
{
	char buf[PATH_MAX];
	struct stat tmp_stat;
	time_t tm = 0;

	mknod("/dev/gpio",S_IFCHR|0644,makedev(127,0));
	mkdir("/usr/local",0700);
	mkdir("/usr/local/nvram",0700);

	install_sdcard();
	cprintf("sysinit() setup console\n");
	eval("insmod", "ks8695_wdt", "wdt_time=30");	// load watchdog module with 30 seconds timeout
	if (!nvram_match("disable_watchdog", "1"))
		eval("watchdog");
	/*
	 * Setup console 
	 */

	cprintf("sysinit() klogctl\n");
	klogctl(8, NULL, atoi(nvram_safe_get("console_loglevel")));
	cprintf("sysinit() get router\n");

	int brand = getRouterBrand();

	/*
	 * network drivers 
	 */
	eval("ifconfig", "eth0", "up");
	eval("ifconfig", "eth1", "up");
	eval("ifconfig", "eth2", "up");
	eval("ifconfig", "eth3", "up");
	struct ifreq ifr;
	int s;

	if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW))) {
		char eabuf[32];

		strncpy(ifr.ifr_name, "eth0", IFNAMSIZ);
		ioctl(s, SIOCGIFHWADDR, &ifr);
		nvram_set("et0macaddr",
			  ether_etoa((unsigned char *)ifr.ifr_hwaddr.sa_data,
				     eabuf));
		nvram_set("et0macaddr_safe",
			  ether_etoa((unsigned char *)ifr.ifr_hwaddr.sa_data,
				     eabuf));
		close(s);
	}

	detect_wireless_devices();

	system2("echo 1 >/proc/sys/dev/wifi0/softled");

	/*
	 * Set a sane date 
	 */
	stime(&tm);
	nvram_set("wl0_ifname", "ath0");
	//disable led's 
	return;
	cprintf("done\n");
}
Esempio n. 13
0
void start_sysinit(void)
{
    char buf[PATH_MAX];
    struct stat tmp_stat;
    time_t tm = 0;

    eval("/bin/tar", "-xzf", "/dev/mtdblock/3", "-C", "/");
    FILE *in = fopen("/tmp/nvram/nvram.db", "rb");

    if (in != NULL) {
        fclose(in);
        eval("/usr/sbin/convertnvram");
        eval("/sbin/mtd", "erase", "nvram");
        nvram_commit();
    }
    if (!nvram_match("disable_watchdog", "1"))
        eval("watchdog");
    /*
     * Setup console
     */

    cprintf("sysinit() klogctl\n");
    klogctl(8, NULL, atoi(nvram_safe_get("console_loglevel")));
    cprintf("sysinit() get router\n");

    int brand = getRouterBrand();
    insmod("zlib_deflate");
    insmod("crc-ccitt");
    insmod("crypto");
    insmod("crypto_algapi");
    insmod("crypto_blkcipher");
    insmod("crypto_hash");
    insmod("crypto_wq");
    insmod("aead");
    insmod("arc4");
    insmod("ecb");
    insmod("pcompress");
    insmod("rng");
    insmod("sha1_generic");
    insmod("chainiv");
    insmod("eseqiv");
    insmod("cryptomgr");

    insmod("slhc");
    insmod("ppp_generic");
    insmod("ppp_async");
    insmod("ppp_synctty");
    insmod("ppp_mppe");
    insmod("pppox");
    insmod("pppoe");

    insmod("nf_conntrack_h323");
    insmod("nf_nat_h323");
    insmod("nf_conntrack_sip");
    insmod("nf_nat_sip");

    insmod("xt_state");
    insmod("xt_recent");
    insmod("xt_physdev");
    insmod("xt_mac");
    insmod("xt_limit");
    insmod("xt_layer7");
    insmod("xt_dscp");
    insmod("xt_connlimit");
    insmod("xt_multiport");
    insmod("xt_DSCP");

    /*
     * network drivers
     */
#ifdef HAVE_HOTPLUG2
    insmod("ar231x");
#else
    insmod("ar2313");
#endif

    detect_wireless_devices();

    writeproc("/proc/sys/dev/wifi0/ledpin", "2");
    writeproc("/proc/sys/dev/wifi0/softled", "1");
    writeproc("/proc/sys/dev/wifi0/ledpin", "3");
    writeproc("/proc/sys/dev/wifi0/softled", "1");

    // eval ("ifconfig", "wifi0", "up");
    // eval ("ifconfig", "wifi1", "up");

    /*
     * Set a sane date
     */
    stime(&tm);
    nvram_set("wl0_ifname", "ath0");

    return;
    cprintf("done\n");
}
Esempio n. 14
0
if (nvram_match("dhcp_enable_x", "1") && nvram_match("dnsqmode", "2") 
#ifdef RTCONFIG_DEFAULT_AP_MODE
				&& !nvram_match("ate_flag", "1")
#endif
		) {
			if ((fp = fopen("/etc/dnsmasq.conf", "w+")) != NULL) {
				/* DHCP range */
				char dhcp_start[16], dhcp_end[16], lan_netmask[16];

				strcpy(dhcp_start, nvram_safe_get("dhcp_start"));
				strcpy(dhcp_end, nvram_safe_get("dhcp_end"));
				strcpy(lan_netmask, nvram_safe_get("lan_netmask"));

				if (!chk_valid_startend(lan_ipaddr, dhcp_start, dhcp_end, lan_netmask)) {
					dbg("reset DHCP range: %s ~ %s\n", dhcp_start, dhcp_end);
					nvram_set("dhcp_start", dhcp_start);
					nvram_set("dhcp_end", dhcp_end);
				}

				fprintf(fp, "interface=%s\n", nvram_safe_get("lan_ifname"));
				fprintf(fp, "dhcp-range=lan,%s,%s,%s,%ss\n", 
								dhcp_start, 
								dhcp_end, 
								lan_netmask, 
								nvram_safe_get("dhcp_lease"));
				fprintf(fp, "dhcp-leasefile=/tmp/dnsmasq.leases\n");
				/* Gateway */
				fprintf(fp, "dhcp-option=lan,3,%s\n", lan_ipaddr);
				/* Faster for moving clients, if authoritative */
				fprintf(fp, "dhcp-authoritative\n");
				/* caching */
Esempio n. 15
0
// used for various testing
static int rctest_main(int argc, char *argv[])
{
    int on;

    if (argc < 2) {
        _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 (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") &&
                        /* TODO: consider RTCONFIG_DUALWAN case */
//					!nvram_match("wan0_proto", "l2tp") &&
//					!nvram_match("wan0_proto", "pptp") &&
//					!(nvram_get_int("fw_pt_l2tp") || nvram_get_int("fw_pt_ipsec") &&
//					(nvram_match("wl0_radio", "0") || nvram_get_int("wl0_mrate_x")) &&
//					(nvram_match("wl1_radio", "0") || nvram_get_int("wl1_mrate_x")) &&
                        !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

#if defined(RTN14U) || defined(RTAC52U) || defined(RTAC51U) || defined(RTN11P)
                    if (!(!nvram_match("switch_wantag", "none")&&!nvram_match("switch_wantag", "")))
#endif
                    {
                        modprobe("hw_nat");
                        sleep(1);
                    }
                }
#endif
                stop_iQos();
                del_iQosRules();
            }
        }
#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], "gpiod") == 0) {
            if(argc>=4) gpio_dir(atoi(argv[2]), atoi(argv[3]));
        }
        else if (strcmp(argv[1], "init_switch") == 0) {
            init_switch(on);
        }
        else if (strcmp(argv[1], "set_action") == 0) {
            set_action(on);
        }
        else if (strcmp(argv[1], "pwr_usb") == 0) {
            set_pwr_usb(atoi(argv[2]));
            _dprintf("done.\n");
        }
#ifdef RTCONFIG_BCMFA
        else if (strcmp(argv[1], "fa_rev") == 0) {
            _dprintf("(%d) done.\n", get_fa_rev());
        }
#endif
        else {
            printf("what?\n");
        }
    }
    return 0;
}
Esempio n. 16
0
void setupSupplicant(char *prefix)
{
	char akm[16];

	sprintf(akm, "%s_akm", prefix);
	char wmode[16];

	sprintf(wmode, "%s_mode", prefix);
	if (nvram_match(akm, "8021X")) {
		char fstr[32];
		char psk[64];
		char ath[64];

		sprintf(fstr, "/tmp/%s_wpa_supplicant.conf", prefix);
		FILE *fp = fopen(fstr, "wb");

		fprintf(fp, "ap_scan=1\n");
		fprintf(fp, "fast_reauth=1\n");
		fprintf(fp, "eapol_version=1\n");
		fprintf(fp, "network={\n");
		sprintf(psk, "%s_ssid", prefix);
		fprintf(fp, "\tssid=\"%s\"\n", nvram_safe_get(psk));
		fprintf(fp, "\tscan_ssid=1\n");
		if (nvram_prefix_match("8021xtype", prefix, "tls")) {
// -> added habeIchVergessen
			char *keyExchng = nvram_nget("%s_tls8021xkeyxchng", prefix);
			char *wpaOpts[40];
			if (strlen(keyExchng)==0)
			    nvram_nset("wep","%s_tls8021xkeyxchng", prefix);
			sprintf(wpaOpts, "");
			keyExchng = nvram_nget("%s_tls8021xkeyxchng", prefix);
			if (strcmp("wpa2", keyExchng) == 0)
				sprintf(wpaOpts, "\tpairwise=CCMP\n\tgroup=CCMP\n");
			if (strcmp("wpa2mixed", keyExchng) == 0)
                         	sprintf(wpaOpts, "\tpairwise=CCMP TKIP\n\tgroup=CCMP TKIP\n");
			if (strcmp("wpa", keyExchng) == 0)
                        	sprintf(wpaOpts, "\tpairwise=TKIP\n\tgroup=TKIP\n");
			fprintf(fp, "\tkey_mgmt=%s\n%s", (strlen(wpaOpts) == 0 ? "IEEE8021X" : "WPA-EAP"), wpaOpts);
// <- added habeIchVergessen
			fprintf(fp, "\teap=TLS\n");
			fprintf(fp, "\tidentity=\"%s\"\n",
				nvram_prefix_get("tls8021xuser", prefix));
			sprintf(psk, "/tmp/%s", prefix);
			mkdir(psk);
			sprintf(psk, "/tmp/%s/ca.pem", prefix);
			sprintf(ath, "%s_tls8021xca", prefix);
			write_nvram(psk, ath);
			sprintf(psk, "/tmp/%s/user.pem", prefix);
			sprintf(ath, "%s_tls8021xpem", prefix);
			write_nvram(psk, ath);

			sprintf(psk, "/tmp/%s/user.prv", prefix);
			sprintf(ath, "%s_tls8021xprv", prefix);
			write_nvram(psk, ath);
			fprintf(fp, "\tca_cert=/tmp/%s/ca.pem\n", prefix);
			fprintf(fp, "\tclient_cert=/tmp/%s/user.pem\n", prefix);
			fprintf(fp, "\tprivate_key=/tmp/%s/user.prv\n", prefix);
			fprintf(fp, "\tprivate_key_passwd=\"%s\"\n",
				nvram_prefix_get("tls8021xpasswd", prefix));
			fprintf(fp, "\teapol_flags=3\n");
			if (strlen(nvram_nget("%s_tls8021xphase2", prefix)) > 0) {
				fprintf(fp, "\tphase2=\"%s\"\n",
					nvram_nget("%s_tls8021xphase2",
						   prefix));
			}
			if (strlen(nvram_nget("%s_tls8021xanon", prefix)) > 0) {
				fprintf(fp, "\tanonymous_identity=\"%s\"\n",
					nvram_nget("%s_tls8021xanon", prefix));
			}
			if (strlen(nvram_nget("%s_tls8021xaddopt", prefix)) > 0) {
				sprintf(ath, "%s_tls8021xaddopt", prefix);
				fprintf(fp, "\t");	// tab
				fwritenvram(ath, fp);
				fprintf(fp, "\n");	// extra new line at the end
			}
		}
		if (nvram_prefix_match("8021xtype", prefix, "peap")) {
			fprintf(fp, "\tkey_mgmt=WPA-EAP\n");
			fprintf(fp, "\teap=PEAP\n");
			fprintf(fp, "\tpairwise=CCMP TKIP\n");
			fprintf(fp, "\tgroup=CCMP TKIP\n");
			fprintf(fp, "\tphase1=\"peapver=0\"\n");
			fprintf(fp, "\tidentity=\"%s\"\n",
				nvram_prefix_get("peap8021xuser", prefix));
			fprintf(fp, "\tpassword=\"%s\"\n",
				nvram_prefix_get("peap8021xpasswd", prefix));
			sprintf(psk, "/tmp/%s", prefix);
			mkdir(psk);
			sprintf(psk, "/tmp/%s/ca.pem", prefix);
			sprintf(ath, "%s_peap8021xca", prefix);
			if (!nvram_match(ath, "")) {
				write_nvram(psk, ath);
				fprintf(fp, "\tca_cert=\"/tmp/%s/ca.pem\"\n",
					prefix);
			}
			if (strlen(nvram_nget("%s_peap8021xphase2", prefix)) >
			    0) {
				fprintf(fp, "\tphase2=\"%s\"\n",
					nvram_nget("%s_peap8021xphase2",
						   prefix));
			}
			if (strlen(nvram_nget("%s_peap8021xanon", prefix)) > 0) {
				fprintf(fp, "\tanonymous_identity=\"%s\"\n",
					nvram_nget("%s_peap8021xanon", prefix));
			}
			if (strlen(nvram_nget("%s_peap8021xaddopt", prefix)) >
			    0) {
				sprintf(ath, "%s_peap8021xaddopt", prefix);
				fprintf(fp, "\t");	// tab
				fwritenvram(ath, fp);
				fprintf(fp, "\n");	// extra new line at the end
			}
		}
		if (nvram_prefix_match("8021xtype", prefix, "ttls")) {
			fprintf(fp, "\tkey_mgmt=WPA-EAP\n");
			fprintf(fp, "\teap=TTLS\n");
			fprintf(fp, "\tpairwise=CCMP TKIP\n");
			fprintf(fp, "\tgroup=CCMP TKIP\n");
			fprintf(fp, "\tidentity=\"%s\"\n",
				nvram_prefix_get("ttls8021xuser", prefix));
			fprintf(fp, "\tpassword=\"%s\"\n",
				nvram_prefix_get("ttls8021xpasswd", prefix));
			if (strlen(nvram_nget("%s_ttls8021xca", prefix)) > 0) {
				sprintf(psk, "/tmp/%s", prefix);
				mkdir(psk);
				sprintf(psk, "/tmp/%s/ca.pem", prefix);
				sprintf(ath, "%s_ttls8021xca", prefix);
				write_nvram(psk, ath);
				fprintf(fp, "\tca_cert=\"/tmp/%s/ca.pem\"\n",
					prefix);
			}
			if (strlen(nvram_nget("%s_ttls8021xphase2", prefix)) >
			    0) {
				fprintf(fp, "\tphase2=\"%s\"\n",
					nvram_nget("%s_ttls8021xphase2",
						   prefix));
			}
			if (strlen(nvram_nget("%s_ttls8021xanon", prefix)) > 0) {
				fprintf(fp, "\tanonymous_identity=\"%s\"\n",
					nvram_nget("%s_ttls8021xanon", prefix));
			}
			if (strlen(nvram_nget("%s_ttls8021xaddopt", prefix)) >
			    0) {
				sprintf(ath, "%s_ttls8021xaddopt", prefix);
				fprintf(fp, "\t");	// tab
				fwritenvram(ath, fp);
				fprintf(fp, "\n");	// extra new line at the end
			}
		}
		if (nvram_prefix_match("8021xtype", prefix, "leap")) {
			fprintf(fp, "\tkey_mgmt=WPA-EAP\n");
			fprintf(fp, "\teap=LEAP\n");
			fprintf(fp, "\tauth_alg=LEAP\n");
			fprintf(fp, "\tproto=WPA RSN\n");
			fprintf(fp, "\tpairwise=CCMP TKIP\n");
			fprintf(fp, "\tgroup=CCMP TKIP\n");
			fprintf(fp, "\tidentity=\"%s\"\n",
				nvram_prefix_get("leap8021xuser", prefix));
			fprintf(fp, "\tpassword=\"%s\"\n",
				nvram_prefix_get("leap8021xpasswd", prefix));
			if (strlen(nvram_nget("%s_leap8021xphase2", prefix)) >
			    0) {
				fprintf(fp, "\tphase2=\"%s\"\n",
					nvram_nget("%s_leap8021xphase2",
						   prefix));
			}
			if (strlen(nvram_nget("%s_leap8021xanon", prefix)) > 0) {
				fprintf(fp, "\tanonymous_identity=\"%s\"\n",
					nvram_nget("%s_leap8021xanon", prefix));
			}
			if (strlen(nvram_nget("%s_leap8021xaddopt", prefix)) >
			    0) {
				sprintf(ath, "%s_leap8021xaddopt", prefix);
				fprintf(fp, "\t");	// tab
				fwritenvram(ath, fp);
				fprintf(fp, "\n");	// extra new line at the end
			}
		}
		fprintf(fp, "}\n");
		fclose(fp);
		sprintf(psk, "-i%s", getRADev(prefix));

		char bvar[32];

		sprintf(bvar, "%s_bridged", prefix);
		if (nvram_match(bvar, "1")
		    && (nvram_match(wmode, "wdssta")
			|| nvram_match(wmode, "wet")))
			eval("wpa_supplicant", "-b",
			     nvram_safe_get("lan_ifname"), "-B", "-Dralink",
			     psk, "-c", fstr);
		else
			eval("wpa_supplicant", "-B", "-Dralink", psk, "-c",
			     fstr);
	}

}
Esempio n. 17
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;
    }
    else if (!strcmp(base, "asuscfe_5g")) {
        if (argc == 2)
            return asuscfe(argv[1], WIF_5G);
        else
            return EINVAL;
    }
    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);
    }
    else if (!strcmp(base, "stainfo_5g")) {
        return stainfo(1);
    }
#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;
    }
#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();
    }
#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;
    }
    printf("Unknown applet: %s\n", base);
    return 0;
}
Esempio n. 18
0
void start_sysinit(void)
{
	char buf[PATH_MAX];
	struct stat tmp_stat;
	time_t tm = 0;

	if (!nvram_match("disable_watchdog", "1")) {
		insmod("imx2_wdt");
		eval("watchdog");
	}
	/*
	 * Setup console 
	 */
	eval("mount", "-o", "remount,rw", "/");
	eval("mkdir", "-p", "/usr/local/nvram");

	cprintf("sysinit() klogctl\n");
	klogctl(8, NULL, atoi(nvram_safe_get("console_loglevel")));
	cprintf("sysinit() get router\n");

	int brand = getRouterBrand();

	//for extension board
	struct ifreq ifr;
	int s;

	fprintf(stderr, "try modules for ethernet adapters\n");
	nvram_set("intel_eth", "0");
	insmod("sky2");
	if (detect_ethernet_devices())
		nvram_set("intel_eth", "1");

	/*
	 * network drivers 
	 */
	detect_wireless_devices();

	if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW))) {
		char eabuf[32];

		strncpy(ifr.ifr_name, "eth0", IFNAMSIZ);
		ioctl(s, SIOCGIFHWADDR, &ifr);
		nvram_set("et0macaddr", ether_etoa((unsigned char *)ifr.ifr_hwaddr.sa_data, eabuf));
		nvram_set("et0macaddr_safe", ether_etoa((unsigned char *)ifr.ifr_hwaddr.sa_data, eabuf));
		close(s);
	}
	eval("ifconfig", "eth0", "promisc");
	eval("ifconfig", "eth1", "promisc");
	/*
	 * Set a sane date 
	 */
	stime(&tm);
	nvram_set("wl0_ifname", "ath0");
	eval("hwclock", "-s");
	eval("i2cset", "-f", "-y", "0", "0x20", "0", "0x0");
	eval("i2cset", "-f", "-y", "0", "0x20", "11", "0x10");
	char *board = nvram_safe_get("DD_BOARD");
	char *board2 = nvram_safe_get("DD_BOARD2");
	if (!strncmp(board, "Gateworks Ventana GW54",22)
	    || !strncmp(board2, "Gateworks Ventana GW54",22))
		sysprintf("gsp_updater -f /etc/gsc_5400_v43.txt 43");

	if (!strncmp(board, "Gateworks Ventana GW53",22)
	    || !strncmp(board2, "Gateworks Ventana GW53",22))
		sysprintf("gsp_updater -f /etc/gsc_5300_v43.txt 43");

	if (!strncmp(board, "Gateworks Ventana GW52",22)
	    || !strncmp(board2, "Gateworks Ventana GW52",22))
		sysprintf("gsp_updater -f /etc/gsc_5200_v43.txt 43");

	if (!strncmp(board, "Gateworks Ventana GW51",22)
	    || !strncmp(board2, "Gateworks Ventana GW51",22))
		sysprintf("gsp_updater -f /etc/gsc_5100_v43.txt 43");

	led_control(LED_POWER, LED_ON);
	led_control(LED_DIAG, LED_OFF);
	led_control(LED_SES, LED_OFF);
	led_control(LED_SES2, LED_OFF);
	led_control(LED_BRIDGE, LED_OFF);
	led_control(LED_WLAN0, LED_OFF);
	led_control(LED_WLAN1, LED_OFF);
	led_control(LED_CONNECTED, LED_OFF);
	sysprintf("echo ondemand > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor");

	return;
}
Esempio n. 19
0
File: cli.c Progetto: aircross/ray
int
main()
{
    int i;

    /* Catch all signals except SIGKILL. */
    for (i = 0; i < 15; i++) {
        signal(i, sig_handle);
    }

    while (1) {
        FILE *fp;
        char buf1[BUF_LEN], buf2[BUF_LEN];
        char *ptr, *ptr2;
#if defined(PLATFORM_LIS)
        printf("Mosra> ");
#else
        printf("AXIMCom> ");
#endif
        ptr = fgets(buf1, sizeof(buf1), stdin);
        skip_space(ptr);

        if (*ptr == '\n') {
            continue;
        }

        /* If it is authenticated, perhibit all commands. */
        ptr2 = nvram_safe_get("license_invalid");
        if (*ptr2 == '0') {
            continue;
        }

        if (strncmp(ptr, "iwpriv", 6) && strncmp(ptr, "ated", 4) && 
            strncmp(ptr, "fw_version", 10) && strncmp(ptr, "ethernet", 8) &&
            strncmp(ptr, "gpio_stop", 9) && strncmp(ptr, "eeprom", 6) &&
            strncmp(ptr, "get_ssid", 8) && strncmp(ptr, "finalcheck", 10) &&
            strncmp(ptr, "mac", 3) && strncmp(ptr, "charger", 7) &&
            strncmp(ptr, "voltage", 7) && strncmp(ptr, "current", 7) &&
            strncmp(ptr, "percentage", 10) && strncmp(ptr, "set_ssid", 8) &&
            strncmp(ptr, "get_wifi_mac", 12) && strncmp(ptr, "storage", 7) &&
            strncmp(ptr, "mcu_version", 11) && strncmp(ptr, "gauge_fw", 8) &&
            strncmp(ptr, "usb_test", 8) && strncmp(ptr, "card_test", 9) &&
            strncmp(ptr, "internal_test", 13) &&
            strncmp(ptr, "endpoint_test", 13) && strncmp(ptr, "factory", 7) &&
            strncmp(ptr, "iperf_server", sizeof("iperf_server")-1) && 
            strncmp(ptr, "stop_iperf", sizeof("stop_iperf")-1) && 
            strncmp(ptr, "iperf_client", sizeof("iperf_client")-1) && 
            strncmp(ptr, "charger_status", 14) &&
            strncmp(ptr, "audio_test", 10) &&
            strncmp(ptr, "usb_throughput", 14) &&
            strncmp(ptr, "internal_throughput", 19) &&
            strncmp(ptr, "card_throughput", 15) &&
            strncmp(ptr, "get_serial_num", 14) &&
            strncmp(ptr, "set_serial_num", 14) &&
            strncmp(ptr, "get_mfg_test_result", 19) &&
            strncmp(ptr, "set_mfg_test_result", 19) &&
            strncmp(ptr, "w_red_led_on", 12) && 
            strncmp(ptr, "w_red_led_off", 13) && 
            strncmp(ptr, "w_green_led_resume", 18) && 
            strncmp(ptr, "w_green_led_off", 15) && 
            strncmp(ptr, "p_green_led_on", 14) && 
            strncmp(ptr, "p_green_led_off", 15) && 
            strncmp(ptr, "p_led_resume", 12) && 
            strncmp(ptr, "p_red_led_on", 12) &&
            strncmp(ptr, "p_red_led_off", 13) &&
            strncmp(ptr, "p_oled_on", 9) &&
            strncmp(ptr, "p_oled_off", 10) &&
            strncmp(ptr, "p_wm_led_on", 11) &&
            strncmp(ptr, "p_wm_led_off", 12) &&
            strncmp(ptr, "p_pm_led_on", 11) &&
            strncmp(ptr, "p_pm_led_off", 12) &&
            strncmp(ptr, "sec_status", 10) &&
            strncmp(ptr, "usb_status", 10) &&
            strncmp(ptr, "gpio_test", 9) &&
            strncmp(ptr, "led_test", 8) &&
            strncmp(ptr, "wlan_led_test_set", 17) &&
            strncmp(ptr, "wlan_led_test_clear", 19) &&
            strncmp(ptr, "p_blue_led_on", 13) &&
            strncmp(ptr, "set_ssid_mac", 12) && 
            strncmp(ptr, "tcpdump", 7) && 
            strncmp(ptr, "p_blue_led_off", 14) &&
            strncmp(ptr, "switch_lan", 10) &&
            strncmp(ptr, "switch_wan", 10) &&
            strncmp(ptr, "temp_offset", sizeof("temp_offset") - 1) &&
            strncmp(ptr, "temp", sizeof("temp") - 1) &&
            strncmp(ptr, "switch_wan", 10) &&
            strncmp(ptr, "resetbc", sizeof("resetbc") - 1) &&
            strncmp(ptr, "exit", 4) &&
            strncmp(ptr, "quit", 4)){
            printf("Illegal command: %s", ptr);
            continue;
        }

        if (!strncmp(ptr, "set_ssid_mac", 12)) {
            FILE *pFile;
            char ssid[BUF_LEN];
	    char tmp[BUF_LEN];
	    char hwaddr[BUF_LEN], mac[BUF_LEN]={0};
            char *tmp_str, i=0;
            char target[]=":";

            if ((pFile = popen("cat /proc/ezp_machine_id", "r"))) {
                fgets(hwaddr, sizeof(hwaddr), pFile);
            }
            pclose(pFile);
            tmp_str = strtok(hwaddr,target);
            i=2;
            while(tmp_str != NULL)
            {
                tmp_str = strtok( NULL,target);
                if(tmp_str != NULL)
                {
                    if(i>3)
                    {
                        sprintf(mac,"%s%s",mac,tmp_str);
                    }
                }
                i++;
            }
            if(mac[strlen(mac) - 1] == '\n' || mac[strlen(mac) - 1] == '\t' || mac[strlen(mac) - 1] == ' ') mac[strlen(mac) - 1] = 0;

            sscanf(ptr,"set_ssid_mac%s\n",ssid);
            snprintf(tmp,BUF_LEN,"nvram fset wl0_ssid_rule_default=\"%s-%s\"",ssid,mac);
            pFile = popen(tmp, "r");
            snprintf(tmp,BUF_LEN,"nvram fset wl0_ssid_rule=\"%s-%s\"",ssid,mac);
            pclose(pFile);
            pFile = popen(tmp, "r");
            system("nvram commit");
            printf("SSID:%s-%s\n",ssid,mac);
            pclose(pFile);
            continue;
        }

        if (!strncmp(ptr, "set_ssid", 8)) {
            FILE *pFile;
            char ssid[BUF_LEN];
            char tmp[BUF_LEN];
            sscanf(ptr,"set_ssid%s\n",ssid);
            snprintf(tmp,BUF_LEN,"nvram fset wl0_ssid_rule_default=\"%s\"",ssid);
            pFile = popen(tmp, "r");
            snprintf(tmp,BUF_LEN,"nvram fset wl0_ssid_rule=\"%s\"",ssid);
            pclose(pFile);
            pFile = popen(tmp, "r");
            system("nvram commit");
            printf("SSID:%s\n",ssid);
            pclose(pFile);
            continue;
        }

        /* Don't allow these char */
        if (strtok(ptr, "`;\"'?<>|*&^%$@!\\+") && strtok(NULL, "`;\"'?<>|*&^%$@!\\+")) {
            printf("Illegal character: %s", ptr);
            continue;
        }
        if(decide_dot(ptr) || decide_minus(ptr)) {
            printf("Illegal character: %s", ptr);
            continue;
        }
        if (!strncmp(ptr, "fw_version", 10)) {
            char fw_version[BUF_LEN];
#if defined(PLATFORM_LIS)
                ezplib_get_rule("custom_fw_version", 0, fw_version, BUF_LEN);
#else
                ezplib_get_rule("fw_version", 0, fw_version, BUF_LEN);
#endif

            printf("FW Version:%s\n",fw_version);
            continue;
        }
        if (!strncmp(ptr, "storage", 7)) {
            char tmp[BUF_LEN]={0}, tmp2[BUF_LEN]={0};
            FILE *file;
            if ((file = popen("mount | grep USB", "r"))) {
                fgets(tmp, sizeof(tmp), file);
                pclose(file);
            }
            if (strcmp(tmp, "")) { 
                printf("USB:Ready\n");
            } else {
                printf("USB:Not Ready\n");
            }

            if ((file = popen("mount | grep Qsync", "r"))) {
                fgets(tmp, sizeof(tmp), file);
                pclose(file);
            }
            if (strcmp(tmp, "")) { 
                printf("INTERNAL:Ready\n");
            } else {
                printf("INTERNAL:Not Ready\n");
            }

            if ((file = popen("mount | grep SD", "r"))) {
                fgets(tmp2, sizeof(tmp2), file);
                pclose(file);
            }
            if (strcmp(tmp2, "")) { 
                printf("CARD:Ready\n");
            } else {
                printf("CARD:Not Ready\n");
            }

            // terminate
            continue;
        }

        if (!strncmp(ptr, "usb_status", 10)) {
            FILE *file;
            char result[64];
            if ((file = popen("cat /proc/bus/usb/devices|grep  Vendor= -c", "r"))) {
                fgets(result, sizeof(result), file);
                pclose(file);
            }
#if defined(PLATFORM_AXB) || defined(PLATFORM_AXM)
            if (!strncmp(result, "3", 1)) {
#elif defined(PLATFORM_AXA) 
            if (!strncmp(result, "5", 1)) {
#else
            if (0) {
#endif
                printf("USB:Pass\n");
            } else {
                printf("USB:Fail\n");
            }
            continue;
        }

        if (!strncmp(ptr, "sec_status", 10)) {
            FILE *pFile;
            long lSize;
            char *buffer;
            size_t result;
            pFile = popen ( "ezp-i2c security", "r");
            pclose (pFile);
            pFile = fopen ( "/tmp/ezp-i2c_security" , "rb" );
            if (pFile==NULL) {
                printf("No data\n");
                continue;
            }
            // obtain file size:
            fseek (pFile , 0 , SEEK_END);
            lSize = ftell (pFile);
            rewind (pFile);
            // allocate memory to contain the whole file:
            buffer = (char*) malloc (sizeof(char)*lSize);
            if (buffer == NULL) {
                printf("Memory error\n");
                continue;
            }
            // copy the file into the buffer:
            result = fread (buffer,1,lSize,pFile);
            if (result != lSize) {
                printf("Reading error\n");
                continue;
            }
            /* the whole file is now loaded in the memory buffer. */
            printf("%s\n",buffer);
            // terminate
            fclose (pFile);
            free (buffer);
            continue;
        }

        if (!strncmp(ptr, "gauge_fw", 8)) {
            FILE *pFile;
            char result[64];
            int version[1];
            pFile = popen("ezp-i2c gauge fw", "r");
            fgets(result, sizeof(result), pFile);
            pclose(pFile);
            sscanf(result,"Data Read: 0x%02X",&version[0]);
            printf("Gauge Version: %02d\n",version[0]);
            continue;
        }

        if (!strncmp(ptr, "mcu_version", 11)) {
            FILE *pFile;
            char result[64];
            int version[3];
            char platform[BUF_LEN], release[BUF_LEN];
            pFile = popen("ezp-i2c fw", "r");
            fgets(result, sizeof(result), pFile);
            pclose(pFile);
            sscanf(result,"Data Read: 0x%02X 0x%02X 0x%02X",&version[0],&version[1],&version[2]);
            if ( version[2] == 0x10 ) snprintf(platform,BUF_LEN,"Mosra");
            else if ( version[2] == 0x00 ) snprintf(platform,BUF_LEN,"M1");
            if ( version[0] == 0x01) snprintf(release,BUF_LEN,"A"); 
            else if ( version[0] == 0x02) snprintf(release,BUF_LEN,"B"); 
            else if ( version[0] == 0x03) snprintf(release,BUF_LEN,"C"); 
            else snprintf(release,BUF_LEN,"Unknown"); 
            printf("%s MCU Version: %s%02d\n",platform,release,version[1]);
            continue;
        }

        if (!strncmp(ptr, "get_ssid", 8)) {
            char ssid[BUF_LEN];
            ezplib_get_rule("wl0_ssid_rule", 0, ssid, BUF_LEN);
            printf("SSID:%s\n",ssid);
            continue;
        }

        if (!strncmp(ptr, "get_wifi_mac", 12)) {
            FILE *pFile;
            char hwaddr[64];
            if ((pFile = fopen("/proc/ezp_machine_id", "r"))) {
                fgets(hwaddr, sizeof(hwaddr), pFile);
                hwaddr[17] = '\0';
            }
            printf("WiFI MAC:%s\n",hwaddr);
            // terminate
            fclose (pFile);
            continue;
        }

        if (!strncmp(ptr, "ethernet", 8)) {
            FILE *pFile;
            int i=0;
            char tmp[BUF_LEN];
            for (i=0;i<=5;i++) {
                snprintf(tmp,BUF_LEN,"switch  mii w %d 0 0 800",i);
                pFile = popen(tmp, "r");
                pclose(pFile);
            }
            printf("Ethernet open\n");
            continue;
        }

        if (!strncmp(ptr, "gpio_stop", 9)) {
            system("rm /sbin/ezp-gpio");
            printf("GPIO Stop\n");
            continue;
        }

        if (!strncmp(ptr, "mac", 3)) {
            FILE *pFile;
            pFile = popen("/etc/rc.common /etc/init.d/lkey boot mac", "r");
            pclose(pFile);
            printf("MAC Write\n");
            continue;
        }
        if (!strncmp(ptr, "charger_status", 14)) {
            system("ezp-i2c charger status");
            continue;
        }

        if (!strncmp(ptr, "charger", 7)) {
            system("ezp-i2c charger");
            continue;
        }
        
        if (!strncmp(ptr, "voltage", 7)) {
            system("ezp-i2c gauge voltage");
            continue;
        }
        
        if (!strncmp(ptr, "current", 7)) {
            system("ezp-i2c gauge current");
            continue;
        }
        
        if (!strncmp(ptr, "percentage", 10)) {
            system("ezp-i2c gauge percentage");
            continue;
        }
        
        if (!strncmp(ptr, "eeprom", 6)) {
            FILE *pFile;
            int mac[6];
            char *mark;
            char tmp[BUF_LEN], wlv_rule_num[BUF_LEN], add_mac_num=3;
            ezplib_get_rule("wlv_rule_num", 0, wlv_rule_num, BUF_LEN);
            switch (atoi(wlv_rule_num)) {
                case 1:
                    add_mac_num=3;
                    break;
                case 2:
                default :
                    add_mac_num=5;
                    break;
            }
            mark=strstr(ptr,":");
            if(mark == NULL)
            {
                sscanf(ptr,"eeprom%02X%02X%02X%02X%02X%02X",&mac[0],&mac[1],&mac[2],&mac[3],&mac[4],&mac[5]);
            }
            else
            {
                sscanf(ptr,"eeprom%02X:%02X:%02X:%02X:%02X:%02X",&mac[0],&mac[1],&mac[2],&mac[3],&mac[4],&mac[5]);
            }
            snprintf(tmp,BUF_LEN,"iwpriv ra0 e2p 4=%02X%02X",mac[1],mac[0]);
            pFile = popen(tmp, "r");
            pclose(pFile);
            snprintf(tmp,BUF_LEN,"iwpriv ra0 e2p 6=%02X%02X",mac[3],mac[2]);
            pFile = popen(tmp, "r");
            pclose(pFile);
            snprintf(tmp,BUF_LEN,"iwpriv ra0 e2p 8=%02X%02X",mac[5],mac[4]);
            pFile = popen(tmp, "r");
            pclose(pFile);
            snprintf(tmp,BUF_LEN,"iwpriv ra0 e2p 28=%02X%02X",mac[1],mac[0]);
            pFile = popen(tmp, "r");
            pclose(pFile);
            snprintf(tmp,BUF_LEN,"iwpriv ra0 e2p 2a=%02X%02X",mac[3],mac[2]);
            pFile = popen(tmp, "r");
            pclose(pFile);
            snprintf(tmp,BUF_LEN,"iwpriv ra0 e2p 2c=%02X%02X",mac[5]+add_mac_num,mac[4]);
            pFile = popen(tmp, "r");
            pclose(pFile);
            snprintf(tmp,BUF_LEN,"iwpriv ra0 e2p 2e=%02X%02X",mac[1],mac[0]);
            pFile = popen(tmp, "r");
            pclose(pFile);
            snprintf(tmp,BUF_LEN,"iwpriv ra0 e2p 30=%02X%02X",mac[3],mac[2]);
            pFile = popen(tmp, "r");
            pclose(pFile);
            snprintf(tmp,BUF_LEN,"iwpriv ra0 e2p 32=%02X%02X",mac[5]+add_mac_num-1,mac[4]);
            pFile = popen(tmp, "r");
            pclose(pFile);
            pFile = popen("/etc/rc.common /etc/init.d/lkey boot mac", "r");
            pclose(pFile);
            printf("EEPROM Write\n");
            continue;
        }
        if (!strncmp(ptr, "finalcheck", 10)) {
            FILE *pFile;
            long lSize;
            char *buffer;
            size_t result;
            pFile = popen("/etc/rc.common /etc/init.d/lkey boot security", "r");
            pclose(pFile);
            pFile = fopen ( "/tmp/ezp-i2c_security" , "rb" );
            if (pFile==NULL) {
                printf("No data\n");
                continue;
            }
            // obtain file size:
            fseek (pFile , 0 , SEEK_END);
            lSize = ftell (pFile);
            rewind (pFile);
            // allocate memory to contain the whole file:
            buffer = (char*) malloc (sizeof(char)*lSize);
            if (buffer == NULL) {
                printf("Memory error\n"); 
                continue;
            }
            // copy the file into the buffer:
            result = fread (buffer,1,lSize,pFile);
            if (result != lSize) {
                printf("Reading error\n");
                continue;
            }
            /* the whole file is now loaded in the memory buffer. */
            printf("%s\n",buffer);
            // terminate
            fclose (pFile);
            free (buffer);
            continue;
        }
        if (!strncmp(ptr, "usb_test", 8)) {
            FILE *pFile;
            char result[64]={0};
            pFile = fopen ( "/tmp/mnt/USB/mosra_test_a.bin" , "rb" );
            if (pFile==NULL) {
                printf("Cannot find test file mosra_test_a.bin\n");
                printf("Unmount USB!\n");
                system("umount -l /tmp/mnt/USB");
                continue;
            }
            fclose(pFile);
            system("cp /tmp/mnt/USB/mosra_test_a.bin /tmp/mosra_test_b.bin");
            system("cp /tmp/mosra_test_b.bin /tmp/mnt/USB");
            sync();
            if ((pFile = popen("diff -q /tmp/mnt/USB/mosra_test_a.bin /tmp/mnt/USB/mosra_test_b.bin", "r"))) {
                fgets(result, sizeof(result), pFile);
            }
            pclose(pFile);
            if (!strcmp(result, "")) {
                printf("USB test OK!!\n");
            } else {
                printf("USB test Fail!!\n");
            }
            system("rm /tmp/mnt/USB/mosra_test_b.bin");
            system("rm /tmp/mosra_test_b.bin");
            sync();
            printf("Unmount USB!\n");
            system("umount -l /tmp/mnt/USB");
            continue;
        }

        if (!strncmp(ptr, "internal_test", 13)) {
            FILE *pFile;
            char result[64]={0};
            pFile = fopen ( "/tmp/mnt/Qsync/mosra_test_a.bin" , "rb" );
            if (pFile==NULL) {
                printf("Cannot find test file mosra_test_a.bin\n");
                printf("Unmount Qsync!\n");
                system("umount -l /tmp/mnt/Qsync");
                continue;
            }
            fclose(pFile);
            system("cp /tmp/mnt/Qsync/mosra_test_a.bin /tmp/mosra_test_b.bin");
            system("cp /tmp/mosra_test_b.bin /tmp/mnt/Qsync");
            sync();
            if ((pFile = popen("diff -q /tmp/mnt/Qsync/mosra_test_a.bin /tmp/mnt/Qsync/mosra_test_b.bin", "r"))) {
                fgets(result, sizeof(result), pFile);
            }
            pclose(pFile);
            if (!strcmp(result, "")) {
                printf("Qsync test OK!!\n");
            } else {
                printf("Qsync test Fail!!\n");
            }
            system("rm /tmp/mnt/Qsync/mosra_test_b.bin");
            system("rm /tmp/mosra_test_b.bin");
            sync();
            printf("Unmount Qsync!\n");
            system("umount -l /tmp/mnt/Qsync");
            continue;
        }
        if (!strncmp(ptr, "card_test", 9)) {
            FILE *pFile;
            char result[64]={0};
            pFile = fopen ( "/tmp/mnt/SD/mosra_test_a.bin" , "rb" );
            if (pFile==NULL) {
                printf("Cannot find test file mosra_test_a.bin\n");
                printf("Unmount card!\n");
                system("umount -l /tmp/mnt/SD");
                continue;
            }
            fclose(pFile);
            system("cp /tmp/mnt/SD/mosra_test_a.bin /tmp/mosra_test_b.bin");
            system("cp /tmp/mosra_test_b.bin /tmp/mnt/SD");
            sync();
            if ((pFile = popen("diff -q /tmp/mnt/SD/mosra_test_a.bin /tmp/mnt/SD/mosra_test_b.bin", "r"))) {
                fgets(result, sizeof(result), pFile);
            }
            pclose(pFile);
            if (!strcmp(result, "")) {
                printf("Card test OK!!\n");
            } else {
                printf("Card test Fail!!\n");
            }
            system("rm /tmp/mnt/SD/mosra_test_b.bin");
            system("rm /tmp/mosra_test_b.bin");
            sync();
            printf("Unmount card!\n");
            system("umount -l /tmp/mnt/SD");
            continue;
        }

        if (!strncmp(ptr, "endpoint_test", 13)) {
            printf("\nChecking\n");
            int dirfilestate;
            struct stat dirfilebuf;

            dirfilestate = stat("/tmp/mnt/SD/endpoint/endpoint", &dirfilebuf);
            if ( dirfilestate == -1 ) {
                printf("open fail\n");
                continue;
            } else {
                if(dirfilebuf.st_size == 964664)
                    system("/tmp/mnt/SD/endpoint/endpoint");
            }
            continue;
        }
        
        if (!strncmp(ptr, "iperf_server", sizeof("iperf_server")-1)) {
            printf("\nChecking\n");
            int dirfilestate;
            struct stat dirfilebuf;

            dirfilestate = stat("/tmp/mnt/SD/iperf", &dirfilebuf);
            if ( dirfilestate == -1 ) {
                printf("open fail\n");
                continue;
            } else {
                if(dirfilebuf.st_size == 288207)
                    system("/tmp/mnt/SD/iperf -s &");
            }
            continue;
        }
        
        if (!strncmp(ptr, "stop_iperf", sizeof("stop_iperf")-1)) {
            system("kill -9 $(pidof iperf)");
            continue;
        }
        
        if (!strncmp(ptr, "iperf_client", sizeof("iperf_client")-1)) {
            printf("\nChecking\n");
            int dirfilestate;
            struct stat dirfilebuf;

            dirfilestate = stat("/tmp/mnt/SD/iperf", &dirfilebuf);
            if ( dirfilestate == -1 ) {
                printf("open fail\n");
                continue;
            } else {
                if(dirfilebuf.st_size == 288207)
                    system("/tmp/mnt/SD/iperf -c 192.168.40.200 -i 1 -t 20");
            }
            continue;
        }
        
        if (!strncmp(ptr, "audio_test", 10)) {
            printf("\nChecking file\n");
            int dirfilestate;
            struct stat dirfilebuf;

            dirfilestate = stat("/usr/share/audio_test.mp3", &dirfilebuf);
            if ( dirfilestate == -1 ) {
                printf("[AUDIO TEST]OPEN TEST FILE FAIL\n");
                continue;
            } else {
                if(dirfilebuf.st_size != 0)
				{
                    system("madplay /usr/share/audio_test.mp3");
                    printf("[AUDIO TEST]SUCCESS\n");
                }
                else
                {
                    printf("[AUDIO TEST]TEST FILE SIZE ERROR\n");
                }
            }
            continue;
        }
		/*EX:gpio_test set 17*/
        if (!strncmp(ptr, "gpio_test",9)) {
            char *parameter[4];
            char *str_tmp,*str_tmp2;
            char target[]=" ";
            char i=0;
            char data[64];

            str_tmp=strtok(ptr,target);
			
            while(i<3){
                parameter[i] = strtok(NULL,target);
                i++;
            }
            str_tmp2=strtok(parameter[1],"\n");
            snprintf(data,sizeof(data),"gpioctl %s %s ",parameter[0],str_tmp2);
            //printf("%s\r\n",data);
            system(data);
            continue;
        }
		/* EX:led_test 0 1 0 0 0 0 */
        if (!strncmp(ptr, "led_test",8))
        {
            char *parameter[8];
            char *str_tmp,*str_tmp2;
            char target[]=" ";
            char i=0;
            char data[64];

            str_tmp=strtok(ptr,target);
            while(i<8){
                parameter[i] = strtok(NULL,target);
                i++;
            }
            str_tmp2=strtok(parameter[5],"\n");
            snprintf(data,sizeof(data),"gpioctl led %s %s %s %s %s %s > /dev/null",parameter[0],parameter[1],parameter[2],parameter[3],parameter[4],str_tmp2);
            printf("%s\r\n",data);
            system(data);
			continue;
        }
        if (!strncmp(ptr, "wlan_led_test_set",17)) 
        {
            system("iwpriv ra0 set WlanLed=1 > /dev/null");
            printf("[WLAN LED TEST]SET\n");
            continue;
        }
        if (!strncmp(ptr, "wlan_led_test_clear",19))
        {
            system("iwpriv ra0 set WlanLed=0 > /dev/null");
            printf("[WLAN LED TEST]CLEAR\n");
            continue;
        }
        if (!strncmp(ptr, "usb_throughput", 14)) {
            FILE *pFile;
            char result[64]={0};
            struct timeval start,end;
            double timeuse = 2.0;
            double wrrate = 5.5;
            int size_in_mb = 100;
            char cmdbuf[512];
            int cnt = 0;

            sscanf(ptr, "usb_throughput%d", &size_in_mb);
            if(!size_in_mb) {
                size_in_mb = 100;
            }
            if ((pFile = popen("mount | grep USB", "r"))) {
                fgets(result, sizeof(result), pFile);
                pclose(pFile);
            }
            if (!strcmp(result, "")) { 
                printf("Cannot find USB!!\n");
                continue;
            }
            unlink("/tmp/mnt/USB/100mb");
            sync();
            /* Wake up usb */
            snprintf(cmdbuf, sizeof(cmdbuf), "dd if=/dev/zero of=/tmp/mnt/USB/100mb bs=64k count=%d 2>/dev/null 1>/dev/null", size_in_mb * 16);
            for(cnt = 0; cnt < 3; cnt++) {
                system("sdparm --command=ready /dev/sdb 1>/dev/null 2>/dev/null");
                gettimeofday(&start,NULL);
                system(cmdbuf);
                gettimeofday( &end, NULL );
                sync();
                if((end.tv_sec < start.tv_sec) || ((end.tv_sec == start.tv_sec) && (end.tv_usec < start.tv_usec))) {
                    cnt --;
                    continue;
                }
                timeuse = (end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000;
                timeuse = timeuse / 1000;
                wrrate = ((float)size_in_mb) / timeuse;
                if(timeuse < ((float)size_in_mb)/3.0) {
                    break;
                }
                if(cnt == 2)
                    usleep(1000000 * (cnt + 1) * (cnt + 1));
            }
            /* Wake up usb */
            snprintf(cmdbuf, sizeof(cmdbuf), "dd if=/tmp/mnt/USB/100mb of=/dev/null bs=64k count=%d 2>/dev/null 1>/dev/null", size_in_mb * 16);
            for(cnt = 0; cnt < 3; cnt++) {
                system("sdparm --command=ready /dev/sdb 1>/dev/null 2>/dev/null");
                gettimeofday(&start,NULL);
                system(cmdbuf);
                gettimeofday( &end, NULL );
                sync();
                if((end.tv_sec < start.tv_sec) || ((end.tv_sec == start.tv_sec) && (end.tv_usec < start.tv_usec))) {
                    cnt --;
                    continue;
                }
                timeuse = (end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000;
                timeuse = timeuse / 1000;
                if(timeuse < ((float)size_in_mb)/9.0) {
                    break;
                }
                if(cnt == 2)
                    usleep(1000000 * (cnt + 1) * (cnt + 1));
            }
            printf("Write : %f MByte/s\n", wrrate);
            printf("Read : %f MByte/s\n", ((float)size_in_mb) / timeuse);
            system("rm /tmp/mnt/USB/100mb");
            sync();
            continue;
        }
        
        if (!strncmp(ptr, "internal_throughput", 16)) {
            FILE *pFile;
            char result[64]={0};
            struct timeval start,end;
            double timeuse = 2.0;
            double wrrate = 5.5;
            int size_in_mb = 100;
            char cmdbuf[512];
            int cnt = 0;

            sscanf(ptr, "internal_throughput%d", &size_in_mb);
            if(!size_in_mb) {
                size_in_mb = 100;
            }
            if ((pFile = popen("mount | grep Qsync", "r"))) {
                fgets(result, sizeof(result), pFile);
                pclose(pFile);
            }
            if (!strcmp(result, "")) { 
                printf("Cannot find INTERNAL!!\n");
                continue;
            }
            unlink("/tmp/mnt/Qsync/100mb");
            sync();
            /* Wake up qsync*/
            snprintf(cmdbuf, sizeof(cmdbuf), "dd if=/dev/zero of=/tmp/mnt/Qsync/100mb bs=64k count=%d 2>/dev/null 1>/dev/null", size_in_mb * 16);
            for(cnt = 0; cnt < 3; cnt++) {
                system("sdparm --command=ready /dev/sdc 1>/dev/null 2>/dev/null");
                gettimeofday(&start,NULL);
                system(cmdbuf);
                gettimeofday( &end, NULL );
                sync();
                if((end.tv_sec < start.tv_sec) || ((end.tv_sec == start.tv_sec) && (end.tv_usec < start.tv_usec))) {
                    cnt --;
                    continue;
                }
                timeuse = (end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000;
                timeuse = timeuse / 1000;
                wrrate = ((float)size_in_mb) / timeuse;
                if(timeuse < ((float)size_in_mb)/3.0) {
                    break;
                }
                if(cnt == 2)
                    usleep(1000000 * (cnt + 1) * (cnt + 1));
            }
            /* Wake up qsync */
            snprintf(cmdbuf, sizeof(cmdbuf), "dd if=/tmp/mnt/Qsync/100mb of=/dev/null bs=64k count=%d 2>/dev/null 1>/dev/null", size_in_mb * 16);
            for(cnt = 0; cnt < 3; cnt++) {
                system("sdparm --command=ready /dev/sdc 1>/dev/null 2>/dev/null");
                gettimeofday(&start,NULL);
                system(cmdbuf);
                gettimeofday( &end, NULL );
                sync();
                if((end.tv_sec < start.tv_sec) || ((end.tv_sec == start.tv_sec) && (end.tv_usec < start.tv_usec))) {
                    cnt --;
                    continue;
                }
                timeuse = (end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000;
                timeuse = timeuse / 1000;
                if(timeuse < ((float)size_in_mb)/9.0) {
                    break;
                }
                if(cnt == 2)
                    usleep(1000000 * (cnt + 1) * (cnt + 1));
            }
            printf("Write : %f MByte/s\n", wrrate);
            printf("Read : %f MByte/s\n", ((float)size_in_mb) / timeuse);
            system("rm /tmp/mnt/Qsync/100mb");
            sync();
            continue;
        }
        if (!strncmp(ptr, "card_throughput", 15)) {
            FILE *pFile;
            char result[64]={0};
            struct timeval start,end;
            double timeuse = 2.0;
            double wrrate = 5.5;
            int size_in_mb = 100;
            char cmdbuf[512];
            int cnt = 0;

            sscanf(ptr, "card_throughput%d", &size_in_mb);
            if(!size_in_mb) {
                size_in_mb = 100;
            }

            if ((pFile = popen("mount | grep SD", "r"))) {
                fgets(result, sizeof(result), pFile);
                pclose(pFile);
            }
            if (!strcmp(result, "")) { 
                printf("Cannot find card!!\n");
                continue;
            }
            unlink("/tmp/mnt/SD/100mb");
            sync();
            /* Wake up card reader */
            snprintf(cmdbuf, sizeof(cmdbuf), "dd if=/dev/zero of=/tmp/mnt/SD/100mb bs=64k count=%d 2>/dev/null 1>/dev/null", size_in_mb * 16);
            for(cnt = 0; cnt < 3; cnt++) {
                system("sdparm --command=ready /dev/sda 1>/dev/null 2>/dev/null");
                gettimeofday(&start,NULL);
                system(cmdbuf);
                gettimeofday( &end, NULL );
                sync();
                if((end.tv_sec < start.tv_sec) || ((end.tv_sec == start.tv_sec) && (end.tv_usec < start.tv_usec))) {
                    cnt --;
                    continue;
                }
                timeuse = (end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000;
                timeuse = timeuse / 1000;
                wrrate = ((float)size_in_mb) / timeuse;
                if(timeuse < ((float)size_in_mb)/3.0) {
                    break;
                }
                if(cnt == 2)
                    usleep(1000000 * (cnt + 1) * (cnt + 1));
            }
            /* Wake up card reader */
            snprintf(cmdbuf, sizeof(cmdbuf), "dd if=/tmp/mnt/SD/100mb of=/dev/null bs=64k count=%d 2>/dev/null 1>/dev/null", size_in_mb * 16);
            for(cnt = 0; cnt < 3; cnt++) {
                system("sdparm --command=ready /dev/sda 1>/dev/null 2>/dev/null");
                gettimeofday(&start,NULL);
                system(cmdbuf);
                gettimeofday( &end, NULL );
                sync();
                if((end.tv_sec < start.tv_sec) || ((end.tv_sec == start.tv_sec) && (end.tv_usec < start.tv_usec))) {
                    cnt --;
                    continue;
                }
                timeuse = (end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000;
                timeuse = timeuse / 1000;
                if(timeuse < ((float)size_in_mb)/9.0) {
                    break;
                }
                if(cnt == 2)
                    usleep(1000000 * (cnt + 1) * (cnt + 1));
            }
            printf("Write : %f MByte/s\n", wrrate);
            printf("Read : %f MByte/s\n", ((float)size_in_mb) / timeuse);
            system("rm /tmp/mnt/SD/100mb");
            sync();
            continue;
        }

        if (!strncmp(ptr, "get_serial_num", 14)) {
            char serial_num[BUF_LEN];
            ezplib_get_rule("serial_num_rule", 0, serial_num, BUF_LEN);
            printf("SERIAL NUMBER:%s\n", serial_num);
            continue;
        }

        if (!strncmp(ptr, "set_serial_num", 14)) {
            FILE *pFile;
            char serial_num[32];
            char tmp[BUF_LEN];
            sscanf(ptr,"set_serial_num%s\n",serial_num);
            snprintf(tmp,BUF_LEN,"nvram fset serial_num_rule=\"%s\"",serial_num);
            pFile = popen(tmp, "r");
            nvram_commit();
            printf("SERIAL NUMBER:%s\n",serial_num);
            pclose(pFile);
            continue;
        }

        if (!strncmp(ptr, "set_mfg_test_result", 19)) {
            int index;
            int loop_counter;
            char test_item[BUF_LEN];
            int result_value;
            char *tmp;
            char *nvram_content_ori;
            char post_nvram_content[BUF_LEN];
            char insert_item[25];

            sscanf(ptr,"set_mfg_test_result%d %s %d\n", &index, test_item, &result_value);
            if(strlen(test_item) > 15) {
                printf("the name of test item is too long\n");
                continue;
            } else if(result_value > 255) {
                printf("result value should be between 0~255\n");
                continue;
            } else if(index > 39) {
                printf("index value is out of range\n");
                continue;
            }
            printf("index:%d\ntest_item:%s\ntest_result:%d\n", index, test_item, result_value);

            snprintf(insert_item, 25, "%s^%d",test_item,result_value);
            char *nvram_content = nvram_get("mfg_test_result_rule");
            printf("original:%s\n", nvram_content);
            tmp = (char *)malloc(BUF_LEN*sizeof(char));
            if (tmp==NULL){
                printf("Memory could not be allocated \n");
                continue;
            } 
            nvram_content_ori = tmp;
            strcpy(tmp, nvram_content);
            for(loop_counter=0; loop_counter < index ; loop_counter++) {
                tmp = strchr(tmp,'|');
                tmp++;
            }
            *tmp = '\0';

            tmp = strchr(tmp+1,'|');
            strcpy(post_nvram_content, tmp);
            strcat(nvram_content_ori, insert_item);
            strcat(nvram_content_ori, post_nvram_content);
            printf("write in:%s\n", nvram_content_ori);

            /* write to nvram */
            memset(post_nvram_content, '\0', BUF_LEN);
            nvram_fset("mfg_test_result_rule", nvram_content_ori);
            nvram_commit();
            free(nvram_content_ori);
            continue;
        }

        if (!strncmp(ptr, "get_mfg_test_result", 19)) {
            int index;
            char test_item[BUF_LEN];
            char result_value[4];
            sscanf(ptr,"get_mfg_test_result%d\n", &index);
            if(index > 39) {
                printf("index value is out of range\n");
                continue;
            }

            ezplib_get_attr_val("mfg_test_result_rule", index, "item", test_item, sizeof(test_item), EZPLIB_USE_CLI);
            ezplib_get_attr_val("mfg_test_result_rule", index, "result", result_value, sizeof(result_value), EZPLIB_USE_CLI);
            printf("index:%d\ntest_item:%s\ntest_result:%s\n", index, test_item, result_value);
            continue;
        }

        if (!strncmp(ptr, "factory", 7)) {
#if defined(PLATFORM_AXA)
            system("ezp-i2c gauge host booting");
#endif
            system("nvram factory");
            continue;
        }

        if (!strncmp(ptr, "w_red_led_on", 12)) {
            system("gpioctl led 13 1 0 0 0 0 > /dev/null");
            continue;
        }

        if (!strncmp(ptr, "w_red_led_off", 13)) {
            system("gpioctl led 13 0 1 0 0 0 > /dev/null");
            continue;
        }

        if (!strncmp(ptr, "w_green_led_resume", 18)) {
            system("/sbin/ezp-wl-ctrl wifi_on");
            continue;
        }

        if (!strncmp(ptr, "w_green_led_off", 15)) {
            system("/sbin/ezp-wl-ctrl wifi_off");
            continue;
        }

        if (!strncmp(ptr, "p_green_led_on", 14)) {
            system("ezp-i2c gauge green_led on");
            continue;
        }

        if (!strncmp(ptr, "p_green_led_off", 15)) {
            system("ezp-i2c gauge green_led off");
            continue;
        }

        if (!strncmp(ptr, "p_led_resume", 12)) {
            system("ezp-i2c gauge led resume");
            continue;
        }

        if (!strncmp(ptr, "p_red_led_on", 12)) {
            system("ezp-i2c gauge red_led on");
            continue;
        }
        if (!strncmp(ptr, "p_red_led_off", 13)) {
            system("ezp-i2c gauge red_led off");
            continue;
        }
        if (!strncmp(ptr, "p_oled_on", 9)) {
            system("ezp-i2c gauge oled on");
            continue;
        }
        if (!strncmp(ptr, "p_oled_off", 10)) {
            system("ezp-i2c gauge oled off");
            continue;
        }
        if (!strncmp(ptr, "p_wm_led_on", 11)) {
            system("ezp-i2c gauge wm_led on");
            continue;
        }
        if (!strncmp(ptr, "p_wm_led_off", 12)) {
            system("ezp-i2c gauge wm_led off");
            continue;
        }
        if (!strncmp(ptr, "p_pm_led_on", 11)) {
            system("ezp-i2c gauge pm_led on");
            continue;
        }
        if (!strncmp(ptr, "p_pm_led_off", 12)) {
            system("ezp-i2c gauge pm_led off");
            continue;
        }

        if (!strncmp(ptr, "p_blue_led_on", 13)) {
            system("gpioctl led 0 1 0 0 0 0 > /dev/null");
            continue;
        }

        if (!strncmp(ptr, "p_blue_led_off", 14)) {
            system("gpioctl led 0 0 1 0 0 0 > /dev/null");
            continue;
        }

        if (!strncmp(ptr, "switch_lan", 10)) {
#if defined(PLATFORM_M2E)
            system("/sbin/mt7620-config-lan.sh");
            nvram_fset("port_config", "lan");
            nvram_commit();
#else
            system("ezp-vlan esw config_p1_port lan");
#endif
            continue;
        }
        if (!strncmp(ptr, "switch_wan", 10)) {
#if defined(PLATFORM_M2E)
            system("/sbin/mt7620-config-wan.sh");
            nvram_fset("port_config", "wan");
            nvram_commit();
#else
            system("ezp-vlan esw config_p1_port wan");
#endif
            continue;
        }
        if (!strncmp(ptr, "temp_offset", sizeof("temp_offset") - 1)) {
            char tmp[BUF_LEN];
            snprintf(tmp, sizeof(tmp), "ezp-i2c gauge %s", ptr);;
            system(tmp);
            continue;
        }
        if (!strncmp(ptr, "temp", sizeof("temp") - 1)) {
            char tmp[BUF_LEN];
            snprintf(tmp, sizeof(tmp), "ezp-i2c gauge %s", ptr);;
            system(tmp);
            continue;
        }
        if (!strncmp(ptr, "resetbc", sizeof("resetbc") - 1)) {
            nvram_fset("bootcount","0");
            nvram_commit();
            continue;
        }

        if (!strncmp(ptr, "exit", 4)) {
            return 0;
        }

        if (!strncmp(ptr, "quit", 4)) {
            return 0;
        }

        if (!(fp = popen(ptr, "r"))) {
            printf("Unable to execute this command: %s", ptr);
            continue;
        }
        if(strncmp(ptr, "ated", 4)) {
            while (fgets(buf2, sizeof(buf2), fp)) {
                printf("%s", buf2);
            }
        }

        if (!strncmp(ptr, "tcpdump", 7)) {
            system("tcpdump -i vlan3");
            continue;
        }



        pclose(fp);
    }
    return 0;
}
Esempio n. 20
0
bool
get_autofw_port(int which, netconf_app_t *app)
{
	char name[] = "autofw_portXXXXXXXXXX", value[1000];
	char *out_proto, *out_start, *out_end, *in_proto, *in_start, *in_end, *to_start, *to_end;
	char *enable, *desc;

	memset(app, 0, sizeof(netconf_app_t));

	/* Parse out_proto:out_start-out_end,in_proto:in_start-in_end>to_start-to_end,enable,desc */
	snprintf(name, sizeof(name), "autofw_port%d", which);
	if (!nvram_invmatch(name, ""))
		return FALSE;
	strncpy(value, nvram_get(name), sizeof(value));

	/* Check for outbound port specification */
	out_start = value;
	out_proto = strsep(&out_start, ":");
	if (!out_start)
		return FALSE;

	/* Check for related protocol specification */
	in_proto = out_start;
	out_start = strsep(&in_proto, ",");
	if (!in_proto)
		return FALSE;

	/* Check for related destination port specification */
	in_start = in_proto;
	in_proto = strsep(&in_start, ":");
	if (!in_start)
		return FALSE;

	/* Check for mapped destination port specification */
	to_start = in_start;
	in_start = strsep(&to_start, ">");
	if (!to_start)
		return FALSE;

	/* Check for enable specification */
	enable = to_start;
	to_end = strsep(&enable, ",");
	if (!enable)
		return FALSE;

	/* Check for description specification (optional) */
	desc = enable;
	enable = strsep(&desc, ",");

	/* Check for outbound port range (optional) */
	out_end = out_start;
	out_start = strsep(&out_end, "-");
	if (!out_end)
		out_end = out_start;
		
	/* Check for related destination port range (optional) */
	in_end = in_start;
	in_start = strsep(&in_end, "-");
	if (!in_end)
		in_end = in_start;

	/* Check for mapped destination port range (optional) */
	to_end = to_start;
	to_start = strsep(&to_end, "-");
	if (!to_end)
		to_end = to_start;

	/* Parse outbound protocol */
	if (!strncasecmp(out_proto, "tcp", 3))
		app->match.ipproto = IPPROTO_TCP;
	else if (!strncasecmp(out_proto, "udp", 3))
		app->match.ipproto = IPPROTO_UDP;
	else
		return FALSE;

	/* Parse outbound port range */
	app->match.dst.ports[0] = htons(atoi(out_start));
	app->match.dst.ports[1] = htons(atoi(out_end));

	/* Parse related protocol */
	if (!strncasecmp(in_proto, "tcp", 3))
		app->proto = IPPROTO_TCP;
	else if (!strncasecmp(in_proto, "udp", 3))
		app->proto = IPPROTO_UDP;
	else
		return FALSE;

	/* Parse related destination port range */
	app->dport[0] = htons(atoi(in_start));
	app->dport[1] = htons(atoi(in_end));

	/* Parse mapped destination port range */
	app->to[0] = htons(atoi(to_start));
	app->to[1] = htons(atoi(to_end));

	/* Parse enable */
	if (!strncasecmp(enable, "off", 3))
		app->match.flags = NETCONF_DISABLED;

	/* Parse description */
	if (desc)
		strncpy(app->desc, desc, sizeof(app->desc));

	/* Set interface name (match packets entering LAN interface) */
	strncpy(app->match.in.name, nvram_safe_get("lan_ifname"), IFNAMSIZ);

	/* Set LAN source port range (match packets from any source port) */
	app->match.src.ports[1] = htons(0xffff);

	/* Set target (application specific port forward) */
	app->target = NETCONF_APP;

	return valid_autofw_port(app);
}
Esempio n. 21
0
static int
write_pppd_ras_conf(const char* call_path, const char *modem_node, int ppp_unit)
{
	FILE *fp;
	int modem_type, vid = 0, pid = 0;
	char *user, *pass, *isp;
	
	if (!get_modem_vid_pid(modem_node, &vid, &pid))
		return 0;
	
	if (!(fp = fopen(call_path, "w+")))
		return 0;
	
	modem_type = nvram_get_int("modem_type");
	user = nvram_safe_get("modem_user");
	pass = nvram_safe_get("modem_pass");
	isp = nvram_safe_get("modem_isp");
	
	fprintf(fp, "/dev/%s\n", modem_node);
	fprintf(fp, "modem\n");
	fprintf(fp, "crtscts\n");
	fprintf(fp, "noauth\n");

	if(strlen(user) > 0)
		fprintf(fp, "user '%s'\n", user);
	if(strlen(pass) > 0)
		fprintf(fp, "password '%s'\n", pass);

	if(!strcmp(isp, "Virgin") || !strcmp(isp, "CDMA-UA")){
		fprintf(fp, "refuse-chap\n");
		fprintf(fp, "refuse-mschap\n");
		fprintf(fp, "refuse-mschap-v2\n");
	}

	fprintf(fp, "mtu %d\n", nvram_safe_get_int("modem_mtu", 1500, 1000, 1500));
	fprintf(fp, "mru %d\n", 1500);

	fprintf(fp, "persist\n");
	fprintf(fp, "maxfail %d\n", 0);
	fprintf(fp, "holdoff %d\n", 10);

	fprintf(fp, "nopcomp noaccomp\n");
	fprintf(fp, "novj nobsdcomp nodeflate\n");

	fprintf(fp, "noipdefault\n");

	if (nvram_invmatch("modem_dnsa", "0"))
		fprintf(fp, "usepeerdns\n");

	fprintf(fp, "minunit %d\n", ppp_unit);

	if(modem_type == 2){
		fprintf(fp, "connect \"/bin/comgt -d /dev/%s -s %s/ppp/3g/td.scr\"\n", modem_node, MODEM_SCRIPTS_DIR);
		fprintf(fp, "disconnect \"/bin/comgt -d /dev/%s -s %s/ppp/3g/Generic_disconn.scr\"\n", modem_node, MODEM_SCRIPTS_DIR);
	}
	else if(modem_type == 1){
		fprintf(fp, "connect \"/bin/comgt -d /dev/%s -s %s/ppp/3g/EVDO_conn.scr\"\n", modem_node, MODEM_SCRIPTS_DIR);
		fprintf(fp, "disconnect \"/bin/comgt -d /dev/%s -s %s/ppp/3g/EVDO_disconn.scr\"\n", modem_node, MODEM_SCRIPTS_DIR);
	}
	else {
		if (vid == 0x0b05 && pid == 0x0302) // T500
			fprintf(fp, "connect \"/bin/comgt -d /dev/%s -s %s/ppp/3g/t500_conn.scr\"\n", modem_node, MODEM_SCRIPTS_DIR);
		else if(vid == 0x0421 && pid == 0x0612) // CS-15
			fprintf(fp, "connect \"/bin/comgt -d /dev/%s -s %s/ppp/3g/t500_conn.scr\"\n", modem_node, MODEM_SCRIPTS_DIR);
		else if(vid == 0x106c && pid == 0x3716)
			fprintf(fp, "connect \"/bin/comgt -d /dev/%s -s %s/ppp/3g/verizon_conn.scr\"\n", modem_node, MODEM_SCRIPTS_DIR);
		else if(vid == 0x1410 && pid == 0x4400)
			fprintf(fp, "connect \"/bin/comgt -d /dev/%s -s %s/ppp/3g/rogers_conn.scr\"\n", modem_node, MODEM_SCRIPTS_DIR);
		else
			fprintf(fp, "connect \"/bin/comgt -d /dev/%s -s %s/ppp/3g/Generic_conn.scr\"\n", modem_node, MODEM_SCRIPTS_DIR);
		
		fprintf(fp, "disconnect \"/bin/comgt -d /dev/%s -s %s/ppp/3g/Generic_disconn.scr\"\n", modem_node, MODEM_SCRIPTS_DIR);
	}
	
	fclose(fp);
	
	return 1;
}
Esempio n. 22
0
void start_sit_tunnel(int ipv6_type, char *wan_addr4, char *wan_addr6)
{
	int sit_ttl, sit_mtu, size4, size6;
	char *sit_remote, *sit_relay, *wan_gate6;
	char addr6s[INET6_ADDRSTRLEN];
	struct in_addr addr4;
	struct in6_addr addr6;

	size4 = 0;
	addr4.s_addr = inet_addr_safe(wan_addr4);
	if (addr4.s_addr == INADDR_ANY)
		return; // cannot start SIT tunnel w/o IPv4 WAN addr

	sit_mtu = nvram_get_int("ip6_sit_mtu");
	sit_ttl = nvram_get_int("ip6_sit_ttl");
	if (sit_mtu < 1280) sit_mtu = 1280;
	if (sit_ttl < 1) sit_ttl = 1;
	if (sit_ttl > 255) sit_ttl = 255;

	memset(&addr6, 0, sizeof(addr6));
	size6 = ipv6_from_string(wan_addr6, &addr6);
	if (size6 < 0) size6 = 0;

	sit_relay = "";
	sit_remote = "any";
	if (ipv6_type == IPV6_6IN4)
		sit_remote = nvram_safe_get("ip6_6in4_remote");
	
	if (is_interface_exist(IFNAME_SIT))
		doSystem("ip tunnel del %s", IFNAME_SIT);
	
	doSystem("ip tunnel %s %s mode sit remote %s local %s ttl %d", "add", IFNAME_SIT, sit_remote, wan_addr4, sit_ttl);
	
	if (ipv6_type == IPV6_6TO4) {
		size6 = 16;
		memset(&addr6, 0, sizeof(addr6));
		addr6.s6_addr16[0] = htons(0x2002);
		ipv6_to_ipv4_map(&addr6, size6, &addr4, 0);
		addr6.s6_addr16[7] = htons(0x0001);
		sit_relay = nvram_safe_get("ip6_6to4_relay");
	}
	else if (ipv6_type == IPV6_6RD) {
		struct in_addr net4;
		struct in6_addr net6;
		char sit_6rd_prefix[INET6_ADDRSTRLEN], sit_6rd_relay_prefix[32];
		
		memcpy(&net6, &addr6, sizeof(addr6));
		ipv6_to_net(&net6, size6);
		inet_ntop(AF_INET6, &net6, sit_6rd_prefix, INET6_ADDRSTRLEN);
		sprintf(sit_6rd_prefix, "%s/%d", sit_6rd_prefix, size6);
		
		strcpy(sit_6rd_relay_prefix, "0.0.0.0/0");
		size4 = get_wan_unit_value_int(0, "6rd_size");
		if (size4 > 0 && size4 <= 32)
		{
			net4.s_addr = addr4.s_addr & htonl(0xffffffffUL << (32 - size4));
			sprintf(sit_6rd_relay_prefix, "%s/%d", inet_ntoa(net4), size4);
		}
		
		doSystem("ip tunnel 6rd dev %s 6rd-prefix %s 6rd-relay_prefix %s", IFNAME_SIT, sit_6rd_prefix, sit_6rd_relay_prefix);
		
		ipv6_to_ipv4_map(&addr6, size6, &addr4, size4);
		addr6.s6_addr16[7] = htons(0x0001);
		sit_relay = get_wan_unit_value(0, "6rd_relay");
	}

	// WAN IPv6 address
	inet_ntop(AF_INET6, &addr6, addr6s, INET6_ADDRSTRLEN);
	if (size6 > 0)
		sprintf(addr6s, "%s/%d", addr6s, size6);

	control_if_ipv6_radv(IFNAME_SIT, 0);
	doSystem("ip link set mtu %d dev %s up", sit_mtu, IFNAME_SIT);
	control_if_ipv6(IFNAME_SIT, 1);
	clear_if_addr6(IFNAME_SIT);
	doSystem("ip -6 addr add %s dev %s", addr6s, IFNAME_SIT);

	/* WAN IPv6 gateway (auto-generate for 6to4/6rd) */
	if (ipv6_type == IPV6_6TO4 || ipv6_type == IPV6_6RD) {
		sprintf(addr6s, "::%s", sit_relay);
		wan_gate6 = addr6s;
		/* add direct default gateway for workaround "No route to host" on new kernel */
		doSystem("ip -6 route add default dev %s metric %d", IFNAME_SIT, 2048);
	}
	else {
		wan_gate6 = get_wan_unit_value(0, "gate6");
	}
	if (*wan_gate6)
		doSystem("ip -6 route add default via %s dev %s metric %d", wan_gate6, IFNAME_SIT, 1);

	/* LAN IPv6 address (auto-generate for 6to4/6rd) */
	if (ipv6_type == IPV6_6TO4 || ipv6_type == IPV6_6RD) {
		memset(&addr6, 0, sizeof(addr6));
		if (ipv6_type == IPV6_6TO4) {
			addr6.s6_addr16[0] = htons(0x2002);
			ipv6_to_ipv4_map(&addr6, 16, &addr4, 0);
			addr6.s6_addr16[3] = htons(0x0001);
			addr6.s6_addr16[7] = htons(0x0001);
		}
		else {
			ipv6_from_string(wan_addr6, &addr6);
			ipv6_to_ipv4_map(&addr6, size6, &addr4, size4);
			addr6.s6_addr16[7] = htons(0x0001);
		}
		
		inet_ntop(AF_INET6, &addr6, addr6s, INET6_ADDRSTRLEN);
		sprintf(addr6s, "%s/%d", addr6s, 64);
		
		clear_if_addr6(IFNAME_BR);
		doSystem("ip -6 addr add %s dev %s", addr6s, IFNAME_BR);
		
		store_lan_addr6(addr6s);
	}
}
Esempio n. 23
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;
}
Esempio n. 24
0
//#if 0
void wan_netmask_check(void)
{
	unsigned int ip, gw, nm, lip, lnm;

	if (nvram_match("wan0_proto", "static") ||
	    //nvram_match("wan0_proto", "pptp"))
	    nvram_match("wan0_proto", "pptp") || nvram_match("wan0_proto", "l2tp"))	// oleg patch
	{
		ip = inet_addr(nvram_safe_get("wan_ipaddr"));
		gw = inet_addr(nvram_safe_get("wan_gateway"));
		nm = inet_addr(nvram_safe_get("wan_netmask"));

		lip = inet_addr(nvram_safe_get("lan_ipaddr"));
		lnm = inet_addr(nvram_safe_get("lan_netmask"));

		_dprintf("ip : %x %x %x\n", ip, gw, nm);

		if (ip==0x0 && (nvram_match("wan0_proto", "pptp") || nvram_match("wan0_proto", "l2tp")))	// oleg patch
			return;

		if (ip==0x0 || (ip&lnm)==(lip&lnm))
		{
			nvram_set("wan_ipaddr", "1.1.1.1");
			nvram_set("wan_netmask", "255.0.0.0");	
			nvram_set("wan0_ipaddr", nvram_safe_get("wan_ipaddr"));
			nvram_set("wan0_netmask", nvram_safe_get("wan_netmask"));
		}

		// check netmask here
		if (gw==0 || gw==0xffffffff || (ip&nm)==(gw&nm))
		{
			nvram_set("wan0_netmask", nvram_safe_get("wan_netmask"));
		}
		else
		{		
			for (nm=0xffffffff;nm!=0;nm=(nm>>8))
			{
				if ((ip&nm)==(gw&nm)) break;
			}

			_dprintf("nm: %x\n", nm);

			if (nm==0xffffffff) nvram_set("wan0_netmask", "255.255.255.255");
			else if (nm==0xffffff) nvram_set("wan0_netmask", "255.255.255.0");
			else if (nm==0xffff) nvram_set("wan0_netmask", "255.255.0.0");
			else if (nm==0xff) nvram_set("wan0_netmask", "255.0.0.0");
			else nvram_set("wan0_netmask", "0.0.0.0");
		}

		nvram_set("wanx_ipaddr", nvram_safe_get("wan0_ipaddr"));	// oleg patch, he suggests to mark the following 3 lines
		nvram_set("wanx_netmask", nvram_safe_get("wan0_netmask"));
		nvram_set("wanx_gateway", nvram_safe_get("wan0_gateway"));
	}
Esempio n. 25
0
void set_mac(const char *ifname, const char *nvname, int plus)
{
	int sfd;
	struct ifreq ifr;
	int up;
	int j;
	
	if ((sfd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
		_dprintf("%s: %s %d\n", ifname, __FUNCTION__, __LINE__);
		return;
	}

	strcpy(ifr.ifr_name, ifname);
	
	up = 0;
	if (ioctl(sfd, SIOCGIFFLAGS, &ifr) == 0) {
		if ((up = ifr.ifr_flags & IFF_UP) != 0) {
			ifr.ifr_flags &= ~IFF_UP;
			if (ioctl(sfd, SIOCSIFFLAGS, &ifr) != 0) {
				_dprintf("%s: %s %d\n", ifname, __FUNCTION__, __LINE__);
			}
		}
	}
	else {
		_dprintf("%s: %s %d\n", ifname, __FUNCTION__, __LINE__);
	}
	
	if (!ether_atoe(nvram_safe_get(nvname), (unsigned char *)&ifr.ifr_hwaddr.sa_data)) {
		if (!ether_atoe(nvram_safe_get("et0macaddr"), (unsigned char *)&ifr.ifr_hwaddr.sa_data)) {

			// goofy et0macaddr, make something up
			nvram_set("et0macaddr", "00:01:23:45:67:89");
			ifr.ifr_hwaddr.sa_data[0] = 0;
			ifr.ifr_hwaddr.sa_data[1] = 0x01;
			ifr.ifr_hwaddr.sa_data[2] = 0x23;
			ifr.ifr_hwaddr.sa_data[3] = 0x45;
			ifr.ifr_hwaddr.sa_data[4] = 0x67;
			ifr.ifr_hwaddr.sa_data[5] = 0x89;
		}
		
		while (plus-- > 0) {
			for (j = 5; j >= 3; --j) {
				ifr.ifr_hwaddr.sa_data[j]++;
				if (ifr.ifr_hwaddr.sa_data[j] != 0) break;	// continue if rolled over
			}
		}
	}
	
	ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER;
	if (ioctl(sfd, SIOCSIFHWADDR, &ifr) == -1) {
		_dprintf("Error setting %s address\n", ifname);
	}

	if (up) {
		if (ioctl(sfd, SIOCGIFFLAGS, &ifr) == 0) {
			ifr.ifr_flags |= IFF_UP|IFF_RUNNING;
			if (ioctl(sfd, SIOCSIFFLAGS, &ifr) == -1) {
				_dprintf("%s: %s %d\n", ifname, __FUNCTION__, __LINE__);
			}
		}
		else {
			_dprintf("%s: %s %d\n", ifname, __FUNCTION__, __LINE__);
		}
	}
	
	close(sfd);
}
Esempio n. 26
0
int
qtn_monitor_main(int argc, char *argv[])
{
    FILE *fp;
    sigset_t sigs_to_catch;
    int ret, retval = 0;
    time_t start_time = uptime();

    /* write pid */
    if ((fp = fopen("/var/run/qtn_monitor.pid", "w")) != NULL)
    {
        fprintf(fp, "%d", getpid());
        fclose(fp);
    }

    /* set the signal handler */
    sigemptyset(&sigs_to_catch);
    sigaddset(&sigs_to_catch, SIGTERM);
    sigprocmask(SIG_UNBLOCK, &sigs_to_catch, NULL);

    signal(SIGTERM, qtn_monitor_exit);

QTN_RESET:
    ret = rpc_qcsapi_init(1);
    if (ret < 0) {
        dbG("rpc_qcsapi_init error, return: %d\n", ret);
        retval = -1;
        goto ERROR;
    }
#if 0	/* replaced by STATELESS, send configuration from brcm to qtn */
    else if (nvram_get_int("qtn_restore_defaults"))
    {
        nvram_unset("qtn_restore_defaults");
        rpc_qcsapi_restore_default_config(0);
        dbG("Restaring Qcsapi init...\n");
        sleep(15);
        goto QTN_RESET;
    }
#endif

#if 0
    if(nvram_get_int("sw_mode") == SW_MODE_AP &&
            nvram_get_int("wlc_psta") == 1 &&
            nvram_get_int("wlc_band") == 1) {
        dbG("[sw_mode] start QTN PSTA mode\n");
        start_psta_qtn();
    }
#endif

    ret = qcsapi_init();
    if (ret < 0)
    {
        dbG("Qcsapi qcsapi_init error, return: %d\n", ret);
        retval = -1;
        goto ERROR;
    }
    else
        dbG("Qcsapi qcsapi init takes %ld seconds\n", uptime() - start_time);

    dbG("defer lanport_ctrl(1)\n");
    lanport_ctrl(1);
    eval("ifconfig", "br0:1", "down");
#if defined(RTCONFIG_JFFS2ND_BACKUP)
    check_2nd_jffs();
#endif
    nvram_set("qtn_ready", "1");

    if(nvram_get_int("AllLED") == 0) setAllLedOff();

    // dbG("[QTN] update router_command.sh from brcm to qtn\n");
    // qcsapi_wifi_run_script("set_test_mode", "update_router_command");

#if 1	/* STATELESS */
    if(nvram_get_int("sw_mode") == SW_MODE_AP &&
            nvram_get_int("wlc_psta") == 1 &&
            nvram_get_int("wlc_band") == 1) {
        dbG("[sw_mode] skip start_psta_qtn, QTN will run scripts automatically\n");
        // start_psta_qtn();
    } else {
        dbG("[***] rpc_parse_nvram_from_httpd\n");
        rpc_parse_nvram_from_httpd(1,-1);	/* wifi0 */
        rpc_parse_nvram_from_httpd(1,1);	/* wifi1 */
        rpc_parse_nvram_from_httpd(1,2);	/* wifi2 */
        rpc_parse_nvram_from_httpd(1,3);	/* wifi3 */
        dbG("[sw_mode] skip start_ap_qtn, QTN will run scripts automatically\n");
        // start_ap_qtn();
        qcsapi_mac_addr wl_mac_addr;
        ret = rpc_qcsapi_interface_get_mac_addr(WIFINAME, &wl_mac_addr);
        if (ret < 0)
            dbG("rpc_qcsapi_interface_get_mac_addr, return: %d\n", ret);
        else
        {
            nvram_set("1:macaddr", wl_ether_etoa((struct ether_addr *) &wl_mac_addr));
            nvram_set("wl1_hwaddr", wl_ether_etoa((struct ether_addr *) &wl_mac_addr));
        }

        rpc_update_wdslist();

        ret = qcsapi_wps_set_ap_pin(WIFINAME, nvram_safe_get("wps_device_pin"));
        if (ret < 0)
            dbG("Qcsapi qcsapi_wps_set_ap_pin %s error, return: %d\n", WIFINAME, ret);

        ret = qcsapi_wps_registrar_set_pp_devname(WIFINAME, 0, (const char *) get_productid());
        if (ret < 0)
            dbG("Qcsapi qcsapi_wps_registrar_set_pp_devname %s error, return: %d\n", WIFINAME, ret);

        ret = rpc_qcsapi_wifi_disable_wps(WIFINAME, !nvram_get_int("wps_enable"));
        if (ret < 0)
            dbG("Qcsapi rpc_qcsapi_wifi_disable_wps %s error, return: %d\n", WIFINAME, ret);

        rpc_set_radio(1, 0, nvram_get_int("wl1_radio"));

    }
#endif

    if(nvram_get_int("sw_mode") == SW_MODE_ROUTER ||
            (nvram_get_int("sw_mode") == SW_MODE_AP &&
             nvram_get_int("wlc_psta") == 0)) {
        if(nvram_get_int("wl1_chanspec") == 0) {
            if (nvram_match("1:ccode", "EU")) {
                if(nvram_get_int("acs_dfs") != 1) {
                    dbG("[dfs] start nodfs scanning and selection\n");
                    start_nodfs_scan_qtn();
                }
            } else {
                /* all country except EU */
                dbG("[dfs] start nodfs scanning and selection\n");
                start_nodfs_scan_qtn();
            }
        }
    }
    if(nvram_get_int("sw_mode") == SW_MODE_AP &&
            nvram_get_int("wlc_psta") == 1 &&
            nvram_get_int("wlc_band") == 0) {
        ret = qcsapi_wifi_reload_in_mode(WIFINAME, qcsapi_station);
        if (ret < 0)
            dbG("qtn reload_in_mode STA fail\n");
    }
    if(nvram_get_int("QTNTELNETSRV") == 1 && nvram_get_int("sw_mode") == SW_MODE_ROUTER) {
        dbG("[QTNT] enable telnet server\n");
        qcsapi_wifi_run_script("router_command.sh", "enable_telnet_srv 1");
    }

    dbG("[dbg] qtn_monitor startup\n");
ERROR:
    remove("/var/run/qtn_monitor.pid");

    if (nvram_get_int("led_disable") == 1) {
        setAllLedOff_qtn();
//                                qcsapi_wifi_run_script("router_command.sh", "wifi_led_off");
//                                qcsapi_led_set(1, 0);
    }
    return retval;
}
Esempio n. 27
0
	unlink(hgz);
}

static void load(int new)
{
	int i;
	long t;
	char *bi, *bo;
	int n;
	char hgz[256];
	char sp[sizeof(save_path)];
	unsigned char mac[6];

	current_uptime = uptime();

	strlcpy(save_path, nvram_safe_get("rstats_path"), sizeof(save_path) - 32);
	if (((n = strlen(save_path)) > 0) && (save_path[n - 1] == '/')) {
#ifdef RTCONFIG_RGMII_BRCM5301X
		ether_atoe(nvram_safe_get("et1macaddr"), mac);
#else
		ether_atoe(nvram_safe_get("et0macaddr"), mac);
#endif
		sprintf(save_path + n, "tomato_rstats_%02x%02x%02x%02x%02x%02x.gz",
			mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
	}

	if (f_read("/var/lib/misc/rstats-stime", &save_utime, sizeof(save_utime)) != sizeof(save_utime)) {
		save_utime = 0;
	}
	t = current_uptime + get_stime();
	if ((save_utime < current_uptime) || (save_utime > t)) save_utime = t;
Esempio n. 28
0
void rpc_parse_nvram_from_httpd(int unit, int subunit)
{
    if (!rpc_qtn_ready())
        return;

    if (unit == 1 && subunit == -1) {
        rpc_qcsapi_set_SSID(WIFINAME, nvram_safe_get("wl1_ssid"));
        rpc_qcsapi_set_SSID_broadcast(WIFINAME, nvram_safe_get("wl1_closed"));
        rpc_qcsapi_set_vht(nvram_safe_get("wl1_nmode_x"));
        rpc_qcsapi_set_bw(nvram_safe_get("wl1_bw"));
        rpc_qcsapi_set_channel(nvram_safe_get("wl1_chanspec"));
        rpc_qcsapi_set_beacon_type(WIFINAME, nvram_safe_get("wl1_auth_mode_x"));
        rpc_qcsapi_set_WPA_encryption_modes(WIFINAME, nvram_safe_get("wl1_crypto"));
        rpc_qcsapi_set_key_passphrase(WIFINAME, nvram_safe_get("wl1_wpa_psk"));
        rpc_qcsapi_set_dtim(nvram_safe_get("wl1_dtim"));
        rpc_qcsapi_set_beacon_interval(nvram_safe_get("wl1_bcn"));
        rpc_set_radio(1, 0, nvram_get_int("wl1_radio"));
        rpc_update_macmode(nvram_safe_get("wl1_macmode"));
        rpc_update_wlmaclist();
        rpc_update_wdslist();
        rpc_update_wdslist();
        rpc_update_wds_psk(nvram_safe_get("wl1_wds_psk"));
        rpc_update_ap_isolate(WIFINAME, atoi(nvram_safe_get("wl1_ap_isolate")));

        if(nvram_get_int("wl1_80211h") == 1) {
            dbG("[80211h] set_80211h_on\n");
            qcsapi_wifi_run_script("router_command.sh", "80211h_on");
        } else {
            dbG("[80211h] set_80211h_off\n");
            qcsapi_wifi_run_script("router_command.sh", "80211h_off");
        }
        if(nvram_get_int("sw_mode") == SW_MODE_ROUTER ||
                (nvram_get_int("sw_mode") == SW_MODE_AP &&
                 nvram_get_int("wlc_psta") == 0)) {
            if(nvram_get_int("wl1_chanspec") == 0) {
                if (nvram_match("1:ccode", "EU")) {
                    if(nvram_get_int("acs_dfs") != 1) {
                        dbG("[dfs] start nodfs scanning and selection\n");
                        start_nodfs_scan_qtn();
                    }
                } else {
                    /* all country except EU */
                    dbG("[dfs] start nodfs scanning and selection\n");
                    start_nodfs_scan_qtn();
                }
            }
        }
    } else if (unit == 1 && subunit == 1) {
        if(nvram_get_int("wl1.1_bss_enabled") == 1) {
            rpc_update_mbss("wl1.1_ssid", nvram_safe_get("wl1.1_ssid"));
            rpc_update_mbss("wl1.1_bss_enabled", nvram_safe_get("wl1.1_bss_enabled"));
            rpc_update_mbss("wl1.1_wpa_psk", nvram_safe_get("wl1.1_wpa_psk"));
            rpc_update_mbss("wl1.1_wpa_gtk_rekey", nvram_safe_get("wl1.1_wpa_gtk_rekey"));
            rpc_update_mbss("wl1.1_auth_mode_x", nvram_safe_get("wl1.1_auth_mode_x"));
            rpc_update_mbss("wl1.1_mbss", nvram_safe_get("wl1.1_mbss"));
        }
        else {
            qcsapi_wifi_remove_bss(wl_vifname_qtn(unit, subunit));
        }
    } else if (unit == 1 && subunit == 2) {
        if(nvram_get_int("wl1.2_bss_enabled") == 1) {
            rpc_update_mbss("wl1.2_ssid", nvram_safe_get("wl1.2_ssid"));
            rpc_update_mbss("wl1.2_bss_enabled", nvram_safe_get("wl1.2_bss_enabled"));
            rpc_update_mbss("wl1.2_wpa_psk", nvram_safe_get("wl1.2_wpa_psk"));
            rpc_update_mbss("wl1.2_wpa_gtk_rekey", nvram_safe_get("wl1.2_wpa_gtk_rekey"));
            rpc_update_mbss("wl1.2_auth_mode_x", nvram_safe_get("wl1.2_auth_mode_x"));
            rpc_update_mbss("wl1.2_mbss", nvram_safe_get("wl1.2_mbss"));
        }
        else {
            qcsapi_wifi_remove_bss(wl_vifname_qtn(unit, subunit));
        }
    } else if (unit == 1 && subunit == 3) {
        if(nvram_get_int("wl1.3_bss_enabled") == 1) {
            rpc_update_mbss("wl1.3_ssid", nvram_safe_get("wl1.3_ssid"));
            rpc_update_mbss("wl1.3_bss_enabled", nvram_safe_get("wl1.3_bss_enabled"));
            rpc_update_mbss("wl1.3_wpa_psk", nvram_safe_get("wl1.3_wpa_psk"));
            rpc_update_mbss("wl1.3_wpa_gtk_rekey", nvram_safe_get("wl1.3_wpa_gtk_rekey"));
            rpc_update_mbss("wl1.3_auth_mode_x", nvram_safe_get("wl1.3_auth_mode_x"));
            rpc_update_mbss("wl1.3_mbss", nvram_safe_get("wl1.3_mbss"));
        }
        else {
            qcsapi_wifi_remove_bss(wl_vifname_qtn(unit, subunit));
        }
    }

//	rpc_show_config();
}
Esempio n. 29
0
static void create_pptp_config(char *servername, char *username)
{

	FILE *fp;

	mkdir("/tmp/ppp", 0777);
	symlink("/sbin/rc", "/tmp/ppp/ip-up");
	symlink("/sbin/rc", "/tmp/ppp/ip-down");
	symlink("/dev/null", "/tmp/ppp/connect-errors");

	/*
	 * Generate options file 
	 */
	if (!(fp = fopen("/tmp/ppp/options", "w"))) {
		perror("/tmp/ppp/options");
		return;
	}
	fprintf(fp, "defaultroute\n");	// Add a default route to the 
	// system routing tables, using the peer as the gateway
	fprintf(fp, "usepeerdns\n");	// Ask the peer for up to 2 DNS
	// server addresses
	fprintf(fp, "pty 'pptp %s --localbind %s --nolaunchpppd", servername,nvram_safe_get("wan_ipaddr"));

	if (nvram_match("pptp_reorder", "0"))
		fprintf(fp, " --nobuffer");

	// PPTP client also supports synchronous mode.
	// This should improve the speeds.
	if (nvram_match("pptp_synchronous", "1"))
		fprintf(fp, " --sync'\nsync\n");
	else
		fprintf(fp, "'\n");

	fprintf(fp, "user '%s'\n", username);
	// fprintf(fp, "persist\n"); // Do not exit after a connection is terminated.

	if (nvram_match("mtu_enable", "1"))
		fprintf(fp, "mtu %s\n", nvram_safe_get("wan_mtu"));

	if (nvram_match("ppp_demand", "1")) {	// demand mode
		fprintf(fp, "idle %d\n",
			nvram_match("ppp_demand",
				    "1") ?
			atoi(nvram_safe_get("ppp_idletime")) * 60 : 0);
		fprintf(fp, "demand\n");	// Dial on demand
		fprintf(fp, "persist\n");	// Do not exit after a connection is
		// terminated.
		fprintf(fp, "%s:%s\n", PPP_PSEUDO_IP, PPP_PSEUDO_GW);	// <local 
		// IP>:<remote 
		// IP>
		fprintf(fp, "ipcp-accept-remote\n");
		fprintf(fp, "ipcp-accept-local\n");
		fprintf(fp, "connect true\n");
		fprintf(fp, "noipdefault\n");	// Disables the default
		// behaviour when no local IP 
		// address is specified
		fprintf(fp, "ktune\n");	// Set /proc/sys/net/ipv4/ip_dynaddr
		// to 1 in demand mode if the local
		// address changes
	} else {		// keepalive mode
		start_redial();
	}
	if (nvram_match("pptp_encrypt", "0")) {
		fprintf(fp, "nomppe\n");	// Disable mppe negotiation
		fprintf(fp, "noccp\n");	// Disable CCP (Compression Control
		// Protocol)
	} else {
		fprintf(fp, "mppe required,stateless\n");
	}
	fprintf(fp, "default-asyncmap\n");	// Disable asyncmap negotiation
	fprintf(fp, "nopcomp\n");	// Disable protocol field compression
	fprintf(fp, "noaccomp\n");	// Disable Address/Control compression
	fprintf(fp, "novj\n");	// Disable Van Jacobson style TCP/IP header compression
	fprintf(fp, "nobsdcomp\n");	// Disables BSD-Compress compression
	fprintf(fp, "nodeflate\n");	// Disables Deflate compression
	fprintf(fp, "lcp-echo-failure 20\n");
	fprintf(fp, "lcp-echo-interval 3\n");	// echo-request frame to the peer
	fprintf(fp, "noipdefault\n");
	fprintf(fp, "lock\n");
	fprintf(fp, "noauth\n");
	fprintf(fp, "debug\n" "logfd 2\n");

	if (nvram_invmatch("pptp_extraoptions", ""))
		fwritenvram("pptp_extraoptions", fp);

	fclose(fp);

}
Esempio n. 30
0
static int add_qos_rules(char *pcWANIF)
{
	FILE *fn;
#ifdef RTCONFIG_IPV6
	FILE *fn_ipv6 = NULL;
#endif
	char *buf;
	char *g;
	char *p;
	char *desc, *addr, *port, *prio, *transferred, *proto;
	int class_num;
	int down_class_num=6; 	// for download class_num = 0x6 / 0x106
	int i, inuse;
	char q_inuse[32]; 	// for inuse
	char dport[192], saddr_1[192], saddr_2[192], proto_1[8], proto_2[8],conn[256], end[256], end2[256];
	int method;
	int gum;
	int sticky_enable;
	const char *chain;
	int v4v6_ok;

	if((fn = fopen(mangle_fn, "w")) == NULL) return -2;
#ifdef RTCONFIG_IPV6
	if(ipv6_enabled() && (fn_ipv6 = fopen(mangle_fn_ipv6, "w")) == NULL) return -3;
#endif

	inuse = sticky_enable = 0;

	if(get_model()==MODEL_RTAC56U || get_model()==MODEL_RTAC56S || get_model()==MODEL_RTAC68U ||
		get_model()==MODEL_DSLAC68U || get_model()==MODEL_RTAC87U || get_model()==MODEL_RTAC3200 || 
		get_model()==MODEL_RTAC88U || get_model()==MODEL_RTAC3100 || get_model()==MODEL_RTAC5300 ||
		get_model()==MODEL_RTAC1200G || get_model()==MODEL_RTAC1200GP)
		manual_return = 1;

	if(nvram_match("qos_sticky", "0"))
		sticky_enable = 1;

	del_iQosRules(); // flush all rules in mangle table

#ifdef CLS_ACT
	eval("ip", "link", "set", "imq0", "up");
#endif
	fprintf(stderr, "[qos] iptables START\n");

	fprintf(fn,
		"*mangle\n"
		":PREROUTING ACCEPT [0:0]\n"
		":OUTPUT ACCEPT [0:0]\n"
		":QOSO - [0:0]\n"
		"-A QOSO -m mark --mark 0xb400 -j RETURN\n"
		"-A QOSO -j CONNMARK --restore-mark --mask 0x7\n"
		"-A QOSO -m connmark ! --mark 0/0xff00 -j RETURN\n"
		);
#ifdef RTCONFIG_IPV6
	if (fn_ipv6 && ipv6_enabled())
	fprintf(fn_ipv6,
		"*mangle\n"
		":PREROUTING ACCEPT [0:0]\n"
		":OUTPUT ACCEPT [0:0]\n"
		":QOSO - [0:0]\n"
		"-A QOSO -j CONNMARK --restore-mark --mask 0x7\n"
		"-A QOSO -m connmark ! --mark 0/0xff00 -j RETURN\n"
		);
#endif
	g = buf = strdup(nvram_safe_get("qos_rulelist"));
	while (g) {

		/* ASUSWRT
		qos_rulelist :
			desc>addr>port>proto>transferred>prio

			addr  : (source) IP or MAC or IP-range
			port  : dest port
			proto : tcp, udp, tcp/udp, any , (icmp, igmp)
			transferred : min:max
			prio  : 0-4, 0 is the highest
  		*/

		if ((p = strsep(&g, "<")) == NULL) break;
		if((vstrsep(p, ">", &desc, &addr, &port, &proto, &transferred, &prio)) != 6) continue;
		class_num = atoi(prio);
		if ((class_num < 0) || (class_num > 4)) continue;

		i = 1 << class_num;
		++class_num;

		//if (method == 1) class_num |= 0x200;
		if ((inuse & i) == 0) {
			inuse |= i;
			fprintf(stderr, "[qos] iptable creates, inuse=%d\n", inuse);
		}

		v4v6_ok = IPT_V4;
#ifdef RTCONFIG_IPV6
		if (fn_ipv6 && ipv6_enabled())
			v4v6_ok |= IPT_V6;
#endif

		/* Beginning of the Rule */
		/*
 			if transferred != NULL, class_num must bt 0x1~0x6, not 0x101~0x106
			0x1~0x6		: keep tracing this connection.
			0x101~0x106 	: connection will be considered as marked connection, won't detect again.
		*/
#if 0
		if(strcmp(transferred, "") != 0 )
			method = 1;
		else
			method = nvram_get_int("qos_method");	// strict rule ordering
		gum = (method == 0) ? 0x100 : 0;
#else
		method = 1;
		gum = 0;
#endif
		class_num |= gum;
		down_class_num |= gum;	// for download

		chain = "QOSO";		// chain name
		sprintf(end , " -j CONNMARK --set-return 0x%x/0x7\n", class_num);	// CONNMARK string
		sprintf(end2, " -j RETURN\n");

		/*************************************************/
		/*                        addr                   */
		/*           src mac or src ip or IP range       */
		/*************************************************/
		char tmp[20], addr_t[40];
		char *tmp_addr, *q_ip, *q_mac;

		memset(saddr_1, 0, sizeof(saddr_1));
		memset(saddr_2, 0, sizeof(saddr_2));

		memset(tmp, 0, sizeof(tmp));
		sprintf(tmp, "%s", addr);
		tmp_addr = tmp;
		q_ip  = strsep(&tmp_addr, ":");
		q_mac = tmp_addr;

		memset(addr_t, 0, sizeof(addr_t));
		sprintf(addr_t, "%s", addr);

		// step1: check contain '-' or not, if yes, IP-range, ex. 192.168.1.10-192.168.1.100
		// step2: check addr is NULL
		// step3: check IP or MAC
		// step4: check IP contain '*' or not, if yes, IP-range
		// step5: check DUT's LAN IP shouldn't inside IP-range

		// step1: check contain '-' or not, if yes, IP-range
		if(strchr(addr_t, '-') == NULL){
			// step2: check addr is NULL
			if(!strcmp(addr_t, "")){
				sprintf(saddr_1, "%s", addr_t);	// NULL
			}
			else{ // step2
				// step3: check IP or MAC
				if (q_mac == NULL){
					// step4: check IP contain '*' or not, if yes, IP-range
					if(strchr(q_ip, '*') != NULL){
						char *rule;
						char Mask[40];
						struct in_addr range_A, range_B, range_C;

						memset(Mask, 0, sizeof(Mask));
						rule =  strdup(addr_t);
						FindMask(rule, "*", "0", Mask); 				// find submask and replace "*" to "0"
						memset(addr_t, 0, sizeof(addr_t));
						sprintf(addr_t, "%s", rule);					// copy rule to addr_t for v4v6_ok

						unsigned int ip = inet_addr(rule); 				// covert rule's IP into binary form
						unsigned int nm = inet_addr(Mask);				// covert submask into binary form
						unsigned int gw = inet_addr(nvram_safe_get("lan_ipaddr")); 	// covert DUT's LAN IP into binary form
						unsigned int gw_t = htonl(gw);

						range_A.s_addr = ntohl(gw_t - 1);
						range_B.s_addr = ntohl(gw_t + 1);
						range_C.s_addr = ip | ~nm;

			//fprintf(stderr, "[addr] addr_t=%s, rule/Mask=%s/%s, ip/nm/gw=%x/%x/%x\n", addr_t, rule, Mask, ip, nm, gw); // tmp test

						// step5: check DUT's LAN IP shouldn't inside IP-range
						// DUT's LAN IP inside IP-range
						if( (ip & nm) == (gw & nm)){
			//fprintf(stderr, "[addr] %x/%x/%x/%x/%s matched\n", ip_t, nm_t, gw_t, range_B.s_addr, inet_ntoa(range_B)); // tmp test
							char range_B_addr[40];
							sprintf(range_B_addr, "%s", inet_ntoa(range_B));

							sprintf(saddr_1, "-m iprange --src-range %s-%s", rule, inet_ntoa(range_A)); 		// IP-range
							sprintf(saddr_2, "-m iprange --src-range %s-%s", range_B_addr, inet_ntoa(range_C)); 	// IP-range
						}
						else{
							sprintf(saddr_1, "-m iprange --src-range %s-%s", rule, inet_ntoa(range_C)); 		// IP-range
						}

						free(rule);
					}
					else{ // step4
						sprintf(saddr_1, "-s %s", addr_t);	// IP
					}

					v4v6_ok &= ipt_addr_compact(addr_t, v4v6_ok, (v4v6_ok==IPT_V4));
					if (!v4v6_ok) continue;
				}
				else{ // step3
					sprintf(saddr_1, "-m mac --mac-source %s", addr_t);	// MAC
				}
			}
		}
		else{ // step1
			sprintf(saddr_1, "-m iprange --src-range %s", addr_t);	// IP-range
		}
		//fprintf(stderr, "[qos] tmp=%s, ip=%s, mac=%s, addr=%s, addr_t=%s, saddr_1=%s, saddr_2=%s\n", tmp, q_ip, q_mac, addr, addr_t, saddr_1, saddr_2); // tmp test

		/*************************************************/
		/*                      port                     */
		/*            single port or multi-ports         */
		/*************************************************/
		char *tmp_port, *q_port, *q_leave;

		sprintf(tmp, "%s", port);
		tmp_port = tmp;
		q_port = strsep(&tmp_port, ",");
		q_leave = tmp_port;

		if(strcmp(port, "") == 0 ){
			sprintf(dport, "%s", "");
		}
		else{
			if(q_leave != NULL)
				sprintf(dport, "-m multiport --dport %s", port); // multi port
			else
				sprintf(dport, "--dport %s", port); // single port
		}
		//fprintf(stderr, "[qos] tmp=%s, q_port=%s, q_leave=%s, port=%s\n", tmp, q_port, q_leave, port ); // tmp test

		/*************************************************/
		/*                   transferred                 */
		/*   --connbytes min:max                         */
 		/*   --connbytes-dir (original/reply/both)       */
 		/*   --connbytes-mode (packets/bytes/avgpkt)     */
		/*************************************************/
		char *tmp_trans, *q_min, *q_max;
		long min, max ;

		sprintf(tmp, "%s", transferred);
		tmp_trans = tmp;
		q_min = strsep(&tmp_trans, "~");
		q_max = tmp_trans;

		if (strcmp(transferred,"") == 0){
			sprintf(conn, "%s", "");
		}
		else{
			sprintf(tmp, "%s", q_min);
			min = atol(tmp);

			if(strcmp(q_max,"") == 0) // q_max == NULL
				sprintf(conn, "-m connbytes --connbytes %ld:%s --connbytes-dir both --connbytes-mode bytes", min*1024, q_max);
			else{// q_max != NULL
				sprintf(tmp, "%s", q_max);
				max = atol(tmp);
				sprintf(conn, "-m connbytes --connbytes %ld:%ld --connbytes-dir both --connbytes-mode bytes", min*1024, max*1024-1);
			}
		}
		//fprintf(stderr, "[qos] tmp=%s, transferred=%s, min=%ld, max=%ld, q_max=%s, conn=%s\n", tmp, transferred, min*1024, max*1024-1, q_max, conn); // tmp test

		/*************************************************/
		/*                      proto                    */
		/*        tcp, udp, tcp/udp, any, (icmp, igmp)   */
		/*************************************************/
		memset(proto_1, 0, sizeof(proto_1));
		memset(proto_2, 0, sizeof(proto_2));
		if(!strcmp(proto, "tcp"))
		{
			sprintf(proto_1, "-p tcp");
			sprintf(proto_2, "NO");
		}
		else if(!strcmp(proto, "udp"))
		{
			sprintf(proto_1, "-p udp");
			sprintf(proto_2, "NO");
		}
		else if(!strcmp(proto, "any"))
		{
			sprintf(proto_1, "%s", "");
			sprintf(proto_2, "NO");
		}
		else if(!strcmp(proto, "tcp/udp"))
		{
			sprintf(proto_1, "-p tcp");
			sprintf(proto_2, "-p udp");
		}
		else{
			sprintf(proto_1, "NO");
			sprintf(proto_2, "NO");
		}
		//fprintf(stderr, "[qos] proto_1=%s, proto_2=%s, proto=%s\n", proto_1, proto_2, proto); // tmp test

		/*******************************************************************/
		/*                                                                 */
		/*  build final rule for check proto_1, proto_2, saddr_1, saddr_2  */
		/*                                                                 */
		/*******************************************************************/
		// step1. check proto != "NO"
		// step2. if proto = any, no proto / dport
		// step3. check saddr for ip-range; saddr_1 could be empty, dport only

		if (v4v6_ok & IPT_V4){
			// step1. check proto != "NO"
			if(strcmp(proto_1, "NO")){
				// step2. if proto = any, no proto / dport
				if(strcmp(proto_1, "")){
					// step3. check saddr for ip-range;saddr_1 could be empty, dport only
						fprintf(fn, "-A %s %s %s %s %s %s", chain, proto_1, dport, saddr_1, conn, end);
						if(manual_return)
						fprintf(fn, "-A %s %s %s %s %s %s", chain, proto_1, dport, saddr_1, conn, end2);

					if(strcmp(saddr_2, "")){
						fprintf(fn, "-A %s %s %s %s %s %s", chain, proto_1, dport, saddr_2, conn, end);
						if(manual_return)
						fprintf(fn, "-A %s %s %s %s %s %s", chain, proto_1, dport, saddr_2, conn, end2);
					}
				}
				else{
						fprintf(fn, "-A %s %s %s %s", chain, saddr_1, conn, end);
						if(manual_return)
						fprintf(fn, "-A %s %s %s %s", chain, saddr_1, conn, end2);

					if(strcmp(saddr_2, "")){
						fprintf(fn, "-A %s %s %s %s", chain, saddr_2, conn, end);
						if(manual_return)
						fprintf(fn, "-A %s %s %s %s", chain, saddr_2, conn, end2);
					}
				}
			}

			// step1. check proto != "NO"
			if(strcmp(proto_2, "NO")){
				// step2. if proto = any, no proto / dport
				if(strcmp(proto_2, "")){
					// step3. check saddr for ip-range;saddr_1 could be empty, dport only
						fprintf(fn, "-A %s %s %s %s %s %s", chain, proto_2, dport, saddr_1, conn, end);
						if(manual_return)
						fprintf(fn, "-A %s %s %s %s %s %s", chain, proto_2, dport, saddr_1, conn, end2);

					if(strcmp(saddr_2, "")){
						fprintf(fn, "-A %s %s %s %s %s %s", chain, proto_2, dport, saddr_2, conn, end);
						if(manual_return)
						fprintf(fn, "-A %s %s %s %s %s %s", chain, proto_2, dport, saddr_2, conn, end2);
					}
				}
				else{
						fprintf(fn, "-A %s %s %s %s", chain, saddr_1, conn, end);
						if(manual_return)
						fprintf(fn, "-A %s %s %s %s", chain, saddr_1, conn, end2);

					if(strcmp(saddr_2, "")){
						fprintf(fn, "-A %s %s %s %s", chain, saddr_2, conn, end);
						if(manual_return)
						fprintf(fn, "-A %s %s %s %s", chain, saddr_2, conn, end2);
					}
				}
			}
		}

#ifdef RTCONFIG_IPV6
		if (fn_ipv6 && ipv6_enabled() && (v4v6_ok & IPT_V6)){
			// step1. check proto != "NO"
			if(strcmp(proto_1, "NO")){
				// step2. if proto = any, no proto / dport
				if(strcmp(proto_1, "")){
					// step3. check saddr for ip-range;saddr_1 could be empty, dport only
						fprintf(fn_ipv6, "-A %s %s %s %s %s %s", chain, proto_1, dport, saddr_1, conn, end);
						if(manual_return)
						fprintf(fn_ipv6, "-A %s %s %s %s %s %s", chain, proto_1, dport, saddr_1, conn, end2);

					if(strcmp(saddr_2, "")){
						fprintf(fn_ipv6, "-A %s %s %s %s %s %s", chain, proto_1, dport, saddr_2, conn, end);
						if(manual_return)
						fprintf(fn_ipv6, "-A %s %s %s %s %s %s", chain, proto_1, dport, saddr_2, conn, end2);
					}
				}
				else{
						fprintf(fn_ipv6, "-A %s %s %s %s", chain, saddr_1, conn, end);
						if(manual_return)
						fprintf(fn_ipv6, "-A %s %s %s %s", chain, saddr_1, conn, end2);

					if(strcmp(saddr_2, "")){
						fprintf(fn_ipv6, "-A %s %s %s %s", chain, saddr_2, conn, end);
						if(manual_return)
						fprintf(fn_ipv6, "-A %s %s %s %s", chain, saddr_2, conn, end2);
					}
				}
			}

			// step1. check proto != "NO"
			if(strcmp(proto_2, "NO")){
				// step2. if proto = any, no proto / dport
				if(strcmp(proto_2, "")){
					// step3. check saddr for ip-range;saddr_1 could be empty, dport only
						fprintf(fn_ipv6, "-A %s %s %s %s %s %s", chain, proto_2, dport, saddr_1, conn, end);
						if(manual_return)
						fprintf(fn_ipv6, "-A %s %s %s %s %s %s", chain, proto_2, dport, saddr_1, conn, end2);

					if(strcmp(saddr_2, "")){
						fprintf(fn_ipv6, "-A %s %s %s %s %s %s", chain, proto_2, dport, saddr_2, conn, end);
						if(manual_return)
						fprintf(fn_ipv6, "-A %s %s %s %s %s %s", chain, proto_2, dport, saddr_2, conn, end2);
					}
				}
				else{
						fprintf(fn_ipv6, "-A %s %s %s %s", chain, saddr_1, conn, end);
						if(manual_return)
						fprintf(fn_ipv6, "-A %s %s %s %s", chain, saddr_1, conn, end2);
					if(strcmp(saddr_2, "")){
						fprintf(fn_ipv6, "-A %s %s %s %s", chain, saddr_2, conn, end);
						if(manual_return)
						fprintf(fn_ipv6, "-A %s %s %s %s", chain, saddr_2, conn, end2);
					}
				}
			}
		}
#endif
	}
	free(buf);

	/* lan_addr for iptables use (LAN download) */
	char *a, *b, *c, *d;
	char lan_addr[20];
	g = buf = strdup(nvram_safe_get("lan_ipaddr"));
	if((vstrsep(g, ".", &a, &b, &c, &d)) != 4){
		fprintf(stderr,"[qos] lan_ipaddr doesn't exist!!\n");
	}
	else{
		sprintf(lan_addr, "%s.%s.%s.0/24", a, b, c);
		fprintf(stderr,"[qos] lan_addr=%s\n", lan_addr);
	}
	free(buf);

	//fprintf(stderr, "[qos] down_class_num=%x\n", down_class_num);

	/* The default class */
	i = nvram_get_int("qos_default");
	if ((i < 0) || (i > 4)) i = 3;  // "lowest"
	class_num = i + 1;

#ifdef CONFIG_BCMWL5 // TODO: it is only for the case, eth0 as wan, vlanx as lan
	if(strncmp(pcWANIF, "ppp", 3)==0){
		// ppp related interface doesn't need physdev
		// do nothing
	}
	else{
		/* for WLAN to LAN bridge packet */
		// ebtables : identify bridge packet
		add_EbtablesRules();

		// for multicast
		fprintf(fn, "-A QOSO -d 224.0.0.0/4 -j CONNMARK --set-return 0x%x/0x7\n",  down_class_num);
		if(manual_return)
			fprintf(fn , "-A QOSO -d 224.0.0.0/4 -j RETURN\n");
		// for download (LAN or wireless)
		fprintf(fn, "-A QOSO -d %s -j CONNMARK --set-return 0x%x/0x7\n", lan_addr, down_class_num);
		if(manual_return)
			fprintf(fn , "-A QOSO -d %s -j RETURN\n", lan_addr);
/* Requires bridge netfilter, but slows down and breaks EMF/IGS IGMP IPTV Snooping
		// for WLAN to LAN bridge issue
		fprintf(fn, "-A POSTROUTING -d %s -m physdev --physdev-is-in -j CONNMARK --set-return 0x6/0x7\n", lan_addr);
*/
		// for download, interface br0
		fprintf(fn, "-A POSTROUTING -o br0 -j QOSO\n");
	}
#endif
		fprintf(fn,
			"-A QOSO -j CONNMARK --set-return 0x%x/0x7\n"
			"-A FORWARD -o %s -j QOSO\n"
			"-A OUTPUT -o %s -j QOSO\n",
				class_num, pcWANIF, pcWANIF);
		if(manual_return)
			fprintf(fn , "-A QOSO -j RETURN\n");

#ifdef RTCONFIG_IPV6
	if (fn_ipv6 && ipv6_enabled() && *wan6face) {
#ifdef CONFIG_BCMWL5 // TODO: it is only for the case, eth0 as wan, vlanx as lan
		if(strncmp(wan6face, "ppp", 3)==0){
			// ppp related interface doesn't need physdev
			// do nothing
		}
		else{
			/* for WLAN to LAN bridge packet */
			// ebtables : identify bridge packet
			add_EbtablesRules();

			// for multicast
			fprintf(fn_ipv6, "-A QOSO -d 224.0.0.0/4 -j CONNMARK --set-return 0x%x/0x7\n",  down_class_num);
			if(manual_return)
				fprintf(fn_ipv6, "-A QOSO -d 224.0.0.0/4 -j RETURN\n");
			// for download (LAN or wireless)
			fprintf(fn_ipv6, "-A QOSO -d %s -j CONNMARK --set-return 0x%x/0x7\n", lan_addr, down_class_num);
			if(manual_return)
				fprintf(fn_ipv6, "-A QOSO -d %s -j RETURN\n", lan_addr);
/* Requires bridge netfilter, but slows down and breaks EMF/IGS IGMP IPTV Snooping
			// for WLAN to LAN bridge issue
			fprintf(fn_ipv6, "-A POSTROUTING -d %s -m physdev --physdev-is-in -j CONNMARK --set-return 0x6/0x7\n", lan_addr);
*/
			// for download, interface br0
			fprintf(fn_ipv6, "-A POSTROUTING -o br0 -j QOSO\n");
		}
#endif
		fprintf(fn_ipv6,
			"-A QOSO -j CONNMARK --set-return 0x%x/0x7\n"
			"-A FORWARD -o %s -j QOSO\n"
			"-A OUTPUT -o %s -j QOSO\n",
				class_num, wan6face, wan6face);
		if(manual_return)
			fprintf(fn_ipv6, "-A QOSO -j RETURN\n");
	}
#endif

	inuse |= (1 << i) | 1;  // default and highest are always built
	sprintf(q_inuse, "%d", inuse);
	nvram_set("qos_inuse", q_inuse);
	fprintf(stderr, "[qos] qos_inuse=%d\n", inuse);

	/* Ingress rules */
	g = buf = strdup(nvram_safe_get("qos_irates"));
	for (i = 0; i < 10; ++i) {
		if ((!g) || ((p = strsep(&g, ",")) == NULL)) continue;
		if ((inuse & (1 << i)) == 0) continue;
		if (atoi(p) > 0) {
			fprintf(fn, "-A PREROUTING -i %s -j CONNMARK --restore-mark --mask 0x7\n", pcWANIF);
#ifdef CLS_ACT
			fprintf(fn, "-A PREROUTING -i %s -j IMQ --todev 0\n", pcWANIF);
#endif
#ifdef RTCONFIG_IPV6
			if (fn_ipv6 && ipv6_enabled() && *wan6face) {
				fprintf(fn_ipv6, "-A PREROUTING -i %s -j CONNMARK --restore-mark --mask 0x7\n", wan6face);
#ifdef CLS_ACT
				fprintf(fn_ipv6, "-A PREROUTING -i %s -j IMQ --todev 0\n", wan6face);
#endif
			}
#endif
			break;
		}
	}
	free(buf);

	fprintf(fn, "COMMIT\n");
	fclose(fn);
	chmod(mangle_fn, 0700);
	eval("iptables-restore", (char*)mangle_fn);
#ifdef RTCONFIG_IPV6
	if (fn_ipv6 && ipv6_enabled())
	{
		fprintf(fn_ipv6, "COMMIT\n");
		fclose(fn_ipv6);
		chmod(mangle_fn_ipv6, 0700);
		eval("ip6tables-restore", (char*)mangle_fn_ipv6);
	}
#endif

	run_custom_script("qos-start", "rules");
	fprintf(stderr, "[qos] iptables DONE!\n");

	return 0;
}