subscribe.lua 32 KB

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