subService.go 25 KB

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