sub.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. package service
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "net/url"
  6. "strings"
  7. "x-ui/database"
  8. "x-ui/database/model"
  9. "x-ui/logger"
  10. "x-ui/xray"
  11. "github.com/goccy/go-json"
  12. "gorm.io/gorm"
  13. )
  14. type SubService struct {
  15. address string
  16. inboundService InboundService
  17. }
  18. func (s *SubService) GetSubs(subId string, host string) ([]string, string, error) {
  19. s.address = host
  20. var result []string
  21. var header string
  22. var traffic xray.ClientTraffic
  23. var clientTraffics []xray.ClientTraffic
  24. inbounds, err := s.getInboundsBySubId(subId)
  25. if err != nil {
  26. return nil, "", err
  27. }
  28. for _, inbound := range inbounds {
  29. clients, err := s.inboundService.getClients(inbound)
  30. if err != nil {
  31. logger.Error("SubService - GetSub: Unable to get clients from inbound")
  32. }
  33. if clients == nil {
  34. continue
  35. }
  36. for _, client := range clients {
  37. if client.SubID == subId {
  38. link := s.getLink(inbound, client.Email)
  39. result = append(result, link)
  40. clientTraffics = append(clientTraffics, s.getClientTraffics(inbound.ClientStats, client.Email))
  41. }
  42. }
  43. }
  44. for index, clientTraffic := range clientTraffics {
  45. if index == 0 {
  46. traffic.Up = clientTraffic.Up
  47. traffic.Down = clientTraffic.Down
  48. traffic.Total = clientTraffic.Total
  49. if clientTraffic.ExpiryTime > 0 {
  50. traffic.ExpiryTime = clientTraffic.ExpiryTime
  51. }
  52. } else {
  53. traffic.Up += clientTraffic.Up
  54. traffic.Down += clientTraffic.Down
  55. if traffic.Total == 0 || clientTraffic.Total == 0 {
  56. traffic.Total = 0
  57. } else {
  58. traffic.Total += clientTraffic.Total
  59. }
  60. if clientTraffic.ExpiryTime != traffic.ExpiryTime {
  61. traffic.ExpiryTime = 0
  62. }
  63. }
  64. }
  65. header = fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  66. return result, header, nil
  67. }
  68. func (s *SubService) getInboundsBySubId(subId string) ([]*model.Inbound, error) {
  69. db := database.GetDB()
  70. var inbounds []*model.Inbound
  71. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("settings like ?", fmt.Sprintf(`%%"subId": "%s"%%`, subId)).Find(&inbounds).Error
  72. if err != nil && err != gorm.ErrRecordNotFound {
  73. return nil, err
  74. }
  75. return inbounds, nil
  76. }
  77. func (s *SubService) getClientTraffics(traffics []xray.ClientTraffic, email string) xray.ClientTraffic {
  78. for _, traffic := range traffics {
  79. if traffic.Email == email {
  80. return traffic
  81. }
  82. }
  83. return xray.ClientTraffic{}
  84. }
  85. func (s *SubService) getLink(inbound *model.Inbound, email string) string {
  86. switch inbound.Protocol {
  87. case "vmess":
  88. return s.genVmessLink(inbound, email)
  89. case "vless":
  90. return s.genVlessLink(inbound, email)
  91. case "trojan":
  92. return s.genTrojanLink(inbound, email)
  93. }
  94. return ""
  95. }
  96. func (s *SubService) genVmessLink(inbound *model.Inbound, email string) string {
  97. if inbound.Protocol != model.VMess {
  98. return ""
  99. }
  100. obj := map[string]interface{}{
  101. "v": "2",
  102. "ps": email,
  103. "add": s.address,
  104. "port": inbound.Port,
  105. "type": "none",
  106. }
  107. var stream map[string]interface{}
  108. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  109. network, _ := stream["network"].(string)
  110. obj["net"] = network
  111. switch network {
  112. case "tcp":
  113. tcp, _ := stream["tcpSettings"].(map[string]interface{})
  114. header, _ := tcp["header"].(map[string]interface{})
  115. typeStr, _ := header["type"].(string)
  116. obj["type"] = typeStr
  117. if typeStr == "http" {
  118. request := header["request"].(map[string]interface{})
  119. requestPath, _ := request["path"].([]interface{})
  120. obj["path"] = requestPath[0].(string)
  121. headers, _ := request["headers"].(map[string]interface{})
  122. obj["host"] = searchHost(headers)
  123. }
  124. case "kcp":
  125. kcp, _ := stream["kcpSettings"].(map[string]interface{})
  126. header, _ := kcp["header"].(map[string]interface{})
  127. obj["type"], _ = header["type"].(string)
  128. obj["path"], _ = kcp["seed"].(string)
  129. case "ws":
  130. ws, _ := stream["wsSettings"].(map[string]interface{})
  131. obj["path"] = ws["path"].(string)
  132. headers, _ := ws["headers"].(map[string]interface{})
  133. obj["host"] = searchHost(headers)
  134. case "http":
  135. obj["net"] = "h2"
  136. http, _ := stream["httpSettings"].(map[string]interface{})
  137. obj["path"], _ = http["path"].(string)
  138. obj["host"] = searchHost(http)
  139. case "quic":
  140. quic, _ := stream["quicSettings"].(map[string]interface{})
  141. header := quic["header"].(map[string]interface{})
  142. obj["type"], _ = header["type"].(string)
  143. obj["host"], _ = quic["security"].(string)
  144. obj["path"], _ = quic["key"].(string)
  145. case "grpc":
  146. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  147. obj["path"] = grpc["serviceName"].(string)
  148. if grpc["multiMode"].(bool) {
  149. obj["type"] = "multi"
  150. }
  151. }
  152. security, _ := stream["security"].(string)
  153. obj["tls"] = security
  154. if security == "tls" {
  155. tlsSetting, _ := stream["tlsSettings"].(map[string]interface{})
  156. alpns, _ := tlsSetting["alpn"].([]interface{})
  157. if len(alpns) > 0 {
  158. var alpn []string
  159. for _, a := range alpns {
  160. alpn = append(alpn, a.(string))
  161. }
  162. obj["alpn"] = strings.Join(alpn, ",")
  163. }
  164. tlsSettings, _ := searchKey(tlsSetting, "settings")
  165. if tlsSetting != nil {
  166. if sniValue, ok := searchKey(tlsSettings, "serverName"); ok {
  167. obj["sni"], _ = sniValue.(string)
  168. }
  169. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  170. obj["fp"], _ = fpValue.(string)
  171. }
  172. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  173. obj["allowInsecure"], _ = insecure.(bool)
  174. }
  175. }
  176. serverName, _ := tlsSetting["serverName"].(string)
  177. if serverName != "" {
  178. obj["add"] = serverName
  179. }
  180. }
  181. clients, _ := s.inboundService.getClients(inbound)
  182. clientIndex := -1
  183. for i, client := range clients {
  184. if client.Email == email {
  185. clientIndex = i
  186. break
  187. }
  188. }
  189. obj["id"] = clients[clientIndex].ID
  190. obj["aid"] = clients[clientIndex].AlterIds
  191. jsonStr, _ := json.MarshalIndent(obj, "", " ")
  192. return "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
  193. }
  194. func (s *SubService) genVlessLink(inbound *model.Inbound, email string) string {
  195. address := s.address
  196. if inbound.Protocol != model.VLESS {
  197. return ""
  198. }
  199. var stream map[string]interface{}
  200. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  201. clients, _ := s.inboundService.getClients(inbound)
  202. clientIndex := -1
  203. for i, client := range clients {
  204. if client.Email == email {
  205. clientIndex = i
  206. break
  207. }
  208. }
  209. uuid := clients[clientIndex].ID
  210. port := inbound.Port
  211. streamNetwork := stream["network"].(string)
  212. params := make(map[string]string)
  213. params["type"] = streamNetwork
  214. switch streamNetwork {
  215. case "tcp":
  216. tcp, _ := stream["tcpSettings"].(map[string]interface{})
  217. header, _ := tcp["header"].(map[string]interface{})
  218. typeStr, _ := header["type"].(string)
  219. if typeStr == "http" {
  220. request := header["request"].(map[string]interface{})
  221. requestPath, _ := request["path"].([]interface{})
  222. params["path"] = requestPath[0].(string)
  223. headers, _ := request["headers"].(map[string]interface{})
  224. params["host"] = searchHost(headers)
  225. params["headerType"] = "http"
  226. }
  227. case "kcp":
  228. kcp, _ := stream["kcpSettings"].(map[string]interface{})
  229. header, _ := kcp["header"].(map[string]interface{})
  230. params["headerType"] = header["type"].(string)
  231. params["seed"] = kcp["seed"].(string)
  232. case "ws":
  233. ws, _ := stream["wsSettings"].(map[string]interface{})
  234. params["path"] = ws["path"].(string)
  235. headers, _ := ws["headers"].(map[string]interface{})
  236. params["host"] = searchHost(headers)
  237. case "http":
  238. http, _ := stream["httpSettings"].(map[string]interface{})
  239. params["path"] = http["path"].(string)
  240. params["host"] = searchHost(http)
  241. case "quic":
  242. quic, _ := stream["quicSettings"].(map[string]interface{})
  243. params["quicSecurity"] = quic["security"].(string)
  244. params["key"] = quic["key"].(string)
  245. header := quic["header"].(map[string]interface{})
  246. params["headerType"] = header["type"].(string)
  247. case "grpc":
  248. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  249. params["serviceName"] = grpc["serviceName"].(string)
  250. if grpc["multiMode"].(bool) {
  251. params["mode"] = "multi"
  252. }
  253. }
  254. security, _ := stream["security"].(string)
  255. if security == "tls" {
  256. params["security"] = "tls"
  257. tlsSetting, _ := stream["tlsSettings"].(map[string]interface{})
  258. alpns, _ := tlsSetting["alpn"].([]interface{})
  259. var alpn []string
  260. for _, a := range alpns {
  261. alpn = append(alpn, a.(string))
  262. }
  263. if len(alpn) > 0 {
  264. params["alpn"] = strings.Join(alpn, ",")
  265. }
  266. tlsSettings, _ := searchKey(tlsSetting, "settings")
  267. if tlsSetting != nil {
  268. if sniValue, ok := searchKey(tlsSettings, "serverName"); ok {
  269. params["sni"], _ = sniValue.(string)
  270. }
  271. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  272. params["fp"], _ = fpValue.(string)
  273. }
  274. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  275. if insecure.(bool) {
  276. params["allowInsecure"] = "1"
  277. }
  278. }
  279. }
  280. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  281. params["flow"] = clients[clientIndex].Flow
  282. }
  283. serverName, _ := tlsSetting["serverName"].(string)
  284. if serverName != "" {
  285. address = serverName
  286. }
  287. }
  288. if security == "reality" {
  289. params["security"] = "reality"
  290. realitySetting, _ := stream["realitySettings"].(map[string]interface{})
  291. realitySettings, _ := searchKey(realitySetting, "settings")
  292. if realitySetting != nil {
  293. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  294. sNames, _ := sniValue.([]interface{})
  295. params["sni"], _ = sNames[0].(string)
  296. }
  297. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  298. params["pbk"], _ = pbkValue.(string)
  299. }
  300. if sidValue, ok := searchKey(realitySetting, "shortIds"); ok {
  301. shortIds, _ := sidValue.([]interface{})
  302. params["sid"], _ = shortIds[0].(string)
  303. }
  304. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  305. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  306. params["fp"] = fp
  307. }
  308. }
  309. if serverName, ok := searchKey(realitySettings, "serverName"); ok {
  310. if sname, ok := serverName.(string); ok && len(sname) > 0 {
  311. address = sname
  312. }
  313. }
  314. }
  315. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  316. params["flow"] = clients[clientIndex].Flow
  317. }
  318. }
  319. if security == "xtls" {
  320. params["security"] = "xtls"
  321. xtlsSetting, _ := stream["xtlsSettings"].(map[string]interface{})
  322. alpns, _ := xtlsSetting["alpn"].([]interface{})
  323. var alpn []string
  324. for _, a := range alpns {
  325. alpn = append(alpn, a.(string))
  326. }
  327. if len(alpn) > 0 {
  328. params["alpn"] = strings.Join(alpn, ",")
  329. }
  330. xtlsSettings, _ := searchKey(xtlsSetting, "settings")
  331. if xtlsSetting != nil {
  332. if fpValue, ok := searchKey(xtlsSettings, "fingerprint"); ok {
  333. params["fp"], _ = fpValue.(string)
  334. }
  335. if insecure, ok := searchKey(xtlsSettings, "allowInsecure"); ok {
  336. if insecure.(bool) {
  337. params["allowInsecure"] = "1"
  338. }
  339. }
  340. }
  341. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  342. params["flow"] = clients[clientIndex].Flow
  343. }
  344. serverName, _ := xtlsSetting["serverName"].(string)
  345. if serverName != "" {
  346. address = serverName
  347. }
  348. }
  349. link := fmt.Sprintf("vless://%s@%s:%d", uuid, address, port)
  350. url, _ := url.Parse(link)
  351. q := url.Query()
  352. for k, v := range params {
  353. q.Add(k, v)
  354. }
  355. // Set the new query values on the URL
  356. url.RawQuery = q.Encode()
  357. url.Fragment = email
  358. return url.String()
  359. }
  360. func (s *SubService) genTrojanLink(inbound *model.Inbound, email string) string {
  361. address := s.address
  362. if inbound.Protocol != model.Trojan {
  363. return ""
  364. }
  365. var stream map[string]interface{}
  366. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  367. clients, _ := s.inboundService.getClients(inbound)
  368. clientIndex := -1
  369. for i, client := range clients {
  370. if client.Email == email {
  371. clientIndex = i
  372. break
  373. }
  374. }
  375. password := clients[clientIndex].Password
  376. port := inbound.Port
  377. streamNetwork := stream["network"].(string)
  378. params := make(map[string]string)
  379. params["type"] = streamNetwork
  380. switch streamNetwork {
  381. case "tcp":
  382. tcp, _ := stream["tcpSettings"].(map[string]interface{})
  383. header, _ := tcp["header"].(map[string]interface{})
  384. typeStr, _ := header["type"].(string)
  385. if typeStr == "http" {
  386. request := header["request"].(map[string]interface{})
  387. requestPath, _ := request["path"].([]interface{})
  388. params["path"] = requestPath[0].(string)
  389. headers, _ := request["headers"].(map[string]interface{})
  390. params["host"] = searchHost(headers)
  391. params["headerType"] = "http"
  392. }
  393. case "kcp":
  394. kcp, _ := stream["kcpSettings"].(map[string]interface{})
  395. header, _ := kcp["header"].(map[string]interface{})
  396. params["headerType"] = header["type"].(string)
  397. params["seed"] = kcp["seed"].(string)
  398. case "ws":
  399. ws, _ := stream["wsSettings"].(map[string]interface{})
  400. params["path"] = ws["path"].(string)
  401. headers, _ := ws["headers"].(map[string]interface{})
  402. params["host"] = searchHost(headers)
  403. case "http":
  404. http, _ := stream["httpSettings"].(map[string]interface{})
  405. params["path"] = http["path"].(string)
  406. params["host"] = searchHost(http)
  407. case "quic":
  408. quic, _ := stream["quicSettings"].(map[string]interface{})
  409. params["quicSecurity"] = quic["security"].(string)
  410. params["key"] = quic["key"].(string)
  411. header := quic["header"].(map[string]interface{})
  412. params["headerType"] = header["type"].(string)
  413. case "grpc":
  414. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  415. params["serviceName"] = grpc["serviceName"].(string)
  416. if grpc["multiMode"].(bool) {
  417. params["mode"] = "multi"
  418. }
  419. }
  420. security, _ := stream["security"].(string)
  421. if security == "tls" {
  422. params["security"] = "tls"
  423. tlsSetting, _ := stream["tlsSettings"].(map[string]interface{})
  424. alpns, _ := tlsSetting["alpn"].([]interface{})
  425. var alpn []string
  426. for _, a := range alpns {
  427. alpn = append(alpn, a.(string))
  428. }
  429. if len(alpn) > 0 {
  430. params["alpn"] = strings.Join(alpn, ",")
  431. }
  432. tlsSettings, _ := searchKey(tlsSetting, "settings")
  433. if tlsSetting != nil {
  434. if sniValue, ok := searchKey(tlsSettings, "serverName"); ok {
  435. params["sni"], _ = sniValue.(string)
  436. }
  437. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  438. params["fp"], _ = fpValue.(string)
  439. }
  440. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  441. if insecure.(bool) {
  442. params["allowInsecure"] = "1"
  443. }
  444. }
  445. }
  446. serverName, _ := tlsSetting["serverName"].(string)
  447. if serverName != "" {
  448. address = serverName
  449. }
  450. }
  451. if security == "reality" {
  452. params["security"] = "reality"
  453. realitySetting, _ := stream["realitySettings"].(map[string]interface{})
  454. realitySettings, _ := searchKey(realitySetting, "settings")
  455. if realitySetting != nil {
  456. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  457. sNames, _ := sniValue.([]interface{})
  458. params["sni"], _ = sNames[0].(string)
  459. }
  460. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  461. params["pbk"], _ = pbkValue.(string)
  462. }
  463. if sidValue, ok := searchKey(realitySettings, "shortIds"); ok {
  464. shortIds, _ := sidValue.([]interface{})
  465. params["sid"], _ = shortIds[0].(string)
  466. }
  467. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  468. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  469. params["fp"] = fp
  470. }
  471. }
  472. if serverName, ok := searchKey(realitySettings, "serverName"); ok {
  473. if sname, ok := serverName.(string); ok && len(sname) > 0 {
  474. address = sname
  475. }
  476. }
  477. }
  478. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  479. params["flow"] = clients[clientIndex].Flow
  480. }
  481. }
  482. if security == "xtls" {
  483. params["security"] = "xtls"
  484. xtlsSetting, _ := stream["xtlsSettings"].(map[string]interface{})
  485. alpns, _ := xtlsSetting["alpn"].([]interface{})
  486. var alpn []string
  487. for _, a := range alpns {
  488. alpn = append(alpn, a.(string))
  489. }
  490. if len(alpn) > 0 {
  491. params["alpn"] = strings.Join(alpn, ",")
  492. }
  493. xtlsSettings, _ := searchKey(xtlsSetting, "settings")
  494. if xtlsSetting != nil {
  495. if fpValue, ok := searchKey(xtlsSettings, "fingerprint"); ok {
  496. params["fp"], _ = fpValue.(string)
  497. }
  498. if insecure, ok := searchKey(xtlsSettings, "allowInsecure"); ok {
  499. if insecure.(bool) {
  500. params["allowInsecure"] = "1"
  501. }
  502. }
  503. }
  504. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  505. params["flow"] = clients[clientIndex].Flow
  506. }
  507. serverName, _ := xtlsSetting["serverName"].(string)
  508. if serverName != "" {
  509. address = serverName
  510. }
  511. }
  512. link := fmt.Sprintf("trojan://%s@%s:%d", password, address, port)
  513. url, _ := url.Parse(link)
  514. q := url.Query()
  515. for k, v := range params {
  516. q.Add(k, v)
  517. }
  518. // Set the new query values on the URL
  519. url.RawQuery = q.Encode()
  520. url.Fragment = email
  521. return url.String()
  522. }
  523. func searchKey(data interface{}, key string) (interface{}, bool) {
  524. switch val := data.(type) {
  525. case map[string]interface{}:
  526. for k, v := range val {
  527. if k == key {
  528. return v, true
  529. }
  530. if result, ok := searchKey(v, key); ok {
  531. return result, true
  532. }
  533. }
  534. case []interface{}:
  535. for _, v := range val {
  536. if result, ok := searchKey(v, key); ok {
  537. return result, true
  538. }
  539. }
  540. }
  541. return nil, false
  542. }
  543. func searchHost(headers interface{}) string {
  544. data, _ := headers.(map[string]interface{})
  545. for k, v := range data {
  546. if strings.EqualFold(k, "host") {
  547. switch v.(type) {
  548. case []interface{}:
  549. hosts, _ := v.([]interface{})
  550. if len(hosts) > 0 {
  551. return hosts[0].(string)
  552. } else {
  553. return ""
  554. }
  555. case interface{}:
  556. return v.(string)
  557. }
  558. }
  559. }
  560. return ""
  561. }