socks5_server.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package socks5
  2. import (
  3. "context"
  4. "ehang.io/nps/core"
  5. "ehang.io/nps/server/common"
  6. "fmt"
  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, ServerIp string, ServerPort int) *S5Server {
  20. s5 := &S5Server{
  21. globalConfig: globalConfig,
  22. clientConfig: clientConfig,
  23. pluginConfig: pluginConfig,
  24. plugins: &core.Plugins{},
  25. ServerIp: ServerIp,
  26. ServerPort: ServerPort,
  27. }
  28. s5.plugins.Add(new(Handshake), new(Access), new(CheckAccess), new(Request), new(common.Proxy))
  29. return s5
  30. }
  31. func (s5 *S5Server) Start(ctx context.Context) error {
  32. // init config of plugin
  33. for _, pg := range s5.plugins.AllPgs {
  34. if pg.GetConfigName() != nil {
  35. pg.InitConfig(s5.globalConfig, s5.clientConfig, s5.pluginConfig, pg.GetConfigName().GetAll())
  36. }
  37. }
  38. core.NewTcpListenerAndProcess(s5.ServerIp+":"+strconv.Itoa(s5.ServerPort), func(c net.Conn) {
  39. // init ctx value clientConn
  40. connCtx := context.WithValue(ctx, core.CLIENT_CONNECTION, c)
  41. var err error
  42. // run the plugin contains start
  43. if connCtx, err = core.RunPlugin(connCtx, s5.plugins.StartPgs, core.STAGE_START); err != nil {
  44. fmt.Println(err)
  45. return
  46. }
  47. // start run the plugin run
  48. if connCtx, err = core.RunPlugin(connCtx, s5.plugins.RunPgs, core.STAGE_RUN); err != nil {
  49. fmt.Println(err)
  50. return
  51. }
  52. // start run the plugin end
  53. if connCtx, err = core.RunPlugin(connCtx, s5.plugins.EndPgs, core.STAGE_END); err != nil {
  54. fmt.Println(err)
  55. return
  56. }
  57. }, &s5.listener)
  58. return nil
  59. }