]> git.r.bdr.sh - rbdr/mobius/blame - hotline/client_conn.go
patch: v0.10.8
[rbdr/mobius] / hotline / client_conn.go
CommitLineData
6988a057
JH
1package hotline
2
3import (
6988a057 4 "encoding/binary"
df1ade54 5 "fmt"
67db911d 6 "go.uber.org/zap"
6988a057 7 "golang.org/x/crypto/bcrypt"
d4c152a4 8 "io"
6988a057 9 "math/big"
7cd900d6 10 "sort"
df1ade54
JH
11 "strings"
12 "sync"
6988a057
JH
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 {
d4c152a4
JH
31 Connection io.ReadWriteCloser
32 RemoteAddr string
6988a057 33 ID *[]byte
a7216f67
JH
34 Icon []byte
35 Flags []byte
72dd37f1 36 UserName []byte
6988a057 37 Account *Account
61c272e1 38 IdleTime int
6988a057 39 Server *Server
a7216f67 40 Version []byte
6988a057 41 Idle bool
aebc4d36 42 AutoReply []byte
df1ade54
JH
43
44 transfersMU sync.Mutex
45 transfers map[int]map[[4]byte]*FileTransfer
46
47 Agreed bool
48 logger *zap.SugaredLogger
6988a057
JH
49}
50
51func (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
3178ae58 57func (cc *ClientConn) handleTransaction(transaction Transaction) error {
6988a057
JH
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 {
0fcfa5d5 65 cc.logger.Errorw(
6988a057 66 "Missing required field",
0fcfa5d5 67 "RequestType", handler.Name, "FieldID", reqField.ID,
6988a057
JH
68 )
69 return nil
70 }
71
72 if len(field.Data) < reqField.minLen {
0fcfa5d5 73 cc.logger.Infow(
6988a057 74 "Field does not meet minLen",
0fcfa5d5 75 "RequestType", handler.Name, "FieldID", reqField.ID,
6988a057
JH
76 )
77 return nil
78 }
79 }
6988a057 80
0da28a1f 81 cc.logger.Debugw("Received Transaction", "RequestType", handler.Name)
6988a057 82
3178ae58 83 transactions, err := handler.Handler(cc, &transaction)
6988a057
JH
84 if err != nil {
85 return err
86 }
87 for _, t := range transactions {
88 cc.Server.outbox <- t
89 }
90 } else {
0fcfa5d5
JH
91 cc.logger.Errorw(
92 "Unimplemented transaction type received", "RequestID", requestNum)
6988a057
JH
93 }
94
95 cc.Server.mux.Lock()
96 defer cc.Server.mux.Unlock()
97
61c272e1
JH
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 {
a7216f67 105 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
61c272e1 106 flagBitmap.SetBit(flagBitmap, userFlagAway, 0)
a7216f67 107 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
61c272e1
JH
108 cc.Idle = false
109
110 cc.sendAll(
111 tranNotifyChangeUser,
112 NewField(fieldUserID, *cc.ID),
a7216f67 113 NewField(fieldUserFlags, cc.Flags),
61c272e1 114 NewField(fieldUserName, cc.UserName),
a7216f67 115 NewField(fieldUserIconID, cc.Icon),
61c272e1
JH
116 )
117 }
6988a057
JH
118 }
119
6988a057
JH
120 return nil
121}
122
123func (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
131func (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
137func (cc *ClientConn) Authorize(access int) bool {
187d6dc5 138 return cc.Account.Access.IsSet(access)
6988a057
JH
139}
140
141// Disconnect notifies other clients that a client has disconnected
0a92e50b 142func (cc *ClientConn) Disconnect() {
6988a057
JH
143 cc.Server.mux.Lock()
144 defer cc.Server.mux.Unlock()
145
146 delete(cc.Server.Clients, binary.BigEndian.Uint16(*cc.ID))
147
21581958
JH
148 for _, t := range cc.notifyOthers(*NewTransaction(tranNotifyDeleteUser, nil, NewField(fieldUserID, *cc.ID))) {
149 cc.Server.outbox <- t
150 }
6988a057
JH
151
152 if err := cc.Connection.Close(); err != nil {
d4c152a4 153 cc.Server.Logger.Errorw("error closing client connection", "RemoteAddr", cc.RemoteAddr)
6988a057
JH
154 }
155}
156
003a743e 157// notifyOthers sends transaction t to other clients connected to the server
21581958 158func (cc *ClientConn) notifyOthers(t Transaction) (trans []Transaction) {
6988a057 159 for _, c := range sortedClients(cc.Server.Clients) {
bd1ce113 160 if c.ID != cc.ID && c.Agreed {
6988a057 161 t.clientID = c.ID
21581958 162 trans = append(trans, t)
6988a057
JH
163 }
164 }
21581958 165 return trans
6988a057
JH
166}
167
6988a057
JH
168// NewReply returns a reply Transaction with fields for the ClientConn
169func (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
184func (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}
7cd900d6
JH
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.
200func 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}
df1ade54
JH
207
208const userInfoTemplate = `Nickname: %s
209Name: %s
210Account: %s
211Address: %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
230func 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
242func (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}