subscribe.lua 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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 return '' end
  80. text = text:gsub("%z", "")
  81. text = text:gsub("_", "/")
  82. text = text:gsub("-", "+")
  83. local mod4 = #text % 4
  84. text = text .. string.sub('====', mod4 + 1)
  85. local result = b64decode(text)
  86. if result then
  87. return result:gsub("%z", "")
  88. else
  89. return raw
  90. end
  91. end
  92. -- 处理数据
  93. local function processData(szType, content)
  94. local result = {
  95. type = szType,
  96. local_port = 1234,
  97. kcp_param = '--nocomp'
  98. }
  99. if szType == 'ssr' then
  100. local dat = split(content, "/%?")
  101. local hostInfo = split(dat[1], ':')
  102. result.server = hostInfo[1]
  103. result.server_port = hostInfo[2]
  104. result.protocol = hostInfo[3]
  105. result.encrypt_method = hostInfo[4]
  106. result.obfs = hostInfo[5]
  107. result.password = base64Decode(hostInfo[6])
  108. local params = {}
  109. for _, v in pairs(split(dat[2], '&')) do
  110. local t = split(v, '=')
  111. params[t[1]] = t[2]
  112. end
  113. result.obfs_param = base64Decode(params.obfsparam)
  114. result.protocol_param = base64Decode(params.protoparam)
  115. local group = base64Decode(params.group)
  116. if group then
  117. result.alias = "[" .. group .. "] "
  118. end
  119. result.alias = result.alias .. base64Decode(params.remarks)
  120. elseif szType == 'vmess' then
  121. local info = jsonParse(content)
  122. result.type = 'vmess'
  123. result.server = info.add
  124. result.server_port = info.port
  125. result.transport = info.net
  126. result.alter_id = info.aid
  127. result.vmess_id = info.id
  128. result.alias = info.ps
  129. -- result.mux = 1
  130. -- result.concurrency = 8
  131. if info.net == 'ws' then
  132. result.ws_host = info.host
  133. result.ws_path = info.path
  134. end
  135. if info.net == 'h2' then
  136. result.h2_host = info.host
  137. result.h2_path = info.path
  138. end
  139. if info.net == 'tcp' then
  140. if info.type and info.type ~= "http" then
  141. info.type = "none"
  142. end
  143. result.tcp_guise = info.type
  144. result.http_host = info.host
  145. result.http_path = info.path
  146. end
  147. if info.net == 'kcp' then
  148. result.kcp_guise = info.type
  149. result.mtu = 1350
  150. result.tti = 50
  151. result.uplink_capacity = 5
  152. result.downlink_capacity = 20
  153. result.read_buffer_size = 2
  154. result.write_buffer_size = 2
  155. end
  156. if info.net == 'quic' then
  157. result.quic_guise = info.type
  158. result.quic_key = info.key
  159. result.quic_security = info.securty
  160. end
  161. if info.security then
  162. result.security = info.security
  163. end
  164. if info.tls == "tls" or info.tls == "1" then
  165. result.tls = "1"
  166. result.tls_host = info.host
  167. result.insecure = 1
  168. else
  169. result.tls = "0"
  170. end
  171. elseif szType == "ss" then
  172. local idx_sp = 0
  173. local alias = ""
  174. if content:find("#") then
  175. idx_sp = content:find("#")
  176. alias = content:sub(idx_sp + 1, -1)
  177. end
  178. local info = content:sub(1, idx_sp - 1)
  179. local hostInfo = split(base64Decode(info), "@")
  180. local host = split(hostInfo[2], ":")
  181. local userinfo = base64Decode(hostInfo[1])
  182. local method = userinfo:sub(1, userinfo:find(":") - 1)
  183. local password = userinfo:sub(userinfo:find(":") + 1, #userinfo)
  184. result.alias = UrlDecode(alias)
  185. result.type = "ss"
  186. result.server = host[1]
  187. if host[2]:find("/%?") then
  188. local query = split(host[2], "/%?")
  189. result.server_port = query[1]
  190. local params = {}
  191. for _, v in pairs(split(query[2], '&')) do
  192. local t = split(v, '=')
  193. params[t[1]] = t[2]
  194. end
  195. if params.plugin then
  196. local plugin_info = UrlDecode(params.plugin)
  197. local idx_pn = plugin_info:find(";")
  198. if idx_pn then
  199. result.plugin = plugin_info:sub(1, idx_pn - 1)
  200. result.plugin_opts = plugin_info:sub(idx_pn + 1, #plugin_info)
  201. else
  202. result.plugin = plugin_info
  203. end
  204. end
  205. else
  206. result.server_port = host[2]
  207. end
  208. result.encrypt_method_ss = method
  209. result.password = password
  210. elseif szType == "ssd" then
  211. result.type = "ss"
  212. result.server = content.server
  213. result.server_port = content.port
  214. result.password = content.password
  215. result.encrypt_method_ss = content.encryption
  216. result.plugin = content.plugin
  217. result.plugin_opts = content.plugin_options
  218. result.alias = "[" .. content.airport .. "] " .. content.remarks
  219. elseif szType == "trojan" then
  220. local idx_sp = 0
  221. local alias = ""
  222. if content:find("#") then
  223. idx_sp = content:find("#")
  224. alias = content:sub(idx_sp + 1, -1)
  225. end
  226. local info = content:sub(1, idx_sp - 1)
  227. local hostInfo = split(info, "@")
  228. local host = split(hostInfo[2], ":")
  229. local userinfo = hostInfo[1]
  230. local password = userinfo
  231. result.alias = UrlDecode(alias)
  232. result.type = "trojan"
  233. result.server = host[1]
  234. -- 按照官方的建议 默认验证ssl证书
  235. result.insecure = "0"
  236. result.tls = "1"
  237. if host[2]:find("?") then
  238. local query = split(host[2], "?")
  239. result.server_port = query[1]
  240. local params = {}
  241. for _, v in pairs(split(query[2], '&')) do
  242. local t = split(v, '=')
  243. params[t[1]] = t[2]
  244. end
  245. if params.peer then
  246. -- 未指定peer(sni)默认使用remote addr
  247. result.tls_host = params.peer
  248. end
  249. if params.allowInsecure == "1" then
  250. result.insecure = "1"
  251. else
  252. result.insecure = "0"
  253. end
  254. else
  255. result.server_port = host[2]
  256. end
  257. result.password = password
  258. end
  259. if not result.alias then
  260. if result.server and result.server_port then
  261. result.alias = result.server .. ':' .. result.server_port
  262. else
  263. result.alias = "NULL"
  264. end
  265. end
  266. -- alias 不参与 hashkey 计算
  267. local alias = result.alias
  268. result.alias = nil
  269. local switch_enable = result.switch_enable
  270. result.switch_enable = nil
  271. result.hashkey = md5(jsonStringify(result))
  272. result.alias = alias
  273. result.switch_enable = switch_enable
  274. return result
  275. end
  276. -- wget
  277. local function wget(url)
  278. 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 -t 3 -T 10 -O- "' .. url .. '"')
  279. return trim(stdout)
  280. end
  281. local function check_filer(result)
  282. do
  283. local filter_word = split(filter_words, "/")
  284. for i, v in pairs(filter_word) do
  285. if result.alias:find(v) then
  286. -- log('订阅节点关键字过滤:“' .. v ..'” ,该节点被丢弃')
  287. return true
  288. end
  289. end
  290. end
  291. end
  292. local execute = function()
  293. -- exec
  294. do
  295. if proxy == '0' then -- 不使用代理更新的话先暂停
  296. log('服务正在暂停')
  297. luci.sys.init.stop(name)
  298. end
  299. for k, url in ipairs(subscribe_url) do
  300. local raw = wget(url)
  301. if #raw > 0 then
  302. local nodes, szType
  303. local groupHash = md5(url)
  304. cache[groupHash] = {}
  305. tinsert(nodeResult, {})
  306. local index = #nodeResult
  307. -- SSD 似乎是这种格式 ssd:// 开头的
  308. if raw:find('ssd://') then
  309. szType = 'ssd'
  310. local nEnd = select(2, raw:find('ssd://'))
  311. nodes = base64Decode(raw:sub(nEnd + 1, #raw))
  312. nodes = jsonParse(nodes)
  313. local extra = {
  314. airport = nodes.airport,
  315. port = nodes.port,
  316. encryption = nodes.encryption,
  317. password = nodes.password
  318. }
  319. local servers = {}
  320. -- SS里面包着 干脆直接这样
  321. for _, server in ipairs(nodes.servers) do
  322. tinsert(servers, setmetatable(server, { __index = extra }))
  323. end
  324. nodes = servers
  325. else
  326. -- ssd 外的格式
  327. nodes = split(base64Decode(raw):gsub(" ", "_"), "\n")
  328. end
  329. for _, v in ipairs(nodes) do
  330. if v then
  331. local result
  332. if szType == 'ssd' then
  333. result = processData(szType, v)
  334. elseif not szType then
  335. local node = trim(v)
  336. local dat = split(node, "://")
  337. if dat and dat[1] and dat[2] then
  338. local dat3 = ""
  339. if dat[3] then
  340. dat3 = "://" .. dat[3]
  341. end
  342. if dat[1] == 'ss' or dat[1] == 'trojan' then
  343. result = processData(dat[1], dat[2] .. dat3)
  344. else
  345. result = processData(dat[1], base64Decode(dat[2]))
  346. end
  347. end
  348. else
  349. log('跳过未知类型: ' .. szType)
  350. end
  351. -- log(result)
  352. if result then
  353. if
  354. not result.server or
  355. not result.server_port or
  356. result.alias == "NULL" or
  357. check_filer(result) or
  358. result.server:match("[^0-9a-zA-Z%-%.%s]") -- 中文做地址的 也没有人拿中文域名搞,就算中文域也有Puny Code SB 机场
  359. then
  360. log('丢弃无效节点: ' .. result.type ..' 节点, ' .. result.alias)
  361. else
  362. -- log('成功解析: ' .. result.type ..' 节点, ' .. result.alias)
  363. result.grouphashkey = groupHash
  364. tinsert(nodeResult[index], result)
  365. cache[groupHash][result.hashkey] = nodeResult[index][#nodeResult[index]]
  366. end
  367. end
  368. end
  369. end
  370. log('成功解析节点数量: ' ..#nodes)
  371. else
  372. log(url .. ': 获取内容为空')
  373. end
  374. end
  375. end
  376. -- diff
  377. do
  378. if next(nodeResult) == nil then
  379. log("更新失败,没有可用的节点信息")
  380. if proxy == '0' then
  381. luci.sys.init.start(name)
  382. log('订阅失败, 恢复服务')
  383. end
  384. return
  385. end
  386. local add, del = 0, 0
  387. ucic:foreach(name, uciType, function(old)
  388. if old.grouphashkey or old.hashkey then -- 没有 hash 的不参与删除
  389. if not nodeResult[old.grouphashkey] or not nodeResult[old.grouphashkey][old.hashkey] then
  390. ucic:delete(name, old['.name'])
  391. del = del + 1
  392. else
  393. local dat = nodeResult[old.grouphashkey][old.hashkey]
  394. ucic:tset(name, old['.name'], dat)
  395. -- 标记一下
  396. setmetatable(nodeResult[old.grouphashkey][old.hashkey], { __index = { _ignore = true } })
  397. end
  398. else
  399. if not old.alias then
  400. old.alias = old.server .. ':' .. old.server_port
  401. end
  402. log('忽略手动添加的节点: ' .. old.alias)
  403. end
  404. end)
  405. for k, v in ipairs(nodeResult) do
  406. for kk, vv in ipairs(v) do
  407. if not vv._ignore then
  408. local section = ucic:add(name, uciType)
  409. ucic:tset(name, section, vv)
  410. ucic:set(name, section, "switch_enable", switch)
  411. add = add + 1
  412. end
  413. end
  414. end
  415. ucic:commit(name)
  416. -- 如果原有服务器节点已经不见了就尝试换为第一个节点
  417. local globalServer = ucic:get_first(name, 'global', 'global_server', '')
  418. if globalServer ~= "nil" then
  419. local firstServer = ucic:get_first(name, uciType)
  420. if firstServer then
  421. if not ucic:get(name, globalServer) then
  422. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  423. ucic:commit(name)
  424. ucic:set(name, ucic:get_first(name, 'global'), 'global_server', ucic:get_first(name, uciType))
  425. ucic:commit(name)
  426. log('当前主服务器节点已被删除,正在自动更换为第一个节点。')
  427. luci.sys.call("/etc/init.d/" .. name .. " start > /dev/null 2>&1 &")
  428. else
  429. log('维持当前主服务器节点。')
  430. luci.sys.call("/etc/init.d/" .. name .." restart > /dev/null 2>&1 &")
  431. end
  432. else
  433. log('没有服务器节点了,停止服务')
  434. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  435. end
  436. end
  437. log('新增节点数量: ' ..add, '删除节点数量: ' .. del)
  438. log('订阅更新成功')
  439. end
  440. end
  441. if subscribe_url and #subscribe_url > 0 then
  442. xpcall(execute, function(e)
  443. log(e)
  444. log(debug.traceback())
  445. log('发生错误, 正在恢复服务')
  446. local firstServer = ucic:get_first(name, uciType)
  447. if firstServer then
  448. luci.sys.call("/etc/init.d/" .. name .." restart > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  449. log('重启服务成功')
  450. else
  451. luci.sys.call("/etc/init.d/" .. name .." stop > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  452. log('停止服务成功')
  453. end
  454. end)
  455. end