subService.go 32 KB

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