xray.go 21 KB

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