socks5_server.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package socks5
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/cnlh/nps/core"
  6. "github.com/cnlh/nps/server/common"
  7. "net"
  8. "strconv"
  9. )
  10. type S5Server struct {
  11. globalConfig map[string]string
  12. clientConfig map[string]string
  13. pluginConfig map[string]string
  14. ServerIp string
  15. ServerPort int
  16. plugins *core.Plugins
  17. listener net.Listener
  18. }
  19. func NewS5Server(globalConfig, clientConfig, pluginConfig map[string]string) *S5Server {
  20. s5 := &S5Server{
  21. globalConfig: globalConfig,
  22. clientConfig: clientConfig,
  23. pluginConfig: pluginConfig,
  24. plugins: &core.Plugins{},
  25. }
  26. s5.plugins.Add(new(Handshake), new(Access), new(CheckAccess), new(Request), new(common.Proxy))
  27. return s5
  28. }
  29. func (s5 *S5Server) Start(ctx context.Context) error {
  30. // init config of plugin
  31. for _, pg := range s5.plugins.AllPgs {
  32. pg.InitConfig(s5.globalConfig, s5.clientConfig, s5.pluginConfig)
  33. }
  34. // run the plugin contains start
  35. if core.RunPlugin(ctx, s5.plugins.StartPgs) != nil {
  36. return nil
  37. }
  38. return core.NewTcpListenerAndProcess(s5.ServerIp+":"+strconv.Itoa(s5.ServerPort), func(c net.Conn) {
  39. // init ctx value clientConn
  40. ctx = context.WithValue(ctx, core.CLIENT_CONNECTION, c)
  41. // start run the plugin run
  42. if err := core.RunPlugin(ctx, s5.plugins.RunPgs); err != nil {
  43. fmt.Println(err)
  44. return
  45. }
  46. // start run the plugin end
  47. if err := core.RunPlugin(ctx, s5.plugins.EndPgs); err != nil {
  48. fmt.Println(err)
  49. return
  50. }
  51. }, &s5.listener)
  52. }