6 "golang.org/x/crypto/bcrypt"
12 type byClientID []*ClientConn
14 func (s byClientID) Len() int {
18 func (s byClientID) Swap(i, j int) {
19 s[i], s[j] = s[j], s[i]
22 func (s byClientID) Less(i, j int) bool {
23 return s[i].uint16ID() < s[j].uint16ID()
26 const template = `Nickname: %s
31 -------- File Downloads ---------
35 ------- Folder Downloads --------
39 --------- File Uploads ----------
43 -------- Folder Uploads ---------
47 ------- Waiting Downloads -------
53 // ClientConn represents a client connected to a Server
54 type ClientConn struct {
55 Connection io.ReadWriteCloser
67 Transfers map[int][]*FileTransfer
69 logger *zap.SugaredLogger
72 func (cc *ClientConn) sendAll(t int, fields ...Field) {
73 for _, c := range sortedClients(cc.Server.Clients) {
74 cc.Server.outbox <- *NewTransaction(t, c.ID, fields...)
78 func (cc *ClientConn) handleTransaction(transaction *Transaction) error {
79 requestNum := binary.BigEndian.Uint16(transaction.Type)
80 if handler, ok := TransactionHandlers[requestNum]; ok {
81 for _, reqField := range handler.RequiredFields {
82 field := transaction.GetField(reqField.ID)
84 // Validate that required field is present
87 "Missing required field",
88 "RequestType", handler.Name, "FieldID", reqField.ID,
93 if len(field.Data) < reqField.minLen {
95 "Field does not meet minLen",
96 "RequestType", handler.Name, "FieldID", reqField.ID,
102 cc.logger.Infow("Received Transaction", "RequestType", handler.Name)
104 transactions, err := handler.Handler(cc, transaction)
108 for _, t := range transactions {
109 cc.Server.outbox <- t
113 "Unimplemented transaction type received", "RequestID", requestNum)
117 defer cc.Server.mux.Unlock()
119 if requestNum != tranKeepAlive {
120 // reset the user idle timer
123 // if user was previously idle, mark as not idle and notify other connected clients that
124 // the user is no longer away
126 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
127 flagBitmap.SetBit(flagBitmap, userFlagAway, 0)
128 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
132 tranNotifyChangeUser,
133 NewField(fieldUserID, *cc.ID),
134 NewField(fieldUserFlags, *cc.Flags),
135 NewField(fieldUserName, cc.UserName),
136 NewField(fieldUserIconID, *cc.Icon),
144 func (cc *ClientConn) Authenticate(login string, password []byte) bool {
145 if account, ok := cc.Server.Accounts[login]; ok {
146 return bcrypt.CompareHashAndPassword([]byte(account.Password), password) == nil
152 func (cc *ClientConn) uint16ID() uint16 {
153 id, _ := byteToInt(*cc.ID)
157 // Authorize checks if the user account has the specified permission
158 func (cc *ClientConn) Authorize(access int) bool {
159 i := big.NewInt(int64(binary.BigEndian.Uint64(*cc.Account.Access)))
161 return i.Bit(63-access) == 1
164 // Disconnect notifies other clients that a client has disconnected
165 func (cc *ClientConn) Disconnect() {
167 defer cc.Server.mux.Unlock()
169 delete(cc.Server.Clients, binary.BigEndian.Uint16(*cc.ID))
171 for _, t := range cc.notifyOthers(*NewTransaction(tranNotifyDeleteUser, nil, NewField(fieldUserID, *cc.ID))) {
172 cc.Server.outbox <- t
175 if err := cc.Connection.Close(); err != nil {
176 cc.Server.Logger.Errorw("error closing client connection", "RemoteAddr", cc.RemoteAddr)
180 // notifyOthers sends transaction t to other clients connected to the server
181 func (cc *ClientConn) notifyOthers(t Transaction) (trans []Transaction) {
182 for _, c := range sortedClients(cc.Server.Clients) {
183 if c.ID != cc.ID && c.Agreed {
185 trans = append(trans, t)
191 // NewReply returns a reply Transaction with fields for the ClientConn
192 func (cc *ClientConn) NewReply(t *Transaction, fields ...Field) Transaction {
193 reply := Transaction{
199 ErrorCode: []byte{0, 0, 0, 0},
206 // NewErrReply returns an error reply Transaction with errMsg
207 func (cc *ClientConn) NewErrReply(t *Transaction, errMsg string) Transaction {
214 ErrorCode: []byte{0, 0, 0, 1},
216 NewField(fieldError, []byte(errMsg)),
221 // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.
222 // The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work.
223 func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) {
224 for _, c := range unsortedClients {
225 clients = append(clients, c)
227 sort.Sort(byClientID(clients))