xray.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  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. "github.com/xtls/xray-core/transport/internet"
  13. core "github.com/xtls/xray-core/core"
  14. "github.com/xtls/xray-core/transport/internet/xtls"
  15. )
  16. var (
  17. inboundConfigLoader = NewJSONConfigLoader(ConfigCreatorCache{
  18. "dokodemo-door": func() interface{} { return new(DokodemoConfig) },
  19. "http": func() interface{} { return new(HTTPServerConfig) },
  20. "shadowsocks": func() interface{} { return new(ShadowsocksServerConfig) },
  21. "socks": func() interface{} { return new(SocksServerConfig) },
  22. "vless": func() interface{} { return new(VLessInboundConfig) },
  23. "vmess": func() interface{} { return new(VMessInboundConfig) },
  24. "trojan": func() interface{} { return new(TrojanServerConfig) },
  25. "mtproto": func() interface{} { return new(MTProtoServerConfig) },
  26. }, "protocol", "settings")
  27. outboundConfigLoader = NewJSONConfigLoader(ConfigCreatorCache{
  28. "blackhole": func() interface{} { return new(BlackholeConfig) },
  29. "loopback": func() interface{} { return new(LoopbackConfig) },
  30. "freedom": func() interface{} { return new(FreedomConfig) },
  31. "http": func() interface{} { return new(HTTPClientConfig) },
  32. "shadowsocks": func() interface{} { return new(ShadowsocksClientConfig) },
  33. "socks": func() interface{} { return new(SocksClientConfig) },
  34. "vless": func() interface{} { return new(VLessOutboundConfig) },
  35. "vmess": func() interface{} { return new(VMessOutboundConfig) },
  36. "trojan": func() interface{} { return new(TrojanClientConfig) },
  37. "mtproto": func() interface{} { return new(MTProtoClientConfig) },
  38. "dns": func() interface{} { return new(DNSOutboundConfig) },
  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 "fakedns":
  74. p = append(p, "fakedns")
  75. case "fakedns+others":
  76. p = append(p, "fakedns+others")
  77. default:
  78. return nil, newError("unknown protocol: ", protocol)
  79. }
  80. }
  81. }
  82. var d []string
  83. if c.DomainsExcluded != nil {
  84. for _, domain := range *c.DomainsExcluded {
  85. d = append(d, strings.ToLower(domain))
  86. }
  87. }
  88. return &proxyman.SniffingConfig{
  89. Enabled: c.Enabled,
  90. DestinationOverride: p,
  91. DomainsExcluded: d,
  92. MetadataOnly: c.MetadataOnly,
  93. RouteOnly: c.RouteOnly,
  94. }, nil
  95. }
  96. type MuxConfig struct {
  97. Enabled bool `json:"enabled"`
  98. Concurrency int16 `json:"concurrency"`
  99. }
  100. // Build creates MultiplexingConfig, Concurrency < 0 completely disables mux.
  101. func (m *MuxConfig) Build() *proxyman.MultiplexingConfig {
  102. if m.Concurrency < 0 {
  103. return nil
  104. }
  105. var con uint32 = 8
  106. if m.Concurrency > 0 {
  107. con = uint32(m.Concurrency)
  108. }
  109. return &proxyman.MultiplexingConfig{
  110. Enabled: m.Enabled,
  111. Concurrency: con,
  112. }
  113. }
  114. type InboundDetourAllocationConfig struct {
  115. Strategy string `json:"strategy"`
  116. Concurrency *uint32 `json:"concurrency"`
  117. RefreshMin *uint32 `json:"refresh"`
  118. }
  119. // Build implements Buildable.
  120. func (c *InboundDetourAllocationConfig) Build() (*proxyman.AllocationStrategy, error) {
  121. config := new(proxyman.AllocationStrategy)
  122. switch strings.ToLower(c.Strategy) {
  123. case "always":
  124. config.Type = proxyman.AllocationStrategy_Always
  125. case "random":
  126. config.Type = proxyman.AllocationStrategy_Random
  127. case "external":
  128. config.Type = proxyman.AllocationStrategy_External
  129. default:
  130. return nil, newError("unknown allocation strategy: ", c.Strategy)
  131. }
  132. if c.Concurrency != nil {
  133. config.Concurrency = &proxyman.AllocationStrategy_AllocationStrategyConcurrency{
  134. Value: *c.Concurrency,
  135. }
  136. }
  137. if c.RefreshMin != nil {
  138. config.Refresh = &proxyman.AllocationStrategy_AllocationStrategyRefresh{
  139. Value: *c.RefreshMin,
  140. }
  141. }
  142. return config, nil
  143. }
  144. type InboundDetourConfig struct {
  145. Protocol string `json:"protocol"`
  146. PortList *PortList `json:"port"`
  147. ListenOn *Address `json:"listen"`
  148. Settings *json.RawMessage `json:"settings"`
  149. Tag string `json:"tag"`
  150. Allocation *InboundDetourAllocationConfig `json:"allocate"`
  151. StreamSetting *StreamConfig `json:"streamSettings"`
  152. DomainOverride *StringList `json:"domainOverride"`
  153. SniffingConfig *SniffingConfig `json:"sniffing"`
  154. }
  155. // Build implements Buildable.
  156. func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
  157. receiverSettings := &proxyman.ReceiverConfig{}
  158. if c.ListenOn == nil {
  159. // Listen on anyip, must set PortList
  160. if c.PortList == nil {
  161. return nil, newError("Listen on AnyIP but no Port(s) set in InboundDetour.")
  162. }
  163. receiverSettings.PortList = c.PortList.Build()
  164. } else {
  165. // Listen on specific IP or Unix Domain Socket
  166. receiverSettings.Listen = c.ListenOn.Build()
  167. listenDS := c.ListenOn.Family().IsDomain() && (c.ListenOn.Domain()[0] == '/' || c.ListenOn.Domain()[0] == '@')
  168. listenIP := c.ListenOn.Family().IsIP() || (c.ListenOn.Family().IsDomain() && c.ListenOn.Domain() == "localhost")
  169. if listenIP {
  170. // Listen on specific IP, must set PortList
  171. if c.PortList == nil {
  172. return nil, newError("Listen on specific ip without port in InboundDetour.")
  173. }
  174. // Listen on IP:Port
  175. receiverSettings.PortList = c.PortList.Build()
  176. } else if listenDS {
  177. if c.PortList != nil {
  178. // Listen on Unix Domain Socket, PortList should be nil
  179. receiverSettings.PortList = nil
  180. }
  181. } else {
  182. return nil, newError("unable to listen on domain address: ", c.ListenOn.Domain())
  183. }
  184. }
  185. if c.Allocation != nil {
  186. concurrency := -1
  187. if c.Allocation.Concurrency != nil && c.Allocation.Strategy == "random" {
  188. concurrency = int(*c.Allocation.Concurrency)
  189. }
  190. portRange := 0
  191. for _, pr := range c.PortList.Range {
  192. portRange += int(pr.To - pr.From + 1)
  193. }
  194. if concurrency >= 0 && concurrency >= portRange {
  195. var ports strings.Builder
  196. for _, pr := range c.PortList.Range {
  197. fmt.Fprintf(&ports, "%d-%d ", pr.From, pr.To)
  198. }
  199. return nil, newError("not enough ports. concurrency = ", concurrency, " ports: ", ports.String())
  200. }
  201. as, err := c.Allocation.Build()
  202. if err != nil {
  203. return nil, err
  204. }
  205. receiverSettings.AllocationStrategy = as
  206. }
  207. if c.StreamSetting != nil {
  208. ss, err := c.StreamSetting.Build()
  209. if err != nil {
  210. return nil, err
  211. }
  212. if ss.SecurityType == serial.GetMessageType(&xtls.Config{}) && !strings.EqualFold(c.Protocol, "vless") && !strings.EqualFold(c.Protocol, "trojan") {
  213. return nil, newError("XTLS doesn't supports " + c.Protocol + " for now.")
  214. }
  215. receiverSettings.StreamSettings = ss
  216. }
  217. if c.SniffingConfig != nil {
  218. s, err := c.SniffingConfig.Build()
  219. if err != nil {
  220. return nil, newError("failed to build sniffing config").Base(err)
  221. }
  222. receiverSettings.SniffingSettings = s
  223. }
  224. if c.DomainOverride != nil {
  225. kp, err := toProtocolList(*c.DomainOverride)
  226. if err != nil {
  227. return nil, newError("failed to parse inbound detour config").Base(err)
  228. }
  229. receiverSettings.DomainOverride = kp
  230. }
  231. settings := []byte("{}")
  232. if c.Settings != nil {
  233. settings = ([]byte)(*c.Settings)
  234. }
  235. rawConfig, err := inboundConfigLoader.LoadWithID(settings, c.Protocol)
  236. if err != nil {
  237. return nil, newError("failed to load inbound detour config.").Base(err)
  238. }
  239. if dokodemoConfig, ok := rawConfig.(*DokodemoConfig); ok {
  240. receiverSettings.ReceiveOriginalDestination = dokodemoConfig.Redirect
  241. }
  242. ts, err := rawConfig.(Buildable).Build()
  243. if err != nil {
  244. return nil, err
  245. }
  246. return &core.InboundHandlerConfig{
  247. Tag: c.Tag,
  248. ReceiverSettings: serial.ToTypedMessage(receiverSettings),
  249. ProxySettings: serial.ToTypedMessage(ts),
  250. }, nil
  251. }
  252. type OutboundDetourConfig struct {
  253. Protocol string `json:"protocol"`
  254. SendThrough *Address `json:"sendThrough"`
  255. Tag string `json:"tag"`
  256. Settings *json.RawMessage `json:"settings"`
  257. StreamSetting *StreamConfig `json:"streamSettings"`
  258. ProxySettings *ProxyConfig `json:"proxySettings"`
  259. MuxSettings *MuxConfig `json:"mux"`
  260. }
  261. func (c *OutboundDetourConfig) checkChainProxyConfig() error {
  262. if c.StreamSetting == nil || c.ProxySettings == nil || c.StreamSetting.SocketSettings == nil {
  263. return nil
  264. }
  265. if len(c.ProxySettings.Tag) > 0 && len(c.StreamSetting.SocketSettings.DialerProxy) > 0 {
  266. return newError("proxySettings.tag is conflicted with sockopt.dialerProxy").AtWarning()
  267. }
  268. return nil
  269. }
  270. // Build implements Buildable.
  271. func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
  272. senderSettings := &proxyman.SenderConfig{}
  273. if err := c.checkChainProxyConfig(); err != nil {
  274. return nil, err
  275. }
  276. if c.SendThrough != nil {
  277. address := c.SendThrough
  278. if address.Family().IsDomain() {
  279. return nil, newError("unable to send through: " + address.String())
  280. }
  281. senderSettings.Via = address.Build()
  282. }
  283. if c.StreamSetting != nil {
  284. ss, err := c.StreamSetting.Build()
  285. if err != nil {
  286. return nil, err
  287. }
  288. if ss.SecurityType == serial.GetMessageType(&xtls.Config{}) && !strings.EqualFold(c.Protocol, "vless") && !strings.EqualFold(c.Protocol, "trojan") {
  289. return nil, newError("XTLS doesn't supports " + c.Protocol + " for now.")
  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 := c.MuxSettings.Build()
  314. if ms != nil && ms.Enabled {
  315. if ss := senderSettings.StreamSettings; ss != nil {
  316. if ss.SecurityType == serial.GetMessageType(&xtls.Config{}) {
  317. return nil, newError("XTLS doesn't support Mux for now.")
  318. }
  319. }
  320. }
  321. senderSettings.MultiplexSettings = ms
  322. }
  323. settings := []byte("{}")
  324. if c.Settings != nil {
  325. settings = ([]byte)(*c.Settings)
  326. }
  327. rawConfig, err := outboundConfigLoader.LoadWithID(settings, c.Protocol)
  328. if err != nil {
  329. return nil, newError("failed to parse to outbound detour config.").Base(err)
  330. }
  331. ts, err := rawConfig.(Buildable).Build()
  332. if err != nil {
  333. return nil, err
  334. }
  335. return &core.OutboundHandlerConfig{
  336. SenderSettings: serial.ToTypedMessage(senderSettings),
  337. Tag: c.Tag,
  338. ProxySettings: serial.ToTypedMessage(ts),
  339. }, nil
  340. }
  341. type StatsConfig struct{}
  342. // Build implements Buildable.
  343. func (c *StatsConfig) Build() (*stats.Config, error) {
  344. return &stats.Config{}, nil
  345. }
  346. type Config struct {
  347. // Port of this Point server.
  348. // Deprecated: Port exists for historical compatibility
  349. // and should not be used.
  350. Port uint16 `json:"port"`
  351. // Deprecated: InboundConfig exists for historical compatibility
  352. // and should not be used.
  353. InboundConfig *InboundDetourConfig `json:"inbound"`
  354. // Deprecated: OutboundConfig exists for historical compatibility
  355. // and should not be used.
  356. OutboundConfig *OutboundDetourConfig `json:"outbound"`
  357. // Deprecated: InboundDetours exists for historical compatibility
  358. // and should not be used.
  359. InboundDetours []InboundDetourConfig `json:"inboundDetour"`
  360. // Deprecated: OutboundDetours exists for historical compatibility
  361. // and should not be used.
  362. OutboundDetours []OutboundDetourConfig `json:"outboundDetour"`
  363. LogConfig *LogConfig `json:"log"`
  364. RouterConfig *RouterConfig `json:"routing"`
  365. DNSConfig *DNSConfig `json:"dns"`
  366. InboundConfigs []InboundDetourConfig `json:"inbounds"`
  367. OutboundConfigs []OutboundDetourConfig `json:"outbounds"`
  368. Transport *TransportConfig `json:"transport"`
  369. Policy *PolicyConfig `json:"policy"`
  370. API *APIConfig `json:"api"`
  371. Stats *StatsConfig `json:"stats"`
  372. Reverse *ReverseConfig `json:"reverse"`
  373. FakeDNS *FakeDNSConfig `json:"fakeDns"`
  374. Observatory *ObservatoryConfig `json:"observatory"`
  375. }
  376. func (c *Config) findInboundTag(tag string) int {
  377. found := -1
  378. for idx, ib := range c.InboundConfigs {
  379. if ib.Tag == tag {
  380. found = idx
  381. break
  382. }
  383. }
  384. return found
  385. }
  386. func (c *Config) findOutboundTag(tag string) int {
  387. found := -1
  388. for idx, ob := range c.OutboundConfigs {
  389. if ob.Tag == tag {
  390. found = idx
  391. break
  392. }
  393. }
  394. return found
  395. }
  396. // Override method accepts another Config overrides the current attribute
  397. func (c *Config) Override(o *Config, fn string) {
  398. // only process the non-deprecated members
  399. if o.LogConfig != nil {
  400. c.LogConfig = o.LogConfig
  401. }
  402. if o.RouterConfig != nil {
  403. c.RouterConfig = o.RouterConfig
  404. }
  405. if o.DNSConfig != nil {
  406. c.DNSConfig = o.DNSConfig
  407. }
  408. if o.Transport != nil {
  409. c.Transport = o.Transport
  410. }
  411. if o.Policy != nil {
  412. c.Policy = o.Policy
  413. }
  414. if o.API != nil {
  415. c.API = o.API
  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.Stats != nil {
  514. statsConf, err := c.Stats.Build()
  515. if err != nil {
  516. return nil, err
  517. }
  518. config.App = append(config.App, serial.ToTypedMessage(statsConf))
  519. }
  520. var logConfMsg *serial.TypedMessage
  521. if c.LogConfig != nil {
  522. logConfMsg = serial.ToTypedMessage(c.LogConfig.Build())
  523. } else {
  524. logConfMsg = serial.ToTypedMessage(DefaultLogConfig())
  525. }
  526. // let logger module be the first App to start,
  527. // so that other modules could print log during initiating
  528. config.App = append([]*serial.TypedMessage{logConfMsg}, config.App...)
  529. if c.RouterConfig != nil {
  530. routerConfig, err := c.RouterConfig.Build()
  531. if err != nil {
  532. return nil, err
  533. }
  534. config.App = append(config.App, serial.ToTypedMessage(routerConfig))
  535. }
  536. if c.DNSConfig != nil {
  537. dnsApp, err := c.DNSConfig.Build()
  538. if err != nil {
  539. return nil, newError("failed to parse DNS config").Base(err)
  540. }
  541. config.App = append(config.App, serial.ToTypedMessage(dnsApp))
  542. }
  543. if c.Policy != nil {
  544. pc, err := c.Policy.Build()
  545. if err != nil {
  546. return nil, err
  547. }
  548. config.App = append(config.App, serial.ToTypedMessage(pc))
  549. }
  550. if c.Reverse != nil {
  551. r, err := c.Reverse.Build()
  552. if err != nil {
  553. return nil, err
  554. }
  555. config.App = append(config.App, serial.ToTypedMessage(r))
  556. }
  557. if c.FakeDNS != nil {
  558. r, err := c.FakeDNS.Build()
  559. if err != nil {
  560. return nil, err
  561. }
  562. config.App = append(config.App, serial.ToTypedMessage(r))
  563. }
  564. if c.Observatory != nil {
  565. r, err := c.Observatory.Build()
  566. if err != nil {
  567. return nil, err
  568. }
  569. config.App = append(config.App, serial.ToTypedMessage(r))
  570. }
  571. var inbounds []InboundDetourConfig
  572. if c.InboundConfig != nil {
  573. inbounds = append(inbounds, *c.InboundConfig)
  574. }
  575. if len(c.InboundDetours) > 0 {
  576. inbounds = append(inbounds, c.InboundDetours...)
  577. }
  578. if len(c.InboundConfigs) > 0 {
  579. inbounds = append(inbounds, c.InboundConfigs...)
  580. }
  581. // Backward compatibility.
  582. if len(inbounds) > 0 && inbounds[0].PortList == nil && c.Port > 0 {
  583. inbounds[0].PortList = &PortList{[]PortRange{{
  584. From: uint32(c.Port),
  585. To: uint32(c.Port),
  586. }}}
  587. }
  588. for _, rawInboundConfig := range inbounds {
  589. if c.Transport != nil {
  590. if rawInboundConfig.StreamSetting == nil {
  591. rawInboundConfig.StreamSetting = &StreamConfig{}
  592. }
  593. applyTransportConfig(rawInboundConfig.StreamSetting, c.Transport)
  594. }
  595. ic, err := rawInboundConfig.Build()
  596. if err != nil {
  597. return nil, err
  598. }
  599. config.Inbound = append(config.Inbound, ic)
  600. }
  601. var outbounds []OutboundDetourConfig
  602. if c.OutboundConfig != nil {
  603. outbounds = append(outbounds, *c.OutboundConfig)
  604. }
  605. if len(c.OutboundDetours) > 0 {
  606. outbounds = append(outbounds, c.OutboundDetours...)
  607. }
  608. if len(c.OutboundConfigs) > 0 {
  609. outbounds = append(outbounds, c.OutboundConfigs...)
  610. }
  611. for _, rawOutboundConfig := range outbounds {
  612. if c.Transport != nil {
  613. if rawOutboundConfig.StreamSetting == nil {
  614. rawOutboundConfig.StreamSetting = &StreamConfig{}
  615. }
  616. applyTransportConfig(rawOutboundConfig.StreamSetting, c.Transport)
  617. }
  618. oc, err := rawOutboundConfig.Build()
  619. if err != nil {
  620. return nil, err
  621. }
  622. config.Outbound = append(config.Outbound, oc)
  623. }
  624. return config, nil
  625. }