1
0

subService.go 27 KB

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