18 type HandlerFunc func(*ClientConn, *Transaction) ([]Transaction, error)
20 type TransactionType struct {
21 Handler HandlerFunc // function for handling the transaction type
22 Name string // Name of transaction as it will appear in logging
23 RequiredFields []requiredField
26 var TransactionHandlers = map[uint16]TransactionType{
32 TranNotifyChangeUser: {
33 Name: "TranNotifyChangeUser",
39 Name: "TranShowAgreement",
42 Name: "TranUserAccess",
44 TranNotifyDeleteUser: {
45 Name: "TranNotifyDeleteUser",
49 Handler: HandleTranAgreed,
53 Handler: HandleChatSend,
54 RequiredFields: []requiredField{
62 Name: "TranDelNewsArt",
63 Handler: HandleDelNewsArt,
66 Name: "TranDelNewsItem",
67 Handler: HandleDelNewsItem,
70 Name: "TranDeleteFile",
71 Handler: HandleDeleteFile,
74 Name: "TranDeleteUser",
75 Handler: HandleDeleteUser,
78 Name: "TranDisconnectUser",
79 Handler: HandleDisconnectUser,
82 Name: "TranDownloadFile",
83 Handler: HandleDownloadFile,
86 Name: "TranDownloadFldr",
87 Handler: HandleDownloadFolder,
89 TranGetClientInfoText: {
90 Name: "TranGetClientInfoText",
91 Handler: HandleGetClientInfoText,
94 Name: "TranGetFileInfo",
95 Handler: HandleGetFileInfo,
97 TranGetFileNameList: {
98 Name: "TranGetFileNameList",
99 Handler: HandleGetFileNameList,
103 Handler: HandleGetMsgs,
105 TranGetNewsArtData: {
106 Name: "TranGetNewsArtData",
107 Handler: HandleGetNewsArtData,
109 TranGetNewsArtNameList: {
110 Name: "TranGetNewsArtNameList",
111 Handler: HandleGetNewsArtNameList,
113 TranGetNewsCatNameList: {
114 Name: "TranGetNewsCatNameList",
115 Handler: HandleGetNewsCatNameList,
119 Handler: HandleGetUser,
121 TranGetUserNameList: {
122 Name: "tranHandleGetUserNameList",
123 Handler: HandleGetUserNameList,
126 Name: "TranInviteNewChat",
127 Handler: HandleInviteNewChat,
130 Name: "TranInviteToChat",
131 Handler: HandleInviteToChat,
134 Name: "TranJoinChat",
135 Handler: HandleJoinChat,
138 Name: "TranKeepAlive",
139 Handler: HandleKeepAlive,
142 Name: "TranJoinChat",
143 Handler: HandleLeaveChat,
146 Name: "TranListUsers",
147 Handler: HandleListUsers,
150 Name: "TranMoveFile",
151 Handler: HandleMoveFile,
154 Name: "TranNewFolder",
155 Handler: HandleNewFolder,
158 Name: "TranNewNewsCat",
159 Handler: HandleNewNewsCat,
162 Name: "TranNewNewsFldr",
163 Handler: HandleNewNewsFldr,
167 Handler: HandleNewUser,
170 Name: "TranUpdateUser",
171 Handler: HandleUpdateUser,
174 Name: "TranOldPostNews",
175 Handler: HandleTranOldPostNews,
178 Name: "TranPostNewsArt",
179 Handler: HandlePostNewsArt,
181 TranRejectChatInvite: {
182 Name: "TranRejectChatInvite",
183 Handler: HandleRejectChatInvite,
185 TranSendInstantMsg: {
186 Name: "TranSendInstantMsg",
187 Handler: HandleSendInstantMsg,
188 RequiredFields: []requiredField{
198 TranSetChatSubject: {
199 Name: "TranSetChatSubject",
200 Handler: HandleSetChatSubject,
203 Name: "TranMakeFileAlias",
204 Handler: HandleMakeAlias,
205 RequiredFields: []requiredField{
206 {ID: FieldFileName, minLen: 1},
207 {ID: FieldFilePath, minLen: 1},
208 {ID: FieldFileNewPath, minLen: 1},
211 TranSetClientUserInfo: {
212 Name: "TranSetClientUserInfo",
213 Handler: HandleSetClientUserInfo,
216 Name: "TranSetFileInfo",
217 Handler: HandleSetFileInfo,
221 Handler: HandleSetUser,
224 Name: "TranUploadFile",
225 Handler: HandleUploadFile,
228 Name: "TranUploadFldr",
229 Handler: HandleUploadFolder,
232 Name: "TranUserBroadcast",
233 Handler: HandleUserBroadcast,
235 TranDownloadBanner: {
236 Name: "TranDownloadBanner",
237 Handler: HandleDownloadBanner,
241 func HandleChatSend(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
242 if !cc.Authorize(accessSendChat) {
243 res = append(res, cc.NewErrReply(t, "You are not allowed to participate in chat."))
247 // Truncate long usernames
248 trunc := fmt.Sprintf("%13s", cc.UserName)
249 formattedMsg := fmt.Sprintf("\r%.14s: %s", trunc, t.GetField(FieldData).Data)
251 // By holding the option key, Hotline chat allows users to send /me formatted messages like:
252 // *** Halcyon does stuff
253 // This is indicated by the presence of the optional field FieldChatOptions set to a value of 1.
254 // Most clients do not send this option for normal chat messages.
255 if t.GetField(FieldChatOptions).Data != nil && bytes.Equal(t.GetField(FieldChatOptions).Data, []byte{0, 1}) {
256 formattedMsg = fmt.Sprintf("\r*** %s %s", cc.UserName, t.GetField(FieldData).Data)
259 // The ChatID field is used to identify messages as belonging to a private chat.
260 // All clients *except* Frogblast omit this field for public chat, but Frogblast sends a value of 00 00 00 00.
261 chatID := t.GetField(FieldChatID).Data
262 if chatID != nil && !bytes.Equal([]byte{0, 0, 0, 0}, chatID) {
263 chatInt := binary.BigEndian.Uint32(chatID)
264 privChat := cc.Server.PrivateChats[chatInt]
266 clients := sortedClients(privChat.ClientConn)
268 // send the message to all connected clients of the private chat
269 for _, c := range clients {
270 res = append(res, *NewTransaction(
273 NewField(FieldChatID, chatID),
274 NewField(FieldData, []byte(formattedMsg)),
280 for _, c := range sortedClients(cc.Server.Clients) {
281 // Filter out clients that do not have the read chat permission
282 if c.Authorize(accessReadChat) {
283 res = append(res, *NewTransaction(TranChatMsg, c.ID, NewField(FieldData, []byte(formattedMsg))))
290 // HandleSendInstantMsg sends instant message to the user on the current server.
291 // Fields used in the request:
295 // One of the following values:
296 // - User message (myOpt_UserMessage = 1)
297 // - Refuse message (myOpt_RefuseMessage = 2)
298 // - Refuse chat (myOpt_RefuseChat = 3)
299 // - Automatic response (myOpt_AutomaticResponse = 4)"
301 // 214 Quoting message Optional
303 // Fields used in the reply:
305 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
306 if !cc.Authorize(accessSendPrivMsg) {
307 res = append(res, cc.NewErrReply(t, "You are not allowed to send private messages."))
308 return res, errors.New("user is not allowed to send private messages")
311 msg := t.GetField(FieldData)
312 ID := t.GetField(FieldUserID)
314 reply := NewTransaction(
317 NewField(FieldData, msg.Data),
318 NewField(FieldUserName, cc.UserName),
319 NewField(FieldUserID, *cc.ID),
320 NewField(FieldOptions, []byte{0, 1}),
323 // Later versions of Hotline include the original message in the FieldQuotingMsg field so
324 // the receiving client can display both the received message and what it is in reply to
325 if t.GetField(FieldQuotingMsg).Data != nil {
326 reply.Fields = append(reply.Fields, NewField(FieldQuotingMsg, t.GetField(FieldQuotingMsg).Data))
329 id, err := byteToInt(ID.Data)
331 return res, errors.New("invalid client ID")
333 otherClient, ok := cc.Server.Clients[uint16(id)]
335 return res, errors.New("invalid client ID")
338 // Check if target user has "Refuse private messages" flag
339 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(otherClient.Flags)))
340 if flagBitmap.Bit(UserFlagRefusePChat) == 1 {
345 NewField(FieldData, []byte(string(otherClient.UserName)+" does not accept private messages.")),
346 NewField(FieldUserName, otherClient.UserName),
347 NewField(FieldUserID, *otherClient.ID),
348 NewField(FieldOptions, []byte{0, 2}),
352 res = append(res, *reply)
355 // Respond with auto reply if other client has it enabled
356 if len(otherClient.AutoReply) > 0 {
361 NewField(FieldData, otherClient.AutoReply),
362 NewField(FieldUserName, otherClient.UserName),
363 NewField(FieldUserID, *otherClient.ID),
364 NewField(FieldOptions, []byte{0, 1}),
369 res = append(res, cc.NewReply(t))
374 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
375 fileName := t.GetField(FieldFileName).Data
376 filePath := t.GetField(FieldFilePath).Data
378 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
383 fw, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
388 res = append(res, cc.NewReply(t,
389 NewField(FieldFileName, []byte(fw.name)),
390 NewField(FieldFileTypeString, fw.ffo.FlatFileInformationFork.friendlyType()),
391 NewField(FieldFileCreatorString, fw.ffo.FlatFileInformationFork.friendlyCreator()),
392 NewField(FieldFileComment, fw.ffo.FlatFileInformationFork.Comment),
393 NewField(FieldFileType, fw.ffo.FlatFileInformationFork.TypeSignature),
394 NewField(FieldFileCreateDate, fw.ffo.FlatFileInformationFork.CreateDate),
395 NewField(FieldFileModifyDate, fw.ffo.FlatFileInformationFork.ModifyDate),
396 NewField(FieldFileSize, fw.totalSize()),
401 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
402 // Fields used in the request:
404 // * 202 File path Optional
405 // * 211 File new name Optional
406 // * 210 File comment Optional
407 // Fields used in the reply: None
408 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
409 fileName := t.GetField(FieldFileName).Data
410 filePath := t.GetField(FieldFilePath).Data
412 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
417 fi, err := cc.Server.FS.Stat(fullFilePath)
422 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
426 if t.GetField(FieldFileComment).Data != nil {
427 switch mode := fi.Mode(); {
429 if !cc.Authorize(accessSetFolderComment) {
430 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for folders."))
433 case mode.IsRegular():
434 if !cc.Authorize(accessSetFileComment) {
435 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for files."))
440 if err := hlFile.ffo.FlatFileInformationFork.setComment(t.GetField(FieldFileComment).Data); err != nil {
443 w, err := hlFile.infoForkWriter()
447 _, err = w.Write(hlFile.ffo.FlatFileInformationFork.MarshalBinary())
453 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, t.GetField(FieldFileNewName).Data)
458 fileNewName := t.GetField(FieldFileNewName).Data
460 if fileNewName != nil {
461 switch mode := fi.Mode(); {
463 if !cc.Authorize(accessRenameFolder) {
464 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
467 err = os.Rename(fullFilePath, fullNewFilePath)
468 if os.IsNotExist(err) {
469 res = append(res, cc.NewErrReply(t, "Cannot rename folder "+string(fileName)+" because it does not exist or cannot be found."))
472 case mode.IsRegular():
473 if !cc.Authorize(accessRenameFile) {
474 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
477 fileDir, err := readPath(cc.Server.Config.FileRoot, filePath, []byte{})
481 hlFile.name = string(fileNewName)
482 err = hlFile.move(fileDir)
483 if os.IsNotExist(err) {
484 res = append(res, cc.NewErrReply(t, "Cannot rename file "+string(fileName)+" because it does not exist or cannot be found."))
493 res = append(res, cc.NewReply(t))
497 // HandleDeleteFile deletes a file or folder
498 // Fields used in the request:
501 // Fields used in the reply: none
502 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
503 fileName := t.GetField(FieldFileName).Data
504 filePath := t.GetField(FieldFilePath).Data
506 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
511 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
516 fi, err := hlFile.dataFile()
518 res = append(res, cc.NewErrReply(t, "Cannot delete file "+string(fileName)+" because it does not exist or cannot be found."))
522 switch mode := fi.Mode(); {
524 if !cc.Authorize(accessDeleteFolder) {
525 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
528 case mode.IsRegular():
529 if !cc.Authorize(accessDeleteFile) {
530 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
535 if err := hlFile.delete(); err != nil {
539 res = append(res, cc.NewReply(t))
543 // HandleMoveFile moves files or folders. Note: seemingly not documented
544 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
545 fileName := string(t.GetField(FieldFileName).Data)
547 filePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(FieldFilePath).Data, t.GetField(FieldFileName).Data)
552 fileNewPath, err := readPath(cc.Server.Config.FileRoot, t.GetField(FieldFileNewPath).Data, nil)
557 cc.logger.Infow("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
559 hlFile, err := newFileWrapper(cc.Server.FS, filePath, 0)
564 fi, err := hlFile.dataFile()
566 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
572 switch mode := fi.Mode(); {
574 if !cc.Authorize(accessMoveFolder) {
575 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
578 case mode.IsRegular():
579 if !cc.Authorize(accessMoveFile) {
580 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
584 if err := hlFile.move(fileNewPath); err != nil {
587 // TODO: handle other possible errors; e.g. fileWrapper delete fails due to fileWrapper permission issue
589 res = append(res, cc.NewReply(t))
593 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
594 if !cc.Authorize(accessCreateFolder) {
595 res = append(res, cc.NewErrReply(t, "You are not allowed to create folders."))
598 folderName := string(t.GetField(FieldFileName).Data)
600 folderName = path.Join("/", folderName)
604 // FieldFilePath is only present for nested paths
605 if t.GetField(FieldFilePath).Data != nil {
607 _, err := newFp.Write(t.GetField(FieldFilePath).Data)
612 for _, pathItem := range newFp.Items {
613 subPath = filepath.Join("/", subPath, string(pathItem.Name))
616 newFolderPath := path.Join(cc.Server.Config.FileRoot, subPath, folderName)
618 // TODO: check path and folder name lengths
620 if _, err := cc.Server.FS.Stat(newFolderPath); !os.IsNotExist(err) {
621 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that name.", folderName)
622 return []Transaction{cc.NewErrReply(t, msg)}, nil
625 // TODO: check for disallowed characters to maintain compatibility for original client
627 if err := cc.Server.FS.Mkdir(newFolderPath, 0777); err != nil {
628 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
629 return []Transaction{cc.NewErrReply(t, msg)}, nil
632 res = append(res, cc.NewReply(t))
636 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
637 if !cc.Authorize(accessModifyUser) {
638 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
642 login := DecodeUserString(t.GetField(FieldUserLogin).Data)
643 userName := string(t.GetField(FieldUserName).Data)
645 newAccessLvl := t.GetField(FieldUserAccess).Data
647 account := cc.Server.Accounts[login]
648 account.Name = userName
649 copy(account.Access[:], newAccessLvl)
651 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
652 // not include FieldUserPassword
653 if t.GetField(FieldUserPassword).Data == nil {
654 account.Password = hashAndSalt([]byte(""))
656 if len(t.GetField(FieldUserPassword).Data) > 1 {
657 account.Password = hashAndSalt(t.GetField(FieldUserPassword).Data)
660 out, err := yaml.Marshal(&account)
664 if err := os.WriteFile(filepath.Join(cc.Server.ConfigDir, "Users", login+".yaml"), out, 0666); err != nil {
668 // Notify connected clients logged in as the user of the new access level
669 for _, c := range cc.Server.Clients {
670 if c.Account.Login == login {
671 // Note: comment out these two lines to test server-side deny messages
672 newT := NewTransaction(TranUserAccess, c.ID, NewField(FieldUserAccess, newAccessLvl))
673 res = append(res, *newT)
675 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
676 if c.Authorize(accessDisconUser) {
677 flagBitmap.SetBit(flagBitmap, UserFlagAdmin, 1)
679 flagBitmap.SetBit(flagBitmap, UserFlagAdmin, 0)
681 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
683 c.Account.Access = account.Access
686 TranNotifyChangeUser,
687 NewField(FieldUserID, *c.ID),
688 NewField(FieldUserFlags, c.Flags),
689 NewField(FieldUserName, c.UserName),
690 NewField(FieldUserIconID, c.Icon),
695 res = append(res, cc.NewReply(t))
699 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
700 if !cc.Authorize(accessOpenUser) {
701 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
705 account := cc.Server.Accounts[string(t.GetField(FieldUserLogin).Data)]
707 res = append(res, cc.NewErrReply(t, "Account does not exist."))
711 res = append(res, cc.NewReply(t,
712 NewField(FieldUserName, []byte(account.Name)),
713 NewField(FieldUserLogin, negateString(t.GetField(FieldUserLogin).Data)),
714 NewField(FieldUserPassword, []byte(account.Password)),
715 NewField(FieldUserAccess, account.Access[:]),
720 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
721 if !cc.Authorize(accessOpenUser) {
722 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
726 var userFields []Field
727 for _, acc := range cc.Server.Accounts {
728 b := make([]byte, 0, 100)
729 n, err := acc.Read(b)
734 userFields = append(userFields, NewField(FieldData, b[:n]))
737 res = append(res, cc.NewReply(t, userFields...))
741 // HandleUpdateUser is used by the v1.5+ multi-user editor to perform account editing for multiple users at a time.
742 // An update can be a mix of these actions:
745 // * Modify user (including renaming the account login)
747 // The Transaction sent by the client includes one data field per user that was modified. This data field in turn
748 // contains another data field encoded in its payload with a varying number of sub fields depending on which action is
749 // performed. This seems to be the only place in the Hotline protocol where a data field contains another data field.
750 func HandleUpdateUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
751 for _, field := range t.Fields {
752 subFields, err := ReadFields(field.Data[0:2], field.Data[2:])
757 if len(subFields) == 1 {
758 login := DecodeUserString(getField(FieldData, &subFields).Data)
759 cc.logger.Infow("DeleteUser", "login", login)
761 if !cc.Authorize(accessDeleteUser) {
762 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
766 if err := cc.Server.DeleteUser(login); err != nil {
772 login := DecodeUserString(getField(FieldUserLogin, &subFields).Data)
774 // check if the login dataFile; if so, we know we are updating an existing user
775 if acc, ok := cc.Server.Accounts[login]; ok {
776 cc.logger.Infow("UpdateUser", "login", login)
778 // account dataFile, so this is an update action
779 if !cc.Authorize(accessModifyUser) {
780 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
784 if getField(FieldUserPassword, &subFields) != nil {
785 newPass := getField(FieldUserPassword, &subFields).Data
786 acc.Password = hashAndSalt(newPass)
788 acc.Password = hashAndSalt([]byte(""))
791 if getField(FieldUserAccess, &subFields) != nil {
792 copy(acc.Access[:], getField(FieldUserAccess, &subFields).Data)
795 err = cc.Server.UpdateUser(
796 DecodeUserString(getField(FieldData, &subFields).Data),
797 DecodeUserString(getField(FieldUserLogin, &subFields).Data),
798 string(getField(FieldUserName, &subFields).Data),
806 cc.logger.Infow("CreateUser", "login", login)
808 if !cc.Authorize(accessCreateUser) {
809 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
813 newAccess := accessBitmap{}
814 copy(newAccess[:], getField(FieldUserAccess, &subFields).Data)
816 // Prevent account from creating new account with greater permission
817 for i := 0; i < 64; i++ {
818 if newAccess.IsSet(i) {
819 if !cc.Authorize(i) {
820 return append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself.")), err
825 err := cc.Server.NewUser(login, string(getField(FieldUserName, &subFields).Data), string(getField(FieldUserPassword, &subFields).Data), newAccess)
827 return []Transaction{}, err
832 res = append(res, cc.NewReply(t))
836 // HandleNewUser creates a new user account
837 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
838 if !cc.Authorize(accessCreateUser) {
839 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
843 login := DecodeUserString(t.GetField(FieldUserLogin).Data)
845 // If the account already dataFile, reply with an error
846 if _, ok := cc.Server.Accounts[login]; ok {
847 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
851 newAccess := accessBitmap{}
852 copy(newAccess[:], t.GetField(FieldUserAccess).Data)
854 // Prevent account from creating new account with greater permission
855 for i := 0; i < 64; i++ {
856 if newAccess.IsSet(i) {
857 if !cc.Authorize(i) {
858 res = append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself."))
864 if err := cc.Server.NewUser(login, string(t.GetField(FieldUserName).Data), string(t.GetField(FieldUserPassword).Data), newAccess); err != nil {
865 return []Transaction{}, err
868 res = append(res, cc.NewReply(t))
872 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
873 if !cc.Authorize(accessDeleteUser) {
874 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
878 // TODO: Handle case where account doesn't exist; e.g. delete race condition
879 login := DecodeUserString(t.GetField(FieldUserLogin).Data)
881 if err := cc.Server.DeleteUser(login); err != nil {
885 res = append(res, cc.NewReply(t))
889 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
890 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
891 if !cc.Authorize(accessBroadcast) {
892 res = append(res, cc.NewErrReply(t, "You are not allowed to send broadcast messages."))
898 NewField(FieldData, t.GetField(TranGetMsgs).Data),
899 NewField(FieldChatOptions, []byte{0}),
902 res = append(res, cc.NewReply(t))
906 // HandleGetClientInfoText returns user information for the specific user.
908 // Fields used in the request:
911 // Fields used in the reply:
913 // 101 Data User info text string
914 func HandleGetClientInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
915 if !cc.Authorize(accessGetClientInfo) {
916 res = append(res, cc.NewErrReply(t, "You are not allowed to get client info."))
920 clientID, _ := byteToInt(t.GetField(FieldUserID).Data)
922 clientConn := cc.Server.Clients[uint16(clientID)]
923 if clientConn == nil {
924 return append(res, cc.NewErrReply(t, "User not found.")), err
927 res = append(res, cc.NewReply(t,
928 NewField(FieldData, []byte(clientConn.String())),
929 NewField(FieldUserName, clientConn.UserName),
934 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
935 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
940 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
941 if t.GetField(FieldUserName).Data != nil {
942 if cc.Authorize(accessAnyName) {
943 cc.UserName = t.GetField(FieldUserName).Data
945 cc.UserName = []byte(cc.Account.Name)
949 cc.Icon = t.GetField(FieldUserIconID).Data
951 cc.logger = cc.logger.With("name", string(cc.UserName))
952 cc.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(cc.Version); return i }()))
954 options := t.GetField(FieldOptions).Data
955 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
957 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
959 // Check refuse private PM option
960 if optBitmap.Bit(refusePM) == 1 {
961 flagBitmap.SetBit(flagBitmap, UserFlagRefusePM, 1)
962 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
965 // Check refuse private chat option
966 if optBitmap.Bit(refuseChat) == 1 {
967 flagBitmap.SetBit(flagBitmap, UserFlagRefusePChat, 1)
968 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
971 // Check auto response
972 if optBitmap.Bit(autoResponse) == 1 {
973 cc.AutoReply = t.GetField(FieldAutomaticResponse).Data
975 cc.AutoReply = []byte{}
978 trans := cc.notifyOthers(
980 TranNotifyChangeUser, nil,
981 NewField(FieldUserName, cc.UserName),
982 NewField(FieldUserID, *cc.ID),
983 NewField(FieldUserIconID, cc.Icon),
984 NewField(FieldUserFlags, cc.Flags),
987 res = append(res, trans...)
989 if cc.Server.Config.BannerFile != "" {
990 res = append(res, *NewTransaction(TranServerBanner, cc.ID, NewField(FieldBannerType, []byte("JPEG"))))
993 res = append(res, cc.NewReply(t))
998 // HandleTranOldPostNews updates the flat news
999 // Fields used in this request:
1001 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1002 if !cc.Authorize(accessNewsPostArt) {
1003 res = append(res, cc.NewErrReply(t, "You are not allowed to post news."))
1007 cc.Server.flatNewsMux.Lock()
1008 defer cc.Server.flatNewsMux.Unlock()
1010 newsDateTemplate := defaultNewsDateFormat
1011 if cc.Server.Config.NewsDateFormat != "" {
1012 newsDateTemplate = cc.Server.Config.NewsDateFormat
1015 newsTemplate := defaultNewsTemplate
1016 if cc.Server.Config.NewsDelimiter != "" {
1017 newsTemplate = cc.Server.Config.NewsDelimiter
1020 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(FieldData).Data)
1021 newsPost = strings.ReplaceAll(newsPost, "\n", "\r")
1023 // update news in memory
1024 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
1026 // update news on disk
1027 if err := cc.Server.FS.WriteFile(filepath.Join(cc.Server.ConfigDir, "MessageBoard.txt"), cc.Server.FlatNews, 0644); err != nil {
1031 // Notify all clients of updated news
1034 NewField(FieldData, []byte(newsPost)),
1037 res = append(res, cc.NewReply(t))
1041 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1042 if !cc.Authorize(accessDisconUser) {
1043 res = append(res, cc.NewErrReply(t, "You are not allowed to disconnect users."))
1047 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(FieldUserID).Data)]
1049 if clientConn.Authorize(accessCannotBeDiscon) {
1050 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
1054 // If FieldOptions is set, then the client IP is banned in addition to disconnected.
1055 // 00 01 = temporary ban
1056 // 00 02 = permanent ban
1057 if t.GetField(FieldOptions).Data != nil {
1058 switch t.GetField(FieldOptions).Data[1] {
1060 // send message: "You are temporarily banned on this server"
1061 cc.logger.Infow("Disconnect & temporarily ban " + string(clientConn.UserName))
1063 res = append(res, *NewTransaction(
1066 NewField(FieldData, []byte("You are temporarily banned on this server")),
1067 NewField(FieldChatOptions, []byte{0, 0}),
1070 banUntil := time.Now().Add(tempBanDuration)
1071 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = &banUntil
1073 // send message: "You are permanently banned on this server"
1074 cc.logger.Infow("Disconnect & ban " + string(clientConn.UserName))
1076 res = append(res, *NewTransaction(
1079 NewField(FieldData, []byte("You are permanently banned on this server")),
1080 NewField(FieldChatOptions, []byte{0, 0}),
1083 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = nil
1086 err := cc.Server.writeBanList()
1092 // TODO: remove this awful hack
1094 time.Sleep(1 * time.Second)
1095 clientConn.Disconnect()
1098 return append(res, cc.NewReply(t)), err
1101 // HandleGetNewsCatNameList returns a list of news categories for a path
1102 // Fields used in the request:
1103 // 325 News path (Optional)
1104 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1105 if !cc.Authorize(accessNewsReadArt) {
1106 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1110 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1111 cats := cc.Server.GetNewsCatByPath(pathStrs)
1113 // To store the keys in slice in sorted order
1114 keys := make([]string, len(cats))
1116 for k := range cats {
1122 var fieldData []Field
1123 for _, k := range keys {
1125 b, _ := cat.MarshalBinary()
1126 fieldData = append(fieldData, NewField(
1127 FieldNewsCatListData15,
1132 res = append(res, cc.NewReply(t, fieldData...))
1136 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1137 if !cc.Authorize(accessNewsCreateCat) {
1138 res = append(res, cc.NewErrReply(t, "You are not allowed to create news categories."))
1142 name := string(t.GetField(FieldNewsCatName).Data)
1143 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1145 cats := cc.Server.GetNewsCatByPath(pathStrs)
1146 cats[name] = NewsCategoryListData15{
1149 Articles: map[uint32]*NewsArtData{},
1150 SubCats: make(map[string]NewsCategoryListData15),
1153 if err := cc.Server.writeThreadedNews(); err != nil {
1156 res = append(res, cc.NewReply(t))
1160 // Fields used in the request:
1161 // 322 News category name
1163 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1164 if !cc.Authorize(accessNewsCreateFldr) {
1165 res = append(res, cc.NewErrReply(t, "You are not allowed to create news folders."))
1169 name := string(t.GetField(FieldFileName).Data)
1170 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1172 cc.logger.Infof("Creating new news folder %s", name)
1174 cats := cc.Server.GetNewsCatByPath(pathStrs)
1175 cats[name] = NewsCategoryListData15{
1178 Articles: map[uint32]*NewsArtData{},
1179 SubCats: make(map[string]NewsCategoryListData15),
1181 if err := cc.Server.writeThreadedNews(); err != nil {
1184 res = append(res, cc.NewReply(t))
1188 // HandleGetNewsArtData gets the list of article names at the specified news path.
1190 // Fields used in the request:
1191 // 325 News path Optional
1193 // Fields used in the reply:
1194 // 321 News article list data Optional
1195 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1196 if !cc.Authorize(accessNewsReadArt) {
1197 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1200 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1202 var cat NewsCategoryListData15
1203 cats := cc.Server.ThreadedNews.Categories
1205 for _, fp := range pathStrs {
1207 cats = cats[fp].SubCats
1210 nald := cat.GetNewsArtListData()
1212 res = append(res, cc.NewReply(t, NewField(FieldNewsArtListData, nald.Payload())))
1216 // HandleGetNewsArtData requests information about the specific news article.
1217 // Fields used in the request:
1221 // 326 News article ID
1222 // 327 News article data flavor
1224 // Fields used in the reply:
1225 // 328 News article title
1226 // 329 News article poster
1227 // 330 News article date
1228 // 331 Previous article ID
1229 // 332 Next article ID
1230 // 335 Parent article ID
1231 // 336 First child article ID
1232 // 327 News article data flavor "Should be “text/plain”
1233 // 333 News article data Optional (if data flavor is “text/plain”)
1234 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1235 if !cc.Authorize(accessNewsReadArt) {
1236 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1240 var cat NewsCategoryListData15
1241 cats := cc.Server.ThreadedNews.Categories
1243 for _, fp := range ReadNewsPath(t.GetField(FieldNewsPath).Data) {
1245 cats = cats[fp].SubCats
1248 // The official Hotline clients will send the article ID as 2 bytes if possible, but
1249 // some third party clients such as Frogblast and Heildrun will always send 4 bytes
1250 convertedID, err := byteToInt(t.GetField(FieldNewsArtID).Data)
1255 art := cat.Articles[uint32(convertedID)]
1257 res = append(res, cc.NewReply(t))
1261 res = append(res, cc.NewReply(t,
1262 NewField(FieldNewsArtTitle, []byte(art.Title)),
1263 NewField(FieldNewsArtPoster, []byte(art.Poster)),
1264 NewField(FieldNewsArtDate, art.Date),
1265 NewField(FieldNewsArtPrevArt, art.PrevArt),
1266 NewField(FieldNewsArtNextArt, art.NextArt),
1267 NewField(FieldNewsArtParentArt, art.ParentArt),
1268 NewField(FieldNewsArt1stChildArt, art.FirstChildArt),
1269 NewField(FieldNewsArtDataFlav, []byte("text/plain")),
1270 NewField(FieldNewsArtData, []byte(art.Data)),
1275 // HandleDelNewsItem deletes an existing threaded news folder or category from the server.
1276 // Fields used in the request:
1278 // Fields used in the reply:
1280 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1281 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1283 cats := cc.Server.ThreadedNews.Categories
1284 delName := pathStrs[len(pathStrs)-1]
1285 if len(pathStrs) > 1 {
1286 for _, fp := range pathStrs[0 : len(pathStrs)-1] {
1287 cats = cats[fp].SubCats
1291 if bytes.Equal(cats[delName].Type, []byte{0, 3}) {
1292 if !cc.Authorize(accessNewsDeleteCat) {
1293 return append(res, cc.NewErrReply(t, "You are not allowed to delete news categories.")), nil
1296 if !cc.Authorize(accessNewsDeleteFldr) {
1297 return append(res, cc.NewErrReply(t, "You are not allowed to delete news folders.")), nil
1301 delete(cats, delName)
1303 if err := cc.Server.writeThreadedNews(); err != nil {
1307 return append(res, cc.NewReply(t)), nil
1310 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1311 if !cc.Authorize(accessNewsDeleteArt) {
1312 res = append(res, cc.NewErrReply(t, "You are not allowed to delete news articles."))
1318 // 326 News article ID
1319 // 337 News article – recursive delete Delete child articles (1) or not (0)
1320 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1321 ID, err := byteToInt(t.GetField(FieldNewsArtID).Data)
1326 // TODO: Delete recursive
1327 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1329 catName := pathStrs[len(pathStrs)-1]
1330 cat := cats[catName]
1332 delete(cat.Articles, uint32(ID))
1335 if err := cc.Server.writeThreadedNews(); err != nil {
1339 res = append(res, cc.NewReply(t))
1345 // 326 News article ID ID of the parent article?
1346 // 328 News article title
1347 // 334 News article flags
1348 // 327 News article data flavor Currently “text/plain”
1349 // 333 News article data
1350 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1351 if !cc.Authorize(accessNewsPostArt) {
1352 res = append(res, cc.NewErrReply(t, "You are not allowed to post news articles."))
1356 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1357 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1359 catName := pathStrs[len(pathStrs)-1]
1360 cat := cats[catName]
1362 artID, err := byteToInt(t.GetField(FieldNewsArtID).Data)
1366 convertedArtID := uint32(artID)
1367 bs := make([]byte, 4)
1368 binary.BigEndian.PutUint32(bs, convertedArtID)
1370 newArt := NewsArtData{
1371 Title: string(t.GetField(FieldNewsArtTitle).Data),
1372 Poster: string(cc.UserName),
1373 Date: toHotlineTime(time.Now()),
1374 PrevArt: []byte{0, 0, 0, 0},
1375 NextArt: []byte{0, 0, 0, 0},
1377 FirstChildArt: []byte{0, 0, 0, 0},
1378 DataFlav: []byte("text/plain"),
1379 Data: string(t.GetField(FieldNewsArtData).Data),
1383 for k := range cat.Articles {
1384 keys = append(keys, int(k))
1390 prevID := uint32(keys[len(keys)-1])
1393 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1395 // Set next article ID
1396 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1399 // Update parent article with first child reply
1400 parentID := convertedArtID
1402 parentArt := cat.Articles[parentID]
1404 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1405 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1409 cat.Articles[nextID] = &newArt
1412 if err := cc.Server.writeThreadedNews(); err != nil {
1416 res = append(res, cc.NewReply(t))
1420 // HandleGetMsgs returns the flat news data
1421 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1422 if !cc.Authorize(accessNewsReadArt) {
1423 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1427 res = append(res, cc.NewReply(t, NewField(FieldData, cc.Server.FlatNews)))
1432 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1433 if !cc.Authorize(accessDownloadFile) {
1434 res = append(res, cc.NewErrReply(t, "You are not allowed to download files."))
1438 fileName := t.GetField(FieldFileName).Data
1439 filePath := t.GetField(FieldFilePath).Data
1440 resumeData := t.GetField(FieldFileResumeData).Data
1442 var dataOffset int64
1443 var frd FileResumeData
1444 if resumeData != nil {
1445 if err := frd.UnmarshalBinary(t.GetField(FieldFileResumeData).Data); err != nil {
1448 // TODO: handle rsrc fork offset
1449 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1452 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1457 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, dataOffset)
1462 xferSize := hlFile.ffo.TransferSize(0)
1464 ft := cc.newFileTransfer(FileDownload, fileName, filePath, xferSize)
1466 // TODO: refactor to remove this
1467 if resumeData != nil {
1468 var frd FileResumeData
1469 if err := frd.UnmarshalBinary(t.GetField(FieldFileResumeData).Data); err != nil {
1472 ft.fileResumeData = &frd
1475 // Optional field for when a HL v1.5+ client requests file preview
1476 // Used only for TEXT, JPEG, GIFF, BMP or PICT files
1477 // The value will always be 2
1478 if t.GetField(FieldFileTransferOptions).Data != nil {
1479 ft.options = t.GetField(FieldFileTransferOptions).Data
1480 xferSize = hlFile.ffo.FlatFileDataForkHeader.DataSize[:]
1483 res = append(res, cc.NewReply(t,
1484 NewField(FieldRefNum, ft.refNum[:]),
1485 NewField(FieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1486 NewField(FieldTransferSize, xferSize),
1487 NewField(FieldFileSize, hlFile.ffo.FlatFileDataForkHeader.DataSize[:]),
1493 // Download all files from the specified folder and sub-folders
1494 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1495 if !cc.Authorize(accessDownloadFile) {
1496 res = append(res, cc.NewErrReply(t, "You are not allowed to download folders."))
1500 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(FieldFilePath).Data, t.GetField(FieldFileName).Data)
1505 transferSize, err := CalcTotalSize(fullFilePath)
1509 itemCount, err := CalcItemCount(fullFilePath)
1514 fileTransfer := cc.newFileTransfer(FolderDownload, t.GetField(FieldFileName).Data, t.GetField(FieldFilePath).Data, transferSize)
1517 _, err = fp.Write(t.GetField(FieldFilePath).Data)
1522 res = append(res, cc.NewReply(t,
1523 NewField(FieldRefNum, fileTransfer.ReferenceNumber),
1524 NewField(FieldTransferSize, transferSize),
1525 NewField(FieldFolderItemCount, itemCount),
1526 NewField(FieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1531 // Upload all files from the local folder and its subfolders to the specified path on the server
1532 // Fields used in the request
1535 // 108 transfer size Total size of all items in the folder
1536 // 220 Folder item count
1537 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1538 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1540 if t.GetField(FieldFilePath).Data != nil {
1541 if _, err = fp.Write(t.GetField(FieldFilePath).Data); err != nil {
1546 // Handle special cases for Upload and Drop Box folders
1547 if !cc.Authorize(accessUploadAnywhere) {
1548 if !fp.IsUploadDir() && !fp.IsDropbox() {
1549 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))))
1554 fileTransfer := cc.newFileTransfer(FolderUpload,
1555 t.GetField(FieldFileName).Data,
1556 t.GetField(FieldFilePath).Data,
1557 t.GetField(FieldTransferSize).Data,
1560 fileTransfer.FolderItemCount = t.GetField(FieldFolderItemCount).Data
1562 res = append(res, cc.NewReply(t, NewField(FieldRefNum, fileTransfer.ReferenceNumber)))
1567 // Fields used in the request:
1570 // 204 File transfer options "Optional
1571 // Used only to resume download, currently has value 2"
1572 // 108 File transfer size "Optional used if download is not resumed"
1573 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1574 if !cc.Authorize(accessUploadFile) {
1575 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1579 fileName := t.GetField(FieldFileName).Data
1580 filePath := t.GetField(FieldFilePath).Data
1581 transferOptions := t.GetField(FieldFileTransferOptions).Data
1582 transferSize := t.GetField(FieldTransferSize).Data // not sent for resume
1585 if filePath != nil {
1586 if _, err = fp.Write(filePath); err != nil {
1591 // Handle special cases for Upload and Drop Box folders
1592 if !cc.Authorize(accessUploadAnywhere) {
1593 if !fp.IsUploadDir() && !fp.IsDropbox() {
1594 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))))
1598 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1603 if _, err := cc.Server.FS.Stat(fullFilePath); err == nil {
1604 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))))
1608 ft := cc.newFileTransfer(FileUpload, fileName, filePath, transferSize)
1610 replyT := cc.NewReply(t, NewField(FieldRefNum, ft.ReferenceNumber))
1612 // client has requested to resume a partially transferred file
1613 if transferOptions != nil {
1614 fileInfo, err := cc.Server.FS.Stat(fullFilePath + incompleteFileSuffix)
1619 offset := make([]byte, 4)
1620 binary.BigEndian.PutUint32(offset, uint32(fileInfo.Size()))
1622 fileResumeData := NewFileResumeData([]ForkInfoList{
1623 *NewForkInfoList(offset),
1626 b, _ := fileResumeData.BinaryMarshal()
1628 ft.TransferSize = offset
1630 replyT.Fields = append(replyT.Fields, NewField(FieldFileResumeData, b))
1633 res = append(res, replyT)
1637 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1638 if len(t.GetField(FieldUserIconID).Data) == 4 {
1639 cc.Icon = t.GetField(FieldUserIconID).Data[2:]
1641 cc.Icon = t.GetField(FieldUserIconID).Data
1643 if cc.Authorize(accessAnyName) {
1644 cc.UserName = t.GetField(FieldUserName).Data
1647 // the options field is only passed by the client versions > 1.2.3.
1648 options := t.GetField(FieldOptions).Data
1650 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1651 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
1653 flagBitmap.SetBit(flagBitmap, UserFlagRefusePM, optBitmap.Bit(refusePM))
1654 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1656 flagBitmap.SetBit(flagBitmap, UserFlagRefusePChat, optBitmap.Bit(refuseChat))
1657 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1659 // Check auto response
1660 if optBitmap.Bit(autoResponse) == 1 {
1661 cc.AutoReply = t.GetField(FieldAutomaticResponse).Data
1663 cc.AutoReply = []byte{}
1667 for _, c := range sortedClients(cc.Server.Clients) {
1668 res = append(res, *NewTransaction(
1669 TranNotifyChangeUser,
1671 NewField(FieldUserID, *cc.ID),
1672 NewField(FieldUserIconID, cc.Icon),
1673 NewField(FieldUserFlags, cc.Flags),
1674 NewField(FieldUserName, cc.UserName),
1681 // HandleKeepAlive responds to keepalive transactions with an empty reply
1682 // * HL 1.9.2 Client sends keepalive msg every 3 minutes
1683 // * HL 1.2.3 Client doesn't send keepalives
1684 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1685 res = append(res, cc.NewReply(t))
1690 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1691 fullPath, err := readPath(
1692 cc.Server.Config.FileRoot,
1693 t.GetField(FieldFilePath).Data,
1701 if t.GetField(FieldFilePath).Data != nil {
1702 if _, err = fp.Write(t.GetField(FieldFilePath).Data); err != nil {
1707 // Handle special case for drop box folders
1708 if fp.IsDropbox() && !cc.Authorize(accessViewDropBoxes) {
1709 res = append(res, cc.NewErrReply(t, "You are not allowed to view drop boxes."))
1713 fileNames, err := getFileNameList(fullPath, cc.Server.Config.IgnoreFiles)
1718 res = append(res, cc.NewReply(t, fileNames...))
1723 // =================================
1724 // Hotline private chat flow
1725 // =================================
1726 // 1. ClientA sends TranInviteNewChat to server with user ID to invite
1727 // 2. Server creates new ChatID
1728 // 3. Server sends TranInviteToChat to invitee
1729 // 4. Server replies to ClientA with new Chat ID
1731 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1732 // If Accepted is clicked:
1733 // 1. ClientB sends TranJoinChat with FieldChatID
1735 // HandleInviteNewChat invites users to new private chat
1736 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1737 if !cc.Authorize(accessOpenChat) {
1738 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1743 targetID := t.GetField(FieldUserID).Data
1744 newChatID := cc.Server.NewPrivateChat(cc)
1746 // Check if target user has "Refuse private chat" flag
1747 binary.BigEndian.Uint16(targetID)
1748 targetClient := cc.Server.Clients[binary.BigEndian.Uint16(targetID)]
1750 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(targetClient.Flags)))
1751 if flagBitmap.Bit(UserFlagRefusePChat) == 1 {
1756 NewField(FieldData, []byte(string(targetClient.UserName)+" does not accept private chats.")),
1757 NewField(FieldUserName, targetClient.UserName),
1758 NewField(FieldUserID, *targetClient.ID),
1759 NewField(FieldOptions, []byte{0, 2}),
1767 NewField(FieldChatID, newChatID),
1768 NewField(FieldUserName, cc.UserName),
1769 NewField(FieldUserID, *cc.ID),
1776 NewField(FieldChatID, newChatID),
1777 NewField(FieldUserName, cc.UserName),
1778 NewField(FieldUserID, *cc.ID),
1779 NewField(FieldUserIconID, cc.Icon),
1780 NewField(FieldUserFlags, cc.Flags),
1787 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1788 if !cc.Authorize(accessOpenChat) {
1789 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1794 targetID := t.GetField(FieldUserID).Data
1795 chatID := t.GetField(FieldChatID).Data
1801 NewField(FieldChatID, chatID),
1802 NewField(FieldUserName, cc.UserName),
1803 NewField(FieldUserID, *cc.ID),
1809 NewField(FieldChatID, chatID),
1810 NewField(FieldUserName, cc.UserName),
1811 NewField(FieldUserID, *cc.ID),
1812 NewField(FieldUserIconID, cc.Icon),
1813 NewField(FieldUserFlags, cc.Flags),
1820 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1821 chatID := t.GetField(FieldChatID).Data
1822 chatInt := binary.BigEndian.Uint32(chatID)
1824 privChat := cc.Server.PrivateChats[chatInt]
1826 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1828 for _, c := range sortedClients(privChat.ClientConn) {
1833 NewField(FieldChatID, chatID),
1834 NewField(FieldData, resMsg),
1842 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1843 // Fields used in the reply:
1844 // * 115 Chat subject
1845 // * 300 User name with info (Optional)
1846 // * 300 (more user names with info)
1847 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1848 chatID := t.GetField(FieldChatID).Data
1849 chatInt := binary.BigEndian.Uint32(chatID)
1851 privChat := cc.Server.PrivateChats[chatInt]
1853 // Send TranNotifyChatChangeUser to current members of the chat to inform of new user
1854 for _, c := range sortedClients(privChat.ClientConn) {
1857 TranNotifyChatChangeUser,
1859 NewField(FieldChatID, chatID),
1860 NewField(FieldUserName, cc.UserName),
1861 NewField(FieldUserID, *cc.ID),
1862 NewField(FieldUserIconID, cc.Icon),
1863 NewField(FieldUserFlags, cc.Flags),
1868 privChat.ClientConn[cc.uint16ID()] = cc
1870 replyFields := []Field{NewField(FieldChatSubject, []byte(privChat.Subject))}
1871 for _, c := range sortedClients(privChat.ClientConn) {
1876 Name: string(c.UserName),
1879 replyFields = append(replyFields, NewField(FieldUsernameWithInfo, user.Payload()))
1882 res = append(res, cc.NewReply(t, replyFields...))
1886 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1887 // Fields used in the request:
1888 // - 114 FieldChatID
1890 // Reply is not expected.
1891 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1892 chatID := t.GetField(FieldChatID).Data
1893 chatInt := binary.BigEndian.Uint32(chatID)
1895 privChat, ok := cc.Server.PrivateChats[chatInt]
1900 delete(privChat.ClientConn, cc.uint16ID())
1902 // Notify members of the private chat that the user has left
1903 for _, c := range sortedClients(privChat.ClientConn) {
1906 TranNotifyChatDeleteUser,
1908 NewField(FieldChatID, chatID),
1909 NewField(FieldUserID, *cc.ID),
1917 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1918 // Fields used in the request:
1920 // * 115 Chat subject
1921 // Reply is not expected.
1922 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1923 chatID := t.GetField(FieldChatID).Data
1924 chatInt := binary.BigEndian.Uint32(chatID)
1926 privChat := cc.Server.PrivateChats[chatInt]
1927 privChat.Subject = string(t.GetField(FieldChatSubject).Data)
1929 for _, c := range sortedClients(privChat.ClientConn) {
1932 TranNotifyChatSubject,
1934 NewField(FieldChatID, chatID),
1935 NewField(FieldChatSubject, t.GetField(FieldChatSubject).Data),
1943 // HandleMakeAlias makes a file alias using the specified path.
1944 // Fields used in the request:
1947 // 212 File new path Destination path
1949 // Fields used in the reply:
1951 func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1952 if !cc.Authorize(accessMakeAlias) {
1953 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
1956 fileName := t.GetField(FieldFileName).Data
1957 filePath := t.GetField(FieldFilePath).Data
1958 fileNewPath := t.GetField(FieldFileNewPath).Data
1960 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1965 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
1970 cc.logger.Debugw("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
1972 if err := cc.Server.FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
1973 res = append(res, cc.NewErrReply(t, "Error creating alias"))
1977 res = append(res, cc.NewReply(t))
1981 // HandleDownloadBanner handles requests for a new banner from the server
1982 // Fields used in the request:
1984 // Fields used in the reply:
1985 // 107 FieldRefNum Used later for transfer
1986 // 108 FieldTransferSize Size of data to be downloaded
1987 func HandleDownloadBanner(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1988 fi, err := cc.Server.FS.Stat(filepath.Join(cc.Server.ConfigDir, cc.Server.Config.BannerFile))
1993 ft := cc.newFileTransfer(bannerDownload, []byte{}, []byte{}, make([]byte, 4))
1995 binary.BigEndian.PutUint32(ft.TransferSize, uint32(fi.Size()))
1997 res = append(res, cc.NewReply(t,
1998 NewField(FieldRefNum, ft.refNum[:]),
1999 NewField(FieldTransferSize, ft.TransferSize),