subscribe.lua 16 KB

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