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