subService.go 31 KB

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