18 type TransactionType struct {
19 Handler func(*ClientConn, *Transaction) ([]Transaction, error) // function for handling the transaction type
20 Name string // Name of transaction as it will appear in logging
21 RequiredFields []requiredField
24 var TransactionHandlers = map[uint16]TransactionType{
30 tranNotifyChangeUser: {
31 Name: "tranNotifyChangeUser",
37 Name: "tranShowAgreement",
40 Name: "tranUserAccess",
42 tranNotifyDeleteUser: {
43 Name: "tranNotifyDeleteUser",
47 Handler: HandleTranAgreed,
51 Handler: HandleChatSend,
52 RequiredFields: []requiredField{
60 Name: "tranDelNewsArt",
61 Handler: HandleDelNewsArt,
64 Name: "tranDelNewsItem",
65 Handler: HandleDelNewsItem,
68 Name: "tranDeleteFile",
69 Handler: HandleDeleteFile,
72 Name: "tranDeleteUser",
73 Handler: HandleDeleteUser,
76 Name: "tranDisconnectUser",
77 Handler: HandleDisconnectUser,
80 Name: "tranDownloadFile",
81 Handler: HandleDownloadFile,
84 Name: "tranDownloadFldr",
85 Handler: HandleDownloadFolder,
87 tranGetClientInfoText: {
88 Name: "tranGetClientInfoText",
89 Handler: HandleGetClientInfoText,
92 Name: "tranGetFileInfo",
93 Handler: HandleGetFileInfo,
95 tranGetFileNameList: {
96 Name: "tranGetFileNameList",
97 Handler: HandleGetFileNameList,
101 Handler: HandleGetMsgs,
103 tranGetNewsArtData: {
104 Name: "tranGetNewsArtData",
105 Handler: HandleGetNewsArtData,
107 tranGetNewsArtNameList: {
108 Name: "tranGetNewsArtNameList",
109 Handler: HandleGetNewsArtNameList,
111 tranGetNewsCatNameList: {
112 Name: "tranGetNewsCatNameList",
113 Handler: HandleGetNewsCatNameList,
117 Handler: HandleGetUser,
119 tranGetUserNameList: {
120 Name: "tranHandleGetUserNameList",
121 Handler: HandleGetUserNameList,
124 Name: "tranInviteNewChat",
125 Handler: HandleInviteNewChat,
128 Name: "tranInviteToChat",
129 Handler: HandleInviteToChat,
132 Name: "tranJoinChat",
133 Handler: HandleJoinChat,
136 Name: "tranKeepAlive",
137 Handler: HandleKeepAlive,
140 Name: "tranJoinChat",
141 Handler: HandleLeaveChat,
144 Name: "tranListUsers",
145 Handler: HandleListUsers,
148 Name: "tranMoveFile",
149 Handler: HandleMoveFile,
152 Name: "tranNewFolder",
153 Handler: HandleNewFolder,
156 Name: "tranNewNewsCat",
157 Handler: HandleNewNewsCat,
160 Name: "tranNewNewsFldr",
161 Handler: HandleNewNewsFldr,
165 Handler: HandleNewUser,
168 Name: "tranUpdateUser",
169 Handler: HandleUpdateUser,
172 Name: "tranOldPostNews",
173 Handler: HandleTranOldPostNews,
176 Name: "tranPostNewsArt",
177 Handler: HandlePostNewsArt,
179 tranRejectChatInvite: {
180 Name: "tranRejectChatInvite",
181 Handler: HandleRejectChatInvite,
183 tranSendInstantMsg: {
184 Name: "tranSendInstantMsg",
185 Handler: HandleSendInstantMsg,
186 RequiredFields: []requiredField{
196 tranSetChatSubject: {
197 Name: "tranSetChatSubject",
198 Handler: HandleSetChatSubject,
201 Name: "tranMakeFileAlias",
202 Handler: HandleMakeAlias,
203 RequiredFields: []requiredField{
204 {ID: fieldFileName, minLen: 1},
205 {ID: fieldFilePath, minLen: 1},
206 {ID: fieldFileNewPath, minLen: 1},
209 tranSetClientUserInfo: {
210 Name: "tranSetClientUserInfo",
211 Handler: HandleSetClientUserInfo,
214 Name: "tranSetFileInfo",
215 Handler: HandleSetFileInfo,
219 Handler: HandleSetUser,
222 Name: "tranUploadFile",
223 Handler: HandleUploadFile,
226 Name: "tranUploadFldr",
227 Handler: HandleUploadFolder,
230 Name: "tranUserBroadcast",
231 Handler: HandleUserBroadcast,
233 tranDownloadBanner: {
234 Name: "tranDownloadBanner",
235 Handler: HandleDownloadBanner,
239 func HandleChatSend(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
240 if !cc.Authorize(accessSendChat) {
241 res = append(res, cc.NewErrReply(t, "You are not allowed to participate in chat."))
245 // Truncate long usernames
246 trunc := fmt.Sprintf("%13s", cc.UserName)
247 formattedMsg := fmt.Sprintf("\r%.14s: %s", trunc, t.GetField(fieldData).Data)
249 // By holding the option key, Hotline chat allows users to send /me formatted messages like:
250 // *** Halcyon does stuff
251 // This is indicated by the presence of the optional field fieldChatOptions in the transaction payload
252 if t.GetField(fieldChatOptions).Data != nil {
253 formattedMsg = fmt.Sprintf("\r*** %s %s", cc.UserName, t.GetField(fieldData).Data)
256 chatID := t.GetField(fieldChatID).Data
257 // a non-nil chatID indicates the message belongs to a private chat
259 chatInt := binary.BigEndian.Uint32(chatID)
260 privChat := cc.Server.PrivateChats[chatInt]
262 clients := sortedClients(privChat.ClientConn)
264 // send the message to all connected clients of the private chat
265 for _, c := range clients {
266 res = append(res, *NewTransaction(
269 NewField(fieldChatID, chatID),
270 NewField(fieldData, []byte(formattedMsg)),
276 for _, c := range sortedClients(cc.Server.Clients) {
277 // Filter out clients that do not have the read chat permission
278 if c.Authorize(accessReadChat) {
279 res = append(res, *NewTransaction(tranChatMsg, c.ID, NewField(fieldData, []byte(formattedMsg))))
286 // HandleSendInstantMsg sends instant message to the user on the current server.
287 // Fields used in the request:
290 // One of the following values:
291 // - User message (myOpt_UserMessage = 1)
292 // - Refuse message (myOpt_RefuseMessage = 2)
293 // - Refuse chat (myOpt_RefuseChat = 3)
294 // - Automatic response (myOpt_AutomaticResponse = 4)"
296 // 214 Quoting message Optional
298 // Fields used in the reply:
300 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
301 if !cc.Authorize(accessSendPrivMsg) {
302 res = append(res, cc.NewErrReply(t, "You are not allowed to send private messages."))
306 msg := t.GetField(fieldData)
307 ID := t.GetField(fieldUserID)
309 reply := NewTransaction(
312 NewField(fieldData, msg.Data),
313 NewField(fieldUserName, cc.UserName),
314 NewField(fieldUserID, *cc.ID),
315 NewField(fieldOptions, []byte{0, 1}),
318 // Later versions of Hotline include the original message in the fieldQuotingMsg field so
319 // the receiving client can display both the received message and what it is in reply to
320 if t.GetField(fieldQuotingMsg).Data != nil {
321 reply.Fields = append(reply.Fields, NewField(fieldQuotingMsg, t.GetField(fieldQuotingMsg).Data))
324 id, _ := byteToInt(ID.Data)
325 otherClient, ok := cc.Server.Clients[uint16(id)]
327 return res, errors.New("invalid client ID")
330 // Check if target user has "Refuse private messages" flag
331 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(otherClient.Flags)))
332 if flagBitmap.Bit(userFLagRefusePChat) == 1 {
337 NewField(fieldData, []byte(string(otherClient.UserName)+" does not accept private messages.")),
338 NewField(fieldUserName, otherClient.UserName),
339 NewField(fieldUserID, *otherClient.ID),
340 NewField(fieldOptions, []byte{0, 2}),
344 res = append(res, *reply)
347 // Respond with auto reply if other client has it enabled
348 if len(otherClient.AutoReply) > 0 {
353 NewField(fieldData, otherClient.AutoReply),
354 NewField(fieldUserName, otherClient.UserName),
355 NewField(fieldUserID, *otherClient.ID),
356 NewField(fieldOptions, []byte{0, 1}),
361 res = append(res, cc.NewReply(t))
366 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
367 fileName := t.GetField(fieldFileName).Data
368 filePath := t.GetField(fieldFilePath).Data
370 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
375 fw, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
380 res = append(res, cc.NewReply(t,
381 NewField(fieldFileName, []byte(fw.name)),
382 NewField(fieldFileTypeString, fw.ffo.FlatFileInformationFork.friendlyType()),
383 NewField(fieldFileCreatorString, fw.ffo.FlatFileInformationFork.friendlyCreator()),
384 NewField(fieldFileComment, fw.ffo.FlatFileInformationFork.Comment),
385 NewField(fieldFileType, fw.ffo.FlatFileInformationFork.TypeSignature),
386 NewField(fieldFileCreateDate, fw.ffo.FlatFileInformationFork.CreateDate),
387 NewField(fieldFileModifyDate, fw.ffo.FlatFileInformationFork.ModifyDate),
388 NewField(fieldFileSize, fw.totalSize()),
393 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
394 // Fields used in the request:
396 // * 202 File path Optional
397 // * 211 File new name Optional
398 // * 210 File comment Optional
399 // Fields used in the reply: None
400 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
401 fileName := t.GetField(fieldFileName).Data
402 filePath := t.GetField(fieldFilePath).Data
404 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
409 fi, err := cc.Server.FS.Stat(fullFilePath)
414 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
418 if t.GetField(fieldFileComment).Data != nil {
419 switch mode := fi.Mode(); {
421 if !cc.Authorize(accessSetFolderComment) {
422 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for folders."))
425 case mode.IsRegular():
426 if !cc.Authorize(accessSetFileComment) {
427 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for files."))
432 if err := hlFile.ffo.FlatFileInformationFork.setComment(t.GetField(fieldFileComment).Data); err != nil {
435 w, err := hlFile.infoForkWriter()
439 _, err = w.Write(hlFile.ffo.FlatFileInformationFork.MarshalBinary())
445 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, t.GetField(fieldFileNewName).Data)
450 fileNewName := t.GetField(fieldFileNewName).Data
452 if fileNewName != nil {
453 switch mode := fi.Mode(); {
455 if !cc.Authorize(accessRenameFolder) {
456 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
459 err = os.Rename(fullFilePath, fullNewFilePath)
460 if os.IsNotExist(err) {
461 res = append(res, cc.NewErrReply(t, "Cannot rename folder "+string(fileName)+" because it does not exist or cannot be found."))
464 case mode.IsRegular():
465 if !cc.Authorize(accessRenameFile) {
466 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
469 fileDir, err := readPath(cc.Server.Config.FileRoot, filePath, []byte{})
473 hlFile.name = string(fileNewName)
474 err = hlFile.move(fileDir)
475 if os.IsNotExist(err) {
476 res = append(res, cc.NewErrReply(t, "Cannot rename file "+string(fileName)+" because it does not exist or cannot be found."))
485 res = append(res, cc.NewReply(t))
489 // HandleDeleteFile deletes a file or folder
490 // Fields used in the request:
493 // Fields used in the reply: none
494 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
495 fileName := t.GetField(fieldFileName).Data
496 filePath := t.GetField(fieldFilePath).Data
498 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
503 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
508 fi, err := hlFile.dataFile()
510 res = append(res, cc.NewErrReply(t, "Cannot delete file "+string(fileName)+" because it does not exist or cannot be found."))
514 switch mode := fi.Mode(); {
516 if !cc.Authorize(accessDeleteFolder) {
517 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
520 case mode.IsRegular():
521 if !cc.Authorize(accessDeleteFile) {
522 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
527 if err := hlFile.delete(); err != nil {
531 res = append(res, cc.NewReply(t))
535 // HandleMoveFile moves files or folders. Note: seemingly not documented
536 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
537 fileName := string(t.GetField(fieldFileName).Data)
539 filePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
544 fileNewPath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFileNewPath).Data, nil)
549 cc.logger.Infow("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
551 hlFile, err := newFileWrapper(cc.Server.FS, filePath, 0)
556 fi, err := hlFile.dataFile()
558 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
564 switch mode := fi.Mode(); {
566 if !cc.Authorize(accessMoveFolder) {
567 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
570 case mode.IsRegular():
571 if !cc.Authorize(accessMoveFile) {
572 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
576 if err := hlFile.move(fileNewPath); err != nil {
579 // TODO: handle other possible errors; e.g. fileWrapper delete fails due to fileWrapper permission issue
581 res = append(res, cc.NewReply(t))
585 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
586 if !cc.Authorize(accessCreateFolder) {
587 res = append(res, cc.NewErrReply(t, "You are not allowed to create folders."))
590 folderName := string(t.GetField(fieldFileName).Data)
592 folderName = path.Join("/", folderName)
596 // fieldFilePath is only present for nested paths
597 if t.GetField(fieldFilePath).Data != nil {
599 _, err := newFp.Write(t.GetField(fieldFilePath).Data)
604 for _, pathItem := range newFp.Items {
605 subPath = filepath.Join("/", subPath, string(pathItem.Name))
608 newFolderPath := path.Join(cc.Server.Config.FileRoot, subPath, folderName)
610 // TODO: check path and folder name lengths
612 if _, err := cc.Server.FS.Stat(newFolderPath); !os.IsNotExist(err) {
613 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that name.", folderName)
614 return []Transaction{cc.NewErrReply(t, msg)}, nil
617 // TODO: check for disallowed characters to maintain compatibility for original client
619 if err := cc.Server.FS.Mkdir(newFolderPath, 0777); err != nil {
620 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
621 return []Transaction{cc.NewErrReply(t, msg)}, nil
624 res = append(res, cc.NewReply(t))
628 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
629 if !cc.Authorize(accessModifyUser) {
630 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
634 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
635 userName := string(t.GetField(fieldUserName).Data)
637 newAccessLvl := t.GetField(fieldUserAccess).Data
639 account := cc.Server.Accounts[login]
640 account.Name = userName
641 copy(account.Access[:], newAccessLvl)
643 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
644 // not include fieldUserPassword
645 if t.GetField(fieldUserPassword).Data == nil {
646 account.Password = hashAndSalt([]byte(""))
648 if len(t.GetField(fieldUserPassword).Data) > 1 {
649 account.Password = hashAndSalt(t.GetField(fieldUserPassword).Data)
652 out, err := yaml.Marshal(&account)
656 if err := os.WriteFile(filepath.Join(cc.Server.ConfigDir, "Users", login+".yaml"), out, 0666); err != nil {
660 // Notify connected clients logged in as the user of the new access level
661 for _, c := range cc.Server.Clients {
662 if c.Account.Login == login {
663 // Note: comment out these two lines to test server-side deny messages
664 newT := NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, newAccessLvl))
665 res = append(res, *newT)
667 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
668 if c.Authorize(accessDisconUser) {
669 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 1)
671 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 0)
673 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
675 c.Account.Access = account.Access
678 tranNotifyChangeUser,
679 NewField(fieldUserID, *c.ID),
680 NewField(fieldUserFlags, c.Flags),
681 NewField(fieldUserName, c.UserName),
682 NewField(fieldUserIconID, c.Icon),
687 res = append(res, cc.NewReply(t))
691 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
692 if !cc.Authorize(accessOpenUser) {
693 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
697 account := cc.Server.Accounts[string(t.GetField(fieldUserLogin).Data)]
699 res = append(res, cc.NewErrReply(t, "Account does not exist."))
703 res = append(res, cc.NewReply(t,
704 NewField(fieldUserName, []byte(account.Name)),
705 NewField(fieldUserLogin, negateString(t.GetField(fieldUserLogin).Data)),
706 NewField(fieldUserPassword, []byte(account.Password)),
707 NewField(fieldUserAccess, account.Access[:]),
712 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
713 if !cc.Authorize(accessOpenUser) {
714 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
718 var userFields []Field
719 for _, acc := range cc.Server.Accounts {
720 b := make([]byte, 0, 100)
721 n, err := acc.Read(b)
726 userFields = append(userFields, NewField(fieldData, b[:n]))
729 res = append(res, cc.NewReply(t, userFields...))
733 // HandleUpdateUser is used by the v1.5+ multi-user editor to perform account editing for multiple users at a time.
734 // An update can be a mix of these actions:
737 // * Modify user (including renaming the account login)
739 // The Transaction sent by the client includes one data field per user that was modified. This data field in turn
740 // contains another data field encoded in its payload with a varying number of sub fields depending on which action is
741 // performed. This seems to be the only place in the Hotline protocol where a data field contains another data field.
742 func HandleUpdateUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
743 for _, field := range t.Fields {
744 subFields, err := ReadFields(field.Data[0:2], field.Data[2:])
749 if len(subFields) == 1 {
750 login := DecodeUserString(getField(fieldData, &subFields).Data)
751 cc.logger.Infow("DeleteUser", "login", login)
753 if !cc.Authorize(accessDeleteUser) {
754 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
758 if err := cc.Server.DeleteUser(login); err != nil {
764 login := DecodeUserString(getField(fieldUserLogin, &subFields).Data)
766 // check if the login dataFile; if so, we know we are updating an existing user
767 if acc, ok := cc.Server.Accounts[login]; ok {
768 cc.logger.Infow("UpdateUser", "login", login)
770 // account dataFile, so this is an update action
771 if !cc.Authorize(accessModifyUser) {
772 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
776 if getField(fieldUserPassword, &subFields) != nil {
777 newPass := getField(fieldUserPassword, &subFields).Data
778 acc.Password = hashAndSalt(newPass)
780 acc.Password = hashAndSalt([]byte(""))
783 if getField(fieldUserAccess, &subFields) != nil {
784 copy(acc.Access[:], getField(fieldUserAccess, &subFields).Data)
787 err = cc.Server.UpdateUser(
788 DecodeUserString(getField(fieldData, &subFields).Data),
789 DecodeUserString(getField(fieldUserLogin, &subFields).Data),
790 string(getField(fieldUserName, &subFields).Data),
798 cc.logger.Infow("CreateUser", "login", login)
800 if !cc.Authorize(accessCreateUser) {
801 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
805 newAccess := accessBitmap{}
806 copy(newAccess[:], getField(fieldUserAccess, &subFields).Data[:])
808 err := cc.Server.NewUser(login, string(getField(fieldUserName, &subFields).Data), string(getField(fieldUserPassword, &subFields).Data), newAccess)
810 return []Transaction{}, err
815 res = append(res, cc.NewReply(t))
819 // HandleNewUser creates a new user account
820 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
821 if !cc.Authorize(accessCreateUser) {
822 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
826 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
828 // If the account already dataFile, reply with an error
829 if _, ok := cc.Server.Accounts[login]; ok {
830 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
834 newAccess := accessBitmap{}
835 copy(newAccess[:], t.GetField(fieldUserAccess).Data[:])
837 if err := cc.Server.NewUser(login, string(t.GetField(fieldUserName).Data), string(t.GetField(fieldUserPassword).Data), newAccess); err != nil {
838 return []Transaction{}, err
841 res = append(res, cc.NewReply(t))
845 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
846 if !cc.Authorize(accessDeleteUser) {
847 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
851 // TODO: Handle case where account doesn't exist; e.g. delete race condition
852 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
854 if err := cc.Server.DeleteUser(login); err != nil {
858 res = append(res, cc.NewReply(t))
862 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
863 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
864 if !cc.Authorize(accessBroadcast) {
865 res = append(res, cc.NewErrReply(t, "You are not allowed to send broadcast messages."))
871 NewField(fieldData, t.GetField(tranGetMsgs).Data),
872 NewField(fieldChatOptions, []byte{0}),
875 res = append(res, cc.NewReply(t))
879 func byteToInt(bytes []byte) (int, error) {
882 return int(binary.BigEndian.Uint16(bytes)), nil
884 return int(binary.BigEndian.Uint32(bytes)), nil
887 return 0, errors.New("unknown byte length")
890 // HandleGetClientInfoText returns user information for the specific user.
892 // Fields used in the request:
895 // Fields used in the reply:
897 // 101 Data User info text string
898 func HandleGetClientInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
899 if !cc.Authorize(accessGetClientInfo) {
900 res = append(res, cc.NewErrReply(t, "You are not allowed to get client info."))
904 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
906 clientConn := cc.Server.Clients[uint16(clientID)]
907 if clientConn == nil {
908 return append(res, cc.NewErrReply(t, "User not found.")), err
911 res = append(res, cc.NewReply(t,
912 NewField(fieldData, []byte(clientConn.String())),
913 NewField(fieldUserName, clientConn.UserName),
918 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
919 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
924 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
927 if t.GetField(fieldUserName).Data != nil {
928 if cc.Authorize(accessAnyName) {
929 cc.UserName = t.GetField(fieldUserName).Data
931 cc.UserName = []byte(cc.Account.Name)
935 cc.Icon = t.GetField(fieldUserIconID).Data
937 cc.logger = cc.logger.With("name", string(cc.UserName))
938 cc.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(cc.Version); return i }()))
940 options := t.GetField(fieldOptions).Data
941 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
943 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
945 // Check refuse private PM option
946 if optBitmap.Bit(refusePM) == 1 {
947 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
948 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
951 // Check refuse private chat option
952 if optBitmap.Bit(refuseChat) == 1 {
953 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
954 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
957 // Check auto response
958 if optBitmap.Bit(autoResponse) == 1 {
959 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
961 cc.AutoReply = []byte{}
964 trans := cc.notifyOthers(
966 tranNotifyChangeUser, nil,
967 NewField(fieldUserName, cc.UserName),
968 NewField(fieldUserID, *cc.ID),
969 NewField(fieldUserIconID, cc.Icon),
970 NewField(fieldUserFlags, cc.Flags),
973 res = append(res, trans...)
975 if cc.Server.Config.BannerFile != "" {
976 res = append(res, *NewTransaction(tranServerBanner, cc.ID, NewField(fieldBannerType, []byte("JPEG"))))
979 res = append(res, cc.NewReply(t))
984 const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
985 // "Mon, 02 Jan 2006 15:04:05 MST"
987 const defaultNewsTemplate = `From %s (%s):
991 __________________________________________________________`
993 // HandleTranOldPostNews updates the flat news
994 // Fields used in this request:
996 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
997 if !cc.Authorize(accessNewsPostArt) {
998 res = append(res, cc.NewErrReply(t, "You are not allowed to post news."))
1002 cc.Server.flatNewsMux.Lock()
1003 defer cc.Server.flatNewsMux.Unlock()
1005 newsDateTemplate := defaultNewsDateFormat
1006 if cc.Server.Config.NewsDateFormat != "" {
1007 newsDateTemplate = cc.Server.Config.NewsDateFormat
1010 newsTemplate := defaultNewsTemplate
1011 if cc.Server.Config.NewsDelimiter != "" {
1012 newsTemplate = cc.Server.Config.NewsDelimiter
1015 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
1016 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
1018 // update news on disk
1019 if err := cc.Server.FS.WriteFile(filepath.Join(cc.Server.ConfigDir, "MessageBoard.txt"), cc.Server.FlatNews, 0644); err != nil {
1023 // update news in memory
1024 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
1026 // Notify all clients of updated news
1029 NewField(fieldData, []byte(newsPost)),
1032 res = append(res, cc.NewReply(t))
1036 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1037 if !cc.Authorize(accessDisconUser) {
1038 res = append(res, cc.NewErrReply(t, "You are not allowed to disconnect users."))
1042 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
1044 if clientConn.Authorize(accessCannotBeDiscon) {
1045 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
1049 // If fieldOptions is set, then the client IP is banned in addition to disconnected.
1050 // 00 01 = temporary ban
1051 // 00 02 = permanent ban
1052 if t.GetField(fieldOptions).Data != nil {
1053 switch t.GetField(fieldOptions).Data[1] {
1055 // send message: "You are temporarily banned on this server"
1056 cc.logger.Infow("Disconnect & temporarily ban " + string(clientConn.UserName))
1058 res = append(res, *NewTransaction(
1061 NewField(fieldData, []byte("You are temporarily banned on this server")),
1062 NewField(fieldChatOptions, []byte{0, 0}),
1065 banUntil := time.Now().Add(tempBanDuration)
1066 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = &banUntil
1067 cc.Server.writeBanList()
1069 // send message: "You are permanently banned on this server"
1070 cc.logger.Infow("Disconnect & ban " + string(clientConn.UserName))
1072 res = append(res, *NewTransaction(
1075 NewField(fieldData, []byte("You are permanently banned on this server")),
1076 NewField(fieldChatOptions, []byte{0, 0}),
1079 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = nil
1080 cc.Server.writeBanList()
1084 // TODO: remove this awful hack
1086 time.Sleep(1 * time.Second)
1087 clientConn.Disconnect()
1090 return append(res, cc.NewReply(t)), err
1093 // HandleGetNewsCatNameList returns a list of news categories for a path
1094 // Fields used in the request:
1095 // 325 News path (Optional)
1096 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1097 if !cc.Authorize(accessNewsReadArt) {
1098 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1102 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1103 cats := cc.Server.GetNewsCatByPath(pathStrs)
1105 // To store the keys in slice in sorted order
1106 keys := make([]string, len(cats))
1108 for k := range cats {
1114 var fieldData []Field
1115 for _, k := range keys {
1117 b, _ := cat.MarshalBinary()
1118 fieldData = append(fieldData, NewField(
1119 fieldNewsCatListData15,
1124 res = append(res, cc.NewReply(t, fieldData...))
1128 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1129 if !cc.Authorize(accessNewsCreateCat) {
1130 res = append(res, cc.NewErrReply(t, "You are not allowed to create news categories."))
1134 name := string(t.GetField(fieldNewsCatName).Data)
1135 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1137 cats := cc.Server.GetNewsCatByPath(pathStrs)
1138 cats[name] = NewsCategoryListData15{
1141 Articles: map[uint32]*NewsArtData{},
1142 SubCats: make(map[string]NewsCategoryListData15),
1145 if err := cc.Server.writeThreadedNews(); err != nil {
1148 res = append(res, cc.NewReply(t))
1152 // Fields used in the request:
1153 // 322 News category name
1155 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1156 if !cc.Authorize(accessNewsCreateFldr) {
1157 res = append(res, cc.NewErrReply(t, "You are not allowed to create news folders."))
1161 name := string(t.GetField(fieldFileName).Data)
1162 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1164 cc.logger.Infof("Creating new news folder %s", name)
1166 cats := cc.Server.GetNewsCatByPath(pathStrs)
1167 cats[name] = NewsCategoryListData15{
1170 Articles: map[uint32]*NewsArtData{},
1171 SubCats: make(map[string]NewsCategoryListData15),
1173 if err := cc.Server.writeThreadedNews(); err != nil {
1176 res = append(res, cc.NewReply(t))
1180 // Fields used in the request:
1181 // 325 News path Optional
1184 // 321 News article list data Optional
1185 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1186 if !cc.Authorize(accessNewsReadArt) {
1187 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1190 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1192 var cat NewsCategoryListData15
1193 cats := cc.Server.ThreadedNews.Categories
1195 for _, fp := range pathStrs {
1197 cats = cats[fp].SubCats
1200 nald := cat.GetNewsArtListData()
1202 res = append(res, cc.NewReply(t, NewField(fieldNewsArtListData, nald.Payload())))
1206 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1207 if !cc.Authorize(accessNewsReadArt) {
1208 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1214 // 326 News article ID
1215 // 327 News article data flavor
1217 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1219 var cat NewsCategoryListData15
1220 cats := cc.Server.ThreadedNews.Categories
1222 for _, fp := range pathStrs {
1224 cats = cats[fp].SubCats
1226 newsArtID := t.GetField(fieldNewsArtID).Data
1228 convertedArtID := binary.BigEndian.Uint16(newsArtID)
1230 art := cat.Articles[uint32(convertedArtID)]
1232 res = append(res, cc.NewReply(t))
1237 // 328 News article title
1238 // 329 News article poster
1239 // 330 News article date
1240 // 331 Previous article ID
1241 // 332 Next article ID
1242 // 335 Parent article ID
1243 // 336 First child article ID
1244 // 327 News article data flavor "Should be “text/plain”
1245 // 333 News article data Optional (if data flavor is “text/plain”)
1247 res = append(res, cc.NewReply(t,
1248 NewField(fieldNewsArtTitle, []byte(art.Title)),
1249 NewField(fieldNewsArtPoster, []byte(art.Poster)),
1250 NewField(fieldNewsArtDate, art.Date),
1251 NewField(fieldNewsArtPrevArt, art.PrevArt),
1252 NewField(fieldNewsArtNextArt, art.NextArt),
1253 NewField(fieldNewsArtParentArt, art.ParentArt),
1254 NewField(fieldNewsArt1stChildArt, art.FirstChildArt),
1255 NewField(fieldNewsArtDataFlav, []byte("text/plain")),
1256 NewField(fieldNewsArtData, []byte(art.Data)),
1261 // HandleDelNewsItem deletes an existing threaded news folder or category from the server.
1262 // Fields used in the request:
1264 // Fields used in the reply:
1266 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1267 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1269 cats := cc.Server.ThreadedNews.Categories
1270 delName := pathStrs[len(pathStrs)-1]
1271 if len(pathStrs) > 1 {
1272 for _, fp := range pathStrs[0 : len(pathStrs)-1] {
1273 cats = cats[fp].SubCats
1277 if bytes.Compare(cats[delName].Type, []byte{0, 3}) == 0 {
1278 if !cc.Authorize(accessNewsDeleteCat) {
1279 return append(res, cc.NewErrReply(t, "You are not allowed to delete news categories.")), nil
1282 if !cc.Authorize(accessNewsDeleteFldr) {
1283 return append(res, cc.NewErrReply(t, "You are not allowed to delete news folders.")), nil
1287 delete(cats, delName)
1289 if err := cc.Server.writeThreadedNews(); err != nil {
1293 return append(res, cc.NewReply(t)), nil
1296 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1297 if !cc.Authorize(accessNewsDeleteArt) {
1298 res = append(res, cc.NewErrReply(t, "You are not allowed to delete news articles."))
1304 // 326 News article ID
1305 // 337 News article – recursive delete Delete child articles (1) or not (0)
1306 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1307 ID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1309 // TODO: Delete recursive
1310 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1312 catName := pathStrs[len(pathStrs)-1]
1313 cat := cats[catName]
1315 delete(cat.Articles, uint32(ID))
1318 if err := cc.Server.writeThreadedNews(); err != nil {
1322 res = append(res, cc.NewReply(t))
1328 // 326 News article ID ID of the parent article?
1329 // 328 News article title
1330 // 334 News article flags
1331 // 327 News article data flavor Currently “text/plain”
1332 // 333 News article data
1333 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1334 if !cc.Authorize(accessNewsPostArt) {
1335 res = append(res, cc.NewErrReply(t, "You are not allowed to post news articles."))
1339 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1340 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1342 catName := pathStrs[len(pathStrs)-1]
1343 cat := cats[catName]
1345 newArt := NewsArtData{
1346 Title: string(t.GetField(fieldNewsArtTitle).Data),
1347 Poster: string(cc.UserName),
1348 Date: toHotlineTime(time.Now()),
1349 PrevArt: []byte{0, 0, 0, 0},
1350 NextArt: []byte{0, 0, 0, 0},
1351 ParentArt: append([]byte{0, 0}, t.GetField(fieldNewsArtID).Data...),
1352 FirstChildArt: []byte{0, 0, 0, 0},
1353 DataFlav: []byte("text/plain"),
1354 Data: string(t.GetField(fieldNewsArtData).Data),
1358 for k := range cat.Articles {
1359 keys = append(keys, int(k))
1365 prevID := uint32(keys[len(keys)-1])
1368 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1370 // Set next article ID
1371 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1374 // Update parent article with first child reply
1375 parentID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1377 parentArt := cat.Articles[uint32(parentID)]
1379 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1380 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1384 cat.Articles[nextID] = &newArt
1387 if err := cc.Server.writeThreadedNews(); err != nil {
1391 res = append(res, cc.NewReply(t))
1395 // HandleGetMsgs returns the flat news data
1396 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1397 if !cc.Authorize(accessNewsReadArt) {
1398 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1402 res = append(res, cc.NewReply(t, NewField(fieldData, cc.Server.FlatNews)))
1407 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1408 if !cc.Authorize(accessDownloadFile) {
1409 res = append(res, cc.NewErrReply(t, "You are not allowed to download files."))
1413 fileName := t.GetField(fieldFileName).Data
1414 filePath := t.GetField(fieldFilePath).Data
1415 resumeData := t.GetField(fieldFileResumeData).Data
1417 var dataOffset int64
1418 var frd FileResumeData
1419 if resumeData != nil {
1420 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1423 // TODO: handle rsrc fork offset
1424 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1427 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1432 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, dataOffset)
1437 xferSize := hlFile.ffo.TransferSize(0)
1439 ft := cc.newFileTransfer(FileDownload, fileName, filePath, xferSize)
1441 // TODO: refactor to remove this
1442 if resumeData != nil {
1443 var frd FileResumeData
1444 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1447 ft.fileResumeData = &frd
1450 // Optional field for when a HL v1.5+ client requests file preview
1451 // Used only for TEXT, JPEG, GIFF, BMP or PICT files
1452 // The value will always be 2
1453 if t.GetField(fieldFileTransferOptions).Data != nil {
1454 ft.options = t.GetField(fieldFileTransferOptions).Data
1455 xferSize = hlFile.ffo.FlatFileDataForkHeader.DataSize[:]
1458 res = append(res, cc.NewReply(t,
1459 NewField(fieldRefNum, ft.refNum[:]),
1460 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1461 NewField(fieldTransferSize, xferSize),
1462 NewField(fieldFileSize, hlFile.ffo.FlatFileDataForkHeader.DataSize[:]),
1468 // Download all files from the specified folder and sub-folders
1469 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1470 if !cc.Authorize(accessDownloadFile) {
1471 res = append(res, cc.NewErrReply(t, "You are not allowed to download folders."))
1475 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
1480 transferSize, err := CalcTotalSize(fullFilePath)
1484 itemCount, err := CalcItemCount(fullFilePath)
1489 fileTransfer := cc.newFileTransfer(FolderDownload, t.GetField(fieldFileName).Data, t.GetField(fieldFilePath).Data, transferSize)
1492 _, err = fp.Write(t.GetField(fieldFilePath).Data)
1497 res = append(res, cc.NewReply(t,
1498 NewField(fieldRefNum, fileTransfer.ReferenceNumber),
1499 NewField(fieldTransferSize, transferSize),
1500 NewField(fieldFolderItemCount, itemCount),
1501 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1506 // Upload all files from the local folder and its subfolders to the specified path on the server
1507 // Fields used in the request
1510 // 108 transfer size Total size of all items in the folder
1511 // 220 Folder item count
1512 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1513 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1515 if t.GetField(fieldFilePath).Data != nil {
1516 if _, err = fp.Write(t.GetField(fieldFilePath).Data); err != nil {
1521 // Handle special cases for Upload and Drop Box folders
1522 if !cc.Authorize(accessUploadAnywhere) {
1523 if !fp.IsUploadDir() && !fp.IsDropbox() {
1524 res = append(res, cc.NewErrReply(t, fmt.Sprintf("Cannot accept upload of the folder \"%v\" because you are only allowed to upload to the \"Uploads\" folder.", string(t.GetField(fieldFileName).Data))))
1529 fileTransfer := cc.newFileTransfer(FolderUpload,
1530 t.GetField(fieldFileName).Data,
1531 t.GetField(fieldFilePath).Data,
1532 t.GetField(fieldTransferSize).Data,
1535 fileTransfer.FolderItemCount = t.GetField(fieldFolderItemCount).Data
1537 res = append(res, cc.NewReply(t, NewField(fieldRefNum, fileTransfer.ReferenceNumber)))
1542 // Fields used in the request:
1545 // 204 File transfer options "Optional
1546 // Used only to resume download, currently has value 2"
1547 // 108 File transfer size "Optional used if download is not resumed"
1548 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1549 if !cc.Authorize(accessUploadFile) {
1550 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1554 fileName := t.GetField(fieldFileName).Data
1555 filePath := t.GetField(fieldFilePath).Data
1556 transferOptions := t.GetField(fieldFileTransferOptions).Data
1557 transferSize := t.GetField(fieldTransferSize).Data // not sent for resume
1560 if filePath != nil {
1561 if _, err = fp.Write(filePath); err != nil {
1566 // Handle special cases for Upload and Drop Box folders
1567 if !cc.Authorize(accessUploadAnywhere) {
1568 if !fp.IsUploadDir() && !fp.IsDropbox() {
1569 res = append(res, cc.NewErrReply(t, fmt.Sprintf("Cannot accept upload of the file \"%v\" because you are only allowed to upload to the \"Uploads\" folder.", string(fileName))))
1573 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1578 if _, err := cc.Server.FS.Stat(fullFilePath); err == nil {
1579 res = append(res, cc.NewErrReply(t, fmt.Sprintf("Cannot accept upload because there is already a file named \"%v\". Try choosing a different name.", string(fileName))))
1583 ft := cc.newFileTransfer(FileUpload, fileName, filePath, transferSize)
1585 replyT := cc.NewReply(t, NewField(fieldRefNum, ft.ReferenceNumber))
1587 // client has requested to resume a partially transferred file
1588 if transferOptions != nil {
1590 fileInfo, err := cc.Server.FS.Stat(fullFilePath + incompleteFileSuffix)
1595 offset := make([]byte, 4)
1596 binary.BigEndian.PutUint32(offset, uint32(fileInfo.Size()))
1598 fileResumeData := NewFileResumeData([]ForkInfoList{
1599 *NewForkInfoList(offset),
1602 b, _ := fileResumeData.BinaryMarshal()
1604 ft.TransferSize = offset
1606 replyT.Fields = append(replyT.Fields, NewField(fieldFileResumeData, b))
1609 res = append(res, replyT)
1613 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1614 if len(t.GetField(fieldUserIconID).Data) == 4 {
1615 cc.Icon = t.GetField(fieldUserIconID).Data[2:]
1617 cc.Icon = t.GetField(fieldUserIconID).Data
1619 if cc.Authorize(accessAnyName) {
1620 cc.UserName = t.GetField(fieldUserName).Data
1623 // the options field is only passed by the client versions > 1.2.3.
1624 options := t.GetField(fieldOptions).Data
1626 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1627 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
1629 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, optBitmap.Bit(refusePM))
1630 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1632 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, optBitmap.Bit(refuseChat))
1633 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1635 // Check auto response
1636 if optBitmap.Bit(autoResponse) == 1 {
1637 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
1639 cc.AutoReply = []byte{}
1643 for _, c := range sortedClients(cc.Server.Clients) {
1644 res = append(res, *NewTransaction(
1645 tranNotifyChangeUser,
1647 NewField(fieldUserID, *cc.ID),
1648 NewField(fieldUserIconID, cc.Icon),
1649 NewField(fieldUserFlags, cc.Flags),
1650 NewField(fieldUserName, cc.UserName),
1657 // HandleKeepAlive responds to keepalive transactions with an empty reply
1658 // * HL 1.9.2 Client sends keepalive msg every 3 minutes
1659 // * HL 1.2.3 Client doesn't send keepalives
1660 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1661 res = append(res, cc.NewReply(t))
1666 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1667 fullPath, err := readPath(
1668 cc.Server.Config.FileRoot,
1669 t.GetField(fieldFilePath).Data,
1677 if t.GetField(fieldFilePath).Data != nil {
1678 if _, err = fp.Write(t.GetField(fieldFilePath).Data); err != nil {
1683 // Handle special case for drop box folders
1684 if fp.IsDropbox() && !cc.Authorize(accessViewDropBoxes) {
1685 res = append(res, cc.NewErrReply(t, "You are not allowed to view drop boxes."))
1689 fileNames, err := getFileNameList(fullPath, cc.Server.Config.IgnoreFiles)
1694 res = append(res, cc.NewReply(t, fileNames...))
1699 // =================================
1700 // Hotline private chat flow
1701 // =================================
1702 // 1. ClientA sends tranInviteNewChat to server with user ID to invite
1703 // 2. Server creates new ChatID
1704 // 3. Server sends tranInviteToChat to invitee
1705 // 4. Server replies to ClientA with new Chat ID
1707 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1708 // If Accepted is clicked:
1709 // 1. ClientB sends tranJoinChat with fieldChatID
1711 // HandleInviteNewChat invites users to new private chat
1712 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1713 if !cc.Authorize(accessOpenChat) {
1714 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1719 targetID := t.GetField(fieldUserID).Data
1720 newChatID := cc.Server.NewPrivateChat(cc)
1722 // Check if target user has "Refuse private chat" flag
1723 binary.BigEndian.Uint16(targetID)
1724 targetClient := cc.Server.Clients[binary.BigEndian.Uint16(targetID)]
1726 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(targetClient.Flags)))
1727 if flagBitmap.Bit(userFLagRefusePChat) == 1 {
1732 NewField(fieldData, []byte(string(targetClient.UserName)+" does not accept private chats.")),
1733 NewField(fieldUserName, targetClient.UserName),
1734 NewField(fieldUserID, *targetClient.ID),
1735 NewField(fieldOptions, []byte{0, 2}),
1743 NewField(fieldChatID, newChatID),
1744 NewField(fieldUserName, cc.UserName),
1745 NewField(fieldUserID, *cc.ID),
1752 NewField(fieldChatID, newChatID),
1753 NewField(fieldUserName, cc.UserName),
1754 NewField(fieldUserID, *cc.ID),
1755 NewField(fieldUserIconID, cc.Icon),
1756 NewField(fieldUserFlags, cc.Flags),
1763 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1764 if !cc.Authorize(accessOpenChat) {
1765 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1770 targetID := t.GetField(fieldUserID).Data
1771 chatID := t.GetField(fieldChatID).Data
1777 NewField(fieldChatID, chatID),
1778 NewField(fieldUserName, cc.UserName),
1779 NewField(fieldUserID, *cc.ID),
1785 NewField(fieldChatID, chatID),
1786 NewField(fieldUserName, cc.UserName),
1787 NewField(fieldUserID, *cc.ID),
1788 NewField(fieldUserIconID, cc.Icon),
1789 NewField(fieldUserFlags, cc.Flags),
1796 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1797 chatID := t.GetField(fieldChatID).Data
1798 chatInt := binary.BigEndian.Uint32(chatID)
1800 privChat := cc.Server.PrivateChats[chatInt]
1802 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1804 for _, c := range sortedClients(privChat.ClientConn) {
1809 NewField(fieldChatID, chatID),
1810 NewField(fieldData, resMsg),
1818 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1819 // Fields used in the reply:
1820 // * 115 Chat subject
1821 // * 300 User name with info (Optional)
1822 // * 300 (more user names with info)
1823 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1824 chatID := t.GetField(fieldChatID).Data
1825 chatInt := binary.BigEndian.Uint32(chatID)
1827 privChat := cc.Server.PrivateChats[chatInt]
1829 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1830 for _, c := range sortedClients(privChat.ClientConn) {
1833 tranNotifyChatChangeUser,
1835 NewField(fieldChatID, chatID),
1836 NewField(fieldUserName, cc.UserName),
1837 NewField(fieldUserID, *cc.ID),
1838 NewField(fieldUserIconID, cc.Icon),
1839 NewField(fieldUserFlags, cc.Flags),
1844 privChat.ClientConn[cc.uint16ID()] = cc
1846 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1847 for _, c := range sortedClients(privChat.ClientConn) {
1852 Name: string(c.UserName),
1855 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1858 res = append(res, cc.NewReply(t, replyFields...))
1862 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1863 // Fields used in the request:
1864 // * 114 fieldChatID
1865 // Reply is not expected.
1866 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1867 chatID := t.GetField(fieldChatID).Data
1868 chatInt := binary.BigEndian.Uint32(chatID)
1870 privChat, ok := cc.Server.PrivateChats[chatInt]
1875 delete(privChat.ClientConn, cc.uint16ID())
1877 // Notify members of the private chat that the user has left
1878 for _, c := range sortedClients(privChat.ClientConn) {
1881 tranNotifyChatDeleteUser,
1883 NewField(fieldChatID, chatID),
1884 NewField(fieldUserID, *cc.ID),
1892 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1893 // Fields used in the request:
1895 // * 115 Chat subject Chat subject string
1896 // Reply is not expected.
1897 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1898 chatID := t.GetField(fieldChatID).Data
1899 chatInt := binary.BigEndian.Uint32(chatID)
1901 privChat := cc.Server.PrivateChats[chatInt]
1902 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1904 for _, c := range sortedClients(privChat.ClientConn) {
1907 tranNotifyChatSubject,
1909 NewField(fieldChatID, chatID),
1910 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),
1918 // HandleMakeAlias makes a filer alias using the specified path.
1919 // Fields used in the request:
1922 // 212 File new path Destination path
1924 // Fields used in the reply:
1926 func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1927 if !cc.Authorize(accessMakeAlias) {
1928 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
1931 fileName := t.GetField(fieldFileName).Data
1932 filePath := t.GetField(fieldFilePath).Data
1933 fileNewPath := t.GetField(fieldFileNewPath).Data
1935 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1940 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
1945 cc.logger.Debugw("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
1947 if err := cc.Server.FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
1948 res = append(res, cc.NewErrReply(t, "Error creating alias"))
1952 res = append(res, cc.NewReply(t))
1956 // HandleDownloadBanner handles requests for a new banner from the server
1957 // Fields used in the request:
1959 // Fields used in the reply:
1960 // 107 fieldRefNum Used later for transfer
1961 // 108 fieldTransferSize Size of data to be downloaded
1962 func HandleDownloadBanner(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1963 fi, err := cc.Server.FS.Stat(filepath.Join(cc.Server.ConfigDir, cc.Server.Config.BannerFile))
1968 ft := cc.newFileTransfer(bannerDownload, []byte{}, []byte{}, make([]byte, 4))
1970 binary.BigEndian.PutUint32(ft.TransferSize, uint32(fi.Size()))
1972 res = append(res, cc.NewReply(t,
1973 NewField(fieldRefNum, ft.refNum[:]),
1974 NewField(fieldTransferSize, ft.TransferSize),