subService.go 29 KB

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