#!/bin/sh

if [ "${PALANG}" = "en" ]; then
	LANG_001="NO_PASSWORD_FILE"
	LANG_002="PASSWORD_ERROR"
	LANG_003="Permission denied"
fi


RAMDISK=/usr/ramdisk

. ${RAMDISK}/PG.conf
. ${RAMDISK}/etc/panabit.inf

TMPDIR=${DATAPATH}/webtmp
WEB_DOWNLOAD=${TMPDIR}/web_download

EVENTFILE=${PGETC}/log/pending_events
CURL="/usr/bin/curl"
FLOWEYE="${RAMDISK}/bin/floweye"
NTMEYE="${RAMDISK}/bin/ntmeye"
IPECTRL="${RAMDISK}/bin/ipectrl"
ESCTOOL="${RAMDISK}/bin/esctool"
URLENCODE="${RAMDISK}/bin/urlencode"
WEBUICTL="${RAMDISK}/app/webui/appctrl"
USER_DIR="${RAMDISK}/etc/webuser"
NGNTM="${RAMDISK}/bin/ngntmctrl"

NTM_TLS_DIR="${DATAPATH}/tls/key"
NTM_TLS_CONF="tls_key.list"
NTM_SESSKEY_CONF="session_key.list"
IPMAC_DESC_DIR="${PGETC}/ipmac_desc"
IPMAC_DESC_CONF_COL="ntm_cus_ipmacnote_col.conf"
IPMAC_DESC_CONF_TITLE="ntm_cus_ipmacnote_title.conf"

# set global env
export HOME="${DATAPATH}/webtmp"
export PATH="/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/usr/ramdisk/bin"
alias grep="grep -i"

if [ -f "/usr/pabin/pacu" ]; then
	CURL="/usr/pabin/pacu"
else
	CURL="`which curl | tail -1`"
fi


print_json_head()
{
	local charset=$1

	[ "${charset}" = "" ] && charset="gb2312"
	
	printf "Cache-Control:max-age=1\r\n"
	printf "X-Content-Type-Options:nosniff\r\n"
	printf "X-Frame-Options:SAMEORIGIN\r\n"
	printf "X-Xss-Protection:1;mode=block\r\n"
	printf "Referrer-Policy: strict-origin-when-cross-origin\r\n"
	printf "Content-Security-Policy:upgrade-insecure-requests\r\n"
	printf "Content-Security-Policy:'default-src' 'self' 'unsafe-eval';\r\n"
	printf "Content-Type:application/json;charset=${charset}\r\n"
	printf "\r\n"
}


retjson()
{
	print_json_head "gb2312"
	
	if [ "${3}" = "" ]; then
		echo -n "{ \"code\": ${1}, \"msg\": \"${2}\", \"data\": \"\"}"
	else
		echo -n "{ \"code\": ${1}, \"msg\": \"${2}\", \"data\": ${3}}"
	fi

	exit 0
}


retu8json()
{
	print_json_head "utf-8"

	if [ "${3}" = "" ]; then
		echo -n "{ \"code\": ${1}, \"msg\": \"${2}\", \"data\": \"\"}"
	else
		echo -n "{ \"code\": ${1}, \"msg\": \"${2}\", \"data\": ${3}}"
	fi

	exit 0
}


print_json_file()
{
	if [ ! -f ${1} ]; then
		printf "[]"
		return
	fi

	awk '{gsub("\\t", "", $0); printf "%s ", $0}' $1
}


admin_check()
{
	login_level=1
	ckfile=`get_cookie_file`

	aes_name=`${ESCTOOL} -e ${PANABIT_USER}`
	ufile=${USER_DIR}/${aes_name}

	#  ⲿ˺Ųⲿ˺ſܸ˺
	[ ! -f "${ufile}" ] && retjson 1 "${LANG_003:=Ȩ޲}!"

	. ${ufile}
	[ -f "${ckfile}" ] && . ${ckfile}

	[ "${login_level}" != 0 ] && retjson 1 "${LANG_003:=Ȩ޲}!"
	[ "${CGI_password}" != "" -a "${CGI_password}" != "${password}" ] && retjson 1 "${LANG_002:=}!"
}


action_check()
{
	login_level=1
	ckfile=`get_cookie_file`

	[ -f "${ckfile}" ] && . ${ckfile}

	[ "${login_level}" -gt 1 ] && retjson 1 "${LANG_003:=Ȩ޲}!"
}


is_ipaddr()
{
    is_ipv6=`echo "${1}" | grep ":"`
    [ "${is_ipv6}" != "" ] && return 0

	echo "${1}" | grep "^[0-9]\{1,3\}\.\([0-9]\{1,3\}\.\)\{2\}[0-9]\{1,3\}$" > /dev/null;
	[ $? -ne 0 ] && return 1

	uipaddr=$1
	a=`echo $uipaddr|awk -F . '{print $1}'`
	b=`echo $uipaddr|awk -F . '{print $2}'`
	c=`echo $uipaddr|awk -F . '{print $3}'`
	d=`echo $uipaddr|awk -F . '{print $4}'`

	for num in $a $b $c $d
	do
		[ $num -gt 255 ] || [ $num -lt 0 ] && return 1
	done

	return 0
}


sync_floweye()
{
	enable=0
	sync_conf="${PGETC}/web/config_sync.conf"
	sync_dir="${RAMDISK}/tmp/ipe_syncd"

	[ -f "${sync_conf}" ] && . ${sync_conf}
	[ "${enable}" != "1" ] && return

	cur_nsec=`/usr/ramdisk/bin/paui_time`
	sync_file="${sync_dir}/${cur_nsec}.syncd"
	
	mkdir -p ${sync_dir}
	echo "${*}" > ${sync_file}
}


