outbound.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package json
  2. import (
  3. "encoding/json"
  4. "net"
  5. "strings"
  6. "github.com/v2ray/v2ray-core/common/log"
  7. v2net "github.com/v2ray/v2ray-core/common/net"
  8. proxyconfig "github.com/v2ray/v2ray-core/proxy/common/config"
  9. jsonconfig "github.com/v2ray/v2ray-core/proxy/common/config/json"
  10. vmessconfig "github.com/v2ray/v2ray-core/proxy/vmess/config"
  11. )
  12. type RawConfigTarget struct {
  13. Address string `json:"address"`
  14. Port uint16 `json:"port"`
  15. Users []*ConfigUser `json:"users"`
  16. Network string `json:"network"`
  17. }
  18. func (config RawConfigTarget) HasNetwork(network string) bool {
  19. return strings.Contains(config.Network, network)
  20. }
  21. type ConfigTarget struct {
  22. Address v2net.Address
  23. Users []*ConfigUser
  24. TCPEnabled bool
  25. UDPEnabled bool
  26. }
  27. func (t *ConfigTarget) UnmarshalJSON(data []byte) error {
  28. var rawConfig RawConfigTarget
  29. if err := json.Unmarshal(data, &rawConfig); err != nil {
  30. return err
  31. }
  32. t.Users = rawConfig.Users
  33. ip := net.ParseIP(rawConfig.Address)
  34. if ip == nil {
  35. log.Error("Unable to parse IP: %s", rawConfig.Address)
  36. return proxyconfig.BadConfiguration
  37. }
  38. t.Address = v2net.IPAddress(ip, rawConfig.Port)
  39. if rawConfig.HasNetwork("tcp") {
  40. t.TCPEnabled = true
  41. }
  42. if rawConfig.HasNetwork("udp") {
  43. t.UDPEnabled = true
  44. }
  45. return nil
  46. }
  47. type Outbound struct {
  48. TargetList []*ConfigTarget `json:"vnext"`
  49. }
  50. func (o *Outbound) Targets() []*vmessconfig.OutboundTarget {
  51. targets := make([]*vmessconfig.OutboundTarget, 0, 2*len(o.TargetList))
  52. for _, rawTarget := range o.TargetList {
  53. users := make([]vmessconfig.User, 0, len(rawTarget.Users))
  54. for _, rawUser := range rawTarget.Users {
  55. users = append(users, rawUser)
  56. }
  57. if rawTarget.TCPEnabled {
  58. targets = append(targets, &vmessconfig.OutboundTarget{
  59. Destination: v2net.NewTCPDestination(rawTarget.Address),
  60. Accounts: users,
  61. })
  62. }
  63. if rawTarget.UDPEnabled {
  64. targets = append(targets, &vmessconfig.OutboundTarget{
  65. Destination: v2net.NewUDPDestination(rawTarget.Address),
  66. Accounts: users,
  67. })
  68. }
  69. }
  70. return targets
  71. }
  72. func init() {
  73. jsonconfig.RegisterOutboundConnectionConfig("vmess", func() interface{} {
  74. return new(Outbound)
  75. })
  76. }