Server.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package zsshrpc_server
  2. import (
  3. "fmt"
  4. "golang.org/x/crypto/ssh"
  5. "net"
  6. "strings"
  7. )
  8. type ZSshRpcServer struct {
  9. sshcfg *ssh.ServerConfig
  10. stopchan chan int
  11. logger SvrLogFunc
  12. ioBlockSize int
  13. OperationHandelr ZSshRpcOperationHandler
  14. }
  15. func NewZSshRpcServer(conf *ZSshRpcServerCfg) *ZSshRpcServer {
  16. o := &ZSshRpcServer{}
  17. o.sshcfg = &ssh.ServerConfig{
  18. ServerVersion: "SSH-2.0-zSshRpcTest-1.0",
  19. NoClientAuth: conf.NoClientAuth,
  20. MaxAuthTries: conf.MaxAuthTries,
  21. PasswordCallback: conf.PasswordCallback,
  22. PublicKeyCallback: conf.PublicKeyCallback,
  23. KeyboardInteractiveCallback: conf.KeyboardInteractiveCallback,
  24. AuthLogCallback: conf.AuthLogCallback,
  25. }
  26. ciphers := []string{
  27. "aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", "arcfour256", "arcfour128",
  28. }
  29. if conf.Support_AES128_CBC {
  30. ciphers = append(ciphers, "aes128-cbc")
  31. }
  32. o.sshcfg.Ciphers = ciphers
  33. o.sshcfg.AddHostKey(conf.HostKey)
  34. o.logger = conf.ServerLogger
  35. o.OperationHandelr = conf.OperationHandler
  36. o.ioBlockSize = conf.IOBlockSize
  37. return o
  38. }
  39. func (this *ZSshRpcServer) Stop() {
  40. this.stopchan <- 1
  41. }
  42. func (this *ZSshRpcServer) StartWithListener(listener net.Listener) error {
  43. this.stopchan = make(chan int)
  44. go func() {
  45. <-this.stopchan
  46. listener.Close()
  47. }()
  48. go func() {
  49. for {
  50. nconn, err := listener.Accept()
  51. if err == nil {
  52. this.logger(SvrLogLevel_INFO, fmt.Sprintf("Client '%v' Come In.", nconn.RemoteAddr()), nil)
  53. go HandleNewSession(nconn, this.sshcfg, this.logger, this.OperationHandelr, this.ioBlockSize)
  54. } else {
  55. if strings.Contains(err.Error(), "use of closed network connection") {
  56. this.logger(SvrLogLevel_INFO, "Server Terminated By User.", err)
  57. } else {
  58. this.logger(SvrLogLevel_ERROR, fmt.Sprintf("Failed Handle Connection From Client '%v'", nconn.RemoteAddr()), err)
  59. }
  60. }
  61. }
  62. }()
  63. return nil
  64. }
  65. func (this *ZSshRpcServer) ListenTCP(network string, addr *net.TCPAddr) error {
  66. lis, err := net.ListenTCP(network, addr)
  67. if err != nil {
  68. return err
  69. }
  70. this.StartWithListener(lis)
  71. return nil
  72. }