subService.go 28 KB

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