v2ray.go 17 KB

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