subService.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. package sub
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "net/url"
  6. "strings"
  7. "time"
  8. "x-ui/database"
  9. "x-ui/database/model"
  10. "x-ui/logger"
  11. "x-ui/util/common"
  12. "x-ui/web/service"
  13. "x-ui/xray"
  14. "github.com/goccy/go-json"
  15. )
  16. type SubService struct {
  17. address string
  18. showInfo bool
  19. inboundService service.InboundService
  20. settingServics service.SettingService
  21. }
  22. func (s *SubService) GetSubs(subId string, host string, showInfo bool) ([]string, []string, error) {
  23. s.address = host
  24. s.showInfo = showInfo
  25. var result []string
  26. var headers []string
  27. var traffic xray.ClientTraffic
  28. var clientTraffics []xray.ClientTraffic
  29. inbounds, err := s.getInboundsBySubId(subId)
  30. if err != nil {
  31. return nil, nil, err
  32. }
  33. for _, inbound := range inbounds {
  34. clients, err := s.inboundService.GetClients(inbound)
  35. if err != nil {
  36. logger.Error("SubService - GetSub: Unable to get clients from inbound")
  37. }
  38. if clients == nil {
  39. continue
  40. }
  41. if len(inbound.Listen) > 0 && inbound.Listen[0] == '@' {
  42. fallbackMaster, err := s.getFallbackMaster(inbound.Listen)
  43. if err == nil {
  44. inbound.Listen = fallbackMaster.Listen
  45. inbound.Port = fallbackMaster.Port
  46. var stream map[string]interface{}
  47. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  48. var masterStream map[string]interface{}
  49. json.Unmarshal([]byte(fallbackMaster.StreamSettings), &masterStream)
  50. stream["security"] = masterStream["security"]
  51. stream["tlsSettings"] = masterStream["tlsSettings"]
  52. modifiedStream, _ := json.MarshalIndent(stream, "", " ")
  53. inbound.StreamSettings = string(modifiedStream)
  54. }
  55. }
  56. for _, client := range clients {
  57. if client.Enable && client.SubID == subId {
  58. link := s.getLink(inbound, client.Email)
  59. result = append(result, link)
  60. clientTraffics = append(clientTraffics, s.getClientTraffics(inbound.ClientStats, client.Email))
  61. }
  62. }
  63. }
  64. for index, clientTraffic := range clientTraffics {
  65. if index == 0 {
  66. traffic.Up = clientTraffic.Up
  67. traffic.Down = clientTraffic.Down
  68. traffic.Total = clientTraffic.Total
  69. if clientTraffic.ExpiryTime > 0 {
  70. traffic.ExpiryTime = clientTraffic.ExpiryTime
  71. }
  72. } else {
  73. traffic.Up += clientTraffic.Up
  74. traffic.Down += clientTraffic.Down
  75. if traffic.Total == 0 || clientTraffic.Total == 0 {
  76. traffic.Total = 0
  77. } else {
  78. traffic.Total += clientTraffic.Total
  79. }
  80. if clientTraffic.ExpiryTime != traffic.ExpiryTime {
  81. traffic.ExpiryTime = 0
  82. }
  83. }
  84. }
  85. headers = append(headers, fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000))
  86. updateInterval, _ := s.settingServics.GetSubUpdates()
  87. headers = append(headers, fmt.Sprintf("%d", updateInterval))
  88. headers = append(headers, subId)
  89. return result, headers, nil
  90. }
  91. func (s *SubService) getInboundsBySubId(subId string) ([]*model.Inbound, error) {
  92. db := database.GetDB()
  93. var inbounds []*model.Inbound
  94. err := db.Model(model.Inbound{}).Preload("ClientStats").Where("settings like ? and enable = ?", fmt.Sprintf(`%%"subId": "%s"%%`, subId), true).Find(&inbounds).Error
  95. if err != nil {
  96. return nil, err
  97. }
  98. return inbounds, nil
  99. }
  100. func (s *SubService) getClientTraffics(traffics []xray.ClientTraffic, email string) xray.ClientTraffic {
  101. for _, traffic := range traffics {
  102. if traffic.Email == email {
  103. return traffic
  104. }
  105. }
  106. return xray.ClientTraffic{}
  107. }
  108. func (s *SubService) getFallbackMaster(dest string) (*model.Inbound, error) {
  109. db := database.GetDB()
  110. var inbound *model.Inbound
  111. err := db.Model(model.Inbound{}).
  112. Where("JSON_TYPE(settings, '$.fallbacks') = 'array'").
  113. Where("EXISTS (SELECT * FROM json_each(settings, '$.fallbacks') WHERE json_extract(value, '$.dest') = ?)", dest).
  114. Find(&inbound).Error
  115. if err != nil {
  116. return nil, err
  117. }
  118. return inbound, nil
  119. }
  120. func (s *SubService) getLink(inbound *model.Inbound, email string) string {
  121. switch inbound.Protocol {
  122. case "vmess":
  123. return s.genVmessLink(inbound, email)
  124. case "vless":
  125. return s.genVlessLink(inbound, email)
  126. case "trojan":
  127. return s.genTrojanLink(inbound, email)
  128. case "shadowsocks":
  129. return s.genShadowsocksLink(inbound, email)
  130. }
  131. return ""
  132. }
  133. func (s *SubService) genVmessLink(inbound *model.Inbound, email string) string {
  134. if inbound.Protocol != model.VMess {
  135. return ""
  136. }
  137. obj := map[string]interface{}{
  138. "v": "2",
  139. "add": s.address,
  140. "port": inbound.Port,
  141. "type": "none",
  142. }
  143. var stream map[string]interface{}
  144. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  145. network, _ := stream["network"].(string)
  146. obj["net"] = network
  147. switch network {
  148. case "tcp":
  149. tcp, _ := stream["tcpSettings"].(map[string]interface{})
  150. header, _ := tcp["header"].(map[string]interface{})
  151. typeStr, _ := header["type"].(string)
  152. obj["type"] = typeStr
  153. if typeStr == "http" {
  154. request := header["request"].(map[string]interface{})
  155. requestPath, _ := request["path"].([]interface{})
  156. obj["path"] = requestPath[0].(string)
  157. headers, _ := request["headers"].(map[string]interface{})
  158. obj["host"] = searchHost(headers)
  159. }
  160. case "kcp":
  161. kcp, _ := stream["kcpSettings"].(map[string]interface{})
  162. header, _ := kcp["header"].(map[string]interface{})
  163. obj["type"], _ = header["type"].(string)
  164. obj["path"], _ = kcp["seed"].(string)
  165. case "ws":
  166. ws, _ := stream["wsSettings"].(map[string]interface{})
  167. obj["path"] = ws["path"].(string)
  168. headers, _ := ws["headers"].(map[string]interface{})
  169. obj["host"] = searchHost(headers)
  170. case "http":
  171. obj["net"] = "h2"
  172. http, _ := stream["httpSettings"].(map[string]interface{})
  173. obj["path"], _ = http["path"].(string)
  174. obj["host"] = searchHost(http)
  175. case "quic":
  176. quic, _ := stream["quicSettings"].(map[string]interface{})
  177. header := quic["header"].(map[string]interface{})
  178. obj["type"], _ = header["type"].(string)
  179. obj["host"], _ = quic["security"].(string)
  180. obj["path"], _ = quic["key"].(string)
  181. case "grpc":
  182. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  183. obj["path"] = grpc["serviceName"].(string)
  184. if grpc["multiMode"].(bool) {
  185. obj["type"] = "multi"
  186. }
  187. }
  188. security, _ := stream["security"].(string)
  189. var domains []interface{}
  190. obj["tls"] = security
  191. if security == "tls" {
  192. tlsSetting, _ := stream["tlsSettings"].(map[string]interface{})
  193. alpns, _ := tlsSetting["alpn"].([]interface{})
  194. if len(alpns) > 0 {
  195. var alpn []string
  196. for _, a := range alpns {
  197. alpn = append(alpn, a.(string))
  198. }
  199. obj["alpn"] = strings.Join(alpn, ",")
  200. }
  201. tlsSettings, _ := searchKey(tlsSetting, "settings")
  202. if tlsSetting != nil {
  203. if sniValue, ok := searchKey(tlsSettings, "serverName"); ok {
  204. obj["sni"], _ = sniValue.(string)
  205. }
  206. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  207. obj["fp"], _ = fpValue.(string)
  208. }
  209. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  210. obj["allowInsecure"], _ = insecure.(bool)
  211. }
  212. if domainSettings, ok := searchKey(tlsSettings, "domains"); ok {
  213. domains, _ = domainSettings.([]interface{})
  214. }
  215. }
  216. serverName, _ := tlsSetting["serverName"].(string)
  217. if serverName != "" {
  218. obj["add"] = serverName
  219. }
  220. }
  221. clients, _ := s.inboundService.GetClients(inbound)
  222. clientIndex := -1
  223. for i, client := range clients {
  224. if client.Email == email {
  225. clientIndex = i
  226. break
  227. }
  228. }
  229. obj["id"] = clients[clientIndex].ID
  230. if len(domains) > 0 {
  231. links := ""
  232. for index, d := range domains {
  233. domain := d.(map[string]interface{})
  234. obj["ps"] = s.genRemark(inbound, email, domain["remark"].(string))
  235. obj["add"] = domain["domain"].(string)
  236. if index > 0 {
  237. links += "\n"
  238. }
  239. jsonStr, _ := json.MarshalIndent(obj, "", " ")
  240. links += "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
  241. }
  242. return links
  243. }
  244. obj["ps"] = s.genRemark(inbound, email, "")
  245. jsonStr, _ := json.MarshalIndent(obj, "", " ")
  246. return "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
  247. }
  248. func (s *SubService) genVlessLink(inbound *model.Inbound, email string) string {
  249. address := s.address
  250. if inbound.Protocol != model.VLESS {
  251. return ""
  252. }
  253. var stream map[string]interface{}
  254. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  255. clients, _ := s.inboundService.GetClients(inbound)
  256. clientIndex := -1
  257. for i, client := range clients {
  258. if client.Email == email {
  259. clientIndex = i
  260. break
  261. }
  262. }
  263. uuid := clients[clientIndex].ID
  264. port := inbound.Port
  265. streamNetwork := stream["network"].(string)
  266. params := make(map[string]string)
  267. params["type"] = streamNetwork
  268. switch streamNetwork {
  269. case "tcp":
  270. tcp, _ := stream["tcpSettings"].(map[string]interface{})
  271. header, _ := tcp["header"].(map[string]interface{})
  272. typeStr, _ := header["type"].(string)
  273. if typeStr == "http" {
  274. request := header["request"].(map[string]interface{})
  275. requestPath, _ := request["path"].([]interface{})
  276. params["path"] = requestPath[0].(string)
  277. headers, _ := request["headers"].(map[string]interface{})
  278. params["host"] = searchHost(headers)
  279. params["headerType"] = "http"
  280. }
  281. case "kcp":
  282. kcp, _ := stream["kcpSettings"].(map[string]interface{})
  283. header, _ := kcp["header"].(map[string]interface{})
  284. params["headerType"] = header["type"].(string)
  285. params["seed"] = kcp["seed"].(string)
  286. case "ws":
  287. ws, _ := stream["wsSettings"].(map[string]interface{})
  288. params["path"] = ws["path"].(string)
  289. headers, _ := ws["headers"].(map[string]interface{})
  290. params["host"] = searchHost(headers)
  291. case "http":
  292. http, _ := stream["httpSettings"].(map[string]interface{})
  293. params["path"] = http["path"].(string)
  294. params["host"] = searchHost(http)
  295. case "quic":
  296. quic, _ := stream["quicSettings"].(map[string]interface{})
  297. params["quicSecurity"] = quic["security"].(string)
  298. params["key"] = quic["key"].(string)
  299. header := quic["header"].(map[string]interface{})
  300. params["headerType"] = header["type"].(string)
  301. case "grpc":
  302. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  303. params["serviceName"] = grpc["serviceName"].(string)
  304. if grpc["multiMode"].(bool) {
  305. params["mode"] = "multi"
  306. }
  307. }
  308. security, _ := stream["security"].(string)
  309. var domains []interface{}
  310. if security == "tls" {
  311. params["security"] = "tls"
  312. tlsSetting, _ := stream["tlsSettings"].(map[string]interface{})
  313. alpns, _ := tlsSetting["alpn"].([]interface{})
  314. var alpn []string
  315. for _, a := range alpns {
  316. alpn = append(alpn, a.(string))
  317. }
  318. if len(alpn) > 0 {
  319. params["alpn"] = strings.Join(alpn, ",")
  320. }
  321. tlsSettings, _ := searchKey(tlsSetting, "settings")
  322. if tlsSetting != nil {
  323. if sniValue, ok := searchKey(tlsSettings, "serverName"); ok {
  324. params["sni"], _ = sniValue.(string)
  325. }
  326. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  327. params["fp"], _ = fpValue.(string)
  328. }
  329. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  330. if insecure.(bool) {
  331. params["allowInsecure"] = "1"
  332. }
  333. }
  334. if domainSettings, ok := searchKey(tlsSettings, "domains"); ok {
  335. domains, _ = domainSettings.([]interface{})
  336. }
  337. }
  338. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  339. params["flow"] = clients[clientIndex].Flow
  340. }
  341. serverName, _ := tlsSetting["serverName"].(string)
  342. if serverName != "" {
  343. address = serverName
  344. }
  345. }
  346. if security == "reality" {
  347. params["security"] = "reality"
  348. realitySetting, _ := stream["realitySettings"].(map[string]interface{})
  349. realitySettings, _ := searchKey(realitySetting, "settings")
  350. if realitySetting != nil {
  351. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  352. sNames, _ := sniValue.([]interface{})
  353. params["sni"], _ = sNames[0].(string)
  354. }
  355. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  356. params["pbk"], _ = pbkValue.(string)
  357. }
  358. if sidValue, ok := searchKey(realitySetting, "shortIds"); ok {
  359. shortIds, _ := sidValue.([]interface{})
  360. params["sid"], _ = shortIds[0].(string)
  361. }
  362. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  363. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  364. params["fp"] = fp
  365. }
  366. }
  367. if spxValue, ok := searchKey(realitySettings, "spiderX"); ok {
  368. if spx, ok := spxValue.(string); ok && len(spx) > 0 {
  369. params["spx"] = spx
  370. }
  371. }
  372. if serverName, ok := searchKey(realitySettings, "serverName"); ok {
  373. if sname, ok := serverName.(string); ok && len(sname) > 0 {
  374. address = sname
  375. }
  376. }
  377. }
  378. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  379. params["flow"] = clients[clientIndex].Flow
  380. }
  381. }
  382. if security == "xtls" {
  383. params["security"] = "xtls"
  384. xtlsSetting, _ := stream["xtlsSettings"].(map[string]interface{})
  385. alpns, _ := xtlsSetting["alpn"].([]interface{})
  386. var alpn []string
  387. for _, a := range alpns {
  388. alpn = append(alpn, a.(string))
  389. }
  390. if len(alpn) > 0 {
  391. params["alpn"] = strings.Join(alpn, ",")
  392. }
  393. xtlsSettings, _ := searchKey(xtlsSetting, "settings")
  394. if xtlsSetting != nil {
  395. if fpValue, ok := searchKey(xtlsSettings, "fingerprint"); ok {
  396. params["fp"], _ = fpValue.(string)
  397. }
  398. if insecure, ok := searchKey(xtlsSettings, "allowInsecure"); ok {
  399. if insecure.(bool) {
  400. params["allowInsecure"] = "1"
  401. }
  402. }
  403. if sniValue, ok := searchKey(xtlsSettings, "serverName"); ok {
  404. params["sni"], _ = sniValue.(string)
  405. }
  406. }
  407. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  408. params["flow"] = clients[clientIndex].Flow
  409. }
  410. serverName, _ := xtlsSetting["serverName"].(string)
  411. if serverName != "" {
  412. address = serverName
  413. }
  414. }
  415. if security != "tls" && security != "reality" && security != "xtls" {
  416. params["security"] = "none"
  417. }
  418. link := fmt.Sprintf("vless://%s@%s:%d", uuid, address, port)
  419. url, _ := url.Parse(link)
  420. q := url.Query()
  421. for k, v := range params {
  422. q.Add(k, v)
  423. }
  424. // Set the new query values on the URL
  425. url.RawQuery = q.Encode()
  426. if len(domains) > 0 {
  427. links := ""
  428. for index, d := range domains {
  429. domain := d.(map[string]interface{})
  430. url.Fragment = s.genRemark(inbound, email, domain["remark"].(string))
  431. url.Host = fmt.Sprintf("%s:%d", domain["domain"].(string), port)
  432. if index > 0 {
  433. links += "\n"
  434. }
  435. links += url.String()
  436. }
  437. return links
  438. }
  439. url.Fragment = s.genRemark(inbound, email, "")
  440. return url.String()
  441. }
  442. func (s *SubService) genTrojanLink(inbound *model.Inbound, email string) string {
  443. address := s.address
  444. if inbound.Protocol != model.Trojan {
  445. return ""
  446. }
  447. var stream map[string]interface{}
  448. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  449. clients, _ := s.inboundService.GetClients(inbound)
  450. clientIndex := -1
  451. for i, client := range clients {
  452. if client.Email == email {
  453. clientIndex = i
  454. break
  455. }
  456. }
  457. password := clients[clientIndex].Password
  458. port := inbound.Port
  459. streamNetwork := stream["network"].(string)
  460. params := make(map[string]string)
  461. params["type"] = streamNetwork
  462. switch streamNetwork {
  463. case "tcp":
  464. tcp, _ := stream["tcpSettings"].(map[string]interface{})
  465. header, _ := tcp["header"].(map[string]interface{})
  466. typeStr, _ := header["type"].(string)
  467. if typeStr == "http" {
  468. request := header["request"].(map[string]interface{})
  469. requestPath, _ := request["path"].([]interface{})
  470. params["path"] = requestPath[0].(string)
  471. headers, _ := request["headers"].(map[string]interface{})
  472. params["host"] = searchHost(headers)
  473. params["headerType"] = "http"
  474. }
  475. case "kcp":
  476. kcp, _ := stream["kcpSettings"].(map[string]interface{})
  477. header, _ := kcp["header"].(map[string]interface{})
  478. params["headerType"] = header["type"].(string)
  479. params["seed"] = kcp["seed"].(string)
  480. case "ws":
  481. ws, _ := stream["wsSettings"].(map[string]interface{})
  482. params["path"] = ws["path"].(string)
  483. headers, _ := ws["headers"].(map[string]interface{})
  484. params["host"] = searchHost(headers)
  485. case "http":
  486. http, _ := stream["httpSettings"].(map[string]interface{})
  487. params["path"] = http["path"].(string)
  488. params["host"] = searchHost(http)
  489. case "quic":
  490. quic, _ := stream["quicSettings"].(map[string]interface{})
  491. params["quicSecurity"] = quic["security"].(string)
  492. params["key"] = quic["key"].(string)
  493. header := quic["header"].(map[string]interface{})
  494. params["headerType"] = header["type"].(string)
  495. case "grpc":
  496. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  497. params["serviceName"] = grpc["serviceName"].(string)
  498. if grpc["multiMode"].(bool) {
  499. params["mode"] = "multi"
  500. }
  501. }
  502. security, _ := stream["security"].(string)
  503. var domains []interface{}
  504. if security == "tls" {
  505. params["security"] = "tls"
  506. tlsSetting, _ := stream["tlsSettings"].(map[string]interface{})
  507. alpns, _ := tlsSetting["alpn"].([]interface{})
  508. var alpn []string
  509. for _, a := range alpns {
  510. alpn = append(alpn, a.(string))
  511. }
  512. if len(alpn) > 0 {
  513. params["alpn"] = strings.Join(alpn, ",")
  514. }
  515. tlsSettings, _ := searchKey(tlsSetting, "settings")
  516. if tlsSetting != nil {
  517. if sniValue, ok := searchKey(tlsSettings, "serverName"); ok {
  518. params["sni"], _ = sniValue.(string)
  519. }
  520. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  521. params["fp"], _ = fpValue.(string)
  522. }
  523. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  524. if insecure.(bool) {
  525. params["allowInsecure"] = "1"
  526. }
  527. }
  528. if domainSettings, ok := searchKey(tlsSettings, "domains"); ok {
  529. domains, _ = domainSettings.([]interface{})
  530. }
  531. }
  532. serverName, _ := tlsSetting["serverName"].(string)
  533. if serverName != "" {
  534. address = serverName
  535. }
  536. }
  537. if security == "reality" {
  538. params["security"] = "reality"
  539. realitySetting, _ := stream["realitySettings"].(map[string]interface{})
  540. realitySettings, _ := searchKey(realitySetting, "settings")
  541. if realitySetting != nil {
  542. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  543. sNames, _ := sniValue.([]interface{})
  544. params["sni"], _ = sNames[0].(string)
  545. }
  546. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  547. params["pbk"], _ = pbkValue.(string)
  548. }
  549. if sidValue, ok := searchKey(realitySetting, "shortIds"); ok {
  550. shortIds, _ := sidValue.([]interface{})
  551. params["sid"], _ = shortIds[0].(string)
  552. }
  553. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  554. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  555. params["fp"] = fp
  556. }
  557. }
  558. if spxValue, ok := searchKey(realitySettings, "spiderX"); ok {
  559. if spx, ok := spxValue.(string); ok && len(spx) > 0 {
  560. params["spx"] = spx
  561. }
  562. }
  563. if serverName, ok := searchKey(realitySettings, "serverName"); ok {
  564. if sname, ok := serverName.(string); ok && len(sname) > 0 {
  565. address = sname
  566. }
  567. }
  568. }
  569. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  570. params["flow"] = clients[clientIndex].Flow
  571. }
  572. }
  573. if security == "xtls" {
  574. params["security"] = "xtls"
  575. xtlsSetting, _ := stream["xtlsSettings"].(map[string]interface{})
  576. alpns, _ := xtlsSetting["alpn"].([]interface{})
  577. var alpn []string
  578. for _, a := range alpns {
  579. alpn = append(alpn, a.(string))
  580. }
  581. if len(alpn) > 0 {
  582. params["alpn"] = strings.Join(alpn, ",")
  583. }
  584. xtlsSettings, _ := searchKey(xtlsSetting, "settings")
  585. if xtlsSetting != nil {
  586. if fpValue, ok := searchKey(xtlsSettings, "fingerprint"); ok {
  587. params["fp"], _ = fpValue.(string)
  588. }
  589. if insecure, ok := searchKey(xtlsSettings, "allowInsecure"); ok {
  590. if insecure.(bool) {
  591. params["allowInsecure"] = "1"
  592. }
  593. }
  594. if sniValue, ok := searchKey(xtlsSettings, "serverName"); ok {
  595. params["sni"], _ = sniValue.(string)
  596. }
  597. }
  598. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  599. params["flow"] = clients[clientIndex].Flow
  600. }
  601. serverName, _ := xtlsSetting["serverName"].(string)
  602. if serverName != "" {
  603. address = serverName
  604. }
  605. }
  606. if security != "tls" && security != "reality" && security != "xtls" {
  607. params["security"] = "none"
  608. }
  609. link := fmt.Sprintf("trojan://%s@%s:%d", password, address, port)
  610. url, _ := url.Parse(link)
  611. q := url.Query()
  612. for k, v := range params {
  613. q.Add(k, v)
  614. }
  615. // Set the new query values on the URL
  616. url.RawQuery = q.Encode()
  617. if len(domains) > 0 {
  618. links := ""
  619. for index, d := range domains {
  620. domain := d.(map[string]interface{})
  621. url.Fragment = s.genRemark(inbound, email, domain["remark"].(string))
  622. url.Host = fmt.Sprintf("%s:%d", domain["domain"].(string), port)
  623. if index > 0 {
  624. links += "\n"
  625. }
  626. links += url.String()
  627. }
  628. return links
  629. }
  630. url.Fragment = s.genRemark(inbound, email, "")
  631. return url.String()
  632. }
  633. func (s *SubService) genShadowsocksLink(inbound *model.Inbound, email string) string {
  634. address := s.address
  635. if inbound.Protocol != model.Shadowsocks {
  636. return ""
  637. }
  638. var stream map[string]interface{}
  639. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  640. clients, _ := s.inboundService.GetClients(inbound)
  641. var settings map[string]interface{}
  642. json.Unmarshal([]byte(inbound.Settings), &settings)
  643. inboundPassword := settings["password"].(string)
  644. method := settings["method"].(string)
  645. clientIndex := -1
  646. for i, client := range clients {
  647. if client.Email == email {
  648. clientIndex = i
  649. break
  650. }
  651. }
  652. streamNetwork := stream["network"].(string)
  653. params := make(map[string]string)
  654. params["type"] = streamNetwork
  655. switch streamNetwork {
  656. case "tcp":
  657. tcp, _ := stream["tcpSettings"].(map[string]interface{})
  658. header, _ := tcp["header"].(map[string]interface{})
  659. typeStr, _ := header["type"].(string)
  660. if typeStr == "http" {
  661. request := header["request"].(map[string]interface{})
  662. requestPath, _ := request["path"].([]interface{})
  663. params["path"] = requestPath[0].(string)
  664. headers, _ := request["headers"].(map[string]interface{})
  665. params["host"] = searchHost(headers)
  666. params["headerType"] = "http"
  667. }
  668. case "kcp":
  669. kcp, _ := stream["kcpSettings"].(map[string]interface{})
  670. header, _ := kcp["header"].(map[string]interface{})
  671. params["headerType"] = header["type"].(string)
  672. params["seed"] = kcp["seed"].(string)
  673. case "ws":
  674. ws, _ := stream["wsSettings"].(map[string]interface{})
  675. params["path"] = ws["path"].(string)
  676. headers, _ := ws["headers"].(map[string]interface{})
  677. params["host"] = searchHost(headers)
  678. case "http":
  679. http, _ := stream["httpSettings"].(map[string]interface{})
  680. params["path"] = http["path"].(string)
  681. params["host"] = searchHost(http)
  682. case "quic":
  683. quic, _ := stream["quicSettings"].(map[string]interface{})
  684. params["quicSecurity"] = quic["security"].(string)
  685. params["key"] = quic["key"].(string)
  686. header := quic["header"].(map[string]interface{})
  687. params["headerType"] = header["type"].(string)
  688. case "grpc":
  689. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  690. params["serviceName"] = grpc["serviceName"].(string)
  691. if grpc["multiMode"].(bool) {
  692. params["mode"] = "multi"
  693. }
  694. }
  695. encPart := fmt.Sprintf("%s:%s", method, clients[clientIndex].Password)
  696. if method[0] == '2' {
  697. encPart = fmt.Sprintf("%s:%s:%s", method, inboundPassword, clients[clientIndex].Password)
  698. }
  699. link := fmt.Sprintf("ss://%s@%s:%d", base64.StdEncoding.EncodeToString([]byte(encPart)), address, inbound.Port)
  700. url, _ := url.Parse(link)
  701. q := url.Query()
  702. for k, v := range params {
  703. q.Add(k, v)
  704. }
  705. // Set the new query values on the URL
  706. url.RawQuery = q.Encode()
  707. url.Fragment = s.genRemark(inbound, email, "")
  708. return url.String()
  709. }
  710. func (s *SubService) genRemark(inbound *model.Inbound, email string, extra string) string {
  711. var remark []string
  712. if len(email) > 0 {
  713. if len(inbound.Remark) > 0 {
  714. remark = append(remark, inbound.Remark)
  715. }
  716. remark = append(remark, email)
  717. if len(extra) > 0 {
  718. remark = append(remark, extra)
  719. }
  720. } else {
  721. return inbound.Remark
  722. }
  723. if s.showInfo {
  724. statsExist := false
  725. var stats xray.ClientTraffic
  726. for _, clientStat := range inbound.ClientStats {
  727. if clientStat.Email == email {
  728. stats = clientStat
  729. statsExist = true
  730. break
  731. }
  732. }
  733. // Get remained days
  734. if statsExist {
  735. if !stats.Enable {
  736. return fmt.Sprintf("⛔️N/A-%s", strings.Join(remark, "-"))
  737. }
  738. if vol := stats.Total - (stats.Up + stats.Down); vol > 0 {
  739. remark = append(remark, fmt.Sprintf("%s%s", common.FormatTraffic(vol), "📊"))
  740. }
  741. now := time.Now().Unix()
  742. switch exp := stats.ExpiryTime / 1000; {
  743. case exp > 0:
  744. remark = append(remark, fmt.Sprintf("%d%s⏳", (exp-now)/86400, "Days"))
  745. case exp < 0:
  746. remark = append(remark, fmt.Sprintf("%d%s⏳", exp/-86400, "Days"))
  747. }
  748. }
  749. }
  750. return strings.Join(remark, " : ")
  751. }
  752. func searchKey(data interface{}, key string) (interface{}, bool) {
  753. switch val := data.(type) {
  754. case map[string]interface{}:
  755. for k, v := range val {
  756. if k == key {
  757. return v, true
  758. }
  759. if result, ok := searchKey(v, key); ok {
  760. return result, true
  761. }
  762. }
  763. case []interface{}:
  764. for _, v := range val {
  765. if result, ok := searchKey(v, key); ok {
  766. return result, true
  767. }
  768. }
  769. }
  770. return nil, false
  771. }
  772. func searchHost(headers interface{}) string {
  773. data, _ := headers.(map[string]interface{})
  774. for k, v := range data {
  775. if strings.EqualFold(k, "host") {
  776. switch v.(type) {
  777. case []interface{}:
  778. hosts, _ := v.([]interface{})
  779. if len(hosts) > 0 {
  780. return hosts[0].(string)
  781. } else {
  782. return ""
  783. }
  784. case interface{}:
  785. return v.(string)
  786. }
  787. }
  788. }
  789. return ""
  790. }