xray.go 20 KB

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