1
0

subService.go 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115
  1. package sub
  2. import (
  3. "crypto/sha256"
  4. "encoding/base64"
  5. "encoding/hex"
  6. "fmt"
  7. "maps"
  8. "net"
  9. "net/url"
  10. "slices"
  11. "strings"
  12. "time"
  13. "github.com/gin-gonic/gin"
  14. "github.com/goccy/go-json"
  15. "github.com/mhsanaei/3x-ui/v3/database"
  16. "github.com/mhsanaei/3x-ui/v3/database/model"
  17. "github.com/mhsanaei/3x-ui/v3/logger"
  18. "github.com/mhsanaei/3x-ui/v3/util/common"
  19. "github.com/mhsanaei/3x-ui/v3/util/random"
  20. "github.com/mhsanaei/3x-ui/v3/web/service"
  21. "github.com/mhsanaei/3x-ui/v3/xray"
  22. )
  23. // SubService provides business logic for generating subscription links and managing subscription data.
  24. type SubService struct {
  25. address string
  26. showInfo bool
  27. remarkModel string
  28. datepicker string
  29. emailInRemark bool
  30. inboundService service.InboundService
  31. settingService service.SettingService
  32. // nodesByID is populated per request from the Node table so
  33. // resolveInboundAddress can return the node's address for any
  34. // inbound whose NodeID is set. Keeps the per-link host derivation
  35. // O(1) instead of O(N) DB hits.
  36. nodesByID map[int]*model.Node
  37. }
  38. // NewSubService creates a new subscription service with the given configuration.
  39. func NewSubService(showInfo bool, remarkModel string) *SubService {
  40. return &SubService{
  41. showInfo: showInfo,
  42. remarkModel: remarkModel,
  43. }
  44. }
  45. // PrepareForRequest sets per-request state (host + nodes map) on the
  46. // shared SubService. Called by every entry point — GetSubs, GetJson,
  47. // GetClash — so resolveInboundAddress sees the right host and the
  48. // freshly-loaded node map regardless of which sub flavour the client
  49. // hit.
  50. func (s *SubService) PrepareForRequest(host string) {
  51. if !isRoutableHost(host) {
  52. if d := s.configuredPublicHost(); d != "" {
  53. host = d
  54. } else if isLoopbackHost(host) {
  55. host = "localhost"
  56. }
  57. }
  58. s.address = host
  59. s.loadNodes()
  60. }
  61. func (s *SubService) configuredPublicHost() string {
  62. if d, err := s.settingService.GetSubDomain(); err == nil && d != "" {
  63. return d
  64. }
  65. if d, err := s.settingService.GetWebDomain(); err == nil && d != "" {
  66. return d
  67. }
  68. return ""
  69. }
  70. func isRoutableHost(host string) bool {
  71. if host == "" {
  72. return false
  73. }
  74. if ip := net.ParseIP(strings.Trim(host, "[]")); ip != nil {
  75. return !ip.IsLoopback() && !ip.IsUnspecified()
  76. }
  77. return true
  78. }
  79. func isLoopbackHost(host string) bool {
  80. ip := net.ParseIP(strings.Trim(host, "[]"))
  81. return ip != nil && ip.IsLoopback()
  82. }
  83. // GetSubs retrieves subscription links for a given subscription ID and host.
  84. func (s *SubService) GetSubs(subId string, host string) ([]string, []string, int64, xray.ClientTraffic, error) {
  85. s.PrepareForRequest(host)
  86. var result []string
  87. var emails []string
  88. var traffic xray.ClientTraffic
  89. var hasEnabledClient bool
  90. inbounds, err := s.getInboundsBySubId(subId)
  91. if err != nil {
  92. return nil, nil, 0, traffic, err
  93. }
  94. if len(inbounds) == 0 {
  95. return nil, nil, 0, traffic, nil
  96. }
  97. s.datepicker, err = s.settingService.GetDatepicker()
  98. if err != nil {
  99. s.datepicker = "gregorian"
  100. }
  101. s.emailInRemark, err = s.settingService.GetSubEmailInRemark()
  102. if err != nil {
  103. s.emailInRemark = true
  104. }
  105. seenEmails := make(map[string]struct{})
  106. for _, inbound := range inbounds {
  107. clients, err := s.inboundService.GetClients(inbound)
  108. if err != nil {
  109. logger.Error("SubService - GetClients: Unable to get clients from inbound")
  110. }
  111. if clients == nil {
  112. continue
  113. }
  114. s.projectThroughFallbackMaster(inbound)
  115. for _, client := range clients {
  116. if client.SubID == subId {
  117. if client.Enable {
  118. hasEnabledClient = true
  119. }
  120. result = append(result, s.GetLink(inbound, client.Email))
  121. emails = append(emails, client.Email)
  122. seenEmails[client.Email] = struct{}{}
  123. }
  124. }
  125. }
  126. uniqueEmails := make([]string, 0, len(seenEmails))
  127. for e := range seenEmails {
  128. uniqueEmails = append(uniqueEmails, e)
  129. }
  130. traffic, lastOnline := s.AggregateTrafficByEmails(uniqueEmails)
  131. traffic.Enable = hasEnabledClient
  132. return result, emails, lastOnline, traffic, nil
  133. }
  134. // AggregateTrafficByEmails resolves traffic for every email in one
  135. // query and folds the rows into a single ClientTraffic + lastOnline.
  136. // xray.ClientTraffic.Email is globally unique, so a multi-inbound
  137. // client's single row is attached to exactly one inbound — iterating
  138. // per-inbound ClientStats would miss it on the others. Used by GetSubs,
  139. // SubClashService.GetClash, and SubJsonService.GetJson to keep the
  140. // sub-info header consistent across all three formats.
  141. func (s *SubService) AggregateTrafficByEmails(emails []string) (xray.ClientTraffic, int64) {
  142. var agg xray.ClientTraffic
  143. var lastOnline int64
  144. if len(emails) == 0 {
  145. return agg, 0
  146. }
  147. db := database.GetDB()
  148. var rows []xray.ClientTraffic
  149. if err := db.
  150. Model(&xray.ClientTraffic{}).
  151. Where("email IN ?", emails).
  152. Find(&rows).Error; err != nil {
  153. logger.Warning("SubService - AggregateTrafficByEmails: load by email:", err)
  154. return agg, 0
  155. }
  156. // total/expiry are configured limits owned by the clients table, not the
  157. // runtime traffic rows. In a multi-node setup the node snapshot can reset
  158. // client_traffics.total/expiry_time to 0, so fall back to the clients
  159. // table to keep the Subscription-Userinfo header in sync with the UI (#4645).
  160. limits := make(map[string][2]int64, len(emails))
  161. var records []model.ClientRecord
  162. if err := db.Model(&model.ClientRecord{}).Where("email IN ?", emails).Find(&records).Error; err != nil {
  163. logger.Warning("SubService - AggregateTrafficByEmails: load client limits:", err)
  164. } else {
  165. for _, r := range records {
  166. limits[r.Email] = [2]int64{r.TotalGB, r.ExpiryTime}
  167. }
  168. }
  169. now := time.Now().UnixMilli()
  170. first := true
  171. for _, ct := range rows {
  172. if ct.LastOnline > lastOnline {
  173. lastOnline = ct.LastOnline
  174. }
  175. total, expiry := ct.Total, ct.ExpiryTime
  176. if lim, ok := limits[ct.Email]; ok {
  177. if total == 0 {
  178. total = lim[0]
  179. }
  180. if expiry == 0 {
  181. expiry = lim[1]
  182. }
  183. }
  184. if first {
  185. agg.Up = ct.Up
  186. agg.Down = ct.Down
  187. agg.Total = total
  188. agg.ExpiryTime = subscriptionExpiryFromClient(now, expiry)
  189. first = false
  190. continue
  191. }
  192. agg.Up += ct.Up
  193. agg.Down += ct.Down
  194. if agg.Total == 0 || total == 0 {
  195. agg.Total = 0
  196. } else {
  197. agg.Total += total
  198. }
  199. normalized := subscriptionExpiryFromClient(now, expiry)
  200. if normalized != agg.ExpiryTime {
  201. agg.ExpiryTime = 0
  202. }
  203. }
  204. return agg, lastOnline
  205. }
  206. func subscriptionExpiryFromClient(nowMs, expiryTime int64) int64 {
  207. if expiryTime > 0 {
  208. return expiryTime
  209. }
  210. if expiryTime < 0 {
  211. return nowMs + (-expiryTime)
  212. }
  213. return 0
  214. }
  215. func (s *SubService) getInboundsBySubId(subId string) ([]*model.Inbound, error) {
  216. db := database.GetDB()
  217. var inbounds []*model.Inbound
  218. err := db.Model(model.Inbound{}).Preload("ClientStats").Where(`id in (
  219. SELECT DISTINCT inbounds.id
  220. FROM inbounds
  221. JOIN client_inbounds ON client_inbounds.inbound_id = inbounds.id
  222. JOIN clients ON clients.id = client_inbounds.client_id
  223. WHERE
  224. inbounds.protocol in ('vmess','vless','trojan','shadowsocks','hysteria')
  225. AND clients.sub_id = ? AND inbounds.enable = ?
  226. )`, subId, true).Find(&inbounds).Error
  227. if err != nil {
  228. return nil, err
  229. }
  230. return inbounds, nil
  231. }
  232. // projectThroughFallbackMaster mutates the inbound in place so its
  233. // Listen/Port/StreamSettings reflect the externally reachable master
  234. // when applicable. Covers both fallback mechanisms:
  235. // - panel-tracked: an inbound_fallbacks row where child_id = inbound.Id
  236. // - legacy unix-socket: inbound.Listen begins with "@" and some VLESS/
  237. // Trojan inbound's settings.fallbacks references that listen address
  238. //
  239. // Returns true when a projection happened; sub services call this before
  240. // generating links so a child VLESS-WS bound to 127.0.0.1 emits the
  241. // master's :443 + TLS state instead of its own loopback endpoint.
  242. func (s *SubService) projectThroughFallbackMaster(inbound *model.Inbound) bool {
  243. if inbound == nil {
  244. return false
  245. }
  246. db := database.GetDB()
  247. var master *model.Inbound
  248. var rule model.InboundFallback
  249. if err := db.Where("child_id = ?", inbound.Id).
  250. Order("sort_order ASC, id ASC").
  251. First(&rule).Error; err == nil {
  252. var m model.Inbound
  253. if err := db.Where("id = ?", rule.MasterId).First(&m).Error; err == nil {
  254. master = &m
  255. }
  256. }
  257. if master == nil && len(inbound.Listen) > 0 && inbound.Listen[0] == '@' {
  258. var m model.Inbound
  259. if err := db.Model(model.Inbound{}).
  260. Where("JSON_TYPE(settings, '$.fallbacks') = 'array'").
  261. Where("EXISTS (SELECT * FROM json_each(settings, '$.fallbacks') WHERE json_extract(value, '$.dest') = ?)", inbound.Listen).
  262. First(&m).Error; err == nil {
  263. master = &m
  264. }
  265. }
  266. if master == nil {
  267. return false
  268. }
  269. inbound.StreamSettings = mergeStreamFromMaster(inbound.StreamSettings, master.StreamSettings)
  270. inbound.Listen = master.Listen
  271. inbound.Port = master.Port
  272. return true
  273. }
  274. // mergeStreamFromMaster copies the master's security + tlsSettings +
  275. // realitySettings + externalProxy onto the child's stream so the child's
  276. // link advertises the master's TLS / Reality state. Transport (network
  277. // + ws/grpc/etc. settings) stays the child's.
  278. func mergeStreamFromMaster(childStream, masterStream string) string {
  279. var stream map[string]any
  280. json.Unmarshal([]byte(childStream), &stream)
  281. if stream == nil {
  282. stream = map[string]any{}
  283. }
  284. var mst map[string]any
  285. json.Unmarshal([]byte(masterStream), &mst)
  286. if mst == nil {
  287. return childStream
  288. }
  289. stream["security"] = mst["security"]
  290. if v, ok := mst["tlsSettings"]; ok {
  291. stream["tlsSettings"] = v
  292. } else {
  293. delete(stream, "tlsSettings")
  294. }
  295. if v, ok := mst["realitySettings"]; ok {
  296. stream["realitySettings"] = v
  297. } else {
  298. delete(stream, "realitySettings")
  299. }
  300. if v, ok := mst["externalProxy"]; ok {
  301. stream["externalProxy"] = v
  302. }
  303. out, err := json.MarshalIndent(stream, "", " ")
  304. if err != nil {
  305. return childStream
  306. }
  307. return string(out)
  308. }
  309. // GetLink dispatches to the protocol-specific generator for one (inbound, client)
  310. // pair. Returns "" when the inbound's protocol doesn't produce a subscription URL
  311. // (socks, http, mixed, wireguard, dokodemo, tunnel). The returned string may
  312. // contain multiple `\n`-separated URLs when the inbound has externalProxy set.
  313. func (s *SubService) GetLink(inbound *model.Inbound, email string) string {
  314. switch inbound.Protocol {
  315. case "vmess":
  316. return s.genVmessLink(inbound, email)
  317. case "vless":
  318. return s.genVlessLink(inbound, email)
  319. case "trojan":
  320. return s.genTrojanLink(inbound, email)
  321. case "shadowsocks":
  322. return s.genShadowsocksLink(inbound, email)
  323. case "hysteria":
  324. return s.genHysteriaLink(inbound, email)
  325. }
  326. return ""
  327. }
  328. // Protocol link generators are intentionally ordered as:
  329. // vmess -> vless -> trojan -> shadowsocks -> hysteria.
  330. func (s *SubService) genVmessLink(inbound *model.Inbound, email string) string {
  331. if inbound.Protocol != model.VMESS {
  332. return ""
  333. }
  334. address := s.resolveInboundAddress(inbound)
  335. obj := map[string]any{
  336. "v": "2",
  337. "add": address,
  338. "port": inbound.Port,
  339. "type": "none",
  340. }
  341. stream := unmarshalStreamSettings(inbound.StreamSettings)
  342. network, _ := stream["network"].(string)
  343. applyVmessNetworkParams(stream, network, obj)
  344. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  345. applyFinalMaskObj(finalmask, obj)
  346. }
  347. security, _ := stream["security"].(string)
  348. obj["tls"] = security
  349. if security == "tls" {
  350. applyVmessTLSParams(stream, obj)
  351. }
  352. clients, _ := s.inboundService.GetClients(inbound)
  353. clientIndex := findClientIndex(clients, email)
  354. obj["id"] = clients[clientIndex].ID
  355. obj["scy"] = clients[clientIndex].Security
  356. externalProxies, _ := stream["externalProxy"].([]any)
  357. if len(externalProxies) > 0 {
  358. return s.buildVmessExternalProxyLinks(externalProxies, obj, inbound, email)
  359. }
  360. obj["ps"] = s.genRemark(inbound, email, "")
  361. return buildVmessLink(obj)
  362. }
  363. func (s *SubService) genVlessLink(inbound *model.Inbound, email string) string {
  364. if inbound.Protocol != model.VLESS {
  365. return ""
  366. }
  367. address := s.resolveInboundAddress(inbound)
  368. stream := unmarshalStreamSettings(inbound.StreamSettings)
  369. clients, _ := s.inboundService.GetClients(inbound)
  370. clientIndex := findClientIndex(clients, email)
  371. uuid := clients[clientIndex].ID
  372. port := inbound.Port
  373. streamNetwork := stream["network"].(string)
  374. params := make(map[string]string)
  375. params["type"] = streamNetwork
  376. // Add encryption parameter for VLESS from inbound settings
  377. var settings map[string]any
  378. json.Unmarshal([]byte(inbound.Settings), &settings)
  379. if encryption, ok := settings["encryption"].(string); ok {
  380. params["encryption"] = encryption
  381. }
  382. applyShareNetworkParams(stream, streamNetwork, params)
  383. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  384. applyFinalMaskParams(finalmask, params)
  385. }
  386. security, _ := stream["security"].(string)
  387. switch security {
  388. case "tls":
  389. applyShareTLSParams(stream, params)
  390. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  391. params["flow"] = clients[clientIndex].Flow
  392. }
  393. case "reality":
  394. applyShareRealityParams(stream, params)
  395. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  396. params["flow"] = clients[clientIndex].Flow
  397. }
  398. default:
  399. params["security"] = "none"
  400. }
  401. externalProxies, _ := stream["externalProxy"].([]any)
  402. if len(externalProxies) > 0 {
  403. return s.buildExternalProxyURLLinks(
  404. externalProxies,
  405. params,
  406. security,
  407. func(dest string, port int) string {
  408. return fmt.Sprintf("vless://%s@%s:%d", uuid, dest, port)
  409. },
  410. func(ep map[string]any) string {
  411. return s.genRemark(inbound, email, ep["remark"].(string))
  412. },
  413. )
  414. }
  415. link := fmt.Sprintf("vless://%s@%s:%d", uuid, address, port)
  416. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  417. }
  418. func (s *SubService) genTrojanLink(inbound *model.Inbound, email string) string {
  419. if inbound.Protocol != model.Trojan {
  420. return ""
  421. }
  422. address := s.resolveInboundAddress(inbound)
  423. stream := unmarshalStreamSettings(inbound.StreamSettings)
  424. clients, _ := s.inboundService.GetClients(inbound)
  425. clientIndex := findClientIndex(clients, email)
  426. password := encodeUserinfo(clients[clientIndex].Password)
  427. port := inbound.Port
  428. streamNetwork := stream["network"].(string)
  429. params := make(map[string]string)
  430. params["type"] = streamNetwork
  431. applyShareNetworkParams(stream, streamNetwork, params)
  432. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  433. applyFinalMaskParams(finalmask, params)
  434. }
  435. security, _ := stream["security"].(string)
  436. switch security {
  437. case "tls":
  438. applyShareTLSParams(stream, params)
  439. case "reality":
  440. applyShareRealityParams(stream, params)
  441. if streamNetwork == "tcp" && len(clients[clientIndex].Flow) > 0 {
  442. params["flow"] = clients[clientIndex].Flow
  443. }
  444. default:
  445. params["security"] = "none"
  446. }
  447. externalProxies, _ := stream["externalProxy"].([]any)
  448. if len(externalProxies) > 0 {
  449. return s.buildExternalProxyURLLinks(
  450. externalProxies,
  451. params,
  452. security,
  453. func(dest string, port int) string {
  454. return fmt.Sprintf("trojan://%s@%s:%d", password, dest, port)
  455. },
  456. func(ep map[string]any) string {
  457. return s.genRemark(inbound, email, ep["remark"].(string))
  458. },
  459. )
  460. }
  461. link := fmt.Sprintf("trojan://%s@%s:%d", password, address, port)
  462. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  463. }
  464. // encodeUserinfo percent-encodes a userinfo (password/auth) value so it
  465. // can be safely embedded in a `scheme://<value>@host:port` URL. RFC 3986
  466. // allows `=` in userinfo as a sub-delim, but several Trojan and Hysteria
  467. // clients reject share-links where the password contains literal `/`
  468. // or `=` (notably the common base64-with-padding shape produced by the
  469. // panel). Encode them too — this matches encodeURIComponent() on the
  470. // frontend and round-trips cleanly through net/url's parser.
  471. func encodeUserinfo(s string) string {
  472. return strings.ReplaceAll(url.QueryEscape(s), "+", "%20")
  473. }
  474. func (s *SubService) genShadowsocksLink(inbound *model.Inbound, email string) string {
  475. if inbound.Protocol != model.Shadowsocks {
  476. return ""
  477. }
  478. address := s.resolveInboundAddress(inbound)
  479. stream := unmarshalStreamSettings(inbound.StreamSettings)
  480. clients, _ := s.inboundService.GetClients(inbound)
  481. var settings map[string]any
  482. json.Unmarshal([]byte(inbound.Settings), &settings)
  483. inboundPassword := settings["password"].(string)
  484. method := settings["method"].(string)
  485. clientIndex := findClientIndex(clients, email)
  486. streamNetwork := stream["network"].(string)
  487. params := make(map[string]string)
  488. params["type"] = streamNetwork
  489. applyShareNetworkParams(stream, streamNetwork, params)
  490. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  491. applyFinalMaskParams(finalmask, params)
  492. }
  493. security, _ := stream["security"].(string)
  494. if security == "tls" {
  495. applyShareTLSParams(stream, params)
  496. }
  497. encPart := fmt.Sprintf("%s:%s", method, clients[clientIndex].Password)
  498. if method[0] == '2' {
  499. encPart = fmt.Sprintf("%s:%s:%s", method, inboundPassword, clients[clientIndex].Password)
  500. }
  501. externalProxies, _ := stream["externalProxy"].([]any)
  502. if len(externalProxies) > 0 {
  503. proxyParams := cloneStringMap(params)
  504. proxyParams["security"] = security
  505. return s.buildExternalProxyURLLinks(
  506. externalProxies,
  507. proxyParams,
  508. security,
  509. func(dest string, port int) string {
  510. return fmt.Sprintf("ss://%s@%s:%d", base64.RawURLEncoding.EncodeToString([]byte(encPart)), dest, port)
  511. },
  512. func(ep map[string]any) string {
  513. return s.genRemark(inbound, email, ep["remark"].(string))
  514. },
  515. )
  516. }
  517. link := fmt.Sprintf("ss://%s@%s:%d", base64.RawURLEncoding.EncodeToString([]byte(encPart)), address, inbound.Port)
  518. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  519. }
  520. func (s *SubService) genHysteriaLink(inbound *model.Inbound, email string) string {
  521. if inbound.Protocol != model.Hysteria {
  522. return ""
  523. }
  524. var stream map[string]any
  525. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  526. clients, _ := s.inboundService.GetClients(inbound)
  527. clientIndex := -1
  528. for i, client := range clients {
  529. if client.Email == email {
  530. clientIndex = i
  531. break
  532. }
  533. }
  534. auth := encodeUserinfo(clients[clientIndex].Auth)
  535. params := make(map[string]string)
  536. params["security"] = "tls"
  537. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  538. alpns, _ := tlsSetting["alpn"].([]any)
  539. var alpn []string
  540. for _, a := range alpns {
  541. alpn = append(alpn, a.(string))
  542. }
  543. if len(alpn) > 0 {
  544. params["alpn"] = strings.Join(alpn, ",")
  545. }
  546. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  547. params["sni"], _ = sniValue.(string)
  548. }
  549. tlsSettings, _ := searchKey(tlsSetting, "settings")
  550. if tlsSetting != nil {
  551. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  552. params["fp"], _ = fpValue.(string)
  553. }
  554. if echValue, ok := searchKey(tlsSettings, "echConfigList"); ok {
  555. if ech, _ := echValue.(string); ech != "" {
  556. params["ech"] = ech
  557. }
  558. }
  559. if pins, ok := pinnedSha256List(tlsSettings); ok {
  560. for i, p := range pins {
  561. pins[i] = hysteriaPinHex(p)
  562. }
  563. params["pinSHA256"] = strings.Join(pins, ",")
  564. }
  565. }
  566. // salamander obfs (Hysteria2). The panel-side link generator already
  567. // emits these; keep the subscription output in sync so a client has
  568. // the obfs password to match the server.
  569. if finalmask, ok := stream["finalmask"].(map[string]any); ok {
  570. applyFinalMaskParams(finalmask, params)
  571. if udpMasks, ok := finalmask["udp"].([]any); ok {
  572. for _, m := range udpMasks {
  573. mask, _ := m.(map[string]any)
  574. if mask == nil || mask["type"] != "salamander" {
  575. continue
  576. }
  577. settings, _ := mask["settings"].(map[string]any)
  578. if pw, ok := settings["password"].(string); ok && pw != "" {
  579. params["obfs"] = "salamander"
  580. params["obfs-password"] = pw
  581. break
  582. }
  583. }
  584. }
  585. }
  586. var settings map[string]any
  587. json.Unmarshal([]byte(inbound.Settings), &settings)
  588. version, _ := settings["version"].(float64)
  589. protocol := "hysteria2"
  590. if int(version) == 1 {
  591. protocol = "hysteria"
  592. }
  593. // Fan out one link per External Proxy entry if any. Previously this
  594. // generator ignored `externalProxy` entirely, so the link kept the
  595. // server's own IP/port even when the admin configured an alternate
  596. // endpoint (e.g. a CDN hostname + port that forwards to the node).
  597. // Matches the behaviour of genVlessLink / genTrojanLink / ….
  598. externalProxies, _ := stream["externalProxy"].([]any)
  599. if len(externalProxies) > 0 {
  600. links := make([]string, 0, len(externalProxies))
  601. for _, externalProxy := range externalProxies {
  602. ep, ok := externalProxy.(map[string]any)
  603. if !ok {
  604. continue
  605. }
  606. dest, _ := ep["dest"].(string)
  607. portF, okPort := ep["port"].(float64)
  608. if dest == "" || !okPort {
  609. continue
  610. }
  611. epRemark, _ := ep["remark"].(string)
  612. epParams := cloneStringMap(params)
  613. applyExternalProxyHysteriaParams(ep, epParams)
  614. link := fmt.Sprintf("%s://%s@%s:%d", protocol, auth, dest, int(portF))
  615. links = append(links, buildLinkWithParams(link, epParams, s.genRemark(inbound, email, epRemark)))
  616. }
  617. return strings.Join(links, "\n")
  618. }
  619. // No external proxy configured — use the inbound's resolved address so
  620. // node-managed inbounds get the node's host instead of the central panel's.
  621. if hopPorts := hysteriaHopPorts(stream); hopPorts != "" {
  622. params["mport"] = hopPorts
  623. }
  624. link := fmt.Sprintf("%s://%s@%s:%d", protocol, auth, s.resolveInboundAddress(inbound), inbound.Port)
  625. return buildLinkWithParams(link, params, s.genRemark(inbound, email, ""))
  626. }
  627. // hysteriaHopPorts returns the configured Hysteria2 UDP port-hopping range
  628. // (finalmask.quicParams.udpHop.ports), or "" when port hopping is off. The
  629. // range is emitted as the v2rayN-compatible `mport` query param; the URL port
  630. // field stays numeric so .NET-Uri-based importers (v2rayN) can parse the link.
  631. func hysteriaHopPorts(stream map[string]any) string {
  632. finalmask, _ := stream["finalmask"].(map[string]any)
  633. quicParams, _ := finalmask["quicParams"].(map[string]any)
  634. udpHop, _ := quicParams["udpHop"].(map[string]any)
  635. ports, _ := udpHop["ports"].(string)
  636. return strings.TrimSpace(ports)
  637. }
  638. // loadNodes refreshes nodesByID from the DB. Called once per request so
  639. // the per-inbound resolveInboundAddress lookups are pure map reads.
  640. // We filter to address != ” so a half-configured node row doesn't
  641. // accidentally produce a useless host like "https://:2053".
  642. func (s *SubService) loadNodes() {
  643. db := database.GetDB()
  644. var nodes []*model.Node
  645. if err := db.Model(&model.Node{}).Where("address != ''").Find(&nodes).Error; err != nil {
  646. logger.Warning("subscription: load nodes failed:", err)
  647. s.nodesByID = nil
  648. return
  649. }
  650. m := make(map[int]*model.Node, len(nodes))
  651. for _, n := range nodes {
  652. m[n.Id] = n
  653. }
  654. s.nodesByID = m
  655. }
  656. // resolveInboundAddress picks the host an external client should connect to:
  657. // 1. node-managed inbound -> the node's address
  658. // 2. an explicit, client-reachable bind Listen -> that Listen
  659. // 3. otherwise the subscriber's request host (s.address)
  660. // A loopback/wildcard bind or a unix-domain-socket listen is a server-side
  661. // detail and is never advertised; External Proxy remains the way to advertise
  662. // an arbitrary endpoint. Mirrors the frontend's resolveAddr so the panel QR and
  663. // the subscription agree.
  664. func (s *SubService) resolveInboundAddress(inbound *model.Inbound) string {
  665. if inbound.NodeID != nil && s.nodesByID != nil {
  666. if n, ok := s.nodesByID[*inbound.NodeID]; ok && n.Address != "" {
  667. return n.Address
  668. }
  669. }
  670. if listen := inbound.Listen; listen != "" && listen[0] != '@' && listen[0] != '/' && isRoutableHost(listen) {
  671. return listen
  672. }
  673. return s.address
  674. }
  675. func findClientIndex(clients []model.Client, email string) int {
  676. for i, client := range clients {
  677. if client.Email == email {
  678. return i
  679. }
  680. }
  681. return -1
  682. }
  683. func unmarshalStreamSettings(streamSettings string) map[string]any {
  684. var stream map[string]any
  685. json.Unmarshal([]byte(streamSettings), &stream)
  686. return stream
  687. }
  688. func applyPathAndHostParams(settings map[string]any, params map[string]string) {
  689. params["path"] = settings["path"].(string)
  690. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  691. params["host"] = host
  692. } else {
  693. headers, _ := settings["headers"].(map[string]any)
  694. params["host"] = searchHost(headers)
  695. }
  696. }
  697. func applyPathAndHostObj(settings map[string]any, obj map[string]any) {
  698. obj["path"] = settings["path"].(string)
  699. if host, ok := settings["host"].(string); ok && len(host) > 0 {
  700. obj["host"] = host
  701. } else {
  702. headers, _ := settings["headers"].(map[string]any)
  703. obj["host"] = searchHost(headers)
  704. }
  705. }
  706. func applyShareNetworkParams(stream map[string]any, streamNetwork string, params map[string]string) {
  707. switch streamNetwork {
  708. case "tcp":
  709. tcp, _ := stream["tcpSettings"].(map[string]any)
  710. header, _ := tcp["header"].(map[string]any)
  711. typeStr, _ := header["type"].(string)
  712. if typeStr == "http" {
  713. request := header["request"].(map[string]any)
  714. requestPath, _ := request["path"].([]any)
  715. params["path"] = requestPath[0].(string)
  716. host := ""
  717. if response, ok := header["response"].(map[string]any); ok {
  718. if respHeaders, ok := response["headers"].(map[string]any); ok {
  719. host = searchHost(respHeaders)
  720. }
  721. }
  722. if host == "" {
  723. headers, _ := request["headers"].(map[string]any)
  724. host = searchHost(headers)
  725. }
  726. params["host"] = host
  727. params["headerType"] = "http"
  728. }
  729. case "kcp":
  730. applyKcpShareParams(stream, params)
  731. case "ws":
  732. ws, _ := stream["wsSettings"].(map[string]any)
  733. applyPathAndHostParams(ws, params)
  734. case "grpc":
  735. grpc, _ := stream["grpcSettings"].(map[string]any)
  736. params["serviceName"] = grpc["serviceName"].(string)
  737. params["authority"], _ = grpc["authority"].(string)
  738. if grpc["multiMode"].(bool) {
  739. params["mode"] = "multi"
  740. }
  741. case "httpupgrade":
  742. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  743. applyPathAndHostParams(httpupgrade, params)
  744. case "xhttp":
  745. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  746. applyXhttpExtraParams(xhttp, params)
  747. }
  748. }
  749. // applyXhttpExtraObj copies the bidirectional xhttp settings into the
  750. // VMess base64 JSON link object. VMess supports arbitrary keys, so we
  751. // flatten the SplitHTTPConfig "extra" fields directly onto obj.
  752. func applyXhttpExtraObj(xhttp map[string]any, obj map[string]any) {
  753. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  754. obj["x_padding_bytes"] = xpb
  755. }
  756. maps.Copy(obj, buildXhttpExtra(xhttp))
  757. }
  758. func applyVmessNetworkParams(stream map[string]any, network string, obj map[string]any) {
  759. obj["net"] = network
  760. switch network {
  761. case "tcp":
  762. tcp, _ := stream["tcpSettings"].(map[string]any)
  763. header, _ := tcp["header"].(map[string]any)
  764. typeStr, _ := header["type"].(string)
  765. obj["type"] = typeStr
  766. if typeStr == "http" {
  767. request := header["request"].(map[string]any)
  768. requestPath, _ := request["path"].([]any)
  769. obj["path"] = requestPath[0].(string)
  770. host := ""
  771. if response, ok := header["response"].(map[string]any); ok {
  772. if respHeaders, ok := response["headers"].(map[string]any); ok {
  773. host = searchHost(respHeaders)
  774. }
  775. }
  776. if host == "" {
  777. headers, _ := request["headers"].(map[string]any)
  778. host = searchHost(headers)
  779. }
  780. obj["host"] = host
  781. }
  782. case "kcp":
  783. applyKcpShareObj(stream, obj)
  784. case "ws":
  785. ws, _ := stream["wsSettings"].(map[string]any)
  786. applyPathAndHostObj(ws, obj)
  787. case "grpc":
  788. grpc, _ := stream["grpcSettings"].(map[string]any)
  789. obj["path"] = grpc["serviceName"].(string)
  790. obj["authority"] = grpc["authority"].(string)
  791. if grpc["multiMode"].(bool) {
  792. obj["type"] = "multi"
  793. }
  794. case "httpupgrade":
  795. httpupgrade, _ := stream["httpupgradeSettings"].(map[string]any)
  796. applyPathAndHostObj(httpupgrade, obj)
  797. case "xhttp":
  798. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  799. applyPathAndHostObj(xhttp, obj)
  800. if mode, ok := xhttp["mode"].(string); ok {
  801. obj["mode"] = mode
  802. }
  803. applyXhttpExtraObj(xhttp, obj)
  804. }
  805. }
  806. func applyShareTLSParams(stream map[string]any, params map[string]string) {
  807. params["security"] = "tls"
  808. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  809. alpns, _ := tlsSetting["alpn"].([]any)
  810. var alpn []string
  811. for _, a := range alpns {
  812. alpn = append(alpn, a.(string))
  813. }
  814. if len(alpn) > 0 {
  815. params["alpn"] = strings.Join(alpn, ",")
  816. }
  817. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  818. params["sni"], _ = sniValue.(string)
  819. }
  820. tlsSettings, _ := searchKey(tlsSetting, "settings")
  821. if tlsSetting != nil {
  822. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  823. params["fp"], _ = fpValue.(string)
  824. }
  825. if echValue, ok := searchKey(tlsSettings, "echConfigList"); ok {
  826. if ech, _ := echValue.(string); ech != "" {
  827. params["ech"] = ech
  828. }
  829. }
  830. if pins, ok := pinnedSha256List(tlsSettings); ok {
  831. params["pcs"] = strings.Join(pins, ",")
  832. }
  833. }
  834. }
  835. func applyVmessTLSParams(stream map[string]any, obj map[string]any) {
  836. tlsSetting, _ := stream["tlsSettings"].(map[string]any)
  837. alpns, _ := tlsSetting["alpn"].([]any)
  838. if len(alpns) > 0 {
  839. var alpn []string
  840. for _, a := range alpns {
  841. alpn = append(alpn, a.(string))
  842. }
  843. obj["alpn"] = strings.Join(alpn, ",")
  844. }
  845. if sniValue, ok := searchKey(tlsSetting, "serverName"); ok {
  846. obj["sni"], _ = sniValue.(string)
  847. }
  848. tlsSettings, _ := searchKey(tlsSetting, "settings")
  849. if tlsSetting != nil {
  850. if fpValue, ok := searchKey(tlsSettings, "fingerprint"); ok {
  851. obj["fp"], _ = fpValue.(string)
  852. }
  853. if echValue, ok := searchKey(tlsSettings, "echConfigList"); ok {
  854. if ech, _ := echValue.(string); ech != "" {
  855. obj["ech"] = ech
  856. }
  857. }
  858. if pins, ok := pinnedSha256List(tlsSettings); ok {
  859. obj["pcs"] = strings.Join(pins, ",")
  860. }
  861. }
  862. }
  863. // pinnedSha256List extracts tlsSettings.settings.pinnedPeerCertSha256 as a
  864. // []string. The field is panel-only (stripped before the run-config reaches
  865. // xray-core via web/service/xray.go) but flows into share links so clients
  866. // can pin the server's certificate hash.
  867. func pinnedSha256List(tlsClientSettings any) ([]string, bool) {
  868. raw, ok := searchKey(tlsClientSettings, "pinnedPeerCertSha256")
  869. if !ok {
  870. return nil, false
  871. }
  872. arr, ok := raw.([]any)
  873. if !ok || len(arr) == 0 {
  874. return nil, false
  875. }
  876. out := make([]string, 0, len(arr))
  877. for _, v := range arr {
  878. s, ok := v.(string)
  879. if !ok || s == "" {
  880. continue
  881. }
  882. out = append(out, s)
  883. }
  884. if len(out) == 0 {
  885. return nil, false
  886. }
  887. return out, true
  888. }
  889. // hysteriaPinHex normalises a pinnedPeerCertSha256 entry into the 64-character
  890. // lowercase hex form that Xray-core's Hysteria2 pinSHA256 parser requires.
  891. //
  892. // The panel stores pins in several shapes: base64 (xray-core's native TLS
  893. // format, used by the generate button and the JSON subscription) and hex —
  894. // either bare or colon-separated as `openssl x509 -fingerprint -sha256` emits
  895. // it. Hysteria2 clients hex-decode pinSHA256 and crash on a base64 value, so
  896. // each entry is coerced to bare hex here. Anything that is neither a 32-byte
  897. // hex nor a 32-byte base64 SHA-256 is returned unchanged so unexpected data is
  898. // not silently dropped. Mirrors decodeCertPin in web/service/node.go.
  899. func hysteriaPinHex(pin string) string {
  900. pin = strings.TrimSpace(pin)
  901. if h := strings.ReplaceAll(pin, ":", ""); len(h) == hex.EncodedLen(sha256.Size) {
  902. if _, err := hex.DecodeString(h); err == nil {
  903. return strings.ToLower(h)
  904. }
  905. }
  906. for _, enc := range []*base64.Encoding{
  907. base64.StdEncoding,
  908. base64.RawStdEncoding,
  909. base64.URLEncoding,
  910. base64.RawURLEncoding,
  911. } {
  912. if b, err := enc.DecodeString(pin); err == nil && len(b) == sha256.Size {
  913. return hex.EncodeToString(b)
  914. }
  915. }
  916. return pin
  917. }
  918. func applyShareRealityParams(stream map[string]any, params map[string]string) {
  919. params["security"] = "reality"
  920. realitySetting, _ := stream["realitySettings"].(map[string]any)
  921. realitySettings, _ := searchKey(realitySetting, "settings")
  922. if realitySetting != nil {
  923. if sniValue, ok := searchKey(realitySetting, "serverNames"); ok {
  924. sNames, _ := sniValue.([]any)
  925. params["sni"] = sNames[random.Num(len(sNames))].(string)
  926. }
  927. if pbkValue, ok := searchKey(realitySettings, "publicKey"); ok {
  928. params["pbk"], _ = pbkValue.(string)
  929. }
  930. if sidValue, ok := searchKey(realitySetting, "shortIds"); ok {
  931. shortIds, _ := sidValue.([]any)
  932. params["sid"] = shortIds[random.Num(len(shortIds))].(string)
  933. }
  934. if fpValue, ok := searchKey(realitySettings, "fingerprint"); ok {
  935. if fp, ok := fpValue.(string); ok && len(fp) > 0 {
  936. params["fp"] = fp
  937. }
  938. }
  939. if pqvValue, ok := searchKey(realitySettings, "mldsa65Verify"); ok {
  940. if pqv, ok := pqvValue.(string); ok && len(pqv) > 0 {
  941. params["pqv"] = pqv
  942. }
  943. }
  944. params["spx"] = "/" + random.Seq(15)
  945. }
  946. }
  947. func buildVmessLink(obj map[string]any) string {
  948. jsonStr, _ := json.MarshalIndent(obj, "", " ")
  949. return "vmess://" + base64.StdEncoding.EncodeToString(jsonStr)
  950. }
  951. func cloneVmessShareObj(baseObj map[string]any, newSecurity string) map[string]any {
  952. newObj := map[string]any{}
  953. for key, value := range baseObj {
  954. if !(newSecurity == "none" && (key == "alpn" || key == "sni" || key == "fp" || key == "pcs")) {
  955. newObj[key] = value
  956. }
  957. }
  958. return newObj
  959. }
  960. func applyExternalProxyTLSObj(ep map[string]any, obj map[string]any, security string) {
  961. if security != "tls" {
  962. return
  963. }
  964. if sni, ok := externalProxySNI(ep); ok {
  965. obj["sni"] = sni
  966. }
  967. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  968. obj["fp"] = fp
  969. }
  970. if alpn, ok := externalProxyALPN(ep["alpn"]); ok {
  971. obj["alpn"] = alpn
  972. }
  973. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  974. obj["pcs"] = joinAnyStrings(pins)
  975. }
  976. }
  977. func applyExternalProxyTLSParams(ep map[string]any, params map[string]string, security string) {
  978. if security != "tls" {
  979. return
  980. }
  981. if sni, ok := externalProxySNI(ep); ok {
  982. params["sni"] = sni
  983. }
  984. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  985. params["fp"] = fp
  986. }
  987. if alpn, ok := externalProxyALPN(ep["alpn"]); ok {
  988. params["alpn"] = alpn
  989. }
  990. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  991. params["pcs"] = joinAnyStrings(pins)
  992. }
  993. }
  994. // applyExternalProxyHysteriaParams overrides the cert pin for a single
  995. // external-proxy entry on a Hysteria link. Hysteria carries the pin as a hex
  996. // `pinSHA256` (not the `pcs` the URL-param protocols use), so each entry is
  997. // coerced through hysteriaPinHex like the main pin. sni/fp/alpn are left as
  998. // the inbound's own — Hysteria external proxies are typically alternate
  999. // endpoints (port-hop / CDN) fronting the same certificate.
  1000. func applyExternalProxyHysteriaParams(ep map[string]any, params map[string]string) {
  1001. pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"])
  1002. if !ok {
  1003. return
  1004. }
  1005. hexPins := make([]string, 0, len(pins))
  1006. for _, p := range pins {
  1007. if s, ok := p.(string); ok {
  1008. hexPins = append(hexPins, hysteriaPinHex(s))
  1009. }
  1010. }
  1011. params["pinSHA256"] = strings.Join(hexPins, ",")
  1012. }
  1013. // cloneStreamForExternalProxy returns a shallow clone of stream with
  1014. // tlsSettings (and its nested settings map) deep-copied. The external
  1015. // proxy loop mutates tlsSettings per iteration, so without isolating
  1016. // those maps each proxy's SNI/fingerprint/ALPN would leak into the next.
  1017. func cloneStreamForExternalProxy(stream map[string]any) map[string]any {
  1018. out := cloneMap(stream)
  1019. ts, ok := out["tlsSettings"].(map[string]any)
  1020. if !ok || ts == nil {
  1021. return out
  1022. }
  1023. clonedTs := cloneMap(ts)
  1024. if inner, ok := clonedTs["settings"].(map[string]any); ok && inner != nil {
  1025. clonedTs["settings"] = cloneMap(inner)
  1026. }
  1027. out["tlsSettings"] = clonedTs
  1028. return out
  1029. }
  1030. func applyExternalProxyTLSToStream(ep map[string]any, stream map[string]any, security string) {
  1031. if security != "tls" {
  1032. return
  1033. }
  1034. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  1035. if tlsSettings == nil {
  1036. tlsSettings = map[string]any{}
  1037. stream["tlsSettings"] = tlsSettings
  1038. }
  1039. if sni, ok := externalProxySNI(ep); ok {
  1040. tlsSettings["serverName"] = sni
  1041. }
  1042. if fp, ok := ep["fingerprint"].(string); ok && fp != "" {
  1043. tlsSettings["fingerprint"] = fp
  1044. settings, _ := tlsSettings["settings"].(map[string]any)
  1045. if settings == nil {
  1046. settings = map[string]any{}
  1047. tlsSettings["settings"] = settings
  1048. }
  1049. settings["fingerprint"] = fp
  1050. }
  1051. if alpn, ok := externalProxyALPNList(ep["alpn"]); ok {
  1052. tlsSettings["alpn"] = alpn
  1053. }
  1054. if pins, ok := externalProxyPins(ep["pinnedPeerCertSha256"]); ok {
  1055. settings, _ := tlsSettings["settings"].(map[string]any)
  1056. if settings == nil {
  1057. settings = map[string]any{}
  1058. tlsSettings["settings"] = settings
  1059. }
  1060. settings["pinnedPeerCertSha256"] = pins
  1061. }
  1062. }
  1063. func externalProxySNI(ep map[string]any) (string, bool) {
  1064. if sni, ok := ep["sni"].(string); ok && sni != "" {
  1065. return sni, true
  1066. }
  1067. return "", false
  1068. }
  1069. func externalProxyALPN(value any) (string, bool) {
  1070. switch v := value.(type) {
  1071. case string:
  1072. return v, v != ""
  1073. case []string:
  1074. if len(v) == 0 {
  1075. return "", false
  1076. }
  1077. return strings.Join(v, ","), true
  1078. case []any:
  1079. alpn := make([]string, 0, len(v))
  1080. for _, item := range v {
  1081. if s, ok := item.(string); ok && s != "" {
  1082. alpn = append(alpn, s)
  1083. }
  1084. }
  1085. if len(alpn) == 0 {
  1086. return "", false
  1087. }
  1088. return strings.Join(alpn, ","), true
  1089. default:
  1090. return "", false
  1091. }
  1092. }
  1093. func externalProxyALPNList(value any) ([]any, bool) {
  1094. switch v := value.(type) {
  1095. case string:
  1096. if v == "" {
  1097. return nil, false
  1098. }
  1099. parts := strings.Split(v, ",")
  1100. out := make([]any, 0, len(parts))
  1101. for _, part := range parts {
  1102. if part = strings.TrimSpace(part); part != "" {
  1103. out = append(out, part)
  1104. }
  1105. }
  1106. return out, len(out) > 0
  1107. case []string:
  1108. out := make([]any, 0, len(v))
  1109. for _, item := range v {
  1110. if item != "" {
  1111. out = append(out, item)
  1112. }
  1113. }
  1114. return out, len(out) > 0
  1115. case []any:
  1116. out := make([]any, 0, len(v))
  1117. for _, item := range v {
  1118. if s, ok := item.(string); ok && s != "" {
  1119. out = append(out, s)
  1120. }
  1121. }
  1122. return out, len(out) > 0
  1123. default:
  1124. return nil, false
  1125. }
  1126. }
  1127. // externalProxyPins extracts an external-proxy entry's pinnedPeerCertSha256
  1128. // as a []any of non-empty strings. The []any element type matches what the
  1129. // JSON/Clash sub builders expect when reading the value back off the cloned
  1130. // stream's tlsSettings.settings.
  1131. func externalProxyPins(value any) ([]any, bool) {
  1132. switch v := value.(type) {
  1133. case []string:
  1134. out := make([]any, 0, len(v))
  1135. for _, item := range v {
  1136. if item != "" {
  1137. out = append(out, item)
  1138. }
  1139. }
  1140. return out, len(out) > 0
  1141. case []any:
  1142. out := make([]any, 0, len(v))
  1143. for _, item := range v {
  1144. if s, ok := item.(string); ok && s != "" {
  1145. out = append(out, s)
  1146. }
  1147. }
  1148. return out, len(out) > 0
  1149. default:
  1150. return nil, false
  1151. }
  1152. }
  1153. func joinAnyStrings(items []any) string {
  1154. parts := make([]string, 0, len(items))
  1155. for _, item := range items {
  1156. if s, ok := item.(string); ok {
  1157. parts = append(parts, s)
  1158. }
  1159. }
  1160. return strings.Join(parts, ",")
  1161. }
  1162. func (s *SubService) buildVmessExternalProxyLinks(externalProxies []any, baseObj map[string]any, inbound *model.Inbound, email string) string {
  1163. var links strings.Builder
  1164. for index, externalProxy := range externalProxies {
  1165. ep, _ := externalProxy.(map[string]any)
  1166. newSecurity, _ := ep["forceTls"].(string)
  1167. securityToApply := baseObj["tls"].(string)
  1168. if newSecurity != "same" {
  1169. securityToApply = newSecurity
  1170. }
  1171. newObj := cloneVmessShareObj(baseObj, newSecurity)
  1172. newObj["ps"] = s.genRemark(inbound, email, ep["remark"].(string))
  1173. newObj["add"] = ep["dest"].(string)
  1174. newObj["port"] = int(ep["port"].(float64))
  1175. if newSecurity != "same" {
  1176. newObj["tls"] = newSecurity
  1177. }
  1178. applyExternalProxyTLSObj(ep, newObj, securityToApply)
  1179. if index > 0 {
  1180. links.WriteString("\n")
  1181. }
  1182. links.WriteString(buildVmessLink(newObj))
  1183. }
  1184. return links.String()
  1185. }
  1186. // buildLinkWithParams appends ?query and #fragment to a pre-built
  1187. // scheme://userinfo@host:port string without re-parsing it. The caller
  1188. // has already escaped userinfo via encodeUserinfo (or chosen a base64
  1189. // alphabet with no reserved chars); a url.Parse + .String() round-trip
  1190. // would silently decode that escaping because Go's userinfo emitter
  1191. // leaves sub-delims (=, +, ;) literal, which breaks Trojan/Hysteria/SS
  1192. // clients that reject those chars in the password.
  1193. func buildLinkWithParams(link string, params map[string]string, fragment string) string {
  1194. return appendQueryAndFragment(link, params, fragment, "", false)
  1195. }
  1196. // buildLinkWithParamsAndSecurity is buildLinkWithParams plus an
  1197. // external-proxy override: the `security` key in params is replaced with
  1198. // the supplied value, and TLS hint fields (alpn/sni/fp/pcs) are stripped
  1199. // when the override is `none`.
  1200. func buildLinkWithParamsAndSecurity(link string, params map[string]string, fragment, security string, omitTLSFields bool) string {
  1201. return appendQueryAndFragment(link, params, fragment, security, omitTLSFields)
  1202. }
  1203. func appendQueryAndFragment(link string, params map[string]string, fragment, securityOverride string, omitTLSFields bool) string {
  1204. var sb strings.Builder
  1205. sb.WriteString(link)
  1206. if len(params) > 0 {
  1207. q := url.Values{}
  1208. for k, v := range params {
  1209. if securityOverride != "" && k == "security" {
  1210. v = securityOverride
  1211. }
  1212. if omitTLSFields && (k == "alpn" || k == "sni" || k == "fp" || k == "pcs") {
  1213. continue
  1214. }
  1215. q.Set(k, v)
  1216. }
  1217. encoded := q.Encode()
  1218. if encoded != "" {
  1219. if strings.Contains(link, "?") {
  1220. sb.WriteByte('&')
  1221. } else {
  1222. sb.WriteByte('?')
  1223. }
  1224. sb.WriteString(encoded)
  1225. }
  1226. }
  1227. if fragment != "" {
  1228. sb.WriteByte('#')
  1229. // Match the frontend's encodeURIComponent(remark): spaces become
  1230. // %20 (not + as in query strings).
  1231. sb.WriteString(strings.ReplaceAll(url.QueryEscape(fragment), "+", "%20"))
  1232. }
  1233. return sb.String()
  1234. }
  1235. func (s *SubService) buildExternalProxyURLLinks(
  1236. externalProxies []any,
  1237. params map[string]string,
  1238. baseSecurity string,
  1239. makeLink func(dest string, port int) string,
  1240. makeRemark func(ep map[string]any) string,
  1241. ) string {
  1242. links := make([]string, 0, len(externalProxies))
  1243. for _, externalProxy := range externalProxies {
  1244. ep, _ := externalProxy.(map[string]any)
  1245. newSecurity, _ := ep["forceTls"].(string)
  1246. dest, _ := ep["dest"].(string)
  1247. port := int(ep["port"].(float64))
  1248. securityToApply := baseSecurity
  1249. if newSecurity != "same" {
  1250. securityToApply = newSecurity
  1251. }
  1252. nextParams := cloneStringMap(params)
  1253. applyExternalProxyTLSParams(ep, nextParams, securityToApply)
  1254. links = append(
  1255. links,
  1256. buildLinkWithParamsAndSecurity(
  1257. makeLink(dest, port),
  1258. nextParams,
  1259. makeRemark(ep),
  1260. securityToApply,
  1261. newSecurity == "none",
  1262. ),
  1263. )
  1264. }
  1265. return strings.Join(links, "\n")
  1266. }
  1267. func cloneStringMap(source map[string]string) map[string]string {
  1268. cloned := make(map[string]string, len(source))
  1269. maps.Copy(cloned, source)
  1270. return cloned
  1271. }
  1272. func (s *SubService) genRemark(inbound *model.Inbound, email string, extra string) string {
  1273. separationChar := string(s.remarkModel[0])
  1274. orderChars := s.remarkModel[1:]
  1275. orders := map[byte]string{
  1276. 'i': "",
  1277. 'e': "",
  1278. 'o': "",
  1279. }
  1280. if len(email) > 0 && s.emailInRemark {
  1281. orders['e'] = email
  1282. }
  1283. if len(inbound.Remark) > 0 {
  1284. orders['i'] = inbound.Remark
  1285. }
  1286. if len(extra) > 0 {
  1287. orders['o'] = extra
  1288. }
  1289. var remark []string
  1290. for i := 0; i < len(orderChars); i++ {
  1291. char := orderChars[i]
  1292. order, exists := orders[char]
  1293. if exists && order != "" {
  1294. remark = append(remark, order)
  1295. }
  1296. }
  1297. if s.showInfo {
  1298. statsExist := false
  1299. var stats xray.ClientTraffic
  1300. for _, clientStat := range inbound.ClientStats {
  1301. if clientStat.Email == email {
  1302. stats = clientStat
  1303. statsExist = true
  1304. break
  1305. }
  1306. }
  1307. // Get remained days
  1308. if statsExist {
  1309. if !stats.Enable {
  1310. return fmt.Sprintf("⛔️N/A%s%s", separationChar, strings.Join(remark, separationChar))
  1311. }
  1312. if vol := stats.Total - (stats.Up + stats.Down); vol > 0 {
  1313. remark = append(remark, fmt.Sprintf("%s%s", common.FormatTraffic(vol), "📊"))
  1314. }
  1315. now := time.Now().Unix()
  1316. switch exp := stats.ExpiryTime / 1000; {
  1317. case exp > 0:
  1318. remainingSeconds := exp - now
  1319. days := remainingSeconds / 86400
  1320. hours := (remainingSeconds % 86400) / 3600
  1321. minutes := (remainingSeconds % 3600) / 60
  1322. if days > 0 {
  1323. if hours > 0 {
  1324. remark = append(remark, fmt.Sprintf("%dD,%dH⏳", days, hours))
  1325. } else {
  1326. remark = append(remark, fmt.Sprintf("%dD⏳", days))
  1327. }
  1328. } else if hours > 0 {
  1329. remark = append(remark, fmt.Sprintf("%dH⏳", hours))
  1330. } else {
  1331. remark = append(remark, fmt.Sprintf("%dM⏳", minutes))
  1332. }
  1333. case exp < 0:
  1334. days := exp / -86400
  1335. hours := (exp % -86400) / 3600
  1336. minutes := (exp % -3600) / 60
  1337. if days > 0 {
  1338. if hours > 0 {
  1339. remark = append(remark, fmt.Sprintf("%dD,%dH⏳", days, hours))
  1340. } else {
  1341. remark = append(remark, fmt.Sprintf("%dD⏳", days))
  1342. }
  1343. } else if hours > 0 {
  1344. remark = append(remark, fmt.Sprintf("%dH⏳", hours))
  1345. } else {
  1346. remark = append(remark, fmt.Sprintf("%dM⏳", minutes))
  1347. }
  1348. }
  1349. }
  1350. }
  1351. return strings.Join(remark, separationChar)
  1352. }
  1353. func searchKey(data any, key string) (any, bool) {
  1354. switch val := data.(type) {
  1355. case map[string]any:
  1356. for k, v := range val {
  1357. if k == key {
  1358. return v, true
  1359. }
  1360. if result, ok := searchKey(v, key); ok {
  1361. return result, true
  1362. }
  1363. }
  1364. case []any:
  1365. for _, v := range val {
  1366. if result, ok := searchKey(v, key); ok {
  1367. return result, true
  1368. }
  1369. }
  1370. }
  1371. return nil, false
  1372. }
  1373. // buildXhttpExtra walks an xhttpSettings map and returns the JSON blob
  1374. // that goes into the URL's `extra` param (or, for VMess, the link
  1375. // object). Carries ONLY the bidirectional fields from xray-core's
  1376. // SplitHTTPConfig — i.e. the ones the server enforces and the client
  1377. // must match. Strictly one-sided fields are excluded:
  1378. //
  1379. // - server-only (noSSEHeader, scMaxBufferedPosts, scStreamUpServerSecs,
  1380. // serverMaxHeaderBytes) — client wouldn't read them, so emitting
  1381. // them just bloats the URL.
  1382. // - client-only values are included only when present in the inbound
  1383. // JSON. Some deployments/imported configs carry them there, and the
  1384. // subscription link is the only place clients can receive them.
  1385. //
  1386. // Truthy-only guards keep default inbounds emitting the same compact URL
  1387. // they did before this helper grew.
  1388. func buildXhttpExtra(xhttp map[string]any) map[string]any {
  1389. if xhttp == nil {
  1390. return nil
  1391. }
  1392. extra := map[string]any{}
  1393. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1394. extra["xPaddingBytes"] = xpb
  1395. }
  1396. if obfs, ok := xhttp["xPaddingObfsMode"].(bool); ok && obfs {
  1397. extra["xPaddingObfsMode"] = true
  1398. for _, field := range []string{"xPaddingKey", "xPaddingHeader", "xPaddingPlacement", "xPaddingMethod"} {
  1399. if v, ok := xhttp[field].(string); ok && len(v) > 0 {
  1400. extra[field] = v
  1401. }
  1402. }
  1403. }
  1404. stringFields := []string{
  1405. "uplinkHTTPMethod",
  1406. "sessionPlacement", "sessionKey",
  1407. "seqPlacement", "seqKey",
  1408. "uplinkDataPlacement", "uplinkDataKey",
  1409. "scMaxEachPostBytes", "scMinPostsIntervalMs",
  1410. }
  1411. for _, field := range stringFields {
  1412. if v, ok := xhttp[field].(string); ok && len(v) > 0 {
  1413. extra[field] = v
  1414. }
  1415. }
  1416. for _, field := range []string{"uplinkChunkSize"} {
  1417. if v, ok := nonZeroShareValue(xhttp[field]); ok {
  1418. extra[field] = v
  1419. }
  1420. }
  1421. for _, field := range []string{"noGRPCHeader"} {
  1422. if v, ok := xhttp[field].(bool); ok && v {
  1423. extra[field] = v
  1424. }
  1425. }
  1426. for _, field := range []string{"xmux", "downloadSettings"} {
  1427. if v, ok := nonEmptyShareObject(xhttp[field]); ok {
  1428. extra[field] = v
  1429. }
  1430. }
  1431. // Headers — emitted as the {name: value} map upstream's struct
  1432. // expects. The server runtime ignores this field, but the client
  1433. // (consuming the share link) honors it. Drop any "host" entry —
  1434. // host already wins as a top-level URL param.
  1435. if rawHeaders, ok := xhttp["headers"].(map[string]any); ok && len(rawHeaders) > 0 {
  1436. out := map[string]any{}
  1437. for k, v := range rawHeaders {
  1438. if strings.EqualFold(k, "host") {
  1439. continue
  1440. }
  1441. out[k] = v
  1442. }
  1443. if len(out) > 0 {
  1444. extra["headers"] = out
  1445. }
  1446. }
  1447. if len(extra) == 0 {
  1448. return nil
  1449. }
  1450. return extra
  1451. }
  1452. func nonZeroShareValue(v any) (any, bool) {
  1453. switch value := v.(type) {
  1454. case string:
  1455. return value, value != ""
  1456. case int:
  1457. return value, value != 0
  1458. case int32:
  1459. return value, value != 0
  1460. case int64:
  1461. return value, value != 0
  1462. case float32:
  1463. return value, value != 0
  1464. case float64:
  1465. return value, value != 0
  1466. default:
  1467. return nil, false
  1468. }
  1469. }
  1470. func nonEmptyShareObject(v any) (any, bool) {
  1471. switch value := v.(type) {
  1472. case map[string]any:
  1473. return value, len(value) > 0
  1474. case map[string]string:
  1475. return value, len(value) > 0
  1476. case []any:
  1477. return value, len(value) > 0
  1478. default:
  1479. return nil, false
  1480. }
  1481. }
  1482. // applyXhttpExtraParams emits the full xhttp config into the URL query
  1483. // params of a vless:// / trojan:// / ss:// link. Sets path/host/mode at
  1484. // top level (xray's Build() always lets these win over `extra`) and packs
  1485. // everything else into a JSON `extra` param. Also writes the flat
  1486. // `x_padding_bytes` param sing-box-family clients understand.
  1487. //
  1488. // Without this, the admin's custom xPaddingBytes / sessionKey / etc. never
  1489. // reach the client and handshakes are silently rejected with
  1490. // `invalid padding (...) length: 0` — the client-visible symptom is
  1491. // "xhttp doesn't connect" on OpenWRT / sing-box.
  1492. //
  1493. // Two encodings are written so every popular client can read at least one:
  1494. //
  1495. // - x_padding_bytes=<range> — flat param, understood by sing-box and its
  1496. // derivatives (Podkop, OpenWRT sing-box, Karing, NekoBox, …).
  1497. // - extra=<url-encoded-json> — full xhttp settings blob, which is how
  1498. // xray-core clients (v2rayNG, Happ, Furious, Exclave, …) pick up the
  1499. // bidirectional fields beyond path/host/mode.
  1500. func applyXhttpExtraParams(xhttp map[string]any, params map[string]string) {
  1501. if xhttp == nil {
  1502. return
  1503. }
  1504. applyPathAndHostParams(xhttp, params)
  1505. if mode, ok := xhttp["mode"].(string); ok {
  1506. params["mode"] = mode
  1507. }
  1508. if xpb, ok := xhttp["xPaddingBytes"].(string); ok && len(xpb) > 0 {
  1509. params["x_padding_bytes"] = xpb
  1510. }
  1511. extra := buildXhttpExtra(xhttp)
  1512. if extra != nil {
  1513. if b, err := json.Marshal(extra); err == nil {
  1514. params["extra"] = string(b)
  1515. }
  1516. }
  1517. }
  1518. var kcpMaskToHeaderType = map[string]string{
  1519. "dns": "dns",
  1520. "dtls": "dtls",
  1521. "srtp": "srtp",
  1522. "utp": "utp",
  1523. "wechat": "wechat-video",
  1524. "wireguard": "wireguard",
  1525. }
  1526. var validFinalMaskUDPTypes = map[string]struct{}{
  1527. "salamander": {},
  1528. "mkcp-legacy": {},
  1529. "xdns": {},
  1530. "xicmp": {},
  1531. "noise": {},
  1532. "header-custom": {},
  1533. "realm": {},
  1534. }
  1535. var validFinalMaskTCPTypes = map[string]struct{}{
  1536. "header-custom": {},
  1537. "fragment": {},
  1538. "sudoku": {},
  1539. }
  1540. // applyKcpShareParams reconstructs legacy KCP share-link fields from either
  1541. // the historical kcpSettings.header/seed shape or the current finalmask model.
  1542. // This keeps subscription output compatible while avoiding panics when older
  1543. // keys are absent from modern inbounds.
  1544. func applyKcpShareParams(stream map[string]any, params map[string]string) {
  1545. extractKcpShareFields(stream).applyToParams(params)
  1546. }
  1547. func applyKcpShareObj(stream map[string]any, obj map[string]any) {
  1548. extractKcpShareFields(stream).applyToObj(obj)
  1549. }
  1550. type kcpShareFields struct {
  1551. headerType string
  1552. seed string
  1553. mtu int
  1554. tti int
  1555. }
  1556. func (f kcpShareFields) applyToParams(params map[string]string) {
  1557. if f.headerType != "" && f.headerType != "none" {
  1558. params["headerType"] = f.headerType
  1559. }
  1560. setStringParam(params, "seed", f.seed)
  1561. setIntParam(params, "mtu", f.mtu)
  1562. setIntParam(params, "tti", f.tti)
  1563. }
  1564. func (f kcpShareFields) applyToObj(obj map[string]any) {
  1565. if f.headerType != "" && f.headerType != "none" {
  1566. obj["type"] = f.headerType
  1567. }
  1568. setStringField(obj, "path", f.seed)
  1569. setIntField(obj, "mtu", f.mtu)
  1570. setIntField(obj, "tti", f.tti)
  1571. }
  1572. func extractKcpShareFields(stream map[string]any) kcpShareFields {
  1573. fields := kcpShareFields{headerType: "none"}
  1574. if kcp, ok := stream["kcpSettings"].(map[string]any); ok {
  1575. if header, ok := kcp["header"].(map[string]any); ok {
  1576. if value, ok := header["type"].(string); ok && value != "" {
  1577. fields.headerType = value
  1578. }
  1579. }
  1580. if value, ok := kcp["seed"].(string); ok && value != "" {
  1581. fields.seed = value
  1582. }
  1583. if value, ok := readPositiveInt(kcp["mtu"]); ok {
  1584. fields.mtu = value
  1585. }
  1586. if value, ok := readPositiveInt(kcp["tti"]); ok {
  1587. fields.tti = value
  1588. }
  1589. }
  1590. for _, rawMask := range normalizedFinalMaskUDPMasks(stream["finalmask"]) {
  1591. mask, _ := rawMask.(map[string]any)
  1592. if mask == nil {
  1593. continue
  1594. }
  1595. if maskType, _ := mask["type"].(string); maskType != "mkcp-legacy" {
  1596. continue
  1597. }
  1598. settings, _ := mask["settings"].(map[string]any)
  1599. header, _ := settings["header"].(string)
  1600. value, _ := settings["value"].(string)
  1601. if header == "" {
  1602. fields.seed = value
  1603. continue
  1604. }
  1605. if mapped, ok := kcpMaskToHeaderType[header]; ok {
  1606. fields.headerType = mapped
  1607. }
  1608. }
  1609. return fields
  1610. }
  1611. func readPositiveInt(value any) (int, bool) {
  1612. switch number := value.(type) {
  1613. case int:
  1614. return number, number > 0
  1615. case int32:
  1616. return int(number), number > 0
  1617. case int64:
  1618. return int(number), number > 0
  1619. case float32:
  1620. parsed := int(number)
  1621. return parsed, parsed > 0
  1622. case float64:
  1623. parsed := int(number)
  1624. return parsed, parsed > 0
  1625. default:
  1626. return 0, false
  1627. }
  1628. }
  1629. func setStringParam(params map[string]string, key, value string) {
  1630. if value == "" {
  1631. delete(params, key)
  1632. return
  1633. }
  1634. params[key] = value
  1635. }
  1636. func setIntParam(params map[string]string, key string, value int) {
  1637. if value <= 0 {
  1638. delete(params, key)
  1639. return
  1640. }
  1641. params[key] = fmt.Sprintf("%d", value)
  1642. }
  1643. func setStringField(obj map[string]any, key, value string) {
  1644. if value == "" {
  1645. delete(obj, key)
  1646. return
  1647. }
  1648. obj[key] = value
  1649. }
  1650. func setIntField(obj map[string]any, key string, value int) {
  1651. if value <= 0 {
  1652. delete(obj, key)
  1653. return
  1654. }
  1655. obj[key] = value
  1656. }
  1657. // applyFinalMaskParams exports the finalmask payload as the compact
  1658. // `fm=<json>` share-link field used by v2rayN-compatible clients.
  1659. func applyFinalMaskParams(finalmask map[string]any, params map[string]string) {
  1660. if fm, ok := marshalFinalMask(finalmask); ok {
  1661. params["fm"] = fm
  1662. }
  1663. }
  1664. func applyFinalMaskObj(finalmask map[string]any, obj map[string]any) {
  1665. if fm, ok := marshalFinalMask(finalmask); ok {
  1666. obj["fm"] = fm
  1667. }
  1668. }
  1669. func marshalFinalMask(finalmask map[string]any) (string, bool) {
  1670. normalized := normalizeFinalMask(finalmask)
  1671. if !hasFinalMaskContent(normalized) {
  1672. return "", false
  1673. }
  1674. b, err := json.Marshal(normalized)
  1675. if err != nil || len(b) == 0 || string(b) == "null" {
  1676. return "", false
  1677. }
  1678. return string(b), true
  1679. }
  1680. func normalizeFinalMask(finalmask map[string]any) map[string]any {
  1681. tcpMasks := normalizedFinalMaskTCPMasks(finalmask)
  1682. udpMasks := normalizedFinalMaskUDPMasks(finalmask)
  1683. quicParams, hasQuicParams := finalmask["quicParams"].(map[string]any)
  1684. if len(tcpMasks) == 0 && len(udpMasks) == 0 && !hasQuicParams {
  1685. return nil
  1686. }
  1687. result := map[string]any{}
  1688. if len(tcpMasks) > 0 {
  1689. result["tcp"] = tcpMasks
  1690. }
  1691. if len(udpMasks) > 0 {
  1692. result["udp"] = udpMasks
  1693. }
  1694. if hasQuicParams && len(quicParams) > 0 {
  1695. result["quicParams"] = quicParams
  1696. }
  1697. return result
  1698. }
  1699. func normalizedFinalMaskTCPMasks(value any) []any {
  1700. finalmask, _ := value.(map[string]any)
  1701. if finalmask == nil {
  1702. return nil
  1703. }
  1704. rawMasks, _ := finalmask["tcp"].([]any)
  1705. if len(rawMasks) == 0 {
  1706. return nil
  1707. }
  1708. normalized := make([]any, 0, len(rawMasks))
  1709. for _, rawMask := range rawMasks {
  1710. mask, _ := rawMask.(map[string]any)
  1711. if mask == nil {
  1712. continue
  1713. }
  1714. maskType, _ := mask["type"].(string)
  1715. if _, ok := validFinalMaskTCPTypes[maskType]; !ok || maskType == "" {
  1716. continue
  1717. }
  1718. normalizedMask := map[string]any{"type": maskType}
  1719. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  1720. normalizedMask["settings"] = settings
  1721. }
  1722. normalized = append(normalized, normalizedMask)
  1723. }
  1724. if len(normalized) == 0 {
  1725. return nil
  1726. }
  1727. return normalized
  1728. }
  1729. func normalizedFinalMaskUDPMasks(value any) []any {
  1730. finalmask, _ := value.(map[string]any)
  1731. if finalmask == nil {
  1732. return nil
  1733. }
  1734. rawMasks, _ := finalmask["udp"].([]any)
  1735. if len(rawMasks) == 0 {
  1736. return nil
  1737. }
  1738. normalized := make([]any, 0, len(rawMasks))
  1739. for _, rawMask := range rawMasks {
  1740. mask, _ := rawMask.(map[string]any)
  1741. if mask == nil {
  1742. continue
  1743. }
  1744. maskType, _ := mask["type"].(string)
  1745. if _, ok := validFinalMaskUDPTypes[maskType]; !ok || maskType == "" {
  1746. continue
  1747. }
  1748. normalizedMask := map[string]any{"type": maskType}
  1749. if settings, ok := mask["settings"].(map[string]any); ok && len(settings) > 0 {
  1750. normalizedMask["settings"] = settings
  1751. }
  1752. normalized = append(normalized, normalizedMask)
  1753. }
  1754. if len(normalized) == 0 {
  1755. return nil
  1756. }
  1757. return normalized
  1758. }
  1759. func hasFinalMaskContent(value any) bool {
  1760. switch v := value.(type) {
  1761. case nil:
  1762. return false
  1763. case string:
  1764. return len(v) > 0
  1765. case map[string]any:
  1766. for _, item := range v {
  1767. if hasFinalMaskContent(item) {
  1768. return true
  1769. }
  1770. }
  1771. return false
  1772. case []any:
  1773. return slices.ContainsFunc(v, hasFinalMaskContent)
  1774. default:
  1775. return true
  1776. }
  1777. }
  1778. func searchHost(headers any) string {
  1779. data, _ := headers.(map[string]any)
  1780. for k, v := range data {
  1781. if strings.EqualFold(k, "host") {
  1782. switch v.(type) {
  1783. case []any:
  1784. hosts, _ := v.([]any)
  1785. if len(hosts) > 0 {
  1786. return hosts[0].(string)
  1787. } else {
  1788. return ""
  1789. }
  1790. case any:
  1791. return v.(string)
  1792. }
  1793. }
  1794. }
  1795. return ""
  1796. }
  1797. // PageData is a view model for subpage.html
  1798. // PageData contains data for rendering the subscription information page.
  1799. type PageData struct {
  1800. Host string
  1801. BasePath string
  1802. SId string
  1803. Enabled bool
  1804. Download string
  1805. Upload string
  1806. Total string
  1807. Used string
  1808. Remained string
  1809. Expire int64
  1810. LastOnline int64
  1811. Datepicker string
  1812. DownloadByte int64
  1813. UploadByte int64
  1814. TotalByte int64
  1815. SubUrl string
  1816. SubJsonUrl string
  1817. SubClashUrl string
  1818. SubTitle string
  1819. SubSupportUrl string
  1820. Result []string
  1821. Emails []string
  1822. }
  1823. // ResolveRequest extracts scheme and host info from request/headers consistently.
  1824. // ResolveRequest extracts scheme, host, and header information from an HTTP request.
  1825. func (s *SubService) ResolveRequest(c *gin.Context) (scheme string, host string, hostWithPort string, hostHeader string) {
  1826. // scheme
  1827. scheme = "http"
  1828. if c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https") {
  1829. scheme = "https"
  1830. }
  1831. // base host (no port)
  1832. if h, err := getHostFromXFH(c.GetHeader("X-Forwarded-Host")); err == nil && h != "" {
  1833. host = h
  1834. }
  1835. if host == "" {
  1836. host = c.GetHeader("X-Real-IP")
  1837. }
  1838. if host == "" {
  1839. var err error
  1840. host, _, err = net.SplitHostPort(c.Request.Host)
  1841. if err != nil {
  1842. host = c.Request.Host
  1843. }
  1844. }
  1845. // host:port for URLs
  1846. hostWithPort = c.GetHeader("X-Forwarded-Host")
  1847. if hostWithPort == "" {
  1848. hostWithPort = c.Request.Host
  1849. }
  1850. if hostWithPort == "" {
  1851. hostWithPort = host
  1852. }
  1853. // header display host
  1854. hostHeader = c.GetHeader("X-Forwarded-Host")
  1855. if hostHeader == "" {
  1856. hostHeader = c.GetHeader("X-Real-IP")
  1857. }
  1858. if hostHeader == "" {
  1859. hostHeader = host
  1860. }
  1861. return
  1862. }
  1863. // BuildURLs constructs absolute subscription and JSON subscription URLs for a given subscription ID.
  1864. // It prioritizes configured URIs, then individual settings, and finally falls back to request-derived components.
  1865. func (s *SubService) BuildURLs(subPath, subJsonPath, subClashPath, subId string) (subURL, subJsonURL, subClashURL string) {
  1866. if subId == "" {
  1867. return "", "", ""
  1868. }
  1869. configuredSubURI, _ := s.settingService.GetSubURI()
  1870. configuredSubJsonURI, _ := s.settingService.GetSubJsonURI()
  1871. configuredSubClashURI, _ := s.settingService.GetSubClashURI()
  1872. // Same base as the panel's Client Information page; s.address is the
  1873. // subscriber's host already normalized away from any loopback/bind IP.
  1874. base := s.settingService.BuildSubURIBase(s.address)
  1875. subURL = s.buildSingleURL(configuredSubURI, base, subPath, subId)
  1876. subJsonURL = s.buildSingleURL(configuredSubJsonURI, base, subJsonPath, subId)
  1877. subClashURL = s.buildSingleURL(configuredSubClashURI, base, subClashPath, subId)
  1878. return subURL, subJsonURL, subClashURL
  1879. }
  1880. // buildSingleURL constructs a single URL using configured URI or base components
  1881. func (s *SubService) buildSingleURL(configuredURI, base, basePath, subId string) string {
  1882. if configuredURI != "" {
  1883. return s.joinPathWithID(configuredURI, subId)
  1884. }
  1885. return s.joinPathWithID(base+basePath, subId)
  1886. }
  1887. // joinPathWithID safely joins a base path with a subscription ID
  1888. func (s *SubService) joinPathWithID(basePath, subId string) string {
  1889. if strings.HasSuffix(basePath, "/") {
  1890. return basePath + subId
  1891. }
  1892. return basePath + "/" + subId
  1893. }
  1894. // BuildPageData parses header and prepares the template view model.
  1895. // BuildPageData constructs page data for rendering the subscription information page.
  1896. func (s *SubService) BuildPageData(subId string, hostHeader string, traffic xray.ClientTraffic, lastOnline int64, subs []string, emails []string, subURL, subJsonURL, subClashURL string, basePath string, subTitle string, subSupportUrl string) PageData {
  1897. download := common.FormatTraffic(traffic.Down)
  1898. upload := common.FormatTraffic(traffic.Up)
  1899. total := "∞"
  1900. used := common.FormatTraffic(traffic.Up + traffic.Down)
  1901. remained := ""
  1902. if traffic.Total > 0 {
  1903. total = common.FormatTraffic(traffic.Total)
  1904. left := max(traffic.Total-(traffic.Up+traffic.Down), 0)
  1905. remained = common.FormatTraffic(left)
  1906. }
  1907. datepicker := s.datepicker
  1908. if datepicker == "" {
  1909. datepicker = "gregorian"
  1910. }
  1911. return PageData{
  1912. Host: hostHeader,
  1913. BasePath: basePath,
  1914. SId: subId,
  1915. Enabled: traffic.Enable,
  1916. Download: download,
  1917. Upload: upload,
  1918. Total: total,
  1919. Used: used,
  1920. Remained: remained,
  1921. Expire: traffic.ExpiryTime / 1000,
  1922. LastOnline: lastOnline,
  1923. Datepicker: datepicker,
  1924. DownloadByte: traffic.Down,
  1925. UploadByte: traffic.Up,
  1926. TotalByte: traffic.Total,
  1927. SubUrl: subURL,
  1928. SubJsonUrl: subJsonURL,
  1929. SubClashUrl: subClashURL,
  1930. SubTitle: subTitle,
  1931. SubSupportUrl: subSupportUrl,
  1932. Result: subs,
  1933. Emails: emails,
  1934. }
  1935. }
  1936. func getHostFromXFH(s string) (string, error) {
  1937. if strings.Contains(s, ":") {
  1938. realHost, _, err := net.SplitHostPort(s)
  1939. if err != nil {
  1940. return "", err
  1941. }
  1942. return realHost, nil
  1943. }
  1944. return s, nil
  1945. }