subscribe.lua 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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_ss = luci.sys.exec('type -t -p ss-redir sslocal') ~= "" and "ss" or "v2ray"
  27. local v2_tj = luci.sys.exec('type -t -p trojan') ~= "" and "trojan" or "v2ray"
  28. local log = function(...)
  29. print(os.date("%Y-%m-%d %H:%M:%S ") .. table.concat({...}, " "))
  30. end
  31. local encrypt_methods_ss = {
  32. -- aead
  33. "aes-128-gcm",
  34. "aes-192-gcm",
  35. "aes-256-gcm",
  36. "chacha20-ietf-poly1305",
  37. "xchacha20-ietf-poly1305"
  38. --[[ stream
  39. "table",
  40. "rc4",
  41. "rc4-md5",
  42. "aes-128-cfb",
  43. "aes-192-cfb",
  44. "aes-256-cfb",
  45. "aes-128-ctr",
  46. "aes-192-ctr",
  47. "aes-256-ctr",
  48. "bf-cfb",
  49. "camellia-128-cfb",
  50. "camellia-192-cfb",
  51. "camellia-256-cfb",
  52. "salsa20",
  53. "chacha20",
  54. "chacha20-ietf" ]]
  55. }
  56. -- 分割字符串
  57. local function split(full, sep)
  58. full = full:gsub("%z", "") -- 这里不是很清楚 有时候结尾带个\0
  59. local off, result = 1, {}
  60. while true do
  61. local nStart, nEnd = full:find(sep, off)
  62. if not nEnd then
  63. local res = ssub(full, off, slen(full))
  64. if #res > 0 then -- 过滤掉 \0
  65. tinsert(result, res)
  66. end
  67. break
  68. else
  69. tinsert(result, ssub(full, off, nStart - 1))
  70. off = nEnd + 1
  71. end
  72. end
  73. return result
  74. end
  75. -- urlencode
  76. local function get_urlencode(c)
  77. return sformat("%%%02X", sbyte(c))
  78. end
  79. local function urlEncode(szText)
  80. local str = szText:gsub("([^0-9a-zA-Z ])", get_urlencode)
  81. str = str:gsub(" ", "+")
  82. return str
  83. end
  84. local function get_urldecode(h)
  85. return schar(tonumber(h, 16))
  86. end
  87. local function UrlDecode(szText)
  88. return szText:gsub("+", " "):gsub("%%(%x%x)", get_urldecode)
  89. end
  90. -- trim
  91. local function trim(text)
  92. if not text or text == "" then
  93. return ""
  94. end
  95. return (sgsub(text, "^%s*(.-)%s*$", "%1"))
  96. end
  97. -- md5
  98. local function md5(content)
  99. local stdout = luci.sys.exec('echo \"' .. urlEncode(content) .. '\" | md5sum | cut -d \" \" -f1')
  100. -- assert(nixio.errno() == 0)
  101. return trim(stdout)
  102. end
  103. -- base64
  104. local function base64Decode(text)
  105. local raw = text
  106. if not text then
  107. return ''
  108. end
  109. text = text:gsub("%z", "")
  110. text = text:gsub("_", "/")
  111. text = text:gsub("-", "+")
  112. local mod4 = #text % 4
  113. text = text .. string.sub('====', mod4 + 1)
  114. local result = b64decode(text)
  115. if result then
  116. return result:gsub("%z", "")
  117. else
  118. return raw
  119. end
  120. end
  121. -- 检查数组(table)中是否存在某个字符值
  122. -- https://www.04007.cn/article/135.html
  123. local function checkTabValue(tab)
  124. local revtab = {}
  125. for k,v in pairs(tab) do
  126. revtab[v] = true
  127. end
  128. return revtab
  129. end
  130. -- 处理数据
  131. local function processData(szType, content)
  132. local result = {type = szType, local_port = 1234, kcp_param = '--nocomp'}
  133. if szType == 'ssr' then
  134. local dat = split(content, "/%?")
  135. local hostInfo = split(dat[1], ':')
  136. result.server = hostInfo[1]
  137. result.server_port = hostInfo[2]
  138. result.protocol = hostInfo[3]
  139. result.encrypt_method = hostInfo[4]
  140. result.obfs = hostInfo[5]
  141. result.password = base64Decode(hostInfo[6])
  142. local params = {}
  143. for _, v in pairs(split(dat[2], '&')) do
  144. local t = split(v, '=')
  145. params[t[1]] = t[2]
  146. end
  147. result.obfs_param = base64Decode(params.obfsparam)
  148. result.protocol_param = base64Decode(params.protoparam)
  149. local group = base64Decode(params.group)
  150. if group then
  151. result.alias = "[" .. group .. "] "
  152. end
  153. result.alias = result.alias .. base64Decode(params.remarks)
  154. elseif szType == 'vmess' then
  155. local info = jsonParse(content)
  156. result.type = 'v2ray'
  157. result.v2ray_protocol = 'vmess'
  158. result.server = info.add
  159. result.server_port = info.port
  160. result.transport = info.net
  161. result.alter_id = info.aid
  162. result.vmess_id = info.id
  163. result.alias = info.ps
  164. -- result.mux = 1
  165. -- result.concurrency = 8
  166. if info.net == 'ws' then
  167. result.ws_host = info.host
  168. result.ws_path = info.path
  169. end
  170. if info.net == 'h2' then
  171. result.h2_host = info.host
  172. result.h2_path = info.path
  173. end
  174. if info.net == 'tcp' then
  175. if info.type and info.type ~= "http" then
  176. info.type = "none"
  177. end
  178. result.tcp_guise = info.type
  179. result.http_host = info.host
  180. result.http_path = info.path
  181. end
  182. if info.net == 'kcp' then
  183. result.kcp_guise = info.type
  184. result.mtu = 1350
  185. result.tti = 50
  186. result.uplink_capacity = 5
  187. result.downlink_capacity = 20
  188. result.read_buffer_size = 2
  189. result.write_buffer_size = 2
  190. end
  191. if info.net == 'quic' then
  192. result.quic_guise = info.type
  193. result.quic_key = info.key
  194. result.quic_security = info.securty
  195. end
  196. if info.security then
  197. result.security = info.security
  198. end
  199. if info.tls == "tls" or info.tls == "1" then
  200. result.tls = "1"
  201. result.tls_host = info.host
  202. result.insecure = 1
  203. else
  204. result.tls = "0"
  205. end
  206. elseif szType == "ss" then
  207. local idx_sp = 0
  208. local alias = ""
  209. if content:find("#") then
  210. idx_sp = content:find("#")
  211. alias = content:sub(idx_sp + 1, -1)
  212. end
  213. local info = content:sub(1, idx_sp - 1)
  214. local hostInfo = split(base64Decode(info), "@")
  215. local host = split(hostInfo[2], ":")
  216. local userinfo = base64Decode(hostInfo[1])
  217. local method = userinfo:sub(1, userinfo:find(":") - 1)
  218. local password = userinfo:sub(userinfo:find(":") + 1, #userinfo)
  219. result.alias = UrlDecode(alias)
  220. result.type = v2_ss
  221. result.v2ray_protocol = "shadowsocks"
  222. result.server = host[1]
  223. if host[2]:find("/%?") then
  224. local query = split(host[2], "/%?")
  225. result.server_port = query[1]
  226. local params = {}
  227. for _, v in pairs(split(query[2], '&')) do
  228. local t = split(v, '=')
  229. params[t[1]] = t[2]
  230. end
  231. if params.plugin then
  232. local plugin_info = UrlDecode(params.plugin)
  233. local idx_pn = plugin_info:find(";")
  234. if idx_pn then
  235. result.plugin = plugin_info:sub(1, idx_pn - 1)
  236. result.plugin_opts = plugin_info:sub(idx_pn + 1, #plugin_info)
  237. else
  238. result.plugin = plugin_info
  239. end
  240. -- 部分机场下发的插件名为 simple-obfs,这里应该改为 obfs-local
  241. if result.plugin == "simple-obfs" then
  242. result.plugin = "obfs-local"
  243. end
  244. end
  245. else
  246. result.server_port = host[2]
  247. end
  248. if checkTabValue(encrypt_methods_ss)[method] then
  249. result.encrypt_method_ss = method
  250. result.password = password
  251. else
  252. -- 1202 年了还不支持 SS AEAD 的屑机场
  253. result.server = nil
  254. end
  255. elseif szType == "ssd" then
  256. result.type = v2_ss
  257. result.v2ray_protocol = "shadowsocks"
  258. result.server = content.server
  259. result.server_port = content.port
  260. result.password = content.password
  261. result.encrypt_method_ss = content.encryption
  262. result.plugin = content.plugin
  263. result.plugin_opts = content.plugin_options
  264. result.alias = "[" .. content.airport .. "] " .. content.remarks
  265. if checkTabValue(encrypt_methods_ss)[result.encrypt_method_ss] then
  266. result.server = nil
  267. elseif result.plugin == "simple-obfs" then
  268. result.plugin = "obfs-local"
  269. end
  270. elseif szType == "trojan" then
  271. local idx_sp = 0
  272. local alias = ""
  273. if content:find("#") then
  274. idx_sp = content:find("#")
  275. alias = content:sub(idx_sp + 1, -1)
  276. end
  277. local info = content:sub(1, idx_sp - 1)
  278. local hostInfo = split(info, "@")
  279. local host = split(hostInfo[2], ":")
  280. local userinfo = hostInfo[1]
  281. local password = userinfo
  282. result.alias = UrlDecode(alias)
  283. result.type = v2_tj
  284. result.v2ray_protocol = "trojan"
  285. result.server = host[1]
  286. -- 按照官方的建议 默认验证ssl证书
  287. result.insecure = "0"
  288. result.tls = "1"
  289. if host[2]:find("?") then
  290. local query = split(host[2], "?")
  291. result.server_port = query[1]
  292. local params = {}
  293. for _, v in pairs(split(query[2], '&')) do
  294. local t = split(v, '=')
  295. params[t[1]] = t[2]
  296. end
  297. if params.sni then
  298. -- 未指定peer(sni)默认使用remote addr
  299. result.tls_host = params.sni
  300. end
  301. else
  302. result.server_port = host[2]
  303. end
  304. result.password = password
  305. elseif szType == "vless" then
  306. local idx_sp = 0
  307. local alias = ""
  308. if content:find("#") then
  309. idx_sp = content:find("#")
  310. alias = content:sub(idx_sp + 1, -1)
  311. end
  312. local info = content:sub(1, idx_sp - 1)
  313. local hostInfo = split(info, "@")
  314. local host = split(hostInfo[2], ":")
  315. local uuid = hostInfo[1]
  316. if host[2]:find("?") then
  317. local query = split(host[2], "?")
  318. local params = {}
  319. for _, v in pairs(split(UrlDecode(query[2]), '&')) do
  320. local t = split(v, '=')
  321. params[t[1]] = t[2]
  322. end
  323. result.alias = UrlDecode(alias)
  324. result.type = 'v2ray'
  325. result.v2ray_protocol = 'vless'
  326. result.server = host[1]
  327. result.server_port = query[1]
  328. result.vmess_id = uuid
  329. result.vless_encryption = params.encryption or "none"
  330. result.transport = params.type and (params.type == 'http' and 'h2' or params.type) or "tcp"
  331. if not params.type or params.type == "tcp" then
  332. if params.security == "xtls" then
  333. result.xtls = "1"
  334. result.tls_host = params.sni
  335. result.vless_flow = params.flow
  336. else
  337. result.xtls = "0"
  338. end
  339. end
  340. if params.type == 'ws' then
  341. result.ws_host = params.host
  342. result.ws_path = params.path or "/"
  343. end
  344. if params.type == 'http' then
  345. result.h2_host = params.host
  346. result.h2_path = params.path or "/"
  347. end
  348. if params.type == 'kcp' then
  349. result.kcp_guise = params.headerType or "none"
  350. result.mtu = 1350
  351. result.tti = 50
  352. result.uplink_capacity = 5
  353. result.downlink_capacity = 20
  354. result.read_buffer_size = 2
  355. result.write_buffer_size = 2
  356. result.seed = params.seed
  357. end
  358. if params.type == 'quic' then
  359. result.quic_guise = params.headerType or "none"
  360. result.quic_key = params.key
  361. result.quic_security = params.quicSecurity or "none"
  362. end
  363. if params.type == 'grpc' then
  364. result.serviceName = params.serviceName
  365. end
  366. if params.security == "tls" then
  367. result.tls = "1"
  368. result.tls_host = params.sni
  369. else
  370. result.tls = "0"
  371. end
  372. else
  373. result.server_port = host[2]
  374. end
  375. end
  376. if not result.alias then
  377. if result.server and result.server_port then
  378. result.alias = result.server .. ':' .. result.server_port
  379. else
  380. result.alias = "NULL"
  381. end
  382. end
  383. -- alias 不参与 hashkey 计算
  384. local alias = result.alias
  385. result.alias = nil
  386. local switch_enable = result.switch_enable
  387. result.switch_enable = nil
  388. result.hashkey = md5(jsonStringify(result))
  389. result.alias = alias
  390. result.switch_enable = switch_enable
  391. return result
  392. end
  393. -- wget
  394. local function wget(url)
  395. local stdout = luci.sys.exec('uclient-fetch -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 .. '"')
  396. return trim(stdout)
  397. end
  398. local function check_filer(result)
  399. do
  400. local filter_word = split(filter_words, "/")
  401. for i, v in pairs(filter_word) do
  402. if result.alias:find(v) then
  403. -- log('订阅节点关键字过滤:“' .. v ..'” ,该节点被丢弃')
  404. return true
  405. end
  406. end
  407. end
  408. end
  409. local execute = function()
  410. -- exec
  411. do
  412. if proxy == '0' then -- 不使用代理更新的话先暂停
  413. log('服务正在暂停')
  414. luci.sys.init.stop(name)
  415. end
  416. for k, url in ipairs(subscribe_url) do
  417. local raw = wget(url)
  418. if #raw > 0 then
  419. local nodes, szType
  420. local groupHash = md5(url)
  421. cache[groupHash] = {}
  422. tinsert(nodeResult, {})
  423. local index = #nodeResult
  424. -- SSD 似乎是这种格式 ssd:// 开头的
  425. if raw:find('ssd://') then
  426. szType = 'ssd'
  427. local nEnd = select(2, raw:find('ssd://'))
  428. nodes = base64Decode(raw:sub(nEnd + 1, #raw))
  429. nodes = jsonParse(nodes)
  430. local extra = {airport = nodes.airport, port = nodes.port, encryption = nodes.encryption, password = nodes.password}
  431. local servers = {}
  432. -- SS里面包着 干脆直接这样
  433. for _, server in ipairs(nodes.servers) do
  434. tinsert(servers, setmetatable(server, {__index = extra}))
  435. end
  436. nodes = servers
  437. else
  438. -- ssd 外的格式
  439. nodes = split(base64Decode(raw):gsub(" ", "_"), "\n")
  440. end
  441. for _, v in ipairs(nodes) do
  442. if v then
  443. local result
  444. if szType == 'ssd' then
  445. result = processData(szType, v)
  446. elseif not szType then
  447. local node = trim(v)
  448. local dat = split(node, "://")
  449. if dat and dat[1] and dat[2] then
  450. local dat3 = ""
  451. if dat[3] then
  452. dat3 = "://" .. dat[3]
  453. end
  454. if dat[1] == 'ss' or dat[1] == 'trojan' then
  455. result = processData(dat[1], dat[2] .. dat3)
  456. else
  457. result = processData(dat[1], base64Decode(dat[2]))
  458. end
  459. end
  460. else
  461. log('跳过未知类型: ' .. szType)
  462. end
  463. -- log(result)
  464. if result then
  465. -- 中文做地址的 也没有人拿中文域名搞,就算中文域也有Puny Code SB 机场
  466. 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]") or cache[groupHash][result.hashkey] then
  467. log('丢弃无效节点: ' .. result.type .. ' 节点, ' .. result.alias)
  468. else
  469. -- log('成功解析: ' .. result.type ..' 节点, ' .. result.alias)
  470. result.grouphashkey = groupHash
  471. tinsert(nodeResult[index], result)
  472. cache[groupHash][result.hashkey] = nodeResult[index][#nodeResult[index]]
  473. end
  474. end
  475. end
  476. end
  477. log('成功解析节点数量: ' .. #nodes)
  478. else
  479. log(url .. ': 获取内容为空')
  480. end
  481. end
  482. end
  483. -- diff
  484. do
  485. if next(nodeResult) == nil then
  486. log("更新失败,没有可用的节点信息")
  487. if proxy == '0' then
  488. luci.sys.init.start(name)
  489. log('订阅失败, 恢复服务')
  490. end
  491. return
  492. end
  493. local add, del = 0, 0
  494. ucic:foreach(name, uciType, function(old)
  495. if old.grouphashkey or old.hashkey then -- 没有 hash 的不参与删除
  496. if not nodeResult[old.grouphashkey] or not nodeResult[old.grouphashkey][old.hashkey] then
  497. ucic:delete(name, old['.name'])
  498. del = del + 1
  499. else
  500. local dat = nodeResult[old.grouphashkey][old.hashkey]
  501. ucic:tset(name, old['.name'], dat)
  502. -- 标记一下
  503. setmetatable(nodeResult[old.grouphashkey][old.hashkey], {__index = {_ignore = true}})
  504. end
  505. else
  506. if not old.alias then
  507. if old.server or old.server_port then
  508. old.alias = old.server .. ':' .. old.server_port
  509. log('忽略手动添加的节点: ' .. old.alias)
  510. else
  511. ucic:delete(name, old['.name'])
  512. end
  513. else
  514. log('忽略手动添加的节点: ' .. old.alias)
  515. end
  516. end
  517. end)
  518. for k, v in ipairs(nodeResult) do
  519. for kk, vv in ipairs(v) do
  520. if not vv._ignore then
  521. local section = ucic:add(name, uciType)
  522. ucic:tset(name, section, vv)
  523. ucic:set(name, section, "switch_enable", switch)
  524. add = add + 1
  525. end
  526. end
  527. end
  528. ucic:commit(name)
  529. -- 如果原有服务器节点已经不见了就尝试换为第一个节点
  530. local globalServer = ucic:get_first(name, 'global', 'global_server', '')
  531. if globalServer ~= "nil" then
  532. local firstServer = ucic:get_first(name, uciType)
  533. if firstServer then
  534. if not ucic:get(name, globalServer) then
  535. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  536. ucic:commit(name)
  537. ucic:set(name, ucic:get_first(name, 'global'), 'global_server', ucic:get_first(name, uciType))
  538. ucic:commit(name)
  539. log('当前主服务器节点已被删除,正在自动更换为第一个节点。')
  540. luci.sys.call("/etc/init.d/" .. name .. " start > /dev/null 2>&1 &")
  541. else
  542. log('维持当前主服务器节点。')
  543. luci.sys.call("/etc/init.d/" .. name .. " restart > /dev/null 2>&1 &")
  544. end
  545. else
  546. log('没有服务器节点了,停止服务')
  547. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  548. end
  549. end
  550. log('新增节点数量: ' .. add, '删除节点数量: ' .. del)
  551. log('订阅更新成功')
  552. end
  553. end
  554. if subscribe_url and #subscribe_url > 0 then
  555. xpcall(execute, function(e)
  556. log(e)
  557. log(debug.traceback())
  558. log('发生错误, 正在恢复服务')
  559. local firstServer = ucic:get_first(name, uciType)
  560. if firstServer then
  561. luci.sys.call("/etc/init.d/" .. name .. " restart > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  562. log('重启服务成功')
  563. else
  564. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  565. log('停止服务成功')
  566. end
  567. end)
  568. end