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
|
package server
import (
"context"
"fmt"
"log/slog"
"net"
"sync"
"golang.org/x/crypto/ssh"
)
func (s *Server) serveConn(ctx context.Context, nConn net.Conn, config *ssh.ServerConfig) error {
conn, chans, reqs, err := ssh.NewServerConn(nConn, config)
if err != nil {
return fmt.Errorf("failed to handshake: %w", err)
}
slog.Info("user connected", slog.Any("user", conn.User()), slog.String("ip", conn.RemoteAddr().String()))
var wg sync.WaitGroup
defer wg.Wait()
wg.Go(func() {
ssh.DiscardRequests(reqs)
})
for newChannel := range chans {
if newChannel.ChannelType() != "session" {
newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
continue
}
channel, requests, err := newChannel.Accept()
if err != nil {
return fmt.Errorf("could not accept channel: %w", err)
}
wg.Go(func() {
for req := range requests {
switch req.Type {
case "pty-req":
req.Reply(true, nil)
case "shell":
req.Reply(true, nil)
default:
req.Reply(false, nil)
}
slog.Debug(
"req",
slog.String("type", req.Type),
slog.Bool("want-reply", req.WantReply),
slog.String("payload", string(req.Payload)),
)
}
})
wg.Go(func() {
identify := conn.Permissions.ExtraData["identify"].(string)
user := s.chat.NewUser(conn.User(), identify)
slog.Info("joined", slog.String("user", user.NUsername()))
s.serveClient(ctx, channel, user)
slog.Info("disconnected", slog.String("user", user.NUsername()))
conn.Close()
})
}
return nil
}
|