Skip to content

Commit

Permalink
Trojan Protocol Handler implements UserManager (#344)
Browse files Browse the repository at this point in the history
* Trojan Protocol Handler implements UserManager

* Update validator.go

Co-authored-by: RPRX <[email protected]>
  • Loading branch information
maskedeken and RPRX authored Oct 22, 2020
1 parent c325fae commit 24f688c
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 7 deletions.
5 changes: 0 additions & 5 deletions infra/conf/trojan.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,6 @@ type TrojanServerConfig struct {
// Build implements Buildable
func (c *TrojanServerConfig) Build() (proto.Message, error) {
config := new(trojan.ServerConfig)

if len(c.Clients) == 0 {
return nil, newError("No trojan user settings.")
}

config.Users = make([]*protocol.User, len(c.Clients))
for idx, rawUser := range c.Clients {
user := new(protocol.User)
Expand Down
10 changes: 10 additions & 0 deletions proxy/trojan/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,16 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Server, error) {
return server, nil
}

// AddUser implements proxy.UserManager.AddUser().
func (s *Server) AddUser(ctx context.Context, u *protocol.MemoryUser) error {
return s.validator.Add(u)
}

// RemoveUser implements proxy.UserManager.RemoveUser().
func (s *Server) RemoveUser(ctx context.Context, e string) error {
return s.validator.Del(e)
}

// Network implements proxy.Inbound.Network().
func (s *Server) Network() []net.Network {
return []net.Network{net.Network_TCP}
Expand Down
27 changes: 25 additions & 2 deletions proxy/trojan/validator.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,43 @@
package trojan

import (
"strings"
"sync"

"v2ray.com/core/common/protocol"
)

// Validator stores valid trojan users
type Validator struct {
// Considering email's usage here, map + sync.Mutex/RWMutex may have better performance.
email sync.Map
users sync.Map
}

// Add a trojan user
func (v *Validator) Add(u *protocol.MemoryUser) error {
user := u.Account.(*MemoryAccount)
v.users.Store(hexString(user.Key), u)
if u.Email != "" {
_, loaded := v.email.LoadOrStore(strings.ToLower(u.Email), u)
if loaded {
return newError("User ", u.Email, " already exists.")
}
}
v.users.Store(hexString(u.Account.(*MemoryAccount).Key), u)
return nil
}

// Del a trojan user
func (v *Validator) Del(e string) error {
if e == "" {
return newError("Email must not be empty.")
}
le := strings.ToLower(e)
u, _ := v.email.Load(le)
if u == nil {
return newError("User ", e, " not found.")
}
v.email.Delete(le)
v.users.Delete(hexString(u.(*protocol.MemoryUser).Account.(*MemoryAccount).Key))
return nil
}

Expand Down

0 comments on commit 24f688c

Please sign in to comment.