subscribe.lua 36 KB

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