v2ray.go 15 KB

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