v2ray.go 16 KB

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