subService.go 28 KB

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