sub.go 17 KB

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