subscribe.lua 29 KB

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