subService.go 28 KB

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