v2ray.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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 uint16 `json:"concurrency"`
  71. }
  72. func (c *MuxConfig) GetConcurrency() uint16 {
  73. if c.Concurrency == 0 {
  74. return 8
  75. }
  76. return c.Concurrency
  77. }
  78. type InboundDetourAllocationConfig struct {
  79. Strategy string `json:"strategy"`
  80. Concurrency *uint32 `json:"concurrency"`
  81. RefreshMin *uint32 `json:"refresh"`
  82. }
  83. // Build implements Buildable.
  84. func (c *InboundDetourAllocationConfig) Build() (*proxyman.AllocationStrategy, error) {
  85. config := new(proxyman.AllocationStrategy)
  86. switch strings.ToLower(c.Strategy) {
  87. case "always":
  88. config.Type = proxyman.AllocationStrategy_Always
  89. case "random":
  90. config.Type = proxyman.AllocationStrategy_Random
  91. case "external":
  92. config.Type = proxyman.AllocationStrategy_External
  93. default:
  94. return nil, newError("unknown allocation strategy: ", c.Strategy)
  95. }
  96. if c.Concurrency != nil {
  97. config.Concurrency = &proxyman.AllocationStrategy_AllocationStrategyConcurrency{
  98. Value: *c.Concurrency,
  99. }
  100. }
  101. if c.RefreshMin != nil {
  102. config.Refresh = &proxyman.AllocationStrategy_AllocationStrategyRefresh{
  103. Value: *c.RefreshMin,
  104. }
  105. }
  106. return config, nil
  107. }
  108. type InboundDetourConfig struct {
  109. Protocol string `json:"protocol"`
  110. PortRange *PortRange `json:"port"`
  111. ListenOn *Address `json:"listen"`
  112. Settings *json.RawMessage `json:"settings"`
  113. Tag string `json:"tag"`
  114. Allocation *InboundDetourAllocationConfig `json:"allocate"`
  115. StreamSetting *StreamConfig `json:"streamSettings"`
  116. DomainOverride *StringList `json:"domainOverride"`
  117. SniffingConfig *SniffingConfig `json:"sniffing"`
  118. }
  119. // Build implements Buildable.
  120. func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
  121. receiverSettings := &proxyman.ReceiverConfig{}
  122. if c.PortRange == nil {
  123. return nil, newError("port range not specified in InboundDetour.")
  124. }
  125. receiverSettings.PortRange = c.PortRange.Build()
  126. if c.ListenOn != nil {
  127. if c.ListenOn.Family().IsDomain() {
  128. return nil, newError("unable to listen on domain address: ", c.ListenOn.Domain())
  129. }
  130. receiverSettings.Listen = c.ListenOn.Build()
  131. }
  132. if c.Allocation != nil {
  133. concurrency := -1
  134. if c.Allocation.Concurrency != nil && c.Allocation.Strategy == "random" {
  135. concurrency = int(*c.Allocation.Concurrency)
  136. }
  137. portRange := int(c.PortRange.To - c.PortRange.From + 1)
  138. if concurrency >= 0 && concurrency >= portRange {
  139. return nil, newError("not enough ports. concurrency = ", concurrency, " ports: ", c.PortRange.From, " - ", c.PortRange.To)
  140. }
  141. as, err := c.Allocation.Build()
  142. if err != nil {
  143. return nil, err
  144. }
  145. receiverSettings.AllocationStrategy = as
  146. }
  147. if c.StreamSetting != nil {
  148. ss, err := c.StreamSetting.Build()
  149. if err != nil {
  150. return nil, err
  151. }
  152. receiverSettings.StreamSettings = ss
  153. }
  154. if c.SniffingConfig != nil {
  155. s, err := c.SniffingConfig.Build()
  156. if err != nil {
  157. return nil, newError("failed to build sniffing config").Base(err)
  158. }
  159. receiverSettings.SniffingSettings = s
  160. }
  161. if c.DomainOverride != nil {
  162. kp, err := toProtocolList(*c.DomainOverride)
  163. if err != nil {
  164. return nil, newError("failed to parse inbound detour config").Base(err)
  165. }
  166. receiverSettings.DomainOverride = kp
  167. }
  168. settings := []byte("{}")
  169. if c.Settings != nil {
  170. settings = ([]byte)(*c.Settings)
  171. }
  172. rawConfig, err := inboundConfigLoader.LoadWithID(settings, c.Protocol)
  173. if err != nil {
  174. return nil, newError("failed to load inbound detour config.").Base(err)
  175. }
  176. if dokodemoConfig, ok := rawConfig.(*DokodemoConfig); ok {
  177. receiverSettings.ReceiveOriginalDestination = dokodemoConfig.Redirect
  178. }
  179. ts, err := rawConfig.(Buildable).Build()
  180. if err != nil {
  181. return nil, err
  182. }
  183. return &core.InboundHandlerConfig{
  184. Tag: c.Tag,
  185. ReceiverSettings: serial.ToTypedMessage(receiverSettings),
  186. ProxySettings: serial.ToTypedMessage(ts),
  187. }, nil
  188. }
  189. type OutboundDetourConfig struct {
  190. Protocol string `json:"protocol"`
  191. SendThrough *Address `json:"sendThrough"`
  192. Tag string `json:"tag"`
  193. Settings *json.RawMessage `json:"settings"`
  194. StreamSetting *StreamConfig `json:"streamSettings"`
  195. ProxySettings *ProxyConfig `json:"proxySettings"`
  196. MuxSettings *MuxConfig `json:"mux"`
  197. }
  198. // Build implements Buildable.
  199. func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
  200. senderSettings := &proxyman.SenderConfig{}
  201. if c.SendThrough != nil {
  202. address := c.SendThrough
  203. if address.Family().IsDomain() {
  204. return nil, newError("unable to send through: " + address.String())
  205. }
  206. senderSettings.Via = address.Build()
  207. }
  208. if c.StreamSetting != nil {
  209. ss, err := c.StreamSetting.Build()
  210. if err != nil {
  211. return nil, err
  212. }
  213. senderSettings.StreamSettings = ss
  214. }
  215. if c.ProxySettings != nil {
  216. ps, err := c.ProxySettings.Build()
  217. if err != nil {
  218. return nil, newError("invalid outbound detour proxy settings.").Base(err)
  219. }
  220. senderSettings.ProxySettings = ps
  221. }
  222. if c.MuxSettings != nil && c.MuxSettings.Enabled {
  223. senderSettings.MultiplexSettings = &proxyman.MultiplexingConfig{
  224. Enabled: true,
  225. Concurrency: uint32(c.MuxSettings.GetConcurrency()),
  226. }
  227. }
  228. settings := []byte("{}")
  229. if c.Settings != nil {
  230. settings = ([]byte)(*c.Settings)
  231. }
  232. rawConfig, err := outboundConfigLoader.LoadWithID(settings, c.Protocol)
  233. if err != nil {
  234. return nil, newError("failed to parse to outbound detour config.").Base(err)
  235. }
  236. ts, err := rawConfig.(Buildable).Build()
  237. if err != nil {
  238. return nil, err
  239. }
  240. return &core.OutboundHandlerConfig{
  241. SenderSettings: serial.ToTypedMessage(senderSettings),
  242. Tag: c.Tag,
  243. ProxySettings: serial.ToTypedMessage(ts),
  244. }, nil
  245. }
  246. type StatsConfig struct{}
  247. func (c *StatsConfig) Build() (*stats.Config, error) {
  248. return &stats.Config{}, nil
  249. }
  250. type Config struct {
  251. Port uint16 `json:"port"` // Port of this Point server. Deprecated.
  252. LogConfig *LogConfig `json:"log"`
  253. RouterConfig *RouterConfig `json:"routing"`
  254. DNSConfig *DnsConfig `json:"dns"`
  255. InboundConfigs []InboundDetourConfig `json:"inbounds"`
  256. OutboundConfigs []OutboundDetourConfig `json:"outbounds"`
  257. InboundConfig *InboundDetourConfig `json:"inbound"` // Deprecated.
  258. OutboundConfig *OutboundDetourConfig `json:"outbound"` // Deprecated.
  259. InboundDetours []InboundDetourConfig `json:"inboundDetour"` // Deprecated.
  260. OutboundDetours []OutboundDetourConfig `json:"outboundDetour"` // Deprecated.
  261. Transport *TransportConfig `json:"transport"`
  262. Policy *PolicyConfig `json:"policy"`
  263. Api *ApiConfig `json:"api"`
  264. Stats *StatsConfig `json:"stats"`
  265. Reverse *ReverseConfig `json:"reverse"`
  266. }
  267. func applyTransportConfig(s *StreamConfig, t *TransportConfig) {
  268. if s.TCPSettings == nil {
  269. s.TCPSettings = t.TCPConfig
  270. }
  271. if s.KCPSettings == nil {
  272. s.KCPSettings = t.KCPConfig
  273. }
  274. if s.WSSettings == nil {
  275. s.WSSettings = t.WSConfig
  276. }
  277. if s.HTTPSettings == nil {
  278. s.HTTPSettings = t.HTTPConfig
  279. }
  280. if s.DSSettings == nil {
  281. s.DSSettings = t.DSConfig
  282. }
  283. }
  284. // Build implements Buildable.
  285. func (c *Config) Build() (*core.Config, error) {
  286. config := &core.Config{
  287. App: []*serial.TypedMessage{
  288. serial.ToTypedMessage(&dispatcher.Config{}),
  289. serial.ToTypedMessage(&proxyman.InboundConfig{}),
  290. serial.ToTypedMessage(&proxyman.OutboundConfig{}),
  291. },
  292. }
  293. if c.Api != nil {
  294. apiConf, err := c.Api.Build()
  295. if err != nil {
  296. return nil, err
  297. }
  298. config.App = append(config.App, serial.ToTypedMessage(apiConf))
  299. }
  300. if c.Stats != nil {
  301. statsConf, err := c.Stats.Build()
  302. if err != nil {
  303. return nil, err
  304. }
  305. config.App = append(config.App, serial.ToTypedMessage(statsConf))
  306. }
  307. var logConfMsg *serial.TypedMessage
  308. if c.LogConfig != nil {
  309. logConfMsg = serial.ToTypedMessage(c.LogConfig.Build())
  310. } else {
  311. logConfMsg = serial.ToTypedMessage(DefaultLogConfig())
  312. }
  313. // let logger module be the first App to start,
  314. // so that other modules could print log during initiating
  315. config.App = append([]*serial.TypedMessage{logConfMsg}, config.App...)
  316. if c.RouterConfig != nil {
  317. routerConfig, err := c.RouterConfig.Build()
  318. if err != nil {
  319. return nil, err
  320. }
  321. config.App = append(config.App, serial.ToTypedMessage(routerConfig))
  322. }
  323. if c.DNSConfig != nil {
  324. dnsApp, err := c.DNSConfig.Build()
  325. if err != nil {
  326. return nil, newError("failed to parse DNS config").Base(err)
  327. }
  328. config.App = append(config.App, serial.ToTypedMessage(dnsApp))
  329. }
  330. if c.Policy != nil {
  331. pc, err := c.Policy.Build()
  332. if err != nil {
  333. return nil, err
  334. }
  335. config.App = append(config.App, serial.ToTypedMessage(pc))
  336. }
  337. if c.Reverse != nil {
  338. r, err := c.Reverse.Build()
  339. if err != nil {
  340. return nil, err
  341. }
  342. config.App = append(config.App, serial.ToTypedMessage(r))
  343. }
  344. var inbounds []InboundDetourConfig
  345. if c.InboundConfig != nil {
  346. inbounds = append(inbounds, *c.InboundConfig)
  347. }
  348. if len(c.InboundDetours) > 0 {
  349. inbounds = append(inbounds, c.InboundDetours...)
  350. }
  351. if len(c.InboundConfigs) > 0 {
  352. inbounds = append(inbounds, c.InboundConfigs...)
  353. }
  354. // Backward compatibility.
  355. if len(inbounds) > 0 && inbounds[0].PortRange == nil && c.Port > 0 {
  356. inbounds[0].PortRange = &PortRange{
  357. From: uint32(c.Port),
  358. To: uint32(c.Port),
  359. }
  360. }
  361. for _, rawInboundConfig := range inbounds {
  362. if c.Transport != nil {
  363. if rawInboundConfig.StreamSetting == nil {
  364. rawInboundConfig.StreamSetting = &StreamConfig{}
  365. }
  366. applyTransportConfig(rawInboundConfig.StreamSetting, c.Transport)
  367. }
  368. ic, err := rawInboundConfig.Build()
  369. if err != nil {
  370. return nil, err
  371. }
  372. config.Inbound = append(config.Inbound, ic)
  373. }
  374. var outbounds []OutboundDetourConfig
  375. if c.OutboundConfig != nil {
  376. outbounds = append(outbounds, *c.OutboundConfig)
  377. }
  378. if len(c.OutboundDetours) > 0 {
  379. outbounds = append(outbounds, c.OutboundDetours...)
  380. }
  381. if len(c.OutboundConfigs) > 0 {
  382. outbounds = append(outbounds, c.OutboundConfigs...)
  383. }
  384. for _, rawOutboundConfig := range outbounds {
  385. if c.Transport != nil {
  386. if rawOutboundConfig.StreamSetting == nil {
  387. rawOutboundConfig.StreamSetting = &StreamConfig{}
  388. }
  389. applyTransportConfig(rawOutboundConfig.StreamSetting, c.Transport)
  390. }
  391. oc, err := rawOutboundConfig.Build()
  392. if err != nil {
  393. return nil, err
  394. }
  395. config.Outbound = append(config.Outbound, oc)
  396. }
  397. return config, nil
  398. }