v2ray.go 13 KB

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