1
0

sub.go 17 KB

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