sub.go 17 KB

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