subService.go 27 KB

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