config.go 1.7 KB

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