subscribe.lua 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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. -- 读取 ss_type 设置
  31. local ss_type = ucic:get_first(name, 'server_subscribe', 'ss_type', 'ss-rust')
  32. -- 根据 ss_type 选择对应的程序
  33. local ss_program = ""
  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. result.alias = url.fragment and UrlDecode(url.fragment) or nil
  189. result.type = hy2_type
  190. result.server = url.host
  191. result.server_port = url.port
  192. if params.protocol then
  193. result.flag_transport = "1"
  194. result.transport_protocol = params.protocol or "udp"
  195. end
  196. result.hy2_auth = url.user
  197. result.uplink_capacity = params.upmbps or "5"
  198. result.downlink_capacity = params.downmbps or "20"
  199. if params.obfs then
  200. result.flag_obfs = "1"
  201. result.obfs_type = params.obfs
  202. result.salamander = params["obfs-password"] or params["obfs_password"]
  203. end
  204. if params.sni then
  205. result.tls = "1"
  206. result.tls_host = params.sni
  207. end
  208. if params.insecure then
  209. result.insecure = "1"
  210. if params.sni then
  211. result.pinsha256 = params.pinSHA256
  212. end
  213. end
  214. if params.mport then
  215. result.flag_port_hopping = "1"
  216. result.port_range = params.mport
  217. end
  218. elseif szType == 'ssr' then
  219. local dat = split(content, "/%?")
  220. local hostInfo = split(dat[1], ':')
  221. result.type = 'ssr'
  222. result.server = hostInfo[1]
  223. result.server_port = hostInfo[2]
  224. result.protocol = hostInfo[3]
  225. result.encrypt_method = hostInfo[4]
  226. result.obfs = hostInfo[5]
  227. result.password = base64Decode(hostInfo[6])
  228. local params = {}
  229. for _, v in pairs(split(dat[2], '&')) do
  230. local t = split(v, '=')
  231. params[t[1]] = t[2]
  232. end
  233. result.obfs_param = base64Decode(params.obfsparam)
  234. result.protocol_param = base64Decode(params.protoparam)
  235. local group = base64Decode(params.group)
  236. if group then
  237. result.alias = "[" .. group .. "] "
  238. end
  239. result.alias = result.alias .. base64Decode(params.remarks)
  240. elseif szType == "vmess" then
  241. -- 解析正常节点
  242. local success, info = pcall(jsonParse, content)
  243. if not success or type(info) ~= "table" then
  244. return nil
  245. end
  246. -- 处理有效数据
  247. result.type = 'v2ray'
  248. result.v2ray_protocol = 'vmess'
  249. result.server = info.add
  250. result.server_port = info.port
  251. if info.net == "tcp" then
  252. info.net = "raw"
  253. end
  254. result.transport = info.net
  255. result.alter_id = info.aid
  256. result.vmess_id = info.id
  257. result.alias = info.ps
  258. -- result.mux = 1
  259. -- result.concurrency = 8
  260. if info.net == 'ws' then
  261. result.ws_host = info.host
  262. result.ws_path = info.path
  263. end
  264. if info.net == 'httpupgrade' then
  265. result.httpupgrade_host = info.host
  266. result.httpupgrade_path = info.path
  267. end
  268. if info.net == 'splithttp' then
  269. result.splithttp_host = info.host
  270. result.splithttp_path = info.path
  271. end
  272. if info.net == 'xhttp' then
  273. result.xhttp_mode = info.mode
  274. result.xhttp_host = info.host
  275. result.xhttp_path = info.path
  276. -- 检查 extra 参数是否存在且非空
  277. result.enable_xhttp_extra = (info.extra and info.extra ~= "") and "1" or nil
  278. result.xhttp_extra = (info.extra and info.extra ~= "") and info.extra or nil
  279. -- 尝试解析 JSON 数据
  280. local success, Data = pcall(jsonParse, info.extra)
  281. if success and Data then
  282. local address = (Data.extra and Data.extra.downloadSettings and Data.extra.downloadSettings.address)
  283. or (Data.downloadSettings and Data.downloadSettings.address)
  284. result.download_address = address and address ~= "" and address or nil
  285. else
  286. -- 如果解析失败,清空下载地址
  287. result.download_address = nil
  288. end
  289. end
  290. if info.net == 'h2' then
  291. result.h2_host = info.host
  292. result.h2_path = info.path
  293. end
  294. if info.net == 'raw' or info.net == 'tcp' then
  295. if info.type and info.type ~= "http" then
  296. info.type = "none"
  297. end
  298. result.tcp_guise = info.type
  299. result.http_host = info.host
  300. result.http_path = info.path
  301. end
  302. if info.net == 'kcp' then
  303. result.kcp_guise = info.type
  304. result.mtu = 1350
  305. result.tti = 50
  306. result.uplink_capacity = 5
  307. result.downlink_capacity = 20
  308. result.read_buffer_size = 2
  309. result.write_buffer_size = 2
  310. end
  311. if info.net == 'grpc' then
  312. if info.path then
  313. result.serviceName = info.path
  314. elseif info.serviceName then
  315. result.serviceName = info.serviceName
  316. end
  317. end
  318. if info.net == 'quic' then
  319. result.quic_guise = info.type
  320. result.quic_key = info.key
  321. result.quic_security = info.securty
  322. end
  323. if info.security then
  324. result.security = info.security
  325. end
  326. if info.tls == "tls" or info.tls == "1" then
  327. result.tls = "1"
  328. if info.alpn and info.alpn ~= "" then
  329. result.xhttp_alpn = info.alpn
  330. end
  331. if info.sni and info.sni ~= "" then
  332. result.tls_host = info.sni
  333. elseif info.host then
  334. result.tls_host = info.host
  335. end
  336. result.insecure = allow_insecure
  337. else
  338. result.tls = "0"
  339. end
  340. elseif szType == "ss" then
  341. local idx_sp = 0
  342. local alias = ""
  343. if content:find("#") then
  344. idx_sp = content:find("#")
  345. alias = content:sub(idx_sp + 1, -1)
  346. end
  347. local info = content:sub(1, idx_sp > 0 and idx_sp - 1 or #content)
  348. local hostInfo = split(base64Decode(info), "@")
  349. if #hostInfo < 2 then
  350. --log("SS节点格式错误,解码后内容:", base64Decode(info))
  351. return nil
  352. end
  353. local host = split(hostInfo[2], ":")
  354. if #host < 2 then
  355. --log("SS节点主机格式错误:", hostInfo[2])
  356. return nil
  357. end
  358. -- 提取用户信息
  359. local userinfo = base64Decode(hostInfo[1])
  360. local method, password = userinfo:match("^([^:]*):(.*)$")
  361. -- 填充结果
  362. result.alias = UrlDecode(alias)
  363. result.type = v2_ss
  364. result.v2ray_protocol = (v2_ss == "v2ray") and "shadowsocks" or nil
  365. result.has_ss_type = has_ss_type
  366. result.encrypt_method_ss = method
  367. result.password = password
  368. result.server = host[1]
  369. -- 处理端口和插件
  370. local port_part = host[2]
  371. if port_part:find("/%?") then
  372. local query = split(port_part, "/%?")
  373. result.server_port = query[1]
  374. if query[2] then
  375. local params = {}
  376. for _, v in pairs(split(query[2], '&')) do
  377. local t = split(v, '=')
  378. if #t >= 2 then
  379. params[t[1]] = t[2]
  380. end
  381. end
  382. if params.plugin then
  383. local plugin_info = UrlDecode(params.plugin)
  384. local idx_pn = plugin_info:find(";")
  385. if idx_pn then
  386. result.plugin = plugin_info:sub(1, idx_pn - 1)
  387. result.plugin_opts = plugin_info:sub(idx_pn + 1, #plugin_info)
  388. else
  389. result.plugin = plugin_info
  390. result.plugin_opts = ""
  391. end
  392. -- 部分机场下发的插件名为 simple-obfs,这里应该改为 obfs-local
  393. if result.plugin == "simple-obfs" then
  394. result.plugin = "obfs-local"
  395. end
  396. -- 如果插件不为 none,确保 enable_plugin 为 1
  397. if result.plugin ~= "none" and result.plugin ~= "" then
  398. result.enable_plugin = 1
  399. end
  400. end
  401. end
  402. else
  403. result.server_port = port_part:gsub("/","")
  404. end
  405. -- 检查加密方法
  406. if not checkTabValue(encrypt_methods_ss)[method] then
  407. -- 1202 年了还不支持 SS AEAD 的屑机场
  408. -- log("不支持的SS加密方法:", method)
  409. result.server = nil
  410. end
  411. elseif szType == "sip008" then
  412. result.type = v2_ss
  413. result.v2ray_protocol = (v2_ss == "v2ray") and "shadowsocks" or nil
  414. result.server = content.server
  415. result.server_port = content.server_port
  416. result.password = content.password
  417. result.encrypt_method_ss = content.method
  418. result.plugin = content.plugin
  419. result.plugin_opts = content.plugin_opts
  420. result.alias = content.remarks
  421. if not checkTabValue(encrypt_methods_ss)[content.method] then
  422. result.server = nil
  423. end
  424. elseif szType == "ssd" then
  425. result.type = v2_ss
  426. result.v2ray_protocol = (v2_ss == "v2ray") and "shadowsocks" or nil
  427. result.server = content.server
  428. result.server_port = content.port
  429. result.password = content.password
  430. result.encrypt_method_ss = content.method
  431. result.plugin_opts = content.plugin_options
  432. result.alias = "[" .. content.airport .. "] " .. content.remarks
  433. if content.plugin == "simple-obfs" then
  434. result.plugin = "obfs-local"
  435. else
  436. result.plugin = content.plugin
  437. end
  438. if not checkTabValue(encrypt_methods_ss)[content.encryption] then
  439. result.server = nil
  440. end
  441. elseif szType == "trojan" then
  442. local params = {}
  443. local idx_sp = 0
  444. local alias = ""
  445. -- 提取别名(如果存在)
  446. if content:find("#") then
  447. idx_sp = content:find("#")
  448. alias = content:sub(idx_sp + 1, -1)
  449. end
  450. local info = content:sub(1, idx_sp > 0 and idx_sp - 1 or #content)
  451. local hostInfo = split(info, "@")
  452. -- 基础验证
  453. if #hostInfo < 2 then
  454. --log("Trojan节点格式错误: 缺少@符号")
  455. return nil
  456. end
  457. local userinfo = hostInfo[1]
  458. local hostPort = hostInfo[2]
  459. -- 分离服务器地址和端口
  460. local hostParts = split(hostPort, ":")
  461. local server = hostParts[1]
  462. local port = hostParts[2]
  463. -- 验证服务器地址和端口
  464. if #hostParts < 2 then
  465. --log("Trojan节点格式错误: 缺少端口号")
  466. return nil
  467. end
  468. result.alias = UrlDecode(alias)
  469. result.type = v2_tj
  470. result.v2ray_protocol = "trojan"
  471. result.server = server
  472. result.password = userinfo
  473. -- 默认设置
  474. -- 按照官方的建议 默认验证ssl证书
  475. result.insecure = "0"
  476. result.tls = "1"
  477. -- 解析查询参数(如果存在)
  478. if port:find("?") then
  479. local queryParts = split(port, "?")
  480. result.server_port = queryParts[1]
  481. -- 解析查询参数
  482. for _, v in pairs(split(queryParts[2], '&')) do
  483. local t = split(v, '=')
  484. if #t >= 2 then
  485. params[t[1]] = t[2]
  486. end
  487. end
  488. -- 处理参数
  489. if params.alpn then
  490. -- 处理 alpn 参数
  491. result.xhttp_alpn = params.alpn
  492. end
  493. if params.sni then
  494. -- 未指定peer(sni)默认使用remote addr
  495. result.tls_host = params.sni
  496. end
  497. if params.allowInsecure then
  498. -- 处理 insecure 参数
  499. result.insecure = params.allowInsecure
  500. end
  501. else
  502. result.server_port = port
  503. end
  504. if v2_tj ~= "trojan" then
  505. if params.fp then
  506. -- 处理 fingerprint 参数
  507. result.fingerprint = params.fp
  508. end
  509. -- 处理传输协议
  510. result.transport = params.type or "tcp" -- 默认传输协议为 tcp
  511. if result.transport == "tcp" then
  512. result.transport = "raw"
  513. end
  514. if result.transport == "ws" then
  515. result.ws_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  516. result.ws_path = params.path and UrlDecode(params.path) or "/"
  517. elseif result.transport == "httpupgrade" then
  518. result.httpupgrade_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  519. result.httpupgrade_path = params.path and UrlDecode(params.path) or "/"
  520. elseif result.transport == "splithttp" then
  521. result.splithttp_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  522. result.splithttp_path = params.path and UrlDecode(params.path) or "/"
  523. elseif result.transport == "xhttp" then
  524. result.xhttp_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  525. result.xhttp_mode = params.mode or "auto"
  526. result.xhttp_path = params.path and UrlDecode(params.path) or "/"
  527. -- 检查 extra 参数是否存在且非空
  528. result.enable_xhttp_extra = (params.extra and params.extra ~= "") and "1" or nil
  529. result.xhttp_extra = (params.extra and params.extra ~= "") and params.extra or nil
  530. -- 尝试解析 JSON 数据
  531. local success, Data = pcall(jsonParse, params.extra)
  532. if success and Data then
  533. local address = (Data.extra and Data.extra.downloadSettings and Data.extra.downloadSettings.address)
  534. or (Data.downloadSettings and Data.downloadSettings.address)
  535. result.download_address = address and address ~= "" and address or nil
  536. else
  537. -- 如果解析失败,清空下载地址
  538. result.download_address = nil
  539. end
  540. elseif result.transport == "http" or result.transport == "h2" then
  541. result.transport = "h2"
  542. result.h2_host = params.host and UrlDecode(params.host) or nil
  543. result.h2_path = params.path and UrlDecode(params.path) or nil
  544. elseif result.transport == "kcp" then
  545. result.kcp_guise = params.headerType or "none"
  546. result.seed = params.seed
  547. result.mtu = 1350
  548. result.tti = 50
  549. result.uplink_capacity = 5
  550. result.downlink_capacity = 20
  551. result.read_buffer_size = 2
  552. result.write_buffer_size = 2
  553. elseif result.transport == "quic" then
  554. result.quic_guise = params.headerType or "none"
  555. result.quic_security = params.quicSecurity or "none"
  556. result.quic_key = params.key
  557. elseif result.transport == "grpc" then
  558. result.serviceName = params.serviceName
  559. result.grpc_mode = params.mode or "gun"
  560. elseif result.transport == "tcp" or result.transport == "raw" then
  561. result.tcp_guise = params.headerType and params.headerType ~= "" and params.headerType or "none"
  562. if result.tcp_guise == "http" then
  563. result.tcp_host = params.host and UrlDecode(params.host) or nil
  564. result.tcp_path = params.path and UrlDecode(params.path) or nil
  565. end
  566. end
  567. end
  568. elseif szType == "vless" then
  569. local url = URL.parse("http://" .. content)
  570. local params = url.query
  571. result.alias = url.fragment and UrlDecode(url.fragment) or nil
  572. result.type = "v2ray"
  573. result.v2ray_protocol = "vless"
  574. result.server = url.host
  575. result.server_port = url.port
  576. result.vmess_id = url.user
  577. result.vless_encryption = params.encryption or "none"
  578. result.transport = params.type or "tcp"
  579. result.tls = (params.security == "tls" or params.security == "xtls") and "1" or "0"
  580. result.xhttp_alpn = params.alpn or ""
  581. result.tls_host = params.sni
  582. result.tls_flow = (params.security == "tls" or params.security == "reality") and params.flow or nil
  583. result.fingerprint = params.fp
  584. result.reality = (params.security == "reality") and "1" or "0"
  585. result.reality_publickey = params.pbk and UrlDecode(params.pbk) or nil
  586. result.reality_shortid = params.sid
  587. result.reality_spiderx = params.spx and UrlDecode(params.spx) or nil
  588. if result.transport == "ws" then
  589. result.ws_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  590. result.ws_path = params.path and UrlDecode(params.path) or "/"
  591. elseif result.transport == "httpupgrade" then
  592. result.httpupgrade_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  593. result.httpupgrade_path = params.path and UrlDecode(params.path) or "/"
  594. elseif result.transport == "splithttp" then
  595. result.splithttp_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  596. result.splithttp_path = params.path and UrlDecode(params.path) or "/"
  597. elseif result.transport == "xhttp" then
  598. result.xhttp_host = (result.tls ~= "1") and (params.host and UrlDecode(params.host)) or nil
  599. result.xhttp_mode = params.mode or "auto"
  600. result.xhttp_path = params.path and UrlDecode(params.path) or "/"
  601. -- 检查 extra 参数是否存在且非空
  602. result.enable_xhttp_extra = (params.extra and params.extra ~= "") and "1" or nil
  603. result.xhttp_extra = (params.extra and params.extra ~= "") and params.extra or nil
  604. -- 尝试解析 JSON 数据
  605. local success, Data = pcall(jsonParse, params.extra)
  606. if success and Data then
  607. local address = (Data.extra and Data.extra.downloadSettings and Data.extra.downloadSettings.address)
  608. or (Data.downloadSettings and Data.downloadSettings.address)
  609. result.download_address = address and address ~= "" and address or nil
  610. else
  611. -- 如果解析失败,清空下载地址
  612. result.download_address = nil
  613. end
  614. -- make it compatible with bullshit, "h2" transport is non-existent at all
  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 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. if not result.alias then
  644. if result.server and result.server_port then
  645. result.alias = result.server .. ':' .. result.server_port
  646. else
  647. result.alias = "NULL"
  648. end
  649. end
  650. -- alias 不参与 hashkey 计算
  651. local alias = result.alias
  652. result.alias = nil
  653. local switch_enable = result.switch_enable
  654. result.switch_enable = nil
  655. result.hashkey = md5(jsonStringify(result))
  656. result.alias = alias
  657. result.switch_enable = switch_enable
  658. return result
  659. end
  660. -- curl
  661. local function curl(url)
  662. -- 清理URL中的隐藏字符
  663. url = url:gsub("%s+$", ""):gsub("^%s+", ""):gsub("%z", "")
  664. local stdout = luci.sys.exec('curl -sSL --connect-timeout 20 --max-time 30 --retry 3 -A "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36" --insecure --location "' .. url .. '"')
  665. return trim(stdout)
  666. end
  667. local function check_filer(result)
  668. do
  669. -- 过滤的关键词列表
  670. local filter_word = split(filter_words, "/")
  671. -- 保留的关键词列表
  672. local check_save = false
  673. if save_words ~= nil and save_words ~= "" and save_words ~= "NULL" then
  674. check_save = true
  675. end
  676. local save_word = split(save_words, "/")
  677. -- 检查结果
  678. local filter_result = false
  679. local save_result = true
  680. -- 检查是否存在过滤关键词
  681. for i, v in pairs(filter_word) do
  682. if tostring(result.alias):find(v, nil, true) then
  683. filter_result = true
  684. end
  685. end
  686. -- 检查是否打开了保留关键词检查,并且进行过滤
  687. if check_save == true then
  688. for i, v in pairs(save_word) do
  689. if tostring(result.alias):find(v, nil, true) then
  690. save_result = false
  691. end
  692. end
  693. else
  694. save_result = false
  695. end
  696. -- 不等时返回
  697. if filter_result == true or save_result == true then
  698. return true
  699. else
  700. return false
  701. end
  702. end
  703. end
  704. local execute = function()
  705. -- exec
  706. do
  707. if proxy == '0' then -- 不使用代理更新的话先暂停
  708. log('服务正在暂停')
  709. luci.sys.init.stop(name)
  710. end
  711. for k, url in ipairs(subscribe_url) do
  712. local raw = curl(url)
  713. if #raw > 0 then
  714. local nodes, szType
  715. local groupHash = md5(url)
  716. cache[groupHash] = {}
  717. tinsert(nodeResult, {})
  718. local index = #nodeResult
  719. -- SSD 似乎是这种格式 ssd:// 开头的
  720. if raw:find('ssd://') then
  721. szType = 'ssd'
  722. local nEnd = select(2, raw:find('ssd://'))
  723. nodes = base64Decode(raw:sub(nEnd + 1, #raw))
  724. nodes = jsonParse(nodes)
  725. local extra = {airport = nodes.airport, port = nodes.port, encryption = nodes.encryption, password = nodes.password}
  726. local servers = {}
  727. -- SS里面包着 干脆直接这样
  728. for _, server in ipairs(nodes.servers) do
  729. tinsert(servers, setmetatable(server, {__index = extra}))
  730. end
  731. nodes = servers
  732. -- SS SIP008 直接使用 Json 格式
  733. elseif jsonParse(raw) then
  734. nodes = jsonParse(raw).servers or jsonParse(raw)
  735. if nodes[1].server and nodes[1].method then
  736. szType = 'sip008'
  737. end
  738. else
  739. -- ssd 外的格式
  740. nodes = split(base64Decode(raw):gsub(" ", "_"), "\n")
  741. end
  742. for _, v in ipairs(nodes) do
  743. if v then
  744. local result
  745. if szType then
  746. result = processData(szType, v)
  747. elseif not szType then
  748. local node = trim(v)
  749. local dat = split(node, "://")
  750. if dat and dat[1] and dat[2] then
  751. local dat3 = ""
  752. if dat[3] then
  753. dat3 = "://" .. dat[3]
  754. end
  755. if dat[1] == 'ss' or dat[1] == 'trojan' then
  756. result = processData(dat[1], dat[2] .. dat3)
  757. else
  758. result = processData(dat[1], base64Decode(dat[2]))
  759. end
  760. end
  761. else
  762. log('跳过未知类型: ' .. szType)
  763. end
  764. -- log(result)
  765. if result then
  766. -- 中文做地址的 也没有人拿中文域名搞,就算中文域也有Puny Code SB 机场
  767. if not result.server or not result.server_port or result.alias == "NULL" or check_filer(result) or result.server:match("[^0-9a-zA-Z%-_%.%s]") or cache[groupHash][result.hashkey] then
  768. log('丢弃无效节点: ' .. result.alias)
  769. else
  770. -- log('成功解析: ' .. result.type ..' 节点, ' .. result.alias)
  771. result.grouphashkey = groupHash
  772. tinsert(nodeResult[index], result)
  773. cache[groupHash][result.hashkey] = nodeResult[index][#nodeResult[index]]
  774. end
  775. end
  776. end
  777. end
  778. log('成功解析节点数量: ' .. #nodes)
  779. else
  780. log(url .. ': 获取内容为空')
  781. end
  782. end
  783. end
  784. -- diff
  785. do
  786. if next(nodeResult) == nil then
  787. log("更新失败,没有可用的节点信息")
  788. if proxy == '0' then
  789. luci.sys.init.start(name)
  790. log('订阅失败, 恢复服务')
  791. end
  792. return
  793. end
  794. local add, del = 0, 0
  795. ucic:foreach(name, uciType, function(old)
  796. if old.grouphashkey or old.hashkey then -- 没有 hash 的不参与删除
  797. if not nodeResult[old.grouphashkey] or not nodeResult[old.grouphashkey][old.hashkey] then
  798. ucic:delete(name, old['.name'])
  799. del = del + 1
  800. else
  801. local dat = nodeResult[old.grouphashkey][old.hashkey]
  802. ucic:tset(name, old['.name'], dat)
  803. -- 标记一下
  804. setmetatable(nodeResult[old.grouphashkey][old.hashkey], {__index = {_ignore = true}})
  805. end
  806. else
  807. if not old.alias then
  808. if old.server or old.server_port then
  809. old.alias = old.server .. ':' .. old.server_port
  810. log('忽略手动添加的节点: ' .. old.alias)
  811. else
  812. ucic:delete(name, old['.name'])
  813. end
  814. else
  815. log('忽略手动添加的节点: ' .. old.alias)
  816. end
  817. end
  818. end)
  819. for k, v in ipairs(nodeResult) do
  820. for kk, vv in ipairs(v) do
  821. if not vv._ignore then
  822. local section = ucic:add(name, uciType)
  823. ucic:tset(name, section, vv)
  824. ucic:set(name, section, "switch_enable", switch)
  825. add = add + 1
  826. end
  827. end
  828. end
  829. ucic:commit(name)
  830. -- 如果原有服务器节点已经不见了就尝试换为第一个节点
  831. local globalServer = ucic:get_first(name, 'global', 'global_server', '')
  832. if globalServer ~= "nil" then
  833. local firstServer = ucic:get_first(name, uciType)
  834. if firstServer then
  835. if not ucic:get(name, globalServer) then
  836. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  837. ucic:commit(name)
  838. ucic:set(name, ucic:get_first(name, 'global'), 'global_server', ucic:get_first(name, uciType))
  839. ucic:commit(name)
  840. log('当前主服务器节点已被删除,正在自动更换为第一个节点。')
  841. luci.sys.call("/etc/init.d/" .. name .. " start > /dev/null 2>&1 &")
  842. else
  843. log('维持当前主服务器节点。')
  844. luci.sys.call("/etc/init.d/" .. name .. " restart > /dev/null 2>&1 &")
  845. end
  846. else
  847. log('没有服务器节点了,停止服务')
  848. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  849. end
  850. end
  851. log('新增节点数量: ' .. add, '删除节点数量: ' .. del)
  852. log('订阅更新成功')
  853. end
  854. end
  855. if subscribe_url and #subscribe_url > 0 then
  856. xpcall(execute, function(e)
  857. log(e)
  858. log(debug.traceback())
  859. log('发生错误, 正在恢复服务')
  860. local firstServer = ucic:get_first(name, uciType)
  861. if firstServer then
  862. luci.sys.call("/etc/init.d/" .. name .. " restart > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  863. log('重启服务成功')
  864. else
  865. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  866. log('停止服务成功')
  867. end
  868. end)
  869. end