xray.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. package conf
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strings"
  8. "github.com/xtls/xray-core/app/dispatcher"
  9. "github.com/xtls/xray-core/app/proxyman"
  10. "github.com/xtls/xray-core/app/stats"
  11. "github.com/xtls/xray-core/common/serial"
  12. core "github.com/xtls/xray-core/core"
  13. "github.com/xtls/xray-core/transport/internet"
  14. )
  15. var (
  16. inboundConfigLoader = NewJSONConfigLoader(ConfigCreatorCache{
  17. "dokodemo-door": func() interface{} { return new(DokodemoConfig) },
  18. "http": func() interface{} { return new(HTTPServerConfig) },
  19. "shadowsocks": func() interface{} { return new(ShadowsocksServerConfig) },
  20. "socks": func() interface{} { return new(SocksServerConfig) },
  21. "vless": func() interface{} { return new(VLessInboundConfig) },
  22. "vmess": func() interface{} { return new(VMessInboundConfig) },
  23. "trojan": func() interface{} { return new(TrojanServerConfig) },
  24. "mtproto": func() interface{} { return new(MTProtoServerConfig) },
  25. }, "protocol", "settings")
  26. outboundConfigLoader = NewJSONConfigLoader(ConfigCreatorCache{
  27. "blackhole": func() interface{} { return new(BlackholeConfig) },
  28. "loopback": func() interface{} { return new(LoopbackConfig) },
  29. "freedom": func() interface{} { return new(FreedomConfig) },
  30. "http": func() interface{} { return new(HTTPClientConfig) },
  31. "shadowsocks": func() interface{} { return new(ShadowsocksClientConfig) },
  32. "socks": func() interface{} { return new(SocksClientConfig) },
  33. "vless": func() interface{} { return new(VLessOutboundConfig) },
  34. "vmess": func() interface{} { return new(VMessOutboundConfig) },
  35. "trojan": func() interface{} { return new(TrojanClientConfig) },
  36. "mtproto": func() interface{} { return new(MTProtoClientConfig) },
  37. "dns": func() interface{} { return new(DNSOutboundConfig) },
  38. "wireguard": func() interface{} { return new(WireGuardConfig) },
  39. }, "protocol", "settings")
  40. ctllog = log.New(os.Stderr, "xctl> ", 0)
  41. )
  42. func toProtocolList(s []string) ([]proxyman.KnownProtocols, error) {
  43. kp := make([]proxyman.KnownProtocols, 0, 8)
  44. for _, p := range s {
  45. switch strings.ToLower(p) {
  46. case "http":
  47. kp = append(kp, proxyman.KnownProtocols_HTTP)
  48. case "https", "tls", "ssl":
  49. kp = append(kp, proxyman.KnownProtocols_TLS)
  50. default:
  51. return nil, newError("Unknown protocol: ", p)
  52. }
  53. }
  54. return kp, nil
  55. }
  56. type SniffingConfig struct {
  57. Enabled bool `json:"enabled"`
  58. DestOverride *StringList `json:"destOverride"`
  59. DomainsExcluded *StringList `json:"domainsExcluded"`
  60. MetadataOnly bool `json:"metadataOnly"`
  61. RouteOnly bool `json:"routeOnly"`
  62. }
  63. // Build implements Buildable.
  64. func (c *SniffingConfig) Build() (*proxyman.SniffingConfig, error) {
  65. var p []string
  66. if c.DestOverride != nil {
  67. for _, protocol := range *c.DestOverride {
  68. switch strings.ToLower(protocol) {
  69. case "http":
  70. p = append(p, "http")
  71. case "tls", "https", "ssl":
  72. p = append(p, "tls")
  73. case "quic":
  74. p = append(p, "quic")
  75. case "fakedns":
  76. p = append(p, "fakedns")
  77. case "fakedns+others":
  78. p = append(p, "fakedns+others")
  79. default:
  80. return nil, newError("unknown protocol: ", protocol)
  81. }
  82. }
  83. }
  84. var d []string
  85. if c.DomainsExcluded != nil {
  86. for _, domain := range *c.DomainsExcluded {
  87. d = append(d, strings.ToLower(domain))
  88. }
  89. }
  90. return &proxyman.SniffingConfig{
  91. Enabled: c.Enabled,
  92. DestinationOverride: p,
  93. DomainsExcluded: d,
  94. MetadataOnly: c.MetadataOnly,
  95. RouteOnly: c.RouteOnly,
  96. }, nil
  97. }
  98. type MuxConfig struct {
  99. Enabled bool `json:"enabled"`
  100. Concurrency int16 `json:"concurrency"`
  101. XudpConcurrency int16 `json:"xudpConcurrency"`
  102. }
  103. // Build creates MultiplexingConfig, Concurrency < 0 completely disables mux.
  104. func (m *MuxConfig) Build() (*proxyman.MultiplexingConfig, error) {
  105. return &proxyman.MultiplexingConfig{
  106. Enabled: m.Enabled,
  107. Concurrency: int32(m.Concurrency),
  108. XudpConcurrency: int32(m.XudpConcurrency),
  109. }, nil
  110. }
  111. type InboundDetourAllocationConfig struct {
  112. Strategy string `json:"strategy"`
  113. Concurrency *uint32 `json:"concurrency"`
  114. RefreshMin *uint32 `json:"refresh"`
  115. }
  116. // Build implements Buildable.
  117. func (c *InboundDetourAllocationConfig) Build() (*proxyman.AllocationStrategy, error) {
  118. config := new(proxyman.AllocationStrategy)
  119. switch strings.ToLower(c.Strategy) {
  120. case "always":
  121. config.Type = proxyman.AllocationStrategy_Always
  122. case "random":
  123. config.Type = proxyman.AllocationStrategy_Random
  124. case "external":
  125. config.Type = proxyman.AllocationStrategy_External
  126. default:
  127. return nil, newError("unknown allocation strategy: ", c.Strategy)
  128. }
  129. if c.Concurrency != nil {
  130. config.Concurrency = &proxyman.AllocationStrategy_AllocationStrategyConcurrency{
  131. Value: *c.Concurrency,
  132. }
  133. }
  134. if c.RefreshMin != nil {
  135. config.Refresh = &proxyman.AllocationStrategy_AllocationStrategyRefresh{
  136. Value: *c.RefreshMin,
  137. }
  138. }
  139. return config, nil
  140. }
  141. type InboundDetourConfig struct {
  142. Protocol string `json:"protocol"`
  143. PortList *PortList `json:"port"`
  144. ListenOn *Address `json:"listen"`
  145. Settings *json.RawMessage `json:"settings"`
  146. Tag string `json:"tag"`
  147. Allocation *InboundDetourAllocationConfig `json:"allocate"`
  148. StreamSetting *StreamConfig `json:"streamSettings"`
  149. DomainOverride *StringList `json:"domainOverride"`
  150. SniffingConfig *SniffingConfig `json:"sniffing"`
  151. }
  152. // Build implements Buildable.
  153. func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
  154. receiverSettings := &proxyman.ReceiverConfig{}
  155. if c.ListenOn == nil {
  156. // Listen on anyip, must set PortList
  157. if c.PortList == nil {
  158. return nil, newError("Listen on AnyIP but no Port(s) set in InboundDetour.")
  159. }
  160. receiverSettings.PortList = c.PortList.Build()
  161. } else {
  162. // Listen on specific IP or Unix Domain Socket
  163. receiverSettings.Listen = c.ListenOn.Build()
  164. listenDS := c.ListenOn.Family().IsDomain() && (c.ListenOn.Domain()[0] == '/' || c.ListenOn.Domain()[0] == '@')
  165. listenIP := c.ListenOn.Family().IsIP() || (c.ListenOn.Family().IsDomain() && c.ListenOn.Domain() == "localhost")
  166. if listenIP {
  167. // Listen on specific IP, must set PortList
  168. if c.PortList == nil {
  169. return nil, newError("Listen on specific ip without port in InboundDetour.")
  170. }
  171. // Listen on IP:Port
  172. receiverSettings.PortList = c.PortList.Build()
  173. } else if listenDS {
  174. if c.PortList != nil {
  175. // Listen on Unix Domain Socket, PortList should be nil
  176. receiverSettings.PortList = nil
  177. }
  178. } else {
  179. return nil, newError("unable to listen on domain address: ", c.ListenOn.Domain())
  180. }
  181. }
  182. if c.Allocation != nil {
  183. concurrency := -1
  184. if c.Allocation.Concurrency != nil && c.Allocation.Strategy == "random" {
  185. concurrency = int(*c.Allocation.Concurrency)
  186. }
  187. portRange := 0
  188. for _, pr := range c.PortList.Range {
  189. portRange += int(pr.To - pr.From + 1)
  190. }
  191. if concurrency >= 0 && concurrency >= portRange {
  192. var ports strings.Builder
  193. for _, pr := range c.PortList.Range {
  194. fmt.Fprintf(&ports, "%d-%d ", pr.From, pr.To)
  195. }
  196. return nil, newError("not enough ports. concurrency = ", concurrency, " ports: ", ports.String())
  197. }
  198. as, err := c.Allocation.Build()
  199. if err != nil {
  200. return nil, err
  201. }
  202. receiverSettings.AllocationStrategy = as
  203. }
  204. if c.StreamSetting != nil {
  205. ss, err := c.StreamSetting.Build()
  206. if err != nil {
  207. return nil, err
  208. }
  209. receiverSettings.StreamSettings = ss
  210. }
  211. if c.SniffingConfig != nil {
  212. s, err := c.SniffingConfig.Build()
  213. if err != nil {
  214. return nil, newError("failed to build sniffing config").Base(err)
  215. }
  216. receiverSettings.SniffingSettings = s
  217. }
  218. if c.DomainOverride != nil {
  219. kp, err := toProtocolList(*c.DomainOverride)
  220. if err != nil {
  221. return nil, newError("failed to parse inbound detour config").Base(err)
  222. }
  223. receiverSettings.DomainOverride = kp
  224. }
  225. settings := []byte("{}")
  226. if c.Settings != nil {
  227. settings = ([]byte)(*c.Settings)
  228. }
  229. rawConfig, err := inboundConfigLoader.LoadWithID(settings, c.Protocol)
  230. if err != nil {
  231. return nil, newError("failed to load inbound detour config.").Base(err)
  232. }
  233. if dokodemoConfig, ok := rawConfig.(*DokodemoConfig); ok {
  234. receiverSettings.ReceiveOriginalDestination = dokodemoConfig.Redirect
  235. }
  236. ts, err := rawConfig.(Buildable).Build()
  237. if err != nil {
  238. return nil, err
  239. }
  240. return &core.InboundHandlerConfig{
  241. Tag: c.Tag,
  242. ReceiverSettings: serial.ToTypedMessage(receiverSettings),
  243. ProxySettings: serial.ToTypedMessage(ts),
  244. }, nil
  245. }
  246. type OutboundDetourConfig struct {
  247. Protocol string `json:"protocol"`
  248. SendThrough *Address `json:"sendThrough"`
  249. Tag string `json:"tag"`
  250. Settings *json.RawMessage `json:"settings"`
  251. StreamSetting *StreamConfig `json:"streamSettings"`
  252. ProxySettings *ProxyConfig `json:"proxySettings"`
  253. MuxSettings *MuxConfig `json:"mux"`
  254. }
  255. func (c *OutboundDetourConfig) checkChainProxyConfig() error {
  256. if c.StreamSetting == nil || c.ProxySettings == nil || c.StreamSetting.SocketSettings == nil {
  257. return nil
  258. }
  259. if len(c.ProxySettings.Tag) > 0 && len(c.StreamSetting.SocketSettings.DialerProxy) > 0 {
  260. return newError("proxySettings.tag is conflicted with sockopt.dialerProxy").AtWarning()
  261. }
  262. return nil
  263. }
  264. // Build implements Buildable.
  265. func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
  266. senderSettings := &proxyman.SenderConfig{}
  267. if err := c.checkChainProxyConfig(); err != nil {
  268. return nil, err
  269. }
  270. if c.SendThrough != nil {
  271. address := c.SendThrough
  272. if address.Family().IsDomain() {
  273. return nil, newError("unable to send through: " + address.String())
  274. }
  275. senderSettings.Via = address.Build()
  276. }
  277. if c.StreamSetting != nil {
  278. ss, err := c.StreamSetting.Build()
  279. if err != nil {
  280. return nil, err
  281. }
  282. senderSettings.StreamSettings = ss
  283. }
  284. if c.ProxySettings != nil {
  285. ps, err := c.ProxySettings.Build()
  286. if err != nil {
  287. return nil, newError("invalid outbound detour proxy settings.").Base(err)
  288. }
  289. if ps.TransportLayerProxy {
  290. if senderSettings.StreamSettings != nil {
  291. if senderSettings.StreamSettings.SocketSettings != nil {
  292. senderSettings.StreamSettings.SocketSettings.DialerProxy = ps.Tag
  293. } else {
  294. senderSettings.StreamSettings.SocketSettings = &internet.SocketConfig{DialerProxy: ps.Tag}
  295. }
  296. } else {
  297. senderSettings.StreamSettings = &internet.StreamConfig{SocketSettings: &internet.SocketConfig{DialerProxy: ps.Tag}}
  298. }
  299. ps = nil
  300. }
  301. senderSettings.ProxySettings = ps
  302. }
  303. if c.MuxSettings != nil {
  304. ms, err := c.MuxSettings.Build()
  305. if err != nil {
  306. return nil, newError("failed to build Mux config.").Base(err)
  307. }
  308. senderSettings.MultiplexSettings = ms
  309. }
  310. settings := []byte("{}")
  311. if c.Settings != nil {
  312. settings = ([]byte)(*c.Settings)
  313. }
  314. rawConfig, err := outboundConfigLoader.LoadWithID(settings, c.Protocol)
  315. if err != nil {
  316. return nil, newError("failed to parse to outbound detour config.").Base(err)
  317. }
  318. ts, err := rawConfig.(Buildable).Build()
  319. if err != nil {
  320. return nil, err
  321. }
  322. return &core.OutboundHandlerConfig{
  323. SenderSettings: serial.ToTypedMessage(senderSettings),
  324. Tag: c.Tag,
  325. ProxySettings: serial.ToTypedMessage(ts),
  326. }, nil
  327. }
  328. type StatsConfig struct{}
  329. // Build implements Buildable.
  330. func (c *StatsConfig) Build() (*stats.Config, error) {
  331. return &stats.Config{}, nil
  332. }
  333. type Config struct {
  334. // Port of this Point server.
  335. // Deprecated: Port exists for historical compatibility
  336. // and should not be used.
  337. Port uint16 `json:"port"`
  338. // Deprecated: InboundConfig exists for historical compatibility
  339. // and should not be used.
  340. InboundConfig *InboundDetourConfig `json:"inbound"`
  341. // Deprecated: OutboundConfig exists for historical compatibility
  342. // and should not be used.
  343. OutboundConfig *OutboundDetourConfig `json:"outbound"`
  344. // Deprecated: InboundDetours exists for historical compatibility
  345. // and should not be used.
  346. InboundDetours []InboundDetourConfig `json:"inboundDetour"`
  347. // Deprecated: OutboundDetours exists for historical compatibility
  348. // and should not be used.
  349. OutboundDetours []OutboundDetourConfig `json:"outboundDetour"`
  350. LogConfig *LogConfig `json:"log"`
  351. RouterConfig *RouterConfig `json:"routing"`
  352. DNSConfig *DNSConfig `json:"dns"`
  353. InboundConfigs []InboundDetourConfig `json:"inbounds"`
  354. OutboundConfigs []OutboundDetourConfig `json:"outbounds"`
  355. Transport *TransportConfig `json:"transport"`
  356. Policy *PolicyConfig `json:"policy"`
  357. API *APIConfig `json:"api"`
  358. Metrics *MetricsConfig `json:"metrics"`
  359. Stats *StatsConfig `json:"stats"`
  360. Reverse *ReverseConfig `json:"reverse"`
  361. FakeDNS *FakeDNSConfig `json:"fakeDns"`
  362. Observatory *ObservatoryConfig `json:"observatory"`
  363. }
  364. func (c *Config) findInboundTag(tag string) int {
  365. found := -1
  366. for idx, ib := range c.InboundConfigs {
  367. if ib.Tag == tag {
  368. found = idx
  369. break
  370. }
  371. }
  372. return found
  373. }
  374. func (c *Config) findOutboundTag(tag string) int {
  375. found := -1
  376. for idx, ob := range c.OutboundConfigs {
  377. if ob.Tag == tag {
  378. found = idx
  379. break
  380. }
  381. }
  382. return found
  383. }
  384. // Override method accepts another Config overrides the current attribute
  385. func (c *Config) Override(o *Config, fn string) {
  386. // only process the non-deprecated members
  387. if o.LogConfig != nil {
  388. c.LogConfig = o.LogConfig
  389. }
  390. if o.RouterConfig != nil {
  391. c.RouterConfig = o.RouterConfig
  392. }
  393. if o.DNSConfig != nil {
  394. c.DNSConfig = o.DNSConfig
  395. }
  396. if o.Transport != nil {
  397. c.Transport = o.Transport
  398. }
  399. if o.Policy != nil {
  400. c.Policy = o.Policy
  401. }
  402. if o.API != nil {
  403. c.API = o.API
  404. }
  405. if o.Metrics != nil {
  406. c.Metrics = o.Metrics
  407. }
  408. if o.Stats != nil {
  409. c.Stats = o.Stats
  410. }
  411. if o.Reverse != nil {
  412. c.Reverse = o.Reverse
  413. }
  414. if o.FakeDNS != nil {
  415. c.FakeDNS = o.FakeDNS
  416. }
  417. if o.Observatory != nil {
  418. c.Observatory = o.Observatory
  419. }
  420. // deprecated attrs... keep them for now
  421. if o.InboundConfig != nil {
  422. c.InboundConfig = o.InboundConfig
  423. }
  424. if o.OutboundConfig != nil {
  425. c.OutboundConfig = o.OutboundConfig
  426. }
  427. if o.InboundDetours != nil {
  428. c.InboundDetours = o.InboundDetours
  429. }
  430. if o.OutboundDetours != nil {
  431. c.OutboundDetours = o.OutboundDetours
  432. }
  433. // deprecated attrs
  434. // update the Inbound in slice if the only one in overide config has same tag
  435. if len(o.InboundConfigs) > 0 {
  436. if len(c.InboundConfigs) > 0 && len(o.InboundConfigs) == 1 {
  437. if idx := c.findInboundTag(o.InboundConfigs[0].Tag); idx > -1 {
  438. c.InboundConfigs[idx] = o.InboundConfigs[0]
  439. ctllog.Println("[", fn, "] updated inbound with tag: ", o.InboundConfigs[0].Tag)
  440. } else {
  441. c.InboundConfigs = append(c.InboundConfigs, o.InboundConfigs[0])
  442. ctllog.Println("[", fn, "] appended inbound with tag: ", o.InboundConfigs[0].Tag)
  443. }
  444. } else {
  445. c.InboundConfigs = o.InboundConfigs
  446. }
  447. }
  448. // update the Outbound in slice if the only one in overide config has same tag
  449. if len(o.OutboundConfigs) > 0 {
  450. if len(c.OutboundConfigs) > 0 && len(o.OutboundConfigs) == 1 {
  451. if idx := c.findOutboundTag(o.OutboundConfigs[0].Tag); idx > -1 {
  452. c.OutboundConfigs[idx] = o.OutboundConfigs[0]
  453. ctllog.Println("[", fn, "] updated outbound with tag: ", o.OutboundConfigs[0].Tag)
  454. } else {
  455. if strings.Contains(strings.ToLower(fn), "tail") {
  456. c.OutboundConfigs = append(c.OutboundConfigs, o.OutboundConfigs[0])
  457. ctllog.Println("[", fn, "] appended outbound with tag: ", o.OutboundConfigs[0].Tag)
  458. } else {
  459. c.OutboundConfigs = append(o.OutboundConfigs, c.OutboundConfigs...)
  460. ctllog.Println("[", fn, "] prepended outbound with tag: ", o.OutboundConfigs[0].Tag)
  461. }
  462. }
  463. } else {
  464. c.OutboundConfigs = o.OutboundConfigs
  465. }
  466. }
  467. }
  468. func applyTransportConfig(s *StreamConfig, t *TransportConfig) {
  469. if s.TCPSettings == nil {
  470. s.TCPSettings = t.TCPConfig
  471. }
  472. if s.KCPSettings == nil {
  473. s.KCPSettings = t.KCPConfig
  474. }
  475. if s.WSSettings == nil {
  476. s.WSSettings = t.WSConfig
  477. }
  478. if s.HTTPSettings == nil {
  479. s.HTTPSettings = t.HTTPConfig
  480. }
  481. if s.DSSettings == nil {
  482. s.DSSettings = t.DSConfig
  483. }
  484. }
  485. // Build implements Buildable.
  486. func (c *Config) Build() (*core.Config, error) {
  487. if err := PostProcessConfigureFile(c); err != nil {
  488. return nil, err
  489. }
  490. config := &core.Config{
  491. App: []*serial.TypedMessage{
  492. serial.ToTypedMessage(&dispatcher.Config{}),
  493. serial.ToTypedMessage(&proxyman.InboundConfig{}),
  494. serial.ToTypedMessage(&proxyman.OutboundConfig{}),
  495. },
  496. }
  497. if c.API != nil {
  498. apiConf, err := c.API.Build()
  499. if err != nil {
  500. return nil, err
  501. }
  502. config.App = append(config.App, serial.ToTypedMessage(apiConf))
  503. }
  504. if c.Metrics != nil {
  505. metricsConf, err := c.Metrics.Build()
  506. if err != nil {
  507. return nil, err
  508. }
  509. config.App = append(config.App, serial.ToTypedMessage(metricsConf))
  510. }
  511. if c.Stats != nil {
  512. statsConf, err := c.Stats.Build()
  513. if err != nil {
  514. return nil, err
  515. }
  516. config.App = append(config.App, serial.ToTypedMessage(statsConf))
  517. }
  518. var logConfMsg *serial.TypedMessage
  519. if c.LogConfig != nil {
  520. logConfMsg = serial.ToTypedMessage(c.LogConfig.Build())
  521. } else {
  522. logConfMsg = serial.ToTypedMessage(DefaultLogConfig())
  523. }
  524. // let logger module be the first App to start,
  525. // so that other modules could print log during initiating
  526. config.App = append([]*serial.TypedMessage{logConfMsg}, config.App...)
  527. if c.RouterConfig != nil {
  528. routerConfig, err := c.RouterConfig.Build()
  529. if err != nil {
  530. return nil, err
  531. }
  532. config.App = append(config.App, serial.ToTypedMessage(routerConfig))
  533. }
  534. if c.DNSConfig != nil {
  535. dnsApp, err := c.DNSConfig.Build()
  536. if err != nil {
  537. return nil, newError("failed to parse DNS config").Base(err)
  538. }
  539. config.App = append(config.App, serial.ToTypedMessage(dnsApp))
  540. }
  541. if c.Policy != nil {
  542. pc, err := c.Policy.Build()
  543. if err != nil {
  544. return nil, err
  545. }
  546. config.App = append(config.App, serial.ToTypedMessage(pc))
  547. }
  548. if c.Reverse != nil {
  549. r, err := c.Reverse.Build()
  550. if err != nil {
  551. return nil, err
  552. }
  553. config.App = append(config.App, serial.ToTypedMessage(r))
  554. }
  555. if c.FakeDNS != nil {
  556. r, err := c.FakeDNS.Build()
  557. if err != nil {
  558. return nil, err
  559. }
  560. config.App = append([]*serial.TypedMessage{serial.ToTypedMessage(r)}, config.App...)
  561. }
  562. if c.Observatory != nil {
  563. r, err := c.Observatory.Build()
  564. if err != nil {
  565. return nil, err
  566. }
  567. config.App = append(config.App, serial.ToTypedMessage(r))
  568. }
  569. var inbounds []InboundDetourConfig
  570. if c.InboundConfig != nil {
  571. inbounds = append(inbounds, *c.InboundConfig)
  572. }
  573. if len(c.InboundDetours) > 0 {
  574. inbounds = append(inbounds, c.InboundDetours...)
  575. }
  576. if len(c.InboundConfigs) > 0 {
  577. inbounds = append(inbounds, c.InboundConfigs...)
  578. }
  579. // Backward compatibility.
  580. if len(inbounds) > 0 && inbounds[0].PortList == nil && c.Port > 0 {
  581. inbounds[0].PortList = &PortList{[]PortRange{{
  582. From: uint32(c.Port),
  583. To: uint32(c.Port),
  584. }}}
  585. }
  586. for _, rawInboundConfig := range inbounds {
  587. if c.Transport != nil {
  588. if rawInboundConfig.StreamSetting == nil {
  589. rawInboundConfig.StreamSetting = &StreamConfig{}
  590. }
  591. applyTransportConfig(rawInboundConfig.StreamSetting, c.Transport)
  592. }
  593. ic, err := rawInboundConfig.Build()
  594. if err != nil {
  595. return nil, err
  596. }
  597. config.Inbound = append(config.Inbound, ic)
  598. }
  599. var outbounds []OutboundDetourConfig
  600. if c.OutboundConfig != nil {
  601. outbounds = append(outbounds, *c.OutboundConfig)
  602. }
  603. if len(c.OutboundDetours) > 0 {
  604. outbounds = append(outbounds, c.OutboundDetours...)
  605. }
  606. if len(c.OutboundConfigs) > 0 {
  607. outbounds = append(outbounds, c.OutboundConfigs...)
  608. }
  609. for _, rawOutboundConfig := range outbounds {
  610. if c.Transport != nil {
  611. if rawOutboundConfig.StreamSetting == nil {
  612. rawOutboundConfig.StreamSetting = &StreamConfig{}
  613. }
  614. applyTransportConfig(rawOutboundConfig.StreamSetting, c.Transport)
  615. }
  616. oc, err := rawOutboundConfig.Build()
  617. if err != nil {
  618. return nil, err
  619. }
  620. config.Outbound = append(config.Outbound, oc)
  621. }
  622. return config, nil
  623. }