v2ray.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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) {
  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("updated inbound with tag: ", o.InboundConfigs[0].Tag).AtInfo().WriteToLog()
  325. } else {
  326. c.InboundConfigs = append(c.InboundConfigs, o.InboundConfigs[0])
  327. }
  328. } else {
  329. c.InboundConfigs = o.InboundConfigs
  330. }
  331. }
  332. // update the Outbound in slice if the only one in overide config has same tag
  333. if len(o.OutboundConfigs) > 0 {
  334. if len(c.OutboundConfigs) > 0 && len(o.OutboundConfigs) == 1 {
  335. if idx := c.findOutboundTag(o.OutboundConfigs[0].Tag); idx > -1 {
  336. c.OutboundConfigs[idx] = o.OutboundConfigs[0]
  337. } else {
  338. c.OutboundConfigs = append(c.OutboundConfigs, o.OutboundConfigs[0])
  339. }
  340. } else {
  341. c.OutboundConfigs = o.OutboundConfigs
  342. }
  343. }
  344. }
  345. func applyTransportConfig(s *StreamConfig, t *TransportConfig) {
  346. if s.TCPSettings == nil {
  347. s.TCPSettings = t.TCPConfig
  348. }
  349. if s.KCPSettings == nil {
  350. s.KCPSettings = t.KCPConfig
  351. }
  352. if s.WSSettings == nil {
  353. s.WSSettings = t.WSConfig
  354. }
  355. if s.HTTPSettings == nil {
  356. s.HTTPSettings = t.HTTPConfig
  357. }
  358. if s.DSSettings == nil {
  359. s.DSSettings = t.DSConfig
  360. }
  361. }
  362. // Build implements Buildable.
  363. func (c *Config) Build() (*core.Config, error) {
  364. config := &core.Config{
  365. App: []*serial.TypedMessage{
  366. serial.ToTypedMessage(&dispatcher.Config{}),
  367. serial.ToTypedMessage(&proxyman.InboundConfig{}),
  368. serial.ToTypedMessage(&proxyman.OutboundConfig{}),
  369. },
  370. }
  371. if c.Api != nil {
  372. apiConf, err := c.Api.Build()
  373. if err != nil {
  374. return nil, err
  375. }
  376. config.App = append(config.App, serial.ToTypedMessage(apiConf))
  377. }
  378. if c.Stats != nil {
  379. statsConf, err := c.Stats.Build()
  380. if err != nil {
  381. return nil, err
  382. }
  383. config.App = append(config.App, serial.ToTypedMessage(statsConf))
  384. }
  385. var logConfMsg *serial.TypedMessage
  386. if c.LogConfig != nil {
  387. logConfMsg = serial.ToTypedMessage(c.LogConfig.Build())
  388. } else {
  389. logConfMsg = serial.ToTypedMessage(DefaultLogConfig())
  390. }
  391. // let logger module be the first App to start,
  392. // so that other modules could print log during initiating
  393. config.App = append([]*serial.TypedMessage{logConfMsg}, config.App...)
  394. if c.RouterConfig != nil {
  395. routerConfig, err := c.RouterConfig.Build()
  396. if err != nil {
  397. return nil, err
  398. }
  399. config.App = append(config.App, serial.ToTypedMessage(routerConfig))
  400. }
  401. if c.DNSConfig != nil {
  402. dnsApp, err := c.DNSConfig.Build()
  403. if err != nil {
  404. return nil, newError("failed to parse DNS config").Base(err)
  405. }
  406. config.App = append(config.App, serial.ToTypedMessage(dnsApp))
  407. }
  408. if c.Policy != nil {
  409. pc, err := c.Policy.Build()
  410. if err != nil {
  411. return nil, err
  412. }
  413. config.App = append(config.App, serial.ToTypedMessage(pc))
  414. }
  415. if c.Reverse != nil {
  416. r, err := c.Reverse.Build()
  417. if err != nil {
  418. return nil, err
  419. }
  420. config.App = append(config.App, serial.ToTypedMessage(r))
  421. }
  422. var inbounds []InboundDetourConfig
  423. if c.InboundConfig != nil {
  424. inbounds = append(inbounds, *c.InboundConfig)
  425. }
  426. if len(c.InboundDetours) > 0 {
  427. inbounds = append(inbounds, c.InboundDetours...)
  428. }
  429. if len(c.InboundConfigs) > 0 {
  430. inbounds = append(inbounds, c.InboundConfigs...)
  431. }
  432. // Backward compatibility.
  433. if len(inbounds) > 0 && inbounds[0].PortRange == nil && c.Port > 0 {
  434. inbounds[0].PortRange = &PortRange{
  435. From: uint32(c.Port),
  436. To: uint32(c.Port),
  437. }
  438. }
  439. for _, rawInboundConfig := range inbounds {
  440. if c.Transport != nil {
  441. if rawInboundConfig.StreamSetting == nil {
  442. rawInboundConfig.StreamSetting = &StreamConfig{}
  443. }
  444. applyTransportConfig(rawInboundConfig.StreamSetting, c.Transport)
  445. }
  446. ic, err := rawInboundConfig.Build()
  447. if err != nil {
  448. return nil, err
  449. }
  450. config.Inbound = append(config.Inbound, ic)
  451. }
  452. var outbounds []OutboundDetourConfig
  453. if c.OutboundConfig != nil {
  454. outbounds = append(outbounds, *c.OutboundConfig)
  455. }
  456. if len(c.OutboundDetours) > 0 {
  457. outbounds = append(outbounds, c.OutboundDetours...)
  458. }
  459. if len(c.OutboundConfigs) > 0 {
  460. outbounds = append(outbounds, c.OutboundConfigs...)
  461. }
  462. for _, rawOutboundConfig := range outbounds {
  463. if c.Transport != nil {
  464. if rawOutboundConfig.StreamSetting == nil {
  465. rawOutboundConfig.StreamSetting = &StreamConfig{}
  466. }
  467. applyTransportConfig(rawOutboundConfig.StreamSetting, c.Transport)
  468. }
  469. oc, err := rawOutboundConfig.Build()
  470. if err != nil {
  471. return nil, err
  472. }
  473. config.Outbound = append(config.Outbound, oc)
  474. }
  475. return config, nil
  476. }