1
0

subService.go 29 KB

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