subscribe.lua 36 KB

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