config.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. func (this *SocksAccountMap) HasAccount(user, pass string) bool {
  30. if actualPass, found := (*this)[user]; found {
  31. return actualPass == pass
  32. }
  33. return false
  34. }
  35. type IPAddress net.IP
  36. func (this *IPAddress) UnmarshalJSON(data []byte) error {
  37. var ipStr string
  38. err := json.Unmarshal(data, &ipStr)
  39. if err != nil {
  40. return err
  41. }
  42. ip := net.ParseIP(ipStr)
  43. if ip == nil {
  44. return errors.New("Unknown IP format: " + ipStr)
  45. }
  46. *this = IPAddress(ip)
  47. return nil
  48. }
  49. type SocksConfig struct {
  50. AuthMethod string `json:"auth"`
  51. Accounts SocksAccountMap `json:"accounts"`
  52. UDPEnabled bool `json:"udp"`
  53. HostIP IPAddress `json:"ip"`
  54. }
  55. func (sc *SocksConfig) IsNoAuth() bool {
  56. return sc.AuthMethod == AuthMethodNoAuth
  57. }
  58. func (sc *SocksConfig) IsPassword() bool {
  59. return sc.AuthMethod == AuthMethodUserPass
  60. }
  61. func (sc *SocksConfig) HasAccount(user, pass string) bool {
  62. return sc.Accounts.HasAccount(user, pass)
  63. }
  64. func (sc *SocksConfig) IP() net.IP {
  65. return net.IP(sc.HostIP)
  66. }
  67. func init() {
  68. jsonconfig.RegisterInboundConnectionConfig("socks", func() interface{} {
  69. return &SocksConfig{
  70. HostIP: IPAddress(net.IPv4(127, 0, 0, 1)),
  71. }
  72. })
  73. }