v2ray.go 16 KB

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