subscribe.lua 35 KB

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