]> git.r.bdr.sh - rbdr/mobius/blob - hotline/client_conn.go
Merge pull request #76 from jhalter/fix_scanner_slice_reuse
[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 return cc.Account.Access.IsSet(access)
139 }
140
141 // Disconnect notifies other clients that a client has disconnected
142 func (cc *ClientConn) Disconnect() {
143 cc.Server.mux.Lock()
144 defer cc.Server.mux.Unlock()
145
146 delete(cc.Server.Clients, binary.BigEndian.Uint16(*cc.ID))
147
148 for _, t := range cc.notifyOthers(*NewTransaction(tranNotifyDeleteUser, nil, NewField(fieldUserID, *cc.ID))) {
149 cc.Server.outbox <- t
150 }
151
152 if err := cc.Connection.Close(); err != nil {
153 cc.Server.Logger.Errorw("error closing client connection", "RemoteAddr", cc.RemoteAddr)
154 }
155 }
156
157 // notifyOthers sends transaction t to other clients connected to the server
158 func (cc *ClientConn) notifyOthers(t Transaction) (trans []Transaction) {
159 for _, c := range sortedClients(cc.Server.Clients) {
160 if c.ID != cc.ID && c.Agreed {
161 t.clientID = c.ID
162 trans = append(trans, t)
163 }
164 }
165 return trans
166 }
167
168 // NewReply returns a reply Transaction with fields for the ClientConn
169 func (cc *ClientConn) NewReply(t *Transaction, fields ...Field) Transaction {
170 reply := Transaction{
171 Flags: 0x00,
172 IsReply: 0x01,
173 Type: t.Type,
174 ID: t.ID,
175 clientID: cc.ID,
176 ErrorCode: []byte{0, 0, 0, 0},
177 Fields: fields,
178 }
179
180 return reply
181 }
182
183 // NewErrReply returns an error reply Transaction with errMsg
184 func (cc *ClientConn) NewErrReply(t *Transaction, errMsg string) Transaction {
185 return Transaction{
186 clientID: cc.ID,
187 Flags: 0x00,
188 IsReply: 0x01,
189 Type: []byte{0, 0},
190 ID: t.ID,
191 ErrorCode: []byte{0, 0, 0, 1},
192 Fields: []Field{
193 NewField(fieldError, []byte(errMsg)),
194 },
195 }
196 }
197
198 // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.
199 // The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work.
200 func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) {
201 for _, c := range unsortedClients {
202 clients = append(clients, c)
203 }
204 sort.Sort(byClientID(clients))
205 return clients
206 }
207
208 const userInfoTemplate = `Nickname: %s
209 Name: %s
210 Account: %s
211 Address: %s
212
213 -------- File Downloads ---------
214
215 %s
216 ------- Folder Downloads --------
217
218 %s
219 --------- File Uploads ----------
220
221 %s
222 -------- Folder Uploads ---------
223
224 %s
225 ------- Waiting Downloads -------
226
227 %s
228 `
229
230 func formatDownloadList(fts map[[4]byte]*FileTransfer) (s string) {
231 if len(fts) == 0 {
232 return "None.\n"
233 }
234
235 for _, dl := range fts {
236 s += dl.String()
237 }
238
239 return s
240 }
241
242 func (cc *ClientConn) String() string {
243 cc.transfersMU.Lock()
244 defer cc.transfersMU.Unlock()
245 template := fmt.Sprintf(
246 userInfoTemplate,
247 cc.UserName,
248 cc.Account.Name,
249 cc.Account.Login,
250 cc.RemoteAddr,
251 formatDownloadList(cc.transfers[FileDownload]),
252 formatDownloadList(cc.transfers[FolderDownload]),
253 formatDownloadList(cc.transfers[FileUpload]),
254 formatDownloadList(cc.transfers[FolderUpload]),
255 "None.\n",
256 )
257
258 return strings.Replace(template, "\n", "\r", -1)
259 }