xray.go 19 KB

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