subService.go 28 KB

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