aboutsummaryrefslogtreecommitdiff
path: root/internal/server/conn.go
blob: 8f856fe42a1a832349df8f036c167459b101312d (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
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() {
			s.serveClient(ctx, conn, channel, requests)
		})
	}

	return nil
}