v2ray.go 19 KB

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