Commit 22beb659 authored by ibuler's avatar ibuler

[Update] 移动结构

parent 187f514a
...@@ -59,7 +59,7 @@ func keepHeartbeat(interval int) { ...@@ -59,7 +59,7 @@ func keepHeartbeat(interval int) {
tasks := service.TerminalHeartBeat(data) tasks := service.TerminalHeartBeat(data)
if len(tasks) != 0 { if len(tasks) != 0 {
for _, task := range tasks { for _, task := range tasks {
proxy.HandlerSessionTask(task) proxy.HandleSessionTask(task)
} }
} }
} }
......
...@@ -511,7 +511,7 @@ func selectHighestPrioritySystemUsers(systemUsers []model.SystemUser) []model.Sy ...@@ -511,7 +511,7 @@ func selectHighestPrioritySystemUsers(systemUsers []model.SystemUser) []model.Sy
// Home := userhome.NewUserSessionHome(sshConn) // Home := userhome.NewUserSessionHome(sshConn)
// logger.Info("session Home ID: ", Home.SessionID()) // logger.Info("session Home ID: ", Home.SessionID())
// //
// err = proxy.Manager.Session(i.sess.Context(), Home, memChan) // err = proxy.Manager.session(i.sess.Context(), Home, memChan)
// if err != nil { // if err != nil {
// logger.Error(err) // logger.Error(err)
// } // }
......
...@@ -38,7 +38,7 @@ func AuthDecorator(handler http.HandlerFunc) http.HandlerFunc { ...@@ -38,7 +38,7 @@ func AuthDecorator(handler http.HandlerFunc) http.HandlerFunc {
func OnConnectHandler(s socketio.Conn) error { func OnConnectHandler(s socketio.Conn) error {
// 首次连接 1.获取当前用户的信息 // 首次连接 1.获取当前用户的信息
logger.Debug("OnConnectHandler") logger.Debug("On connect trigger")
cookies := strings.Split(s.RemoteHeader().Get("Cookie"), ";") cookies := strings.Split(s.RemoteHeader().Get("Cookie"), ";")
var csrfToken, sessionID, remoteIP string var csrfToken, sessionID, remoteIP string
for _, line := range cookies { for _, line := range cookies {
...@@ -51,7 +51,9 @@ func OnConnectHandler(s socketio.Conn) error { ...@@ -51,7 +51,9 @@ func OnConnectHandler(s socketio.Conn) error {
} }
user, err := service.CheckUserCookie(sessionID, csrfToken) user, err := service.CheckUserCookie(sessionID, csrfToken)
if err != nil { if err != nil {
return errors.New("user is not authenticated") msg := "User is not authenticated"
logger.Error(msg)
return errors.New(strings.ToLower(msg))
} }
remoteAddr := s.RemoteHeader().Get("X-Forwarded-For") remoteAddr := s.RemoteHeader().Get("X-Forwarded-For")
if remoteAddr == "" { if remoteAddr == "" {
...@@ -65,7 +67,6 @@ func OnConnectHandler(s socketio.Conn) error { ...@@ -65,7 +67,6 @@ func OnConnectHandler(s socketio.Conn) error {
s.SetContext(ctx) s.SetContext(ctx)
conns.AddWebConn(s.ID(), conn) conns.AddWebConn(s.ID(), conn)
logger.Info("On Connect handler end") logger.Info("On Connect handler end")
s.Emit("3")
return nil return nil
} }
...@@ -191,7 +192,6 @@ func OnResizeHandler(s socketio.Conn, message ResizeMsg) { ...@@ -191,7 +192,6 @@ func OnResizeHandler(s socketio.Conn, message ResizeMsg) {
func OnLogoutHandler(s socketio.Conn, message string) { func OnLogoutHandler(s socketio.Conn, message string) {
logger.Debug("OnLogout trigger") logger.Debug("OnLogout trigger")
logger.Debugf("Msg: %s\n", message)
webConn := conns.GetWebConn(s.ID()) webConn := conns.GetWebConn(s.ID())
if webConn == nil { if webConn == nil {
logger.Error("No conn found") logger.Error("No conn found")
......
package httpd package httpd
import ( import (
"cocogo/pkg/config"
"cocogo/pkg/logger"
"github.com/googollee/go-engine.io"
"github.com/googollee/go-socket.io"
"github.com/satori/go.uuid"
"net/http" "net/http"
"strconv" "strconv"
"strings"
"sync" "sync"
"github.com/googollee/go-socket.io"
"cocogo/pkg/config"
"cocogo/pkg/logger"
) )
var ( var (
...@@ -17,17 +16,9 @@ var ( ...@@ -17,17 +16,9 @@ var (
conns = &connections{container: make(map[string]*WebConn), mu: new(sync.RWMutex)} conns = &connections{container: make(map[string]*WebConn), mu: new(sync.RWMutex)}
) )
type UUIDSessionIDGenerator struct {
}
func (u *UUIDSessionIDGenerator) NewID() string {
return strings.Split(uuid.NewV4().String(), "-")[4]
}
func StartHTTPServer() { func StartHTTPServer() {
conf := config.GetConf() conf := config.GetConf()
option := engineio.Options{} server, err := socketio.NewServer(nil)
server, err := socketio.NewServer(&option)
if err != nil { if err != nil {
logger.Fatal(err) logger.Fatal(err)
} }
...@@ -35,7 +26,7 @@ func StartHTTPServer() { ...@@ -35,7 +26,7 @@ func StartHTTPServer() {
server.OnDisconnect("/ssh", OnDisconnect) server.OnDisconnect("/ssh", OnDisconnect)
server.OnError("/ssh", OnErrorHandler) server.OnError("/ssh", OnErrorHandler)
server.OnEvent("/ssh", "host", OnHostHandler) server.OnEvent("/ssh", "host", OnHostHandler)
//server.OnEvent("/ssh", "token", OnTokenHandler) server.OnEvent("/ssh", "token", OnTokenHandler)
server.OnEvent("/ssh", "data", OnDataHandler) server.OnEvent("/ssh", "data", OnDataHandler)
server.OnEvent("/ssh", "resize", OnResizeHandler) server.OnEvent("/ssh", "resize", OnResizeHandler)
server.OnEvent("/ssh", "logout", OnLogoutHandler) server.OnEvent("/ssh", "logout", OnLogoutHandler)
......
package proxy package proxy
import ( import (
"cocogo/pkg/srvconn"
"cocogo/pkg/utils" "cocogo/pkg/utils"
"fmt" "fmt"
"regexp" "regexp"
...@@ -34,7 +35,7 @@ func (p *ProxyServer) getSystemUserAuthOrManualSet() { ...@@ -34,7 +35,7 @@ func (p *ProxyServer) getSystemUserAuthOrManualSet() {
if err != nil { if err != nil {
logger.Errorf("Get password from user err %s", err.Error()) logger.Errorf("Get password from user err %s", err.Error())
} }
logger.Info("Get password from user input: ", line) logger.Debug("Get password from user input: ", line)
p.SystemUser.Password = line p.SystemUser.Password = line
} }
} }
...@@ -72,50 +73,57 @@ func (p *ProxyServer) validatePermission() bool { ...@@ -72,50 +73,57 @@ func (p *ProxyServer) validatePermission() bool {
return true return true
} }
func (p *ProxyServer) getSSHConn() (srvConn *ServerSSHConnection, err error) { func (p *ProxyServer) getSSHConn() (srvConn *srvconn.ServerSSHConnection, err error) {
srvConn = &ServerSSHConnection{ proxyConfig := &srvconn.SSHClientConfig{}
name: p.Asset.Hostname, sshConfig := srvconn.SSHClientConfig{
host: p.Asset.Ip, Host: p.Asset.Ip,
port: strconv.Itoa(p.Asset.Port), Port: strconv.Itoa(p.Asset.Port),
user: p.SystemUser.Username, User: p.SystemUser.Username,
password: p.SystemUser.Password, Password: p.SystemUser.Password,
privateKey: p.SystemUser.PrivateKey, PrivateKey: p.SystemUser.PrivateKey,
timeout: config.GetConf().SSHTimeout, Overtime: config.GetConf().SSHTimeout,
Proxy: proxyConfig,
}
srvConn = &srvconn.ServerSSHConnection{
Name: p.Asset.Hostname,
Creator: p.User.Username,
SSHClientConfig: sshConfig,
} }
pty := p.UserConn.Pty() pty := p.UserConn.Pty()
done := make(chan struct{})
go p.sendConnectingMsg(done, srvConn.timeout)
err = srvConn.Connect(pty.Window.Height, pty.Window.Width, pty.Term) err = srvConn.Connect(pty.Window.Height, pty.Window.Width, pty.Term)
utils.IgnoreErrWriteString(p.UserConn, "\r\n") fmt.Println("Error: ", err)
close(done)
return return
} }
func (p *ProxyServer) getTelnetConn() (srvConn *ServerTelnetConnection, err error) { func (p *ProxyServer) getTelnetConn() (srvConn *srvconn.ServerTelnetConnection, err error) {
conf := config.GetConf() conf := config.GetConf()
cusString := conf.TelnetRegex cusString := conf.TelnetRegex
pattern, _ := regexp.Compile(cusString) pattern, _ := regexp.Compile(cusString)
srvConn = &ServerTelnetConnection{ srvConn = &srvconn.ServerTelnetConnection{
name: p.Asset.Hostname, Name: p.Asset.Hostname,
host: p.Asset.Ip, Creator: p.User.ID,
port: strconv.Itoa(p.Asset.Port), Host: p.Asset.Ip,
user: p.SystemUser.Username, Port: strconv.Itoa(p.Asset.Port),
password: p.SystemUser.Password, User: p.SystemUser.Username,
customString: cusString, Password: p.SystemUser.Password,
customSuccessPattern: pattern, CustomString: cusString,
timeout: conf.SSHTimeout, CustomSuccessPattern: pattern,
Overtime: conf.SSHTimeout,
} }
done := make(chan struct{})
go p.sendConnectingMsg(done, srvConn.timeout)
err = srvConn.Connect(0, 0, "") err = srvConn.Connect(0, 0, "")
utils.IgnoreErrWriteString(p.UserConn, "\r\n") utils.IgnoreErrWriteString(p.UserConn, "\r\n")
close(done)
return return
} }
func (p *ProxyServer) getServerConn() (srvConn ServerConnection, err error) { func (p *ProxyServer) getServerConn() (srvConn srvconn.ServerConnection, err error) {
p.getSystemUserUsernameIfNeed() p.getSystemUserUsernameIfNeed()
p.getSystemUserAuthOrManualSet() p.getSystemUserAuthOrManualSet()
done := make(chan struct{})
defer func() {
utils.IgnoreErrWriteString(p.UserConn, "\r\n")
close(done)
}()
go p.sendConnectingMsg(done, config.GetConf().SSHTimeout)
if p.Asset.Protocol == "telnet" { if p.Asset.Protocol == "telnet" {
return p.getTelnetConn() return p.getTelnetConn()
} else { } else {
...@@ -204,7 +212,7 @@ func (p *ProxyServer) finishSession(s *SwitchSession) { ...@@ -204,7 +212,7 @@ func (p *ProxyServer) finishSession(s *SwitchSession) {
data := s.MapData() data := s.MapData()
service.FinishSession(data) service.FinishSession(data)
service.FinishReply(s.Id) service.FinishReply(s.Id)
logger.Debugf("finish Session: %s", s.Id) logger.Debugf("finish session: %s", s.Id)
} }
func (p *ProxyServer) GetFilterRules() []model.SystemUserFilterRule { func (p *ProxyServer) GetFilterRules() []model.SystemUserFilterRule {
......
...@@ -66,7 +66,7 @@ func (c *CommandRecorder) record() { ...@@ -66,7 +66,7 @@ func (c *CommandRecorder) record() {
} }
case p, ok := <-c.queue: case p, ok := <-c.queue:
if !ok { if !ok {
logger.Debug("Session command recorder close: ", c.sessionID) logger.Debug("session command recorder close: ", c.sessionID)
return return
} }
cmdList = append(cmdList, p) cmdList = append(cmdList, p)
......
...@@ -9,7 +9,7 @@ import ( ...@@ -9,7 +9,7 @@ import (
var sessionMap = make(map[string]*SwitchSession) var sessionMap = make(map[string]*SwitchSession)
var lock = new(sync.RWMutex) var lock = new(sync.RWMutex)
func HandlerSessionTask(task model.TerminalTask) { func HandleSessionTask(task model.TerminalTask) {
switch task.Name { switch task.Name {
case "kill_session": case "kill_session":
KillSession(task.Args) KillSession(task.Args)
......
package proxy package proxy
import ( import (
"cocogo/pkg/srvconn"
"context" "context"
"fmt" "fmt"
"strings" "strings"
...@@ -117,13 +118,13 @@ func (s *SwitchSession) SetFilterRules(cmdRules []model.SystemUserFilterRule) { ...@@ -117,13 +118,13 @@ func (s *SwitchSession) SetFilterRules(cmdRules []model.SystemUserFilterRule) {
s.parser.SetCMDFilterRules(cmdRules) s.parser.SetCMDFilterRules(cmdRules)
} }
func (s *SwitchSession) Bridge(userConn UserConnection, srvConn ServerConnection) (err error) { func (s *SwitchSession) Bridge(userConn UserConnection, srvConn srvconn.ServerConnection) (err error) {
winCh := userConn.WinCh() winCh := userConn.WinCh()
s.srvTran = NewDirectTransport(s.Id, srvConn) s.srvTran = NewDirectTransport(s.Id, srvConn)
s.userTran = NewDirectTransport(s.Id, userConn) s.userTran = NewDirectTransport(s.Id, userConn)
defer func() { defer func() {
logger.Info("Session bridge done: ", s.Id) logger.Info("session bridge done: ", s.Id)
}() }()
go s.parser.Parse() go s.parser.Parse()
......
package srvconn
import (
"fmt"
"strconv"
"sync"
gossh "golang.org/x/crypto/ssh"
"cocogo/pkg/config"
"cocogo/pkg/logger"
"cocogo/pkg/model"
)
var (
sshClients = make(map[string]*gossh.Client)
clientsRefCounter = make(map[*gossh.Client]int)
clientLock = new(sync.RWMutex)
)
func newClient(user *model.User, asset *model.Asset,
systemUser *model.SystemUser) (client *gossh.Client, err error) {
cfg := SSHClientConfig{
Host: asset.Ip,
Port: strconv.Itoa(asset.Port),
User: systemUser.Username,
Password: systemUser.Password,
PrivateKey: systemUser.PrivateKey,
Overtime: config.GetConf().SSHTimeout,
}
client, err = cfg.Dial()
return
}
func NewClient(user *model.User, asset *model.Asset, systemUser *model.SystemUser) (client *gossh.Client, err error) {
key := fmt.Sprintf("%s_%s_%s", user.ID, asset.Id, systemUser.Id)
clientLock.RLock()
client, ok := sshClients[key]
clientLock.RUnlock()
var u = user.Username
var ip = asset.Ip
var sysName = systemUser.Username
if ok {
clientLock.Lock()
clientsRefCounter[client]++
var counter = clientsRefCounter[client]
logger.Infof("Reuse connection: %s->%s@%s\n ref: %d", u, sysName, ip, counter)
clientLock.Unlock()
return client, nil
}
client, err = newClient(user, asset, systemUser)
if err == nil {
clientLock.Lock()
sshClients[key] = client
clientsRefCounter[client] = 1
clientLock.Unlock()
}
return
}
func RecycleClient(client *gossh.Client) {
clientLock.Lock()
defer clientLock.Unlock()
if counter, ok := clientsRefCounter[client]; ok {
if counter == 1 {
logger.Debug("Recycle client: close it")
_ = client.Close()
delete(clientsRefCounter, client)
var key string
for k, v := range sshClients {
if v == client {
key = k
break
}
}
if key != "" {
delete(sshClients, key)
}
} else {
logger.Debug("Recycle client: ref -1")
clientsRefCounter[client]--
}
}
}
package proxy package srvconn
import ( import (
"fmt" "fmt"
"testing" "testing"
) )
var testConnection = ServerSSHConnection{ var testConnection = SSHClientConfig{
host: "127.0.0.1", Host: "127.0.0.1",
port: "22", Port: "22",
user: "root", User: "root",
password: "redhat", Password: "redhat",
Proxy: &ServerSSHConnection{host: "192.168.244.185", port: "22", user: "root", password: "redhat"}, Proxy: &SSHClientConfig{Host: "192.168.244.185", Port: "22", User: "root", Password: "redhat"},
} }
func TestSSHConnection_Config(t *testing.T) { func TestSSHConnection_Config(t *testing.T) {
...@@ -22,7 +22,7 @@ func TestSSHConnection_Config(t *testing.T) { ...@@ -22,7 +22,7 @@ func TestSSHConnection_Config(t *testing.T) {
} }
func TestSSHConnection_Connect(t *testing.T) { func TestSSHConnection_Connect(t *testing.T) {
err := testConnection.Connect(24, 80, "xterm") _, err := testConnection.Dial()
if err != nil { if err != nil {
t.Errorf("Connect error %s", err) t.Errorf("Connect error %s", err)
} }
......
package proxy package srvconn
import ( import (
"fmt" "fmt"
"github.com/pkg/errors"
"io" "io"
"net" "net"
"time" "time"
...@@ -11,86 +12,54 @@ import ( ...@@ -11,86 +12,54 @@ import (
type ServerConnection interface { type ServerConnection interface {
io.ReadWriteCloser io.ReadWriteCloser
Name() string
Host() string
Port() string
User() string
Timeout() time.Duration Timeout() time.Duration
Protocol() string Protocol() string
Connect(h, w int, term string) error
SetWinSize(w, h int) error SetWinSize(w, h int) error
} }
type ServerSSHConnection struct { type SSHClientConfig struct {
name string Host string
host string Port string
port string User string
user string Password string
password string PrivateKey string
privateKey string PrivateKeyPath string
privateKeyPath string Overtime int
timeout int Proxy *SSHClientConfig
Proxy *ServerSSHConnection
client *gossh.Client
Session *gossh.Session
proxyConn gossh.Conn
stdin io.WriteCloser
stdout io.Reader
closed bool
}
func (sc *ServerSSHConnection) Protocol() string {
return "ssh"
}
func (sc *ServerSSHConnection) User() string {
return sc.user
}
func (sc *ServerSSHConnection) Host() string {
return sc.host
}
func (sc *ServerSSHConnection) Name() string {
return sc.name
}
func (sc *ServerSSHConnection) Port() string {
return sc.port
}
func (sc *ServerSSHConnection) Timeout() time.Duration { proxyConn gossh.Conn
return time.Duration(sc.timeout) * time.Second
} }
func (sc *ServerSSHConnection) String() string { func (sc *SSHClientConfig) Timeout() time.Duration {
return fmt.Sprintf("%s@%s:%s", sc.user, sc.host, sc.port) if sc.Overtime == 0 {
sc.Overtime = 30
}
return time.Duration(sc.Overtime) * time.Second
} }
func (sc *ServerSSHConnection) Config() (config *gossh.ClientConfig, err error) { func (sc *SSHClientConfig) Config() (config *gossh.ClientConfig, err error) {
authMethods := make([]gossh.AuthMethod, 0) authMethods := make([]gossh.AuthMethod, 0)
if sc.password != "" { if sc.Password != "" {
authMethods = append(authMethods, gossh.Password(sc.password)) authMethods = append(authMethods, gossh.Password(sc.Password))
} }
if sc.privateKeyPath != "" { if sc.PrivateKeyPath != "" {
if pubkey, err := GetPubKeyFromFile(sc.privateKeyPath); err != nil { if pubkey, err := GetPubKeyFromFile(sc.PrivateKeyPath); err != nil {
err = fmt.Errorf("parse private key from file error: %sc", err) err = fmt.Errorf("parse private key from file error: %s", err)
return config, err return config, err
} else { } else {
authMethods = append(authMethods, gossh.PublicKeys(pubkey)) authMethods = append(authMethods, gossh.PublicKeys(pubkey))
} }
} }
if sc.privateKey != "" { if sc.PrivateKey != "" {
if signer, err := gossh.ParsePrivateKey([]byte(sc.privateKey)); err != nil { if signer, err := gossh.ParsePrivateKey([]byte(sc.PrivateKey)); err != nil {
err = fmt.Errorf("parse private key error: %sc", err) err = fmt.Errorf("parse private key error: %s", err)
return config, err return config, err
} else { } else {
authMethods = append(authMethods, gossh.PublicKeys(signer)) authMethods = append(authMethods, gossh.PublicKeys(signer))
} }
} }
config = &gossh.ClientConfig{ config = &gossh.ClientConfig{
User: sc.user, User: sc.User,
Auth: authMethods, Auth: authMethods,
HostKeyCallback: gossh.InsecureIgnoreHostKey(), HostKeyCallback: gossh.InsecureIgnoreHostKey(),
Timeout: sc.Timeout(), Timeout: sc.Timeout(),
...@@ -98,42 +67,68 @@ func (sc *ServerSSHConnection) Config() (config *gossh.ClientConfig, err error) ...@@ -98,42 +67,68 @@ func (sc *ServerSSHConnection) Config() (config *gossh.ClientConfig, err error)
return config, nil return config, nil
} }
func (sc *ServerSSHConnection) connect() (client *gossh.Client, err error) { func (sc *SSHClientConfig) Dial() (client *gossh.Client, err error) {
config, err := sc.Config() cfg, err := sc.Config()
if err != nil { if err != nil {
return return
} }
if sc.Proxy != nil { if sc.Proxy != nil && sc.Proxy.Host != "" {
proxyClient, err := sc.Proxy.connect() proxyClient, err := sc.Proxy.Dial()
if err != nil { if err != nil {
err = errors.New("connect proxy Host error1: " + err.Error())
return client, err return client, err
} }
proxySock, err := proxyClient.Dial("tcp", net.JoinHostPort(sc.host, sc.port)) proxySock, err := proxyClient.Dial("tcp", net.JoinHostPort(sc.Host, sc.Port))
if err != nil { if err != nil {
err = errors.New("connect proxy Host error2: " + err.Error())
return client, err return client, err
} }
proxyConn, chans, reqs, err := gossh.NewClientConn(proxySock, net.JoinHostPort(sc.host, sc.port), config) proxyConn, chans, reqs, err := gossh.NewClientConn(proxySock, net.JoinHostPort(sc.Host, sc.Port), cfg)
if err != nil { if err != nil {
return client, err return client, err
} }
sc.proxyConn = proxyConn sc.proxyConn = proxyConn
client = gossh.NewClient(proxyConn, chans, reqs) client = gossh.NewClient(proxyConn, chans, reqs)
} else { } else {
client, err = gossh.Dial("tcp", net.JoinHostPort(sc.host, sc.port), config) client, err = gossh.Dial("tcp", net.JoinHostPort(sc.Host, sc.Port), cfg)
if err != nil { if err != nil {
return return
} }
} }
sc.client = client
return client, nil return client, nil
} }
func (sc *SSHClientConfig) String() string {
return fmt.Sprintf("%s@%s:%s", sc.User, sc.Host, sc.Port)
}
type ServerSSHConnection struct {
SSHClientConfig
Name string
Creator string
client *gossh.Client
session *gossh.Session
stdin io.WriteCloser
stdout io.Reader
closed bool
refCount int
}
func (sc *ServerSSHConnection) Protocol() string {
return "ssh"
}
func (sc *ServerSSHConnection) String() string {
return fmt.Sprintf("%s@%s:%s", sc.User, sc.Host, sc.Port)
}
func (sc *ServerSSHConnection) invokeShell(h, w int, term string) (err error) { func (sc *ServerSSHConnection) invokeShell(h, w int, term string) (err error) {
sess, err := sc.client.NewSession() sess, err := sc.client.NewSession()
if err != nil { if err != nil {
return return
} }
sc.Session = sess sc.session = sess
modes := gossh.TerminalModes{ modes := gossh.TerminalModes{
gossh.ECHO: 1, // enable echoing gossh.ECHO: 1, // enable echoing
gossh.TTY_OP_ISPEED: 14400, // input speed = 14.4 kbaud gossh.TTY_OP_ISPEED: 14400, // input speed = 14.4 kbaud
...@@ -156,7 +151,7 @@ func (sc *ServerSSHConnection) invokeShell(h, w int, term string) (err error) { ...@@ -156,7 +151,7 @@ func (sc *ServerSSHConnection) invokeShell(h, w int, term string) (err error) {
} }
func (sc *ServerSSHConnection) Connect(h, w int, term string) (err error) { func (sc *ServerSSHConnection) Connect(h, w int, term string) (err error) {
_, err = sc.connect() sc.client, err = sc.Dial()
if err != nil { if err != nil {
return return
} }
...@@ -168,7 +163,7 @@ func (sc *ServerSSHConnection) Connect(h, w int, term string) (err error) { ...@@ -168,7 +163,7 @@ func (sc *ServerSSHConnection) Connect(h, w int, term string) (err error) {
} }
func (sc *ServerSSHConnection) SetWinSize(h, w int) error { func (sc *ServerSSHConnection) SetWinSize(h, w int) error {
return sc.Session.WindowChange(h, w) return sc.session.WindowChange(h, w)
} }
func (sc *ServerSSHConnection) Read(p []byte) (n int, err error) { func (sc *ServerSSHConnection) Read(p []byte) (n int, err error) {
...@@ -183,7 +178,7 @@ func (sc *ServerSSHConnection) Close() (err error) { ...@@ -183,7 +178,7 @@ func (sc *ServerSSHConnection) Close() (err error) {
if sc.closed { if sc.closed {
return return
} }
err = sc.Session.Close() err = sc.session.Close()
err = sc.client.Close() err = sc.client.Close()
if sc.proxyConn != nil { if sc.proxyConn != nil {
err = sc.proxyConn.Close() err = sc.proxyConn.Close()
......
package proxy package srvconn
import ( import (
"bytes" "bytes"
...@@ -45,38 +45,25 @@ const ( ...@@ -45,38 +45,25 @@ const (
) )
type ServerTelnetConnection struct { type ServerTelnetConnection struct {
name string Name string
host string Creator string
port string Host string
user string Port string
password string User string
timeout int Password string
customString string Overtime int
customSuccessPattern *regexp.Regexp CustomString string
CustomSuccessPattern *regexp.Regexp
conn net.Conn
conn net.Conn
closed bool closed bool
} }
func (tc *ServerTelnetConnection) Name() string {
return tc.name
}
func (tc *ServerTelnetConnection) Host() string {
return tc.host
}
func (tc *ServerTelnetConnection) Port() string {
return tc.port
}
func (tc *ServerTelnetConnection) User() string {
return tc.user
}
func (tc *ServerTelnetConnection) Timeout() time.Duration { func (tc *ServerTelnetConnection) Timeout() time.Duration {
return time.Duration(tc.timeout) * time.Second if tc.Overtime == 0 {
tc.Overtime = 30
}
return time.Duration(tc.Overtime) * time.Second
} }
func (tc *ServerTelnetConnection) Protocol() string { func (tc *ServerTelnetConnection) Protocol() string {
...@@ -133,18 +120,18 @@ func (tc *ServerTelnetConnection) login(data []byte) AuthStatus { ...@@ -133,18 +120,18 @@ func (tc *ServerTelnetConnection) login(data []byte) AuthStatus {
if incorrectPattern.Match(data) { if incorrectPattern.Match(data) {
return AuthFailed return AuthFailed
} else if usernamePattern.Match(data) { } else if usernamePattern.Match(data) {
_, _ = tc.conn.Write([]byte(tc.user + "\r\n")) _, _ = tc.conn.Write([]byte(tc.User + "\r\n"))
logger.Debug("usernamePattern ", tc.user) logger.Debug("usernamePattern ", tc.User)
return AuthPartial return AuthPartial
} else if passwordPattern.Match(data) { } else if passwordPattern.Match(data) {
_, _ = tc.conn.Write([]byte(tc.password + "\r\n")) _, _ = tc.conn.Write([]byte(tc.Password + "\r\n"))
logger.Debug("passwordPattern ", tc.password) logger.Debug("passwordPattern ", tc.Password)
return AuthPartial return AuthPartial
} else if successPattern.Match(data) { } else if successPattern.Match(data) {
return AuthSuccess return AuthSuccess
} }
if tc.customString != "" { if tc.CustomString != "" {
if tc.customSuccessPattern.Match(data) { if tc.CustomSuccessPattern.Match(data) {
return AuthSuccess return AuthSuccess
} }
} }
...@@ -152,7 +139,7 @@ func (tc *ServerTelnetConnection) login(data []byte) AuthStatus { ...@@ -152,7 +139,7 @@ func (tc *ServerTelnetConnection) login(data []byte) AuthStatus {
} }
func (tc *ServerTelnetConnection) Connect(h, w int, term string) (err error) { func (tc *ServerTelnetConnection) Connect(h, w int, term string) (err error) {
conn, err := net.DialTimeout("tcp", net.JoinHostPort(tc.host, tc.port), tc.Timeout()) conn, err := net.DialTimeout("tcp", net.JoinHostPort(tc.Host, tc.Port), tc.Timeout())
if err != nil { if err != nil {
return return
} }
......
package proxy package srvconn
import ( import (
"golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment