subService.go 28 KB

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