config.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package json
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "net"
  6. "github.com/v2ray/v2ray-core/proxy/internal/config"
  7. jsonconfig "github.com/v2ray/v2ray-core/proxy/internal/config/json"
  8. )
  9. const (
  10. AuthMethodNoAuth = "noauth"
  11. AuthMethodUserPass = "password"
  12. )
  13. type SocksAccount struct {
  14. Username string `json:"user"`
  15. Password string `json:"pass"`
  16. }
  17. type SocksAccountMap map[string]string
  18. func (this *SocksAccountMap) UnmarshalJSON(data []byte) error {
  19. var accounts []SocksAccount
  20. err := json.Unmarshal(data, &accounts)
  21. if err != nil {
  22. return err
  23. }
  24. *this = make(map[string]string)
  25. for _, account := range accounts {
  26. (*this)[account.Username] = account.Password
  27. }
  28. return nil
  29. }
  30. func (this *SocksAccountMap) HasAccount(user, pass string) bool {
  31. if actualPass, found := (*this)[user]; found {
  32. return actualPass == pass
  33. }
  34. return false
  35. }
  36. type IPAddress net.IP
  37. func (this *IPAddress) UnmarshalJSON(data []byte) error {
  38. var ipStr string
  39. err := json.Unmarshal(data, &ipStr)
  40. if err != nil {
  41. return err
  42. }
  43. ip := net.ParseIP(ipStr)
  44. if ip == nil {
  45. return errors.New("Unknown IP format: " + ipStr)
  46. }
  47. *this = IPAddress(ip)
  48. return nil
  49. }
  50. type SocksConfig struct {
  51. AuthMethod string `json:"auth"`
  52. Accounts SocksAccountMap `json:"accounts"`
  53. UDP bool `json:"udp"`
  54. HostIP IPAddress `json:"ip"`
  55. }
  56. func (sc *SocksConfig) IsNoAuth() bool {
  57. return sc.AuthMethod == AuthMethodNoAuth
  58. }
  59. func (sc *SocksConfig) IsPassword() bool {
  60. return sc.AuthMethod == AuthMethodUserPass
  61. }
  62. func (sc *SocksConfig) HasAccount(user, pass string) bool {
  63. return sc.Accounts.HasAccount(user, pass)
  64. }
  65. func (sc *SocksConfig) IP() net.IP {
  66. return net.IP(sc.HostIP)
  67. }
  68. func (this *SocksConfig) UDPEnabled() bool {
  69. return this.UDP
  70. }
  71. func init() {
  72. config.RegisterInboundConnectionConfig("socks", jsonconfig.JsonConfigLoader(func() interface{} {
  73. return &SocksConfig{
  74. HostIP: IPAddress(net.IPv4(127, 0, 0, 1)),
  75. }
  76. }))
  77. }