7 "golang.org/x/crypto/bcrypt"
15 type byClientID []*ClientConn
17 func (s byClientID) Len() int {
21 func (s byClientID) Swap(i, j int) {
22 s[i], s[j] = s[j], s[i]
25 func (s byClientID) Less(i, j int) bool {
26 return s[i].uint16ID() < s[j].uint16ID()
29 // ClientConn represents a client connected to a Server
30 type ClientConn struct {
31 Connection io.ReadWriteCloser
44 transfersMU sync.Mutex
45 transfers map[int]map[[4]byte]*FileTransfer
48 logger *zap.SugaredLogger
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...)
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)
63 // Validate that required field is present
66 "Missing required field",
67 "RequestType", handler.Name, "FieldID", reqField.ID,
72 if len(field.Data) < reqField.minLen {
74 "Field does not meet minLen",
75 "RequestType", handler.Name, "FieldID", reqField.ID,
81 cc.logger.Debugw("Received Transaction", "RequestType", handler.Name)
83 transactions, err := handler.Handler(cc, &transaction)
87 for _, t := range transactions {
92 "Unimplemented transaction type received", "RequestID", requestNum)
96 defer cc.Server.mux.Unlock()
98 if requestNum != tranKeepAlive {
99 // reset the user idle timer
102 // if user was previously idle, mark as not idle and notify other connected clients that
103 // the user is no longer away
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()))
111 tranNotifyChangeUser,
112 NewField(fieldUserID, *cc.ID),
113 NewField(fieldUserFlags, cc.Flags),
114 NewField(fieldUserName, cc.UserName),
115 NewField(fieldUserIconID, cc.Icon),
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
131 func (cc *ClientConn) uint16ID() uint16 {
132 id, _ := byteToInt(*cc.ID)
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)
141 // Disconnect notifies other clients that a client has disconnected
142 func (cc *ClientConn) Disconnect() {
144 defer cc.Server.mux.Unlock()
146 delete(cc.Server.Clients, binary.BigEndian.Uint16(*cc.ID))
148 for _, t := range cc.notifyOthers(*NewTransaction(tranNotifyDeleteUser, nil, NewField(fieldUserID, *cc.ID))) {
149 cc.Server.outbox <- t
152 if err := cc.Connection.Close(); err != nil {
153 cc.Server.Logger.Errorw("error closing client connection", "RemoteAddr", cc.RemoteAddr)
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 {
162 trans = append(trans, t)
168 // NewReply returns a reply Transaction with fields for the ClientConn
169 func (cc *ClientConn) NewReply(t *Transaction, fields ...Field) Transaction {
170 reply := Transaction{
173 Type: []byte{0x00, 0x00},
176 ErrorCode: []byte{0, 0, 0, 0},
183 // NewErrReply returns an error reply Transaction with errMsg
184 func (cc *ClientConn) NewErrReply(t *Transaction, errMsg string) Transaction {
191 ErrorCode: []byte{0, 0, 0, 1},
193 NewField(fieldError, []byte(errMsg)),
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)
204 sort.Sort(byClientID(clients))
208 const userInfoTemplate = `Nickname: %s
213 -------- File Downloads ---------
216 ------- Folder Downloads --------
219 --------- File Uploads ----------
222 -------- Folder Uploads ---------
225 ------- Waiting Downloads -------
230 func formatDownloadList(fts map[[4]byte]*FileTransfer) (s string) {
235 for _, dl := range fts {
242 func (cc *ClientConn) String() string {
243 cc.transfersMU.Lock()
244 defer cc.transfersMU.Unlock()
245 template := fmt.Sprintf(
251 formatDownloadList(cc.transfers[FileDownload]),
252 formatDownloadList(cc.transfers[FolderDownload]),
253 formatDownloadList(cc.transfers[FileUpload]),
254 formatDownloadList(cc.transfers[FolderUpload]),
258 return strings.Replace(template, "\n", "\r", -1)