6 "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
50 func (cc *ClientConn) sendAll(t int, fields ...Field) {
51 for _, c := range sortedClients(cc.Server.Clients) {
52 cc.Server.outbox <- *NewTransaction(t, c.ID, fields...)
56 func (cc *ClientConn) handleTransaction(transaction Transaction) error {
57 requestNum := binary.BigEndian.Uint16(transaction.Type[:])
58 if handler, ok := TransactionHandlers[requestNum]; ok {
59 for _, reqField := range handler.RequiredFields {
60 field := transaction.GetField(reqField.ID)
62 // Validate that required field is present
63 if field.ID == [2]byte{0, 0} {
65 "Missing required field",
66 "RequestType", handler.Name, "FieldID", reqField.ID,
71 if len(field.Data) < reqField.minLen {
73 "Field does not meet minLen",
74 "RequestType", handler.Name, "FieldID", reqField.ID,
80 cc.logger.Debug("Received Transaction", "RequestType", handler.Name)
82 transactions, err := handler.Handler(cc, &transaction)
84 return fmt.Errorf("error handling transaction: %w", err)
86 for _, t := range transactions {
91 "Unimplemented transaction type received", "RequestID", requestNum)
95 defer cc.Server.mux.Unlock()
97 if requestNum != TranKeepAlive {
98 // reset the user idle timer
101 // if user was previously idle, mark as not idle and notify other connected clients that
102 // the user is no longer away
104 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
105 flagBitmap.SetBit(flagBitmap, UserFlagAway, 0)
106 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
110 TranNotifyChangeUser,
111 NewField(FieldUserID, *cc.ID),
112 NewField(FieldUserFlags, cc.Flags),
113 NewField(FieldUserName, cc.UserName),
114 NewField(FieldUserIconID, cc.Icon),
122 func (cc *ClientConn) Authenticate(login string, password []byte) bool {
123 if account, ok := cc.Server.Accounts[login]; ok {
124 return bcrypt.CompareHashAndPassword([]byte(account.Password), password) == nil
130 func (cc *ClientConn) uint16ID() uint16 {
131 id, _ := byteToInt(*cc.ID)
135 // Authorize checks if the user account has the specified permission
136 func (cc *ClientConn) Authorize(access int) bool {
137 return cc.Account.Access.IsSet(access)
140 // Disconnect notifies other clients that a client has disconnected
141 func (cc *ClientConn) Disconnect() {
143 defer cc.Server.mux.Unlock()
145 delete(cc.Server.Clients, binary.BigEndian.Uint16(*cc.ID))
147 for _, t := range cc.notifyOthers(*NewTransaction(TranNotifyDeleteUser, nil, NewField(FieldUserID, *cc.ID))) {
148 cc.Server.outbox <- t
151 if err := cc.Connection.Close(); err != nil {
152 cc.Server.Logger.Error("error closing client connection", "RemoteAddr", cc.RemoteAddr)
156 // notifyOthers sends transaction t to other clients connected to the server
157 func (cc *ClientConn) notifyOthers(t Transaction) (trans []Transaction) {
158 for _, c := range sortedClients(cc.Server.Clients) {
161 trans = append(trans, t)
167 // NewReply returns a reply Transaction with fields for the ClientConn
168 func (cc *ClientConn) NewReply(t *Transaction, fields ...Field) Transaction {
171 Type: [2]byte{0x00, 0x00},
174 ErrorCode: [4]byte{0, 0, 0, 0},
179 // NewErrReply returns an error reply Transaction with errMsg
180 func (cc *ClientConn) NewErrReply(t *Transaction, errMsg string) Transaction {
186 ErrorCode: [4]byte{0, 0, 0, 1},
188 NewField(FieldError, []byte(errMsg)),
193 // sortedClients is a utility function that takes a map of *ClientConn and returns a sorted slice of the values.
194 // The purpose of this is to ensure that the ordering of client connections is deterministic so that test assertions work.
195 func sortedClients(unsortedClients map[uint16]*ClientConn) (clients []*ClientConn) {
196 for _, c := range unsortedClients {
197 clients = append(clients, c)
199 sort.Sort(byClientID(clients))
203 const userInfoTemplate = `Nickname: %s
208 -------- File Downloads ---------
211 ------- Folder Downloads --------
214 --------- File Uploads ----------
217 -------- Folder Uploads ---------
220 ------- Waiting Downloads -------
225 func formatDownloadList(fts map[[4]byte]*FileTransfer) (s string) {
230 for _, dl := range fts {
237 func (cc *ClientConn) String() string {
238 cc.transfersMU.Lock()
239 defer cc.transfersMU.Unlock()
240 template := fmt.Sprintf(
246 formatDownloadList(cc.transfers[FileDownload]),
247 formatDownloadList(cc.transfers[FolderDownload]),
248 formatDownloadList(cc.transfers[FileUpload]),
249 formatDownloadList(cc.transfers[FolderUpload]),
253 return strings.ReplaceAll(template, "\n", "\r")