v2ray.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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.ListenOn == nil {
  140. // Listen on anyip, must set PortRange
  141. if c.PortRange == nil {
  142. return nil, newError("Listen on AnyIP but no Port(s) set in InboundDetour.")
  143. }
  144. receiverSettings.PortRange = c.PortRange.Build()
  145. } else {
  146. // Listen on specific IP or Unix Domain Socket
  147. receiverSettings.Listen = c.ListenOn.Build()
  148. listenDS := c.ListenOn.Family().IsDomain() && (c.ListenOn.Domain()[0] == '/' || c.ListenOn.Domain()[0] == '@')
  149. listenIP := c.ListenOn.Family().IsIP() || (c.ListenOn.Family().IsDomain() && c.ListenOn.Domain() == "localhost")
  150. if listenIP {
  151. // Listen on specific IP, must set PortRange
  152. if c.PortRange == nil {
  153. return nil, newError("Listen on specific ip without port in InboundDetour.")
  154. }
  155. // Listen on IP:Port
  156. receiverSettings.PortRange = c.PortRange.Build()
  157. } else if listenDS {
  158. if c.PortRange != nil {
  159. // Listen on Unix Domain Socket, PortRange should be nil
  160. receiverSettings.PortRange = nil
  161. }
  162. } else {
  163. return nil, newError("unable to listen on domain address: ", c.ListenOn.Domain())
  164. }
  165. }
  166. if c.Allocation != nil {
  167. concurrency := -1
  168. if c.Allocation.Concurrency != nil && c.Allocation.Strategy == "random" {
  169. concurrency = int(*c.Allocation.Concurrency)
  170. }
  171. portRange := int(c.PortRange.To - c.PortRange.From + 1)
  172. if concurrency >= 0 && concurrency >= portRange {
  173. return nil, newError("not enough ports. concurrency = ", concurrency, " ports: ", c.PortRange.From, " - ", c.PortRange.To)
  174. }
  175. as, err := c.Allocation.Build()
  176. if err != nil {
  177. return nil, err
  178. }
  179. receiverSettings.AllocationStrategy = as
  180. }
  181. if c.StreamSetting != nil {
  182. ss, err := c.StreamSetting.Build()
  183. if err != nil {
  184. return nil, err
  185. }
  186. if ss.SecurityType == serial.GetMessageType(&xtls.Config{}) && !strings.EqualFold(c.Protocol, "vless") && !strings.EqualFold(c.Protocol, "trojan") {
  187. return nil, newError("XTLS doesn't supports " + c.Protocol + " for now.")
  188. }
  189. receiverSettings.StreamSettings = ss
  190. }
  191. if c.SniffingConfig != nil {
  192. s, err := c.SniffingConfig.Build()
  193. if err != nil {
  194. return nil, newError("failed to build sniffing config").Base(err)
  195. }
  196. receiverSettings.SniffingSettings = s
  197. }
  198. if c.DomainOverride != nil {
  199. kp, err := toProtocolList(*c.DomainOverride)
  200. if err != nil {
  201. return nil, newError("failed to parse inbound detour config").Base(err)
  202. }
  203. receiverSettings.DomainOverride = kp
  204. }
  205. settings := []byte("{}")
  206. if c.Settings != nil {
  207. settings = ([]byte)(*c.Settings)
  208. }
  209. rawConfig, err := inboundConfigLoader.LoadWithID(settings, c.Protocol)
  210. if err != nil {
  211. return nil, newError("failed to load inbound detour config.").Base(err)
  212. }
  213. if dokodemoConfig, ok := rawConfig.(*DokodemoConfig); ok {
  214. receiverSettings.ReceiveOriginalDestination = dokodemoConfig.Redirect
  215. }
  216. ts, err := rawConfig.(Buildable).Build()
  217. if err != nil {
  218. return nil, err
  219. }
  220. return &core.InboundHandlerConfig{
  221. Tag: c.Tag,
  222. ReceiverSettings: serial.ToTypedMessage(receiverSettings),
  223. ProxySettings: serial.ToTypedMessage(ts),
  224. }, nil
  225. }
  226. type OutboundDetourConfig struct {
  227. Protocol string `json:"protocol"`
  228. SendThrough *Address `json:"sendThrough"`
  229. Tag string `json:"tag"`
  230. Settings *json.RawMessage `json:"settings"`
  231. StreamSetting *StreamConfig `json:"streamSettings"`
  232. ProxySettings *ProxyConfig `json:"proxySettings"`
  233. MuxSettings *MuxConfig `json:"mux"`
  234. }
  235. // Build implements Buildable.
  236. func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
  237. senderSettings := &proxyman.SenderConfig{}
  238. if c.SendThrough != nil {
  239. address := c.SendThrough
  240. if address.Family().IsDomain() {
  241. return nil, newError("unable to send through: " + address.String())
  242. }
  243. senderSettings.Via = address.Build()
  244. }
  245. if c.StreamSetting != nil {
  246. ss, err := c.StreamSetting.Build()
  247. if err != nil {
  248. return nil, err
  249. }
  250. if ss.SecurityType == serial.GetMessageType(&xtls.Config{}) && !strings.EqualFold(c.Protocol, "vless") && !strings.EqualFold(c.Protocol, "trojan") {
  251. return nil, newError("XTLS doesn't supports " + c.Protocol + " for now.")
  252. }
  253. senderSettings.StreamSettings = ss
  254. }
  255. if c.ProxySettings != nil {
  256. ps, err := c.ProxySettings.Build()
  257. if err != nil {
  258. return nil, newError("invalid outbound detour proxy settings.").Base(err)
  259. }
  260. senderSettings.ProxySettings = ps
  261. }
  262. if c.MuxSettings != nil {
  263. ms := c.MuxSettings.Build()
  264. if ms != nil && ms.Enabled {
  265. if ss := senderSettings.StreamSettings; ss != nil {
  266. if ss.SecurityType == serial.GetMessageType(&xtls.Config{}) {
  267. return nil, newError("XTLS doesn't support Mux for now.")
  268. }
  269. }
  270. }
  271. senderSettings.MultiplexSettings = ms
  272. }
  273. settings := []byte("{}")
  274. if c.Settings != nil {
  275. settings = ([]byte)(*c.Settings)
  276. }
  277. rawConfig, err := outboundConfigLoader.LoadWithID(settings, c.Protocol)
  278. if err != nil {
  279. return nil, newError("failed to parse to outbound detour config.").Base(err)
  280. }
  281. ts, err := rawConfig.(Buildable).Build()
  282. if err != nil {
  283. return nil, err
  284. }
  285. return &core.OutboundHandlerConfig{
  286. SenderSettings: serial.ToTypedMessage(senderSettings),
  287. Tag: c.Tag,
  288. ProxySettings: serial.ToTypedMessage(ts),
  289. }, nil
  290. }
  291. type StatsConfig struct{}
  292. // Build implements Buildable.
  293. func (c *StatsConfig) Build() (*stats.Config, error) {
  294. return &stats.Config{}, nil
  295. }
  296. type Config struct {
  297. Port uint16 `json:"port"` // Port of this Point server. Deprecated.
  298. LogConfig *LogConfig `json:"log"`
  299. RouterConfig *RouterConfig `json:"routing"`
  300. DNSConfig *DNSConfig `json:"dns"`
  301. InboundConfigs []InboundDetourConfig `json:"inbounds"`
  302. OutboundConfigs []OutboundDetourConfig `json:"outbounds"`
  303. InboundConfig *InboundDetourConfig `json:"inbound"` // Deprecated.
  304. OutboundConfig *OutboundDetourConfig `json:"outbound"` // Deprecated.
  305. InboundDetours []InboundDetourConfig `json:"inboundDetour"` // Deprecated.
  306. OutboundDetours []OutboundDetourConfig `json:"outboundDetour"` // Deprecated.
  307. Transport *TransportConfig `json:"transport"`
  308. Policy *PolicyConfig `json:"policy"`
  309. API *APIConfig `json:"api"`
  310. Stats *StatsConfig `json:"stats"`
  311. Reverse *ReverseConfig `json:"reverse"`
  312. }
  313. func (c *Config) findInboundTag(tag string) int {
  314. found := -1
  315. for idx, ib := range c.InboundConfigs {
  316. if ib.Tag == tag {
  317. found = idx
  318. break
  319. }
  320. }
  321. return found
  322. }
  323. func (c *Config) findOutboundTag(tag string) int {
  324. found := -1
  325. for idx, ob := range c.OutboundConfigs {
  326. if ob.Tag == tag {
  327. found = idx
  328. break
  329. }
  330. }
  331. return found
  332. }
  333. // Override method accepts another Config overrides the current attribute
  334. func (c *Config) Override(o *Config, fn string) {
  335. // only process the non-deprecated members
  336. if o.LogConfig != nil {
  337. c.LogConfig = o.LogConfig
  338. }
  339. if o.RouterConfig != nil {
  340. c.RouterConfig = o.RouterConfig
  341. }
  342. if o.DNSConfig != nil {
  343. c.DNSConfig = o.DNSConfig
  344. }
  345. if o.Transport != nil {
  346. c.Transport = o.Transport
  347. }
  348. if o.Policy != nil {
  349. c.Policy = o.Policy
  350. }
  351. if o.API != nil {
  352. c.API = o.API
  353. }
  354. if o.Stats != nil {
  355. c.Stats = o.Stats
  356. }
  357. if o.Reverse != nil {
  358. c.Reverse = o.Reverse
  359. }
  360. // deprecated attrs... keep them for now
  361. if o.InboundConfig != nil {
  362. c.InboundConfig = o.InboundConfig
  363. }
  364. if o.OutboundConfig != nil {
  365. c.OutboundConfig = o.OutboundConfig
  366. }
  367. if o.InboundDetours != nil {
  368. c.InboundDetours = o.InboundDetours
  369. }
  370. if o.OutboundDetours != nil {
  371. c.OutboundDetours = o.OutboundDetours
  372. }
  373. // deprecated attrs
  374. // update the Inbound in slice if the only one in overide config has same tag
  375. if len(o.InboundConfigs) > 0 {
  376. if len(c.InboundConfigs) > 0 && len(o.InboundConfigs) == 1 {
  377. if idx := c.findInboundTag(o.InboundConfigs[0].Tag); idx > -1 {
  378. c.InboundConfigs[idx] = o.InboundConfigs[0]
  379. ctllog.Println("[", fn, "] updated inbound with tag: ", o.InboundConfigs[0].Tag)
  380. } else {
  381. c.InboundConfigs = append(c.InboundConfigs, o.InboundConfigs[0])
  382. ctllog.Println("[", fn, "] appended inbound with tag: ", o.InboundConfigs[0].Tag)
  383. }
  384. } else {
  385. c.InboundConfigs = o.InboundConfigs
  386. }
  387. }
  388. // update the Outbound in slice if the only one in overide config has same tag
  389. if len(o.OutboundConfigs) > 0 {
  390. if len(c.OutboundConfigs) > 0 && len(o.OutboundConfigs) == 1 {
  391. if idx := c.findOutboundTag(o.OutboundConfigs[0].Tag); idx > -1 {
  392. c.OutboundConfigs[idx] = o.OutboundConfigs[0]
  393. ctllog.Println("[", fn, "] updated outbound with tag: ", o.OutboundConfigs[0].Tag)
  394. } else {
  395. if strings.Contains(strings.ToLower(fn), "tail") {
  396. c.OutboundConfigs = append(c.OutboundConfigs, o.OutboundConfigs[0])
  397. ctllog.Println("[", fn, "] appended outbound with tag: ", o.OutboundConfigs[0].Tag)
  398. } else {
  399. c.OutboundConfigs = append(o.OutboundConfigs, c.OutboundConfigs...)
  400. ctllog.Println("[", fn, "] prepended outbound with tag: ", o.OutboundConfigs[0].Tag)
  401. }
  402. }
  403. } else {
  404. c.OutboundConfigs = o.OutboundConfigs
  405. }
  406. }
  407. }
  408. func applyTransportConfig(s *StreamConfig, t *TransportConfig) {
  409. if s.TCPSettings == nil {
  410. s.TCPSettings = t.TCPConfig
  411. }
  412. if s.KCPSettings == nil {
  413. s.KCPSettings = t.KCPConfig
  414. }
  415. if s.WSSettings == nil {
  416. s.WSSettings = t.WSConfig
  417. }
  418. if s.HTTPSettings == nil {
  419. s.HTTPSettings = t.HTTPConfig
  420. }
  421. if s.DSSettings == nil {
  422. s.DSSettings = t.DSConfig
  423. }
  424. }
  425. // Build implements Buildable.
  426. func (c *Config) Build() (*core.Config, error) {
  427. config := &core.Config{
  428. App: []*serial.TypedMessage{
  429. serial.ToTypedMessage(&dispatcher.Config{}),
  430. serial.ToTypedMessage(&proxyman.InboundConfig{}),
  431. serial.ToTypedMessage(&proxyman.OutboundConfig{}),
  432. },
  433. }
  434. if c.API != nil {
  435. apiConf, err := c.API.Build()
  436. if err != nil {
  437. return nil, err
  438. }
  439. config.App = append(config.App, serial.ToTypedMessage(apiConf))
  440. }
  441. if c.Stats != nil {
  442. statsConf, err := c.Stats.Build()
  443. if err != nil {
  444. return nil, err
  445. }
  446. config.App = append(config.App, serial.ToTypedMessage(statsConf))
  447. }
  448. var logConfMsg *serial.TypedMessage
  449. if c.LogConfig != nil {
  450. logConfMsg = serial.ToTypedMessage(c.LogConfig.Build())
  451. } else {
  452. logConfMsg = serial.ToTypedMessage(DefaultLogConfig())
  453. }
  454. // let logger module be the first App to start,
  455. // so that other modules could print log during initiating
  456. config.App = append([]*serial.TypedMessage{logConfMsg}, config.App...)
  457. if c.RouterConfig != nil {
  458. routerConfig, err := c.RouterConfig.Build()
  459. if err != nil {
  460. return nil, err
  461. }
  462. config.App = append(config.App, serial.ToTypedMessage(routerConfig))
  463. }
  464. if c.DNSConfig != nil {
  465. dnsApp, err := c.DNSConfig.Build()
  466. if err != nil {
  467. return nil, newError("failed to parse DNS config").Base(err)
  468. }
  469. config.App = append(config.App, serial.ToTypedMessage(dnsApp))
  470. }
  471. if c.Policy != nil {
  472. pc, err := c.Policy.Build()
  473. if err != nil {
  474. return nil, err
  475. }
  476. config.App = append(config.App, serial.ToTypedMessage(pc))
  477. }
  478. if c.Reverse != nil {
  479. r, err := c.Reverse.Build()
  480. if err != nil {
  481. return nil, err
  482. }
  483. config.App = append(config.App, serial.ToTypedMessage(r))
  484. }
  485. var inbounds []InboundDetourConfig
  486. if c.InboundConfig != nil {
  487. inbounds = append(inbounds, *c.InboundConfig)
  488. }
  489. if len(c.InboundDetours) > 0 {
  490. inbounds = append(inbounds, c.InboundDetours...)
  491. }
  492. if len(c.InboundConfigs) > 0 {
  493. inbounds = append(inbounds, c.InboundConfigs...)
  494. }
  495. // Backward compatibility.
  496. if len(inbounds) > 0 && inbounds[0].PortRange == nil && c.Port > 0 {
  497. inbounds[0].PortRange = &PortRange{
  498. From: uint32(c.Port),
  499. To: uint32(c.Port),
  500. }
  501. }
  502. for _, rawInboundConfig := range inbounds {
  503. if c.Transport != nil {
  504. if rawInboundConfig.StreamSetting == nil {
  505. rawInboundConfig.StreamSetting = &StreamConfig{}
  506. }
  507. applyTransportConfig(rawInboundConfig.StreamSetting, c.Transport)
  508. }
  509. ic, err := rawInboundConfig.Build()
  510. if err != nil {
  511. return nil, err
  512. }
  513. config.Inbound = append(config.Inbound, ic)
  514. }
  515. var outbounds []OutboundDetourConfig
  516. if c.OutboundConfig != nil {
  517. outbounds = append(outbounds, *c.OutboundConfig)
  518. }
  519. if len(c.OutboundDetours) > 0 {
  520. outbounds = append(outbounds, c.OutboundDetours...)
  521. }
  522. if len(c.OutboundConfigs) > 0 {
  523. outbounds = append(outbounds, c.OutboundConfigs...)
  524. }
  525. for _, rawOutboundConfig := range outbounds {
  526. if c.Transport != nil {
  527. if rawOutboundConfig.StreamSetting == nil {
  528. rawOutboundConfig.StreamSetting = &StreamConfig{}
  529. }
  530. applyTransportConfig(rawOutboundConfig.StreamSetting, c.Transport)
  531. }
  532. oc, err := rawOutboundConfig.Build()
  533. if err != nil {
  534. return nil, err
  535. }
  536. config.Outbound = append(config.Outbound, oc)
  537. }
  538. return config, nil
  539. }