subscribe.lua 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. #!/usr/bin/lua
  2. ------------------------------------------------
  3. -- This file is part of the luci-app-ssr-plus subscribe.lua
  4. -- @author William Chan <[email protected]>
  5. ------------------------------------------------
  6. require "luci.model.uci"
  7. require "nixio"
  8. require "luci.util"
  9. require "luci.sys"
  10. require "luci.jsonc"
  11. -- these global functions are accessed all the time by the event handler
  12. -- so caching them is worth the effort
  13. local tinsert = table.insert
  14. local ssub, slen, schar, sbyte, sformat, sgsub = string.sub, string.len, string.char, string.byte, string.format, string.gsub
  15. local jsonParse, jsonStringify = luci.jsonc.parse, luci.jsonc.stringify
  16. local b64decode = nixio.bin.b64decode
  17. local cache = {}
  18. local nodeResult = setmetatable({}, {__index = cache}) -- update result
  19. local name = 'shadowsocksr'
  20. local uciType = 'servers'
  21. local ucic = luci.model.uci.cursor()
  22. local proxy = ucic:get_first(name, 'server_subscribe', 'proxy', '0')
  23. local switch = ucic:get_first(name, 'server_subscribe', 'switch', '1')
  24. local subscribe_url = ucic:get_first(name, 'server_subscribe', 'subscribe_url', {})
  25. local filter_words = ucic:get_first(name, 'server_subscribe', 'filter_words', '过期时间/剩余流量')
  26. local log = function(...)
  27. print(os.date("%Y-%m-%d %H:%M:%S ") .. table.concat({...}, " "))
  28. end
  29. -- 分割字符串
  30. local function split(full, sep)
  31. full = full:gsub("%z", "") -- 这里不是很清楚 有时候结尾带个\0
  32. local off, result = 1, {}
  33. while true do
  34. local nStart, nEnd = full:find(sep, off)
  35. if not nEnd then
  36. local res = ssub(full, off, slen(full))
  37. if #res > 0 then -- 过滤掉 \0
  38. tinsert(result, res)
  39. end
  40. break
  41. else
  42. tinsert(result, ssub(full, off, nStart - 1))
  43. off = nEnd + 1
  44. end
  45. end
  46. return result
  47. end
  48. -- urlencode
  49. local function get_urlencode(c)
  50. return sformat("%%%02X", sbyte(c))
  51. end
  52. local function urlEncode(szText)
  53. local str = szText:gsub("([^0-9a-zA-Z ])", get_urlencode)
  54. str = str:gsub(" ", "+")
  55. return str
  56. end
  57. local function get_urldecode(h)
  58. return schar(tonumber(h, 16))
  59. end
  60. local function UrlDecode(szText)
  61. return szText:gsub("+", " "):gsub("%%(%x%x)", get_urldecode)
  62. end
  63. -- trim
  64. local function trim(text)
  65. if not text or text == "" then
  66. return ""
  67. end
  68. return (sgsub(text, "^%s*(.-)%s*$", "%1"))
  69. end
  70. -- md5
  71. local function md5(content)
  72. local stdout = luci.sys.exec('echo \"' .. urlEncode(content) .. '\" | md5sum | cut -d \" \" -f1')
  73. -- assert(nixio.errno() == 0)
  74. return trim(stdout)
  75. end
  76. -- base64
  77. local function base64Decode(text)
  78. local raw = text
  79. if not text then
  80. return ''
  81. end
  82. text = text:gsub("%z", "")
  83. text = text:gsub("_", "/")
  84. text = text:gsub("-", "+")
  85. local mod4 = #text % 4
  86. text = text .. string.sub('====', mod4 + 1)
  87. local result = b64decode(text)
  88. if result then
  89. return result:gsub("%z", "")
  90. else
  91. return raw
  92. end
  93. end
  94. -- 处理数据
  95. local function processData(szType, content)
  96. local result = {type = szType, local_port = 1234, kcp_param = '--nocomp'}
  97. if szType == 'ssr' then
  98. local dat = split(content, "/%?")
  99. local hostInfo = split(dat[1], ':')
  100. result.server = hostInfo[1]
  101. result.server_port = hostInfo[2]
  102. result.protocol = hostInfo[3]
  103. result.encrypt_method = hostInfo[4]
  104. result.obfs = hostInfo[5]
  105. result.password = base64Decode(hostInfo[6])
  106. local params = {}
  107. for _, v in pairs(split(dat[2], '&')) do
  108. local t = split(v, '=')
  109. params[t[1]] = t[2]
  110. end
  111. result.obfs_param = base64Decode(params.obfsparam)
  112. result.protocol_param = base64Decode(params.protoparam)
  113. local group = base64Decode(params.group)
  114. if group then
  115. result.alias = "[" .. group .. "] "
  116. end
  117. result.alias = result.alias .. base64Decode(params.remarks)
  118. elseif szType == 'vmess' then
  119. local info = jsonParse(content)
  120. result.type = 'vmess'
  121. result.server = info.add
  122. result.server_port = info.port
  123. result.transport = info.net
  124. result.alter_id = info.aid
  125. result.vmess_id = info.id
  126. result.alias = info.ps
  127. -- result.mux = 1
  128. -- result.concurrency = 8
  129. if info.net == 'ws' then
  130. result.ws_host = info.host
  131. result.ws_path = info.path
  132. end
  133. if info.net == 'h2' then
  134. result.h2_host = info.host
  135. result.h2_path = info.path
  136. end
  137. if info.net == 'tcp' then
  138. if info.type and info.type ~= "http" then
  139. info.type = "none"
  140. end
  141. result.tcp_guise = info.type
  142. result.http_host = info.host
  143. result.http_path = info.path
  144. end
  145. if info.net == 'kcp' then
  146. result.kcp_guise = info.type
  147. result.mtu = 1350
  148. result.tti = 50
  149. result.uplink_capacity = 5
  150. result.downlink_capacity = 20
  151. result.read_buffer_size = 2
  152. result.write_buffer_size = 2
  153. end
  154. if info.net == 'quic' then
  155. result.quic_guise = info.type
  156. result.quic_key = info.key
  157. result.quic_security = info.securty
  158. end
  159. if info.security then
  160. result.security = info.security
  161. end
  162. if info.tls == "tls" or info.tls == "1" then
  163. result.tls = "1"
  164. result.tls_host = info.host
  165. result.insecure = 1
  166. else
  167. result.tls = "0"
  168. end
  169. elseif szType == "ss" then
  170. local idx_sp = 0
  171. local alias = ""
  172. if content:find("#") then
  173. idx_sp = content:find("#")
  174. alias = content:sub(idx_sp + 1, -1)
  175. end
  176. local info = content:sub(1, idx_sp - 1)
  177. local hostInfo = split(base64Decode(info), "@")
  178. local host = split(hostInfo[2], ":")
  179. local userinfo = base64Decode(hostInfo[1])
  180. local method = userinfo:sub(1, userinfo:find(":") - 1)
  181. local password = userinfo:sub(userinfo:find(":") + 1, #userinfo)
  182. result.alias = UrlDecode(alias)
  183. result.type = "ss"
  184. result.server = host[1]
  185. if host[2]:find("/%?") then
  186. local query = split(host[2], "/%?")
  187. result.server_port = query[1]
  188. local params = {}
  189. for _, v in pairs(split(query[2], '&')) do
  190. local t = split(v, '=')
  191. params[t[1]] = t[2]
  192. end
  193. if params.plugin then
  194. local plugin_info = UrlDecode(params.plugin)
  195. local idx_pn = plugin_info:find(";")
  196. if idx_pn then
  197. result.plugin = plugin_info:sub(1, idx_pn - 1)
  198. result.plugin_opts = plugin_info:sub(idx_pn + 1, #plugin_info)
  199. else
  200. result.plugin = plugin_info
  201. end
  202. end
  203. else
  204. result.server_port = host[2]
  205. end
  206. result.encrypt_method_ss = method
  207. result.password = password
  208. elseif szType == "ssd" then
  209. result.type = "ss"
  210. result.server = content.server
  211. result.server_port = content.port
  212. result.password = content.password
  213. result.encrypt_method_ss = content.encryption
  214. result.plugin = content.plugin
  215. result.plugin_opts = content.plugin_options
  216. result.alias = "[" .. content.airport .. "] " .. content.remarks
  217. elseif szType == "trojan" then
  218. local idx_sp = 0
  219. local alias = ""
  220. if content:find("#") then
  221. idx_sp = content:find("#")
  222. alias = content:sub(idx_sp + 1, -1)
  223. end
  224. local info = content:sub(1, idx_sp - 1)
  225. local hostInfo = split(info, "@")
  226. local host = split(hostInfo[2], ":")
  227. local userinfo = hostInfo[1]
  228. local password = userinfo
  229. result.alias = UrlDecode(alias)
  230. result.type = "trojan"
  231. result.server = host[1]
  232. -- 按照官方的建议 默认验证ssl证书
  233. result.insecure = "0"
  234. result.tls = "1"
  235. if host[2]:find("?") then
  236. local query = split(host[2], "?")
  237. result.server_port = query[1]
  238. local params = {}
  239. for _, v in pairs(split(query[2], '&')) do
  240. local t = split(v, '=')
  241. params[t[1]] = t[2]
  242. end
  243. if params.peer then
  244. -- 未指定peer(sni)默认使用remote addr
  245. result.tls_host = params.peer
  246. end
  247. if params.allowInsecure == "1" then
  248. result.insecure = "1"
  249. else
  250. result.insecure = "0"
  251. end
  252. else
  253. result.server_port = host[2]
  254. end
  255. result.password = password
  256. end
  257. if not result.alias then
  258. if result.server and result.server_port then
  259. result.alias = result.server .. ':' .. result.server_port
  260. else
  261. result.alias = "NULL"
  262. end
  263. end
  264. -- alias 不参与 hashkey 计算
  265. local alias = result.alias
  266. result.alias = nil
  267. local switch_enable = result.switch_enable
  268. result.switch_enable = nil
  269. result.hashkey = md5(jsonStringify(result))
  270. result.alias = alias
  271. result.switch_enable = switch_enable
  272. return result
  273. end
  274. -- wget
  275. local function wget(url)
  276. local stdout = luci.sys.exec('wget -q --user-agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36" --no-check-certificate -O- "' .. url .. '"')
  277. return trim(stdout)
  278. end
  279. local function check_filer(result)
  280. do
  281. local filter_word = split(filter_words, "/")
  282. for i, v in pairs(filter_word) do
  283. if result.alias:find(v) then
  284. -- log('订阅节点关键字过滤:“' .. v ..'” ,该节点被丢弃')
  285. return true
  286. end
  287. end
  288. end
  289. end
  290. local execute = function()
  291. -- exec
  292. do
  293. if proxy == '0' then -- 不使用代理更新的话先暂停
  294. log('服务正在暂停')
  295. luci.sys.init.stop(name)
  296. end
  297. for k, url in ipairs(subscribe_url) do
  298. local raw = wget(url)
  299. if #raw > 0 then
  300. local nodes, szType
  301. local groupHash = md5(url)
  302. cache[groupHash] = {}
  303. tinsert(nodeResult, {})
  304. local index = #nodeResult
  305. -- SSD 似乎是这种格式 ssd:// 开头的
  306. if raw:find('ssd://') then
  307. szType = 'ssd'
  308. local nEnd = select(2, raw:find('ssd://'))
  309. nodes = base64Decode(raw:sub(nEnd + 1, #raw))
  310. nodes = jsonParse(nodes)
  311. local extra = {airport = nodes.airport, port = nodes.port, encryption = nodes.encryption, password = nodes.password}
  312. local servers = {}
  313. -- SS里面包着 干脆直接这样
  314. for _, server in ipairs(nodes.servers) do
  315. tinsert(servers, setmetatable(server, {__index = extra}))
  316. end
  317. nodes = servers
  318. else
  319. -- ssd 外的格式
  320. nodes = split(base64Decode(raw):gsub(" ", "_"), "\n")
  321. end
  322. for _, v in ipairs(nodes) do
  323. if v then
  324. local result
  325. if szType == 'ssd' then
  326. result = processData(szType, v)
  327. elseif not szType then
  328. local node = trim(v)
  329. local dat = split(node, "://")
  330. if dat and dat[1] and dat[2] then
  331. local dat3 = ""
  332. if dat[3] then
  333. dat3 = "://" .. dat[3]
  334. end
  335. if dat[1] == 'ss' or dat[1] == 'trojan' then
  336. result = processData(dat[1], dat[2] .. dat3)
  337. else
  338. result = processData(dat[1], base64Decode(dat[2]))
  339. end
  340. end
  341. else
  342. log('跳过未知类型: ' .. szType)
  343. end
  344. -- log(result)
  345. if result then
  346. -- 中文做地址的 也没有人拿中文域名搞,就算中文域也有Puny Code SB 机场
  347. if not result.server or not result.server_port or result.alias == "NULL" or check_filer(result) or result.server:match("[^0-9a-zA-Z%-%.%s]") then
  348. log('丢弃无效节点: ' .. result.type .. ' 节点, ' .. result.alias)
  349. else
  350. -- log('成功解析: ' .. result.type ..' 节点, ' .. result.alias)
  351. result.grouphashkey = groupHash
  352. tinsert(nodeResult[index], result)
  353. cache[groupHash][result.hashkey] = nodeResult[index][#nodeResult[index]]
  354. end
  355. end
  356. end
  357. end
  358. log('成功解析节点数量: ' .. #nodes)
  359. else
  360. log(url .. ': 获取内容为空')
  361. end
  362. end
  363. end
  364. -- diff
  365. do
  366. if next(nodeResult) == nil then
  367. log("更新失败,没有可用的节点信息")
  368. if proxy == '0' then
  369. luci.sys.init.start(name)
  370. log('订阅失败, 恢复服务')
  371. end
  372. return
  373. end
  374. local add, del = 0, 0
  375. ucic:foreach(name, uciType, function(old)
  376. if old.grouphashkey or old.hashkey then -- 没有 hash 的不参与删除
  377. if not nodeResult[old.grouphashkey] or not nodeResult[old.grouphashkey][old.hashkey] then
  378. ucic:delete(name, old['.name'])
  379. del = del + 1
  380. else
  381. local dat = nodeResult[old.grouphashkey][old.hashkey]
  382. ucic:tset(name, old['.name'], dat)
  383. -- 标记一下
  384. setmetatable(nodeResult[old.grouphashkey][old.hashkey], {__index = {_ignore = true}})
  385. end
  386. else
  387. if not old.alias then
  388. old.alias = old.server .. ':' .. old.server_port
  389. end
  390. log('忽略手动添加的节点: ' .. old.alias)
  391. end
  392. end)
  393. for k, v in ipairs(nodeResult) do
  394. for kk, vv in ipairs(v) do
  395. if not vv._ignore then
  396. local section = ucic:add(name, uciType)
  397. ucic:tset(name, section, vv)
  398. ucic:set(name, section, "switch_enable", switch)
  399. add = add + 1
  400. end
  401. end
  402. end
  403. ucic:commit(name)
  404. -- 如果原有服务器节点已经不见了就尝试换为第一个节点
  405. local globalServer = ucic:get_first(name, 'global', 'global_server', '')
  406. if globalServer ~= "nil" then
  407. local firstServer = ucic:get_first(name, uciType)
  408. if firstServer then
  409. if not ucic:get(name, globalServer) then
  410. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  411. ucic:commit(name)
  412. ucic:set(name, ucic:get_first(name, 'global'), 'global_server', ucic:get_first(name, uciType))
  413. ucic:commit(name)
  414. log('当前主服务器节点已被删除,正在自动更换为第一个节点。')
  415. luci.sys.call("/etc/init.d/" .. name .. " start > /dev/null 2>&1 &")
  416. else
  417. log('维持当前主服务器节点。')
  418. luci.sys.call("/etc/init.d/" .. name .. " restart > /dev/null 2>&1 &")
  419. end
  420. else
  421. log('没有服务器节点了,停止服务')
  422. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  423. end
  424. end
  425. log('新增节点数量: ' .. add, '删除节点数量: ' .. del)
  426. log('订阅更新成功')
  427. end
  428. end
  429. if subscribe_url and #subscribe_url > 0 then
  430. xpcall(execute, function(e)
  431. log(e)
  432. log(debug.traceback())
  433. log('发生错误, 正在恢复服务')
  434. local firstServer = ucic:get_first(name, uciType)
  435. if firstServer then
  436. luci.sys.call("/etc/init.d/" .. name .. " restart > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  437. log('重启服务成功')
  438. else
  439. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  440. log('停止服务成功')
  441. end
  442. end)
  443. end