subscribe.lua 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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 v2_tj = luci.sys.exec('type -t -p trojan') ~= "" and "trojan" or "v2ray"
  27. local log = function(...)
  28. print(os.date("%Y-%m-%d %H:%M:%S ") .. table.concat({...}, " "))
  29. end
  30. -- 分割字符串
  31. local function split(full, sep)
  32. full = full:gsub("%z", "") -- 这里不是很清楚 有时候结尾带个\0
  33. local off, result = 1, {}
  34. while true do
  35. local nStart, nEnd = full:find(sep, off)
  36. if not nEnd then
  37. local res = ssub(full, off, slen(full))
  38. if #res > 0 then -- 过滤掉 \0
  39. tinsert(result, res)
  40. end
  41. break
  42. else
  43. tinsert(result, ssub(full, off, nStart - 1))
  44. off = nEnd + 1
  45. end
  46. end
  47. return result
  48. end
  49. -- urlencode
  50. local function get_urlencode(c)
  51. return sformat("%%%02X", sbyte(c))
  52. end
  53. local function urlEncode(szText)
  54. local str = szText:gsub("([^0-9a-zA-Z ])", get_urlencode)
  55. str = str:gsub(" ", "+")
  56. return str
  57. end
  58. local function get_urldecode(h)
  59. return schar(tonumber(h, 16))
  60. end
  61. local function UrlDecode(szText)
  62. return szText:gsub("+", " "):gsub("%%(%x%x)", get_urldecode)
  63. end
  64. -- trim
  65. local function trim(text)
  66. if not text or text == "" then
  67. return ""
  68. end
  69. return (sgsub(text, "^%s*(.-)%s*$", "%1"))
  70. end
  71. -- md5
  72. local function md5(content)
  73. local stdout = luci.sys.exec('echo \"' .. urlEncode(content) .. '\" | md5sum | cut -d \" \" -f1')
  74. -- assert(nixio.errno() == 0)
  75. return trim(stdout)
  76. end
  77. -- base64
  78. local function base64Decode(text)
  79. local raw = text
  80. if not text then
  81. return ''
  82. end
  83. text = text:gsub("%z", "")
  84. text = text:gsub("_", "/")
  85. text = text:gsub("-", "+")
  86. local mod4 = #text % 4
  87. text = text .. string.sub('====', mod4 + 1)
  88. local result = b64decode(text)
  89. if result then
  90. return result:gsub("%z", "")
  91. else
  92. return raw
  93. end
  94. end
  95. -- 处理数据
  96. local function processData(szType, content)
  97. local result = {type = szType, local_port = 1234, kcp_param = '--nocomp'}
  98. if szType == 'ssr' then
  99. local dat = split(content, "/%?")
  100. local hostInfo = split(dat[1], ':')
  101. result.server = hostInfo[1]
  102. result.server_port = hostInfo[2]
  103. result.protocol = hostInfo[3]
  104. result.encrypt_method = hostInfo[4]
  105. result.obfs = hostInfo[5]
  106. result.password = base64Decode(hostInfo[6])
  107. local params = {}
  108. for _, v in pairs(split(dat[2], '&')) do
  109. local t = split(v, '=')
  110. params[t[1]] = t[2]
  111. end
  112. result.obfs_param = base64Decode(params.obfsparam)
  113. result.protocol_param = base64Decode(params.protoparam)
  114. local group = base64Decode(params.group)
  115. if group then
  116. result.alias = "[" .. group .. "] "
  117. end
  118. result.alias = result.alias .. base64Decode(params.remarks)
  119. elseif szType == 'vmess' then
  120. local info = jsonParse(content)
  121. result.type = 'v2ray'
  122. result.v2ray_protocol = '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 = v2_tj
  233. result.v2ray_protocol = "trojan"
  234. result.server = host[1]
  235. -- 按照官方的建议 默认验证ssl证书
  236. result.insecure = "0"
  237. result.tls = "1"
  238. if host[2]:find("?") then
  239. local query = split(host[2], "?")
  240. result.server_port = query[1]
  241. local params = {}
  242. for _, v in pairs(split(query[2], '&')) do
  243. local t = split(v, '=')
  244. params[t[1]] = t[2]
  245. end
  246. if params.sni then
  247. -- 未指定peer(sni)默认使用remote addr
  248. result.tls_host = params.sni
  249. end
  250. else
  251. result.server_port = host[2]
  252. end
  253. result.password = password
  254. elseif szType == "vless" then
  255. local idx_sp = 0
  256. local alias = ""
  257. if content:find("#") then
  258. idx_sp = content:find("#")
  259. alias = content:sub(idx_sp + 1, -1)
  260. end
  261. local info = content:sub(1, idx_sp - 1)
  262. local hostInfo = split(info, "@")
  263. local host = split(hostInfo[2], ":")
  264. local uuid = hostInfo[1]
  265. if host[2]:find("?") then
  266. local query = split(host[2], "?")
  267. local params = {}
  268. for _, v in pairs(split(UrlDecode(query[2]), '&')) do
  269. local t = split(v, '=')
  270. params[t[1]] = t[2]
  271. end
  272. result.alias = UrlDecode(alias)
  273. result.type = 'v2ray'
  274. result.v2ray_protocol = 'vless'
  275. result.server = host[1]
  276. result.server_port = query[1]
  277. result.vmess_id = uuid
  278. result.vless_encryption = params.encryption or "none"
  279. result.transport = params.type and (params.type == 'http' and 'h2' or params.type) or "tcp"
  280. if not params.type or params.type == "tcp" then
  281. if params.security == "xtls" then
  282. result.xtls = "1"
  283. result.tls_host = params.sni or host[1]
  284. result.vless_flow = params.flow
  285. else
  286. result.xtls = "0"
  287. end
  288. end
  289. if params.type == 'ws' then
  290. result.ws_host = params.host
  291. result.ws_path = params.path or "/"
  292. end
  293. if params.type == 'http' then
  294. result.h2_host = params.host or host[1]
  295. result.h2_path = params.path or "/"
  296. end
  297. if params.type == 'kcp' then
  298. result.kcp_guise = params.headerType or "none"
  299. result.mtu = 1350
  300. result.tti = 50
  301. result.uplink_capacity = 5
  302. result.downlink_capacity = 20
  303. result.read_buffer_size = 2
  304. result.write_buffer_size = 2
  305. result.seed = params.seed
  306. end
  307. if params.type == 'quic' then
  308. result.quic_guise = params.headerType or "none"
  309. result.quic_key = params.key
  310. result.quic_security = params.quicSecurity or "none"
  311. end
  312. if params.security == "tls" then
  313. result.tls = "1"
  314. result.tls_host = params.sni or host[1]
  315. else
  316. result.tls = "0"
  317. end
  318. else
  319. result.server_port = host[2]
  320. end
  321. end
  322. if not result.alias then
  323. if result.server and result.server_port then
  324. result.alias = result.server .. ':' .. result.server_port
  325. else
  326. result.alias = "NULL"
  327. end
  328. end
  329. -- alias 不参与 hashkey 计算
  330. local alias = result.alias
  331. result.alias = nil
  332. local switch_enable = result.switch_enable
  333. result.switch_enable = nil
  334. result.hashkey = md5(jsonStringify(result))
  335. result.alias = alias
  336. result.switch_enable = switch_enable
  337. return result
  338. end
  339. -- wget
  340. local function wget(url)
  341. 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 .. '"')
  342. return trim(stdout)
  343. end
  344. local function check_filer(result)
  345. do
  346. local filter_word = split(filter_words, "/")
  347. for i, v in pairs(filter_word) do
  348. if result.alias:find(v) then
  349. -- log('订阅节点关键字过滤:“' .. v ..'” ,该节点被丢弃')
  350. return true
  351. end
  352. end
  353. end
  354. end
  355. local execute = function()
  356. -- exec
  357. do
  358. if proxy == '0' then -- 不使用代理更新的话先暂停
  359. log('服务正在暂停')
  360. luci.sys.init.stop(name)
  361. end
  362. for k, url in ipairs(subscribe_url) do
  363. local raw = wget(url)
  364. if #raw > 0 then
  365. local nodes, szType
  366. local groupHash = md5(url)
  367. cache[groupHash] = {}
  368. tinsert(nodeResult, {})
  369. local index = #nodeResult
  370. -- SSD 似乎是这种格式 ssd:// 开头的
  371. if raw:find('ssd://') then
  372. szType = 'ssd'
  373. local nEnd = select(2, raw:find('ssd://'))
  374. nodes = base64Decode(raw:sub(nEnd + 1, #raw))
  375. nodes = jsonParse(nodes)
  376. local extra = {airport = nodes.airport, port = nodes.port, encryption = nodes.encryption, password = nodes.password}
  377. local servers = {}
  378. -- SS里面包着 干脆直接这样
  379. for _, server in ipairs(nodes.servers) do
  380. tinsert(servers, setmetatable(server, {__index = extra}))
  381. end
  382. nodes = servers
  383. else
  384. -- ssd 外的格式
  385. nodes = split(base64Decode(raw):gsub(" ", "_"), "\n")
  386. end
  387. for _, v in ipairs(nodes) do
  388. if v then
  389. local result
  390. if szType == 'ssd' then
  391. result = processData(szType, v)
  392. elseif not szType then
  393. local node = trim(v)
  394. local dat = split(node, "://")
  395. if dat and dat[1] and dat[2] then
  396. local dat3 = ""
  397. if dat[3] then
  398. dat3 = "://" .. dat[3]
  399. end
  400. if dat[1] == 'ss' or dat[1] == 'trojan' then
  401. result = processData(dat[1], dat[2] .. dat3)
  402. else
  403. result = processData(dat[1], base64Decode(dat[2]))
  404. end
  405. end
  406. else
  407. log('跳过未知类型: ' .. szType)
  408. end
  409. -- log(result)
  410. if result then
  411. -- 中文做地址的 也没有人拿中文域名搞,就算中文域也有Puny Code SB 机场
  412. 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
  413. log('丢弃无效节点: ' .. result.type .. ' 节点, ' .. result.alias)
  414. else
  415. -- log('成功解析: ' .. result.type ..' 节点, ' .. result.alias)
  416. result.grouphashkey = groupHash
  417. tinsert(nodeResult[index], result)
  418. cache[groupHash][result.hashkey] = nodeResult[index][#nodeResult[index]]
  419. end
  420. end
  421. end
  422. end
  423. log('成功解析节点数量: ' .. #nodes)
  424. else
  425. log(url .. ': 获取内容为空')
  426. end
  427. end
  428. end
  429. -- diff
  430. do
  431. if next(nodeResult) == nil then
  432. log("更新失败,没有可用的节点信息")
  433. if proxy == '0' then
  434. luci.sys.init.start(name)
  435. log('订阅失败, 恢复服务')
  436. end
  437. return
  438. end
  439. local add, del = 0, 0
  440. ucic:foreach(name, uciType, function(old)
  441. if old.grouphashkey or old.hashkey then -- 没有 hash 的不参与删除
  442. if not nodeResult[old.grouphashkey] or not nodeResult[old.grouphashkey][old.hashkey] then
  443. ucic:delete(name, old['.name'])
  444. del = del + 1
  445. else
  446. local dat = nodeResult[old.grouphashkey][old.hashkey]
  447. ucic:tset(name, old['.name'], dat)
  448. -- 标记一下
  449. setmetatable(nodeResult[old.grouphashkey][old.hashkey], {__index = {_ignore = true}})
  450. end
  451. else
  452. if not old.alias then
  453. if old.server or old.server_port then
  454. old.alias = old.server .. ':' .. old.server_port
  455. log('忽略手动添加的节点: ' .. old.alias)
  456. else
  457. ucic:delete(name, old['.name'])
  458. end
  459. else
  460. log('忽略手动添加的节点: ' .. old.alias)
  461. end
  462. end
  463. end)
  464. for k, v in ipairs(nodeResult) do
  465. for kk, vv in ipairs(v) do
  466. if not vv._ignore then
  467. local section = ucic:add(name, uciType)
  468. ucic:tset(name, section, vv)
  469. ucic:set(name, section, "switch_enable", switch)
  470. add = add + 1
  471. end
  472. end
  473. end
  474. ucic:commit(name)
  475. -- 如果原有服务器节点已经不见了就尝试换为第一个节点
  476. local globalServer = ucic:get_first(name, 'global', 'global_server', '')
  477. if globalServer ~= "nil" then
  478. local firstServer = ucic:get_first(name, uciType)
  479. if firstServer then
  480. if not ucic:get(name, globalServer) then
  481. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  482. ucic:commit(name)
  483. ucic:set(name, ucic:get_first(name, 'global'), 'global_server', ucic:get_first(name, uciType))
  484. ucic:commit(name)
  485. log('当前主服务器节点已被删除,正在自动更换为第一个节点。')
  486. luci.sys.call("/etc/init.d/" .. name .. " start > /dev/null 2>&1 &")
  487. else
  488. log('维持当前主服务器节点。')
  489. luci.sys.call("/etc/init.d/" .. name .. " restart > /dev/null 2>&1 &")
  490. end
  491. else
  492. log('没有服务器节点了,停止服务')
  493. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  494. end
  495. end
  496. log('新增节点数量: ' .. add, '删除节点数量: ' .. del)
  497. log('订阅更新成功')
  498. end
  499. end
  500. if subscribe_url and #subscribe_url > 0 then
  501. xpcall(execute, function(e)
  502. log(e)
  503. log(debug.traceback())
  504. log('发生错误, 正在恢复服务')
  505. local firstServer = ucic:get_first(name, uciType)
  506. if firstServer then
  507. luci.sys.call("/etc/init.d/" .. name .. " restart > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  508. log('重启服务成功')
  509. else
  510. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  511. log('停止服务成功')
  512. end
  513. end)
  514. end