subService.go 31 KB

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