subscribe.lua 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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 = 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.security == "tls" then
  352. result.tls = "1"
  353. result.tls_host = params.sni or host[1]
  354. else
  355. result.tls = "0"
  356. end
  357. else
  358. result.server_port = host[2]
  359. end
  360. end
  361. if not result.alias then
  362. if result.server and result.server_port then
  363. result.alias = result.server .. ':' .. result.server_port
  364. else
  365. result.alias = "NULL"
  366. end
  367. end
  368. -- alias 不参与 hashkey 计算
  369. local alias = result.alias
  370. result.alias = nil
  371. local switch_enable = result.switch_enable
  372. result.switch_enable = nil
  373. result.hashkey = md5(jsonStringify(result))
  374. result.alias = alias
  375. result.switch_enable = switch_enable
  376. return result
  377. end
  378. -- wget
  379. local function wget(url)
  380. 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 .. '"')
  381. return trim(stdout)
  382. end
  383. local function check_filer(result)
  384. do
  385. local filter_word = split(filter_words, "/")
  386. for i, v in pairs(filter_word) do
  387. if result.alias:find(v) then
  388. -- log('订阅节点关键字过滤:“' .. v ..'” ,该节点被丢弃')
  389. return true
  390. end
  391. end
  392. end
  393. end
  394. local execute = function()
  395. -- exec
  396. do
  397. if proxy == '0' then -- 不使用代理更新的话先暂停
  398. log('服务正在暂停')
  399. luci.sys.init.stop(name)
  400. end
  401. for k, url in ipairs(subscribe_url) do
  402. local raw = wget(url)
  403. if #raw > 0 then
  404. local nodes, szType
  405. local groupHash = md5(url)
  406. cache[groupHash] = {}
  407. tinsert(nodeResult, {})
  408. local index = #nodeResult
  409. -- SSD 似乎是这种格式 ssd:// 开头的
  410. if raw:find('ssd://') then
  411. szType = 'ssd'
  412. local nEnd = select(2, raw:find('ssd://'))
  413. nodes = base64Decode(raw:sub(nEnd + 1, #raw))
  414. nodes = jsonParse(nodes)
  415. local extra = {airport = nodes.airport, port = nodes.port, encryption = nodes.encryption, password = nodes.password}
  416. local servers = {}
  417. -- SS里面包着 干脆直接这样
  418. for _, server in ipairs(nodes.servers) do
  419. tinsert(servers, setmetatable(server, {__index = extra}))
  420. end
  421. nodes = servers
  422. else
  423. -- ssd 外的格式
  424. nodes = split(base64Decode(raw):gsub(" ", "_"), "\n")
  425. end
  426. for _, v in ipairs(nodes) do
  427. if v then
  428. local result
  429. if szType == 'ssd' then
  430. result = processData(szType, v)
  431. elseif not szType then
  432. local node = trim(v)
  433. local dat = split(node, "://")
  434. if dat and dat[1] and dat[2] then
  435. local dat3 = ""
  436. if dat[3] then
  437. dat3 = "://" .. dat[3]
  438. end
  439. if dat[1] == 'ss' or dat[1] == 'trojan' then
  440. result = processData(dat[1], dat[2] .. dat3)
  441. else
  442. result = processData(dat[1], base64Decode(dat[2]))
  443. end
  444. end
  445. else
  446. log('跳过未知类型: ' .. szType)
  447. end
  448. -- log(result)
  449. if result then
  450. -- 中文做地址的 也没有人拿中文域名搞,就算中文域也有Puny Code SB 机场
  451. 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
  452. log('丢弃无效节点: ' .. result.type .. ' 节点, ' .. result.alias)
  453. else
  454. -- log('成功解析: ' .. result.type ..' 节点, ' .. result.alias)
  455. result.grouphashkey = groupHash
  456. tinsert(nodeResult[index], result)
  457. cache[groupHash][result.hashkey] = nodeResult[index][#nodeResult[index]]
  458. end
  459. end
  460. end
  461. end
  462. log('成功解析节点数量: ' .. #nodes)
  463. else
  464. log(url .. ': 获取内容为空')
  465. end
  466. end
  467. end
  468. -- diff
  469. do
  470. if next(nodeResult) == nil then
  471. log("更新失败,没有可用的节点信息")
  472. if proxy == '0' then
  473. luci.sys.init.start(name)
  474. log('订阅失败, 恢复服务')
  475. end
  476. return
  477. end
  478. local add, del = 0, 0
  479. ucic:foreach(name, uciType, function(old)
  480. if old.grouphashkey or old.hashkey then -- 没有 hash 的不参与删除
  481. if not nodeResult[old.grouphashkey] or not nodeResult[old.grouphashkey][old.hashkey] then
  482. ucic:delete(name, old['.name'])
  483. del = del + 1
  484. else
  485. local dat = nodeResult[old.grouphashkey][old.hashkey]
  486. ucic:tset(name, old['.name'], dat)
  487. -- 标记一下
  488. setmetatable(nodeResult[old.grouphashkey][old.hashkey], {__index = {_ignore = true}})
  489. end
  490. else
  491. if not old.alias then
  492. if old.server or old.server_port then
  493. old.alias = old.server .. ':' .. old.server_port
  494. log('忽略手动添加的节点: ' .. old.alias)
  495. else
  496. ucic:delete(name, old['.name'])
  497. end
  498. else
  499. log('忽略手动添加的节点: ' .. old.alias)
  500. end
  501. end
  502. end)
  503. for k, v in ipairs(nodeResult) do
  504. for kk, vv in ipairs(v) do
  505. if not vv._ignore then
  506. local section = ucic:add(name, uciType)
  507. ucic:tset(name, section, vv)
  508. ucic:set(name, section, "switch_enable", switch)
  509. add = add + 1
  510. end
  511. end
  512. end
  513. ucic:commit(name)
  514. -- 如果原有服务器节点已经不见了就尝试换为第一个节点
  515. local globalServer = ucic:get_first(name, 'global', 'global_server', '')
  516. if globalServer ~= "nil" then
  517. local firstServer = ucic:get_first(name, uciType)
  518. if firstServer then
  519. if not ucic:get(name, globalServer) then
  520. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  521. ucic:commit(name)
  522. ucic:set(name, ucic:get_first(name, 'global'), 'global_server', ucic:get_first(name, uciType))
  523. ucic:commit(name)
  524. log('当前主服务器节点已被删除,正在自动更换为第一个节点。')
  525. luci.sys.call("/etc/init.d/" .. name .. " start > /dev/null 2>&1 &")
  526. else
  527. log('维持当前主服务器节点。')
  528. luci.sys.call("/etc/init.d/" .. name .. " restart > /dev/null 2>&1 &")
  529. end
  530. else
  531. log('没有服务器节点了,停止服务')
  532. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &")
  533. end
  534. end
  535. log('新增节点数量: ' .. add, '删除节点数量: ' .. del)
  536. log('订阅更新成功')
  537. end
  538. end
  539. if subscribe_url and #subscribe_url > 0 then
  540. xpcall(execute, function(e)
  541. log(e)
  542. log(debug.traceback())
  543. log('发生错误, 正在恢复服务')
  544. local firstServer = ucic:get_first(name, uciType)
  545. if firstServer then
  546. luci.sys.call("/etc/init.d/" .. name .. " restart > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  547. log('重启服务成功')
  548. else
  549. luci.sys.call("/etc/init.d/" .. name .. " stop > /dev/null 2>&1 &") -- 不加&的话日志会出现的更早
  550. log('停止服务成功')
  551. end
  552. end)
  553. end