config.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. UDP 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 (this *SocksConfig) UDPEnabled() bool {
  68. return this.UDP
  69. }
  70. func init() {
  71. jsonconfig.RegisterInboundConnectionConfig("socks", func() interface{} {
  72. return &SocksConfig{
  73. HostIP: IPAddress(net.IPv4(127, 0, 0, 1)),
  74. }
  75. })
  76. }