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