sendto_webui_pipe()
{
	local cmd_dir="${RAMDISK}/var/webui_pipe.d"
	local cmd_file="${cmd_dir}/$$_$(date +%s)"

	[ ! -d "${cmd_dir}" ] && retjson 1 "WEBUI_PIPEδ"

	echo "$@" > ${cmd_file}
}


WEB_LOGGER()
{
	local curtime=`date +%Y.%m.%d/%H:%M:%S`
	local localfile="${DATAPATH}/web_`date +%Y.%m.%d`.log"
	local cloudfile="${TMPDIR}/cloudfile.log"
	local logmsg="${curtime} ${REMOTE_ADDR} ${PANABIT_USER} $1 $2"

	echo "${logmsg}" >> ${localfile}

	if [ -f ${TMPDIR}/log2cloud ]; then
		if [ -f ${cloudfile} ]; then
			rows=`awk 'END{print NR}' ${cloudfile}`
			if [ ${rows} -gt 500 ]; then
				echo "${logmsg}" > ${cloudfile}
			else
				echo "${logmsg}" >> ${cloudfile}
			fi
		else
			echo "${logmsg}" >> ${cloudfile}
		fi
	fi

	if [ -f "${PGETC}/web/actlog.conf" ]; then
		. ${PGETC}/web/actlog.conf

		if [ "${actlog_enable}" = "1" ]; then
			deviceid=`${FLOWEYE} logger stat | grep "deviceid" | cut -d"=" -f2`
			for item in `${FLOWEYE} key info`
			do
				key=`echo ${item} | cut -d"=" -f1`
				val=`echo ${item} | cut -d"=" -f2`
				[ "${key}" = "oem" ] && oem=${val}
			done
			[ "${oem}" = "" ] && return
			${RAMDISK}/bin/sendlog ${actlog_ip} ${actlog_port} ${oem} ${deviceid} "${logmsg}"
		fi
	fi

	if [ "${NTM}" != "1" -a "${TAP}" != "1" ]; then
		sync
		sync
	fi
}


chart_dump()
{
	[ $# -ne 3 ] && retjson 1 "INV_ARGS"

	hours="${1}"
	tmend="${2}"
	tag="${3}"
	
	${FLOWEYE} chart dump json=1 hours=${hours} tmend=${tmend} ${tag}
}


utf8togb2312()
{
	${FLOWEYE} iconv utf8togb2312 $* | tr -ds "\n" ""
}


gb2312toutf8()
{
	${FLOWEYE} iconv gb2312toutf8 $* | tr -ds "\n" ""
}


nslookup_url()
{
	url=$1
	dns=`cat /etc/resolv.conf | grep "^nameserver" | head -1 | cut -d" " -f2`
	[ "${dns}" = "" -o "${dns}" = "0.0.0.0" ] && dns="114.114.114.114"

	${FLOWEYE} nslookup ${url} ${dns} | head -1
}


get_cookie_file()
{
	ckfile=""

	for line in `echo "${HTTP_COOKIE}" | tr ";" " "`
	do
		key=`echo ${line} | cut -d"=" -f1`
		val=`echo ${line} | cut -d"=" -f2`
		pauser=`echo ${key} | grep "pauser_"`

		if [ "${pauser}" != "" ]; then
			ckfile="/usr/ramdisk/weblogin/${val}"
		fi
	done

	echo "${ckfile}"
}


_do_xss_filter()
{
	xss_verify_rule="<>\"'()"

	errstr=`echo "${1}" | grep "\.\."`

	if [ "${errstr}" != "" ]; then
		echo ".."
		return 1
	fi

	awk -v str="${1}" -v rule="${xss_verify_rule}" \
	'BEGIN{
		split(str, args, "&");
		for(j = 1; j <= length(args); j++){

			if(index(args[j], "=") <= 1){
				print args[j];
				exit 1;
			}

			for(i = 1; i <= length(args[j]); i++){
				char = substr(args[j], i, 1);

				if (char == "`"){
					print char;
					exit 1;
				}

				if (char == " " || char == "-" || char == "=" || char == "_" || char == ".") continue;

				for(x = 1; x <= length(rule); x++){
					r = substr(rule, x, 1);
					if(char == r){
						print char;
						exit 1;
					}
				}
			}
		}
	}'

	return $?
}


XSS_FILTER()
{
	[ ! -f "${RAMDISK}/web_secure.conf" ] && return

	file_upload=`echo "${CONTENT_TYPE}" | grep "multipart/form-data"`
	[ "${file_upload}" != "" ] && return

	[ "${URLENCODE}" = "" -a "${QUERY_STRING}" = "" ] && return

	get_str=`${URLENCODE} -d ${QUERY_STRING}`
	post_str=`${URLENCODE} -d  ${POST_STRING}`

	errstr=`_do_xss_filter "${get_str}"`
	[ $? -ne 0 ] && retjson 1 "INV_STR:${errstr}"

	errstr=`_do_xss_filter "${post_str}"`
	[ $? -ne 0 ] && retjson 1 "INV_STR:${errstr}"
}


TOKEN_CHECK()
{
	local ckfile=`get_cookie_file`
	local enable=0
	local token=""

	[ ! -f "${RAMDISK}/csrf_verify.conf" ] && return

	is_ajax=`echo "${SCRIPT_NAME}" | grep "ajax_"`
	[ "${is_ajax}" = "" ] && return

	token=`grep token ${ckfile} | cut -d"=" -f2`
	[ "${token}" != "${HTTP_TOKEN}" ] && retjson 1 "INV_TOKEN"
}


XSS_FILTER
TOKEN_CHECK

export PATH="${PATH}:${RAMDISK}/bin/"
