luci-app-udp2raw

This commit is contained in:
CN_SZTL 2019-05-25 18:57:41 +08:00
parent c992e42ec2
commit ac2f8bc2a5
No known key found for this signature in database
GPG Key ID: 6850B6345C862176
18 changed files with 1603 additions and 6 deletions

View File

@ -1,5 +1,9 @@
# A OpenWRT firmware based on Lean's source
### Welcome to my Telegram Group: [@openwrt_discuss](https://t.me/openwrt_discuss).
### Welcome to my Telegram Group: [@openwrt\_discuss](https://t.me/openwrt_discuss).
# Tips
You'd better not use **root** to make it, or you may be not able to use.<br/>
Default username is **root** and password is **password**, login address: 192.168.1.1.
# How to make it
## OS require
@ -28,11 +32,10 @@ make menuconfig
make -j1 V=s
```
# TIPS
You'd better not use **root** to make it, or you may be not able to use.<br/>
Default username is **root** and password is **password**, login address: 192.168.1.1.
# Origin source
### Based on: [coolsnowwolf/lede](https://github.com/coolsnowwolf/lede).<br/>
luci-app-koolproxy source: [openwrt-develop/luci-app-koolproxy](https://github.com/openwrt-develop/luci-app-koolproxy).<br/>
luci-app-udp2raw source: [luci-app-udp2raw](https://github.com/sensec/luci-app-udp2raw)
# License
### [GPL v3](https://www.gnu.org/licenses/gpl-3.0.html).
### Origin source: [coolsnowwolf/lede](https://github.com/coolsnowwolf/lede).
### luci-app-koolproxy source: [openwrt-develop/luci-app-koolproxy](https://github.com/openwrt-develop/luci-app-koolproxy).

View File

@ -0,0 +1,73 @@
#
# Copyright (C) 2016-2017 Jian Chang <aa65535@live.com>
#
# This is free software, licensed under the GNU General Public License v3.
# See /LICENSE for more information.
#
include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-udp2raw
PKG_VERSION:=1.0.0
PKG_RELEASE:=4
PKG_LICENSE:=GPLv3
PKG_LICENSE_FILES:=LICENSE
PKG_MAINTAINER:=Jian Chang <aa65535@live.com>
include $(INCLUDE_DIR)/package.mk
define Package/$(PKG_NAME)
SECTION:=luci
CATEGORY:=LuCI
SUBMENU:=3. Applications
TITLE:=LuCI Support for udp2raw-tunnel
PKGARCH:=all
# DEPENDS:=+udp2raw-tunnel
endef
define Package/$(PKG_NAME)/description
LuCI Support for udp2raw-tunnel.
endef
define Build/Prepare
$(foreach po,$(wildcard ${CURDIR}/files/luci/i18n/*.po), \
po2lmo $(po) $(PKG_BUILD_DIR)/$(patsubst %.po,%.lmo,$(notdir $(po)));)
endef
define Build/Configure
endef
define Build/Compile
endef
define Package/$(PKG_NAME)/postinst
#!/bin/sh
if [ -z "$${IPKG_INSTROOT}" ]; then
( . /etc/uci-defaults/luci-udp2raw ) && rm -f /etc/uci-defaults/luci-udp2raw
fi
exit 0
endef
define Package/$(PKG_NAME)/conffiles
/etc/config/udp2raw
endef
define Package/$(PKG_NAME)/install
$(INSTALL_DIR) $(1)/usr/lib/lua/luci/i18n
$(INSTALL_DATA) $(PKG_BUILD_DIR)/udp2raw.*.lmo $(1)/usr/lib/lua/luci/i18n/
$(INSTALL_DIR) $(1)/usr/lib/lua/luci/controller
$(INSTALL_DATA) ./files/luci/controller/*.lua $(1)/usr/lib/lua/luci/controller/
$(INSTALL_DIR) $(1)/usr/lib/lua/luci/model/cbi/udp2raw
$(INSTALL_DATA) ./files/luci/model/cbi/udp2raw/*.lua $(1)/usr/lib/lua/luci/model/cbi/udp2raw/
$(INSTALL_DIR) $(1)/usr/lib/lua/luci/view/udp2raw
$(INSTALL_DATA) ./files/luci/view/udp2raw/*.htm $(1)/usr/lib/lua/luci/view/udp2raw/
$(INSTALL_DIR) $(1)/etc/config
$(INSTALL_CONF) ./files/root/etc/config/udp2raw $(1)/etc/config/udp2raw
$(INSTALL_DIR) $(1)/etc/init.d
$(INSTALL_BIN) ./files/root/etc/init.d/udp2raw $(1)/etc/init.d/udp2raw
$(INSTALL_DIR) $(1)/etc/uci-defaults
$(INSTALL_BIN) ./files/root/etc/uci-defaults/luci-udp2raw $(1)/etc/uci-defaults/luci-udp2raw
endef
$(eval $(call BuildPackage,$(PKG_NAME)))

View File

@ -0,0 +1,30 @@
module("luci.controller.udp2raw", package.seeall)
function index()
if not nixio.fs.access("/etc/config/udp2raw") then
return
end
entry({"admin", "services", "udp2raw"},
firstchild(), _("udp2raw-tunnel")).dependent = false
entry({"admin", "services", "udp2raw", "general"},
cbi("udp2raw/general"), _("Settings"), 1)
entry({"admin", "services", "udp2raw", "servers"},
arcombine(cbi("udp2raw/servers"), cbi("udp2raw/servers-details")),
_("Servers Manage"), 2).leaf = true
entry({"admin", "services", "udp2raw", "status"}, call("action_status"))
end
local function is_running(name)
return luci.sys.call("pidof %s >/dev/null" %{name}) == 0
end
function action_status()
luci.http.prepare_content("application/json")
luci.http.write_json({
running = is_running("udp2raw")
})
end

View File

@ -0,0 +1,120 @@
msgid ""
msgstr "Content-Type: text/plain; charset=UTF-8\n"
msgid "udp2raw-tunnel"
msgstr "udp2raw 隧道"
msgid "Settings"
msgstr "设置"
msgid "Servers Manage"
msgstr "服务器管理"
msgid "Running Status"
msgstr "运行状态"
msgid "Binary Version"
msgstr "文件版本"
msgid "Build Time"
msgstr "编译时间"
msgid "Invalid Binary File."
msgstr "可执行文件无效。"
msgid "RUNNING"
msgstr "运行中"
msgid "NOT RUNNING"
msgstr "未运行"
msgid "General Settings"
msgstr "基本设置"
msgid "Server"
msgstr "服务器"
msgid "Disable"
msgstr "停用"
msgid "Run Daemon as User"
msgstr "以该用户启动"
msgid "Alias"
msgstr "别名"
msgid "None"
msgstr "无"
msgid "Server Address"
msgstr "服务器地址"
msgid "Listen Address"
msgstr "监听地址"
msgid "Edit Server"
msgstr "编辑服务器"
msgid "Alias(optional)"
msgstr "别名(可选)"
msgid "Server Port"
msgstr "服务器端口"
msgid "Local Listen Host"
msgstr "本地监听地址"
msgid "Local Listen Port"
msgstr "本地监听端口"
msgid "Raw Mode"
msgstr "Raw 方式"
msgid "Password"
msgstr "密码"
msgid "Cipher Mode"
msgstr "加密方式"
msgid "Auth Mode"
msgstr "验证方式"
msgid "Auto Rule"
msgstr "自动规则"
msgid "Auto add (and delete) iptables rule."
msgstr "自动添加/删除 iptables 规则。"
msgid "Keep Rule"
msgstr "保持规则"
msgid "Monitor iptables and auto re-add if necessary."
msgstr "定期检查 iptables 并在必要时重新添加规则。"
msgid "seq Mode"
msgstr "seq 模式"
msgid "seq increase mode for faketcp."
msgstr "用于 faketcp 的 seq 增加方式。"
msgid "Lower Level"
msgstr ""
msgid "Send packets at OSI level 2, format: \"eth0#00:11:22:33:44:55\", or \"auto\"."
msgstr "在 OSI 模型第二层发送数据包,格式:\"eth0#00:11:22:33:44:55\",或 \"auto\"。"
msgid "Source-IP"
msgstr "源IP"
msgid "Force source-ip for Raw Socket."
msgstr "在原始数据包中强制指定源IP。"
msgid "Source-Port"
msgstr "源端口"
msgid "Force source-port for Raw Socket, TCP/UDP only."
msgstr "在原始数据包中强制指定源端口,仅用于 TCP/UDP。"
msgid "Log Level"
msgstr "日志级别"

View File

@ -0,0 +1,39 @@
local m, s, o
local uci = luci.model.uci.cursor()
local servers = {}
local function has_bin(name)
return luci.sys.call("command -v %s >/dev/null" %{name}) == 0
end
if not has_bin("udp2raw") then
return Map("udp2raw", "%s - %s" %{translate("udp2raw-tunnel"),
translate("Settings")}, '<b style="color:red">udp2raw-tunnel binary file not found. install udp2raw-tunnel package, or copy binary to /usr/bin/udp2raw manually. </b>')
end
uci:foreach("udp2raw", "servers", function(s)
if s.server_addr and s.server_port then
servers[#servers+1] = {name = s[".name"], alias = s.alias or "%s:%s" %{s.server_addr, s.server_port}}
end
end)
m = Map("udp2raw", "%s - %s" %{translate("udp2raw-tunnel"), translate("Settings")})
m:append(Template("udp2raw/status"))
s = m:section(NamedSection, "general", "general", translate("General Settings"))
s.anonymous = true
s.addremove = false
o = s:option(DynamicList, "server", translate("Server"))
o.template = "udp2raw/dynamiclist"
o:value("nil", translate("Disable"))
for _, s in ipairs(servers) do o:value(s.name, s.alias) end
o.default = "nil"
o.rmempty = false
o = s:option(ListValue, "daemon_user", translate("Run Daemon as User"))
for u in luci.util.execi("cat /etc/passwd | cut -d ':' -f1") do o:value(u) end
o.default = "root"
o.rmempty = false
return m

View File

@ -0,0 +1,92 @@
local m, s, o
local sid = arg[1]
local raw_modes = {
"faketcp",
"udp",
"icmp",
}
local cipher_modes = {
"aes128cbc",
"xor",
"none",
}
local auth_modes = {
"md5",
"crc32",
"simple",
"none",
}
m = Map("udp2raw", "%s - %s" %{translate("udp2raw-tunnel"), translate("Edit Server")})
m.redirect = luci.dispatcher.build_url("admin/services/udp2raw/servers")
m.sid = sid
if m.uci:get("udp2raw", sid) ~= "servers" then
luci.http.redirect(m.redirect)
return
end
s = m:section(NamedSection, sid, "servers")
s.anonymous = true
s.addremove = false
o = s:option(Value, "alias", translate("Alias(optional)"))
o = s:option(Value, "server_addr", translate("Server"))
o.datatype = "host"
o.rmempty = false
o = s:option(Value, "server_port", translate("Server Port"))
o.datatype = "port"
o.placeholder = "8080"
o = s:option(Value, "listen_addr", translate("Local Listen Host"))
o.datatype = "ipaddr"
o.placeholder = "127.0.0.1"
o = s:option(Value, "listen_port", translate("Local Listen Port"))
o.datatype = "port"
o.placeholder = "2080"
o = s:option(ListValue, "raw_mode", translate("Raw Mode"))
for _, v in ipairs(raw_modes) do o:value(v, v:lower()) end
o.default = "faketcp"
o.rmempty = false
o = s:option(Value, "key", translate("Password"))
o.password = true
o = s:option(ListValue, "cipher_mode", translate("Cipher Mode"))
for _, v in ipairs(cipher_modes) do o:value(v, v:lower()) end
o.default = "aes128cbc"
o = s:option(ListValue, "auth_mode", translate("Auth Mode"))
for _, v in ipairs(auth_modes) do o:value(v, v:lower()) end
o.default = "md5"
o = s:option(Flag, "auto_rule", translate("Auto Rule"), translate("Auto add (and delete) iptables rule."))
o.default = "1"
o = s:option(Flag, "keep_rule", translate("Keep Rule"), translate("Monitor iptables and auto re-add if necessary."))
o:depends("auto_rule", "1")
o = s:option(Value, "seq_mode", translate("seq Mode"), translate("seq increase mode for faketcp."))
o.datatype = "range(0,4)"
o.placeholder = "3"
o = s:option(Value, "lower_level", translate("Lower Level"), translate("Send packets at OSI level 2, format: \"eth0#00:11:22:33:44:55\", or \"auto\"."))
o = s:option(Value, "source_ip", translate("Source-IP"), translate("Force source-ip for Raw Socket."))
o.datatype = "ipaddr"
o = s:option(Value, "source_port", translate("Source-Port"), translate("Force source-port for Raw Socket, TCP/UDP only."))
o.datatype = "port"
o = s:option(Value, "log_level", translate("Log Level"))
o.datatype = "range(0,6)"
o.placeholder = "4"
return m

View File

@ -0,0 +1,56 @@
local m, s, o
m = Map("udp2raw", "%s - %s" %{translate("udp2raw-tunnel"), translate("Servers Manage")})
s = m:section(TypedSection, "servers")
s.anonymous = true
s.addremove = true
s.sortable = true
s.template = "cbi/tblsection"
s.extedit = luci.dispatcher.build_url("admin/services/udp2raw/servers/%s")
function s.create(...)
local sid = TypedSection.create(...)
if sid then
luci.http.redirect(s.extedit % sid)
return
end
end
o = s:option(DummyValue, "alias", translate("Alias"))
function o.cfgvalue(...)
return Value.cfgvalue(...) or translate("None")
end
o = s:option(DummyValue, "_server_address", translate("Server Address"))
function o.cfgvalue(self, section)
local server_addr = m.uci:get("udp2raw", section, "server_addr") or "?"
local server_port = m.uci:get("udp2raw", section, "server_port") or "8080"
return "%s:%s" %{server_addr, server_port}
end
o = s:option(DummyValue, "_listen_address", translate("Listen Address"))
function o.cfgvalue(self, section)
local listen_addr = m.uci:get("udp2raw", section, "listen_addr") or "127.0.0.1"
local listen_port = m.uci:get("udp2raw", section, "listen_port") or "2080"
return "%s:%s" %{listen_addr, listen_port}
end
o = s:option(DummyValue, "raw_mode", translate("Raw Mode"))
function o.cfgvalue(...)
local v = Value.cfgvalue(...)
return v and v:lower() or "faketcp"
end
o = s:option(DummyValue, "cipher_mode", translate("Cipher Mode"))
function o.cfgvalue(...)
local v = Value.cfgvalue(...)
return v and v:lower() or "aes128cbc"
end
o = s:option(DummyValue, "auth_mode", translate("Auth Mode"))
function o.cfgvalue(...)
local v = Value.cfgvalue(...)
return v and v:lower() or "md5"
end
return m

View File

@ -0,0 +1,98 @@
<%#
Copyright (C) 2017 Jian Chang <aa65535@live.com>
Licensed to the public under the GNU General Public License v3.
-%>
<%+cbi/valueheader%>
<%-
local values = self:formvalue(section)
if not values then
values = self:cfgvalue(section) or {self.default}
end
local function serialize_json(x, cb)
local rv, push = nil, cb
if not push then
rv = { }
push = function(tok) rv[#rv+1] = tok end
end
if x == nil then
push("null")
elseif type(x) == "table" then
push("[")
for k = 1, #x do
if k > 1 then
push(",")
end
serialize_json(x[k], push)
end
push("]")
else
push('"%s"' % tostring(x):gsub('["%z\1-\31\\]',
function(c) return '\\u%04x' % c:byte(1) end))
end
if not cb then
return table.concat(rv, "")
end
end
-%>
<div<%=attr("id", cbid .. ".value.field")%>></div>
<script type="text/javascript">//<![CDATA[
(function() {
var values = <%=serialize_json(values)%>;
var keylist = <%=serialize_json(self.keylist)%>;
var vallist = <%=serialize_json(self.vallist)%>;
var parent = document.getElementById("<%=cbid%>.value.field");
var dynamiclist_cbi_init = function() {
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
for (var i = 0; i < values.length; i++) {
var sel = document.createElement("select");
sel.id = "<%=cbid%>." + (i + 1);
sel.name = "<%=cbid%>";
sel.index = i;
sel.className = "cbi-input-select";
sel.onchange = function() {
values[this.index] = this.value;
};
parent.appendChild(sel);
for (var j = 0; j < keylist.length; j++) {
var opt = document.createElement("option");
opt.value = keylist[j];
if (opt.value == values[i]) {
opt.selected = "selected";
}
opt.appendChild(document.createTextNode(vallist[j]));
sel.appendChild(opt);
}
var btn = document.createElement('img');
btn.src = "<%=resource%>" + ((i + 1) < values.length ? "/cbi/remove.gif" : "/cbi/add.gif");
btn.index = i;
btn.className = 'cbi-image-button';
btn.onclick = function() {
if (this.src.indexOf('remove') > -1) {
values.splice(this.index, 1);
} else {
values.push("<%=self.default%>");
}
dynamiclist_cbi_init();
return false;
};
parent.appendChild(btn);
parent.appendChild(document.createElement('br'));
}
};
dynamiclist_cbi_init();
}());
//]]></script>
<%+cbi/valuefooter%>

View File

@ -0,0 +1,39 @@
<%
local function get_udp2raw_version(name)
local info = luci.util.split(luci.sys.exec("%s -h 2>/dev/null" %{name}), "\n")
local version = string.match(info[2], "git version:(%w+)")
local build = string.match(info[2], "build date:(.+)")
return info[1] == "udp2raw-tunnel" and version or "", info[1] == "udp2raw-tunnel" and build or ""
end
local udp2raw_version, udp2raw_build = get_udp2raw_version("udp2raw")
-%>
<fieldset class="cbi-section">
<legend><%:Running Status%></legend>
<table width="100%" cellspacing="10" id="_udp2raw_status_table">
<tr>
<td width="33%"><%:Binary Version%></td>
<td>
<% if udp2raw_version == "" then -%>
<em><%:Invalid Binary File.%></em>
<% else -%>
<%=pcdata(udp2raw_version)%>
<%- end %>
</td>
</tr>
<% if udp2raw_build ~= "" then -%>
<tr><td width="33%"><%:Build Time%></td><td><%=pcdata(udp2raw_build)%></td></tr>
<% end -%>
<tr><td width="33%"><%:Running Status%></td><td id="_udp2raw_status"><em><%:Collecting data...%></em></td></tr>
</table>
</fieldset>
<script type="text/javascript">//<![CDATA[
var udp2raw_status = document.getElementById('_udp2raw_status');
XHR.poll(5, '<%=luci.dispatcher.build_url("admin", "services", "udp2raw", "status")%>', null, function(x, status) {
if ( x && x.status == 200 ) {
udp2raw_status.innerHTML = status.running ? '<%:RUNNING%>' : '<%:NOT RUNNING%>';
}
});
//]]></script>

View File

@ -0,0 +1,16 @@
config general 'general'
list server 'nil'
option daemon_user 'root'
config servers 'default'
option server_addr ''
option server_port '8080'
option listen_addr '127.0.0.1'
option listen_port '2080'
option raw_mode 'faketcp'
option key ''
option cipher_mode 'aes128cbc'
option auth_mode 'md5'
option auto_rule '1'

View File

@ -0,0 +1,156 @@
#!/bin/sh /etc/rc.common
START=88
STOP=15
USE_PROCD=1
NAME=udp2raw
_log() {
logger -p "daemon.$1" -t "$NAME" "$2"
}
has_valid_server() {
local server
for server in $@; do
[ "$(uci_get $NAME $server)" = "servers" ] && return 0
done
return 1
}
add_ipt_rule() {
if [ -z "$ipt_cmd" ]; then
command -v iptables >/dev/null 2>&1 || return 1
ipt_cmd='iptables'
[ -n "$(iptables -h 2> /dev/null | grep -e '--wait')" ] && ipt_cmd="$ipt_cmd --wait"
echo "# firewall include file" > "/var/etc/$NAME.include"
else
echo "$ipt_cmd" | grep -q -e '--wait'
[ $? -ne 0 ] && sleep 2
fi
$ipt_cmd -I INPUT -s "$server_addr"/32 -p tcp -m tcp --sport "$server_port" -m comment --comment "${NAME}DwrW" -j DROP
}
flush_ipt_rules() {
iptables-save -c | grep -v "${NAME}DwrW" | iptables-restore -c
[ -f "/var/etc/$NAME.include" ] && rm -f "/var/etc/$NAME.include"
}
export_ipt_rules() {
[ -f "/var/etc/$NAME.include" ] || return
cat <<-CAT >> "/var/etc/$NAME.include"
iptables-save -c | grep -v "${NAME}DwrW" | iptables-restore -c
iptables-restore -n <<-EOF
$(iptables-save -t filter | grep -E "${NAME}DwrW|^\*|^COMMIT" | sed 's/^-A /-I /')
EOF
CAT
}
create_config() {
local config_file="$1"
echo "# auto-generated config file from /etc/config/udp2raw" > $config_file
echo "-c" >> $config_file
echo "-l ${listen_addr}:${listen_port}" >> $config_file && _log "info" "listening on: ${listen_addr}:${listen_port}"
echo "-r ${server_addr}:${server_port}" >> $config_file
[ -n "$raw_mode" ] && echo "--raw-mode ${raw_mode}" >> $config_file && _log "info" "raw-mode: ${raw_mode}"
[ -n "$key" ] && echo "--key ${key}" >> $config_file
[ -n "$cipher_mode" ] && echo "--cipher-mode ${cipher_mode}" >> $config_file
[ -n "$auth_mode" ] && echo "--auth-mode ${auth_mode}" >> $config_file
[ $auto_rule -eq 1 -a $keep_rule -eq 1 ] && echo "--auto-rule" >> $config_file
[ $auto_rule -eq 1 -a $keep_rule -eq 1 ] && echo "--keep-rule" >> $config_file
[ -n "$seq_mode" ] && echo "--seq-mode ${seq_mode}" >> $config_file
[ -n "$lower_level" ] && echo "--lower-level ${lower_level}" >> $config_file
[ -n "$source_ip" ] && echo "--source-ip ${source_ip}" >> $config_file
[ -n "$source_port" ] && echo "--source-port ${source_port}" >> $config_file
echo "--retry-on-error" >> $config_file
[ -n "$log_level" ] && echo "--log-level ${log_level}" >> $config_file
echo "--disable-color" >> $config_file
}
validate_config_section() {
uci_validate_section "$NAME" general "$1" \
'server:uciname' \
'daemon_user:string:root'
}
validate_server_section() {
uci_validate_section "$NAME" servers "$1" \
'server_addr:host' \
'server_port:port:8080' \
'listen_addr:ipaddr:127.0.0.1' \
'listen_port:port:2080' \
'raw_mode:or("faketcp", "udp", "icmp"):faketcp' \
'key:string' \
'cipher_mode:or("aes128cbc", "xor", "none"):aes128cbc' \
'auth_mode:or("md5", "crc32", "simple", "none"):md5' \
'auto_rule:bool:1' \
'keep_rule:bool:0' \
'seq_mode:range(0,4)' \
'lower_level:string' \
'source_ip:ipaddr' \
'source_port:port' \
'log_level:range(0,6)'
}
start_instance() {
local server="$1"
if [ -z "$server" -o "$server" == "nil" ]; then
return 0
elif ! validate_server_section "$server"; then
_log "err" "Server config validation failed."
return 1
fi
/sbin/validate_data "ipaddr" "$server_addr" >/dev/null 2>&1
[ $? -ne 0 ] && server_addr=$(nslookup "$server_addr" | \
sed -n 's/^Address[[:space:]]*[0-9]*:[[:space:]]*\(\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}\)$/\1/p')
if [ -z "$server_addr" ]; then
_log "err" "Server address validation failed."
return 1
fi
[ -d /var/etc ] || mkdir -p /var/etc
local config_file="/var/etc/${NAME}.${server}.conf"
create_config "$config_file" || return 1
if [ $auto_rule -eq 1 -a $keep_rule -ne 1 ]; then
add_ipt_rule || { _log "err" "added iptables rule failed."; return 1; }
fi
procd_open_instance
procd_set_param command /usr/bin/udp2raw
procd_append_param command --conf-file "$config_file"
procd_set_param respawn
procd_set_param file "$config_file"
[ -n "$daemon_user" ] && procd_set_param user "$daemon_user" && _log "info" "running from ${daemon_user} user"
procd_set_param pidfile "/var/run/${NAME}.${server}.pid"
procd_close_instance
}
service_triggers() {
procd_add_reload_trigger "$NAME"
}
start_service() {
if ! validate_config_section "general" ; then
_log "err" "Config validate failed."
return 1
fi
has_valid_server $server || return 1
flush_ipt_rules
for srv in $server; do
start_instance $srv
done
export_ipt_rules
}
stop_service() {
flush_ipt_rules
}

View File

@ -0,0 +1,167 @@
#!/bin/sh /etc/rc.common
START=88
STOP=15
NAME=udp2raw
_log() {
logger -p "daemon.$1" -t "$NAME" "$2"
}
has_valid_server() {
local server
for server in $@; do
[ "$(uci_get $NAME $server)" = "servers" ] && return 0
done
return 1
}
add_ipt_rule() {
if [ -z "$ipt_cmd" ]; then
command -v iptables >/dev/null 2>&1 || return 1
ipt_cmd='iptables'
[ -n "$(iptables -h 2> /dev/null | grep -e '--wait')" ] && ipt_cmd="$ipt_cmd --wait"
echo "# firewall include file" > "/var/etc/$NAME.include"
else
echo "$ipt_cmd" | grep -q -e '--wait'
[ $? -ne 0 ] && sleep 2
fi
$ipt_cmd -I INPUT -s "$server_addr"/32 -p tcp -m tcp --sport "$server_port" -m comment --comment "${NAME}DwrW" -j DROP
}
flush_ipt_rules() {
iptables-save -c | grep -v "${NAME}DwrW" | iptables-restore -c
[ -f "/var/etc/$NAME.include" ] && rm -f "/var/etc/$NAME.include"
}
export_ipt_rules() {
[ -f "/var/etc/$NAME.include" ] || return
cat <<-CAT >> "/var/etc/$NAME.include"
iptables-save -c | grep -v "${NAME}DwrW" | iptables-restore -c
iptables-restore -n <<-EOF
$(iptables-save -t filter | grep -E "${NAME}DwrW|^\*|^COMMIT" | sed 's/^-A /-I /')
EOF
CAT
}
create_config() {
local config_file="$1"
echo "# auto-generated config file from /etc/config/udp2raw" > $config_file
echo "-c" >> $config_file
echo "-l ${listen_addr}:${listen_port}" >> $config_file
echo "-r ${server_addr}:${server_port}" >> $config_file
[ -n "$raw_mode" ] && echo "--raw-mode ${raw_mode}" >> $config_file
[ -n "$key" ] && echo "--key ${key}" >> $config_file
[ -n "$cipher_mode" ] && echo "--cipher-mode ${cipher_mode}" >> $config_file
[ -n "$auth_mode" ] && echo "--auth-mode ${auth_mode}" >> $config_file
[ $auto_rule -eq 1 -a $keep_rule -eq 1 ] && echo "--auto-rule" >> $config_file
[ $auto_rule -eq 1 -a $keep_rule -eq 1 ] && echo "--keep-rule" >> $config_file
[ -n "$seq_mode" ] && echo "--seq-mode ${seq_mode}" >> $config_file
[ -n "$lower_level" ] && echo "--lower-level ${lower_level}" >> $config_file
[ -n "$source_ip" ] && echo "--source-ip ${source_ip}" >> $config_file
[ -n "$source_port" ] && echo "--source-port ${source_port}" >> $config_file
echo "--retry-on-error" >> $config_file
[ -n "$log_level" ] && echo "--log-level ${log_level}" >> $config_file
echo "--disable-color" >> $config_file
}
validate_config_section() {
local ret=$(/sbin/validate_data "$NAME" general "$1" \
'server:uciname' \
'daemon_user:string:root' \
2> /dev/null)
[ $? -ne 0 ] && return 1
eval "$ret"
}
validate_server_section() {
local ret=$(/sbin/validate_data "$NAME" servers "$1" \
'server_addr:host' \
'server_port:port:8080' \
'listen_addr:ipaddr:127.0.0.1' \
'listen_port:port:2080' \
'raw_mode:or("faketcp", "udp", "icmp"):faketcp' \
'key:string' \
'cipher_mode:or("aes128cbc", "xor", "none"):aes128cbc' \
'auth_mode:or("md5", "crc32", "simple", "none"):md5' \
'auto_rule:bool:1' \
'keep_rule:bool:0' \
'seq_mode:range(0,4)' \
'lower_level:string' \
'source_ip:ipaddr' \
'source_port:port' \
'log_level:range(0,6)' \
2> /dev/null)
[ $? -ne 0 ] && return 1
eval "$ret"
}
start_instance() {
local server="$1"
if [ -z "$server" -o "$server" == "nil" ]; then
return 0
elif ! validate_server_section "$server"; then
_log "err" "Server config validation failed."
return 1
fi
/sbin/validate_data "ipaddr" "$server_addr" >/dev/null 2>&1
[ $? -ne 0 ] && server_addr=$(nslookup "$server_addr" | \
sed -n 's/^Address[[:space:]]*[0-9]*:[[:space:]]*\(\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}\)$/\1/p')
if [ -z "$server_addr" ]; then
_log "err" "Server address validation failed."
return 1
fi
[ -d /var/etc ] || mkdir -p /var/etc
local config_file="/var/etc/${NAME}.${server}.conf"
create_config "$config_file" || return 1
[ -d "/var/log/${NAME}" ] || mkdir -p "/var/log/${NAME}"
if [ $auto_rule -eq 1 -a $keep_rule -ne 1 ]; then
add_ipt_rule || { _log "err" "added iptables rule failed."; return 1; }
fi
/usr/bin/udp2raw --conf-file "$config_file" >> "/var/log/${NAME}/${NAME}.${server}.log" &
echo $! > "/var/run/${NAME}.${server}.pid"
return 0
}
start() {
pgrep "/usr/bin/${NAME}" >/dev/null 2>&1 && return
if ! validate_config_section "general" ; then
_log "err" "Config validate failed."
return 1
fi
has_valid_server $server || return 1
flush_ipt_rules
for srv in $server; do
start_instance $srv
done
export_ipt_rules
}
stop() {
local pids=$(pgrep "/usr/bin/${NAME}" 2> /dev/null)
[ $? -ne 0 ] && return
for pid in $pids; do
kill $pid >/dev/null 2>&1
done
flush_ipt_rules
return 0
}
restart() {
stop
sleep 1
start
}

View File

@ -0,0 +1,29 @@
#!/bin/sh
uci -q batch <<-EOF > /dev/null
delete ucitrack.@udp2raw[-1]
add ucitrack udp2raw
set ucitrack.@udp2raw[-1].init=udp2raw
commit ucitrack
delete firewall.udp2raw
set firewall.udp2raw=include
set firewall.udp2raw.type=script
set firewall.udp2raw.path=/var/etc/udp2raw.include
set firewall.udp2raw.reload=1
commit firewall
EOF
general=$(uci -q get udp2raw.@general[-1])
if [ -z "$general" ]; then
uci -q add udp2raw general
fi
if [ "$general"x != "general"x ]; then
uci -q batch <<-EOF > /dev/null
rename udp2raw.@general[-1]="general"
set udp2raw.@general[-1].server="nil"
commit udp2raw
EOF
fi
rm -rf /tmp/luci-indexcache /tmp/luci-modulecache
exit 0

View File

@ -0,0 +1,12 @@
INSTALL = install
PREFIX = /usr/bin
po2lmo: src/po2lmo.o src/template_lmo.o
$(CC) $(LDFLAGS) -o src/po2lmo src/po2lmo.o src/template_lmo.o
install:
$(INSTALL) -m 755 src/po2lmo $(PREFIX)
clean:
$(RM) src/po2lmo src/*.o

View File

@ -0,0 +1,247 @@
/*
* lmo - Lua Machine Objects - PO to LMO conversion tool
*
* Copyright (C) 2009-2012 Jo-Philipp Wich <xm@subsignal.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "template_lmo.h"
static void die(const char *msg)
{
fprintf(stderr, "Error: %s\n", msg);
exit(1);
}
static void usage(const char *name)
{
fprintf(stderr, "Usage: %s input.po output.lmo\n", name);
exit(1);
}
static void print(const void *ptr, size_t size, size_t nmemb, FILE *stream)
{
if( fwrite(ptr, size, nmemb, stream) == 0 )
die("Failed to write stdout");
}
static int extract_string(const char *src, char *dest, int len)
{
int pos = 0;
int esc = 0;
int off = -1;
for( pos = 0; (pos < strlen(src)) && (pos < len); pos++ )
{
if( (off == -1) && (src[pos] == '"') )
{
off = pos + 1;
}
else if( off >= 0 )
{
if( esc == 1 )
{
switch (src[pos])
{
case '"':
case '\\':
off++;
break;
}
dest[pos-off] = src[pos];
esc = 0;
}
else if( src[pos] == '\\' )
{
dest[pos-off] = src[pos];
esc = 1;
}
else if( src[pos] != '"' )
{
dest[pos-off] = src[pos];
}
else
{
dest[pos-off] = '\0';
break;
}
}
}
return (off > -1) ? strlen(dest) : -1;
}
static int cmp_index(const void *a, const void *b)
{
uint32_t x = ((const lmo_entry_t *)a)->key_id;
uint32_t y = ((const lmo_entry_t *)b)->key_id;
if (x < y)
return -1;
else if (x > y)
return 1;
return 0;
}
static void print_uint32(uint32_t x, FILE *out)
{
uint32_t y = htonl(x);
print(&y, sizeof(uint32_t), 1, out);
}
static void print_index(void *array, int n, FILE *out)
{
lmo_entry_t *e;
qsort(array, n, sizeof(*e), cmp_index);
for (e = array; n > 0; n--, e++)
{
print_uint32(e->key_id, out);
print_uint32(e->val_id, out);
print_uint32(e->offset, out);
print_uint32(e->length, out);
}
}
int main(int argc, char *argv[])
{
char line[4096];
char key[4096];
char val[4096];
char tmp[4096];
int state = 0;
int offset = 0;
int length = 0;
int n_entries = 0;
void *array = NULL;
lmo_entry_t *entry = NULL;
uint32_t key_id, val_id;
FILE *in;
FILE *out;
if( (argc != 3) || ((in = fopen(argv[1], "r")) == NULL) || ((out = fopen(argv[2], "w")) == NULL) )
usage(argv[0]);
memset(line, 0, sizeof(key));
memset(key, 0, sizeof(val));
memset(val, 0, sizeof(val));
while( (NULL != fgets(line, sizeof(line), in)) || (state >= 2 && feof(in)) )
{
if( state == 0 && strstr(line, "msgid \"") == line )
{
switch(extract_string(line, key, sizeof(key)))
{
case -1:
die("Syntax error in msgid");
case 0:
state = 1;
break;
default:
state = 2;
}
}
else if( state == 1 || state == 2 )
{
if( strstr(line, "msgstr \"") == line || state == 2 )
{
switch(extract_string(line, val, sizeof(val)))
{
case -1:
state = 4;
break;
default:
state = 3;
}
}
else
{
switch(extract_string(line, tmp, sizeof(tmp)))
{
case -1:
state = 2;
break;
default:
strcat(key, tmp);
}
}
}
else if( state == 3 )
{
switch(extract_string(line, tmp, sizeof(tmp)))
{
case -1:
state = 4;
break;
default:
strcat(val, tmp);
}
}
if( state == 4 )
{
if( strlen(key) > 0 && strlen(val) > 0 )
{
key_id = sfh_hash(key, strlen(key));
val_id = sfh_hash(val, strlen(val));
if( key_id != val_id )
{
n_entries++;
array = realloc(array, n_entries * sizeof(lmo_entry_t));
entry = (lmo_entry_t *)array + n_entries - 1;
if (!array)
die("Out of memory");
entry->key_id = key_id;
entry->val_id = val_id;
entry->offset = offset;
entry->length = strlen(val);
length = strlen(val) + ((4 - (strlen(val) % 4)) % 4);
print(val, length, 1, out);
offset += length;
}
}
state = 0;
memset(key, 0, sizeof(key));
memset(val, 0, sizeof(val));
}
memset(line, 0, sizeof(line));
}
print_index(array, n_entries, out);
if( offset > 0 )
{
print_uint32(offset, out);
fsync(fileno(out));
fclose(out);
}
else
{
fclose(out);
unlink(argv[2]);
}
fclose(in);
return(0);
}

View File

@ -0,0 +1,328 @@
/*
* lmo - Lua Machine Objects - Base functions
*
* Copyright (C) 2009-2010 Jo-Philipp Wich <xm@subsignal.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "template_lmo.h"
/*
* Hash function from http://www.azillionmonkeys.com/qed/hash.html
* Copyright (C) 2004-2008 by Paul Hsieh
*/
uint32_t sfh_hash(const char *data, int len)
{
uint32_t hash = len, tmp;
int rem;
if (len <= 0 || data == NULL) return 0;
rem = len & 3;
len >>= 2;
/* Main loop */
for (;len > 0; len--) {
hash += sfh_get16(data);
tmp = (sfh_get16(data+2) << 11) ^ hash;
hash = (hash << 16) ^ tmp;
data += 2*sizeof(uint16_t);
hash += hash >> 11;
}
/* Handle end cases */
switch (rem) {
case 3: hash += sfh_get16(data);
hash ^= hash << 16;
hash ^= data[sizeof(uint16_t)] << 18;
hash += hash >> 11;
break;
case 2: hash += sfh_get16(data);
hash ^= hash << 11;
hash += hash >> 17;
break;
case 1: hash += *data;
hash ^= hash << 10;
hash += hash >> 1;
}
/* Force "avalanching" of final 127 bits */
hash ^= hash << 3;
hash += hash >> 5;
hash ^= hash << 4;
hash += hash >> 17;
hash ^= hash << 25;
hash += hash >> 6;
return hash;
}
uint32_t lmo_canon_hash(const char *str, int len)
{
char res[4096];
char *ptr, prev;
int off;
if (!str || len >= sizeof(res))
return 0;
for (prev = ' ', ptr = res, off = 0; off < len; prev = *str, off++, str++)
{
if (isspace(*str))
{
if (!isspace(prev))
*ptr++ = ' ';
}
else
{
*ptr++ = *str;
}
}
if ((ptr > res) && isspace(*(ptr-1)))
ptr--;
return sfh_hash(res, ptr - res);
}
lmo_archive_t * lmo_open(const char *file)
{
int in = -1;
uint32_t idx_offset = 0;
struct stat s;
lmo_archive_t *ar = NULL;
if (stat(file, &s) == -1)
goto err;
if ((in = open(file, O_RDONLY)) == -1)
goto err;
if ((ar = (lmo_archive_t *)malloc(sizeof(*ar))) != NULL)
{
memset(ar, 0, sizeof(*ar));
ar->fd = in;
ar->size = s.st_size;
fcntl(ar->fd, F_SETFD, fcntl(ar->fd, F_GETFD) | FD_CLOEXEC);
if ((ar->mmap = mmap(NULL, ar->size, PROT_READ, MAP_SHARED, ar->fd, 0)) == MAP_FAILED)
goto err;
idx_offset = ntohl(*((const uint32_t *)
(ar->mmap + ar->size - sizeof(uint32_t))));
if (idx_offset >= ar->size)
goto err;
ar->index = (lmo_entry_t *)(ar->mmap + idx_offset);
ar->length = (ar->size - idx_offset - sizeof(uint32_t)) / sizeof(lmo_entry_t);
ar->end = ar->mmap + ar->size;
return ar;
}
err:
if (in > -1)
close(in);
if (ar != NULL)
{
if ((ar->mmap != NULL) && (ar->mmap != MAP_FAILED))
munmap(ar->mmap, ar->size);
free(ar);
}
return NULL;
}
void lmo_close(lmo_archive_t *ar)
{
if (ar != NULL)
{
if ((ar->mmap != NULL) && (ar->mmap != MAP_FAILED))
munmap(ar->mmap, ar->size);
close(ar->fd);
free(ar);
ar = NULL;
}
}
lmo_catalog_t *_lmo_catalogs = NULL;
lmo_catalog_t *_lmo_active_catalog = NULL;
int lmo_load_catalog(const char *lang, const char *dir)
{
DIR *dh = NULL;
char pattern[16];
char path[PATH_MAX];
struct dirent *de = NULL;
lmo_archive_t *ar = NULL;
lmo_catalog_t *cat = NULL;
if (!lmo_change_catalog(lang))
return 0;
if (!dir || !(dh = opendir(dir)))
goto err;
if (!(cat = malloc(sizeof(*cat))))
goto err;
memset(cat, 0, sizeof(*cat));
snprintf(cat->lang, sizeof(cat->lang), "%s", lang);
snprintf(pattern, sizeof(pattern), "*.%s.lmo", lang);
while ((de = readdir(dh)) != NULL)
{
if (!fnmatch(pattern, de->d_name, 0))
{
snprintf(path, sizeof(path), "%s/%s", dir, de->d_name);
ar = lmo_open(path);
if (ar)
{
ar->next = cat->archives;
cat->archives = ar;
}
}
}
closedir(dh);
cat->next = _lmo_catalogs;
_lmo_catalogs = cat;
if (!_lmo_active_catalog)
_lmo_active_catalog = cat;
return 0;
err:
if (dh) closedir(dh);
if (cat) free(cat);
return -1;
}
int lmo_change_catalog(const char *lang)
{
lmo_catalog_t *cat;
for (cat = _lmo_catalogs; cat; cat = cat->next)
{
if (!strncmp(cat->lang, lang, sizeof(cat->lang)))
{
_lmo_active_catalog = cat;
return 0;
}
}
return -1;
}
static lmo_entry_t * lmo_find_entry(lmo_archive_t *ar, uint32_t hash)
{
unsigned int m, l, r;
uint32_t k;
l = 0;
r = ar->length - 1;
while (1)
{
m = l + ((r - l) / 2);
if (r < l)
break;
k = ntohl(ar->index[m].key_id);
if (k == hash)
return &ar->index[m];
if (k > hash)
{
if (!m)
break;
r = m - 1;
}
else
{
l = m + 1;
}
}
return NULL;
}
int lmo_translate(const char *key, int keylen, char **out, int *outlen)
{
uint32_t hash;
lmo_entry_t *e;
lmo_archive_t *ar;
if (!key || !_lmo_active_catalog)
return -2;
hash = lmo_canon_hash(key, keylen);
for (ar = _lmo_active_catalog->archives; ar; ar = ar->next)
{
if ((e = lmo_find_entry(ar, hash)) != NULL)
{
*out = ar->mmap + ntohl(e->offset);
*outlen = ntohl(e->length);
return 0;
}
}
return -1;
}
void lmo_close_catalog(const char *lang)
{
lmo_archive_t *ar, *next;
lmo_catalog_t *cat, *prev;
for (prev = NULL, cat = _lmo_catalogs; cat; prev = cat, cat = cat->next)
{
if (!strncmp(cat->lang, lang, sizeof(cat->lang)))
{
if (prev)
prev->next = cat->next;
else
_lmo_catalogs = cat->next;
for (ar = cat->archives; ar; ar = next)
{
next = ar->next;
lmo_close(ar);
}
free(cat);
break;
}
}
}

View File

@ -0,0 +1,92 @@
/*
* lmo - Lua Machine Objects - General header
*
* Copyright (C) 2009-2012 Jo-Philipp Wich <xm@subsignal.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _TEMPLATE_LMO_H_
#define _TEMPLATE_LMO_H_
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <fnmatch.h>
#include <dirent.h>
#include <ctype.h>
#include <limits.h>
#if (defined(__GNUC__) && defined(__i386__))
#define sfh_get16(d) (*((const uint16_t *) (d)))
#else
#define sfh_get16(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\
+(uint32_t)(((const uint8_t *)(d))[0]) )
#endif
struct lmo_entry {
uint32_t key_id;
uint32_t val_id;
uint32_t offset;
uint32_t length;
} __attribute__((packed));
typedef struct lmo_entry lmo_entry_t;
struct lmo_archive {
int fd;
int length;
uint32_t size;
lmo_entry_t *index;
char *mmap;
char *end;
struct lmo_archive *next;
};
typedef struct lmo_archive lmo_archive_t;
struct lmo_catalog {
char lang[6];
struct lmo_archive *archives;
struct lmo_catalog *next;
};
typedef struct lmo_catalog lmo_catalog_t;
uint32_t sfh_hash(const char *data, int len);
uint32_t lmo_canon_hash(const char *data, int len);
lmo_archive_t * lmo_open(const char *file);
void lmo_close(lmo_archive_t *ar);
extern lmo_catalog_t *_lmo_catalogs;
extern lmo_catalog_t *_lmo_active_catalog;
int lmo_load_catalog(const char *lang, const char *dir);
int lmo_change_catalog(const char *lang);
int lmo_translate(const char *key, int keylen, char **out, int *outlen);
void lmo_close_catalog(const char *lang);
#endif