1
0

socks5_handshake_handle.go 862 B

123456789101112131415161718192021222324252627282930313233343536
  1. package socks5
  2. import (
  3. "context"
  4. "ehang.io/nps/core"
  5. "errors"
  6. "fmt"
  7. "io"
  8. )
  9. type Handshake struct {
  10. core.NpsPlugin
  11. }
  12. func (handshake *Handshake) Run(ctx context.Context) (context.Context, error) {
  13. clientConn := handshake.GetClientConn(ctx)
  14. buf := make([]byte, 2)
  15. if _, err := io.ReadFull(clientConn, buf); err != nil {
  16. return ctx, errors.New("negotiation err while read 2 bytes from client connection: " + err.Error())
  17. }
  18. if version := buf[0]; version != 5 {
  19. return ctx, errors.New("only support socks5")
  20. }
  21. nMethods := buf[1]
  22. methods := make([]byte, nMethods)
  23. if n, err := clientConn.Read(methods); n != int(nMethods) || err != nil {
  24. return ctx, errors.New(fmt.Sprintf("read methods error, need %d , read %d, error %s", nMethods, n, err.Error()))
  25. } else {
  26. ctx = context.WithValue(ctx, "methods", methods[:n])
  27. }
  28. return ctx, nil
  29. }