subService.go 28 KB

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