config.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package socks
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "v2ray.com/core/common"
  6. "v2ray.com/core/common/log"
  7. v2net "v2ray.com/core/common/net"
  8. "v2ray.com/core/common/protocol"
  9. "github.com/golang/protobuf/ptypes"
  10. google_protobuf "github.com/golang/protobuf/ptypes/any"
  11. )
  12. func (this *Account) Equals(another protocol.Account) bool {
  13. if account, ok := another.(*Account); ok {
  14. return this.Username == account.Username
  15. }
  16. return false
  17. }
  18. func (this *Account) AsAccount() (protocol.Account, error) {
  19. return this, nil
  20. }
  21. func NewAccount() protocol.AsAccount {
  22. return &Account{}
  23. }
  24. func (this *Account) AsAny() (*google_protobuf.Any, error) {
  25. return ptypes.MarshalAny(this)
  26. }
  27. func (this *ServerConfig) HasAccount(username, password string) bool {
  28. if this.Accounts == nil {
  29. return false
  30. }
  31. storedPassed, found := this.Accounts[username]
  32. if !found {
  33. return false
  34. }
  35. return storedPassed == password
  36. }
  37. func (this *ServerConfig) GetNetAddress() v2net.Address {
  38. if this.Address == nil {
  39. return v2net.LocalHostIP
  40. }
  41. return this.Address.AsAddress()
  42. }
  43. const (
  44. AuthMethodNoAuth = "noauth"
  45. AuthMethodUserPass = "password"
  46. )
  47. func (this *ServerConfig) UnmarshalJSON(data []byte) error {
  48. type SocksConfig struct {
  49. AuthMethod string `json:"auth"`
  50. Accounts []*Account `json:"accounts"`
  51. UDP bool `json:"udp"`
  52. Host *v2net.IPOrDomain `json:"ip"`
  53. Timeout uint32 `json:"timeout"`
  54. }
  55. rawConfig := new(SocksConfig)
  56. if err := json.Unmarshal(data, rawConfig); err != nil {
  57. return errors.New("Socks: Failed to parse config: " + err.Error())
  58. }
  59. if rawConfig.AuthMethod == AuthMethodNoAuth {
  60. this.AuthType = AuthType_NO_AUTH
  61. } else if rawConfig.AuthMethod == AuthMethodUserPass {
  62. this.AuthType = AuthType_PASSWORD
  63. } else {
  64. log.Error("Socks: Unknown auth method: ", rawConfig.AuthMethod)
  65. return common.ErrBadConfiguration
  66. }
  67. if len(rawConfig.Accounts) > 0 {
  68. this.Accounts = make(map[string]string, len(rawConfig.Accounts))
  69. for _, account := range rawConfig.Accounts {
  70. this.Accounts[account.Username] = account.Password
  71. }
  72. }
  73. this.UdpEnabled = rawConfig.UDP
  74. if rawConfig.Host != nil {
  75. this.Address = rawConfig.Host
  76. }
  77. if rawConfig.Timeout >= 0 {
  78. this.Timeout = rawConfig.Timeout
  79. }
  80. return nil
  81. }