v2ray.go 17 KB

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