subscribe.lua 46 KB

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