xray.go 21 KB

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