subscribe.lua 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  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. require "luci.model.ipkg"
  12. -- these global functions are accessed all the time by the event handler
  13. -- so caching them is worth the effort
  14. local tinsert = table.insert
  15. local ssub, slen, schar, sbyte, sformat, sgsub = string.sub, string.len, string.char, string.byte, string.format, string.gsub
  16. local jsonParse, jsonStringify = luci.jsonc.parse, luci.jsonc.stringify
  17. local b64decode = nixio.bin.b64decode
  18. local URL = require "url"
  19. local cache = {}
  20. local nodeResult = setmetatable({}, {__index = cache}) -- update result
  21. local name = 'shadowsocksr'
  22. local uciType = 'servers'
  23. local ucic = require "luci.model.uci".cursor()
  24. local proxy = ucic:get_first(name, 'server_subscribe', 'proxy', '0')
  25. local switch = ucic:get_first(name, 'server_subscribe', 'switch', '1')
  26. local allow_insecure = ucic:get_first(name, 'server_subscribe', 'allow_insecure', '0')
  27. local subscribe_url = ucic:get_first(name, 'server_subscribe', 'subscribe_url', {})
  28. local filter_words = ucic:get_first(name, 'server_subscribe', 'filter_words', '过期时间/剩余流量')
  29. local save_words = ucic:get_first(name, 'server_subscribe', 'save_words', '')
  30. -- 读取 ss_type 设置
  31. local ss_type = ucic:get_first(name, 'server_subscribe', 'ss_type')
  32. -- 根据 ss_type 选择对应的程序
  33. local ss_program = ""
  34. if ss_type == "ss-rust" then
  35. ss_program = "sslocal" -- Rust 版本使用 sslocal
  36. elseif ss_type == "ss-libev" then
  37. ss_program = "ss-redir" -- Libev 版本使用 ss-redir
  38. end
  39. local v2_ss = luci.sys.exec('type -t -p ' .. ss_program .. ' 2>/dev/null') ~= "" and "ss" or "v2ray"
  40. local has_ss_type = luci.sys.exec('type -t -p ' .. ss_program .. ' 2>/dev/null') ~= "" and ss_type
  41. local v2_tj = luci.sys.exec('type -t -p trojan') ~= "" and "trojan" or "v2ray"
  42. local log = function(...)
  43. print(os.date("%Y-%m-%d %H:%M:%S ") .. table.concat({...}, " "))
  44. end
  45. local encrypt_methods_ss = {
  46. -- plain
  47. "none",
  48. "plain",
  49. -- aead
  50. "aes-128-gcm",
  51. "aes-192-gcm",
  52. "aes-256-gcm",
  53. "chacha20-ietf-poly1305",
  54. "xchacha20-ietf-poly1305",
  55. -- aead 2022
  56. "2022-blake3-aes-128-gcm",
  57. "2022-blake3-aes-256-gcm",
  58. "2022-blake3-chacha20-poly1305"
  59. --[[ stream
  60. "table",
  61. "rc4",
  62. "rc4-md5",
  63. "aes-128-cfb",
  64. "aes-192-cfb",
  65. "aes-256-cfb",
  66. "aes-128-ctr",
  67. "aes-192-ctr",
  68. "aes-256-ctr",
  69. "bf-cfb",
  70. "camellia-128-cfb",
  71. "camellia-192-cfb",
  72. "camellia-256-cfb",
  73. "salsa20",
  74. "chacha20",
  75. "chacha20-ietf" ]]
  76. }
  77. -- 分割字符串
  78. local function split(full, sep)
  79. full = full:gsub("%z", "") -- 这里不是很清楚 有时候结尾带个\0
  80. local off, result = 1, {}
  81. while true do
  82. local nStart, nEnd = full:find(sep, off)
  83. if not nEnd then
  84. local res = ssub(full, off, slen(full))
  85. if #res > 0 then -- 过滤掉 \0
  86. tinsert(result, res)
  87. end
  88. break
  89. else
  90. tinsert(result, ssub(full, off, nStart - 1))
  91. off = nEnd + 1
  92. end
  93. end
  94. return result
  95. end
  96. -- urlencode
  97. local function get_urlencode(c)
  98. return sformat("%%%02X", sbyte(c))
  99. end
  100. local function urlEncode(szText)
  101. local str = szText:gsub("([^0-9a-zA-Z ])", get_urlencode)
  102. str = str:gsub(" ", "+")
  103. return str
  104. end
  105. local function get_urldecode(h)
  106. return schar(tonumber(h, 16))
  107. end
  108. local function UrlDecode(szText)
  109. return szText:gsub("+", " "):gsub("%%(%x%x)", get_urldecode)
  110. end
  111. -- trim
  112. local function trim(text)
  113. if not text or text == "" then
  114. return ""
  115. end
  116. return (sgsub(text, "^%s*(.-)%s*$", "%1"))
  117. end
  118. -- md5
  119. local function md5(content)
  120. local stdout = luci.sys.exec('echo \"' .. urlEncode(content) .. '\" | md5sum | cut -d \" \" -f1')
  121. -- assert(nixio.errno() == 0)
  122. return trim(stdout)
  123. end
  124. -- base64
  125. local function base64Decode(text)
  126. local raw = text
  127. if not text then
  128. return ''
  129. end
  130. text = text:gsub("%z", "")
  131. text = text:gsub("_", "/")
  132. text = text:gsub("-", "+")
  133. local mod4 = #text % 4
  134. text = text .. string.sub('====', mod4 + 1)
  135. local result = b64decode(text)
  136. if result then
  137. return result:gsub("%z", "")
  138. else
  139. return raw
  140. end
  141. end
  142. -- 检查数组(table)中是否存在某个字符值
  143. -- https://www.04007.cn/article/135.html
  144. local function checkTabValue(tab)
  145. local revtab = {}
  146. for k,v in pairs(tab) do
  147. revtab[v] = true
  148. end
  149. return revtab
  150. end
  151. -- 处理数据
  152. local function processData(szType, content)
  153. local result = {type = szType, local_port = 1234, kcp_param = '--nocomp'}
  154. if szType == 'ssr' then
  155. local dat = split(content, "/%?")
  156. local hostInfo = split(dat[1], ':')
  157. result.type = 'ssr'
  158. result.server = hostInfo[1]
  159. result.server_port = hostInfo[2]
  160. result.protocol = hostInfo[3]
  161. result.encrypt_method = hostInfo[4]
  162. result.obfs = hostInfo[5]
  163. result.password = base64Decode(hostInfo[6])
  164. local params = {}
  165. for _, v in pairs(split(dat[2], '&')) do
  166. local t = split(v, '=')
  167. params[t[1]] = t[2]
  168. end
  169. result.obfs_param = base64Decode(params.obfsparam)
  170. result.protocol_param = base64Decode(params.protoparam)
  171. local group = base64Decode(params.group)
  172. if group then
  173. result.alias = "[" .. group .. "] "
  174. end
  175. result.alias = result.alias .. base64Decode(params.remarks)
  176. elseif szType == 'vmess' then
  177. local info = jsonParse(content)
  178. result.type = 'v2ray'
  179. result.v2ray_protocol = 'vmess'
  180. result.server = info.add
  181. result.server_port = info.port
  182. if info.net == "tcp" then
  183. info.net = "raw"
  184. end
  185. result.transport = info.net
  186. result.alter_id = info.aid
  187. result.vmess_id = info.id
  188. result.alias = info.ps
  189. -- result.mux = 1
  190. -- result.concurrency = 8
  191. if info.net == 'ws' then
  192. result.ws_host = info.host
  193. result.ws_path = info.path
  194. end
  195. if info.net == 'httpupgrade' then
  196. result.httpupgrade_host = info.host
  197. result.httpupgrade_path = info.path
  198. end
  199. if info.net == 'splithttp' then
  200. result.splithttp_host = info.host
  201. result.splithttp_path = info.path
  202. end
  203. if info.net == 'xhttp' then
  204. result.xhttp_mode = info.mode
  205. result.xhttp_host = info.host
  206. result.xhttp_path = info.path
  207. -- 检查 extra 参数是否存在且非空
  208. result.enable_xhttp_extra = (info.extra and info.extra ~= "") and "1" or nil
  209. result.xhttp_extra = (info.extra and info.extra ~= "") and info.extra or nil
  210. -- 尝试解析 JSON 数据
  211. local success, Data = pcall(jsonParse, info.extra)
  212. if success and Data then
  213. local address = (Data.extra and Data.extra.downloadSettings and Data.extra.downloadSettings.address)
  214. or (Data.downloadSettings and Data.downloadSettings.address)
  215. result.download_address = address and address ~= "" and address or nil
  216. else
  217. -- 如果解析失败,清空下载地址
  218. result.download_address = nil
  219. end
  220. end
  221. if info.net == 'h2' then
  222. result.h2_host = info.host
  223. result.h2_path = info.path
  224. end
  225. if info.net == 'raw' or info.net == 'tcp' then
  226. if info.type and info.type ~= "http" then
  227. info.type = "none"
  228. end
  229. result.tcp_guise = info.type
  230. result.http_host = info.host
  231. result.http_path = info.path
  232. end
  233. if info.net == 'kcp' then
  234. result.kcp_guise = info.type
  235. result.mtu = 1350
  236. result.tti = 50
  237. result.uplink_capacity = 5
  238. result.downlink_capacity = 20
  239. result.read_buffer_size = 2
  240. result.write_buffer_size = 2
  241. end
  242. if info.net == 'grpc' then
  243. if info.path then
  244. result.serviceName = info.path
  245. elseif info.serviceName then
  246. result.serviceName = info.serviceName
  247. end
  248. end
  249. if info.net == 'quic' then
  250. result.quic_guise = info.type
  251. result.quic_key = info.key
  252. result.quic_security = info.securty
  253. end
  254. if info.security then
  255. result.security = info.security
  256. end
  257. if info.tls == "tls" or info.tls == "1" then
  258. result.tls = "1"
  259. if info.alpn and info.alpn ~= "" then
  260. result.xhttp_alpn = info.alpn
  261. end
  262. if info.sni and info.sni ~= "" then
  263. result.tls_host = info.sni
  264. elseif info.host then
  265. result.tls_host = info.host
  266. end
  267. result.insecure = allow_insecure
  268. else
  269. result.tls = "0"
  270. end
  271. elseif szType == "ss" then
  272. local idx_sp = 0
  273. local alias = ""
  274. if content:find("#") then
  275. idx_sp = content:find("#")
  276. alias = content:sub(idx_sp + 1, -1)
  277. end
  278. local info = content:sub(1, idx_sp - 1)
  279. local hostInfo = split(base64Decode(info), "@")
  280. local host = split(hostInfo[2], ":")
  281. local userinfo = base64Decode(hostInfo[1])
  282. local method = userinfo:sub(1, userinfo:find(":") - 1)
  283. local password = userinfo:sub(userinfo:find(":") + 1, #userinfo)
  284. result.alias = UrlDecode(alias)
  285. result.type = v2_ss
  286. result.v2ray_protocol = (v2_ss == "v2ray") and "shadowsocks" or nil
  287. result.has_ss_type = has_ss_type
  288. result.encrypt_method_ss = method
  289. result.password = password
  290. result.server = host[1]
  291. if host[2]:find("/%?") then
  292. local query = split(host[2], "/%?")
  293. result.server_port = query[1]
  294. local params = {}
  295. for _, v in pairs(split(query[2], '&')) do
  296. local t = split(v, '=')
  297. params[t[1]] = t[2]
  298. end
  299. if params.plugin then
  300. local plugin_info = UrlDecode(params.plugin)
  301. local idx_pn = plugin_info:find(";")
  302. if idx_pn then
  303. result.plugin = plugin_info:sub(1, idx_pn - 1)
  304. result.plugin_opts = plugin_info:sub(idx_pn + 1, #plugin_info)
  305. else
  306. result.plugin = plugin_info
  307. end
  308. -- 部分机场下发的插件名为 simple-obfs,这里应该改为 obfs-local
  309. if result.plugin == "simple-obfs" then
  310. result.plugin = "obfs-local"
  311. end
  312. -- 如果插件不為 none,確保 enable_plugin 為 1
  313. if result.plugin ~= "none" and result.plugin ~= "" then
  314. result.enable_plugin = 1
  315. end
  316. end
  317. else
  318. result.server_port = host[2]:gsub("/","")
  319. end
  320. if not checkTabValue(encrypt_methods_ss)[method] then
  321. -- 1202 年了还不支持 SS AEAD 的屑机场
  322. result.server = nil
  323. end
  324. elseif szType == "sip008" then
  325. result.type = v2_ss
  326. result.v2ray_protocol = (v2_ss == "v2ray") and "shadowsocks" or nil
  327. result.server = content.server
  328. result.server_port = content.server_port
  329. result.password = content.password
  330. result.encrypt_method_ss = content.method
  331. result.plugin = content.plugin
  332. result.plugin_opts = content.plugin_opts
  333. result.alias = content.remarks
  334. if not checkTabValue(encrypt_methods_ss)[content.method] then
  335. result.server = nil
  336. end
  337. elseif szType == "ssd" then
  338. result.type = v2_ss
  339. result.v2ray_protocol = (v2_ss == "v2ray") and "shadowsocks" or nil
  340. result.server = content.server
  341. result.server_port = content.port
  342. result.password = content.password
  343. result.encrypt_method_ss = content.method
  344. result.plugin_opts = content.plugin_options
  345. result.alias = "[" .. content.airport .. "] " .. content.remarks
  346. if content.plugin == "simple-obfs" then
  347. result.plugin = "obfs-local"
  348. else
  349. result.plugin = content.plugin
  350. end
  351. if not checkTabValue(encrypt_methods_ss)[content.encryption] then
  352. result.server = nil
  353. end
  354. elseif szType == "trojan" then
  355. local params = {}
  356. local idx_sp = 0
  357. local alias = ""
  358. if content:find("#") then
  359. idx_sp = content:find("#")
  360. alias = content:sub(idx_sp + 1, -1)
  361. end
  362. local info = content:sub(1, idx_sp - 1)
  363. local hostInfo = split(info, "@")
  364. local userinfo = hostInfo[1]
  365. local password = userinfo
  366. -- 分离服务器地址和端口
  367. local host = split(hostInfo[2], ":")
  368. local server = host[1]
  369. local port = host[2]
  370. result.alias = UrlDecode(alias)
  371. result.type = v2_tj
  372. result.v2ray_protocol = "trojan"
  373. result.server = server
  374. result.password = password
  375. -- 按照官方的建议 默认验证ssl证书
  376. result.insecure = "0"
  377. result.tls = "1"
  378. if port:find("?") then
  379. local query = split(port, "?")
  380. result.server_port = query[1]
  381. for _, v in pairs(split(query[2], '&')) do
  382. local t = split(v, '=')
  383. params[t[1]] = t[2]
  384. end
  385. if params.alpn then
  386. -- 处理 alpn 参数
  387. result.xhttp_alpn = params.alpn
  388. end
  389. if params.sni then
  390. -- 未指定peer(sni)默认使用remote addr
  391. result.tls_host = params.sni
  392. end
  393. if params.allowInsecure then
  394. -- 处理 insecure 参数
  395. result.insecure = params.allowInsecure
  396. end
  397. else
  398. result.server_port = port
  399. end
  400. if v2_tj ~= "trojan" then
  401. if params.fp then
  402. -- 处理 fingerprint 参数
  403. result.fingerprint = params.fp
  404. end
  405. -- 处理传输协议
  406. result.transport = params.type or "tcp" -- 默认传输协议为 tcp
  407. if result.transport == "tcp" then
  408. result.transport = "raw"
  409. end
  410. if result.transport == "ws" then
  411. result.ws_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  412. result.ws_path = params.path and UrlDecode(params.path) or "/"
  413. elseif result.transport == "httpupgrade" then
  414. result.httpupgrade_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  415. result.httpupgrade_path = params.path and UrlDecode(params.path) or "/"
  416. elseif result.transport == "splithttp" then
  417. result.splithttp_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  418. result.splithttp_path = params.path and UrlDecode(params.path) or "/"
  419. elseif result.transport == "xhttp" then
  420. result.xhttp_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  421. result.xhttp_mode = params.mode or "auto"
  422. result.xhttp_path = params.path and UrlDecode(params.path) or "/"
  423. -- 检查 extra 参数是否存在且非空
  424. result.enable_xhttp_extra = (params.extra and params.extra ~= "") and "1" or nil
  425. result.xhttp_extra = (params.extra and params.extra ~= "") and params.extra or nil
  426. -- 尝试解析 JSON 数据
  427. local success, Data = pcall(jsonParse, params.extra)
  428. if success and Data then
  429. local address = (Data.extra and Data.extra.downloadSettings and Data.extra.downloadSettings.address)
  430. or (Data.downloadSettings and Data.downloadSettings.address)
  431. result.download_address = address and address ~= "" and address or nil
  432. else
  433. -- 如果解析失败,清空下载地址
  434. result.download_address = nil
  435. end
  436. elseif result.transport == "http" or result.transport == "h2" then
  437. result.transport = "h2"
  438. result.h2_host = params.host and UrlDecode(params.host) or nil
  439. result.h2_path = params.path and UrlDecode(params.path) or nil
  440. elseif result.transport == "kcp" then
  441. result.kcp_guise = params.headerType or "none"
  442. result.seed = params.seed
  443. result.mtu = 1350
  444. result.tti = 50
  445. result.uplink_capacity = 5
  446. result.downlink_capacity = 20
  447. result.read_buffer_size = 2
  448. result.write_buffer_size = 2
  449. elseif result.transport == "quic" then
  450. result.quic_guise = params.headerType or "none"
  451. result.quic_security = params.quicSecurity or "none"
  452. result.quic_key = params.key
  453. elseif result.transport == "grpc" then
  454. result.serviceName = params.serviceName
  455. result.grpc_mode = params.mode or "gun"
  456. elseif result.transport == "tcp" or result.transport == "raw" then
  457. result.tcp_guise = params.headerType and params.headerType ~= "" and params.headerType or "none"
  458. if result.tcp_guise == "http" then
  459. result.tcp_host = params.host and UrlDecode(params.host) or nil
  460. result.tcp_path = params.path and UrlDecode(params.path) or nil
  461. end
  462. end
  463. end
  464. elseif szType == "vless" then
  465. local url = URL.parse("http://" .. content)
  466. local params = url.query
  467. result.alias = url.fragment and UrlDecode(url.fragment) or nil
  468. result.type = "v2ray"
  469. result.v2ray_protocol = "vless"
  470. result.server = url.host
  471. result.server_port = url.port
  472. result.vmess_id = url.user
  473. result.vless_encryption = params.encryption or "none"
  474. result.transport = params.type or "tcp"
  475. result.tls = (params.security == "tls" or params.security == "xtls") and "1" or "0"
  476. result.xhttp_alpn = params.alpn or ""
  477. result.tls_host = params.sni
  478. result.tls_flow = (params.security == "tls" or params.security == "reality") and params.flow or nil
  479. result.fingerprint = params.fp
  480. result.reality = (params.security == "reality") and "1" or "0"
  481. result.reality_publickey = params.pbk and UrlDecode(params.pbk) or nil
  482. result.reality_shortid = params.sid
  483. result.reality_spiderx = params.spx and UrlDecode(params.spx) or nil
  484. if result.transport == "ws" then
  485. result.ws_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  486. result.ws_path = params.path and UrlDecode(params.path) or "/"
  487. elseif result.transport == "httpupgrade" then
  488. result.httpupgrade_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  489. result.httpupgrade_path = params.path and UrlDecode(params.path) or "/"
  490. elseif result.transport == "splithttp" then
  491. result.splithttp_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  492. result.splithttp_path = params.path and UrlDecode(params.path) or "/"
  493. elseif result.transport == "xhttp" then
  494. result.xhttp_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  495. result.xhttp_mode = params.mode or "auto"
  496. result.xhttp_path = params.path and UrlDecode(params.path) or "/"
  497. -- 检查 extra 参数是否存在且非空
  498. result.enable_xhttp_extra = (params.extra and params.extra ~= "") and "1" or nil
  499. result.xhttp_extra = (params.extra and params.extra ~= "") and params.extra or nil
  500. -- 尝试解析 JSON 数据
  501. local success, Data = pcall(jsonParse, params.extra)
  502. if success and Data then
  503. local address = (Data.extra and Data.extra.downloadSettings and Data.extra.downloadSettings.address)
  504. or (Data.downloadSettings and Data.downloadSettings.address)
  505. result.download_address = address and address ~= "" and address or nil
  506. else
  507. -- 如果解析失败,清空下载地址
  508. result.download_address = nil
  509. end
  510. -- make it compatible with bullshit, "h2" transport is non-existent at all
  511. elseif result.transport == "http" or result.transport == "h2" then
  512. result.transport = "h2"
  513. result.h2_host = params.host and UrlDecode(params.host) or nil
  514. result.h2_path = params.path and UrlDecode(params.path) or nil
  515. elseif result.transport == "kcp" then
  516. result.kcp_guise = params.headerType or "none"
  517. result.seed = params.seed
  518. result.mtu = 1350
  519. result.tti = 50
  520. result.uplink_capacity = 5
  521. result.downlink_capacity = 20
  522. result.read_buffer_size = 2
  523. result.write_buffer_size = 2
  524. elseif result.transport == "quic" then
  525. result.quic_guise = params.headerType or "none"
  526. result.quic_security = params.quicSecurity or "none"
  527. result.quic_key = params.key
  528. elseif result.transport == "grpc" then
  529. result.serviceName = params.serviceName
  530. result.grpc_mode = params.mode or "gun"
  531. elseif result.transport == "tcp" or result.transport == "raw" then
  532. result.tcp_guise = params.headerType or "none"
  533. if result.tcp_guise == "http" then
  534. result.tcp_host = params.host and UrlDecode(params.host) or nil
  535. result.tcp_path = params.path and UrlDecode(params.path) or nil
  536. end
  537. end
  538. end
  539. if not result.alias then
  540. if result.server and result.server_port then
  541. result.alias = result.server .. ':' .. result.server_port
  542. else
  543. result.alias = "NULL"
  544. end
  545. end
  546. -- alias 不参与 hashkey 计算
  547. local alias = result.alias
  548. result.alias = nil
  549. local switch_enable = result.switch_enable
  550. result.switch_enable = nil
  551. result.hashkey = md5(jsonStringify(result))
  552. result.alias = alias
  553. result.switch_enable = switch_enable
  554. return result
  555. end
  556. -- wget
  557. local function wget(url)
  558. 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 .. '"')
  559. return trim(stdout)
  560. end
  561. local function check_filer(result)
  562. do
  563. -- 过滤的关键词列表
  564. local filter_word = split(filter_words, "/")
  565. -- 保留的关键词列表
  566. local check_save = false
  567. if save_words ~= nil and save_words ~= "" and save_words ~= "NULL" then
  568. check_save = true
  569. end
  570. local save_word = split(save_words, "/")
  571. -- 检查结果
  572. local filter_result = false
  573. local save_result = true
  574. -- 检查是否存在过滤关键词
  575. for i, v in pairs(filter_word) do
  576. if tostring(result.alias):find(v, nil, true) then
  577. filter_result = true
  578. end
  579. end
  580. -- 检查是否打开了保留关键词检查,并且进行过滤
  581. if check_save == true then
  582. for i, v in pairs(save_word) do
  583. if tostring(result.alias):find(v, nil, true) then
  584. save_result = false
  585. end
  586. end
  587. else
  588. save_result = false
  589. end
  590. -- 不等时返回
  591. if filter_result == true or save_result == true then
  592. return true
  593. else
  594. return false
  595. end
  596. end
  597. end
  598. local execute = function()
  599. -- exec
  600. do
  601. if proxy == '0' then -- 不使用代理更新的话先暂停
  602. log('服务正在暂停')
  603. luci.sys.init.stop(name)
  604. end
  605. for k, url in ipairs(subscribe_url) do
  606. local raw = wget(url)
  607. if #raw > 0 then
  608. local nodes, szType
  609. local groupHash = md5(url)
  610. cache[groupHash] = {}
  611. tinsert(nodeResult, {})
  612. local index = #nodeResult
  613. -- SSD 似乎是这种格式 ssd:// 开头的
  614. if raw:find('ssd://') then
  615. szType = 'ssd'
  616. local nEnd = select(2, raw:find('ssd://'))
  617. nodes = base64Decode(raw:sub(nEnd + 1, #raw))
  618. nodes = jsonParse(nodes)
  619. local extra = {airport = nodes.airport, port = nodes.port, encryption = nodes.encryption, password = nodes.password}
  620. local servers = {}
  621. -- SS里面包着 干脆直接这样
  622. for _, server in ipairs(nodes.servers) do
  623. tinsert(servers, setmetatable(server, {__index = extra}))
  624. end
  625. nodes = servers
  626. -- SS SIP008 直接使用 Json 格式
  627. elseif jsonParse(raw) then
  628. nodes = jsonParse(raw).servers or jsonParse(raw)
  629. if nodes[1].server and nodes[1].method then
  630. szType = 'sip008'
  631. end
  632. else
  633. -- ssd 外的格式
  634. nodes = split(base64Decode(raw):gsub(" ", "_"), "\n")
  635. end
  636. for _, v in ipairs(nodes) do
  637. if v then
  638. local result
  639. if szType then
  640. result = processData(szType, v)
  641. elseif not szType then
  642. local node = trim(v)
  643. local dat = split(node, "://")
  644. if dat and dat[1] and dat[2] then
  645. local dat3 = ""
  646. if dat[3] then
  647. dat3 = "://" .. dat[3]
  648. end
  649. if dat[1] == 'ss' or dat[1] == 'trojan' then
  650. result = processData(dat[1], dat[2] .. dat3)
  651. else
  652. result = processData(dat[1], base64Decode(dat[2]))
  653. end
  654. end
  655. else
  656. log('跳过未知类型: ' .. szType)
  657. end
  658. -- log(result)
  659. if result then
  660. -- 中文做地址的 也没有人拿中文域名搞,就算中文域也有Puny Code SB 机场
  661. 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
  662. log('丢弃无效节点: ' .. result.type .. ' 节点, ' .. result.alias)
  663. else
  664. -- log('成功解析: ' .. result.type ..' 节点, ' .. result.alias)
  665. result.grouphashkey = groupHash
  666. tinsert(nodeResult[index], result)
  667. cache[groupHash][result.hashkey] = nodeResult[index][#nodeResult[index]]
  668. end
  669. end
  670. end
  671. end
  672. log('成功解析节点数量: ' .. #nodes)
  673. else
  674. log(url .. ': 获取内容为空')
  675. end
  676. end
  677. end
  678. -- diff
  679. do
  680. if next(nodeResult) == nil then
  681. log("更新失败,没有可用的节点信息")
  682. if proxy == '0' then
  683. luci.sys.init.start(name)
  684. log('订阅失败, 恢复服务')
  685. end
  686. return
  687. end
  688. local add, del = 0, 0
  689. ucic:foreach(name, uciType, function(old)
  690. if old.grouphashkey or old.hashkey then -- 没有 hash 的不参与删除
  691. if not nodeResult[old.grouphashkey] or not nodeResult[old.grouphashkey][old.hashkey] then
  692. ucic:delete(name, old['.name'])
  693. del = del + 1
  694. else
  695. local dat = nodeResult[old.grouphashkey][old.hashkey]
  696. ucic:tset(name, old['.name'], dat)
  697. -- 标记一下
  698. setmetatable(nodeResult[old.grouphashkey][old.hashkey], {__index = {_ignore = true}})
  699. end
  700. else
  701. if not old.alias then
  702. if old.server or old.server_port then
  703. old.alias = old.server .. ':' .. old.server_port
  704. log('忽略手动添加的节点: ' .. old.alias)
  705. else
  706. ucic:delete(name, old['.name'])
  707. end
  708. else
  709. log('忽略手动添加的节点: ' .. old.alias)
  710. end
  711. end
  712. end)
  713. for k, v in ipairs(nodeResult) do
  714. for kk, vv in ipairs(v) do
  715. if not vv._ignore then
  716. local section = ucic:add(name, uciType)
  717. ucic:tset(name, section, vv)
  718. ucic:set(name, section, "switch_enable", switch)
  719. add = add + 1
  720. end
  721. end
  722. end
  723. ucic:commit(name)
  724. -- 如果原有服务器节点已经不见了就尝试换为第一个节点
  725. local globalServer = ucic:get_first(name, 'global', 'global_server', '')
  726. if globalServer ~= "nil" then
  727. local firstServer = ucic:get_first(name, uciType)
  728. if firstServer then
  729. if not ucic:get(name, globalServer) then
  730. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  731. ucic:commit(name)
  732. ucic:set(name, ucic:get_first(name, 'global'), 'global_server', ucic:get_first(name, uciType))
  733. ucic:commit(name)
  734. log('当前主服务器节点已被删除,正在自动更换为第一个节点。')
  735. luci.sys.call("/etc/init.d/" .. name .. " start > /dev/null 2>&1 &")
  736. else
  737. log('维持当前主服务器节点。')
  738. luci.sys.call("/etc/init.d/" .. name .. " restart > /dev/null 2>&1 &")
  739. end
  740. else
  741. log('没有服务器节点了,停止服务')
  742. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  743. end
  744. end
  745. log('新增节点数量: ' .. add, '删除节点数量: ' .. del)
  746. log('订阅更新成功')
  747. end
  748. end
  749. if subscribe_url and #subscribe_url > 0 then
  750. xpcall(execute, function(e)
  751. log(e)
  752. log(debug.traceback())
  753. log('发生错误, 正在恢复服务')
  754. local firstServer = ucic:get_first(name, uciType)
  755. if firstServer then
  756. luci.sys.call("/etc/init.d/" .. name .. " restart > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  757. log('重启服务成功')
  758. else
  759. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  760. log('停止服务成功')
  761. end
  762. end)
  763. end