sub.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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 sniValue, ok := searchKey(xtlsSettings, "serverName"); ok {
  336. params["sni"], _ = sniValue.(string)
  337. }
  338. if fpValue, ok := searchKey(xtlsSettings, "fingerprint"); ok {
  339. params["fp"], _ = fpValue.(string)
  340. }
  341. if insecure, ok := searchKey(xtlsSettings, "allowInsecure"); ok {
  342. if insecure.(bool) {
  343. params["allowInsecure"] = "1"
  344. }
  345. }
  346. }
  347. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  348. params["flow"] = clients[clientIndex].Flow
  349. }
  350. serverName, _ := xtlsSetting["serverName"].(string)
  351. if serverName != "" {
  352. address = serverName
  353. }
  354. }
  355. link := fmt.Sprintf("vless://%s@%s:%d", uuid, address, port)
  356. url, _ := url.Parse(link)
  357. q := url.Query()
  358. for k, v := range params {
  359. q.Add(k, v)
  360. }
  361. // Set the new query values on the URL
  362. url.RawQuery = q.Encode()
  363. url.Fragment = email
  364. return url.String()
  365. }
  366. func (s *SubService) genTrojanLink(inbound *model.Inbound, email string) string {
  367. address := s.address
  368. if inbound.Protocol != model.Trojan {
  369. return ""
  370. }
  371. var stream map[string]interface{}
  372. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  373. clients, _ := s.inboundService.getClients(inbound)
  374. clientIndex := -1
  375. for i, client := range clients {
  376. if client.Email == email {
  377. clientIndex = i
  378. break
  379. }
  380. }
  381. password := clients[clientIndex].Password
  382. port := inbound.Port
  383. streamNetwork := stream["network"].(string)
  384. params := make(map[string]string)
  385. params["type"] = streamNetwork
  386. switch streamNetwork {
  387. case "tcp":
  388. tcp, _ := stream["tcpSettings"].(map[string]interface{})
  389. header, _ := tcp["header"].(map[string]interface{})
  390. typeStr, _ := header["type"].(string)
  391. if typeStr == "http" {
  392. request := header["request"].(map[string]interface{})
  393. requestPath, _ := request["path"].([]interface{})
  394. params["path"] = requestPath[0].(string)
  395. headers, _ := request["headers"].(map[string]interface{})
  396. params["host"] = searchHost(headers)
  397. params["headerType"] = "http"
  398. }
  399. case "kcp":
  400. kcp, _ := stream["kcpSettings"].(map[string]interface{})
  401. header, _ := kcp["header"].(map[string]interface{})
  402. params["headerType"] = header["type"].(string)
  403. params["seed"] = kcp["seed"].(string)
  404. case "ws":
  405. ws, _ := stream["wsSettings"].(map[string]interface{})
  406. params["path"] = ws["path"].(string)
  407. headers, _ := ws["headers"].(map[string]interface{})
  408. params["host"] = searchHost(headers)
  409. case "http":
  410. http, _ := stream["httpSettings"].(map[string]interface{})
  411. params["path"] = http["path"].(string)
  412. params["host"] = searchHost(http)
  413. case "quic":
  414. quic, _ := stream["quicSettings"].(map[string]interface{})
  415. params["quicSecurity"] = quic["security"].(string)
  416. params["key"] = quic["key"].(string)
  417. header := quic["header"].(map[string]interface{})
  418. params["headerType"] = header["type"].(string)
  419. case "grpc":
  420. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  421. params["serviceName"] = grpc["serviceName"].(string)
  422. }
  423. security, _ := stream["security"].(string)
  424. if security == "tls" {
  425. params["security"] = "tls"
  426. tlsSetting, _ := stream["tlsSettings"].(map[string]interface{})
  427. alpns, _ := tlsSetting["alpn"].([]interface{})
  428. var alpn []string
  429. for _, a := range alpns {
  430. alpn = append(alpn, a.(string))
  431. }
  432. if len(alpn) > 0 {
  433. params["alpn"] = strings.Join(alpn, ",")
  434. }
  435. tlsSettings, _ := searchKey(tlsSetting, "settings")
  436. if tlsSetting != nil {
  437. if sniValue, ok := searchKey(tlsSettings, "serverName"); ok {
  438. params["sni"], _ = sniValue.(string)
  439. }
  440. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  441. params["fp"], _ = fpValue.(string)
  442. }
  443. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  444. if insecure.(bool) {
  445. params["allowInsecure"] = "1"
  446. }
  447. }
  448. }
  449. serverName, _ := tlsSetting["serverName"].(string)
  450. if serverName != "" {
  451. address = serverName
  452. }
  453. }
  454. if security == "reality" {
  455. params["security"] = "reality"
  456. realitySetting, _ := stream["realitySettings"].(map[string]interface{})
  457. realitySettings, _ := searchKey(realitySetting, "settings")
  458. if realitySetting != nil {
  459. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  460. sNames, _ := sniValue.([]interface{})
  461. params["sni"], _ = sNames[0].(string)
  462. }
  463. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  464. params["pbk"], _ = pbkValue.(string)
  465. }
  466. if sidValue, ok := searchKey(realitySettings, "shortIds"); ok {
  467. shortIds, _ := sidValue.([]interface{})
  468. params["sid"], _ = shortIds[0].(string)
  469. }
  470. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  471. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  472. params["fp"] = fp
  473. }
  474. }
  475. if serverName, ok := searchKey(realitySettings, "serverName"); ok {
  476. if sname, ok := serverName.(string); ok && len(sname) > 0 {
  477. address = sname
  478. }
  479. }
  480. }
  481. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  482. params["flow"] = clients[clientIndex].Flow
  483. }
  484. }
  485. if security == "xtls" {
  486. params["security"] = "xtls"
  487. xtlsSetting, _ := stream["xtlsSettings"].(map[string]interface{})
  488. alpns, _ := xtlsSetting["alpn"].([]interface{})
  489. var alpn []string
  490. for _, a := range alpns {
  491. alpn = append(alpn, a.(string))
  492. }
  493. if len(alpn) > 0 {
  494. params["alpn"] = strings.Join(alpn, ",")
  495. }
  496. xtlsSettings, _ := searchKey(xtlsSetting, "settings")
  497. if xtlsSetting != nil {
  498. if sniValue, ok := searchKey(xtlsSettings, "serverName"); ok {
  499. params["sni"], _ = sniValue.(string)
  500. }
  501. if fpValue, ok := searchKey(xtlsSettings, "fingerprint"); ok {
  502. params["fp"], _ = fpValue.(string)
  503. }
  504. if insecure, ok := searchKey(xtlsSettings, "allowInsecure"); ok {
  505. if insecure.(bool) {
  506. params["allowInsecure"] = "1"
  507. }
  508. }
  509. }
  510. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  511. params["flow"] = clients[clientIndex].Flow
  512. }
  513. serverName, _ := xtlsSetting["serverName"].(string)
  514. if serverName != "" {
  515. address = serverName
  516. }
  517. }
  518. link := fmt.Sprintf("trojan://%s@%s:%d", password, address, port)
  519. url, _ := url.Parse(link)
  520. q := url.Query()
  521. for k, v := range params {
  522. q.Add(k, v)
  523. }
  524. // Set the new query values on the URL
  525. url.RawQuery = q.Encode()
  526. url.Fragment = email
  527. return url.String()
  528. }
  529. func searchKey(data interface{}, key string) (interface{}, bool) {
  530. switch val := data.(type) {
  531. case map[string]interface{}:
  532. for k, v := range val {
  533. if k == key {
  534. return v, true
  535. }
  536. if result, ok := searchKey(v, key); ok {
  537. return result, true
  538. }
  539. }
  540. case []interface{}:
  541. for _, v := range val {
  542. if result, ok := searchKey(v, key); ok {
  543. return result, true
  544. }
  545. }
  546. }
  547. return nil, false
  548. }
  549. func searchHost(headers interface{}) string {
  550. data, _ := headers.(map[string]interface{})
  551. for k, v := range data {
  552. if strings.EqualFold(k, "host") {
  553. switch v.(type) {
  554. case []interface{}:
  555. hosts, _ := v.([]interface{})
  556. return hosts[0].(string)
  557. case interface{}:
  558. return v.(string)
  559. }
  560. }
  561. }
  562. return ""
  563. }