aboutsummaryrefslogtreecommitdiff
path: root/hotline/client.go
blob: e300bb8bb61485ea5d510353cb7a6a36b21e4734 (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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package hotline

import (
	"bufio"
	"bytes"
	"context"
	"encoding/binary"
	"fmt"
	"io"
	"log/slog"
	"net"
	"time"
)

type ClientPrefs struct {
	Username   string `yaml:"Username"`
	IconID     int    `yaml:"IconID"`
	Tracker    string `yaml:"Tracker"`
	EnableBell bool   `yaml:"EnableBell"`
}

func (cp *ClientPrefs) IconBytes() []byte {
	iconBytes := make([]byte, 2)
	binary.BigEndian.PutUint16(iconBytes, uint16(cp.IconID))
	return iconBytes
}

type Client struct {
	Connection  net.Conn
	Logger      *slog.Logger
	Pref        *ClientPrefs
	Handlers    map[[2]byte]ClientHandler
	activeTasks map[[4]byte]*Transaction
	UserList    []User
}

type ClientHandler func(context.Context, *Client, *Transaction) ([]Transaction, error)

func (c *Client) HandleFunc(tranType [2]byte, handler ClientHandler) {
	c.Handlers[tranType] = handler
}

func NewClient(username string, logger *slog.Logger) *Client {
	c := &Client{
		Logger:      logger,
		activeTasks: make(map[[4]byte]*Transaction),
		Handlers:    make(map[[2]byte]ClientHandler),
		Pref:        &ClientPrefs{Username: username},
	}

	return c
}

type ClientTransaction struct {
	Name    string
	Handler func(*Client, *Transaction) ([]Transaction, error)
}

func (ch ClientTransaction) Handle(cc *Client, t *Transaction) ([]Transaction, error) {
	return ch.Handler(cc, t)
}

type ClientTHandler interface {
	Handle(*Client, *Transaction) ([]Transaction, error)
}

// JoinServer connects to a Hotline server and completes the login flow
func (c *Client) Connect(address, login, passwd string) (err error) {
	// Establish TCP connection to server
	c.Connection, err = net.DialTimeout("tcp", address, 5*time.Second)
	if err != nil {
		return err
	}

	// Send handshake sequence
	if err := c.Handshake(); err != nil {
		return err
	}

	// Authenticate (send TranLogin 107)

	err = c.Send(
		NewTransaction(
			TranLogin, [2]byte{0, 0},
			NewField(FieldUserName, []byte(c.Pref.Username)),
			NewField(FieldUserIconID, c.Pref.IconBytes()),
			NewField(FieldUserLogin, EncodeString([]byte(login))),
			NewField(FieldUserPassword, EncodeString([]byte(passwd))),
		),
	)
	if err != nil {
		return fmt.Errorf("error sending login transaction: %w", err)
	}

	// start keepalive go routine
	go func() { _ = c.keepalive() }()

	return nil
}

const keepaliveInterval = 300 * time.Second

func (c *Client) keepalive() error {
	for {
		time.Sleep(keepaliveInterval)
		_ = c.Send(NewTransaction(TranKeepAlive, [2]byte{}))
	}
}

var ClientHandshake = []byte{
	0x54, 0x52, 0x54, 0x50, // TRTP
	0x48, 0x4f, 0x54, 0x4c, // HOTL
	0x00, 0x01,
	0x00, 0x02,
}

var ServerHandshake = []byte{
	0x54, 0x52, 0x54, 0x50, // TRTP
	0x00, 0x00, 0x00, 0x00, // ErrorCode
}

func (c *Client) Handshake() error {
	// Protocol Type	4	‘TRTP’	0x54 52 54 50
	// Sub-protocol Type	4		User defined
	// Version	2	1	Currently 1
	// Sub-version	2		User defined
	if _, err := c.Connection.Write(ClientHandshake); err != nil {
		return fmt.Errorf("handshake write err: %s", err)
	}

	replyBuf := make([]byte, 8)
	_, err := c.Connection.Read(replyBuf)
	if err != nil {
		return err
	}

	if bytes.Equal(replyBuf, ServerHandshake) {
		return nil
	}

	// In the case of an error, client and server close the connection.
	return fmt.Errorf("handshake response err: %s", err)
}

func (c *Client) Send(t Transaction) error {
	requestNum := binary.BigEndian.Uint16(t.Type[:])

	// if transaction is NOT reply, add it to the list to transactions we're expecting a response for
	if t.IsReply == 0 {
		c.activeTasks[t.ID] = &t
	}

	n, err := io.Copy(c.Connection, &t)
	if err != nil {
		return fmt.Errorf("error sending transaction: %w", err)
	}

	c.Logger.Debug("Sent Transaction",
		"IsReply", t.IsReply,
		"type", requestNum,
		"sentBytes", n,
	)
	return nil
}

func (c *Client) HandleTransaction(ctx context.Context, t *Transaction) error {
	var origT Transaction
	if t.IsReply == 1 {
		origT = *c.activeTasks[t.ID]
		t.Type = origT.Type
	}

	if handler, ok := c.Handlers[t.Type]; ok {
		c.Logger.Debug(
			"Received transaction",
			"IsReply", t.IsReply,
			"type", t.Type[:],
		)
		outT, err := handler(ctx, c, t)
		if err != nil {
			c.Logger.Error("error handling transaction", "err", err)
		}
		for _, t := range outT {
			if err := c.Send(t); err != nil {
				return err
			}
		}
	}

	return nil
}

func (c *Client) Disconnect() error {
	return c.Connection.Close()
}

func (c *Client) HandleTransactions(ctx context.Context) error {
	// Create a new scanner for parsing incoming bytes into transaction tokens
	scanner := bufio.NewScanner(c.Connection)
	scanner.Split(transactionScanner)

	// Scan for new transactions and handle them as they come in.
	for scanner.Scan() {
		// Make a new []byte slice and copy the scanner bytes to it.  This is critical to avoid a data race as the
		// scanner re-uses the buffer for subsequent scans.
		buf := make([]byte, len(scanner.Bytes()))
		copy(buf, scanner.Bytes())

		var t Transaction
		_, err := t.Write(buf)
		if err != nil {
			break
		}

		if err := c.HandleTransaction(ctx, &t); err != nil {
			c.Logger.Error("Error handling transaction", "err", err)
		}
	}

	if scanner.Err() == nil {
		return scanner.Err()
	}
	return nil
}