v2ray.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 applyTransportConfig(s *StreamConfig, t *TransportConfig) {
  273. if s.TCPSettings == nil {
  274. s.TCPSettings = t.TCPConfig
  275. }
  276. if s.KCPSettings == nil {
  277. s.KCPSettings = t.KCPConfig
  278. }
  279. if s.WSSettings == nil {
  280. s.WSSettings = t.WSConfig
  281. }
  282. if s.HTTPSettings == nil {
  283. s.HTTPSettings = t.HTTPConfig
  284. }
  285. if s.DSSettings == nil {
  286. s.DSSettings = t.DSConfig
  287. }
  288. }
  289. // Build implements Buildable.
  290. func (c *Config) Build() (*core.Config, error) {
  291. config := &core.Config{
  292. App: []*serial.TypedMessage{
  293. serial.ToTypedMessage(&dispatcher.Config{}),
  294. serial.ToTypedMessage(&proxyman.InboundConfig{}),
  295. serial.ToTypedMessage(&proxyman.OutboundConfig{}),
  296. },
  297. }
  298. if c.Api != nil {
  299. apiConf, err := c.Api.Build()
  300. if err != nil {
  301. return nil, err
  302. }
  303. config.App = append(config.App, serial.ToTypedMessage(apiConf))
  304. }
  305. if c.Stats != nil {
  306. statsConf, err := c.Stats.Build()
  307. if err != nil {
  308. return nil, err
  309. }
  310. config.App = append(config.App, serial.ToTypedMessage(statsConf))
  311. }
  312. var logConfMsg *serial.TypedMessage
  313. if c.LogConfig != nil {
  314. logConfMsg = serial.ToTypedMessage(c.LogConfig.Build())
  315. } else {
  316. logConfMsg = serial.ToTypedMessage(DefaultLogConfig())
  317. }
  318. // let logger module be the first App to start,
  319. // so that other modules could print log during initiating
  320. config.App = append([]*serial.TypedMessage{logConfMsg}, config.App...)
  321. if c.RouterConfig != nil {
  322. routerConfig, err := c.RouterConfig.Build()
  323. if err != nil {
  324. return nil, err
  325. }
  326. config.App = append(config.App, serial.ToTypedMessage(routerConfig))
  327. }
  328. if c.DNSConfig != nil {
  329. dnsApp, err := c.DNSConfig.Build()
  330. if err != nil {
  331. return nil, newError("failed to parse DNS config").Base(err)
  332. }
  333. config.App = append(config.App, serial.ToTypedMessage(dnsApp))
  334. }
  335. if c.Policy != nil {
  336. pc, err := c.Policy.Build()
  337. if err != nil {
  338. return nil, err
  339. }
  340. config.App = append(config.App, serial.ToTypedMessage(pc))
  341. }
  342. if c.Reverse != nil {
  343. r, err := c.Reverse.Build()
  344. if err != nil {
  345. return nil, err
  346. }
  347. config.App = append(config.App, serial.ToTypedMessage(r))
  348. }
  349. var inbounds []InboundDetourConfig
  350. if c.InboundConfig != nil {
  351. inbounds = append(inbounds, *c.InboundConfig)
  352. }
  353. if len(c.InboundDetours) > 0 {
  354. inbounds = append(inbounds, c.InboundDetours...)
  355. }
  356. if len(c.InboundConfigs) > 0 {
  357. inbounds = append(inbounds, c.InboundConfigs...)
  358. }
  359. // Backward compatibility.
  360. if len(inbounds) > 0 && inbounds[0].PortRange == nil && c.Port > 0 {
  361. inbounds[0].PortRange = &PortRange{
  362. From: uint32(c.Port),
  363. To: uint32(c.Port),
  364. }
  365. }
  366. for _, rawInboundConfig := range inbounds {
  367. if c.Transport != nil {
  368. if rawInboundConfig.StreamSetting == nil {
  369. rawInboundConfig.StreamSetting = &StreamConfig{}
  370. }
  371. applyTransportConfig(rawInboundConfig.StreamSetting, c.Transport)
  372. }
  373. ic, err := rawInboundConfig.Build()
  374. if err != nil {
  375. return nil, err
  376. }
  377. config.Inbound = append(config.Inbound, ic)
  378. }
  379. var outbounds []OutboundDetourConfig
  380. if c.OutboundConfig != nil {
  381. outbounds = append(outbounds, *c.OutboundConfig)
  382. }
  383. if len(c.OutboundDetours) > 0 {
  384. outbounds = append(outbounds, c.OutboundDetours...)
  385. }
  386. if len(c.OutboundConfigs) > 0 {
  387. outbounds = append(outbounds, c.OutboundConfigs...)
  388. }
  389. for _, rawOutboundConfig := range outbounds {
  390. if c.Transport != nil {
  391. if rawOutboundConfig.StreamSetting == nil {
  392. rawOutboundConfig.StreamSetting = &StreamConfig{}
  393. }
  394. applyTransportConfig(rawOutboundConfig.StreamSetting, c.Transport)
  395. }
  396. oc, err := rawOutboundConfig.Build()
  397. if err != nil {
  398. return nil, err
  399. }
  400. config.Outbound = append(config.Outbound, oc)
  401. }
  402. return config, nil
  403. }