subService.go 29 KB

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