1
0

subService.go 30 KB

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