subscribe.lua 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. #!/usr/bin/lua
  2. ------------------------------------------------
  3. -- This file is part of the luci-app-ssr-plus subscribe.lua
  4. -- @author William Chan <[email protected]>
  5. ------------------------------------------------
  6. require "luci.model.uci"
  7. require "nixio"
  8. require "luci.util"
  9. require "luci.sys"
  10. require "luci.jsonc"
  11. -- these global functions are accessed all the time by the event handler
  12. -- so caching them is worth the effort
  13. local tinsert = table.insert
  14. local ssub, slen, schar, sbyte, sformat, sgsub = string.sub, string.len, string.char, string.byte, string.format, string.gsub
  15. local jsonParse, jsonStringify = luci.jsonc.parse, luci.jsonc.stringify
  16. local b64decode = nixio.bin.b64decode
  17. local cache = {}
  18. local nodeResult = setmetatable({}, {__index = cache}) -- update result
  19. local name = 'shadowsocksr'
  20. local uciType = 'servers'
  21. local ucic = luci.model.uci.cursor()
  22. local proxy = ucic:get_first(name, 'server_subscribe', 'proxy', '0')
  23. local switch = ucic:get_first(name, 'server_subscribe', 'switch', '1')
  24. local subscribe_url = ucic:get_first(name, 'server_subscribe', 'subscribe_url', {})
  25. local filter_words = ucic:get_first(name, 'server_subscribe', 'filter_words', '过期时间/剩余流量')
  26. local v2_ss = luci.sys.exec('type -t -p ss-redir sslocal') ~= "" and "ss" or "v2ray"
  27. local v2_tj = luci.sys.exec('type -t -p trojan') ~= "" and "trojan" or "v2ray"
  28. local log = function(...)
  29. print(os.date("%Y-%m-%d %H:%M:%S ") .. table.concat({...}, " "))
  30. end
  31. local encrypt_methods_ss = {
  32. -- aead
  33. "aes-128-gcm",
  34. "aes-192-gcm",
  35. "aes-256-gcm",
  36. "chacha20-ietf-poly1305",
  37. "xchacha20-ietf-poly1305"
  38. --[[ stream
  39. "table",
  40. "rc4",
  41. "rc4-md5",
  42. "aes-128-cfb",
  43. "aes-192-cfb",
  44. "aes-256-cfb",
  45. "aes-128-ctr",
  46. "aes-192-ctr",
  47. "aes-256-ctr",
  48. "bf-cfb",
  49. "camellia-128-cfb",
  50. "camellia-192-cfb",
  51. "camellia-256-cfb",
  52. "salsa20",
  53. "chacha20",
  54. "chacha20-ietf" ]]
  55. }
  56. -- 分割字符串
  57. local function split(full, sep)
  58. full = full:gsub("%z", "") -- 这里不是很清楚 有时候结尾带个\0
  59. local off, result = 1, {}
  60. while true do
  61. local nStart, nEnd = full:find(sep, off)
  62. if not nEnd then
  63. local res = ssub(full, off, slen(full))
  64. if #res > 0 then -- 过滤掉 \0
  65. tinsert(result, res)
  66. end
  67. break
  68. else
  69. tinsert(result, ssub(full, off, nStart - 1))
  70. off = nEnd + 1
  71. end
  72. end
  73. return result
  74. end
  75. -- urlencode
  76. local function get_urlencode(c)
  77. return sformat("%%%02X", sbyte(c))
  78. end
  79. local function urlEncode(szText)
  80. local str = szText:gsub("([^0-9a-zA-Z ])", get_urlencode)
  81. str = str:gsub(" ", "+")
  82. return str
  83. end
  84. local function get_urldecode(h)
  85. return schar(tonumber(h, 16))
  86. end
  87. local function UrlDecode(szText)
  88. return szText:gsub("+", " "):gsub("%%(%x%x)", get_urldecode)
  89. end
  90. -- trim
  91. local function trim(text)
  92. if not text or text == "" then
  93. return ""
  94. end
  95. return (sgsub(text, "^%s*(.-)%s*$", "%1"))
  96. end
  97. -- md5
  98. local function md5(content)
  99. local stdout = luci.sys.exec('echo \"' .. urlEncode(content) .. '\" | md5sum | cut -d \" \" -f1')
  100. -- assert(nixio.errno() == 0)
  101. return trim(stdout)
  102. end
  103. -- base64
  104. local function base64Decode(text)
  105. local raw = text
  106. if not text then
  107. return ''
  108. end
  109. text = text:gsub("%z", "")
  110. text = text:gsub("_", "/")
  111. text = text:gsub("-", "+")
  112. local mod4 = #text % 4
  113. text = text .. string.sub('====', mod4 + 1)
  114. local result = b64decode(text)
  115. if result then
  116. return result:gsub("%z", "")
  117. else
  118. return raw
  119. end
  120. end
  121. -- 检查数组(table)中是否存在某个字符值
  122. -- https://www.04007.cn/article/135.html
  123. local function checkTabValue(tab)
  124. local revtab = {}
  125. for k,v in pairs(tab) do
  126. revtab[v] = true
  127. end
  128. return revtab
  129. end
  130. -- 处理数据
  131. local function processData(szType, content)
  132. local result = {type = szType, local_port = 1234, kcp_param = '--nocomp'}
  133. if szType == 'ssr' then
  134. local dat = split(content, "/%?")
  135. local hostInfo = split(dat[1], ':')
  136. result.server = hostInfo[1]
  137. result.server_port = hostInfo[2]
  138. result.protocol = hostInfo[3]
  139. result.encrypt_method = hostInfo[4]
  140. result.obfs = hostInfo[5]
  141. result.password = base64Decode(hostInfo[6])
  142. local params = {}
  143. for _, v in pairs(split(dat[2], '&')) do
  144. local t = split(v, '=')
  145. params[t[1]] = t[2]
  146. end
  147. result.obfs_param = base64Decode(params.obfsparam)
  148. result.protocol_param = base64Decode(params.protoparam)
  149. local group = base64Decode(params.group)
  150. if group then
  151. result.alias = "[" .. group .. "] "
  152. end
  153. result.alias = result.alias .. base64Decode(params.remarks)
  154. elseif szType == 'vmess' then
  155. local info = jsonParse(content)
  156. result.type = 'v2ray'
  157. result.v2ray_protocol = 'vmess'
  158. result.server = info.add
  159. result.server_port = info.port
  160. result.transport = info.net
  161. result.alter_id = info.aid
  162. result.vmess_id = info.id
  163. result.alias = info.ps
  164. -- result.mux = 1
  165. -- result.concurrency = 8
  166. if info.net == 'ws' then
  167. result.ws_host = info.host
  168. result.ws_path = info.path
  169. end
  170. if info.net == 'h2' then
  171. result.h2_host = info.host
  172. result.h2_path = info.path
  173. end
  174. if info.net == 'tcp' then
  175. if info.type and info.type ~= "http" then
  176. info.type = "none"
  177. end
  178. result.tcp_guise = info.type
  179. result.http_host = info.host
  180. result.http_path = info.path
  181. end
  182. if info.net == 'kcp' then
  183. result.kcp_guise = info.type
  184. result.mtu = 1350
  185. result.tti = 50
  186. result.uplink_capacity = 5
  187. result.downlink_capacity = 20
  188. result.read_buffer_size = 2
  189. result.write_buffer_size = 2
  190. end
  191. if info.net == 'quic' then
  192. result.quic_guise = info.type
  193. result.quic_key = info.key
  194. result.quic_security = info.securty
  195. end
  196. if info.security then
  197. result.security = info.security
  198. end
  199. if info.tls == "tls" or info.tls == "1" then
  200. result.tls = "1"
  201. result.tls_host = info.host
  202. result.insecure = 1
  203. else
  204. result.tls = "0"
  205. end
  206. elseif szType == "ss" then
  207. local idx_sp = 0
  208. local alias = ""
  209. if content:find("#") then
  210. idx_sp = content:find("#")
  211. alias = content:sub(idx_sp + 1, -1)
  212. end
  213. local info = content:sub(1, idx_sp - 1)
  214. local hostInfo = split(base64Decode(info), "@")
  215. local host = split(hostInfo[2], ":")
  216. local userinfo = base64Decode(hostInfo[1])
  217. local method = userinfo:sub(1, userinfo:find(":") - 1)
  218. local password = userinfo:sub(userinfo:find(":") + 1, #userinfo)
  219. result.alias = UrlDecode(alias)
  220. result.type = v2_ss
  221. result.v2ray_protocol = "shadowsocks"
  222. result.server = host[1]
  223. if host[2]:find("/%?") then
  224. local query = split(host[2], "/%?")
  225. result.server_port = query[1]
  226. local params = {}
  227. for _, v in pairs(split(query[2], '&')) do
  228. local t = split(v, '=')
  229. params[t[1]] = t[2]
  230. end
  231. if params.plugin then
  232. local plugin_info = UrlDecode(params.plugin)
  233. local idx_pn = plugin_info:find(";")
  234. if idx_pn then
  235. result.plugin = plugin_info:sub(1, idx_pn - 1)
  236. result.plugin_opts = plugin_info:sub(idx_pn + 1, #plugin_info)
  237. else
  238. result.plugin = plugin_info
  239. end
  240. -- 部分机场下发的插件名为 simple-obfs,这里应该改为 obfs-local
  241. if result.plugin == "simple-obfs" then
  242. result.plugin = "obfs-local"
  243. end
  244. end
  245. else
  246. result.server_port = host[2]:gsub("/","")
  247. end
  248. if checkTabValue(encrypt_methods_ss)[method] then
  249. result.encrypt_method_ss = method
  250. result.password = password
  251. else
  252. -- 1202 年了还不支持 SS AEAD 的屑机场
  253. result.server = nil
  254. end
  255. elseif szType == "sip008" then
  256. result.type = v2_ss
  257. result.v2ray_protocol = "shadowsocks"
  258. result.server = content.server
  259. result.server_port = content.server_port
  260. result.password = content.password
  261. result.encrypt_method_ss = content.method
  262. result.plugin = content.plugin
  263. result.plugin_opts = content.plugin_opts
  264. result.alias = content.remarks
  265. if not checkTabValue(encrypt_methods_ss)[content.method] then
  266. result.server = nil
  267. end
  268. elseif szType == "ssd" then
  269. result.type = v2_ss
  270. result.v2ray_protocol = "shadowsocks"
  271. result.server = content.server
  272. result.server_port = content.port
  273. result.password = content.password
  274. result.encrypt_method_ss = content.encryption
  275. result.plugin = content.plugin
  276. result.plugin_opts = content.plugin_options
  277. result.alias = "[" .. content.airport .. "] " .. content.remarks
  278. if checkTabValue(encrypt_methods_ss)[result.encrypt_method_ss] then
  279. result.server = nil
  280. elseif result.plugin == "simple-obfs" then
  281. result.plugin = "obfs-local"
  282. end
  283. elseif szType == "trojan" then
  284. local idx_sp = 0
  285. local alias = ""
  286. if content:find("#") then
  287. idx_sp = content:find("#")
  288. alias = content:sub(idx_sp + 1, -1)
  289. end
  290. local info = content:sub(1, idx_sp - 1)
  291. local hostInfo = split(info, "@")
  292. local host = split(hostInfo[2], ":")
  293. local userinfo = hostInfo[1]
  294. local password = userinfo
  295. result.alias = UrlDecode(alias)
  296. result.type = v2_tj
  297. result.v2ray_protocol = "trojan"
  298. result.server = host[1]
  299. -- 按照官方的建议 默认验证ssl证书
  300. result.insecure = "0"
  301. result.tls = "1"
  302. if host[2]:find("?") then
  303. local query = split(host[2], "?")
  304. result.server_port = query[1]
  305. local params = {}
  306. for _, v in pairs(split(query[2], '&')) do
  307. local t = split(v, '=')
  308. params[t[1]] = t[2]
  309. end
  310. if params.sni then
  311. -- 未指定peer(sni)默认使用remote addr
  312. result.tls_host = params.sni
  313. end
  314. else
  315. result.server_port = host[2]
  316. end
  317. result.password = password
  318. elseif szType == "vless" then
  319. local idx_sp = 0
  320. local alias = ""
  321. if content:find("#") then
  322. idx_sp = content:find("#")
  323. alias = content:sub(idx_sp + 1, -1)
  324. end
  325. local info = content:sub(1, idx_sp - 1)
  326. local hostInfo = split(info, "@")
  327. local host = split(hostInfo[2], ":")
  328. local uuid = hostInfo[1]
  329. if host[2]:find("?") then
  330. local query = split(host[2], "?")
  331. local params = {}
  332. for _, v in pairs(split(UrlDecode(query[2]), '&')) do
  333. local t = split(v, '=')
  334. params[t[1]] = t[2]
  335. end
  336. result.alias = UrlDecode(alias)
  337. result.type = 'v2ray'
  338. result.v2ray_protocol = 'vless'
  339. result.server = host[1]
  340. result.server_port = query[1]
  341. result.vmess_id = uuid
  342. result.vless_encryption = params.encryption or "none"
  343. result.transport = params.type and (params.type == 'http' and 'h2' or params.type) or "tcp"
  344. if not params.type or params.type == "tcp" then
  345. if params.security == "xtls" then
  346. result.xtls = "1"
  347. result.tls_host = params.sni
  348. result.vless_flow = params.flow
  349. else
  350. result.xtls = "0"
  351. end
  352. end
  353. if params.type == 'ws' then
  354. result.ws_host = params.host
  355. result.ws_path = params.path or "/"
  356. end
  357. if params.type == 'http' then
  358. result.h2_host = params.host
  359. result.h2_path = params.path or "/"
  360. end
  361. if params.type == 'kcp' then
  362. result.kcp_guise = params.headerType or "none"
  363. result.mtu = 1350
  364. result.tti = 50
  365. result.uplink_capacity = 5
  366. result.downlink_capacity = 20
  367. result.read_buffer_size = 2
  368. result.write_buffer_size = 2
  369. result.seed = params.seed
  370. end
  371. if params.type == 'quic' then
  372. result.quic_guise = params.headerType or "none"
  373. result.quic_key = params.key
  374. result.quic_security = params.quicSecurity or "none"
  375. end
  376. if params.type == 'grpc' then
  377. result.serviceName = params.serviceName
  378. end
  379. if params.security == "tls" then
  380. result.tls = "1"
  381. result.tls_host = params.sni
  382. else
  383. result.tls = "0"
  384. end
  385. else
  386. result.server_port = host[2]
  387. end
  388. end
  389. if not result.alias then
  390. if result.server and result.server_port then
  391. result.alias = result.server .. ':' .. result.server_port
  392. else
  393. result.alias = "NULL"
  394. end
  395. end
  396. -- alias 不参与 hashkey 计算
  397. local alias = result.alias
  398. result.alias = nil
  399. local switch_enable = result.switch_enable
  400. result.switch_enable = nil
  401. result.hashkey = md5(jsonStringify(result))
  402. result.alias = alias
  403. result.switch_enable = switch_enable
  404. return result
  405. end
  406. -- wget
  407. local function wget(url)
  408. local stdout = luci.sys.exec('uclient-fetch -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 .. '"')
  409. return trim(stdout)
  410. end
  411. local function check_filer(result)
  412. do
  413. local filter_word = split(filter_words, "/")
  414. for i, v in pairs(filter_word) do
  415. if result.alias:find(v) then
  416. -- log('订阅节点关键字过滤:“' .. v ..'” ,该节点被丢弃')
  417. return true
  418. end
  419. end
  420. end
  421. end
  422. local execute = function()
  423. -- exec
  424. do
  425. if proxy == '0' then -- 不使用代理更新的话先暂停
  426. log('服务正在暂停')
  427. luci.sys.init.stop(name)
  428. end
  429. for k, url in ipairs(subscribe_url) do
  430. local raw = wget(url)
  431. if #raw > 0 then
  432. local nodes, szType
  433. local groupHash = md5(url)
  434. cache[groupHash] = {}
  435. tinsert(nodeResult, {})
  436. local index = #nodeResult
  437. -- SSD 似乎是这种格式 ssd:// 开头的
  438. if raw:find('ssd://') then
  439. szType = 'ssd'
  440. local nEnd = select(2, raw:find('ssd://'))
  441. nodes = base64Decode(raw:sub(nEnd + 1, #raw))
  442. nodes = jsonParse(nodes)
  443. local extra = {airport = nodes.airport, port = nodes.port, encryption = nodes.encryption, password = nodes.password}
  444. local servers = {}
  445. -- SS里面包着 干脆直接这样
  446. for _, server in ipairs(nodes.servers) do
  447. tinsert(servers, setmetatable(server, {__index = extra}))
  448. end
  449. nodes = servers
  450. -- SS SIP008 直接使用 Json 格式
  451. elseif jsonParse(raw) then
  452. nodes = jsonParse(raw)
  453. if nodes[1].server and nodes[1].method then
  454. szType = 'sip008'
  455. end
  456. else
  457. -- ssd 外的格式
  458. nodes = split(base64Decode(raw):gsub(" ", "_"), "\n")
  459. end
  460. for _, v in ipairs(nodes) do
  461. if v then
  462. local result
  463. if szType then
  464. result = processData(szType, v)
  465. elseif not szType then
  466. local node = trim(v)
  467. local dat = split(node, "://")
  468. if dat and dat[1] and dat[2] then
  469. local dat3 = ""
  470. if dat[3] then
  471. dat3 = "://" .. dat[3]
  472. end
  473. if dat[1] == 'ss' or dat[1] == 'trojan' then
  474. result = processData(dat[1], dat[2] .. dat3)
  475. else
  476. result = processData(dat[1], base64Decode(dat[2]))
  477. end
  478. end
  479. else
  480. log('跳过未知类型: ' .. szType)
  481. end
  482. -- log(result)
  483. if result then
  484. -- 中文做地址的 也没有人拿中文域名搞,就算中文域也有Puny Code SB 机场
  485. 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
  486. log('丢弃无效节点: ' .. result.type .. ' 节点, ' .. result.alias)
  487. else
  488. -- log('成功解析: ' .. result.type ..' 节点, ' .. result.alias)
  489. result.grouphashkey = groupHash
  490. tinsert(nodeResult[index], result)
  491. cache[groupHash][result.hashkey] = nodeResult[index][#nodeResult[index]]
  492. end
  493. end
  494. end
  495. end
  496. log('成功解析节点数量: ' .. #nodes)
  497. else
  498. log(url .. ': 获取内容为空')
  499. end
  500. end
  501. end
  502. -- diff
  503. do
  504. if next(nodeResult) == nil then
  505. log("更新失败,没有可用的节点信息")
  506. if proxy == '0' then
  507. luci.sys.init.start(name)
  508. log('订阅失败, 恢复服务')
  509. end
  510. return
  511. end
  512. local add, del = 0, 0
  513. ucic:foreach(name, uciType, function(old)
  514. if old.grouphashkey or old.hashkey then -- 没有 hash 的不参与删除
  515. if not nodeResult[old.grouphashkey] or not nodeResult[old.grouphashkey][old.hashkey] then
  516. ucic:delete(name, old['.name'])
  517. del = del + 1
  518. else
  519. local dat = nodeResult[old.grouphashkey][old.hashkey]
  520. ucic:tset(name, old['.name'], dat)
  521. -- 标记一下
  522. setmetatable(nodeResult[old.grouphashkey][old.hashkey], {__index = {_ignore = true}})
  523. end
  524. else
  525. if not old.alias then
  526. if old.server or old.server_port then
  527. old.alias = old.server .. ':' .. old.server_port
  528. log('忽略手动添加的节点: ' .. old.alias)
  529. else
  530. ucic:delete(name, old['.name'])
  531. end
  532. else
  533. log('忽略手动添加的节点: ' .. old.alias)
  534. end
  535. end
  536. end)
  537. for k, v in ipairs(nodeResult) do
  538. for kk, vv in ipairs(v) do
  539. if not vv._ignore then
  540. local section = ucic:add(name, uciType)
  541. ucic:tset(name, section, vv)
  542. ucic:set(name, section, "switch_enable", switch)
  543. add = add + 1
  544. end
  545. end
  546. end
  547. ucic:commit(name)
  548. -- 如果原有服务器节点已经不见了就尝试换为第一个节点
  549. local globalServer = ucic:get_first(name, 'global', 'global_server', '')
  550. if globalServer ~= "nil" then
  551. local firstServer = ucic:get_first(name, uciType)
  552. if firstServer then
  553. if not ucic:get(name, globalServer) then
  554. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  555. ucic:commit(name)
  556. ucic:set(name, ucic:get_first(name, 'global'), 'global_server', ucic:get_first(name, uciType))
  557. ucic:commit(name)
  558. log('当前主服务器节点已被删除,正在自动更换为第一个节点。')
  559. luci.sys.call("/etc/init.d/" .. name .. " start > /dev/null 2>&1 &")
  560. else
  561. log('维持当前主服务器节点。')
  562. luci.sys.call("/etc/init.d/" .. name .. " restart > /dev/null 2>&1 &")
  563. end
  564. else
  565. log('没有服务器节点了,停止服务')
  566. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  567. end
  568. end
  569. log('新增节点数量: ' .. add, '删除节点数量: ' .. del)
  570. log('订阅更新成功')
  571. end
  572. end
  573. if subscribe_url and #subscribe_url > 0 then
  574. xpcall(execute, function(e)
  575. log(e)
  576. log(debug.traceback())
  577. log('发生错误, 正在恢复服务')
  578. local firstServer = ucic:get_first(name, uciType)
  579. if firstServer then
  580. luci.sys.call("/etc/init.d/" .. name .. " restart > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  581. log('重启服务成功')
  582. else
  583. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  584. log('停止服务成功')
  585. end
  586. end)
  587. end