v2ray.go 18 KB

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