subService.go 26 KB

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