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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
|
package hotline
import (
"cmp"
"encoding/binary"
"fmt"
"io"
"log/slog"
"net"
"strings"
"sync"
"golang.org/x/crypto/bcrypt"
"golang.org/x/text/encoding"
)
var clientConnSortFunc = func(a, b *ClientConn) int {
return cmp.Compare(
binary.BigEndian.Uint16(a.ID[:]),
binary.BigEndian.Uint16(b.ID[:]),
)
}
// sendQueueDepth is the number of transactions that can be queued for delivery to a client before
// the client is considered too slow and is disconnected.
const sendQueueDepth = 64
// ClientConn represents a client connected to a Server
type ClientConn struct {
Connection io.ReadWriteCloser
RemoteAddr string
ID ClientID
Version []byte // TODO: make fixed size of 2
Account *Account
Server *Server // TODO: consider adding methods to interact with server
// The following fields hold mutable session state guarded by mu. They are read and written
// by multiple goroutines (the client's own transaction loop, other clients' handlers, and the
// server keepalive loop), so production code must use the accessor methods below. Direct
// field access is only safe before the connection is shared, e.g. in tests.
Flags UserFlags
UserName []byte
Icon []byte // TODO: make fixed size of 2
IdleTime int
AutoReply []byte
ClientFileTransferMgr ClientFileTransferMgr
Logger *slog.Logger
mu sync.RWMutex // guards the mutable session state fields above
sendCh chan Transaction
sendInit sync.Once
sendMu sync.Mutex // guards sendClosed and close(sendCh)
sendClosed bool
}
func (cc *ClientConn) initSendQueue() {
cc.sendInit.Do(func() { cc.sendCh = make(chan Transaction, sendQueueDepth) })
}
// Send enqueues t for delivery to this client by its writer goroutine, preserving enqueue order.
// It never blocks: if the queue is full, the client is considered too slow and its connection is
// closed, which unblocks the client's read loop and triggers the usual Disconnect cleanup.
func (cc *ClientConn) Send(t Transaction) {
cc.initSendQueue()
cc.sendMu.Lock()
defer cc.sendMu.Unlock()
if cc.sendClosed {
return
}
select {
case cc.sendCh <- t:
default:
cc.sendClosed = true
close(cc.sendCh)
if cc.Logger != nil {
cc.Logger.Warn("Send queue full; disconnecting slow client")
}
if cc.Connection != nil {
_ = cc.Connection.Close()
}
}
}
// closeSendQueue idempotently closes the send queue, stopping the client's writer goroutine after
// it drains any remaining queued transactions.
func (cc *ClientConn) closeSendQueue() {
cc.initSendQueue()
cc.sendMu.Lock()
defer cc.sendMu.Unlock()
if !cc.sendClosed {
cc.sendClosed = true
close(cc.sendCh)
}
}
// writeLoop is the single writer to cc.Connection. Serializing all writes through one goroutine
// prevents concurrent sends from interleaving bytes within the connection's transaction framing.
// It runs until the send queue is closed or a write fails.
func (cc *ClientConn) writeLoop() {
cc.initSendQueue()
for t := range cc.sendCh {
if _, err := io.Copy(cc.Connection, &t); err != nil {
if cc.Logger != nil {
cc.Logger.Debug("error writing transaction to client", "err", err)
}
_ = cc.Connection.Close()
return
}
}
}
func (cc *ClientConn) TextDecoder() *encoding.Decoder { return cc.Server.TextDecoder }
func (cc *ClientConn) TextEncoder() *encoding.Encoder { return cc.Server.TextEncoder }
// SetFlag sets the user flag at position flag to v.
func (cc *ClientConn) SetFlag(flag int, v uint) {
cc.mu.Lock()
defer cc.mu.Unlock()
cc.Flags.Set(flag, v)
}
// IsFlagSet reports whether the user flag at position flag is set.
func (cc *ClientConn) IsFlagSet(flag int) bool {
cc.mu.RLock()
defer cc.mu.RUnlock()
return cc.Flags.IsSet(flag)
}
// FlagBytes returns a copy of the user flags bitmap, suitable for use as a transaction field.
func (cc *ClientConn) FlagBytes() []byte {
cc.mu.RLock()
defer cc.mu.RUnlock()
flags := cc.Flags
return flags[:]
}
// SetUserName sets the client's display name.
func (cc *ClientConn) SetUserName(name []byte) {
cc.mu.Lock()
defer cc.mu.Unlock()
cc.UserName = name
}
// GetUserName returns the client's display name. Callers must not modify the returned slice.
func (cc *ClientConn) GetUserName() []byte {
cc.mu.RLock()
defer cc.mu.RUnlock()
return cc.UserName
}
// SetIcon sets the client's icon ID bytes.
func (cc *ClientConn) SetIcon(icon []byte) {
cc.mu.Lock()
defer cc.mu.Unlock()
cc.Icon = icon
}
// GetIcon returns the client's icon ID bytes. Callers must not modify the returned slice.
func (cc *ClientConn) GetIcon() []byte {
cc.mu.RLock()
defer cc.mu.RUnlock()
return cc.Icon
}
// SetAutoReply sets the client's away auto-reply message.
func (cc *ClientConn) SetAutoReply(msg []byte) {
cc.mu.Lock()
defer cc.mu.Unlock()
cc.AutoReply = msg
}
// GetAutoReply returns the client's away auto-reply message. Callers must not modify the
// returned slice.
func (cc *ClientConn) GetAutoReply() []byte {
cc.mu.RLock()
defer cc.mu.RUnlock()
return cc.AutoReply
}
// incrementIdleTime adds interval seconds to the client's idle time. It returns true if this
// crossed the idle threshold and marked the client as away, in which case the caller should
// notify other clients of the change.
func (cc *ClientConn) incrementIdleTime(interval int) bool {
cc.mu.Lock()
defer cc.mu.Unlock()
cc.IdleTime += interval
if cc.IdleTime > userIdleSeconds && !cc.Flags.IsSet(UserFlagAway) {
cc.Flags.Set(UserFlagAway, 1)
return true
}
return false
}
// clearIdleAndAway resets the client's idle timer. It returns true if the client was marked as
// away and is no longer, in which case the caller should notify other clients of the change.
func (cc *ClientConn) clearIdleAndAway() bool {
cc.mu.Lock()
defer cc.mu.Unlock()
cc.IdleTime = 0
if cc.Flags.IsSet(UserFlagAway) {
cc.Flags.Set(UserFlagAway, 0)
return true
}
return false
}
func (cc *ClientConn) FileRoot() string {
if cc.Account.FileRoot != "" {
return cc.Account.FileRoot
}
return cc.Server.Config.FileRoot
}
// IP returns the IP address portion of the client's remote address.
func (cc *ClientConn) IP() string {
ip, _, _ := net.SplitHostPort(cc.RemoteAddr)
return ip
}
type ClientFileTransferMgr struct {
transfers map[FileTransferType]map[FileTransferID]*FileTransfer
mu sync.RWMutex
}
func NewClientFileTransferMgr() ClientFileTransferMgr {
return ClientFileTransferMgr{
transfers: map[FileTransferType]map[FileTransferID]*FileTransfer{
FileDownload: {},
FileUpload: {},
FolderDownload: {},
FolderUpload: {},
BannerDownload: {},
},
}
}
func (cftm *ClientFileTransferMgr) Add(ftType FileTransferType, ft *FileTransfer) {
cftm.mu.Lock()
defer cftm.mu.Unlock()
cftm.transfers[ftType][ft.RefNum] = ft
}
func (cftm *ClientFileTransferMgr) Get(ftType FileTransferType) []FileTransfer {
cftm.mu.Lock()
defer cftm.mu.Unlock()
fts := cftm.transfers[ftType]
var transfers []FileTransfer
for _, ft := range fts {
transfers = append(transfers, *ft)
}
return transfers
}
func (cftm *ClientFileTransferMgr) Delete(ftType FileTransferType, id FileTransferID) {
cftm.mu.Lock()
defer cftm.mu.Unlock()
delete(cftm.transfers[ftType], id)
}
func (cc *ClientConn) SendAll(t [2]byte, fields ...Field) {
for _, c := range cc.Server.ClientMgr.List() {
c.Send(NewTransaction(t, c.ID, fields...))
}
}
func (cc *ClientConn) handleTransaction(transaction Transaction) {
// Contain panics to the individual transaction so a single malformed request
// cannot tear down the whole client connection.
defer dontPanic(cc.Logger)
if handler, ok := cc.Server.handlers[transaction.Type]; ok {
if transaction.Type != TranKeepAlive {
cc.Logger.Info(tranTypeNames[transaction.Type])
}
for _, t := range handler(cc, &transaction) {
cc.Server.Send(t)
}
}
if transaction.Type != TranKeepAlive {
// Reset the user idle timer. If the user was previously marked as away, notify other
// connected clients that the user is no longer away.
if cc.clearIdleAndAway() {
cc.SendAll(
TranNotifyChangeUser,
NewField(FieldUserID, cc.ID[:]),
NewField(FieldUserFlags, cc.FlagBytes()),
NewField(FieldUserName, cc.GetUserName()),
NewField(FieldUserIconID, cc.GetIcon()),
)
}
}
}
func (cc *ClientConn) Authenticate(login string, password []byte) bool {
if account := cc.Server.AccountManager.Get(login); account != nil {
return bcrypt.CompareHashAndPassword([]byte(account.Password), password) == nil
}
return false
}
// Authorize checks if the user account has the specified permission
func (cc *ClientConn) Authorize(access int) bool {
if cc.Account == nil {
return false
}
return cc.Account.Access.IsSet(access)
}
// Disconnect notifies other clients that a client has disconnected and closes the connection.
func (cc *ClientConn) Disconnect() {
// Remove the client from the manager first so no new transactions are routed to it.
cc.Server.ClientMgr.Delete(cc.ID)
for _, t := range cc.NotifyOthers(NewTransaction(TranNotifyDeleteUser, [2]byte{}, NewField(FieldUserID, cc.ID[:]))) {
cc.Server.Send(t)
}
cc.closeSendQueue()
if err := cc.Connection.Close(); err != nil {
cc.Server.Logger.Debug("error closing client connection", "remoteAddr", cc.RemoteAddr)
}
}
// NotifyOthers sends transaction t to other clients connected to the server
func (cc *ClientConn) NotifyOthers(t Transaction) (trans []Transaction) {
for _, c := range cc.Server.ClientMgr.List() {
if c.ID != cc.ID {
t.ClientID = c.ID
trans = append(trans, t)
}
}
return trans
}
// NewReply returns a reply Transaction with fields for the ClientConn
func (cc *ClientConn) NewReply(t *Transaction, fields ...Field) Transaction {
return Transaction{
IsReply: 1,
ID: t.ID,
ClientID: cc.ID,
Fields: fields,
}
}
// NewErrReply returns an error reply Transaction with errMsg
func (cc *ClientConn) NewErrReply(t *Transaction, errMsg string) []Transaction {
return []Transaction{
{
ClientID: cc.ID,
IsReply: 1,
ID: t.ID,
ErrorCode: [4]byte{0, 0, 0, 1},
Fields: []Field{
NewField(FieldError, []byte(errMsg)),
},
},
}
}
const userInfoTemplate = `Nickname: %s
Name: %s
Account: %s
Address: %s
-------- File Downloads ---------
%s
------- Folder Downloads --------
%s
--------- File Uploads ----------
%s
-------- Folder Uploads ---------
%s
------- Waiting Downloads -------
%s
`
func formatDownloadList(fts []FileTransfer) (s string) {
if len(fts) == 0 {
return "None.\n"
}
for _, dl := range fts {
s += dl.String()
}
return s
}
func (cc *ClientConn) String() string {
template := fmt.Sprintf(
userInfoTemplate,
cc.GetUserName(),
cc.Account.Name,
cc.Account.Login,
cc.RemoteAddr,
formatDownloadList(cc.ClientFileTransferMgr.Get(FileDownload)),
formatDownloadList(cc.ClientFileTransferMgr.Get(FolderDownload)),
formatDownloadList(cc.ClientFileTransferMgr.Get(FileUpload)),
formatDownloadList(cc.ClientFileTransferMgr.Get(FolderUpload)),
"None.\n",
)
return strings.ReplaceAll(template, "\n", "\r")
}
|