subscribe.lua 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  1. #!/usr/bin/lua
  2. ------------------------------------------------
  3. -- This file is part of the luci-app-ssr-plus subscribe.lua
  4. -- @author William Chan <[email protected]>
  5. ------------------------------------------------
  6. require "luci.model.uci"
  7. require "nixio"
  8. require "luci.util"
  9. require "luci.sys"
  10. require "luci.jsonc"
  11. require "luci.model.ipkg"
  12. -- these global functions are accessed all the time by the event handler
  13. -- so caching them is worth the effort
  14. local tinsert = table.insert
  15. local ssub, slen, schar, sbyte, sformat, sgsub = string.sub, string.len, string.char, string.byte, string.format, string.gsub
  16. local jsonParse, jsonStringify = luci.jsonc.parse, luci.jsonc.stringify
  17. local b64decode = nixio.bin.b64decode
  18. local URL = require "url"
  19. local cache = {}
  20. local nodeResult = setmetatable({}, {__index = cache}) -- update result
  21. local name = 'shadowsocksr'
  22. local uciType = 'servers'
  23. local ucic = require "luci.model.uci".cursor()
  24. local proxy = ucic:get_first(name, 'server_subscribe', 'proxy', '0')
  25. local switch = ucic:get_first(name, 'server_subscribe', 'switch', '1')
  26. local allow_insecure = ucic:get_first(name, 'server_subscribe', 'allow_insecure', '0')
  27. local subscribe_url = ucic:get_first(name, 'server_subscribe', 'subscribe_url', {})
  28. local filter_words = ucic:get_first(name, 'server_subscribe', 'filter_words', '过期时间/剩余流量')
  29. local save_words = ucic:get_first(name, 'server_subscribe', 'save_words', '')
  30. local user_agent = ucic:get_first(name, 'server_subscribe', 'user_agent', 'v2rayN/9.99')
  31. -- 读取 ss_type 设置
  32. local ss_type = ucic:get_first(name, 'server_subscribe', 'ss_type', 'ss-rust')
  33. -- 根据 ss_type 选择对应的程序
  34. local ss_program = ""
  35. if ss_type == "ss-rust" then
  36. ss_program = "sslocal" -- Rust 版本使用 sslocal
  37. elseif ss_type == "ss-libev" then
  38. ss_program = "ss-redir" -- Libev 版本使用 ss-redir
  39. end
  40. local v2_ss = luci.sys.exec('type -t -p ' .. ss_program .. ' 2>/dev/null') ~= "" and "ss" or "v2ray"
  41. local has_ss_type = luci.sys.exec('type -t -p ' .. ss_program .. ' 2>/dev/null') ~= "" and ss_type
  42. local v2_tj = luci.sys.exec('type -t -p trojan') ~= "" and "trojan" or "v2ray"
  43. local hy2_type = luci.sys.exec('type -t -p hysteria') ~= "" and "hysteria2"
  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. result.alias = url.fragment and UrlDecode(url.fragment) or nil
  190. result.type = hy2_type
  191. result.server = url.host
  192. result.server_port = url.port
  193. if params.protocol then
  194. result.flag_transport = "1"
  195. result.transport_protocol = params.protocol or "udp"
  196. end
  197. result.hy2_auth = url.user
  198. result.uplink_capacity = tonumber((params.upmbps or ""):match("^(%d+)")) or nil
  199. result.downlink_capacity = tonumber((params.downmbps or ""):match("^(%d+)")) or nil
  200. if params.obfs and params.obfs ~= "none" then
  201. result.flag_obfs = "1"
  202. result.obfs_type = params.obfs
  203. result.salamander = params["obfs-password"] or params["obfs_password"]
  204. end
  205. if params.sni then
  206. result.tls = "1"
  207. result.tls_host = params.sni
  208. end
  209. if params.insecure then
  210. result.insecure = "1"
  211. if params.sni then
  212. result.pinsha256 = params.pinSHA256
  213. end
  214. end
  215. if params.mport then
  216. result.flag_port_hopping = "1"
  217. result.port_range = params.mport
  218. end
  219. elseif szType == 'ssr' then
  220. local dat = split(content, "/%?")
  221. local hostInfo = split(dat[1], ':')
  222. result.type = 'ssr'
  223. result.server = hostInfo[1]
  224. result.server_port = hostInfo[2]
  225. result.protocol = hostInfo[3]
  226. result.encrypt_method = hostInfo[4]
  227. result.obfs = hostInfo[5]
  228. result.password = base64Decode(hostInfo[6])
  229. local params = {}
  230. for _, v in pairs(split(dat[2], '&')) do
  231. local t = split(v, '=')
  232. params[t[1]] = t[2]
  233. end
  234. result.obfs_param = base64Decode(params.obfsparam)
  235. result.protocol_param = base64Decode(params.protoparam)
  236. local group = base64Decode(params.group)
  237. if group then
  238. result.alias = "[" .. group .. "] "
  239. end
  240. result.alias = result.alias .. base64Decode(params.remarks)
  241. elseif szType == "vmess" then
  242. -- 解析正常节点
  243. local success, info = pcall(jsonParse, content)
  244. if not success or type(info) ~= "table" then
  245. return nil
  246. end
  247. -- 处理有效数据
  248. result.type = 'v2ray'
  249. result.v2ray_protocol = 'vmess'
  250. result.server = info.add
  251. result.server_port = info.port
  252. if info.net == "tcp" then
  253. info.net = "raw"
  254. end
  255. result.transport = info.net
  256. result.alter_id = info.aid
  257. result.vmess_id = info.id
  258. result.alias = info.ps
  259. -- result.mux = 1
  260. -- result.concurrency = 8
  261. if info.net == 'ws' then
  262. result.ws_host = info.host
  263. result.ws_path = info.path
  264. end
  265. if info.net == 'httpupgrade' then
  266. result.httpupgrade_host = info.host
  267. result.httpupgrade_path = info.path
  268. end
  269. if info.net == 'splithttp' then
  270. result.splithttp_host = info.host
  271. result.splithttp_path = info.path
  272. end
  273. if info.net == 'xhttp' then
  274. result.xhttp_mode = info.mode
  275. result.xhttp_host = info.host
  276. result.xhttp_path = info.path
  277. -- 检查 extra 参数是否存在且非空
  278. result.enable_xhttp_extra = (info.extra and info.extra ~= "") and "1" or nil
  279. result.xhttp_extra = (info.extra and info.extra ~= "") and info.extra or nil
  280. -- 尝试解析 JSON 数据
  281. local success, Data = pcall(jsonParse, info.extra)
  282. if success and Data then
  283. local address = (Data.extra and Data.extra.downloadSettings and Data.extra.downloadSettings.address)
  284. or (Data.downloadSettings and Data.downloadSettings.address)
  285. result.download_address = address and address ~= "" and address or nil
  286. else
  287. -- 如果解析失败,清空下载地址
  288. result.download_address = nil
  289. end
  290. end
  291. if info.net == 'h2' then
  292. result.h2_host = info.host
  293. result.h2_path = info.path
  294. end
  295. if info.net == 'raw' or info.net == 'tcp' then
  296. if info.type and info.type ~= "http" then
  297. info.type = "none"
  298. end
  299. result.tcp_guise = info.type
  300. result.http_host = info.host
  301. result.http_path = info.path
  302. end
  303. if info.net == 'kcp' then
  304. result.kcp_guise = info.type
  305. result.mtu = 1350
  306. result.tti = 50
  307. result.uplink_capacity = 5
  308. result.downlink_capacity = 20
  309. result.read_buffer_size = 2
  310. result.write_buffer_size = 2
  311. end
  312. if info.net == 'grpc' then
  313. if info.path then
  314. result.serviceName = info.path
  315. elseif info.serviceName then
  316. result.serviceName = info.serviceName
  317. end
  318. end
  319. if info.net == 'quic' then
  320. result.quic_guise = info.type
  321. result.quic_key = info.key
  322. result.quic_security = info.securty
  323. end
  324. if info.security then
  325. result.security = info.security
  326. end
  327. if info.tls == "tls" or info.tls == "1" then
  328. result.tls = "1"
  329. if info.alpn and info.alpn ~= "" then
  330. result.xhttp_alpn = info.alpn
  331. end
  332. if info.sni and info.sni ~= "" then
  333. result.tls_host = info.sni
  334. elseif info.host then
  335. result.tls_host = info.host
  336. end
  337. result.insecure = allow_insecure
  338. else
  339. result.tls = "0"
  340. end
  341. elseif szType == "ss" then
  342. local idx_sp = content:find("#") or 0
  343. local alias = ""
  344. if idx_sp > 0 then
  345. alias = UrlDecode(content:sub(idx_sp + 1))
  346. end
  347. local info = content:sub(1, idx_sp > 0 and idx_sp - 1 or #content)
  348. -- 拆 base64 主体和 ? 参数部分
  349. local uri_main, query_str = info:match("^([^?]+)%??(.*)$")
  350. --log("SS 节点格式:", uri_main)
  351. local params = {}
  352. if query_str and query_str ~= "" then
  353. for _, v in ipairs(split(query_str, '&')) do
  354. local t = split(v, '=')
  355. if #t >= 2 then
  356. params[t[1]] = UrlDecode(t[2])
  357. end
  358. end
  359. end
  360. local is_old_format = uri_main:find("@") and not uri_main:find("://.*@")
  361. local base64_str, host_port, userinfo, server, port, method, password
  362. if is_old_format then
  363. -- 旧格式:base64(method:pass)@host:port
  364. base64_str, host_port = uri_main:match("^([^@]+)@(.-)$")
  365. log("SS 节点旧格式解析:", base64_str)
  366. if not base64_str or not host_port then
  367. log("SS 节点旧格式解析失败:", uri_main)
  368. return nil
  369. end
  370. local decoded = base64Decode(UrlDecode(base64_str))
  371. if not decoded then
  372. log("SS base64 解码失败(旧格式):", base64_str)
  373. return nil
  374. end
  375. userinfo = decoded
  376. else
  377. -- 新格式:base64(method:pass@host:port)
  378. local decoded = base64Decode(UrlDecode(uri_main))
  379. if not decoded then
  380. log("SS base64 解码失败(新格式):", uri_main)
  381. return nil
  382. end
  383. userinfo, host_port = decoded:match("^(.-)@(.-)$")
  384. if not userinfo or not host_port then
  385. log("SS 解码内容缺失 @ 分隔:", decoded)
  386. return nil
  387. end
  388. end
  389. -- 解析加密方式和密码(允许密码包含冒号)
  390. local split_pos = userinfo:find(":")
  391. if not split_pos then
  392. log("SS 用户信息格式错误:", userinfo)
  393. return nil
  394. end
  395. method = userinfo:sub(1, split_pos - 1)
  396. password = userinfo:sub(split_pos + 1)
  397. -- 解析服务器地址和端口(兼容 IPv6)
  398. if host_port:find("^%[.*%]:%d+$") then
  399. server, port = host_port:match("^%[(.*)%]:(%d+)$")
  400. else
  401. server, port = host_port:match("^(.-):(%d+)$")
  402. end
  403. if not server or not port then
  404. log("SS 节点服务器信息格式错误:", host_port)
  405. return nil
  406. end
  407. -- 填充 result
  408. result.alias = alias
  409. result.type = v2_ss
  410. result.v2ray_protocol = (v2_ss == "v2ray") and "shadowsocks" or nil
  411. result.has_ss_type = has_ss_type
  412. result.encrypt_method_ss = method
  413. result.password = password
  414. result.server = server
  415. result.server_port = port
  416. -- 插件处理
  417. if params.plugin then
  418. local plugin_info = UrlDecode(params.plugin)
  419. local idx_pn = plugin_info:find(";")
  420. if idx_pn then
  421. result.plugin = plugin_info:sub(1, idx_pn - 1)
  422. result.plugin_opts = plugin_info:sub(idx_pn + 1, #plugin_info)
  423. else
  424. result.plugin = plugin_info
  425. result.plugin_opts = ""
  426. end
  427. -- 部分机场下发的插件名为 simple-obfs,这里应该改为 obfs-local
  428. if result.plugin == "simple-obfs" then
  429. result.plugin = "obfs-local"
  430. end
  431. -- 如果插件不为 none,确保 enable_plugin 为 1
  432. if result.plugin ~= "none" and result.plugin ~= "" then
  433. result.enable_plugin = 1
  434. end
  435. elseif has_ss_type and has_ss_type ~= "ss-libev" then
  436. if params["shadow-tls"] then
  437. -- 特别处理 shadow-tls 作为插件
  438. -- log("原始 shadow-tls 参数:", params["shadow-tls"])
  439. local decoded_tls = base64Decode(UrlDecode(params["shadow-tls"]))
  440. --log("SS 节点 shadow-tls 解码后:", decoded_tls or "nil")
  441. if decoded_tls then
  442. local ok, st = pcall(jsonParse, decoded_tls)
  443. if ok and st then
  444. result.plugin = "shadow-tls"
  445. result.enable_plugin = 1
  446. local version_flag = ""
  447. if st.version and tonumber(st.version) then
  448. version_flag = string.format("v%s=1;", st.version)
  449. end
  450. -- 合成 plugin_opts 格式:v%s=1;host=xxx;password=xxx
  451. result.plugin_opts = string.format("%shost=%s;passwd=%s",
  452. version_flag,
  453. st.host or "",
  454. st.password or "")
  455. else
  456. log("shadow-tls JSON 解析失败")
  457. end
  458. end
  459. end
  460. else
  461. if params["shadow-tls"] then
  462. log("错误:ShadowSocks-libev 不支持使用 shadow-tls 插件")
  463. return nil, "ShadowSocks-libev 不支持使用 shadow-tls 插件"
  464. end
  465. end
  466. -- 检查加密方法是否受支持
  467. if not checkTabValue(encrypt_methods_ss)[method] then
  468. -- 1202 年了还不支持 SS AEAD 的屑机场
  469. -- log("不支持的SS加密方法:", method)
  470. result.server = nil
  471. end
  472. elseif szType == "sip008" then
  473. result.type = v2_ss
  474. result.v2ray_protocol = (v2_ss == "v2ray") and "shadowsocks" or nil
  475. result.has_ss_type = has_ss_type
  476. result.server = content.server
  477. result.server_port = content.server_port
  478. result.password = content.password
  479. result.encrypt_method_ss = content.method
  480. result.plugin = content.plugin
  481. result.plugin_opts = content.plugin_opts
  482. result.alias = content.remarks
  483. if not checkTabValue(encrypt_methods_ss)[content.method] then
  484. result.server = nil
  485. end
  486. elseif szType == "ssd" then
  487. result.type = v2_ss
  488. result.v2ray_protocol = (v2_ss == "v2ray") and "shadowsocks" or nil
  489. result.has_ss_type = has_ss_type
  490. result.server = content.server
  491. result.server_port = content.port
  492. result.password = content.password
  493. result.encrypt_method_ss = content.method
  494. result.plugin_opts = content.plugin_options
  495. result.alias = "[" .. content.airport .. "] " .. content.remarks
  496. if content.plugin == "simple-obfs" then
  497. result.plugin = "obfs-local"
  498. else
  499. result.plugin = content.plugin
  500. end
  501. if not checkTabValue(encrypt_methods_ss)[content.encryption] then
  502. result.server = nil
  503. end
  504. elseif szType == "trojan" then
  505. local params = {}
  506. local idx_sp = 0
  507. local alias = ""
  508. -- 提取别名(如果存在)
  509. if content:find("#") then
  510. idx_sp = content:find("#")
  511. alias = content:sub(idx_sp + 1, -1)
  512. end
  513. local info = content:sub(1, idx_sp > 0 and idx_sp - 1 or #content)
  514. local hostInfo = split(info, "@")
  515. -- 基础验证
  516. if #hostInfo < 2 then
  517. --log("Trojan节点格式错误: 缺少@符号")
  518. return nil
  519. end
  520. local userinfo = hostInfo[1]
  521. local hostPort = hostInfo[2]
  522. -- 分离服务器地址和端口
  523. local hostParts = split(hostPort, ":")
  524. local server = hostParts[1]
  525. local port = hostParts[2]
  526. -- 验证服务器地址和端口
  527. if #hostParts < 2 then
  528. --log("Trojan节点格式错误: 缺少端口号")
  529. return nil
  530. end
  531. result.alias = UrlDecode(alias)
  532. result.type = v2_tj
  533. result.v2ray_protocol = "trojan"
  534. result.server = server
  535. result.password = userinfo
  536. -- 默认设置
  537. -- 按照官方的建议 默认验证ssl证书
  538. result.insecure = "0"
  539. result.tls = "1"
  540. -- 解析查询参数(如果存在)
  541. if port:find("?") then
  542. local queryParts = split(port, "?")
  543. result.server_port = queryParts[1]
  544. -- 解析查询参数
  545. for _, v in pairs(split(queryParts[2], '&')) do
  546. local t = split(v, '=')
  547. if #t >= 2 then
  548. params[t[1]] = t[2]
  549. end
  550. end
  551. -- 处理参数
  552. if params.alpn then
  553. -- 处理 alpn 参数
  554. result.xhttp_alpn = params.alpn
  555. end
  556. if params.sni then
  557. -- 未指定peer(sni)默认使用remote addr
  558. result.tls_host = params.sni
  559. end
  560. if params.allowInsecure then
  561. -- 处理 insecure 参数
  562. result.insecure = params.allowInsecure
  563. end
  564. else
  565. result.server_port = port
  566. end
  567. if v2_tj ~= "trojan" then
  568. if params.fp then
  569. -- 处理 fingerprint 参数
  570. result.fingerprint = params.fp
  571. end
  572. -- 处理传输协议
  573. result.transport = params.type or "tcp" -- 默认传输协议为 tcp
  574. if result.transport == "tcp" then
  575. result.transport = "raw"
  576. end
  577. if result.transport == "ws" then
  578. result.ws_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  579. result.ws_path = params.path and UrlDecode(params.path) or "/"
  580. elseif result.transport == "httpupgrade" then
  581. result.httpupgrade_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  582. result.httpupgrade_path = params.path and UrlDecode(params.path) or "/"
  583. elseif result.transport == "splithttp" then
  584. result.splithttp_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  585. result.splithttp_path = params.path and UrlDecode(params.path) or "/"
  586. elseif result.transport == "xhttp" then
  587. result.xhttp_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  588. result.xhttp_mode = params.mode or "auto"
  589. result.xhttp_path = params.path and UrlDecode(params.path) or "/"
  590. -- 检查 extra 参数是否存在且非空
  591. result.enable_xhttp_extra = (params.extra and params.extra ~= "") and "1" or nil
  592. result.xhttp_extra = (params.extra and params.extra ~= "") and params.extra or nil
  593. -- 尝试解析 JSON 数据
  594. local success, Data = pcall(jsonParse, params.extra)
  595. if success and Data then
  596. local address = (Data.extra and Data.extra.downloadSettings and Data.extra.downloadSettings.address)
  597. or (Data.downloadSettings and Data.downloadSettings.address)
  598. result.download_address = address and address ~= "" and address or nil
  599. else
  600. -- 如果解析失败,清空下载地址
  601. result.download_address = nil
  602. end
  603. elseif result.transport == "http" or result.transport == "h2" then
  604. result.transport = "h2"
  605. result.h2_host = params.host and UrlDecode(params.host) or nil
  606. result.h2_path = params.path and UrlDecode(params.path) or nil
  607. elseif result.transport == "kcp" then
  608. result.kcp_guise = params.headerType or "none"
  609. result.seed = params.seed
  610. result.mtu = 1350
  611. result.tti = 50
  612. result.uplink_capacity = 5
  613. result.downlink_capacity = 20
  614. result.read_buffer_size = 2
  615. result.write_buffer_size = 2
  616. elseif result.transport == "quic" then
  617. result.quic_guise = params.headerType or "none"
  618. result.quic_security = params.quicSecurity or "none"
  619. result.quic_key = params.key
  620. elseif result.transport == "grpc" then
  621. result.serviceName = params.serviceName
  622. result.grpc_mode = params.mode or "gun"
  623. elseif result.transport == "tcp" or result.transport == "raw" then
  624. result.tcp_guise = params.headerType and params.headerType ~= "" and params.headerType or "none"
  625. if result.tcp_guise == "http" then
  626. result.tcp_host = params.host and UrlDecode(params.host) or nil
  627. result.tcp_path = params.path and UrlDecode(params.path) or nil
  628. end
  629. end
  630. end
  631. elseif szType == "vless" then
  632. local url = URL.parse("http://" .. content)
  633. local params = url.query
  634. result.alias = url.fragment and UrlDecode(url.fragment) or nil
  635. result.type = "v2ray"
  636. result.v2ray_protocol = "vless"
  637. result.server = url.host
  638. result.server_port = url.port
  639. result.vmess_id = url.user
  640. result.vless_encryption = params.encryption or "none"
  641. result.transport = params.type or "tcp"
  642. result.tls = (params.security == "tls" or params.security == "xtls") and "1" or "0"
  643. result.xhttp_alpn = params.alpn or ""
  644. result.tls_host = params.sni
  645. result.tls_flow = (params.security == "tls" or params.security == "reality") and params.flow or nil
  646. result.fingerprint = params.fp
  647. result.reality = (params.security == "reality") and "1" or "0"
  648. result.reality_publickey = params.pbk and UrlDecode(params.pbk) or nil
  649. result.reality_shortid = params.sid
  650. result.reality_spiderx = params.spx and UrlDecode(params.spx) or nil
  651. if result.transport == "ws" then
  652. result.ws_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  653. result.ws_path = params.path and UrlDecode(params.path) or "/"
  654. elseif result.transport == "httpupgrade" then
  655. result.httpupgrade_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  656. result.httpupgrade_path = params.path and UrlDecode(params.path) or "/"
  657. elseif result.transport == "splithttp" then
  658. result.splithttp_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  659. result.splithttp_path = params.path and UrlDecode(params.path) or "/"
  660. elseif result.transport == "xhttp" then
  661. result.xhttp_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  662. result.xhttp_mode = params.mode or "auto"
  663. result.xhttp_path = params.path and UrlDecode(params.path) or "/"
  664. -- 检查 extra 参数是否存在且非空
  665. result.enable_xhttp_extra = (params.extra and params.extra ~= "") and "1" or nil
  666. result.xhttp_extra = (params.extra and params.extra ~= "") and params.extra or nil
  667. -- 尝试解析 JSON 数据
  668. local success, Data = pcall(jsonParse, params.extra)
  669. if success and Data then
  670. local address = (Data.extra and Data.extra.downloadSettings and Data.extra.downloadSettings.address)
  671. or (Data.downloadSettings and Data.downloadSettings.address)
  672. result.download_address = address and address ~= "" and address or nil
  673. else
  674. -- 如果解析失败,清空下载地址
  675. result.download_address = nil
  676. end
  677. -- make it compatible with bullshit, "h2" transport is non-existent at all
  678. elseif result.transport == "http" or result.transport == "h2" then
  679. result.transport = "h2"
  680. result.h2_host = params.host and UrlDecode(params.host) or nil
  681. result.h2_path = params.path and UrlDecode(params.path) or nil
  682. elseif result.transport == "kcp" then
  683. result.kcp_guise = params.headerType or "none"
  684. result.seed = params.seed
  685. result.mtu = 1350
  686. result.tti = 50
  687. result.uplink_capacity = 5
  688. result.downlink_capacity = 20
  689. result.read_buffer_size = 2
  690. result.write_buffer_size = 2
  691. elseif result.transport == "quic" then
  692. result.quic_guise = params.headerType or "none"
  693. result.quic_security = params.quicSecurity or "none"
  694. result.quic_key = params.key
  695. elseif result.transport == "grpc" then
  696. result.serviceName = params.serviceName
  697. result.grpc_mode = params.mode or "gun"
  698. elseif result.transport == "tcp" or result.transport == "raw" then
  699. result.tcp_guise = params.headerType or "none"
  700. if result.tcp_guise == "http" then
  701. result.tcp_host = params.host and UrlDecode(params.host) or nil
  702. result.tcp_path = params.path and UrlDecode(params.path) or nil
  703. end
  704. end
  705. end
  706. if not result.alias then
  707. if result.server and result.server_port then
  708. result.alias = result.server .. ':' .. result.server_port
  709. else
  710. result.alias = "NULL"
  711. end
  712. end
  713. -- alias 不参与 hashkey 计算
  714. local alias = result.alias
  715. result.alias = nil
  716. local switch_enable = result.switch_enable
  717. result.switch_enable = nil
  718. result.hashkey = md5(jsonStringify(result))
  719. result.alias = alias
  720. result.switch_enable = switch_enable
  721. return result
  722. end
  723. -- 计算、储存和读取 md5 值
  724. -- 计算 md5 值
  725. local function md5_string(data)
  726. -- 生成临时文件名
  727. local tmp = "/tmp/md5_tmp_" .. os.time() .. "_" .. math.random(1000,9999) -- os.time 保证每秒唯一,但不足以避免全部冲突;math.random(1000,9999) 增加文件名唯一性,避免并发时冲突
  728. nixio.fs.writefile(tmp, data) -- 写入临时文件
  729. -- 执行 md5sum 命令
  730. local md5 = luci.sys.exec(string.format('md5sum "%s" 2>/dev/null | cut -d " " -f1', tmp)):gsub("%s+", "")
  731. nixio.fs.remove(tmp) -- 删除临时文件
  732. return md5
  733. end
  734. -- 返回临时文件路径,用来存储订阅的 MD5 值,以便判断订阅内容是否发生变化。
  735. local function get_md5_path(groupHash)
  736. return "/tmp/sub_md5_" .. groupHash
  737. end
  738. -- 读取上次订阅时记录的 MD5 值,以便和当前内容的 MD5 进行对比,从而判断是否需要更新节点列表。
  739. local function read_old_md5(groupHash)
  740. local path = get_md5_path(groupHash)
  741. if nixio.fs.access(path) then
  742. return trim(nixio.fs.readfile(path) or "")
  743. end
  744. return ""
  745. end
  746. -- 将订阅分组最新内容的 MD5 值保存到对应的临时文件中,以便下次更新时进行对比。
  747. local function write_new_md5(groupHash, md5)
  748. nixio.fs.writefile(get_md5_path(groupHash), md5)
  749. end
  750. -- curl
  751. local function curl(url)
  752. -- 清理 URL 中的隐藏字符
  753. url = url:gsub("%s+$", ""):gsub("^%s+", ""):gsub("%z", "")
  754. -- 构建curl命令(确保 user_agent 为空时不添加 -A 参数)
  755. local cmd = string.format(
  756. 'curl -sSL --connect-timeout 20 --max-time 30 --retry 3 %s --insecure --location "%s"',
  757. user_agent ~= "" and ('-A "' .. user_agent .. '"') or "", -- 添加 or "" 处理 nil 情况
  758. url:gsub('["$`\\]', '\\%0') -- 安全转义
  759. )
  760. local stdout = luci.sys.exec(cmd)
  761. stdout = trim(stdout)
  762. local md5 = md5_string(stdout)
  763. return stdout, md5
  764. end
  765. local function check_filer(result)
  766. do
  767. -- 过滤的关键词列表
  768. local filter_word = split(filter_words, "/")
  769. -- 保留的关键词列表
  770. local check_save = false
  771. if save_words ~= nil and save_words ~= "" and save_words ~= "NULL" then
  772. check_save = true
  773. end
  774. local save_word = split(save_words, "/")
  775. -- 检查结果
  776. local filter_result = false
  777. local save_result = true
  778. -- 检查是否存在过滤关键词
  779. for i, v in pairs(filter_word) do
  780. if tostring(result.alias):find(v, nil, true) then
  781. filter_result = true
  782. end
  783. end
  784. -- 检查是否打开了保留关键词检查,并且进行过滤
  785. if check_save == true then
  786. for i, v in pairs(save_word) do
  787. if tostring(result.alias):find(v, nil, true) then
  788. save_result = false
  789. end
  790. end
  791. else
  792. save_result = false
  793. end
  794. -- 不等时返回
  795. if filter_result == true or save_result == true then
  796. return true
  797. else
  798. return false
  799. end
  800. end
  801. end
  802. -- 加载订阅未变化的节点用于防止被误删
  803. local function loadOldNodes(groupHash)
  804. local nodes = {}
  805. cache[groupHash] = {}
  806. nodeResult[#nodeResult + 1] = nodes
  807. local index = #nodeResult
  808. ucic:foreach(name, uciType, function(s)
  809. if s.grouphashkey == groupHash and s.hashkey then
  810. local section = setmetatable({}, {__index = s})
  811. nodes[s.hashkey] = section
  812. cache[groupHash][s.hashkey] = section
  813. end
  814. end)
  815. end
  816. local execute = function()
  817. -- exec
  818. do
  819. --local updated = false
  820. local service_stopped = false
  821. for k, url in ipairs(subscribe_url) do
  822. local raw, new_md5 = curl(url)
  823. log("raw 长度: "..#raw)
  824. local groupHash = md5(url)
  825. local old_md5 = read_old_md5(groupHash)
  826. log("处理订阅: " .. url)
  827. log("groupHash: " .. groupHash)
  828. log("old_md5: " .. tostring(old_md5))
  829. log("new_md5: " .. tostring(new_md5))
  830. if #raw > 0 then
  831. if old_md5 and new_md5 == old_md5 then
  832. log("订阅未变化, 跳过无需更新的订阅: " .. url)
  833. -- 防止 diff 阶段误删未更新订阅节点
  834. loadOldNodes(groupHash)
  835. --ucic:foreach(name, uciType, function(s)
  836. -- if s.grouphashkey == groupHash and s.hashkey then
  837. -- cache[groupHash][s.hashkey] = s
  838. -- tinsert(nodeResult[index], s)
  839. -- end
  840. --end)
  841. else
  842. updated = true
  843. -- 保存更新后的 MD5 值到以 groupHash 为标识的临时文件中,用于下次订阅更新时进行对比
  844. write_new_md5(groupHash, new_md5)
  845. -- 暂停服务(仅当 MD5 有变化时才执行)
  846. if proxy == '0' and not service_stopped then
  847. log('服务正在暂停')
  848. luci.sys.init.stop(name)
  849. service_stopped = true
  850. end
  851. cache[groupHash] = {}
  852. tinsert(nodeResult, {})
  853. local index = #nodeResult
  854. local nodes, szType
  855. -- SSD 似乎是这种格式 ssd:// 开头的
  856. if raw:find('ssd://') then
  857. szType = 'ssd'
  858. local nEnd = select(2, raw:find('ssd://'))
  859. nodes = base64Decode(raw:sub(nEnd + 1, #raw))
  860. nodes = jsonParse(nodes)
  861. local extra = {
  862. airport = nodes.airport,
  863. port = nodes.port,
  864. encryption = nodes.encryption,
  865. password = nodes.password
  866. }
  867. local servers = {}
  868. -- SS里面包着 干脆直接这样
  869. for _, server in ipairs(nodes.servers or {}) do
  870. tinsert(servers, setmetatable(server, {__index = extra}))
  871. end
  872. nodes = servers
  873. -- SS SIP008 直接使用 Json 格式
  874. elseif jsonParse(raw) then
  875. nodes = jsonParse(raw).servers or jsonParse(raw)
  876. if nodes[1] and nodes[1].server and nodes[1].method then
  877. szType = 'sip008'
  878. end
  879. -- 其他 base64 格式
  880. else
  881. -- ssd 外的格式
  882. nodes = split(base64Decode(raw):gsub(" ", "_"), "\n")
  883. end
  884. for _, v in ipairs(nodes) do
  885. if v then
  886. local result
  887. if szType then
  888. result = processData(szType, v)
  889. elseif not szType then
  890. local node = trim(v)
  891. local dat = split(node, "://")
  892. if dat and dat[1] and dat[2] then
  893. local dat3 = ""
  894. if dat[3] then
  895. dat3 = "://" .. dat[3]
  896. end
  897. if dat[1] == 'ss' or dat[1] == 'trojan' then
  898. result = processData(dat[1], dat[2] .. dat3)
  899. else
  900. result = processData(dat[1], base64Decode(dat[2]))
  901. end
  902. end
  903. else
  904. log('跳过未知类型: ' .. szType)
  905. end
  906. -- log(result)
  907. if result then
  908. -- 中文做地址的 也没有人拿中文域名搞,就算中文域也有Puny Code SB 机场
  909. if not result.server or not result.server_port
  910. or result.alias == "NULL"
  911. or check_filer(result)
  912. or result.server:match("[^0-9a-zA-Z%-_%.%s]")
  913. or cache[groupHash][result.hashkey]
  914. then
  915. log('丢弃无效节点: ' .. result.alias)
  916. else
  917. -- log('成功解析: ' .. result.type ..' 节点, ' .. result.alias)
  918. result.grouphashkey = groupHash
  919. tinsert(nodeResult[index], result)
  920. cache[groupHash][result.hashkey] = nodeResult[index][#nodeResult[index]]
  921. end
  922. end
  923. end
  924. end
  925. log('成功解析节点数量: ' .. #nodes)
  926. end
  927. else
  928. log(url .. ': 获取内容为空')
  929. end
  930. end
  931. end
  932. -- 输出日志并判断是否需要进行 diff
  933. if not updated then
  934. log("订阅未变化,无需更新节点信息。")
  935. log('保留手动添加的节点。')
  936. return
  937. end
  938. -- diff
  939. do
  940. if next(nodeResult) == nil then
  941. log("更新失败,没有可用的节点信息")
  942. if proxy == '0' then
  943. luci.sys.init.start(name)
  944. log('订阅失败, 恢复服务')
  945. end
  946. return
  947. end
  948. local add, del = 0, 0
  949. ucic:foreach(name, uciType, function(old)
  950. if old.grouphashkey or old.hashkey then -- 没有 hash 的不参与删除
  951. if not nodeResult[old.grouphashkey] or not nodeResult[old.grouphashkey][old.hashkey] then
  952. ucic:delete(name, old['.name'])
  953. del = del + 1
  954. else
  955. local dat = nodeResult[old.grouphashkey][old.hashkey]
  956. ucic:tset(name, old['.name'], dat)
  957. -- 标记一下
  958. setmetatable(nodeResult[old.grouphashkey][old.hashkey], {__index = {_ignore = true}})
  959. end
  960. else
  961. if not old.alias then
  962. if old.server or old.server_port then
  963. old.alias = old.server .. ':' .. old.server_port
  964. log('忽略手动添加的节点: ' .. old.alias)
  965. else
  966. ucic:delete(name, old['.name'])
  967. end
  968. else
  969. log('忽略手动添加的节点: ' .. old.alias)
  970. end
  971. end
  972. end)
  973. for k, v in ipairs(nodeResult) do
  974. for kk, vv in ipairs(v) do
  975. if not vv._ignore then
  976. local section = ucic:add(name, uciType)
  977. ucic:tset(name, section, vv)
  978. ucic:set(name, section, "switch_enable", switch)
  979. add = add + 1
  980. end
  981. end
  982. end
  983. ucic:commit(name)
  984. -- 如果原有服务器节点已经不见了就尝试换为第一个节点
  985. local globalServer = ucic:get_first(name, 'global', 'global_server', '')
  986. if globalServer ~= "nil" then
  987. local firstServer = ucic:get_first(name, uciType)
  988. if firstServer then
  989. if not ucic:get(name, globalServer) then
  990. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  991. ucic:commit(name)
  992. ucic:set(name, ucic:get_first(name, 'global'), 'global_server', firstServer)
  993. ucic:commit(name)
  994. log('当前主服务器节点已被删除,正在自动更换为第一个节点。')
  995. luci.sys.call("/etc/init.d/" .. name .. " start > /dev/null 2>&1 &")
  996. else
  997. log('维持当前主服务器节点。')
  998. luci.sys.call("/etc/init.d/" .. name .. " restart > /dev/null 2>&1 &")
  999. end
  1000. else
  1001. log('没有服务器节点了,停止服务')
  1002. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  1003. end
  1004. end
  1005. log('新增节点数量: ' .. add, '删除节点数量: ' .. del)
  1006. log('订阅更新成功')
  1007. end
  1008. end
  1009. if subscribe_url and #subscribe_url > 0 then
  1010. xpcall(execute, function(e)
  1011. log(e)
  1012. log(debug.traceback())
  1013. log('发生错误, 正在恢复服务')
  1014. local firstServer = ucic:get_first(name, uciType)
  1015. if firstServer then
  1016. luci.sys.call("/etc/init.d/" .. name .. " restart > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  1017. log('重启服务成功')
  1018. else
  1019. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  1020. log('停止服务成功')
  1021. end
  1022. end)
  1023. end