xray.go 20 KB

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