subscribe.lua 35 KB

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