subscribe.lua 43 KB

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