xray.go 20 KB

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