subService.go 48 KB

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