]> git.r.bdr.sh - rbdr/mobius/blame_incremental - hotline/client_conn.go
Refactoring and cleanup
[rbdr/mobius] / hotline / client_conn.go
... / ...
CommitLineData
1package hotline
2
3import (
4 "encoding/binary"
5 "fmt"
6 "golang.org/x/crypto/bcrypt"
7 "io"
8 "log/slog"
9 "math/big"
10 "sort"
11 "strings"
12 "sync"
13)
14
15type byClientID []*ClientConn
16
17func (s byClientID) Len() int {
18 return len(s)
19}
20
21func (s byClientID) Swap(i, j int) {
22 s[i], s[j] = s[j], s[i]
23}
24
25func (s byClientID) Less(i, j int) bool {
26 return s[i].uint16ID() < s[j].uint16ID()
27}
28
29// ClientConn represents a client connected to a Server
30type ClientConn struct {
31 Connection io.ReadWriteCloser
32 RemoteAddr string
33 ID *[]byte
34 Icon []byte
35 Flags []byte
36 UserName []byte
37 Account *Account
38 IdleTime int
39 Server *Server
40 Version []byte
41 Idle bool
42 AutoReply []byte
43
44 transfersMU sync.Mutex
45 transfers map[int]map[[4]byte]*FileTransfer
46
47 logger *slog.Logger
48}
49
50func (cc *ClientConn) sendAll(t int, fields ...Field) {
51 for _, c := range sortedClients(cc.Server.Clients) {
52 cc.Server.outbox <- *NewTransaction(t, c.ID, fields...)
53 }
54}
55
56func (cc *ClientConn) handleTransaction(transaction Transaction) error {
57 requestNum := binary.BigEndian.Uint16(transaction.Type)
58 if handler, ok := TransactionHandlers[requestNum]; ok {
59 for _, reqField := range handler.RequiredFields {
60 field := transaction.GetField(reqField.ID)
61
62 // Validate that required field is present
63 if field.ID == [2]byte{0, 0} {
64 cc.logger.Error(
65 "Missing required field",
66 "RequestType", handler.Name, "FieldID", reqField.ID,
67 )
68 return nil
69 }
70
71 if len(field.Data) < reqField.minLen {
72 cc.logger.Info(
73 "Field does not meet minLen",
74 "RequestType", handler.Name, "FieldID", reqField.ID,
75 )
76 return nil
77 }
78 }
79
80 cc.logger.Debug("Received Transaction", "RequestType", handler.Name)
81
82 transactions, err := handler.Handler(cc, &transaction)
83 if err != nil {
84 return err
85 }
86 for _, t := range transactions {
87 cc.Server.outbox <- t
88 }
89 } else {
90 cc.logger.Error(
91 "Unimplemented transaction type received", "RequestID", requestNum)
92 }
93
94 cc.Server.mux.Lock()
95 defer cc.Server.mux.Unlock()
96
97 if requestNum != TranKeepAlive {
98 // reset the user idle timer
99 cc.IdleTime = 0
100
101 // if user was previously idle, mark as not idle and notify other connected clients that
102 // the user is no longer away
103 if cc.Idle {
104 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
105 flagBitmap.SetBit(flagBitmap, UserFlagAway, 0)
106 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
107 cc.Idle = false
108
109 cc.sendAll(
110 TranNotifyChangeUser,
111 NewField(FieldUserID, *cc.ID),
112 NewField(FieldUserFlags, cc.Flags),
113 NewField(FieldUserName, cc.UserName),
114 NewField(FieldUserIconID, cc.Icon),
115 )
116 }
117 }
118
119 return nil
120}
121
122func (cc *ClientConn) Authenticate(login string, password []byte) bool {
123 if account, ok := cc.Server.Accounts[login]; ok {
124 return bcrypt.CompareHashAndPassword([]byte(account.Password), password) == nil
125 }
126
127 return false
128}
129
130func (cc *ClientConn) uint16ID() uint16 {
131 id, _ := byteToInt(*cc.ID)
132 return uint16(id)
133}
134
135// Authorize checks if the user account has the specified permission
136func (cc *ClientConn) Authorize(access int) bool {
137 return cc.Account.Access.IsSet(access)
138}
139
140// Disconnect notifies other clients that a client has disconnected
141func (cc *ClientConn) Disconnect() {
142 cc.Server.mux.Lock()
143 defer cc.Server.mux.Unlock()
144
145 delete(cc.Server.Clients, binary.BigEndian.Uint16(*cc.ID))
146
147 for _, t := range cc.notifyOthers(*NewTransaction(TranNotifyDeleteUser, nil, NewField(FieldUserID, *cc.ID))) {
148 cc.Server.outbox <- t
149 }
150
151 if err := cc.Connection.Close(); err != nil {
152 cc.Server.Logger.Error("error closing client connection", "RemoteAddr", cc.RemoteAddr)
153 }
154}
155
156// notifyOthers sends transaction t to other clients connected to the server
157func (cc *ClientConn) notifyOthers(t Transaction) (trans []Transaction) {
158 for _, c := range sortedClients(cc.Server.Clients) {
159 if c.ID != cc.ID {
160 t.clientID = c.ID
161 trans = append(trans, t)
162 }
163 }
164 return trans
165}
166
167// NewReply returns a reply Transaction with fields for the ClientConn
168func (cc *ClientConn) NewReply(t *Transaction, fields ...Field) Transaction {
169 return Transaction{
170 Flags: 0x00,
171 IsReply: 0x01,
172 Type: []byte{0x00, 0x00},
173 ID: t.ID,
174 clientID: cc.ID,
175 ErrorCode: []byte{0, 0, 0, 0},
176 Fields: fields,
177 }
178}
179
180// NewErrReply returns an error reply Transaction with errMsg
181func (cc *ClientConn) NewErrReply(t *Transaction, errMsg string) Transaction {
182 return Transaction{
183 clientID: cc.ID,
184 Flags: 0x00,
185 IsReply: 0x01,
186 Type: []byte{0, 0},
187 ID: t.ID,
188 ErrorCode: []byte{0, 0, 0, 1},
189 Fields: []Field{
190 NewField(FieldError, []byte(errMsg)),
191 },
192 }
193}
194
195// sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.
196// The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work.
197func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) {
198 for _, c := range unsortedClients {
199 clients = append(clients, c)
200 }
201 sort.Sort(byClientID(clients))
202 return clients
203}
204
205const userInfoTemplate = `Nickname: %s
206Name: %s
207Account: %s
208Address: %s
209
210-------- File Downloads ---------
211
212%s
213------- Folder Downloads --------
214
215%s
216--------- File Uploads ----------
217
218%s
219-------- Folder Uploads ---------
220
221%s
222------- Waiting Downloads -------
223
224%s
225`
226
227func formatDownloadList(fts map[[4]byte]*FileTransfer) (s string) {
228 if len(fts) == 0 {
229 return "None.\n"
230 }
231
232 for _, dl := range fts {
233 s += dl.String()
234 }
235
236 return s
237}
238
239func (cc *ClientConn) String() string {
240 cc.transfersMU.Lock()
241 defer cc.transfersMU.Unlock()
242 template := fmt.Sprintf(
243 userInfoTemplate,
244 cc.UserName,
245 cc.Account.Name,
246 cc.Account.Login,
247 cc.RemoteAddr,
248 formatDownloadList(cc.transfers[FileDownload]),
249 formatDownloadList(cc.transfers[FolderDownload]),
250 formatDownloadList(cc.transfers[FileUpload]),
251 formatDownloadList(cc.transfers[FolderUpload]),
252 "None.\n",
253 )
254
255 return strings.ReplaceAll(template, "\n", "\r")
256}