-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_test.go
89 lines (77 loc) · 1.85 KB
/
server_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package sshutil
import (
"bytes"
"errors"
"io"
"net"
"sync"
"testing"
"golang.org/x/crypto/ssh"
)
func TestServer(t *testing.T) {
ln, err := net.Listen("tcp", "localhost:")
if err != nil {
t.Fatalf("err listening on localhost: %v", err)
}
subject := &Server{}
subject.Channel("echo", ChannelHandlerFunc(echo))
var wg sync.WaitGroup
wg.Add(1)
go func() {
// Blocks until Close/Shutdown is called
err := subject.Serve(ln)
if !errors.Is(err, ErrServerClosed) {
t.Errorf("Got incorrect error: %v, expecting %v", err, ErrServerClosed)
}
t.Log("server done")
wg.Done()
}()
signer, err := GenerateKey()
if err != nil {
subject.Close()
t.Fatalf("couldn't generate client key")
}
fp := ssh.FingerprintSHA256(signer.PublicKey())
t.Logf("Client public key fingerprint '%s'", fp)
config := &ssh.ClientConfig{
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, err := ssh.Dial("tcp", ln.Addr().String(), config)
//client, err := ssh.Dial("tcp", "localhost:2022", config)
if err != nil {
subject.Close()
t.Fatalf("error dialing server: %v", err)
}
stream, reqs, err := client.OpenChannel("echo", nil)
if err != nil {
subject.Close()
t.Fatalf("error opening channel: %v", err)
}
go ssh.DiscardRequests(reqs)
msg := []byte("ssh test")
_, err = stream.Write(msg)
if err != nil {
t.Fatalf("unexpected error writing test message")
}
stream.CloseWrite()
reply := make([]byte, len(msg))
_, err = stream.Read(reply)
if err != nil {
t.Fatalf("unexpected error reading test message")
}
if !bytes.Equal(msg, reply) {
t.Errorf("unexpected reply from server: '%s'", reply)
}
stream.Close()
subject.Shutdown()
wg.Wait()
client.Close()
subject.Idle.Wait()
}
func echo(stream Channel, reqs <-chan *ssh.Request) {
go ssh.DiscardRequests(reqs)
io.Copy(stream, stream)
}