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
42 func (cc *ClientConn) sendAll(t int, fields ...Field) {
43 for _, c := range sortedClients(cc.Server.Clients) {
44 cc.Server.outbox <- *NewTransaction(t, c.ID, fields...)
48 func (cc *ClientConn) handleTransaction(transaction *Transaction) error {
49 requestNum := binary.BigEndian.Uint16(transaction.Type)
50 if handler, ok := TransactionHandlers[requestNum]; ok {
51 for _, reqField := range handler.RequiredFields {
52 field := transaction.GetField(reqField.ID)
54 // Validate that required field is present
56 cc.Server.Logger.Infow(
57 "Missing required field",
58 "Account", cc.Account.Login, "UserName", string(*cc.UserName), "RequestType", handler.Name, "FieldID", reqField.ID,
63 if len(field.Data) < reqField.minLen {
64 cc.Server.Logger.Infow(
65 "Field does not meet minLen",
66 "Account", cc.Account.Login, "UserName", string(*cc.UserName), "RequestType", handler.Name, "FieldID", reqField.ID,
71 if !authorize(cc.Account.Access, handler.Access) {
72 cc.Server.Logger.Infow(
73 "Unauthorized Action",
74 "Account", cc.Account.Login, "UserName", string(*cc.UserName), "RequestType", handler.Name,
76 cc.Server.outbox <- cc.NewErrReply(transaction, handler.DenyMsg)
81 cc.Server.Logger.Infow(
82 "Received Transaction",
83 "login", cc.Account.Login,
84 "name", string(*cc.UserName),
85 "RequestType", handler.Name,
88 transactions, err := handler.Handler(cc, transaction)
92 for _, t := range transactions {
96 cc.Server.Logger.Errorw(
97 "Unimplemented transaction type received",
98 "UserName", string(*cc.UserName), "RequestID", requestNum,
103 defer cc.Server.mux.Unlock()
105 // if user was idle and this is a non-keepalive transaction
106 if *cc.IdleTime > userIdleSeconds && requestNum != tranKeepAlive {
107 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
108 flagBitmap.SetBit(flagBitmap, userFlagAway, 0)
109 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
114 tranNotifyChangeUser,
115 NewField(fieldUserID, *cc.ID),
116 NewField(fieldUserFlags, *cc.Flags),
117 NewField(fieldUserName, *cc.UserName),
118 NewField(fieldUserIconID, *cc.Icon),
124 // TODO: Don't we need to skip this if requestNum == tranKeepalive ??
130 func (cc *ClientConn) Authenticate(login string, password []byte) bool {
131 if account, ok := cc.Server.Accounts[login]; ok {
132 return bcrypt.CompareHashAndPassword([]byte(account.Password), password) == nil
138 func (cc *ClientConn) uint16ID() uint16 {
139 id, _ := byteToInt(*cc.ID)
143 // Authorize checks if the user account has the specified permission
144 func (cc *ClientConn) Authorize(access int) bool {
149 accessBitmap := big.NewInt(int64(binary.BigEndian.Uint64(*cc.Account.Access)))
151 return accessBitmap.Bit(63-access) == 1
154 // Disconnect notifies other clients that a client has disconnected
155 func (cc ClientConn) Disconnect() {
157 defer cc.Server.mux.Unlock()
159 delete(cc.Server.Clients, binary.BigEndian.Uint16(*cc.ID))
161 cc.NotifyOthers(*NewTransaction(tranNotifyDeleteUser, nil, NewField(fieldUserID, *cc.ID)))
163 if err := cc.Connection.Close(); err != nil {
164 cc.Server.Logger.Errorw("error closing client connection", "RemoteAddr", cc.Connection.RemoteAddr())
168 // NotifyOthers sends transaction t to other clients connected to the server
169 func (cc ClientConn) NotifyOthers(t Transaction) {
170 for _, c := range sortedClients(cc.Server.Clients) {
173 cc.Server.outbox <- t
178 type handshake struct {
179 Protocol [4]byte // Must be 0x54525450 TRTP
181 Version [2]byte // Always 1
186 // After establishing TCP connection, both client and server start the handshake process
187 // in order to confirm that each of them comply with requirements of the other.
188 // The information provided in this initial data exchange identifies protocols,
189 // and their versions, used in the communication. In the case where, after inspection,
190 // the capabilities of one of the subjects do not comply with the requirements of the other,
191 // the connection is dropped.
193 // The following information is sent to the server:
194 // Description Size Data Note
195 // Protocol ID 4 TRTP 0x54525450
196 // Sub-protocol ID 4 HOTL User defined
197 // VERSION 2 1 Currently 1
198 // Sub-version 2 2 User defined
200 // The server replies with the following:
201 // Description Size Data Note
202 // Protocol ID 4 TRTP
203 //Error code 4 Error code returned by the server (0 = no error)
204 func Handshake(conn net.Conn, buf []byte) error {
206 r := bytes.NewReader(buf)
207 if err := binary.Read(r, binary.BigEndian, &h); err != nil {
211 if h.Protocol != [4]byte{0x54, 0x52, 0x54, 0x50} {
212 return errors.New("invalid handshake")
215 _, err := conn.Write([]byte{84, 82, 84, 80, 0, 0, 0, 0})
219 // NewReply returns a reply Transaction with fields for the ClientConn
220 func (cc *ClientConn) NewReply(t *Transaction, fields ...Field) Transaction {
221 reply := Transaction{
227 ErrorCode: []byte{0, 0, 0, 0},
234 // NewErrReply returns an error reply Transaction with errMsg
235 func (cc *ClientConn) NewErrReply(t *Transaction, errMsg string) Transaction {
242 ErrorCode: []byte{0, 0, 0, 1},
244 NewField(fieldError, []byte(errMsg)),