config.go 2.4 KB

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