v2ray.go 17 KB

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