1
0

subService.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  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 "grpc":
  196. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  197. obj["path"] = grpc["serviceName"].(string)
  198. obj["authority"] = grpc["authority"].(string)
  199. if grpc["multiMode"].(bool) {
  200. obj["type"] = "multi"
  201. }
  202. case "httpupgrade":
  203. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]interface{})
  204. obj["path"] = httpupgrade["path"].(string)
  205. if host, ok := httpupgrade["host"].(string); ok && len(host) > 0 {
  206. obj["host"] = host
  207. } else {
  208. headers, _ := httpupgrade["headers"].(map[string]interface{})
  209. obj["host"] = searchHost(headers)
  210. }
  211. case "xhttp":
  212. xhttp, _ := stream["xhttpSettings"].(map[string]interface{})
  213. obj["path"] = xhttp["path"].(string)
  214. if host, ok := xhttp["host"].(string); ok && len(host) > 0 {
  215. obj["host"] = host
  216. } else {
  217. headers, _ := xhttp["headers"].(map[string]interface{})
  218. obj["host"] = searchHost(headers)
  219. }
  220. obj["mode"] = xhttp["mode"].(string)
  221. }
  222. security, _ := stream["security"].(string)
  223. obj["tls"] = security
  224. if security == "tls" {
  225. tlsSetting, _ := stream["tlsSettings"].(map[string]interface{})
  226. alpns, _ := tlsSetting["alpn"].([]interface{})
  227. if len(alpns) > 0 {
  228. var alpn []string
  229. for _, a := range alpns {
  230. alpn = append(alpn, a.(string))
  231. }
  232. obj["alpn"] = strings.Join(alpn, ",")
  233. }
  234. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  235. obj["sni"], _ = sniValue.(string)
  236. }
  237. tlsSettings, _ := searchKey(tlsSetting, "settings")
  238. if tlsSetting != nil {
  239. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  240. obj["fp"], _ = fpValue.(string)
  241. }
  242. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  243. obj["allowInsecure"], _ = insecure.(bool)
  244. }
  245. }
  246. }
  247. clients, _ := s.inboundService.GetClients(inbound)
  248. clientIndex := -1
  249. for i, client := range clients {
  250. if client.Email == email {
  251. clientIndex = i
  252. break
  253. }
  254. }
  255. obj["id"] = clients[clientIndex].ID
  256. obj["scy"] = clients[clientIndex].Security
  257. externalProxies, _ := stream["externalProxy"].([]interface{})
  258. if len(externalProxies) > 0 {
  259. links := ""
  260. for index, externalProxy := range externalProxies {
  261. ep, _ := externalProxy.(map[string]interface{})
  262. newSecurity, _ := ep["forceTls"].(string)
  263. newObj := map[string]interface{}{}
  264. for key, value := range obj {
  265. if !(newSecurity == "none" && (key == "alpn" || key == "sni" || key == "fp" || key == "allowInsecure")) {
  266. newObj[key] = value
  267. }
  268. }
  269. newObj["ps"] = s.genRemark(inbound, email, ep["remark"].(string))
  270. newObj["add"] = ep["dest"].(string)
  271. newObj["port"] = int(ep["port"].(float64))
  272. if newSecurity != "same" {
  273. newObj["tls"] = newSecurity
  274. }
  275. if index > 0 {
  276. links += "\n"
  277. }
  278. jsonStr, _ := json.MarshalIndent(newObj, "", " ")
  279. links += "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
  280. }
  281. return links
  282. }
  283. obj["ps"] = s.genRemark(inbound, email, "")
  284. jsonStr, _ := json.MarshalIndent(obj, "", " ")
  285. return "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
  286. }
  287. func (s *SubService) genVlessLink(inbound *model.Inbound, email string) string {
  288. address := s.address
  289. if inbound.Protocol != model.VLESS {
  290. return ""
  291. }
  292. var stream map[string]interface{}
  293. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  294. clients, _ := s.inboundService.GetClients(inbound)
  295. clientIndex := -1
  296. for i, client := range clients {
  297. if client.Email == email {
  298. clientIndex = i
  299. break
  300. }
  301. }
  302. uuid := clients[clientIndex].ID
  303. port := inbound.Port
  304. streamNetwork := stream["network"].(string)
  305. params := make(map[string]string)
  306. params["type"] = streamNetwork
  307. switch streamNetwork {
  308. case "tcp":
  309. tcp, _ := stream["tcpSettings"].(map[string]interface{})
  310. header, _ := tcp["header"].(map[string]interface{})
  311. typeStr, _ := header["type"].(string)
  312. if typeStr == "http" {
  313. request := header["request"].(map[string]interface{})
  314. requestPath, _ := request["path"].([]interface{})
  315. params["path"] = requestPath[0].(string)
  316. headers, _ := request["headers"].(map[string]interface{})
  317. params["host"] = searchHost(headers)
  318. params["headerType"] = "http"
  319. }
  320. case "kcp":
  321. kcp, _ := stream["kcpSettings"].(map[string]interface{})
  322. header, _ := kcp["header"].(map[string]interface{})
  323. params["headerType"] = header["type"].(string)
  324. params["seed"] = kcp["seed"].(string)
  325. case "ws":
  326. ws, _ := stream["wsSettings"].(map[string]interface{})
  327. params["path"] = ws["path"].(string)
  328. if host, ok := ws["host"].(string); ok && len(host) > 0 {
  329. params["host"] = host
  330. } else {
  331. headers, _ := ws["headers"].(map[string]interface{})
  332. params["host"] = searchHost(headers)
  333. }
  334. case "grpc":
  335. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  336. params["serviceName"] = grpc["serviceName"].(string)
  337. params["authority"], _ = grpc["authority"].(string)
  338. if grpc["multiMode"].(bool) {
  339. params["mode"] = "multi"
  340. }
  341. case "httpupgrade":
  342. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]interface{})
  343. params["path"] = httpupgrade["path"].(string)
  344. if host, ok := httpupgrade["host"].(string); ok && len(host) > 0 {
  345. params["host"] = host
  346. } else {
  347. headers, _ := httpupgrade["headers"].(map[string]interface{})
  348. params["host"] = searchHost(headers)
  349. }
  350. case "xhttp":
  351. xhttp, _ := stream["xhttpSettings"].(map[string]interface{})
  352. params["path"] = xhttp["path"].(string)
  353. if host, ok := xhttp["host"].(string); ok && len(host) > 0 {
  354. params["host"] = host
  355. } else {
  356. headers, _ := xhttp["headers"].(map[string]interface{})
  357. params["host"] = searchHost(headers)
  358. }
  359. params["mode"] = xhttp["mode"].(string)
  360. }
  361. security, _ := stream["security"].(string)
  362. if security == "tls" {
  363. params["security"] = "tls"
  364. tlsSetting, _ := stream["tlsSettings"].(map[string]interface{})
  365. alpns, _ := tlsSetting["alpn"].([]interface{})
  366. var alpn []string
  367. for _, a := range alpns {
  368. alpn = append(alpn, a.(string))
  369. }
  370. if len(alpn) > 0 {
  371. params["alpn"] = strings.Join(alpn, ",")
  372. }
  373. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  374. params["sni"], _ = sniValue.(string)
  375. }
  376. tlsSettings, _ := searchKey(tlsSetting, "settings")
  377. if tlsSetting != nil {
  378. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  379. params["fp"], _ = fpValue.(string)
  380. }
  381. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  382. if insecure.(bool) {
  383. params["allowInsecure"] = "1"
  384. }
  385. }
  386. }
  387. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  388. params["flow"] = clients[clientIndex].Flow
  389. }
  390. }
  391. if security == "reality" {
  392. params["security"] = "reality"
  393. realitySetting, _ := stream["realitySettings"].(map[string]interface{})
  394. realitySettings, _ := searchKey(realitySetting, "settings")
  395. if realitySetting != nil {
  396. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  397. sNames, _ := sniValue.([]interface{})
  398. params["sni"] = sNames[random.Num(len(sNames))].(string)
  399. }
  400. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  401. params["pbk"], _ = pbkValue.(string)
  402. }
  403. if sidValue, ok := searchKey(realitySetting, "shortIds"); ok {
  404. shortIds, _ := sidValue.([]interface{})
  405. params["sid"] = shortIds[random.Num(len(shortIds))].(string)
  406. }
  407. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  408. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  409. params["fp"] = fp
  410. }
  411. }
  412. params["spx"] = "/" + random.Seq(15)
  413. }
  414. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  415. params["flow"] = clients[clientIndex].Flow
  416. }
  417. }
  418. if security != "tls" && security != "reality" {
  419. params["security"] = "none"
  420. }
  421. externalProxies, _ := stream["externalProxy"].([]interface{})
  422. if len(externalProxies) > 0 {
  423. links := ""
  424. for index, externalProxy := range externalProxies {
  425. ep, _ := externalProxy.(map[string]interface{})
  426. newSecurity, _ := ep["forceTls"].(string)
  427. dest, _ := ep["dest"].(string)
  428. port := int(ep["port"].(float64))
  429. link := fmt.Sprintf("vless://%s@%s:%d", uuid, dest, port)
  430. if newSecurity != "same" {
  431. params["security"] = newSecurity
  432. } else {
  433. params["security"] = security
  434. }
  435. url, _ := url.Parse(link)
  436. q := url.Query()
  437. for k, v := range params {
  438. if !(newSecurity == "none" && (k == "alpn" || k == "sni" || k == "fp" || k == "allowInsecure")) {
  439. q.Add(k, v)
  440. }
  441. }
  442. // Set the new query values on the URL
  443. url.RawQuery = q.Encode()
  444. url.Fragment = s.genRemark(inbound, email, ep["remark"].(string))
  445. if index > 0 {
  446. links += "\n"
  447. }
  448. links += url.String()
  449. }
  450. return links
  451. }
  452. link := fmt.Sprintf("vless://%s@%s:%d", uuid, address, port)
  453. url, _ := url.Parse(link)
  454. q := url.Query()
  455. for k, v := range params {
  456. q.Add(k, v)
  457. }
  458. // Set the new query values on the URL
  459. url.RawQuery = q.Encode()
  460. url.Fragment = s.genRemark(inbound, email, "")
  461. return url.String()
  462. }
  463. func (s *SubService) genTrojanLink(inbound *model.Inbound, email string) string {
  464. address := s.address
  465. if inbound.Protocol != model.Trojan {
  466. return ""
  467. }
  468. var stream map[string]interface{}
  469. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  470. clients, _ := s.inboundService.GetClients(inbound)
  471. clientIndex := -1
  472. for i, client := range clients {
  473. if client.Email == email {
  474. clientIndex = i
  475. break
  476. }
  477. }
  478. password := clients[clientIndex].Password
  479. port := inbound.Port
  480. streamNetwork := stream["network"].(string)
  481. params := make(map[string]string)
  482. params["type"] = streamNetwork
  483. switch streamNetwork {
  484. case "tcp":
  485. tcp, _ := stream["tcpSettings"].(map[string]interface{})
  486. header, _ := tcp["header"].(map[string]interface{})
  487. typeStr, _ := header["type"].(string)
  488. if typeStr == "http" {
  489. request := header["request"].(map[string]interface{})
  490. requestPath, _ := request["path"].([]interface{})
  491. params["path"] = requestPath[0].(string)
  492. headers, _ := request["headers"].(map[string]interface{})
  493. params["host"] = searchHost(headers)
  494. params["headerType"] = "http"
  495. }
  496. case "kcp":
  497. kcp, _ := stream["kcpSettings"].(map[string]interface{})
  498. header, _ := kcp["header"].(map[string]interface{})
  499. params["headerType"] = header["type"].(string)
  500. params["seed"] = kcp["seed"].(string)
  501. case "ws":
  502. ws, _ := stream["wsSettings"].(map[string]interface{})
  503. params["path"] = ws["path"].(string)
  504. if host, ok := ws["host"].(string); ok && len(host) > 0 {
  505. params["host"] = host
  506. } else {
  507. headers, _ := ws["headers"].(map[string]interface{})
  508. params["host"] = searchHost(headers)
  509. }
  510. case "grpc":
  511. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  512. params["serviceName"] = grpc["serviceName"].(string)
  513. params["authority"], _ = grpc["authority"].(string)
  514. if grpc["multiMode"].(bool) {
  515. params["mode"] = "multi"
  516. }
  517. case "httpupgrade":
  518. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]interface{})
  519. params["path"] = httpupgrade["path"].(string)
  520. if host, ok := httpupgrade["host"].(string); ok && len(host) > 0 {
  521. params["host"] = host
  522. } else {
  523. headers, _ := httpupgrade["headers"].(map[string]interface{})
  524. params["host"] = searchHost(headers)
  525. }
  526. case "xhttp":
  527. xhttp, _ := stream["xhttpSettings"].(map[string]interface{})
  528. params["path"] = xhttp["path"].(string)
  529. if host, ok := xhttp["host"].(string); ok && len(host) > 0 {
  530. params["host"] = host
  531. } else {
  532. headers, _ := xhttp["headers"].(map[string]interface{})
  533. params["host"] = searchHost(headers)
  534. }
  535. params["mode"] = xhttp["mode"].(string)
  536. }
  537. security, _ := stream["security"].(string)
  538. if security == "tls" {
  539. params["security"] = "tls"
  540. tlsSetting, _ := stream["tlsSettings"].(map[string]interface{})
  541. alpns, _ := tlsSetting["alpn"].([]interface{})
  542. var alpn []string
  543. for _, a := range alpns {
  544. alpn = append(alpn, a.(string))
  545. }
  546. if len(alpn) > 0 {
  547. params["alpn"] = strings.Join(alpn, ",")
  548. }
  549. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  550. params["sni"], _ = sniValue.(string)
  551. }
  552. tlsSettings, _ := searchKey(tlsSetting, "settings")
  553. if tlsSetting != nil {
  554. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  555. params["fp"], _ = fpValue.(string)
  556. }
  557. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  558. if insecure.(bool) {
  559. params["allowInsecure"] = "1"
  560. }
  561. }
  562. }
  563. }
  564. if security == "reality" {
  565. params["security"] = "reality"
  566. realitySetting, _ := stream["realitySettings"].(map[string]interface{})
  567. realitySettings, _ := searchKey(realitySetting, "settings")
  568. if realitySetting != nil {
  569. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  570. sNames, _ := sniValue.([]interface{})
  571. params["sni"] = sNames[random.Num(len(sNames))].(string)
  572. }
  573. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  574. params["pbk"], _ = pbkValue.(string)
  575. }
  576. if sidValue, ok := searchKey(realitySetting, "shortIds"); ok {
  577. shortIds, _ := sidValue.([]interface{})
  578. params["sid"] = shortIds[random.Num(len(shortIds))].(string)
  579. }
  580. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  581. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  582. params["fp"] = fp
  583. }
  584. }
  585. params["spx"] = "/" + random.Seq(15)
  586. }
  587. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  588. params["flow"] = clients[clientIndex].Flow
  589. }
  590. }
  591. if security != "tls" && security != "reality" {
  592. params["security"] = "none"
  593. }
  594. externalProxies, _ := stream["externalProxy"].([]interface{})
  595. if len(externalProxies) > 0 {
  596. links := ""
  597. for index, externalProxy := range externalProxies {
  598. ep, _ := externalProxy.(map[string]interface{})
  599. newSecurity, _ := ep["forceTls"].(string)
  600. dest, _ := ep["dest"].(string)
  601. port := int(ep["port"].(float64))
  602. link := fmt.Sprintf("trojan://%s@%s:%d", password, dest, port)
  603. if newSecurity != "same" {
  604. params["security"] = newSecurity
  605. } else {
  606. params["security"] = security
  607. }
  608. url, _ := url.Parse(link)
  609. q := url.Query()
  610. for k, v := range params {
  611. if !(newSecurity == "none" && (k == "alpn" || k == "sni" || k == "fp" || k == "allowInsecure")) {
  612. q.Add(k, v)
  613. }
  614. }
  615. // Set the new query values on the URL
  616. url.RawQuery = q.Encode()
  617. url.Fragment = s.genRemark(inbound, email, ep["remark"].(string))
  618. if index > 0 {
  619. links += "\n"
  620. }
  621. links += url.String()
  622. }
  623. return links
  624. }
  625. link := fmt.Sprintf("trojan://%s@%s:%d", password, address, port)
  626. url, _ := url.Parse(link)
  627. q := url.Query()
  628. for k, v := range params {
  629. q.Add(k, v)
  630. }
  631. // Set the new query values on the URL
  632. url.RawQuery = q.Encode()
  633. url.Fragment = s.genRemark(inbound, email, "")
  634. return url.String()
  635. }
  636. func (s *SubService) genShadowsocksLink(inbound *model.Inbound, email string) string {
  637. address := s.address
  638. if inbound.Protocol != model.Shadowsocks {
  639. return ""
  640. }
  641. var stream map[string]interface{}
  642. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  643. clients, _ := s.inboundService.GetClients(inbound)
  644. var settings map[string]interface{}
  645. json.Unmarshal([]byte(inbound.Settings), &settings)
  646. inboundPassword := settings["password"].(string)
  647. method := settings["method"].(string)
  648. clientIndex := -1
  649. for i, client := range clients {
  650. if client.Email == email {
  651. clientIndex = i
  652. break
  653. }
  654. }
  655. streamNetwork := stream["network"].(string)
  656. params := make(map[string]string)
  657. params["type"] = streamNetwork
  658. switch streamNetwork {
  659. case "tcp":
  660. tcp, _ := stream["tcpSettings"].(map[string]interface{})
  661. header, _ := tcp["header"].(map[string]interface{})
  662. typeStr, _ := header["type"].(string)
  663. if typeStr == "http" {
  664. request := header["request"].(map[string]interface{})
  665. requestPath, _ := request["path"].([]interface{})
  666. params["path"] = requestPath[0].(string)
  667. headers, _ := request["headers"].(map[string]interface{})
  668. params["host"] = searchHost(headers)
  669. params["headerType"] = "http"
  670. }
  671. case "kcp":
  672. kcp, _ := stream["kcpSettings"].(map[string]interface{})
  673. header, _ := kcp["header"].(map[string]interface{})
  674. params["headerType"] = header["type"].(string)
  675. params["seed"] = kcp["seed"].(string)
  676. case "ws":
  677. ws, _ := stream["wsSettings"].(map[string]interface{})
  678. params["path"] = ws["path"].(string)
  679. if host, ok := ws["host"].(string); ok && len(host) > 0 {
  680. params["host"] = host
  681. } else {
  682. headers, _ := ws["headers"].(map[string]interface{})
  683. params["host"] = searchHost(headers)
  684. }
  685. case "grpc":
  686. grpc, _ := stream["grpcSettings"].(map[string]interface{})
  687. params["serviceName"] = grpc["serviceName"].(string)
  688. params["authority"], _ = grpc["authority"].(string)
  689. if grpc["multiMode"].(bool) {
  690. params["mode"] = "multi"
  691. }
  692. case "httpupgrade":
  693. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]interface{})
  694. params["path"] = httpupgrade["path"].(string)
  695. if host, ok := httpupgrade["host"].(string); ok && len(host) > 0 {
  696. params["host"] = host
  697. } else {
  698. headers, _ := httpupgrade["headers"].(map[string]interface{})
  699. params["host"] = searchHost(headers)
  700. }
  701. case "xhttp":
  702. xhttp, _ := stream["xhttpSettings"].(map[string]interface{})
  703. params["path"] = xhttp["path"].(string)
  704. if host, ok := xhttp["host"].(string); ok && len(host) > 0 {
  705. params["host"] = host
  706. } else {
  707. headers, _ := xhttp["headers"].(map[string]interface{})
  708. params["host"] = searchHost(headers)
  709. }
  710. params["mode"] = xhttp["mode"].(string)
  711. }
  712. security, _ := stream["security"].(string)
  713. if security == "tls" {
  714. params["security"] = "tls"
  715. tlsSetting, _ := stream["tlsSettings"].(map[string]interface{})
  716. alpns, _ := tlsSetting["alpn"].([]interface{})
  717. var alpn []string
  718. for _, a := range alpns {
  719. alpn = append(alpn, a.(string))
  720. }
  721. if len(alpn) > 0 {
  722. params["alpn"] = strings.Join(alpn, ",")
  723. }
  724. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  725. params["sni"], _ = sniValue.(string)
  726. }
  727. tlsSettings, _ := searchKey(tlsSetting, "settings")
  728. if tlsSetting != nil {
  729. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  730. params["fp"], _ = fpValue.(string)
  731. }
  732. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  733. if insecure.(bool) {
  734. params["allowInsecure"] = "1"
  735. }
  736. }
  737. }
  738. }
  739. encPart := fmt.Sprintf("%s:%s", method, clients[clientIndex].Password)
  740. if method[0] == '2' {
  741. encPart = fmt.Sprintf("%s:%s:%s", method, inboundPassword, clients[clientIndex].Password)
  742. }
  743. externalProxies, _ := stream["externalProxy"].([]interface{})
  744. if len(externalProxies) > 0 {
  745. links := ""
  746. for index, externalProxy := range externalProxies {
  747. ep, _ := externalProxy.(map[string]interface{})
  748. newSecurity, _ := ep["forceTls"].(string)
  749. dest, _ := ep["dest"].(string)
  750. port := int(ep["port"].(float64))
  751. link := fmt.Sprintf("ss://%s@%s:%d", base64.StdEncoding.EncodeToString([]byte(encPart)), dest, port)
  752. if newSecurity != "same" {
  753. params["security"] = newSecurity
  754. } else {
  755. params["security"] = security
  756. }
  757. url, _ := url.Parse(link)
  758. q := url.Query()
  759. for k, v := range params {
  760. if !(newSecurity == "none" && (k == "alpn" || k == "sni" || k == "fp" || k == "allowInsecure")) {
  761. q.Add(k, v)
  762. }
  763. }
  764. // Set the new query values on the URL
  765. url.RawQuery = q.Encode()
  766. url.Fragment = s.genRemark(inbound, email, ep["remark"].(string))
  767. if index > 0 {
  768. links += "\n"
  769. }
  770. links += url.String()
  771. }
  772. return links
  773. }
  774. link := fmt.Sprintf("ss://%s@%s:%d", base64.StdEncoding.EncodeToString([]byte(encPart)), address, inbound.Port)
  775. url, _ := url.Parse(link)
  776. q := url.Query()
  777. for k, v := range params {
  778. q.Add(k, v)
  779. }
  780. // Set the new query values on the URL
  781. url.RawQuery = q.Encode()
  782. url.Fragment = s.genRemark(inbound, email, "")
  783. return url.String()
  784. }
  785. func (s *SubService) genRemark(inbound *model.Inbound, email string, extra string) string {
  786. separationChar := string(s.remarkModel[0])
  787. orderChars := s.remarkModel[1:]
  788. orders := map[byte]string{
  789. 'i': "",
  790. 'e': "",
  791. 'o': "",
  792. }
  793. if len(email) > 0 {
  794. orders['e'] = email
  795. }
  796. if len(inbound.Remark) > 0 {
  797. orders['i'] = inbound.Remark
  798. }
  799. if len(extra) > 0 {
  800. orders['o'] = extra
  801. }
  802. var remark []string
  803. for i := 0; i < len(orderChars); i++ {
  804. char := orderChars[i]
  805. order, exists := orders[char]
  806. if exists && order != "" {
  807. remark = append(remark, order)
  808. }
  809. }
  810. if s.showInfo {
  811. statsExist := false
  812. var stats xray.ClientTraffic
  813. for _, clientStat := range inbound.ClientStats {
  814. if clientStat.Email == email {
  815. stats = clientStat
  816. statsExist = true
  817. break
  818. }
  819. }
  820. // Get remained days
  821. if statsExist {
  822. if !stats.Enable {
  823. return fmt.Sprintf("⛔️N/A%s%s", separationChar, strings.Join(remark, separationChar))
  824. }
  825. if vol := stats.Total - (stats.Up + stats.Down); vol > 0 {
  826. remark = append(remark, fmt.Sprintf("%s%s", common.FormatTraffic(vol), "📊"))
  827. }
  828. now := time.Now().Unix()
  829. switch exp := stats.ExpiryTime / 1000; {
  830. case exp > 0:
  831. remainingSeconds := exp - now
  832. days := remainingSeconds / 86400
  833. hours := (remainingSeconds % 86400) / 3600
  834. minutes := (remainingSeconds % 3600) / 60
  835. if days > 0 {
  836. if hours > 0 {
  837. remark = append(remark, fmt.Sprintf("%dD,%dH⏳", days, hours))
  838. } else {
  839. remark = append(remark, fmt.Sprintf("%dD⏳", days))
  840. }
  841. } else if hours > 0 {
  842. remark = append(remark, fmt.Sprintf("%dH⏳", hours))
  843. } else {
  844. remark = append(remark, fmt.Sprintf("%dM⏳", minutes))
  845. }
  846. case exp < 0:
  847. days := exp / -86400
  848. hours := (exp % -86400) / 3600
  849. minutes := (exp % -3600) / 60
  850. if days > 0 {
  851. if hours > 0 {
  852. remark = append(remark, fmt.Sprintf("%dD,%dH⏳", days, hours))
  853. } else {
  854. remark = append(remark, fmt.Sprintf("%dD⏳", days))
  855. }
  856. } else if hours > 0 {
  857. remark = append(remark, fmt.Sprintf("%dH⏳", hours))
  858. } else {
  859. remark = append(remark, fmt.Sprintf("%dM⏳", minutes))
  860. }
  861. }
  862. }
  863. }
  864. return strings.Join(remark, separationChar)
  865. }
  866. func searchKey(data interface{}, key string) (interface{}, bool) {
  867. switch val := data.(type) {
  868. case map[string]interface{}:
  869. for k, v := range val {
  870. if k == key {
  871. return v, true
  872. }
  873. if result, ok := searchKey(v, key); ok {
  874. return result, true
  875. }
  876. }
  877. case []interface{}:
  878. for _, v := range val {
  879. if result, ok := searchKey(v, key); ok {
  880. return result, true
  881. }
  882. }
  883. }
  884. return nil, false
  885. }
  886. func searchHost(headers interface{}) string {
  887. data, _ := headers.(map[string]interface{})
  888. for k, v := range data {
  889. if strings.EqualFold(k, "host") {
  890. switch v.(type) {
  891. case []interface{}:
  892. hosts, _ := v.([]interface{})
  893. if len(hosts) > 0 {
  894. return hosts[0].(string)
  895. } else {
  896. return ""
  897. }
  898. case interface{}:
  899. return v.(string)
  900. }
  901. }
  902. }
  903. return ""
  904. }