outbound.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. "github.com/v2ray/v2ray-core/config"
  9. jsonconfig "github.com/v2ray/v2ray-core/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. ip := net.ParseIP(rawConfig.Address)
  33. if ip == nil {
  34. log.Error("Unable to parse IP: %s", rawConfig.Address)
  35. return config.BadConfiguration
  36. }
  37. t.Address = v2net.IPAddress(ip, rawConfig.Port)
  38. if rawConfig.HasNetwork("tcp") {
  39. t.TCPEnabled = true
  40. }
  41. if rawConfig.HasNetwork("udp") {
  42. t.UDPEnabled = true
  43. }
  44. return nil
  45. }
  46. type Outbound struct {
  47. TargetList []*ConfigTarget `json:"vnext"`
  48. }
  49. func (o *Outbound) Targets() []*vmessconfig.OutboundTarget {
  50. targets := make([]*vmessconfig.OutboundTarget, 0, 2*len(o.TargetList))
  51. for _, rawTarget := range o.TargetList {
  52. users := make([]vmessconfig.User, 0, len(rawTarget.Users))
  53. for _, rawUser := range rawTarget.Users {
  54. users = append(users, rawUser)
  55. }
  56. if rawTarget.TCPEnabled {
  57. targets = append(targets, &vmessconfig.OutboundTarget{
  58. Destination: v2net.NewTCPDestination(rawTarget.Address),
  59. Accounts: users,
  60. })
  61. }
  62. if rawTarget.UDPEnabled {
  63. targets = append(targets, &vmessconfig.OutboundTarget{
  64. Destination: v2net.NewUDPDestination(rawTarget.Address),
  65. Accounts: users,
  66. })
  67. }
  68. }
  69. return targets
  70. }
  71. func init() {
  72. jsonconfig.RegisterConfigType("vmess", config.TypeOutbound, func() interface{} {
  73. return new(Outbound)
  74. })
  75. }