connection_handler.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package socks
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. )
  7. // ConnectionHandler is the Serve method to handle connections
  8. // from a local TCP listener of the standard library (net.Listener)
  9. type ConnectionHandler interface {
  10. Serve(io.ReadWriter) error
  11. }
  12. // StandardConnectionHandler is the base implementation of handling SOCKS5 requests
  13. type StandardConnectionHandler struct {
  14. requestHandler RequestHandler
  15. authHandler AuthHandler
  16. }
  17. // NewConnectionHandler creates a standard SOCKS5 connection handler
  18. // This process connections from a generic TCP listener from the standard library
  19. func NewConnectionHandler(requestHandler RequestHandler) ConnectionHandler {
  20. return &StandardConnectionHandler{
  21. requestHandler: requestHandler,
  22. authHandler: NewAuthHandler(),
  23. }
  24. }
  25. // Serve process new connection created after calling `Accept()` in the standard library
  26. func (h *StandardConnectionHandler) Serve(c io.ReadWriter) error {
  27. bufConn := bufio.NewReader(c)
  28. // read the version byte
  29. version := []byte{0}
  30. if _, err := bufConn.Read(version); err != nil {
  31. return err
  32. }
  33. // ensure compatibility
  34. if version[0] != socks5Version {
  35. return fmt.Errorf("Unsupported SOCKS version: %v", version)
  36. }
  37. // handle auth
  38. if err := h.authHandler.Handle(bufConn, c); err != nil {
  39. return err
  40. }
  41. // process command/request
  42. req, err := NewRequest(bufConn)
  43. if err != nil {
  44. return err
  45. }
  46. return h.requestHandler.Handle(req, c)
  47. }