subService.go 28 KB

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