v2ray.go 17 KB

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