7 "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 // ClientConn represents a client connected to a Server
27 type ClientConn struct {
39 Transfers map[int][]*FileTransfer
43 func (cc *ClientConn) sendAll(t int, fields ...Field) {
44 for _, c := range sortedClients(cc.Server.Clients) {
45 cc.Server.outbox <- *NewTransaction(t, c.ID, fields...)
49 func (cc *ClientConn) handleTransaction(transaction *Transaction) error {
50 requestNum := binary.BigEndian.Uint16(transaction.Type)
51 if handler, ok := TransactionHandlers[requestNum]; ok {
52 for _, reqField := range handler.RequiredFields {
53 field := transaction.GetField(reqField.ID)
55 // Validate that required field is present
57 cc.Server.Logger.Infow(
58 "Missing required field",
59 "Account", cc.Account.Login, "UserName", string(cc.UserName), "RequestType", handler.Name, "FieldID", reqField.ID,
64 if len(field.Data) < reqField.minLen {
65 cc.Server.Logger.Infow(
66 "Field does not meet minLen",
67 "Account", cc.Account.Login, "UserName", string(cc.UserName), "RequestType", handler.Name, "FieldID", reqField.ID,
72 if !authorize(cc.Account.Access, handler.Access) {
73 cc.Server.Logger.Infow(
74 "Unauthorized Action",
75 "Account", cc.Account.Login, "UserName", string(cc.UserName), "RequestType", handler.Name,
77 cc.Server.outbox <- cc.NewErrReply(transaction, handler.DenyMsg)
82 cc.Server.Logger.Infow(
83 "Received Transaction",
84 "login", cc.Account.Login,
85 "name", string(cc.UserName),
86 "RequestType", handler.Name,
89 transactions, err := handler.Handler(cc, transaction)
93 for _, t := range transactions {
97 cc.Server.Logger.Errorw(
98 "Unimplemented transaction type received",
99 "UserName", string(cc.UserName), "RequestID", requestNum,
104 defer cc.Server.mux.Unlock()
106 if requestNum != tranKeepAlive {
107 // reset the user idle timer
110 // if user was previously idle, mark as not idle and notify other connected clients that
111 // the user is no longer away
113 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
114 flagBitmap.SetBit(flagBitmap, userFlagAway, 0)
115 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
119 tranNotifyChangeUser,
120 NewField(fieldUserID, *cc.ID),
121 NewField(fieldUserFlags, *cc.Flags),
122 NewField(fieldUserName, cc.UserName),
123 NewField(fieldUserIconID, *cc.Icon),
131 func (cc *ClientConn) Authenticate(login string, password []byte) bool {
132 if account, ok := cc.Server.Accounts[login]; ok {
133 return bcrypt.CompareHashAndPassword([]byte(account.Password), password) == nil
139 func (cc *ClientConn) uint16ID() uint16 {
140 id, _ := byteToInt(*cc.ID)
144 // Authorize checks if the user account has the specified permission
145 func (cc *ClientConn) Authorize(access int) bool {
150 accessBitmap := big.NewInt(int64(binary.BigEndian.Uint64(*cc.Account.Access)))
152 return accessBitmap.Bit(63-access) == 1
155 // Disconnect notifies other clients that a client has disconnected
156 func (cc ClientConn) Disconnect() {
158 defer cc.Server.mux.Unlock()
160 delete(cc.Server.Clients, binary.BigEndian.Uint16(*cc.ID))
162 cc.NotifyOthers(*NewTransaction(tranNotifyDeleteUser, nil, NewField(fieldUserID, *cc.ID)))
164 if err := cc.Connection.Close(); err != nil {
165 cc.Server.Logger.Errorw("error closing client connection", "RemoteAddr", cc.Connection.RemoteAddr())
169 // NotifyOthers sends transaction t to other clients connected to the server
170 func (cc ClientConn) NotifyOthers(t Transaction) {
171 for _, c := range sortedClients(cc.Server.Clients) {
172 if c.ID != cc.ID && c.Agreed {
174 cc.Server.outbox <- t
179 type handshake struct {
180 Protocol [4]byte // Must be 0x54525450 TRTP
182 Version [2]byte // Always 1
187 // After establishing TCP connection, both client and server start the handshake process
188 // in order to confirm that each of them comply with requirements of the other.
189 // The information provided in this initial data exchange identifies protocols,
190 // and their versions, used in the communication. In the case where, after inspection,
191 // the capabilities of one of the subjects do not comply with the requirements of the other,
192 // the connection is dropped.
194 // The following information is sent to the server:
195 // Description Size Data Note
196 // Protocol ID 4 TRTP 0x54525450
197 // Sub-protocol ID 4 HOTL User defined
198 // VERSION 2 1 Currently 1
199 // Sub-version 2 2 User defined
201 // The server replies with the following:
202 // Description Size Data Note
203 // Protocol ID 4 TRTP
204 //Error code 4 Error code returned by the server (0 = no error)
205 func Handshake(conn net.Conn, buf []byte) error {
207 r := bytes.NewReader(buf)
208 if err := binary.Read(r, binary.BigEndian, &h); err != nil {
212 if h.Protocol != [4]byte{0x54, 0x52, 0x54, 0x50} {
213 return errors.New("invalid handshake")
216 _, err := conn.Write([]byte{84, 82, 84, 80, 0, 0, 0, 0})
220 // NewReply returns a reply Transaction with fields for the ClientConn
221 func (cc *ClientConn) NewReply(t *Transaction, fields ...Field) Transaction {
222 reply := Transaction{
228 ErrorCode: []byte{0, 0, 0, 0},
235 // NewErrReply returns an error reply Transaction with errMsg
236 func (cc *ClientConn) NewErrReply(t *Transaction, errMsg string) Transaction {
243 ErrorCode: []byte{0, 0, 0, 1},
245 NewField(fieldError, []byte(errMsg)),