subscribe.lua 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  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 URL = require "url"
  18. local cache = {}
  19. local nodeResult = setmetatable({}, {__index = cache}) -- update result
  20. local name = 'shadowsocksr'
  21. local uciType = 'servers'
  22. local ucic = require "luci.model.uci".cursor()
  23. local proxy = ucic:get_first(name, 'server_subscribe', 'proxy', '0')
  24. local switch = ucic:get_first(name, 'server_subscribe', 'switch', '1')
  25. local allow_insecure = ucic:get_first(name, 'server_subscribe', 'allow_insecure', '0')
  26. local subscribe_url = ucic:get_first(name, 'server_subscribe', 'subscribe_url', {})
  27. local filter_words = ucic:get_first(name, 'server_subscribe', 'filter_words', '过期时间/剩余流量')
  28. local save_words = ucic:get_first(name, 'server_subscribe', 'save_words', '')
  29. local user_agent = ucic:get_first(name, 'server_subscribe', 'user_agent', 'v2rayN/9.99')
  30. -- 读取 ss_type 设置
  31. local ss_type = ucic:get_first(name, 'server_subscribe', 'ss_type', 'ss-rust')
  32. -- 根据 ss_type 选择对应的程序
  33. local ss_program = "sslocal"
  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 hy2_type = luci.sys.exec('type -t -p hysteria') ~= "" and "hysteria2"
  43. local log = function(...)
  44. print(os.date("%Y-%m-%d %H:%M:%S ") .. table.concat({...}, " "))
  45. end
  46. local encrypt_methods_ss = {
  47. -- plain
  48. "none",
  49. "plain",
  50. -- aead
  51. "aes-128-gcm",
  52. "aes-192-gcm",
  53. "aes-256-gcm",
  54. "chacha20-ietf-poly1305",
  55. "xchacha20-ietf-poly1305",
  56. -- aead 2022
  57. "2022-blake3-aes-128-gcm",
  58. "2022-blake3-aes-256-gcm",
  59. "2022-blake3-chacha20-poly1305"
  60. --[[ stream
  61. "table",
  62. "rc4",
  63. "rc4-md5",
  64. "aes-128-cfb",
  65. "aes-192-cfb",
  66. "aes-256-cfb",
  67. "aes-128-ctr",
  68. "aes-192-ctr",
  69. "aes-256-ctr",
  70. "bf-cfb",
  71. "camellia-128-cfb",
  72. "camellia-192-cfb",
  73. "camellia-256-cfb",
  74. "salsa20",
  75. "chacha20",
  76. "chacha20-ietf" ]]--
  77. }
  78. -- 分割字符串
  79. local function split(full, sep)
  80. if full == nil or type(full) ~= "string" then
  81. -- print("Debug: split() received nil or non-string value")
  82. return {}
  83. end
  84. full = full:gsub("%z", ""):gsub("^%s+", ""):gsub("%s+$", "") -- 去除首尾空白字符和\0
  85. if full == "" then
  86. -- print("Debug: split() received empty string after trimming")
  87. return {}
  88. end
  89. sep = sep or "," -- 默认分隔符
  90. local off, result = 1, {}
  91. while true do
  92. local nStart, nEnd = full:find(sep, off)
  93. if not nEnd then
  94. local res = ssub(full, off, slen(full))
  95. if #res > 0 then -- 过滤掉 \0
  96. tinsert(result, res)
  97. end
  98. break
  99. else
  100. tinsert(result, ssub(full, off, nStart - 1))
  101. off = nEnd + 1
  102. end
  103. end
  104. return result
  105. end
  106. -- urlencode
  107. local function get_urlencode(c)
  108. return sformat("%%%02X", sbyte(c))
  109. end
  110. local function urlEncode(szText)
  111. local str = szText:gsub("([^0-9a-zA-Z ])", get_urlencode)
  112. str = str:gsub(" ", "+")
  113. return str
  114. end
  115. local function get_urldecode(h)
  116. return schar(tonumber(h, 16))
  117. end
  118. local function UrlDecode(szText)
  119. return szText:gsub("+", " "):gsub("%%(%x%x)", get_urldecode)
  120. end
  121. -- trim
  122. local function trim(text)
  123. if not text or text == "" then
  124. return ""
  125. end
  126. return (sgsub(text, "^%s*(.-)%s*$", "%1"))
  127. end
  128. -- md5
  129. local function md5(content)
  130. local stdout = luci.sys.exec('echo \"' .. urlEncode(content) .. '\" | md5sum | cut -d \" \" -f1')
  131. -- assert(nixio.errno() == 0)
  132. return trim(stdout)
  133. end
  134. -- base64
  135. local function base64Decode(text)
  136. local raw = text
  137. if not text then
  138. return ''
  139. end
  140. text = text:gsub("%z", "")
  141. text = text:gsub("_", "/")
  142. text = text:gsub("-", "+")
  143. local mod4 = #text % 4
  144. text = text .. string.sub('====', mod4 + 1)
  145. local result = b64decode(text)
  146. if result then
  147. return result:gsub("%z", "")
  148. else
  149. return raw
  150. end
  151. end
  152. -- 检查数组(table)中是否存在某个字符值
  153. -- https://www.04007.cn/article/135.html
  154. local function checkTabValue(tab)
  155. local revtab = {}
  156. for k,v in pairs(tab) do
  157. revtab[v] = true
  158. end
  159. return revtab
  160. end
  161. -- JSON完整性检查
  162. local function isCompleteJSON(str)
  163. -- 检查JSON格式
  164. if type(str) ~= "string" or str:match("^%s*$") then
  165. return false
  166. end
  167. -- 尝试解析JSON验证完整性
  168. local success, _ = pcall(jsonParse, str)
  169. return success
  170. end
  171. -- 处理数据
  172. local function processData(szType, content)
  173. local result = {type = szType, local_port = 1234, kcp_param = '--nocomp'}
  174. -- 检查JSON的格式如不完整丢弃
  175. if not (szType == "sip008" or szType == "ssd") then
  176. if not isCompleteJSON(content) then
  177. return nil
  178. end
  179. end
  180. if szType == "hysteria2" or szType == "hy2" then
  181. local url = URL.parse("http://" .. content)
  182. local params = url.query
  183. -- 调试输出所有参数
  184. -- log("Hysteria2 原始参数:")
  185. -- for k,v in pairs(params) do
  186. -- log(k.."="..v)
  187. -- end
  188. -- 如果 hy2 程序未安装则跳过订阅
  189. if not hy2_type then
  190. return nil
  191. end
  192. result.alias = url.fragment and UrlDecode(url.fragment) or nil
  193. result.type = hy2_type
  194. result.server = url.host
  195. result.server_port = url.port or 443
  196. if params.protocol then
  197. result.flag_transport = "1"
  198. result.transport_protocol = params.protocol or "udp"
  199. end
  200. result.hy2_auth = url.user
  201. result.uplink_capacity = tonumber((params.upmbps or ""):match("^(%d+)")) or nil
  202. result.downlink_capacity = tonumber((params.downmbps or ""):match("^(%d+)")) or nil
  203. if params.mport then
  204. result.flag_port_hopping = "1"
  205. result.port_range = params.mport
  206. end
  207. if params.obfs and params.obfs ~= "none" then
  208. result.flag_obfs = "1"
  209. result.obfs_type = params.obfs
  210. result.salamander = params["obfs-password"] or params["obfs_password"]
  211. end
  212. if (params.sni and params.sni ~= "") or (params.alpn and params.alpn ~= "") then
  213. result.tls = "1"
  214. if params.sni then
  215. result.tls_host = params.sni
  216. end
  217. if params.alpn then
  218. local alpn = {}
  219. for v in params.alpn:gmatch("[^,;|%s]+") do
  220. table.insert(alpn, v)
  221. end
  222. result.tls_alpn = alpn
  223. end
  224. end
  225. if params.insecure == "1" then
  226. result.insecure = params.insecure
  227. end
  228. if params.pinSHA256 then
  229. result.pinsha256 = params.pinSHA256
  230. end
  231. elseif szType == 'ssr' then
  232. -- 去掉前后空白和#注释
  233. local link = trim(content:gsub("#.*$", ""))
  234. local dat = split(link, "/%?")
  235. local hostInfo = split(dat[1] or '', ':')
  236. result.type = 'ssr'
  237. result.server = hostInfo[1] or ''
  238. result.server_port = hostInfo[2] or ''
  239. result.protocol = hostInfo[3] or ''
  240. result.encrypt_method = hostInfo[4] or ''
  241. result.obfs = hostInfo[5] or ''
  242. result.password = base64Decode(hostInfo[6] or '')
  243. local params = {}
  244. if dat[2] and dat[2] ~= '' then
  245. for _, v in pairs(split(dat[2], '&')) do
  246. local t = split(v, '=')
  247. if t[1] and t[2] then
  248. params[t[1]] = t[2]
  249. end
  250. end
  251. end
  252. result.obfs_param = base64Decode(params.obfsparam or '')
  253. result.protocol_param = base64Decode(params.protoparam or '')
  254. local group = base64Decode(params.group or '')
  255. local remarks = base64Decode(params.remarks or '')
  256. -- 拼接 alias
  257. local alias = ""
  258. if group ~= "" then
  259. alias = "[" .. group .. "] "
  260. end
  261. alias = alias .. remarks
  262. result.alias = alias
  263. elseif szType == "vmess" then
  264. -- 去掉前后空白和#注释
  265. local link = trim(content:gsub("#.*$", ""))
  266. -- 解析正常节点
  267. local success, info = pcall(jsonParse, link)
  268. if not success or type(info) ~= "table" then
  269. return nil
  270. end
  271. -- 基本信息
  272. result.type = 'v2ray'
  273. result.v2ray_protocol = 'vmess'
  274. result.server = info.add
  275. result.server_port = info.port
  276. result.alter_id = info.aid
  277. result.vmess_id = info.id
  278. result.alias = info.ps
  279. -- 调整传输协议
  280. if info.net == "tcp" then
  281. info.net = "raw"
  282. end
  283. if info.net == "splithttp" then
  284. info.net = "xhttp"
  285. end
  286. result.transport = info.net
  287. -- result.mux = 1
  288. -- result.concurrency = 8
  289. if info.net == 'ws' then
  290. result.ws_host = info.host
  291. result.ws_path = info.path
  292. end
  293. if info.net == 'httpupgrade' then
  294. result.httpupgrade_host = info.host
  295. result.httpupgrade_path = info.path
  296. end
  297. if info.net == 'xhttp' or info.net == 'splithttp' then
  298. result.xhttp_mode = info.mode
  299. result.xhttp_host = info.host
  300. result.xhttp_path = info.path
  301. -- 检查 extra 参数是否存在且非空
  302. result.enable_xhttp_extra = (info.extra and info.extra ~= "") and "1" or nil
  303. result.xhttp_extra = (info.extra and info.extra ~= "") and info.extra or nil
  304. -- 尝试解析 JSON 数据
  305. local success, Data = pcall(jsonParse, info.extra or "")
  306. if success and type(Data) == "table" then
  307. local address = (Data.extra and Data.extra.downloadSettings and Data.extra.downloadSettings.address)
  308. or (Data.downloadSettings and Data.downloadSettings.address)
  309. result.download_address = (address and address ~= "") and address or nil
  310. else
  311. -- 如果解析失败,清空下载地址
  312. result.download_address = nil
  313. end
  314. end
  315. if info.net == 'h2' then
  316. result.h2_host = info.host
  317. result.h2_path = info.path
  318. end
  319. if info.net == 'raw' or info.net == 'tcp' then
  320. result.tcp_guise = info.type or "none"
  321. if result.tcp_guise == "http" then
  322. result.http_host = info.host
  323. result.http_path = info.path
  324. end
  325. end
  326. if info.net == 'kcp' then
  327. result.kcp_guise = info.type
  328. result.mtu = 1350
  329. result.tti = 50
  330. result.uplink_capacity = 5
  331. result.downlink_capacity = 20
  332. result.read_buffer_size = 2
  333. result.write_buffer_size = 2
  334. end
  335. if info.net == 'grpc' then
  336. if info.path then
  337. result.serviceName = info.path
  338. elseif info.serviceName then
  339. result.serviceName = info.serviceName
  340. end
  341. end
  342. if info.net == 'quic' then
  343. result.quic_guise = info.type
  344. result.quic_key = info.key
  345. result.quic_security = info.security
  346. end
  347. if info.security then
  348. result.security = info.security
  349. end
  350. if info.tls == "tls" or info.tls == "1" then
  351. result.tls = "1"
  352. result.fingerprint = info.fp
  353. if info.alpn and info.alpn ~= "" then
  354. local alpn = {}
  355. for v in info.alpn:gmatch("[^,]+") do
  356. table.insert(alpn, v)
  357. end
  358. result.tls_alpn = alpn
  359. end
  360. if info.sni and info.sni ~= "" then
  361. result.tls_host = info.sni
  362. elseif info.host and info.host ~= "" then
  363. result.tls_host = info.host
  364. end
  365. if info.ech and info.ech ~= "" then
  366. result.enable_ech = "1"
  367. result.ech_config = info.ech
  368. end
  369. -- 兼容 allowInsecure / allowlnsecure / skip-cert-verify
  370. if info.allowInsecure or info.allowlnsecure or info["skip-cert-verify"] then
  371. local insecure = info.allowInsecure or info.allowlnsecure or info["skip-cert-verify"]
  372. if insecure == true or insecure == "1" or insecure == "true" then
  373. result.insecure = "1"
  374. end
  375. end
  376. else
  377. result.tls = "0"
  378. end
  379. -- 其它可选安全字段
  380. if info.security then
  381. result.security = info.security
  382. end
  383. elseif szType == "ss" then
  384. local idx_sp = content:find("#") or 0
  385. local alias = ""
  386. if idx_sp > 0 then
  387. alias = UrlDecode(content:sub(idx_sp + 1))
  388. end
  389. local info = content:sub(1, idx_sp > 0 and idx_sp - 1 or #content):gsub("/%?", "?")
  390. -- 拆 base64 主体和 ? 参数部分
  391. local uri_main, query_str = info:match("^([^?]+)%??(.*)$")
  392. --log("SS 节点格式:", uri_main)
  393. local params = {}
  394. if query_str and query_str ~= "" then
  395. for _, v in ipairs(split(query_str, '&')) do
  396. local t = split(v, '=')
  397. if #t >= 2 then
  398. params[t[1]] = UrlDecode(t[2])
  399. end
  400. end
  401. end
  402. if not params.type or params.type == "" then
  403. local is_old_format = uri_main:find("@") and not uri_main:find("://.*@")
  404. local base64_str, host_port, userinfo, server, port, method, password
  405. if is_old_format then
  406. -- 旧格式:base64(method:pass)@host:port
  407. base64_str, host_port = uri_main:match("^([^@]+)@(.-)$")
  408. log("SS 节点旧格式解析:", base64_str)
  409. if not base64_str or not host_port then
  410. log("SS 节点旧格式解析失败:", uri_main)
  411. return nil
  412. end
  413. local decoded = base64Decode(UrlDecode(base64_str))
  414. if not decoded then
  415. log("SS base64 解码失败(旧格式):", base64_str)
  416. return nil
  417. end
  418. userinfo = decoded
  419. else
  420. -- 新格式:base64(method:pass@host:port)
  421. local decoded = base64Decode(UrlDecode(uri_main))
  422. if not decoded then
  423. log("SS base64 解码失败(新格式):", uri_main)
  424. return nil
  425. end
  426. userinfo, host_port = decoded:match("^(.-)@(.-)$")
  427. if not userinfo or not host_port then
  428. log("SS 解码内容缺失 @ 分隔:", decoded)
  429. return nil
  430. end
  431. end
  432. -- 解析加密方式和密码(允许密码包含冒号)
  433. local split_pos = userinfo:find(":")
  434. if not split_pos then
  435. log("SS 用户信息格式错误:", userinfo)
  436. return nil
  437. end
  438. method = userinfo:sub(1, split_pos - 1)
  439. password = userinfo:sub(split_pos + 1)
  440. -- 判断密码是否经过url编码
  441. local function isURLEncodedPassword(pwd)
  442. if not pwd:find("%%[0-9A-Fa-f][0-9A-Fa-f]") then
  443. return false
  444. end
  445. local ok, decoded = pcall(UrlDecode, pwd)
  446. return ok and urlEncode(decoded) == pwd
  447. end
  448. local decoded = UrlDecode(password)
  449. if isURLEncodedPassword(password) and decoded then
  450. password = decoded
  451. end
  452. -- 解析服务器地址和端口(兼容 IPv6)
  453. if host_port:find("^%[.*%]:%d+$") then
  454. server, port = host_port:match("^%[(.*)%]:(%d+)$")
  455. else
  456. server, port = host_port:match("^(.-):(%d+)$")
  457. end
  458. if not server or not port then
  459. log("SS 节点服务器信息格式错误:", host_port)
  460. return nil
  461. end
  462. -- 如果 SS 程序未安装则跳过订阅
  463. if not (v2_ss or has_ss_type) then
  464. return nil
  465. end
  466. -- 填充 result
  467. result.alias = alias
  468. result.type = v2_ss
  469. result.v2ray_protocol = (v2_ss == "v2ray") and "shadowsocks" or nil
  470. result.has_ss_type = has_ss_type
  471. result.encrypt_method_ss = method
  472. result.password = password
  473. result.server = server
  474. result.server_port = port
  475. -- 仅在 v2ray + shadowsocks 协议时处理 ECH
  476. if v2_ss == "v2ray" and result.v2ray_protocol == "shadowsocks" then
  477. if params.ech and params.ech ~= "" then
  478. result.enable_ech = "1"
  479. result.ech_config = ech
  480. end
  481. end
  482. -- 插件处理
  483. if params.plugin then
  484. local plugin_info = UrlDecode(params.plugin)
  485. local idx_pn = plugin_info:find(";")
  486. if idx_pn then
  487. result.plugin = plugin_info:sub(1, idx_pn - 1)
  488. result.plugin_opts = plugin_info:sub(idx_pn + 1, #plugin_info)
  489. else
  490. result.plugin = plugin_info
  491. result.plugin_opts = ""
  492. end
  493. -- 部分机场下发的插件名为 simple-obfs,这里应该改为 obfs-local
  494. if result.plugin == "simple-obfs" then
  495. result.plugin = "obfs-local"
  496. end
  497. -- 如果插件不为 none,确保 enable_plugin 为 1
  498. if result.plugin ~= "none" and result.plugin ~= "" then
  499. result.enable_plugin = 1
  500. end
  501. elseif has_ss_type and has_ss_type ~= "ss-libev" then
  502. if params["shadow-tls"] then
  503. -- 特别处理 shadow-tls 作为插件
  504. -- log("原始 shadow-tls 参数:", params["shadow-tls"])
  505. local decoded_tls = base64Decode(UrlDecode(params["shadow-tls"]))
  506. --log("SS 节点 shadow-tls 解码后:", decoded_tls or "nil")
  507. if decoded_tls then
  508. local ok, st = pcall(jsonParse, decoded_tls)
  509. if ok and st then
  510. result.plugin = "shadow-tls"
  511. result.enable_plugin = 1
  512. local version_flag = ""
  513. if st.version and tonumber(st.version) then
  514. version_flag = string.format("v%s=1;", st.version)
  515. end
  516. -- 合成 plugin_opts 格式:v%s=1;host=xxx;password=xxx
  517. result.plugin_opts = string.format("%shost=%s;passwd=%s",
  518. version_flag,
  519. st.host or "",
  520. st.password or "")
  521. else
  522. log("shadow-tls JSON 解析失败")
  523. end
  524. end
  525. end
  526. else
  527. if params["shadow-tls"] then
  528. log("错误:ShadowSocks-libev 不支持使用 shadow-tls 插件")
  529. return nil, "ShadowSocks-libev 不支持使用 shadow-tls 插件"
  530. end
  531. end
  532. -- 检查加密方法是否受支持
  533. if not checkTabValue(encrypt_methods_ss)[method] then
  534. -- 1202 年了还不支持 SS AEAD 的屑机场
  535. -- log("不支持的SS加密方法:", method)
  536. result.server = nil
  537. end
  538. else
  539. local url = URL.parse("http://" .. info)
  540. local params = url.query
  541. result.alias = alias
  542. result.type = "v2ray"
  543. result.v2ray_protocol = "shadowsocks"
  544. result.server = url.host
  545. result.server_port = url.port
  546. -- 判断 @ 前部分是否为 Base64
  547. local is_base64_decoded = base64Decode(UrlDecode(url.user))
  548. if is_base64_decoded:find(":") then
  549. -- 新格式:method:password
  550. result.encrypt_method_ss, result.password = is_base64_decoded:match("^(.-):(.*)$")
  551. else
  552. -- 旧格式:UUID 直接作为密码
  553. result.password = url.user
  554. result.encrypt_method_ss = params.encryption or "none"
  555. end
  556. result.transport = params.type or "raw"
  557. if result.transport == "tcp" then
  558. result.transport = "raw"
  559. end
  560. if result.transport == "splithttp" then
  561. result.transport = "xhttp"
  562. end
  563. result.tls = (params.security == "tls" or params.security == "xtls") and "1" or "0"
  564. if params.alpn and params.alpn ~= "" then
  565. local alpn = {}
  566. for v in params.alpn:gmatch("[^,;|%s]+") do
  567. table.insert(alpn, v)
  568. end
  569. result.tls_alpn = params.alpn
  570. end
  571. result.tls_host = params.sni
  572. result.tls_flow = (params.security == "tls" or params.security == "reality") and params.flow or nil
  573. result.fingerprint = params.fp
  574. result.reality = (params.security == "reality") and "1" or "0"
  575. result.reality_publickey = params.pbk and UrlDecode(params.pbk) or nil
  576. result.reality_shortid = params.sid
  577. result.reality_spiderx = params.spx and UrlDecode(params.spx) or nil
  578. -- 检查 ech 参数是否存在且非空
  579. result.enable_ech = (params.ech and params.ech ~= "") and "1" or nil
  580. result.ech_config = (params.ech and params.ech ~= "") and params.ech or nil
  581. -- 检查 pqv 参数是否存在且非空
  582. result.enable_mldsa65verify = (params.pqv and params.pqv ~= "") and "1" or nil
  583. result.reality_mldsa65verify = (params.pqv and params.pqv ~= "") and params.pqv or nil
  584. if result.transport == "ws" then
  585. result.ws_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  586. result.ws_path = params.path and UrlDecode(params.path) or "/"
  587. elseif result.transport == "httpupgrade" then
  588. result.httpupgrade_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  589. result.httpupgrade_path = params.path and UrlDecode(params.path) or "/"
  590. elseif result.transport == "xhttp" or result.transport == "splithttp" then
  591. result.xhttp_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  592. result.xhttp_mode = params.mode or "auto"
  593. result.xhttp_path = params.path and UrlDecode(params.path) or "/"
  594. -- 检查 extra 参数是否存在且非空
  595. result.enable_xhttp_extra = (params.extra and params.extra ~= "") and "1" or nil
  596. result.xhttp_extra = (params.extra and params.extra ~= "") and params.extra or nil
  597. -- 尝试解析 JSON 数据
  598. local success, Data = pcall(jsonParse, params.extra or "")
  599. if success and type(Data) == "table" then
  600. local address = (Data.extra and Data.extra.downloadSettings and Data.extra.downloadSettings.address)
  601. or (Data.downloadSettings and Data.downloadSettings.address)
  602. result.download_address = address and address ~= "" and address or nil
  603. else
  604. -- 如果解析失败,清空下载地址
  605. result.download_address = nil
  606. end
  607. -- make it compatible with bullshit, "h2" transport is non-existent at all
  608. elseif result.transport == "http" or result.transport == "h2" then
  609. result.transport = "h2"
  610. result.h2_host = params.host and UrlDecode(params.host) or nil
  611. result.h2_path = params.path and UrlDecode(params.path) or nil
  612. elseif result.transport == "kcp" then
  613. result.kcp_guise = params.headerType or "none"
  614. result.seed = params.seed
  615. result.mtu = 1350
  616. result.tti = 50
  617. result.uplink_capacity = 5
  618. result.downlink_capacity = 20
  619. result.read_buffer_size = 2
  620. result.write_buffer_size = 2
  621. elseif result.transport == "quic" then
  622. result.quic_guise = params.headerType or "none"
  623. result.quic_security = params.quicSecurity or "none"
  624. result.quic_key = params.key
  625. elseif result.transport == "grpc" then
  626. result.serviceName = params.serviceName
  627. result.grpc_mode = params.mode or "gun"
  628. elseif result.transport == "tcp" or result.transport == "raw" then
  629. result.tcp_guise = params.headerType or "none"
  630. if result.tcp_guise == "http" then
  631. result.tcp_host = params.host and UrlDecode(params.host) or nil
  632. result.tcp_path = params.path and UrlDecode(params.path) or nil
  633. end
  634. end
  635. end
  636. elseif szType == "sip008" then
  637. result.type = v2_ss
  638. result.v2ray_protocol = (v2_ss == "v2ray") and "shadowsocks" or nil
  639. result.has_ss_type = has_ss_type
  640. result.server = content.server
  641. result.server_port = content.server_port
  642. result.password = content.password
  643. result.encrypt_method_ss = content.method
  644. result.plugin = content.plugin
  645. result.plugin_opts = content.plugin_opts
  646. result.alias = content.remarks
  647. if not checkTabValue(encrypt_methods_ss)[content.method] then
  648. result.server = nil
  649. end
  650. elseif szType == "ssd" then
  651. result.type = v2_ss
  652. result.v2ray_protocol = (v2_ss == "v2ray") and "shadowsocks" or nil
  653. result.has_ss_type = has_ss_type
  654. result.server = content.server
  655. result.server_port = content.port
  656. result.password = content.password
  657. result.encrypt_method_ss = content.method
  658. result.plugin_opts = content.plugin_options
  659. result.alias = "[" .. content.airport .. "] " .. content.remarks
  660. if content.plugin == "simple-obfs" then
  661. result.plugin = "obfs-local"
  662. else
  663. result.plugin = content.plugin
  664. end
  665. if not checkTabValue(encrypt_methods_ss)[content.encryption] then
  666. result.server = nil
  667. end
  668. elseif szType == "trojan" then
  669. local params = {}
  670. local idx_sp = 0
  671. local alias = ""
  672. -- 提取别名(如果存在)
  673. if content:find("#") then
  674. idx_sp = content:find("#")
  675. alias = content:sub(idx_sp + 1, -1)
  676. end
  677. local info = content:sub(1, idx_sp > 0 and idx_sp - 1 or #content)
  678. local hostInfo = split(info, "@")
  679. -- 基础验证
  680. if #hostInfo < 2 then
  681. --log("Trojan节点格式错误: 缺少@符号")
  682. return nil
  683. end
  684. local userinfo = hostInfo[1]
  685. local hostPort = hostInfo[2]
  686. -- 分离服务器地址和端口
  687. local hostParts = split(hostPort, ":")
  688. -- 验证服务器地址和端口
  689. if #hostParts < 2 then
  690. --log("Trojan节点格式错误: 缺少端口号")
  691. return nil
  692. end
  693. local server = hostParts[1]
  694. local port = hostParts[2]
  695. result.alias = UrlDecode(alias)
  696. result.server = server
  697. result.password = userinfo
  698. -- 默认设置
  699. -- 按照官方的建议 默认验证ssl证书
  700. result.insecure = "0"
  701. result.tls = "1"
  702. -- 解析查询参数(如果存在)
  703. if port:find("?") then
  704. local queryParts = split(port, "?")
  705. result.server_port = queryParts[1]
  706. -- 解析查询参数
  707. for _, v in pairs(split(queryParts[2], "&")) do
  708. local t = split(v, "=")
  709. if #t >= 2 then
  710. params[t[1]] = t[2]
  711. end
  712. end
  713. -- 处理参数
  714. if params.alpn then
  715. -- 处理 alpn 参数
  716. result.tls_alpn = params.alpn
  717. end
  718. if params.sni then
  719. -- 未指定peer(sni)默认使用remote addr
  720. result.tls_host = params.sni
  721. end
  722. if params.allowInsecure then
  723. -- 处理 insecure 参数
  724. result.insecure = params.allowInsecure
  725. end
  726. if params.tfo then
  727. -- 处理 insecure 参数
  728. result.fast_open = params.tfo
  729. end
  730. else
  731. result.server_port = port
  732. end
  733. -- 如果 Tojan 程序未安装则跳过订阅
  734. if not v2_tj or v2_tj == "" then
  735. return nil
  736. end
  737. if params.type and params.type ~= "" then
  738. v2_tj = "v2ray"
  739. result.type = v2_tj
  740. result.v2ray_protocol = "trojan"
  741. if v2_tj ~= "trojan" then
  742. if params.fp then
  743. -- 处理 fingerprint 参数
  744. result.fingerprint = params.fp
  745. end
  746. -- 处理 ech 参数
  747. if params.ech then
  748. result.enable_ech = "1"
  749. result.ech_config = params.ech
  750. end
  751. -- 处理传输协议
  752. result.transport = params.type or "raw" -- 默认传输协议为 raw
  753. if result.transport == "tcp" then
  754. result.transport = "raw"
  755. end
  756. if result.transport == "splithttp" then
  757. result.transport = "xhttp"
  758. end
  759. if result.transport == "ws" then
  760. result.ws_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  761. result.ws_path = params.path and UrlDecode(params.path) or "/"
  762. elseif result.transport == "httpupgrade" then
  763. result.httpupgrade_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  764. result.httpupgrade_path = params.path and UrlDecode(params.path) or "/"
  765. elseif result.transport == "xhttp" or result.transport == "splithttp" then
  766. result.xhttp_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  767. result.xhttp_mode = params.mode or "auto"
  768. result.xhttp_path = params.path and UrlDecode(params.path) or "/"
  769. -- 检查 extra 参数是否存在且非空
  770. result.enable_xhttp_extra = (params.extra and params.extra ~= "") and "1" or nil
  771. result.xhttp_extra = (params.extra and params.extra ~= "") and params.extra or nil
  772. -- 尝试解析 JSON 数据
  773. local success, Data = pcall(jsonParse, params.extra or "")
  774. if success and type(Data) == "table" then
  775. local address = (Data.extra and Data.extra.downloadSettings and Data.extra.downloadSettings.address)
  776. or (Data.downloadSettings and Data.downloadSettings.address)
  777. result.download_address = address and address ~= "" and address or nil
  778. else
  779. -- 如果解析失败,清空下载地址
  780. result.download_address = nil
  781. end
  782. elseif result.transport == "http" or result.transport == "h2" then
  783. result.transport = "h2"
  784. result.h2_host = params.host and UrlDecode(params.host) or nil
  785. result.h2_path = params.path and UrlDecode(params.path) or nil
  786. elseif result.transport == "kcp" then
  787. result.kcp_guise = params.headerType or "none"
  788. result.seed = params.seed
  789. result.mtu = 1350
  790. result.tti = 50
  791. result.uplink_capacity = 5
  792. result.downlink_capacity = 20
  793. result.read_buffer_size = 2
  794. result.write_buffer_size = 2
  795. elseif result.transport == "quic" then
  796. result.quic_guise = params.headerType or "none"
  797. result.quic_security = params.quicSecurity or "none"
  798. result.quic_key = params.key
  799. elseif result.transport == "grpc" then
  800. result.serviceName = params.serviceName
  801. result.grpc_mode = params.mode or "gun"
  802. elseif result.transport == "tcp" or result.transport == "raw" then
  803. result.tcp_guise = params.headerType and params.headerType ~= "" and params.headerType or "none"
  804. if result.tcp_guise == "http" then
  805. result.tcp_host = params.host and UrlDecode(params.host) or nil
  806. result.tcp_path = params.path and UrlDecode(params.path) or nil
  807. end
  808. end
  809. else
  810. result.type = v2_tj
  811. end
  812. end
  813. elseif szType == "vless" then
  814. local url = URL.parse("http://" .. content)
  815. local params = url.query
  816. result.alias = url.fragment and UrlDecode(url.fragment) or nil
  817. result.type = "v2ray"
  818. result.v2ray_protocol = "vless"
  819. result.server = url.host
  820. result.server_port = url.port
  821. result.vmess_id = url.user
  822. result.vless_encryption = params.encryption or "none"
  823. result.transport = params.type or "raw"
  824. if result.transport == "tcp" then
  825. result.transport = "raw"
  826. end
  827. if result.transport == "splithttp" then
  828. result.transport = "xhttp"
  829. end
  830. result.tls = (params.security == "tls" or params.security == "xtls") and "1" or "0"
  831. if params.alpn and params.alpn ~= "" then
  832. local alpn = {}
  833. for v in params.alpn:gmatch("[^,;|%s]+") do
  834. table.insert(alpn, v)
  835. end
  836. result.tls_alpn = alpn
  837. end
  838. result.tls_host = params.sni
  839. result.tls_flow = (params.security == "tls" or params.security == "reality") and params.flow or nil
  840. result.fingerprint = params.fp
  841. result.reality = (params.security == "reality") and "1" or "0"
  842. result.reality_publickey = params.pbk and UrlDecode(params.pbk) or nil
  843. result.reality_shortid = params.sid
  844. result.reality_spiderx = params.spx and UrlDecode(params.spx) or nil
  845. -- 检查 ech 参数是否存在且非空
  846. result.enable_ech = (params.ech and params.ech ~= "") and "1" or nil
  847. result.ech_config = (params.ech and params.ech ~= "") and params.ech or nil
  848. -- 检查 pqv 参数是否存在且非空
  849. result.enable_mldsa65verify = (params.pqv and params.pqv ~= "") and "1" or nil
  850. result.reality_mldsa65verify = (params.pqv and params.pqv ~= "") and params.pqv or nil
  851. if result.transport == "ws" then
  852. result.ws_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  853. result.ws_path = params.path and UrlDecode(params.path) or "/"
  854. elseif result.transport == "httpupgrade" then
  855. result.httpupgrade_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  856. result.httpupgrade_path = params.path and UrlDecode(params.path) or "/"
  857. elseif result.transport == "xhttp" or result.transport == "splithttp" then
  858. result.xhttp_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  859. result.xhttp_mode = params.mode or "auto"
  860. result.xhttp_path = params.path and UrlDecode(params.path) or "/"
  861. -- 检查 extra 参数是否存在且非空
  862. result.enable_xhttp_extra = (params.extra and params.extra ~= "") and "1" or nil
  863. result.xhttp_extra = (params.extra and params.extra ~= "") and params.extra or nil
  864. -- 尝试解析 JSON 数据
  865. local success, Data = pcall(jsonParse, params.extra or "")
  866. if success and type(Data) == "table" then
  867. local address = (Data.extra and Data.extra.downloadSettings and Data.extra.downloadSettings.address)
  868. or (Data.downloadSettings and Data.downloadSettings.address)
  869. result.download_address = address and address ~= "" and address or nil
  870. else
  871. -- 如果解析失败,清空下载地址
  872. result.download_address = nil
  873. end
  874. -- make it compatible with bullshit, "h2" transport is non-existent at all
  875. elseif result.transport == "http" or result.transport == "h2" then
  876. result.transport = "h2"
  877. result.h2_host = params.host and UrlDecode(params.host) or nil
  878. result.h2_path = params.path and UrlDecode(params.path) or nil
  879. elseif result.transport == "kcp" then
  880. result.kcp_guise = params.headerType or "none"
  881. result.seed = params.seed
  882. result.mtu = 1350
  883. result.tti = 50
  884. result.uplink_capacity = 5
  885. result.downlink_capacity = 20
  886. result.read_buffer_size = 2
  887. result.write_buffer_size = 2
  888. elseif result.transport == "quic" then
  889. result.quic_guise = params.headerType or "none"
  890. result.quic_security = params.quicSecurity or "none"
  891. result.quic_key = params.key
  892. elseif result.transport == "grpc" then
  893. result.serviceName = params.serviceName
  894. result.grpc_mode = params.mode or "gun"
  895. elseif result.transport == "tcp" or result.transport == "raw" then
  896. result.tcp_guise = params.headerType or "none"
  897. if result.tcp_guise == "http" then
  898. result.tcp_host = params.host and UrlDecode(params.host) or nil
  899. result.tcp_path = params.path and UrlDecode(params.path) or nil
  900. end
  901. end
  902. end
  903. if not result.alias then
  904. if result.server and result.server_port then
  905. result.alias = result.server .. ':' .. result.server_port
  906. else
  907. result.alias = "NULL"
  908. end
  909. end
  910. -- alias 不参与 hashkey 计算
  911. local alias = result.alias
  912. result.alias = nil
  913. local switch_enable = result.switch_enable
  914. result.switch_enable = nil
  915. result.hashkey = md5(jsonStringify(result))
  916. result.alias = alias
  917. result.switch_enable = switch_enable
  918. return result
  919. end
  920. -- 计算、储存和读取 md5 值
  921. -- 计算 md5 值
  922. local function md5_string(data)
  923. -- 生成临时文件名
  924. local tmp = "/tmp/md5_tmp_" .. os.time() .. "_" .. math.random(1000,9999) -- os.time 保证每秒唯一,但不足以避免全部冲突;math.random(1000,9999) 增加文件名唯一性,避免并发时冲突
  925. nixio.fs.writefile(tmp, data) -- 写入临时文件
  926. -- 执行 md5sum 命令
  927. local md5 = luci.sys.exec(string.format('md5sum "%s" 2>/dev/null | cut -d " " -f1', tmp)):gsub("%s+", "")
  928. nixio.fs.remove(tmp) -- 删除临时文件
  929. return md5
  930. end
  931. -- 返回临时文件路径,用来存储订阅的 MD5 值,以便判断订阅内容是否发生变化。
  932. local function get_md5_path(groupHash)
  933. return "/tmp/sub_md5_" .. groupHash
  934. end
  935. -- 读取上次订阅时记录的 MD5 值,以便和当前内容的 MD5 进行对比,从而判断是否需要更新节点列表。
  936. local function read_old_md5(groupHash)
  937. local path = get_md5_path(groupHash)
  938. if nixio.fs.access(path) then
  939. return trim(nixio.fs.readfile(path) or "")
  940. end
  941. return ""
  942. end
  943. -- 将订阅分组最新内容的 MD5 值保存到对应的临时文件中,以便下次更新时进行对比。
  944. local function write_new_md5(groupHash, md5)
  945. nixio.fs.writefile(get_md5_path(groupHash), md5)
  946. end
  947. -- curl
  948. local function curl(url)
  949. -- 清理 URL 中的隐藏字符
  950. url = url:gsub("%s+$", ""):gsub("^%s+", ""):gsub("%z", "")
  951. -- 构建curl命令(确保 user_agent 为空时不添加 -A 参数)
  952. local cmd = string.format(
  953. 'curl -sSL --connect-timeout 20 --max-time 30 --retry 3 %s --insecure --location "%s"',
  954. user_agent ~= "" and ('-A "' .. user_agent .. '"') or "", -- 添加 or "" 处理 nil 情况
  955. url:gsub('["$`\\]', '\\%0') -- 安全转义
  956. )
  957. local stdout = luci.sys.exec(cmd)
  958. stdout = trim(stdout)
  959. local md5 = md5_string(stdout)
  960. return stdout, md5
  961. end
  962. local function check_filer(result)
  963. do
  964. -- 过滤的关键词列表
  965. local filter_word = split(filter_words, "/")
  966. -- 保留的关键词列表
  967. local check_save = false
  968. if save_words ~= nil and save_words ~= "" and save_words ~= "NULL" then
  969. check_save = true
  970. end
  971. local save_word = split(save_words, "/")
  972. -- 检查结果
  973. local filter_result = false
  974. local save_result = true
  975. -- 检查是否存在过滤关键词
  976. for i, v in pairs(filter_word) do
  977. if tostring(result.alias):find(v, nil, true) then
  978. filter_result = true
  979. end
  980. end
  981. -- 检查是否打开了保留关键词检查,并且进行过滤
  982. if check_save == true then
  983. for i, v in pairs(save_word) do
  984. if tostring(result.alias):find(v, nil, true) then
  985. save_result = false
  986. end
  987. end
  988. else
  989. save_result = false
  990. end
  991. -- 不等时返回
  992. if filter_result == true or save_result == true then
  993. return true
  994. else
  995. return false
  996. end
  997. end
  998. end
  999. -- 加载订阅未变化的节点用于防止被误删
  1000. local function loadOldNodes(groupHash)
  1001. local nodes = {}
  1002. cache[groupHash] = {}
  1003. nodeResult[#nodeResult + 1] = nodes
  1004. local index = #nodeResult
  1005. ucic:foreach(name, uciType, function(s)
  1006. if s.grouphashkey == groupHash and s.hashkey then
  1007. local section = setmetatable({}, {__index = s})
  1008. nodes[s.hashkey] = section
  1009. cache[groupHash][s.hashkey] = section
  1010. end
  1011. end)
  1012. end
  1013. local execute = function()
  1014. -- exec
  1015. do
  1016. --local updated = false
  1017. local service_stopped = false
  1018. for k, url in ipairs(subscribe_url) do
  1019. local raw, new_md5 = curl(url)
  1020. log("raw 长度: "..#raw)
  1021. local groupHash = md5(url)
  1022. local old_md5 = read_old_md5(groupHash)
  1023. log("处理订阅: " .. url)
  1024. log("groupHash: " .. groupHash)
  1025. log("old_md5: " .. tostring(old_md5))
  1026. log("new_md5: " .. tostring(new_md5))
  1027. if #raw > 0 then
  1028. if old_md5 and new_md5 == old_md5 then
  1029. log("订阅未变化, 跳过无需更新的订阅: " .. url)
  1030. -- 防止 diff 阶段误删未更新订阅节点
  1031. loadOldNodes(groupHash)
  1032. --ucic:foreach(name, uciType, function(s)
  1033. -- if s.grouphashkey == groupHash and s.hashkey then
  1034. -- cache[groupHash][s.hashkey] = s
  1035. -- tinsert(nodeResult[index], s)
  1036. -- end
  1037. --end)
  1038. else
  1039. updated = true
  1040. -- 保存更新后的 MD5 值到以 groupHash 为标识的临时文件中,用于下次订阅更新时进行对比
  1041. write_new_md5(groupHash, new_md5)
  1042. -- 暂停服务(仅当 MD5 有变化时才执行)
  1043. if proxy == '0' and not service_stopped then
  1044. log('服务正在暂停')
  1045. luci.sys.init.stop(name)
  1046. service_stopped = true
  1047. end
  1048. cache[groupHash] = {}
  1049. tinsert(nodeResult, {})
  1050. local index = #nodeResult
  1051. local nodes, szType
  1052. -- SSD 似乎是这种格式 ssd:// 开头的
  1053. if raw:find('ssd://') then
  1054. szType = 'ssd'
  1055. local nEnd = select(2, raw:find('ssd://'))
  1056. nodes = base64Decode(raw:sub(nEnd + 1, #raw))
  1057. nodes = jsonParse(nodes)
  1058. local extra = {
  1059. airport = nodes.airport,
  1060. port = nodes.port,
  1061. encryption = nodes.encryption,
  1062. password = nodes.password
  1063. }
  1064. local servers = {}
  1065. -- SS里面包着 干脆直接这样
  1066. for _, server in ipairs(nodes.servers or {}) do
  1067. tinsert(servers, setmetatable(server, {__index = extra}))
  1068. end
  1069. nodes = servers
  1070. -- SS SIP008 直接使用 Json 格式
  1071. elseif jsonParse(raw) then
  1072. nodes = jsonParse(raw).servers or jsonParse(raw)
  1073. if nodes[1] and nodes[1].server and nodes[1].method then
  1074. szType = 'sip008'
  1075. end
  1076. -- 其他 base64 格式
  1077. else
  1078. -- ssd 外的格式
  1079. nodes = split(base64Decode(raw):gsub("\r\n", "\n"), "\n")
  1080. end
  1081. for _, v in ipairs(nodes) do
  1082. if v and not string.match(v, "^%s*$") then
  1083. xpcall(function()
  1084. local result
  1085. if szType then
  1086. result = processData(szType, v)
  1087. elseif not szType then
  1088. local node = trim(v)
  1089. -- 一些奇葩的链接用"&amp;"、"&lt;"当做"&","#"前后带空格
  1090. local link = node:gsub("&[a-zA-Z]+;", "&"):gsub("%s*#%s*", "#")
  1091. local dat = split(link, "://")
  1092. if dat and dat[1] and dat[2] then
  1093. local dat3 = ""
  1094. if dat[3] then
  1095. dat3 = "://" .. dat[3]
  1096. end
  1097. if dat[1] == 'ss' or dat[1] == 'trojan' then
  1098. result = processData(dat[1], dat[2] .. dat3)
  1099. else
  1100. result = processData(dat[1], base64Decode(dat[2]))
  1101. end
  1102. end
  1103. else
  1104. log('跳过未知类型: ' .. szType)
  1105. end
  1106. -- log(result)
  1107. if result then
  1108. -- 中文做地址的 也没有人拿中文域名搞,就算中文域也有Puny Code SB 机场
  1109. if not result.server or not result.server_port
  1110. or result.alias == "NULL"
  1111. or check_filer(result)
  1112. or result.server:match("[^0-9a-zA-Z%-_%.%s]")
  1113. or cache[groupHash][result.hashkey]
  1114. then
  1115. log('丢弃无效节点: ' .. result.alias)
  1116. else
  1117. -- log('成功解析: ' .. result.type ..' 节点, ' .. result.alias)
  1118. result.grouphashkey = groupHash
  1119. tinsert(nodeResult[index], result)
  1120. cache[groupHash][result.hashkey] = nodeResult[index][#nodeResult[index]]
  1121. end
  1122. end
  1123. end, function(err)
  1124. log(string.format("解析节点出错: %s\n原始数据: %s", tostring(err), tostring(v)))
  1125. end)
  1126. end
  1127. end
  1128. log('成功解析节点数量: ' .. #nodes)
  1129. end
  1130. else
  1131. log(url .. ': 获取内容为空')
  1132. end
  1133. end
  1134. end
  1135. -- 输出日志并判断是否需要进行 diff
  1136. if not updated then
  1137. log("订阅未变化,无需更新节点信息。")
  1138. log('保留手动添加的节点。')
  1139. return
  1140. end
  1141. -- diff
  1142. do
  1143. if next(nodeResult) == nil then
  1144. log("更新失败,没有可用的节点信息")
  1145. if proxy == '0' then
  1146. luci.sys.init.start(name)
  1147. log('订阅失败, 恢复服务')
  1148. end
  1149. return
  1150. end
  1151. local add, del = 0, 0
  1152. ucic:foreach(name, uciType, function(old)
  1153. if old.grouphashkey or old.hashkey then -- 没有 hash 的不参与删除
  1154. if not nodeResult[old.grouphashkey] or not nodeResult[old.grouphashkey][old.hashkey] then
  1155. ucic:delete(name, old['.name'])
  1156. del = del + 1
  1157. else
  1158. local dat = nodeResult[old.grouphashkey][old.hashkey]
  1159. ucic:tset(name, old['.name'], dat)
  1160. -- 标记一下
  1161. setmetatable(nodeResult[old.grouphashkey][old.hashkey], {__index = {_ignore = true}})
  1162. end
  1163. else
  1164. if not old.alias then
  1165. if old.server or old.server_port then
  1166. old.alias = old.server .. ':' .. old.server_port
  1167. log('忽略手动添加的节点: ' .. old.alias)
  1168. else
  1169. ucic:delete(name, old['.name'])
  1170. end
  1171. else
  1172. log('忽略手动添加的节点: ' .. old.alias)
  1173. end
  1174. end
  1175. end)
  1176. for k, v in ipairs(nodeResult) do
  1177. for kk, vv in ipairs(v) do
  1178. if not vv._ignore then
  1179. local section = ucic:add(name, uciType)
  1180. ucic:tset(name, section, vv)
  1181. ucic:set(name, section, "switch_enable", switch)
  1182. add = add + 1
  1183. end
  1184. end
  1185. end
  1186. ucic:commit(name)
  1187. -- 如果原有服务器节点已经不见了就尝试换为第一个节点
  1188. local globalServer = ucic:get_first(name, 'global', 'global_server', '')
  1189. if globalServer ~= "nil" then
  1190. local firstServer = ucic:get_first(name, uciType)
  1191. if firstServer then
  1192. if not ucic:get(name, globalServer) then
  1193. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  1194. ucic:commit(name)
  1195. ucic:set(name, ucic:get_first(name, 'global'), 'global_server', firstServer)
  1196. ucic:commit(name)
  1197. log('当前主服务器节点已被删除,正在自动更换为第一个节点。')
  1198. luci.sys.call("/etc/init.d/" .. name .. " start > /dev/null 2>&1 &")
  1199. else
  1200. log('维持当前主服务器节点。')
  1201. luci.sys.call("/etc/init.d/" .. name .. " restart > /dev/null 2>&1 &")
  1202. end
  1203. else
  1204. log('没有服务器节点了,停止服务')
  1205. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  1206. end
  1207. end
  1208. log('新增节点数量: ' .. add .. ', 删除节点数量: ' .. del)
  1209. log('订阅更新成功')
  1210. end
  1211. end
  1212. if subscribe_url and #subscribe_url > 0 then
  1213. xpcall(execute, function(e)
  1214. log(e)
  1215. log(debug.traceback())
  1216. log('发生错误, 正在恢复服务')
  1217. local firstServer = ucic:get_first(name, uciType)
  1218. if firstServer then
  1219. luci.sys.call("/etc/init.d/" .. name .. " restart > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  1220. log('重启服务成功')
  1221. else
  1222. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  1223. log('停止服务成功')
  1224. end
  1225. end)
  1226. end