summaryrefslogtreecommitdiff
path: root/server/handlers/controlhandler.go
blob: c09eb52d35fd807188df352a7c371a4b8851a4e7 (plain)
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
95
96
97
98
99
100
101
102
103
104
105
package handlers

import (
	"dtail/logger"
	"dtail/server/user"
	"fmt"
	"io"
	"os"
	"strings"
)

// ControlHandler is used for control functions and health monitoring.
type ControlHandler struct {
	serverMessages chan string
	pong           chan struct{}
	stop           chan struct{}
	payload        []byte
	hostname       string
	user           *user.User
}

// NewControlHandler returns a new control handler.
func NewControlHandler(user *user.User) *ControlHandler {
	logger.Debug(user, "Creating control handler")

	h := ControlHandler{
		serverMessages: make(chan string, 10),
		pong:           make(chan struct{}, 10),
		stop:           make(chan struct{}),
		user:           user,
	}

	fqdn, err := os.Hostname()
	if err != nil {
		logger.FatalExit(err)
	}

	s := strings.Split(fqdn, ".")
	h.hostname = s[0]
	return &h
}

// Read is to send data to the client via the Reader interface.
func (h *ControlHandler) Read(p []byte) (n int, err error) {
	for {
		select {
		case message := <-h.serverMessages:
			wholePayload := []byte(fmt.Sprintf("SERVER|%s|%s\n", h.hostname, message))
			n = copy(p, wholePayload)
			return
		case <-h.pong:
			logger.Info(h.user, "Sending pong")
			n = copy(p, []byte(".pong\n"))
			return
		case <-h.stop:
			return 0, io.EOF
		}
	}
}

// Write is to read data to the client via the Writer interface.
func (h *ControlHandler) Write(p []byte) (n int, err error) {
	for _, c := range p {
		switch c {
		case ';':
			wholePayload := strings.TrimSpace(string(h.payload))
			h.handleCommand(wholePayload)
			h.payload = nil

		default:
			h.payload = append(h.payload, c)
		}
	}

	n = len(p)
	return
}

// Close the control handler.
func (h *ControlHandler) Close() {
	close(h.stop)
}

// Wait returns the handler stop channel.
func (h *ControlHandler) Wait() <-chan struct{} {
	return h.stop
}

func (h *ControlHandler) handleCommand(command string) {
	logger.Info(h.user, command)
	s := strings.Split(command, " ")
	logger.Debug(h.user, "Receiving command", command, s)

	switch s[0] {
	case "health":
		h.serverMessages <- "OK: DTail SSH Server seems fine"
		h.serverMessages <- "done;"
	case "ping":
		h.pong <- struct{}{}
	case "debug":
		h.serverMessages <- logger.Debug(h.user, "Receiving debug command", command, s)
	default:
		h.serverMessages <- logger.Warn(h.user, "Received unknown command", command, s)
	}
}