subscribe.lua 45 KB

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