aboutsummaryrefslogtreecommitdiff
path: root/internal/server/client.go
blob: 8a23c8ba9370519bf8b981b3ec9f5bdb52eda9ea (plain) (blame)
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
90
91
92
93
94
package server

import (
	"context"
	"encoding/binary"
	"io"
	"log/slog"
	"sync"

	"golang.org/x/crypto/ssh"
	"golang.org/x/term"
)

func (s *Server) serveClient(
	ctx context.Context,
	conn *ssh.ServerConn,
	channel ssh.Channel,
	requests <-chan *ssh.Request,
) {
	wg := sync.WaitGroup{}

	identify := conn.Permissions.ExtraData["identify"].(string)
	user := s.chat.NewUser(conn.User(), identify)

	t := term.NewTerminal(channel, "[] ")

	// Обработка ввода пользователя
	wg.Go(func() {
		for {
			select {
			case <-ctx.Done():
				return
			default:
			}
			if user.CurrentChan != nil {
				t.SetPrompt("[" + user.CurrentChan.Name + "] ")
			}
			line, err := t.ReadLine()
			if err != nil {
				s.chat.RemoveUser(user)

				if err != io.EOF {
					slog.Error("failed read line", slog.Any("err", err))
				}

				conn.Close()

				return
			}
			if len(line) == 0 {
				continue
			}

			s.chat.Input(ctx, user, line)
		}
	})

	wg.Go(func() {
		for req := range requests {
			switch req.Type {
			case "pty-req":
				termLen := req.Payload[3]
				w, h := parseDims(req.Payload[termLen+4:])
				t.SetSize(w, h)
				req.Reply(true, nil)
			case "window-change":
				w, h := parseDims(req.Payload)
				t.SetSize(w, h)
				req.Reply(true, nil)
			case "shell":
				req.Reply(len(req.Payload) == 0, 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)),
			)
		}
	})

	for message := range user.Events {
		processUserEvent(message, t, user)
	}
}

func parseDims(b []byte) (int, int) {
	w := binary.BigEndian.Uint32(b)
	h := binary.BigEndian.Uint32(b[4:])

	return int(w), int(h)
}