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. address := s.address
  98. if inbound.Protocol != model.VMess {
  99. return ""
  100. }
  101. var stream map[string]interface{}
  102. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  103. network, _ := stream["network"].(string)
  104. typeStr := "none"
  105. host := ""
  106. path := ""
  107. sni := ""
  108. fp := ""
  109. var alpn []string
  110. allowInsecure := false
  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. if typeStr == "http" {
  117. request := header["request"].(map[string]interface{})
  118. requestPath, _ := request["path"].([]interface{})
  119. path = requestPath[0].(string)
  120. headers, _ := request["headers"].(map[string]interface{})
  121. host = searchHost(headers)
  122. }
  123. case "kcp":
  124. kcp, _ := stream["kcpSettings"].(map[string]interface{})
  125. header, _ := kcp["header"].(map[string]interface{})
  126. typeStr, _ = header["type"].(string)
  127. path, _ = kcp["seed"].(string)
  128. case "ws":
  129. ws, _ := stream["wsSettings"].(map[string]interface{})
  130. path = ws["path"].(string)
  131. headers, _ := ws["headers"].(map[string]interface{})
  132. host = searchHost(headers)
  133. case "http":
  134. network = "h2"
  135. http, _ := stream["httpSettings"].(map[string]interface{})
  136. path, _ = http["path"].(string)
  137. host = searchHost(http)
  138. case "quic":
  139. quic, _ := stream["quicSettings"].(map[string]interface{})
  140. header := quic["header"].(map[string]interface{})
  141. typeStr, _ = header["type"].(string)
  142. host, _ = quic["security"].(string)
  143. path, _ = quic["key"].(string)
  144. case "grpc":
  145. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  146. path = grpc["serviceName"].(string)
  147. }
  148. security, _ := stream["security"].(string)
  149. if security == "tls" {
  150. tlsSetting, _ := stream["tlsSettings"].(map[string]interface{})
  151. alpns, _ := tlsSetting["alpn"].([]interface{})
  152. for _, a := range alpns {
  153. alpn = append(alpn, a.(string))
  154. }
  155. tlsSettings, _ := searchKey(tlsSetting, "settings")
  156. if tlsSetting != nil {
  157. if sniValue, ok := searchKey(tlsSettings, "serverName"); ok {
  158. sni, _ = sniValue.(string)
  159. }
  160. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  161. fp, _ = fpValue.(string)
  162. }
  163. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  164. allowInsecure, _ = insecure.(bool)
  165. }
  166. }
  167. serverName, _ := tlsSetting["serverName"].(string)
  168. if serverName != "" {
  169. address = serverName
  170. }
  171. }
  172. clients, _ := s.inboundService.getClients(inbound)
  173. clientIndex := -1
  174. for i, client := range clients {
  175. if client.Email == email {
  176. clientIndex = i
  177. break
  178. }
  179. }
  180. obj := map[string]interface{}{
  181. "v": "2",
  182. "ps": email,
  183. "add": address,
  184. "port": inbound.Port,
  185. "id": clients[clientIndex].ID,
  186. "aid": clients[clientIndex].AlterIds,
  187. "net": network,
  188. "type": typeStr,
  189. "host": host,
  190. "path": path,
  191. "tls": security,
  192. "sni": sni,
  193. "fp": fp,
  194. "alpn": strings.Join(alpn, ","),
  195. "allowInsecure": allowInsecure,
  196. }
  197. jsonStr, _ := json.MarshalIndent(obj, "", " ")
  198. return "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
  199. }
  200. func (s *SubService) genVlessLink(inbound *model.Inbound, email string) string {
  201. address := s.address
  202. if inbound.Protocol != model.VLESS {
  203. return ""
  204. }
  205. var stream map[string]interface{}
  206. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  207. clients, _ := s.inboundService.getClients(inbound)
  208. clientIndex := -1
  209. for i, client := range clients {
  210. if client.Email == email {
  211. clientIndex = i
  212. break
  213. }
  214. }
  215. uuid := clients[clientIndex].ID
  216. port := inbound.Port
  217. streamNetwork := stream["network"].(string)
  218. params := make(map[string]string)
  219. params["type"] = streamNetwork
  220. switch streamNetwork {
  221. case "tcp":
  222. tcp, _ := stream["tcpSettings"].(map[string]interface{})
  223. header, _ := tcp["header"].(map[string]interface{})
  224. typeStr, _ := header["type"].(string)
  225. if typeStr == "http" {
  226. request := header["request"].(map[string]interface{})
  227. requestPath, _ := request["path"].([]interface{})
  228. params["path"] = requestPath[0].(string)
  229. headers, _ := request["headers"].(map[string]interface{})
  230. params["host"] = searchHost(headers)
  231. params["headerType"] = "http"
  232. }
  233. case "kcp":
  234. kcp, _ := stream["kcpSettings"].(map[string]interface{})
  235. header, _ := kcp["header"].(map[string]interface{})
  236. params["headerType"] = header["type"].(string)
  237. params["seed"] = kcp["seed"].(string)
  238. case "ws":
  239. ws, _ := stream["wsSettings"].(map[string]interface{})
  240. params["path"] = ws["path"].(string)
  241. headers, _ := ws["headers"].(map[string]interface{})
  242. params["host"] = searchHost(headers)
  243. case "http":
  244. http, _ := stream["httpSettings"].(map[string]interface{})
  245. params["path"] = http["path"].(string)
  246. params["host"] = searchHost(http)
  247. case "quic":
  248. quic, _ := stream["quicSettings"].(map[string]interface{})
  249. params["quicSecurity"] = quic["security"].(string)
  250. params["key"] = quic["key"].(string)
  251. header := quic["header"].(map[string]interface{})
  252. params["headerType"] = header["type"].(string)
  253. case "grpc":
  254. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  255. params["serviceName"] = grpc["serviceName"].(string)
  256. }
  257. security, _ := stream["security"].(string)
  258. if security == "tls" {
  259. params["security"] = "tls"
  260. tlsSetting, _ := stream["tlsSettings"].(map[string]interface{})
  261. alpns, _ := tlsSetting["alpn"].([]interface{})
  262. var alpn []string
  263. for _, a := range alpns {
  264. alpn = append(alpn, a.(string))
  265. }
  266. if len(alpn) > 0 {
  267. params["alpn"] = strings.Join(alpn, ",")
  268. }
  269. tlsSettings, _ := searchKey(tlsSetting, "settings")
  270. if tlsSetting != nil {
  271. if sniValue, ok := searchKey(tlsSettings, "serverName"); ok {
  272. params["sni"], _ = sniValue.(string)
  273. }
  274. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  275. params["fp"], _ = fpValue.(string)
  276. }
  277. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  278. if insecure.(bool) {
  279. params["allowInsecure"] = "1"
  280. }
  281. }
  282. }
  283. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  284. params["flow"] = clients[clientIndex].Flow
  285. }
  286. serverName, _ := tlsSetting["serverName"].(string)
  287. if serverName != "" {
  288. address = serverName
  289. }
  290. }
  291. if security == "reality" {
  292. params["security"] = "reality"
  293. realitySetting, _ := stream["realitySettings"].(map[string]interface{})
  294. realitySettings, _ := searchKey(realitySetting, "settings")
  295. if realitySetting != nil {
  296. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  297. sNames, _ := sniValue.([]interface{})
  298. params["sni"], _ = sNames[0].(string)
  299. }
  300. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  301. params["pbk"], _ = pbkValue.(string)
  302. }
  303. if sidValue, ok := searchKey(realitySetting, "shortIds"); ok {
  304. shortIds, _ := sidValue.([]interface{})
  305. params["sid"], _ = shortIds[0].(string)
  306. }
  307. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  308. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  309. params["fp"] = fp
  310. }
  311. }
  312. if serverName, ok := searchKey(realitySettings, "serverName"); ok {
  313. if sname, ok := serverName.(string); ok && len(sname) > 0 {
  314. address = sname
  315. }
  316. }
  317. }
  318. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  319. params["flow"] = clients[clientIndex].Flow
  320. }
  321. }
  322. if security == "xtls" {
  323. params["security"] = "xtls"
  324. xtlsSetting, _ := stream["xtlsSettings"].(map[string]interface{})
  325. alpns, _ := xtlsSetting["alpn"].([]interface{})
  326. var alpn []string
  327. for _, a := range alpns {
  328. alpn = append(alpn, a.(string))
  329. }
  330. if len(alpn) > 0 {
  331. params["alpn"] = strings.Join(alpn, ",")
  332. }
  333. xtlsSettings, _ := searchKey(xtlsSetting, "settings")
  334. if xtlsSetting != nil {
  335. if fpValue, ok := searchKey(xtlsSettings, "fingerprint"); ok {
  336. params["fp"], _ = fpValue.(string)
  337. }
  338. if insecure, ok := searchKey(xtlsSettings, "allowInsecure"); ok {
  339. if insecure.(bool) {
  340. params["allowInsecure"] = "1"
  341. }
  342. }
  343. }
  344. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  345. params["flow"] = clients[clientIndex].Flow
  346. }
  347. serverName, _ := xtlsSetting["serverName"].(string)
  348. if serverName != "" {
  349. address = serverName
  350. }
  351. }
  352. link := fmt.Sprintf("vless://%s@%s:%d", uuid, address, port)
  353. url, _ := url.Parse(link)
  354. q := url.Query()
  355. for k, v := range params {
  356. q.Add(k, v)
  357. }
  358. // Set the new query values on the URL
  359. url.RawQuery = q.Encode()
  360. url.Fragment = email
  361. return url.String()
  362. }
  363. func (s *SubService) genTrojanLink(inbound *model.Inbound, email string) string {
  364. address := s.address
  365. if inbound.Protocol != model.Trojan {
  366. return ""
  367. }
  368. var stream map[string]interface{}
  369. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  370. clients, _ := s.inboundService.getClients(inbound)
  371. clientIndex := -1
  372. for i, client := range clients {
  373. if client.Email == email {
  374. clientIndex = i
  375. break
  376. }
  377. }
  378. password := clients[clientIndex].Password
  379. port := inbound.Port
  380. streamNetwork := stream["network"].(string)
  381. params := make(map[string]string)
  382. params["type"] = streamNetwork
  383. switch streamNetwork {
  384. case "tcp":
  385. tcp, _ := stream["tcpSettings"].(map[string]interface{})
  386. header, _ := tcp["header"].(map[string]interface{})
  387. typeStr, _ := header["type"].(string)
  388. if typeStr == "http" {
  389. request := header["request"].(map[string]interface{})
  390. requestPath, _ := request["path"].([]interface{})
  391. params["path"] = requestPath[0].(string)
  392. headers, _ := request["headers"].(map[string]interface{})
  393. params["host"] = searchHost(headers)
  394. params["headerType"] = "http"
  395. }
  396. case "kcp":
  397. kcp, _ := stream["kcpSettings"].(map[string]interface{})
  398. header, _ := kcp["header"].(map[string]interface{})
  399. params["headerType"] = header["type"].(string)
  400. params["seed"] = kcp["seed"].(string)
  401. case "ws":
  402. ws, _ := stream["wsSettings"].(map[string]interface{})
  403. params["path"] = ws["path"].(string)
  404. headers, _ := ws["headers"].(map[string]interface{})
  405. params["host"] = searchHost(headers)
  406. case "http":
  407. http, _ := stream["httpSettings"].(map[string]interface{})
  408. params["path"] = http["path"].(string)
  409. params["host"] = searchHost(http)
  410. case "quic":
  411. quic, _ := stream["quicSettings"].(map[string]interface{})
  412. params["quicSecurity"] = quic["security"].(string)
  413. params["key"] = quic["key"].(string)
  414. header := quic["header"].(map[string]interface{})
  415. params["headerType"] = header["type"].(string)
  416. case "grpc":
  417. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  418. params["serviceName"] = grpc["serviceName"].(string)
  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. }