1
0

subService.go 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605
  1. package sub
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "maps"
  6. "net"
  7. "net/url"
  8. "slices"
  9. "strings"
  10. "time"
  11. "github.com/gin-gonic/gin"
  12. "github.com/goccy/go-json"
  13. "github.com/mhsanaei/3x-ui/v3/database"
  14. "github.com/mhsanaei/3x-ui/v3/database/model"
  15. "github.com/mhsanaei/3x-ui/v3/logger"
  16. "github.com/mhsanaei/3x-ui/v3/util/common"
  17. "github.com/mhsanaei/3x-ui/v3/util/random"
  18. "github.com/mhsanaei/3x-ui/v3/web/service"
  19. "github.com/mhsanaei/3x-ui/v3/xray"
  20. )
  21. // SubService provides business logic for generating subscription links and managing subscription data.
  22. type SubService struct {
  23. address string
  24. showInfo bool
  25. remarkModel string
  26. datepicker string
  27. inboundService service.InboundService
  28. settingService service.SettingService
  29. // nodesByID is populated per request from the Node table so
  30. // resolveInboundAddress can return the node's address for any
  31. // inbound whose NodeID is set. Keeps the per-link host derivation
  32. // O(1) instead of O(N) DB hits.
  33. nodesByID map[int]*model.Node
  34. }
  35. // NewSubService creates a new subscription service with the given configuration.
  36. func NewSubService(showInfo bool, remarkModel string) *SubService {
  37. return &SubService{
  38. showInfo: showInfo,
  39. remarkModel: remarkModel,
  40. }
  41. }
  42. // PrepareForRequest sets per-request state (host + nodes map) on the
  43. // shared SubService. Called by every entry point — GetSubs, GetJson,
  44. // GetClash — so resolveInboundAddress sees the right host and the
  45. // freshly-loaded node map regardless of which sub flavour the client
  46. // hit.
  47. func (s *SubService) PrepareForRequest(host string) {
  48. s.address = host
  49. s.loadNodes()
  50. }
  51. // GetSubs retrieves subscription links for a given subscription ID and host.
  52. func (s *SubService) GetSubs(subId string, host string) ([]string, int64, xray.ClientTraffic, error) {
  53. s.PrepareForRequest(host)
  54. var result []string
  55. var traffic xray.ClientTraffic
  56. var lastOnline int64
  57. var hasEnabledClient bool
  58. var clientTraffics []xray.ClientTraffic
  59. inbounds, err := s.getInboundsBySubId(subId)
  60. if err != nil {
  61. return nil, 0, traffic, err
  62. }
  63. if len(inbounds) == 0 {
  64. return nil, 0, traffic, common.NewError("No inbounds found with ", subId)
  65. }
  66. s.datepicker, err = s.settingService.GetDatepicker()
  67. if err != nil {
  68. s.datepicker = "gregorian"
  69. }
  70. seenEmails := make(map[string]struct{})
  71. for _, inbound := range inbounds {
  72. clients, err := s.inboundService.GetClients(inbound)
  73. if err != nil {
  74. logger.Error("SubService - GetClients: Unable to get clients from inbound")
  75. }
  76. if clients == nil {
  77. continue
  78. }
  79. if len(inbound.Listen) > 0 && inbound.Listen[0] == '@' {
  80. listen, port, streamSettings, err := s.getFallbackMaster(inbound.Listen, inbound.StreamSettings)
  81. if err == nil {
  82. inbound.Listen = listen
  83. inbound.Port = port
  84. inbound.StreamSettings = streamSettings
  85. }
  86. }
  87. for _, client := range clients {
  88. if client.SubID == subId {
  89. if client.Enable {
  90. hasEnabledClient = true
  91. }
  92. result = append(result, s.GetLink(inbound, client.Email))
  93. var ct xray.ClientTraffic
  94. ct, clientTraffics = s.appendUniqueTraffic(seenEmails, clientTraffics, inbound.ClientStats, client.Email)
  95. if ct.LastOnline > lastOnline {
  96. lastOnline = ct.LastOnline
  97. }
  98. }
  99. }
  100. }
  101. // Prepare statistics
  102. for index, clientTraffic := range clientTraffics {
  103. if index == 0 {
  104. traffic.Up = clientTraffic.Up
  105. traffic.Down = clientTraffic.Down
  106. traffic.Total = clientTraffic.Total
  107. if clientTraffic.ExpiryTime > 0 {
  108. traffic.ExpiryTime = clientTraffic.ExpiryTime
  109. }
  110. } else {
  111. traffic.Up += clientTraffic.Up
  112. traffic.Down += clientTraffic.Down
  113. if traffic.Total == 0 || clientTraffic.Total == 0 {
  114. traffic.Total = 0
  115. } else {
  116. traffic.Total += clientTraffic.Total
  117. }
  118. if clientTraffic.ExpiryTime != traffic.ExpiryTime {
  119. traffic.ExpiryTime = 0
  120. }
  121. }
  122. }
  123. traffic.Enable = hasEnabledClient
  124. return result, lastOnline, traffic, nil
  125. }
  126. func (s *SubService) getInboundsBySubId(subId string) ([]*model.Inbound, error) {
  127. db := database.GetDB()
  128. var inbounds []*model.Inbound
  129. // allow "hysteria2" so imports stored with the literal v2 protocol
  130. // string still surface here (#4081)
  131. err := db.Model(model.Inbound{}).Preload("ClientStats").Where(`id in (
  132. SELECT DISTINCT inbounds.id
  133. FROM inbounds,
  134. JSON_EACH(JSON_EXTRACT(inbounds.settings, '$.clients')) AS client
  135. WHERE
  136. protocol in ('vmess','vless','trojan','shadowsocks','hysteria','hysteria2')
  137. AND JSON_EXTRACT(client.value, '$.subId') = ? AND enable = ?
  138. )`, subId, true).Find(&inbounds).Error
  139. if err != nil {
  140. return nil, err
  141. }
  142. return inbounds, nil
  143. }
  144. // appendUniqueTraffic resolves the traffic stats for email and appends them
  145. // to acc only the first time email is seen. Shared-email mode lets one
  146. // client_traffics row underpin several inbounds, so without dedupe its
  147. // quota and usage would be counted once per inbound.
  148. func (s *SubService) appendUniqueTraffic(seen map[string]struct{}, acc []xray.ClientTraffic, stats []xray.ClientTraffic, email string) (xray.ClientTraffic, []xray.ClientTraffic) {
  149. ct := s.getClientTraffics(stats, email)
  150. if _, dup := seen[email]; !dup {
  151. seen[email] = struct{}{}
  152. acc = append(acc, ct)
  153. }
  154. return ct, acc
  155. }
  156. func (s *SubService) getClientTraffics(traffics []xray.ClientTraffic, email string) xray.ClientTraffic {
  157. for _, traffic := range traffics {
  158. if traffic.Email == email {
  159. return traffic
  160. }
  161. }
  162. return xray.ClientTraffic{}
  163. }
  164. func (s *SubService) getFallbackMaster(dest string, streamSettings string) (string, int, string, error) {
  165. db := database.GetDB()
  166. var inbound *model.Inbound
  167. err := db.Model(model.Inbound{}).
  168. Where("JSON_TYPE(settings, '$.fallbacks') = 'array'").
  169. Where("EXISTS (SELECT * FROM json_each(settings, '$.fallbacks') WHERE json_extract(value, '$.dest') = ?)", dest).
  170. Find(&inbound).Error
  171. if err != nil {
  172. return "", 0, "", err
  173. }
  174. var stream map[string]any
  175. json.Unmarshal([]byte(streamSettings), &stream)
  176. var masterStream map[string]any
  177. json.Unmarshal([]byte(inbound.StreamSettings), &masterStream)
  178. stream["security"] = masterStream["security"]
  179. stream["tlsSettings"] = masterStream["tlsSettings"]
  180. stream["externalProxy"] = masterStream["externalProxy"]
  181. modifiedStream, _ := json.MarshalIndent(stream, "", " ")
  182. return inbound.Listen, inbound.Port, string(modifiedStream), nil
  183. }
  184. // GetLink dispatches to the protocol-specific generator for one (inbound, client)
  185. // pair. Returns "" when the inbound's protocol doesn't produce a subscription URL
  186. // (socks, http, mixed, wireguard, dokodemo, tunnel). The returned string may
  187. // contain multiple `\n`-separated URLs when the inbound has externalProxy set.
  188. func (s *SubService) GetLink(inbound *model.Inbound, email string) string {
  189. switch inbound.Protocol {
  190. case "vmess":
  191. return s.genVmessLink(inbound, email)
  192. case "vless":
  193. return s.genVlessLink(inbound, email)
  194. case "trojan":
  195. return s.genTrojanLink(inbound, email)
  196. case "shadowsocks":
  197. return s.genShadowsocksLink(inbound, email)
  198. case "hysteria", "hysteria2":
  199. return s.genHysteriaLink(inbound, email)
  200. }
  201. return ""
  202. }
  203. // Protocol link generators are intentionally ordered as:
  204. // vmess -> vless -> trojan -> shadowsocks -> hysteria.
  205. func (s *SubService) genVmessLink(inbound *model.Inbound, email string) string {
  206. if inbound.Protocol != model.VMESS {
  207. return ""
  208. }
  209. address := s.resolveInboundAddress(inbound)
  210. obj := map[string]any{
  211. "v": "2",
  212. "add": address,
  213. "port": inbound.Port,
  214. "type": "none",
  215. }
  216. stream := unmarshalStreamSettings(inbound.StreamSettings)
  217. network, _ := stream["network"].(string)
  218. applyVmessNetworkParams(stream, network, obj)
  219. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  220. applyFinalMaskObj(finalmask, obj)
  221. }
  222. security, _ := stream["security"].(string)
  223. obj["tls"] = security
  224. if security == "tls" {
  225. applyVmessTLSParams(stream, obj)
  226. }
  227. clients, _ := s.inboundService.GetClients(inbound)
  228. clientIndex := findClientIndex(clients, email)
  229. obj["id"] = clients[clientIndex].ID
  230. obj["scy"] = clients[clientIndex].Security
  231. externalProxies, _ := stream["externalProxy"].([]any)
  232. if len(externalProxies) > 0 {
  233. return s.buildVmessExternalProxyLinks(externalProxies, obj, inbound, email)
  234. }
  235. obj["ps"] = s.genRemark(inbound, email, "")
  236. return buildVmessLink(obj)
  237. }
  238. func (s *SubService) genVlessLink(inbound *model.Inbound, email string) string {
  239. if inbound.Protocol != model.VLESS {
  240. return ""
  241. }
  242. address := s.resolveInboundAddress(inbound)
  243. stream := unmarshalStreamSettings(inbound.StreamSettings)
  244. clients, _ := s.inboundService.GetClients(inbound)
  245. clientIndex := findClientIndex(clients, email)
  246. uuid := clients[clientIndex].ID
  247. port := inbound.Port
  248. streamNetwork := stream["network"].(string)
  249. params := make(map[string]string)
  250. params["type"] = streamNetwork
  251. // Add encryption parameter for VLESS from inbound settings
  252. var settings map[string]any
  253. json.Unmarshal([]byte(inbound.Settings), &settings)
  254. if encryption, ok := settings["encryption"].(string); ok {
  255. params["encryption"] = encryption
  256. }
  257. applyShareNetworkParams(stream, streamNetwork, params)
  258. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  259. applyFinalMaskParams(finalmask, params)
  260. }
  261. security, _ := stream["security"].(string)
  262. switch security {
  263. case "tls":
  264. applyShareTLSParams(stream, params)
  265. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  266. params["flow"] = clients[clientIndex].Flow
  267. }
  268. case "reality":
  269. applyShareRealityParams(stream, params)
  270. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  271. params["flow"] = clients[clientIndex].Flow
  272. }
  273. default:
  274. params["security"] = "none"
  275. }
  276. externalProxies, _ := stream["externalProxy"].([]any)
  277. if len(externalProxies) > 0 {
  278. return s.buildExternalProxyURLLinks(
  279. externalProxies,
  280. params,
  281. security,
  282. func(dest string, port int) string {
  283. return fmt.Sprintf("vless://%s@%s:%d", uuid, dest, port)
  284. },
  285. func(ep map[string]any) string {
  286. return s.genRemark(inbound, email, ep["remark"].(string))
  287. },
  288. )
  289. }
  290. link := fmt.Sprintf("vless://%s@%s:%d", uuid, address, port)
  291. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  292. }
  293. func (s *SubService) genTrojanLink(inbound *model.Inbound, email string) string {
  294. if inbound.Protocol != model.Trojan {
  295. return ""
  296. }
  297. address := s.resolveInboundAddress(inbound)
  298. stream := unmarshalStreamSettings(inbound.StreamSettings)
  299. clients, _ := s.inboundService.GetClients(inbound)
  300. clientIndex := findClientIndex(clients, email)
  301. password := clients[clientIndex].Password
  302. port := inbound.Port
  303. streamNetwork := stream["network"].(string)
  304. params := make(map[string]string)
  305. params["type"] = streamNetwork
  306. applyShareNetworkParams(stream, streamNetwork, params)
  307. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  308. applyFinalMaskParams(finalmask, params)
  309. }
  310. security, _ := stream["security"].(string)
  311. switch security {
  312. case "tls":
  313. applyShareTLSParams(stream, params)
  314. case "reality":
  315. applyShareRealityParams(stream, params)
  316. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  317. params["flow"] = clients[clientIndex].Flow
  318. }
  319. default:
  320. params["security"] = "none"
  321. }
  322. externalProxies, _ := stream["externalProxy"].([]any)
  323. if len(externalProxies) > 0 {
  324. return s.buildExternalProxyURLLinks(
  325. externalProxies,
  326. params,
  327. security,
  328. func(dest string, port int) string {
  329. return fmt.Sprintf("trojan://%s@%s:%d", password, dest, port)
  330. },
  331. func(ep map[string]any) string {
  332. return s.genRemark(inbound, email, ep["remark"].(string))
  333. },
  334. )
  335. }
  336. link := fmt.Sprintf("trojan://%s@%s:%d", password, address, port)
  337. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  338. }
  339. func (s *SubService) genShadowsocksLink(inbound *model.Inbound, email string) string {
  340. if inbound.Protocol != model.Shadowsocks {
  341. return ""
  342. }
  343. address := s.resolveInboundAddress(inbound)
  344. stream := unmarshalStreamSettings(inbound.StreamSettings)
  345. clients, _ := s.inboundService.GetClients(inbound)
  346. var settings map[string]any
  347. json.Unmarshal([]byte(inbound.Settings), &settings)
  348. inboundPassword := settings["password"].(string)
  349. method := settings["method"].(string)
  350. clientIndex := findClientIndex(clients, email)
  351. streamNetwork := stream["network"].(string)
  352. params := make(map[string]string)
  353. params["type"] = streamNetwork
  354. applyShareNetworkParams(stream, streamNetwork, params)
  355. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  356. applyFinalMaskParams(finalmask, params)
  357. }
  358. security, _ := stream["security"].(string)
  359. if security == "tls" {
  360. applyShareTLSParams(stream, params)
  361. }
  362. encPart := fmt.Sprintf("%s:%s", method, clients[clientIndex].Password)
  363. if method[0] == '2' {
  364. encPart = fmt.Sprintf("%s:%s:%s", method, inboundPassword, clients[clientIndex].Password)
  365. }
  366. externalProxies, _ := stream["externalProxy"].([]any)
  367. if len(externalProxies) > 0 {
  368. proxyParams := cloneStringMap(params)
  369. proxyParams["security"] = security
  370. return s.buildExternalProxyURLLinks(
  371. externalProxies,
  372. proxyParams,
  373. security,
  374. func(dest string, port int) string {
  375. return fmt.Sprintf("ss://%s@%s:%d", base64.StdEncoding.EncodeToString([]byte(encPart)), dest, port)
  376. },
  377. func(ep map[string]any) string {
  378. return s.genRemark(inbound, email, ep["remark"].(string))
  379. },
  380. )
  381. }
  382. link := fmt.Sprintf("ss://%s@%s:%d", base64.StdEncoding.EncodeToString([]byte(encPart)), address, inbound.Port)
  383. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  384. }
  385. func (s *SubService) genHysteriaLink(inbound *model.Inbound, email string) string {
  386. if !model.IsHysteria(inbound.Protocol) {
  387. return ""
  388. }
  389. var stream map[string]any
  390. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  391. clients, _ := s.inboundService.GetClients(inbound)
  392. clientIndex := -1
  393. for i, client := range clients {
  394. if client.Email == email {
  395. clientIndex = i
  396. break
  397. }
  398. }
  399. auth := clients[clientIndex].Auth
  400. params := make(map[string]string)
  401. params["security"] = "tls"
  402. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  403. alpns, _ := tlsSetting["alpn"].([]any)
  404. var alpn []string
  405. for _, a := range alpns {
  406. alpn = append(alpn, a.(string))
  407. }
  408. if len(alpn) > 0 {
  409. params["alpn"] = strings.Join(alpn, ",")
  410. }
  411. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  412. params["sni"], _ = sniValue.(string)
  413. }
  414. tlsSettings, _ := searchKey(tlsSetting, "settings")
  415. if tlsSetting != nil {
  416. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  417. params["fp"], _ = fpValue.(string)
  418. }
  419. if insecure, ok := searchKey(tlsSettings, "allowInsecure"); ok {
  420. if insecure.(bool) {
  421. params["insecure"] = "1"
  422. }
  423. }
  424. }
  425. // salamander obfs (Hysteria2). The panel-side link generator already
  426. // emits these; keep the subscription output in sync so a client has
  427. // the obfs password to match the server.
  428. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  429. applyFinalMaskParams(finalmask, params)
  430. if udpMasks, ok := finalmask["udp"].([]any); ok {
  431. for _, m := range udpMasks {
  432. mask, _ := m.(map[string]any)
  433. if mask == nil || mask["type"] != "salamander" {
  434. continue
  435. }
  436. settings, _ := mask["settings"].(map[string]any)
  437. if pw, ok := settings["password"].(string); ok && pw != "" {
  438. params["obfs"] = "salamander"
  439. params["obfs-password"] = pw
  440. break
  441. }
  442. }
  443. }
  444. }
  445. var settings map[string]any
  446. json.Unmarshal([]byte(inbound.Settings), &settings)
  447. version, _ := settings["version"].(float64)
  448. protocol := "hysteria2"
  449. if int(version) == 1 {
  450. protocol = "hysteria"
  451. }
  452. // Fan out one link per External Proxy entry if any. Previously this
  453. // generator ignored `externalProxy` entirely, so the link kept the
  454. // server's own IP/port even when the admin configured an alternate
  455. // endpoint (e.g. a CDN hostname + port that forwards to the node).
  456. // Matches the behaviour of genVlessLink / genTrojanLink / ….
  457. externalProxies, _ := stream["externalProxy"].([]any)
  458. if len(externalProxies) > 0 {
  459. links := make([]string, 0, len(externalProxies))
  460. for _, externalProxy := range externalProxies {
  461. ep, ok := externalProxy.(map[string]any)
  462. if !ok {
  463. continue
  464. }
  465. dest, _ := ep["dest"].(string)
  466. portF, okPort := ep["port"].(float64)
  467. if dest == "" || !okPort {
  468. continue
  469. }
  470. epRemark, _ := ep["remark"].(string)
  471. link := fmt.Sprintf("%s://%s@%s:%d", protocol, auth, dest, int(portF))
  472. u, _ := url.Parse(link)
  473. q := u.Query()
  474. for k, v := range params {
  475. q.Add(k, v)
  476. }
  477. u.RawQuery = q.Encode()
  478. u.Fragment = s.genRemark(inbound, email, epRemark)
  479. links = append(links, u.String())
  480. }
  481. return strings.Join(links, "\n")
  482. }
  483. // No external proxy configured — fall back to the request host.
  484. link := fmt.Sprintf("%s://%s@%s:%d", protocol, auth, s.address, inbound.Port)
  485. url, _ := url.Parse(link)
  486. q := url.Query()
  487. for k, v := range params {
  488. q.Add(k, v)
  489. }
  490. url.RawQuery = q.Encode()
  491. url.Fragment = s.genRemark(inbound, email, "")
  492. return url.String()
  493. }
  494. // loadNodes refreshes nodesByID from the DB. Called once per request so
  495. // the per-inbound resolveInboundAddress lookups are pure map reads.
  496. // We filter to address != ” so a half-configured node row doesn't
  497. // accidentally produce a useless host like "https://:2053".
  498. func (s *SubService) loadNodes() {
  499. db := database.GetDB()
  500. var nodes []*model.Node
  501. if err := db.Model(&model.Node{}).Where("address != ''").Find(&nodes).Error; err != nil {
  502. logger.Warning("subscription: load nodes failed:", err)
  503. s.nodesByID = nil
  504. return
  505. }
  506. m := make(map[int]*model.Node, len(nodes))
  507. for _, n := range nodes {
  508. m[n.Id] = n
  509. }
  510. s.nodesByID = m
  511. }
  512. // resolveInboundAddress picks the host an external client should
  513. // connect to. Order:
  514. // 1. If the inbound is node-managed and the node has an address, use
  515. // the node's address — central panel's hostname doesn't speak xray
  516. // for that inbound.
  517. // 2. If the inbound binds to a non-wildcard listen address, use it.
  518. // 3. Otherwise fall back to the request's host (whatever the client
  519. // subscribed against).
  520. func (s *SubService) resolveInboundAddress(inbound *model.Inbound) string {
  521. if inbound.NodeID != nil && s.nodesByID != nil {
  522. if n, ok := s.nodesByID[*inbound.NodeID]; ok && n.Address != "" {
  523. return n.Address
  524. }
  525. }
  526. if inbound.Listen == "" || inbound.Listen == "0.0.0.0" || inbound.Listen == "::" || inbound.Listen == "::0" {
  527. return s.address
  528. }
  529. return inbound.Listen
  530. }
  531. func findClientIndex(clients []model.Client, email string) int {
  532. for i, client := range clients {
  533. if client.Email == email {
  534. return i
  535. }
  536. }
  537. return -1
  538. }
  539. func unmarshalStreamSettings(streamSettings string) map[string]any {
  540. var stream map[string]any
  541. json.Unmarshal([]byte(streamSettings), &stream)
  542. return stream
  543. }
  544. func applyPathAndHostParams(settings map[string]any, params map[string]string) {
  545. params["path"] = settings["path"].(string)
  546. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  547. params["host"] = host
  548. } else {
  549. headers, _ := settings["headers"].(map[string]any)
  550. params["host"] = searchHost(headers)
  551. }
  552. }
  553. func applyPathAndHostObj(settings map[string]any, obj map[string]any) {
  554. obj["path"] = settings["path"].(string)
  555. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  556. obj["host"] = host
  557. } else {
  558. headers, _ := settings["headers"].(map[string]any)
  559. obj["host"] = searchHost(headers)
  560. }
  561. }
  562. func applyShareNetworkParams(stream map[string]any, streamNetwork string, params map[string]string) {
  563. switch streamNetwork {
  564. case "tcp":
  565. tcp, _ := stream["tcpSettings"].(map[string]any)
  566. header, _ := tcp["header"].(map[string]any)
  567. typeStr, _ := header["type"].(string)
  568. if typeStr == "http" {
  569. request := header["request"].(map[string]any)
  570. requestPath, _ := request["path"].([]any)
  571. params["path"] = requestPath[0].(string)
  572. headers, _ := request["headers"].(map[string]any)
  573. params["host"] = searchHost(headers)
  574. params["headerType"] = "http"
  575. }
  576. case "kcp":
  577. applyKcpShareParams(stream, params)
  578. case "ws":
  579. ws, _ := stream["wsSettings"].(map[string]any)
  580. applyPathAndHostParams(ws, params)
  581. case "grpc":
  582. grpc, _ := stream["grpcSettings"].(map[string]any)
  583. params["serviceName"] = grpc["serviceName"].(string)
  584. params["authority"], _ = grpc["authority"].(string)
  585. if grpc["multiMode"].(bool) {
  586. params["mode"] = "multi"
  587. }
  588. case "httpupgrade":
  589. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  590. applyPathAndHostParams(httpupgrade, params)
  591. case "xhttp":
  592. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  593. applyXhttpExtraParams(xhttp, params)
  594. }
  595. }
  596. // applyXhttpExtraObj copies the bidirectional xhttp settings into the
  597. // VMess base64 JSON link object. VMess supports arbitrary keys, so we
  598. // flatten the SplitHTTPConfig "extra" fields directly onto obj.
  599. func applyXhttpExtraObj(xhttp map[string]any, obj map[string]any) {
  600. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  601. obj["x_padding_bytes"] = xpb
  602. }
  603. maps.Copy(obj, buildXhttpExtra(xhttp))
  604. }
  605. func applyVmessNetworkParams(stream map[string]any, network string, obj map[string]any) {
  606. obj["net"] = network
  607. switch network {
  608. case "tcp":
  609. tcp, _ := stream["tcpSettings"].(map[string]any)
  610. header, _ := tcp["header"].(map[string]any)
  611. typeStr, _ := header["type"].(string)
  612. obj["type"] = typeStr
  613. if typeStr == "http" {
  614. request := header["request"].(map[string]any)
  615. requestPath, _ := request["path"].([]any)
  616. obj["path"] = requestPath[0].(string)
  617. headers, _ := request["headers"].(map[string]any)
  618. obj["host"] = searchHost(headers)
  619. }
  620. case "kcp":
  621. applyKcpShareObj(stream, obj)
  622. case "ws":
  623. ws, _ := stream["wsSettings"].(map[string]any)
  624. applyPathAndHostObj(ws, obj)
  625. case "grpc":
  626. grpc, _ := stream["grpcSettings"].(map[string]any)
  627. obj["path"] = grpc["serviceName"].(string)
  628. obj["authority"] = grpc["authority"].(string)
  629. if grpc["multiMode"].(bool) {
  630. obj["type"] = "multi"
  631. }
  632. case "httpupgrade":
  633. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  634. applyPathAndHostObj(httpupgrade, obj)
  635. case "xhttp":
  636. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  637. applyPathAndHostObj(xhttp, obj)
  638. if mode, ok := xhttp["mode"].(string); ok {
  639. obj["mode"] = mode
  640. }
  641. applyXhttpExtraObj(xhttp, obj)
  642. }
  643. }
  644. func applyShareTLSParams(stream map[string]any, params map[string]string) {
  645. params["security"] = "tls"
  646. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  647. alpns, _ := tlsSetting["alpn"].([]any)
  648. var alpn []string
  649. for _, a := range alpns {
  650. alpn = append(alpn, a.(string))
  651. }
  652. if len(alpn) > 0 {
  653. params["alpn"] = strings.Join(alpn, ",")
  654. }
  655. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  656. params["sni"], _ = sniValue.(string)
  657. }
  658. tlsSettings, _ := searchKey(tlsSetting, "settings")
  659. if tlsSetting != nil {
  660. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  661. params["fp"], _ = fpValue.(string)
  662. }
  663. }
  664. }
  665. func applyVmessTLSParams(stream map[string]any, obj map[string]any) {
  666. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  667. alpns, _ := tlsSetting["alpn"].([]any)
  668. if len(alpns) > 0 {
  669. var alpn []string
  670. for _, a := range alpns {
  671. alpn = append(alpn, a.(string))
  672. }
  673. obj["alpn"] = strings.Join(alpn, ",")
  674. }
  675. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  676. obj["sni"], _ = sniValue.(string)
  677. }
  678. tlsSettings, _ := searchKey(tlsSetting, "settings")
  679. if tlsSetting != nil {
  680. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  681. obj["fp"], _ = fpValue.(string)
  682. }
  683. }
  684. }
  685. func applyShareRealityParams(stream map[string]any, params map[string]string) {
  686. params["security"] = "reality"
  687. realitySetting, _ := stream["realitySettings"].(map[string]any)
  688. realitySettings, _ := searchKey(realitySetting, "settings")
  689. if realitySetting != nil {
  690. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  691. sNames, _ := sniValue.([]any)
  692. params["sni"] = sNames[random.Num(len(sNames))].(string)
  693. }
  694. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  695. params["pbk"], _ = pbkValue.(string)
  696. }
  697. if sidValue, ok := searchKey(realitySetting, "shortIds"); ok {
  698. shortIds, _ := sidValue.([]any)
  699. params["sid"] = shortIds[random.Num(len(shortIds))].(string)
  700. }
  701. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  702. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  703. params["fp"] = fp
  704. }
  705. }
  706. if pqvValue, ok := searchKey(realitySettings, "mldsa65Verify"); ok {
  707. if pqv, ok := pqvValue.(string); ok && len(pqv) > 0 {
  708. params["pqv"] = pqv
  709. }
  710. }
  711. params["spx"] = "/" + random.Seq(15)
  712. }
  713. }
  714. func buildVmessLink(obj map[string]any) string {
  715. jsonStr, _ := json.MarshalIndent(obj, "", " ")
  716. return "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
  717. }
  718. func cloneVmessShareObj(baseObj map[string]any, newSecurity string) map[string]any {
  719. newObj := map[string]any{}
  720. for key, value := range baseObj {
  721. if !(newSecurity == "none" && (key == "alpn" || key == "sni" || key == "fp")) {
  722. newObj[key] = value
  723. }
  724. }
  725. return newObj
  726. }
  727. func (s *SubService) buildVmessExternalProxyLinks(externalProxies []any, baseObj map[string]any, inbound *model.Inbound, email string) string {
  728. var links strings.Builder
  729. for index, externalProxy := range externalProxies {
  730. ep, _ := externalProxy.(map[string]any)
  731. newSecurity, _ := ep["forceTls"].(string)
  732. newObj := cloneVmessShareObj(baseObj, newSecurity)
  733. newObj["ps"] = s.genRemark(inbound, email, ep["remark"].(string))
  734. newObj["add"] = ep["dest"].(string)
  735. newObj["port"] = int(ep["port"].(float64))
  736. if newSecurity != "same" {
  737. newObj["tls"] = newSecurity
  738. }
  739. if index > 0 {
  740. links.WriteString("\n")
  741. }
  742. links.WriteString(buildVmessLink(newObj))
  743. }
  744. return links.String()
  745. }
  746. func buildLinkWithParams(link string, params map[string]string, fragment string) string {
  747. parsedURL, _ := url.Parse(link)
  748. q := parsedURL.Query()
  749. for k, v := range params {
  750. q.Add(k, v)
  751. }
  752. parsedURL.RawQuery = q.Encode()
  753. parsedURL.Fragment = fragment
  754. return parsedURL.String()
  755. }
  756. func buildLinkWithParamsAndSecurity(link string, params map[string]string, fragment, security string, omitTLSFields bool) string {
  757. parsedURL, _ := url.Parse(link)
  758. q := parsedURL.Query()
  759. for k, v := range params {
  760. if k == "security" {
  761. v = security
  762. }
  763. if omitTLSFields && (k == "alpn" || k == "sni" || k == "fp") {
  764. continue
  765. }
  766. q.Add(k, v)
  767. }
  768. parsedURL.RawQuery = q.Encode()
  769. parsedURL.Fragment = fragment
  770. return parsedURL.String()
  771. }
  772. func (s *SubService) buildExternalProxyURLLinks(
  773. externalProxies []any,
  774. params map[string]string,
  775. baseSecurity string,
  776. makeLink func(dest string, port int) string,
  777. makeRemark func(ep map[string]any) string,
  778. ) string {
  779. links := make([]string, 0, len(externalProxies))
  780. for _, externalProxy := range externalProxies {
  781. ep, _ := externalProxy.(map[string]any)
  782. newSecurity, _ := ep["forceTls"].(string)
  783. dest, _ := ep["dest"].(string)
  784. port := int(ep["port"].(float64))
  785. securityToApply := baseSecurity
  786. if newSecurity != "same" {
  787. securityToApply = newSecurity
  788. }
  789. links = append(
  790. links,
  791. buildLinkWithParamsAndSecurity(
  792. makeLink(dest, port),
  793. params,
  794. makeRemark(ep),
  795. securityToApply,
  796. newSecurity == "none",
  797. ),
  798. )
  799. }
  800. return strings.Join(links, "\n")
  801. }
  802. func cloneStringMap(source map[string]string) map[string]string {
  803. cloned := make(map[string]string, len(source))
  804. maps.Copy(cloned, source)
  805. return cloned
  806. }
  807. func (s *SubService) genRemark(inbound *model.Inbound, email string, extra string) string {
  808. separationChar := string(s.remarkModel[0])
  809. orderChars := s.remarkModel[1:]
  810. orders := map[byte]string{
  811. 'i': "",
  812. 'e': "",
  813. 'o': "",
  814. }
  815. if len(email) > 0 {
  816. orders['e'] = email
  817. }
  818. if len(inbound.Remark) > 0 {
  819. orders['i'] = inbound.Remark
  820. }
  821. if len(extra) > 0 {
  822. orders['o'] = extra
  823. }
  824. var remark []string
  825. for i := 0; i < len(orderChars); i++ {
  826. char := orderChars[i]
  827. order, exists := orders[char]
  828. if exists && order != "" {
  829. remark = append(remark, order)
  830. }
  831. }
  832. if s.showInfo {
  833. statsExist := false
  834. var stats xray.ClientTraffic
  835. for _, clientStat := range inbound.ClientStats {
  836. if clientStat.Email == email {
  837. stats = clientStat
  838. statsExist = true
  839. break
  840. }
  841. }
  842. // Get remained days
  843. if statsExist {
  844. if !stats.Enable {
  845. return fmt.Sprintf("⛔️N/A%s%s", separationChar, strings.Join(remark, separationChar))
  846. }
  847. if vol := stats.Total - (stats.Up + stats.Down); vol > 0 {
  848. remark = append(remark, fmt.Sprintf("%s%s", common.FormatTraffic(vol), "📊"))
  849. }
  850. now := time.Now().Unix()
  851. switch exp := stats.ExpiryTime / 1000; {
  852. case exp > 0:
  853. remainingSeconds := exp - now
  854. days := remainingSeconds / 86400
  855. hours := (remainingSeconds % 86400) / 3600
  856. minutes := (remainingSeconds % 3600) / 60
  857. if days > 0 {
  858. if hours > 0 {
  859. remark = append(remark, fmt.Sprintf("%dD,%dH⏳", days, hours))
  860. } else {
  861. remark = append(remark, fmt.Sprintf("%dD⏳", days))
  862. }
  863. } else if hours > 0 {
  864. remark = append(remark, fmt.Sprintf("%dH⏳", hours))
  865. } else {
  866. remark = append(remark, fmt.Sprintf("%dM⏳", minutes))
  867. }
  868. case exp < 0:
  869. days := exp / -86400
  870. hours := (exp % -86400) / 3600
  871. minutes := (exp % -3600) / 60
  872. if days > 0 {
  873. if hours > 0 {
  874. remark = append(remark, fmt.Sprintf("%dD,%dH⏳", days, hours))
  875. } else {
  876. remark = append(remark, fmt.Sprintf("%dD⏳", days))
  877. }
  878. } else if hours > 0 {
  879. remark = append(remark, fmt.Sprintf("%dH⏳", hours))
  880. } else {
  881. remark = append(remark, fmt.Sprintf("%dM⏳", minutes))
  882. }
  883. }
  884. }
  885. }
  886. return strings.Join(remark, separationChar)
  887. }
  888. func searchKey(data any, key string) (any, bool) {
  889. switch val := data.(type) {
  890. case map[string]any:
  891. for k, v := range val {
  892. if k == key {
  893. return v, true
  894. }
  895. if result, ok := searchKey(v, key); ok {
  896. return result, true
  897. }
  898. }
  899. case []any:
  900. for _, v := range val {
  901. if result, ok := searchKey(v, key); ok {
  902. return result, true
  903. }
  904. }
  905. }
  906. return nil, false
  907. }
  908. // buildXhttpExtra walks an xhttpSettings map and returns the JSON blob
  909. // that goes into the URL's `extra` param (or, for VMess, the link
  910. // object). Carries ONLY the bidirectional fields from xray-core's
  911. // SplitHTTPConfig — i.e. the ones the server enforces and the client
  912. // must match. Strictly one-sided fields are excluded:
  913. //
  914. // - server-only (noSSEHeader, scMaxBufferedPosts, scStreamUpServerSecs,
  915. // serverMaxHeaderBytes) — client wouldn't read them, so emitting
  916. // them just bloats the URL.
  917. // - client-only (headers, uplinkHTTPMethod, uplinkChunkSize,
  918. // noGRPCHeader, scMinPostsIntervalMs, xmux, downloadSettings) — the
  919. // inbound config doesn't have them; the client configures them
  920. // locally.
  921. //
  922. // Truthy-only guards keep default inbounds emitting the same compact URL
  923. // they did before this helper grew.
  924. func buildXhttpExtra(xhttp map[string]any) map[string]any {
  925. if xhttp == nil {
  926. return nil
  927. }
  928. extra := map[string]any{}
  929. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  930. extra["xPaddingBytes"] = xpb
  931. }
  932. if obfs, ok := xhttp["xPaddingObfsMode"].(bool); ok && obfs {
  933. extra["xPaddingObfsMode"] = true
  934. for _, field := range []string{"xPaddingKey", "xPaddingHeader", "xPaddingPlacement", "xPaddingMethod"} {
  935. if v, ok := xhttp[field].(string); ok && len(v) > 0 {
  936. extra[field] = v
  937. }
  938. }
  939. }
  940. stringFields := []string{
  941. "sessionPlacement", "sessionKey",
  942. "seqPlacement", "seqKey",
  943. "uplinkDataPlacement", "uplinkDataKey",
  944. "scMaxEachPostBytes",
  945. }
  946. for _, field := range stringFields {
  947. if v, ok := xhttp[field].(string); ok && len(v) > 0 {
  948. extra[field] = v
  949. }
  950. }
  951. // Headers — emitted as the {name: value} map upstream's struct
  952. // expects. The server runtime ignores this field, but the client
  953. // (consuming the share link) honors it. Drop any "host" entry —
  954. // host already wins as a top-level URL param.
  955. if rawHeaders, ok := xhttp["headers"].(map[string]any); ok && len(rawHeaders) > 0 {
  956. out := map[string]any{}
  957. for k, v := range rawHeaders {
  958. if strings.EqualFold(k, "host") {
  959. continue
  960. }
  961. out[k] = v
  962. }
  963. if len(out) > 0 {
  964. extra["headers"] = out
  965. }
  966. }
  967. if len(extra) == 0 {
  968. return nil
  969. }
  970. return extra
  971. }
  972. // applyXhttpExtraParams emits the full xhttp config into the URL query
  973. // params of a vless:// / trojan:// / ss:// link. Sets path/host/mode at
  974. // top level (xray's Build() always lets these win over `extra`) and packs
  975. // everything else into a JSON `extra` param. Also writes the flat
  976. // `x_padding_bytes` param sing-box-family clients understand.
  977. //
  978. // Without this, the admin's custom xPaddingBytes / sessionKey / etc. never
  979. // reach the client and handshakes are silently rejected with
  980. // `invalid padding (...) length: 0` — the client-visible symptom is
  981. // "xhttp doesn't connect" on OpenWRT / sing-box.
  982. //
  983. // Two encodings are written so every popular client can read at least one:
  984. //
  985. // - x_padding_bytes=<range> — flat param, understood by sing-box and its
  986. // derivatives (Podkop, OpenWRT sing-box, Karing, NekoBox, …).
  987. // - extra=<url-encoded-json> — full xhttp settings blob, which is how
  988. // xray-core clients (v2rayNG, Happ, Furious, Exclave, …) pick up the
  989. // bidirectional fields beyond path/host/mode.
  990. func applyXhttpExtraParams(xhttp map[string]any, params map[string]string) {
  991. if xhttp == nil {
  992. return
  993. }
  994. applyPathAndHostParams(xhttp, params)
  995. if mode, ok := xhttp["mode"].(string); ok {
  996. params["mode"] = mode
  997. }
  998. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  999. params["x_padding_bytes"] = xpb
  1000. }
  1001. extra := buildXhttpExtra(xhttp)
  1002. if extra != nil {
  1003. if b, err := json.Marshal(extra); err == nil {
  1004. params["extra"] = string(b)
  1005. }
  1006. }
  1007. }
  1008. var kcpMaskToHeaderType = map[string]string{
  1009. "header-dns": "dns",
  1010. "header-dtls": "dtls",
  1011. "header-srtp": "srtp",
  1012. "header-utp": "utp",
  1013. "header-wechat": "wechat-video",
  1014. "header-wireguard": "wireguard",
  1015. }
  1016. var validFinalMaskUDPTypes = map[string]struct{}{
  1017. "salamander": {},
  1018. "mkcp-aes128gcm": {},
  1019. "header-dns": {},
  1020. "header-dtls": {},
  1021. "header-srtp": {},
  1022. "header-utp": {},
  1023. "header-wechat": {},
  1024. "header-wireguard": {},
  1025. "mkcp-original": {},
  1026. "xdns": {},
  1027. "xicmp": {},
  1028. "noise": {},
  1029. "header-custom": {},
  1030. }
  1031. var validFinalMaskTCPTypes = map[string]struct{}{
  1032. "header-custom": {},
  1033. "fragment": {},
  1034. "sudoku": {},
  1035. }
  1036. // applyKcpShareParams reconstructs legacy KCP share-link fields from either
  1037. // the historical kcpSettings.header/seed shape or the current finalmask model.
  1038. // This keeps subscription output compatible while avoiding panics when older
  1039. // keys are absent from modern inbounds.
  1040. func applyKcpShareParams(stream map[string]any, params map[string]string) {
  1041. extractKcpShareFields(stream).applyToParams(params)
  1042. }
  1043. func applyKcpShareObj(stream map[string]any, obj map[string]any) {
  1044. extractKcpShareFields(stream).applyToObj(obj)
  1045. }
  1046. type kcpShareFields struct {
  1047. headerType string
  1048. seed string
  1049. mtu int
  1050. tti int
  1051. }
  1052. func (f kcpShareFields) applyToParams(params map[string]string) {
  1053. if f.headerType != "" && f.headerType != "none" {
  1054. params["headerType"] = f.headerType
  1055. }
  1056. setStringParam(params, "seed", f.seed)
  1057. setIntParam(params, "mtu", f.mtu)
  1058. setIntParam(params, "tti", f.tti)
  1059. }
  1060. func (f kcpShareFields) applyToObj(obj map[string]any) {
  1061. if f.headerType != "" && f.headerType != "none" {
  1062. obj["type"] = f.headerType
  1063. }
  1064. setStringField(obj, "path", f.seed)
  1065. setIntField(obj, "mtu", f.mtu)
  1066. setIntField(obj, "tti", f.tti)
  1067. }
  1068. func extractKcpShareFields(stream map[string]any) kcpShareFields {
  1069. fields := kcpShareFields{headerType: "none"}
  1070. if kcp, ok := stream["kcpSettings"].(map[string]any); ok {
  1071. if header, ok := kcp["header"].(map[string]any); ok {
  1072. if value, ok := header["type"].(string); ok && value != "" {
  1073. fields.headerType = value
  1074. }
  1075. }
  1076. if value, ok := kcp["seed"].(string); ok && value != "" {
  1077. fields.seed = value
  1078. }
  1079. if value, ok := readPositiveInt(kcp["mtu"]); ok {
  1080. fields.mtu = value
  1081. }
  1082. if value, ok := readPositiveInt(kcp["tti"]); ok {
  1083. fields.tti = value
  1084. }
  1085. }
  1086. for _, rawMask := range normalizedFinalMaskUDPMasks(stream["finalmask"]) {
  1087. mask, _ := rawMask.(map[string]any)
  1088. if mask == nil {
  1089. continue
  1090. }
  1091. maskType, _ := mask["type"].(string)
  1092. if mapped, ok := kcpMaskToHeaderType[maskType]; ok {
  1093. fields.headerType = mapped
  1094. continue
  1095. }
  1096. switch maskType {
  1097. case "mkcp-original":
  1098. fields.seed = ""
  1099. case "mkcp-aes128gcm":
  1100. fields.seed = ""
  1101. settings, _ := mask["settings"].(map[string]any)
  1102. if value, ok := settings["password"].(string); ok && value != "" {
  1103. fields.seed = value
  1104. }
  1105. }
  1106. }
  1107. return fields
  1108. }
  1109. func readPositiveInt(value any) (int, bool) {
  1110. switch number := value.(type) {
  1111. case int:
  1112. return number, number > 0
  1113. case int32:
  1114. return int(number), number > 0
  1115. case int64:
  1116. return int(number), number > 0
  1117. case float32:
  1118. parsed := int(number)
  1119. return parsed, parsed > 0
  1120. case float64:
  1121. parsed := int(number)
  1122. return parsed, parsed > 0
  1123. default:
  1124. return 0, false
  1125. }
  1126. }
  1127. func setStringParam(params map[string]string, key, value string) {
  1128. if value == "" {
  1129. delete(params, key)
  1130. return
  1131. }
  1132. params[key] = value
  1133. }
  1134. func setIntParam(params map[string]string, key string, value int) {
  1135. if value <= 0 {
  1136. delete(params, key)
  1137. return
  1138. }
  1139. params[key] = fmt.Sprintf("%d", value)
  1140. }
  1141. func setStringField(obj map[string]any, key, value string) {
  1142. if value == "" {
  1143. delete(obj, key)
  1144. return
  1145. }
  1146. obj[key] = value
  1147. }
  1148. func setIntField(obj map[string]any, key string, value int) {
  1149. if value <= 0 {
  1150. delete(obj, key)
  1151. return
  1152. }
  1153. obj[key] = value
  1154. }
  1155. // applyFinalMaskParams exports the finalmask payload as the compact
  1156. // `fm=<json>` share-link field used by v2rayN-compatible clients.
  1157. func applyFinalMaskParams(finalmask map[string]any, params map[string]string) {
  1158. if fm, ok := marshalFinalMask(finalmask); ok {
  1159. params["fm"] = fm
  1160. }
  1161. }
  1162. func applyFinalMaskObj(finalmask map[string]any, obj map[string]any) {
  1163. if fm, ok := marshalFinalMask(finalmask); ok {
  1164. obj["fm"] = fm
  1165. }
  1166. }
  1167. func marshalFinalMask(finalmask map[string]any) (string, bool) {
  1168. normalized := normalizeFinalMask(finalmask)
  1169. if !hasFinalMaskContent(normalized) {
  1170. return "", false
  1171. }
  1172. b, err := json.Marshal(normalized)
  1173. if err != nil || len(b) == 0 || string(b) == "null" {
  1174. return "", false
  1175. }
  1176. return string(b), true
  1177. }
  1178. func normalizeFinalMask(finalmask map[string]any) map[string]any {
  1179. tcpMasks := normalizedFinalMaskTCPMasks(finalmask)
  1180. udpMasks := normalizedFinalMaskUDPMasks(finalmask)
  1181. quicParams, hasQuicParams := finalmask["quicParams"].(map[string]any)
  1182. if len(tcpMasks) == 0 && len(udpMasks) == 0 && !hasQuicParams {
  1183. return nil
  1184. }
  1185. result := map[string]any{}
  1186. if len(tcpMasks) > 0 {
  1187. result["tcp"] = tcpMasks
  1188. }
  1189. if len(udpMasks) > 0 {
  1190. result["udp"] = udpMasks
  1191. }
  1192. if hasQuicParams && len(quicParams) > 0 {
  1193. result["quicParams"] = quicParams
  1194. }
  1195. return result
  1196. }
  1197. func normalizedFinalMaskTCPMasks(value any) []any {
  1198. finalmask, _ := value.(map[string]any)
  1199. if finalmask == nil {
  1200. return nil
  1201. }
  1202. rawMasks, _ := finalmask["tcp"].([]any)
  1203. if len(rawMasks) == 0 {
  1204. return nil
  1205. }
  1206. normalized := make([]any, 0, len(rawMasks))
  1207. for _, rawMask := range rawMasks {
  1208. mask, _ := rawMask.(map[string]any)
  1209. if mask == nil {
  1210. continue
  1211. }
  1212. maskType, _ := mask["type"].(string)
  1213. if _, ok := validFinalMaskTCPTypes[maskType]; !ok || maskType == "" {
  1214. continue
  1215. }
  1216. normalizedMask := map[string]any{"type": maskType}
  1217. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  1218. normalizedMask["settings"] = settings
  1219. }
  1220. normalized = append(normalized, normalizedMask)
  1221. }
  1222. if len(normalized) == 0 {
  1223. return nil
  1224. }
  1225. return normalized
  1226. }
  1227. func normalizedFinalMaskUDPMasks(value any) []any {
  1228. finalmask, _ := value.(map[string]any)
  1229. if finalmask == nil {
  1230. return nil
  1231. }
  1232. rawMasks, _ := finalmask["udp"].([]any)
  1233. if len(rawMasks) == 0 {
  1234. return nil
  1235. }
  1236. normalized := make([]any, 0, len(rawMasks))
  1237. for _, rawMask := range rawMasks {
  1238. mask, _ := rawMask.(map[string]any)
  1239. if mask == nil {
  1240. continue
  1241. }
  1242. maskType, _ := mask["type"].(string)
  1243. if _, ok := validFinalMaskUDPTypes[maskType]; !ok || maskType == "" {
  1244. continue
  1245. }
  1246. normalizedMask := map[string]any{"type": maskType}
  1247. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  1248. normalizedMask["settings"] = settings
  1249. }
  1250. normalized = append(normalized, normalizedMask)
  1251. }
  1252. if len(normalized) == 0 {
  1253. return nil
  1254. }
  1255. return normalized
  1256. }
  1257. func hasFinalMaskContent(value any) bool {
  1258. switch v := value.(type) {
  1259. case nil:
  1260. return false
  1261. case string:
  1262. return len(v) > 0
  1263. case map[string]any:
  1264. for _, item := range v {
  1265. if hasFinalMaskContent(item) {
  1266. return true
  1267. }
  1268. }
  1269. return false
  1270. case []any:
  1271. return slices.ContainsFunc(v, hasFinalMaskContent)
  1272. default:
  1273. return true
  1274. }
  1275. }
  1276. func searchHost(headers any) string {
  1277. data, _ := headers.(map[string]any)
  1278. for k, v := range data {
  1279. if strings.EqualFold(k, "host") {
  1280. switch v.(type) {
  1281. case []any:
  1282. hosts, _ := v.([]any)
  1283. if len(hosts) > 0 {
  1284. return hosts[0].(string)
  1285. } else {
  1286. return ""
  1287. }
  1288. case any:
  1289. return v.(string)
  1290. }
  1291. }
  1292. }
  1293. return ""
  1294. }
  1295. // PageData is a view model for subpage.html
  1296. // PageData contains data for rendering the subscription information page.
  1297. type PageData struct {
  1298. Host string
  1299. BasePath string
  1300. SId string
  1301. Enabled bool
  1302. Download string
  1303. Upload string
  1304. Total string
  1305. Used string
  1306. Remained string
  1307. Expire int64
  1308. LastOnline int64
  1309. Datepicker string
  1310. DownloadByte int64
  1311. UploadByte int64
  1312. TotalByte int64
  1313. SubUrl string
  1314. SubJsonUrl string
  1315. SubClashUrl string
  1316. SubTitle string
  1317. SubSupportUrl string
  1318. Result []string
  1319. }
  1320. // ResolveRequest extracts scheme and host info from request/headers consistently.
  1321. // ResolveRequest extracts scheme, host, and header information from an HTTP request.
  1322. func (s *SubService) ResolveRequest(c *gin.Context) (scheme string, host string, hostWithPort string, hostHeader string) {
  1323. // scheme
  1324. scheme = "http"
  1325. if c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https") {
  1326. scheme = "https"
  1327. }
  1328. // base host (no port)
  1329. if h, err := getHostFromXFH(c.GetHeader("X-Forwarded-Host")); err == nil && h != "" {
  1330. host = h
  1331. }
  1332. if host == "" {
  1333. host = c.GetHeader("X-Real-IP")
  1334. }
  1335. if host == "" {
  1336. var err error
  1337. host, _, err = net.SplitHostPort(c.Request.Host)
  1338. if err != nil {
  1339. host = c.Request.Host
  1340. }
  1341. }
  1342. // host:port for URLs
  1343. hostWithPort = c.GetHeader("X-Forwarded-Host")
  1344. if hostWithPort == "" {
  1345. hostWithPort = c.Request.Host
  1346. }
  1347. if hostWithPort == "" {
  1348. hostWithPort = host
  1349. }
  1350. // header display host
  1351. hostHeader = c.GetHeader("X-Forwarded-Host")
  1352. if hostHeader == "" {
  1353. hostHeader = c.GetHeader("X-Real-IP")
  1354. }
  1355. if hostHeader == "" {
  1356. hostHeader = host
  1357. }
  1358. return
  1359. }
  1360. // BuildURLs constructs absolute subscription and JSON subscription URLs for a given subscription ID.
  1361. // It prioritizes configured URIs, then individual settings, and finally falls back to request-derived components.
  1362. func (s *SubService) BuildURLs(scheme, hostWithPort, subPath, subJsonPath, subClashPath, subId string) (subURL, subJsonURL, subClashURL string) {
  1363. if subId == "" {
  1364. return "", "", ""
  1365. }
  1366. configuredSubURI, _ := s.settingService.GetSubURI()
  1367. configuredSubJsonURI, _ := s.settingService.GetSubJsonURI()
  1368. configuredSubClashURI, _ := s.settingService.GetSubClashURI()
  1369. var baseScheme, baseHostWithPort string
  1370. if configuredSubURI == "" || configuredSubJsonURI == "" || configuredSubClashURI == "" {
  1371. baseScheme, baseHostWithPort = s.getBaseSchemeAndHost(scheme, hostWithPort)
  1372. }
  1373. subURL = s.buildSingleURL(configuredSubURI, baseScheme, baseHostWithPort, subPath, subId)
  1374. subJsonURL = s.buildSingleURL(configuredSubJsonURI, baseScheme, baseHostWithPort, subJsonPath, subId)
  1375. subClashURL = s.buildSingleURL(configuredSubClashURI, baseScheme, baseHostWithPort, subClashPath, subId)
  1376. return subURL, subJsonURL, subClashURL
  1377. }
  1378. // getBaseSchemeAndHost determines the base scheme and host from settings or falls back to request values
  1379. func (s *SubService) getBaseSchemeAndHost(requestScheme, requestHostWithPort string) (string, string) {
  1380. subDomain, err := s.settingService.GetSubDomain()
  1381. if err != nil || subDomain == "" {
  1382. return requestScheme, requestHostWithPort
  1383. }
  1384. // Get port and TLS settings
  1385. subPort, _ := s.settingService.GetSubPort()
  1386. subKeyFile, _ := s.settingService.GetSubKeyFile()
  1387. subCertFile, _ := s.settingService.GetSubCertFile()
  1388. // Determine scheme from TLS configuration
  1389. scheme := "http"
  1390. if subKeyFile != "" && subCertFile != "" {
  1391. scheme = "https"
  1392. }
  1393. // Build host:port, always include port for clarity
  1394. hostWithPort := fmt.Sprintf("%s:%d", subDomain, subPort)
  1395. return scheme, hostWithPort
  1396. }
  1397. // buildSingleURL constructs a single URL using configured URI or base components
  1398. func (s *SubService) buildSingleURL(configuredURI, baseScheme, baseHostWithPort, basePath, subId string) string {
  1399. if configuredURI != "" {
  1400. return s.joinPathWithID(configuredURI, subId)
  1401. }
  1402. baseURL := fmt.Sprintf("%s://%s", baseScheme, baseHostWithPort)
  1403. return s.joinPathWithID(baseURL+basePath, subId)
  1404. }
  1405. // joinPathWithID safely joins a base path with a subscription ID
  1406. func (s *SubService) joinPathWithID(basePath, subId string) string {
  1407. if strings.HasSuffix(basePath, "/") {
  1408. return basePath + subId
  1409. }
  1410. return basePath + "/" + subId
  1411. }
  1412. // BuildPageData parses header and prepares the template view model.
  1413. // BuildPageData constructs page data for rendering the subscription information page.
  1414. func (s *SubService) BuildPageData(subId string, hostHeader string, traffic xray.ClientTraffic, lastOnline int64, subs []string, subURL, subJsonURL, subClashURL string, basePath string, subTitle string, subSupportUrl string) PageData {
  1415. download := common.FormatTraffic(traffic.Down)
  1416. upload := common.FormatTraffic(traffic.Up)
  1417. total := "∞"
  1418. used := common.FormatTraffic(traffic.Up + traffic.Down)
  1419. remained := ""
  1420. if traffic.Total > 0 {
  1421. total = common.FormatTraffic(traffic.Total)
  1422. left := max(traffic.Total-(traffic.Up+traffic.Down), 0)
  1423. remained = common.FormatTraffic(left)
  1424. }
  1425. datepicker := s.datepicker
  1426. if datepicker == "" {
  1427. datepicker = "gregorian"
  1428. }
  1429. return PageData{
  1430. Host: hostHeader,
  1431. BasePath: basePath,
  1432. SId: subId,
  1433. Enabled: traffic.Enable,
  1434. Download: download,
  1435. Upload: upload,
  1436. Total: total,
  1437. Used: used,
  1438. Remained: remained,
  1439. Expire: traffic.ExpiryTime / 1000,
  1440. LastOnline: lastOnline,
  1441. Datepicker: datepicker,
  1442. DownloadByte: traffic.Down,
  1443. UploadByte: traffic.Up,
  1444. TotalByte: traffic.Total,
  1445. SubUrl: subURL,
  1446. SubJsonUrl: subJsonURL,
  1447. SubClashUrl: subClashURL,
  1448. SubTitle: subTitle,
  1449. SubSupportUrl: subSupportUrl,
  1450. Result: subs,
  1451. }
  1452. }
  1453. func getHostFromXFH(s string) (string, error) {
  1454. if strings.Contains(s, ":") {
  1455. realHost, _, err := net.SplitHostPort(s)
  1456. if err != nil {
  1457. return "", err
  1458. }
  1459. return realHost, nil
  1460. }
  1461. return s, nil
  1462. }