subService.go 27 KB

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