subService.go 28 KB

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