v2ray.go 16 KB

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