19 type HandlerFunc func(*ClientConn, *Transaction) ([]Transaction, error)
21 type TransactionType struct {
22 Handler HandlerFunc // function for handling the transaction type
23 Name string // Name of transaction as it will appear in logging
24 RequiredFields []requiredField
27 var TransactionHandlers = map[uint16]TransactionType{
33 TranNotifyChangeUser: {
34 Name: "TranNotifyChangeUser",
40 Name: "TranShowAgreement",
43 Name: "TranUserAccess",
45 TranNotifyDeleteUser: {
46 Name: "TranNotifyDeleteUser",
50 Handler: HandleTranAgreed,
54 Handler: HandleChatSend,
55 RequiredFields: []requiredField{
63 Name: "TranDelNewsArt",
64 Handler: HandleDelNewsArt,
67 Name: "TranDelNewsItem",
68 Handler: HandleDelNewsItem,
71 Name: "TranDeleteFile",
72 Handler: HandleDeleteFile,
75 Name: "TranDeleteUser",
76 Handler: HandleDeleteUser,
79 Name: "TranDisconnectUser",
80 Handler: HandleDisconnectUser,
83 Name: "TranDownloadFile",
84 Handler: HandleDownloadFile,
87 Name: "TranDownloadFldr",
88 Handler: HandleDownloadFolder,
90 TranGetClientInfoText: {
91 Name: "TranGetClientInfoText",
92 Handler: HandleGetClientInfoText,
95 Name: "TranGetFileInfo",
96 Handler: HandleGetFileInfo,
98 TranGetFileNameList: {
99 Name: "TranGetFileNameList",
100 Handler: HandleGetFileNameList,
104 Handler: HandleGetMsgs,
106 TranGetNewsArtData: {
107 Name: "TranGetNewsArtData",
108 Handler: HandleGetNewsArtData,
110 TranGetNewsArtNameList: {
111 Name: "TranGetNewsArtNameList",
112 Handler: HandleGetNewsArtNameList,
114 TranGetNewsCatNameList: {
115 Name: "TranGetNewsCatNameList",
116 Handler: HandleGetNewsCatNameList,
120 Handler: HandleGetUser,
122 TranGetUserNameList: {
123 Name: "tranHandleGetUserNameList",
124 Handler: HandleGetUserNameList,
127 Name: "TranInviteNewChat",
128 Handler: HandleInviteNewChat,
131 Name: "TranInviteToChat",
132 Handler: HandleInviteToChat,
135 Name: "TranJoinChat",
136 Handler: HandleJoinChat,
139 Name: "TranKeepAlive",
140 Handler: HandleKeepAlive,
143 Name: "TranJoinChat",
144 Handler: HandleLeaveChat,
147 Name: "TranListUsers",
148 Handler: HandleListUsers,
151 Name: "TranMoveFile",
152 Handler: HandleMoveFile,
155 Name: "TranNewFolder",
156 Handler: HandleNewFolder,
159 Name: "TranNewNewsCat",
160 Handler: HandleNewNewsCat,
163 Name: "TranNewNewsFldr",
164 Handler: HandleNewNewsFldr,
168 Handler: HandleNewUser,
171 Name: "TranUpdateUser",
172 Handler: HandleUpdateUser,
175 Name: "TranOldPostNews",
176 Handler: HandleTranOldPostNews,
179 Name: "TranPostNewsArt",
180 Handler: HandlePostNewsArt,
182 TranRejectChatInvite: {
183 Name: "TranRejectChatInvite",
184 Handler: HandleRejectChatInvite,
186 TranSendInstantMsg: {
187 Name: "TranSendInstantMsg",
188 Handler: HandleSendInstantMsg,
189 RequiredFields: []requiredField{
199 TranSetChatSubject: {
200 Name: "TranSetChatSubject",
201 Handler: HandleSetChatSubject,
204 Name: "TranMakeFileAlias",
205 Handler: HandleMakeAlias,
206 RequiredFields: []requiredField{
207 {ID: FieldFileName, minLen: 1},
208 {ID: FieldFilePath, minLen: 1},
209 {ID: FieldFileNewPath, minLen: 1},
212 TranSetClientUserInfo: {
213 Name: "TranSetClientUserInfo",
214 Handler: HandleSetClientUserInfo,
217 Name: "TranSetFileInfo",
218 Handler: HandleSetFileInfo,
222 Handler: HandleSetUser,
225 Name: "TranUploadFile",
226 Handler: HandleUploadFile,
229 Name: "TranUploadFldr",
230 Handler: HandleUploadFolder,
233 Name: "TranUserBroadcast",
234 Handler: HandleUserBroadcast,
236 TranDownloadBanner: {
237 Name: "TranDownloadBanner",
238 Handler: HandleDownloadBanner,
242 func HandleChatSend(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
243 if !cc.Authorize(accessSendChat) {
244 res = append(res, cc.NewErrReply(t, "You are not allowed to participate in chat."))
248 // Truncate long usernames
249 trunc := fmt.Sprintf("%13s", cc.UserName)
250 formattedMsg := fmt.Sprintf("\r%.14s: %s", trunc, t.GetField(FieldData).Data)
252 // By holding the option key, Hotline chat allows users to send /me formatted messages like:
253 // *** Halcyon does stuff
254 // This is indicated by the presence of the optional field FieldChatOptions set to a value of 1.
255 // Most clients do not send this option for normal chat messages.
256 if t.GetField(FieldChatOptions).Data != nil && bytes.Equal(t.GetField(FieldChatOptions).Data, []byte{0, 1}) {
257 formattedMsg = fmt.Sprintf("\r*** %s %s", cc.UserName, t.GetField(FieldData).Data)
260 // The ChatID field is used to identify messages as belonging to a private chat.
261 // All clients *except* Frogblast omit this field for public chat, but Frogblast sends a value of 00 00 00 00.
262 chatID := t.GetField(FieldChatID).Data
263 if chatID != nil && !bytes.Equal([]byte{0, 0, 0, 0}, chatID) {
264 chatInt := binary.BigEndian.Uint32(chatID)
265 privChat := cc.Server.PrivateChats[chatInt]
267 clients := sortedClients(privChat.ClientConn)
269 // send the message to all connected clients of the private chat
270 for _, c := range clients {
271 res = append(res, *NewTransaction(
274 NewField(FieldChatID, chatID),
275 NewField(FieldData, []byte(formattedMsg)),
281 for _, c := range sortedClients(cc.Server.Clients) {
282 // Filter out clients that do not have the read chat permission
283 if c.Authorize(accessReadChat) {
284 res = append(res, *NewTransaction(TranChatMsg, c.ID, NewField(FieldData, []byte(formattedMsg))))
291 // HandleSendInstantMsg sends instant message to the user on the current server.
292 // Fields used in the request:
296 // One of the following values:
297 // - User message (myOpt_UserMessage = 1)
298 // - Refuse message (myOpt_RefuseMessage = 2)
299 // - Refuse chat (myOpt_RefuseChat = 3)
300 // - Automatic response (myOpt_AutomaticResponse = 4)"
302 // 214 Quoting message Optional
304 // Fields used in the reply:
306 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
307 if !cc.Authorize(accessSendPrivMsg) {
308 res = append(res, cc.NewErrReply(t, "You are not allowed to send private messages."))
309 return res, errors.New("user is not allowed to send private messages")
312 msg := t.GetField(FieldData)
313 ID := t.GetField(FieldUserID)
315 reply := NewTransaction(
318 NewField(FieldData, msg.Data),
319 NewField(FieldUserName, cc.UserName),
320 NewField(FieldUserID, *cc.ID),
321 NewField(FieldOptions, []byte{0, 1}),
324 // Later versions of Hotline include the original message in the FieldQuotingMsg field so
325 // the receiving client can display both the received message and what it is in reply to
326 if t.GetField(FieldQuotingMsg).Data != nil {
327 reply.Fields = append(reply.Fields, NewField(FieldQuotingMsg, t.GetField(FieldQuotingMsg).Data))
330 id, err := byteToInt(ID.Data)
332 return res, errors.New("invalid client ID")
334 otherClient, ok := cc.Server.Clients[uint16(id)]
336 return res, errors.New("invalid client ID")
339 // Check if target user has "Refuse private messages" flag
340 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(otherClient.Flags)))
341 if flagBitmap.Bit(UserFlagRefusePM) == 1 {
346 NewField(FieldData, []byte(string(otherClient.UserName)+" does not accept private messages.")),
347 NewField(FieldUserName, otherClient.UserName),
348 NewField(FieldUserID, *otherClient.ID),
349 NewField(FieldOptions, []byte{0, 2}),
353 res = append(res, *reply)
356 // Respond with auto reply if other client has it enabled
357 if len(otherClient.AutoReply) > 0 {
362 NewField(FieldData, otherClient.AutoReply),
363 NewField(FieldUserName, otherClient.UserName),
364 NewField(FieldUserID, *otherClient.ID),
365 NewField(FieldOptions, []byte{0, 1}),
370 res = append(res, cc.NewReply(t))
375 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
376 fileName := t.GetField(FieldFileName).Data
377 filePath := t.GetField(FieldFilePath).Data
379 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
384 fw, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
389 encodedName, err := txtEncoder.String(fw.name)
391 return res, fmt.Errorf("invalid filepath encoding: %w", err)
395 NewField(FieldFileName, []byte(encodedName)),
396 NewField(FieldFileTypeString, fw.ffo.FlatFileInformationFork.friendlyType()),
397 NewField(FieldFileCreatorString, fw.ffo.FlatFileInformationFork.friendlyCreator()),
398 NewField(FieldFileType, fw.ffo.FlatFileInformationFork.TypeSignature),
399 NewField(FieldFileCreateDate, fw.ffo.FlatFileInformationFork.CreateDate),
400 NewField(FieldFileModifyDate, fw.ffo.FlatFileInformationFork.ModifyDate),
403 // Include the optional FileComment field if there is a comment.
404 if len(fw.ffo.FlatFileInformationFork.Comment) != 0 {
405 fields = append(fields, NewField(FieldFileComment, fw.ffo.FlatFileInformationFork.Comment))
408 // Include the FileSize field for files.
409 if !bytes.Equal(fw.ffo.FlatFileInformationFork.TypeSignature, []byte{0x66, 0x6c, 0x64, 0x72}) {
410 fields = append(fields, NewField(FieldFileSize, fw.totalSize()))
413 res = append(res, cc.NewReply(t, fields...))
417 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
418 // Fields used in the request:
420 // * 202 File path Optional
421 // * 211 File new name Optional
422 // * 210 File comment Optional
423 // Fields used in the reply: None
424 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
425 fileName := t.GetField(FieldFileName).Data
426 filePath := t.GetField(FieldFilePath).Data
428 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
433 fi, err := cc.Server.FS.Stat(fullFilePath)
438 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
442 if t.GetField(FieldFileComment).Data != nil {
443 switch mode := fi.Mode(); {
445 if !cc.Authorize(accessSetFolderComment) {
446 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for folders."))
449 case mode.IsRegular():
450 if !cc.Authorize(accessSetFileComment) {
451 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for files."))
456 if err := hlFile.ffo.FlatFileInformationFork.setComment(t.GetField(FieldFileComment).Data); err != nil {
459 w, err := hlFile.infoForkWriter()
463 _, err = io.Copy(w, &hlFile.ffo.FlatFileInformationFork)
469 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, t.GetField(FieldFileNewName).Data)
474 fileNewName := t.GetField(FieldFileNewName).Data
476 if fileNewName != nil {
477 switch mode := fi.Mode(); {
479 if !cc.Authorize(accessRenameFolder) {
480 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
483 err = os.Rename(fullFilePath, fullNewFilePath)
484 if os.IsNotExist(err) {
485 res = append(res, cc.NewErrReply(t, "Cannot rename folder "+string(fileName)+" because it does not exist or cannot be found."))
488 case mode.IsRegular():
489 if !cc.Authorize(accessRenameFile) {
490 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
493 fileDir, err := readPath(cc.Server.Config.FileRoot, filePath, []byte{})
497 hlFile.name, err = txtDecoder.String(string(fileNewName))
499 return res, fmt.Errorf("invalid filepath encoding: %w", err)
502 err = hlFile.move(fileDir)
503 if os.IsNotExist(err) {
504 res = append(res, cc.NewErrReply(t, "Cannot rename file "+string(fileName)+" because it does not exist or cannot be found."))
513 res = append(res, cc.NewReply(t))
517 // HandleDeleteFile deletes a file or folder
518 // Fields used in the request:
521 // Fields used in the reply: none
522 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
523 fileName := t.GetField(FieldFileName).Data
524 filePath := t.GetField(FieldFilePath).Data
526 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
531 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
536 fi, err := hlFile.dataFile()
538 res = append(res, cc.NewErrReply(t, "Cannot delete file "+string(fileName)+" because it does not exist or cannot be found."))
542 switch mode := fi.Mode(); {
544 if !cc.Authorize(accessDeleteFolder) {
545 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
548 case mode.IsRegular():
549 if !cc.Authorize(accessDeleteFile) {
550 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
555 if err := hlFile.delete(); err != nil {
559 res = append(res, cc.NewReply(t))
563 // HandleMoveFile moves files or folders. Note: seemingly not documented
564 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
565 fileName := string(t.GetField(FieldFileName).Data)
567 filePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(FieldFilePath).Data, t.GetField(FieldFileName).Data)
572 fileNewPath, err := readPath(cc.Server.Config.FileRoot, t.GetField(FieldFileNewPath).Data, nil)
577 cc.logger.Infow("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
579 hlFile, err := newFileWrapper(cc.Server.FS, filePath, 0)
584 fi, err := hlFile.dataFile()
586 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
589 switch mode := fi.Mode(); {
591 if !cc.Authorize(accessMoveFolder) {
592 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
595 case mode.IsRegular():
596 if !cc.Authorize(accessMoveFile) {
597 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
601 if err := hlFile.move(fileNewPath); err != nil {
604 // TODO: handle other possible errors; e.g. fileWrapper delete fails due to fileWrapper permission issue
606 res = append(res, cc.NewReply(t))
610 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
611 if !cc.Authorize(accessCreateFolder) {
612 res = append(res, cc.NewErrReply(t, "You are not allowed to create folders."))
615 folderName := string(t.GetField(FieldFileName).Data)
617 folderName = path.Join("/", folderName)
621 // FieldFilePath is only present for nested paths
622 if t.GetField(FieldFilePath).Data != nil {
624 _, err := newFp.Write(t.GetField(FieldFilePath).Data)
629 for _, pathItem := range newFp.Items {
630 subPath = filepath.Join("/", subPath, string(pathItem.Name))
633 newFolderPath := path.Join(cc.Server.Config.FileRoot, subPath, folderName)
634 newFolderPath, err = txtDecoder.String(newFolderPath)
636 return res, fmt.Errorf("invalid filepath encoding: %w", err)
639 // TODO: check path and folder name lengths
641 if _, err := cc.Server.FS.Stat(newFolderPath); !os.IsNotExist(err) {
642 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that name.", folderName)
643 return []Transaction{cc.NewErrReply(t, msg)}, nil
646 if err := cc.Server.FS.Mkdir(newFolderPath, 0777); err != nil {
647 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
648 return []Transaction{cc.NewErrReply(t, msg)}, nil
651 res = append(res, cc.NewReply(t))
655 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
656 if !cc.Authorize(accessModifyUser) {
657 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
661 login := decodeString(t.GetField(FieldUserLogin).Data)
662 userName := string(t.GetField(FieldUserName).Data)
664 newAccessLvl := t.GetField(FieldUserAccess).Data
666 account := cc.Server.Accounts[login]
668 return append(res, cc.NewErrReply(t, "Account not found.")), nil
670 account.Name = userName
671 copy(account.Access[:], newAccessLvl)
673 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
674 // not include FieldUserPassword
675 if t.GetField(FieldUserPassword).Data == nil {
676 account.Password = hashAndSalt([]byte(""))
679 if !bytes.Equal([]byte{0}, t.GetField(FieldUserPassword).Data) {
680 account.Password = hashAndSalt(t.GetField(FieldUserPassword).Data)
683 out, err := yaml.Marshal(&account)
687 if err := os.WriteFile(filepath.Join(cc.Server.ConfigDir, "Users", login+".yaml"), out, 0666); err != nil {
691 // Notify connected clients logged in as the user of the new access level
692 for _, c := range cc.Server.Clients {
693 if c.Account.Login == login {
694 // Note: comment out these two lines to test server-side deny messages
695 newT := NewTransaction(TranUserAccess, c.ID, NewField(FieldUserAccess, newAccessLvl))
696 res = append(res, *newT)
698 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
699 if c.Authorize(accessDisconUser) {
700 flagBitmap.SetBit(flagBitmap, UserFlagAdmin, 1)
702 flagBitmap.SetBit(flagBitmap, UserFlagAdmin, 0)
704 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
706 c.Account.Access = account.Access
709 TranNotifyChangeUser,
710 NewField(FieldUserID, *c.ID),
711 NewField(FieldUserFlags, c.Flags),
712 NewField(FieldUserName, c.UserName),
713 NewField(FieldUserIconID, c.Icon),
718 res = append(res, cc.NewReply(t))
722 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
723 if !cc.Authorize(accessOpenUser) {
724 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
728 account := cc.Server.Accounts[string(t.GetField(FieldUserLogin).Data)]
730 res = append(res, cc.NewErrReply(t, "Account does not exist."))
734 res = append(res, cc.NewReply(t,
735 NewField(FieldUserName, []byte(account.Name)),
736 NewField(FieldUserLogin, encodeString(t.GetField(FieldUserLogin).Data)),
737 NewField(FieldUserPassword, []byte(account.Password)),
738 NewField(FieldUserAccess, account.Access[:]),
743 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
744 if !cc.Authorize(accessOpenUser) {
745 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
749 var userFields []Field
750 for _, acc := range cc.Server.Accounts {
751 b, err := io.ReadAll(acc)
756 userFields = append(userFields, NewField(FieldData, b))
759 res = append(res, cc.NewReply(t, userFields...))
763 // HandleUpdateUser is used by the v1.5+ multi-user editor to perform account editing for multiple users at a time.
764 // An update can be a mix of these actions:
767 // * Modify user (including renaming the account login)
769 // The Transaction sent by the client includes one data field per user that was modified. This data field in turn
770 // contains another data field encoded in its payload with a varying number of sub fields depending on which action is
771 // performed. This seems to be the only place in the Hotline protocol where a data field contains another data field.
772 func HandleUpdateUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
773 for _, field := range t.Fields {
774 subFields, err := ReadFields(field.Data[0:2], field.Data[2:])
779 // If there's only one subfield, that indicates this is a delete operation for the login in FieldData
780 if len(subFields) == 1 {
781 if !cc.Authorize(accessDeleteUser) {
782 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
786 login := decodeString(getField(FieldData, &subFields).Data)
787 cc.logger.Infow("DeleteUser", "login", login)
789 if err := cc.Server.DeleteUser(login); err != nil {
795 // login of the account to update
796 var accountToUpdate, loginToRename string
798 // If FieldData is included, this is a rename operation where FieldData contains the login of the existing
799 // account and FieldUserLogin contains the new login.
800 if getField(FieldData, &subFields) != nil {
801 loginToRename = decodeString(getField(FieldData, &subFields).Data)
803 userLogin := decodeString(getField(FieldUserLogin, &subFields).Data)
804 if loginToRename != "" {
805 accountToUpdate = loginToRename
807 accountToUpdate = userLogin
810 // Check if accountToUpdate has an existing account. If so, we know we are updating an existing user.
811 if acc, ok := cc.Server.Accounts[accountToUpdate]; ok {
812 if loginToRename != "" {
813 cc.logger.Infow("RenameUser", "prevLogin", accountToUpdate, "newLogin", userLogin)
815 cc.logger.Infow("UpdateUser", "login", accountToUpdate)
818 // account exists, so this is an update action
819 if !cc.Authorize(accessModifyUser) {
820 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
824 // This part is a bit tricky. There are three possibilities:
825 // 1) The transaction is intended to update the password.
826 // In this case, FieldUserPassword is sent with the new password.
827 // 2) The transaction is intended to remove the password.
828 // In this case, FieldUserPassword is not sent.
829 // 3) The transaction updates the users access bits, but not the password.
830 // In this case, FieldUserPassword is sent with zero as the only byte.
831 if getField(FieldUserPassword, &subFields) != nil {
832 newPass := getField(FieldUserPassword, &subFields).Data
833 if !bytes.Equal([]byte{0}, newPass) {
834 acc.Password = hashAndSalt(newPass)
837 acc.Password = hashAndSalt([]byte(""))
840 if getField(FieldUserAccess, &subFields) != nil {
841 copy(acc.Access[:], getField(FieldUserAccess, &subFields).Data)
844 err = cc.Server.UpdateUser(
845 decodeString(getField(FieldData, &subFields).Data),
846 decodeString(getField(FieldUserLogin, &subFields).Data),
847 string(getField(FieldUserName, &subFields).Data),
855 if !cc.Authorize(accessCreateUser) {
856 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
860 cc.logger.Infow("CreateUser", "login", userLogin)
862 newAccess := accessBitmap{}
863 copy(newAccess[:], getField(FieldUserAccess, &subFields).Data)
865 // Prevent account from creating new account with greater permission
866 for i := 0; i < 64; i++ {
867 if newAccess.IsSet(i) {
868 if !cc.Authorize(i) {
869 return append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself.")), nil
874 err = cc.Server.NewUser(userLogin, string(getField(FieldUserName, &subFields).Data), string(getField(FieldUserPassword, &subFields).Data), newAccess)
876 return append(res, cc.NewErrReply(t, "Cannot create account because there is already an account with that login.")), nil
881 res = append(res, cc.NewReply(t))
885 // HandleNewUser creates a new user account
886 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
887 if !cc.Authorize(accessCreateUser) {
888 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
892 login := decodeString(t.GetField(FieldUserLogin).Data)
894 // If the account already dataFile, reply with an error
895 if _, ok := cc.Server.Accounts[login]; ok {
896 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
900 newAccess := accessBitmap{}
901 copy(newAccess[:], t.GetField(FieldUserAccess).Data)
903 // Prevent account from creating new account with greater permission
904 for i := 0; i < 64; i++ {
905 if newAccess.IsSet(i) {
906 if !cc.Authorize(i) {
907 res = append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself."))
913 if err := cc.Server.NewUser(login, string(t.GetField(FieldUserName).Data), string(t.GetField(FieldUserPassword).Data), newAccess); err != nil {
914 res = append(res, cc.NewErrReply(t, "Cannot create account because there is already an account with that login."))
918 res = append(res, cc.NewReply(t))
922 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
923 if !cc.Authorize(accessDeleteUser) {
924 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
928 login := decodeString(t.GetField(FieldUserLogin).Data)
930 if err := cc.Server.DeleteUser(login); err != nil {
934 res = append(res, cc.NewReply(t))
938 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
939 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
940 if !cc.Authorize(accessBroadcast) {
941 res = append(res, cc.NewErrReply(t, "You are not allowed to send broadcast messages."))
947 NewField(FieldData, t.GetField(TranGetMsgs).Data),
948 NewField(FieldChatOptions, []byte{0}),
951 res = append(res, cc.NewReply(t))
955 // HandleGetClientInfoText returns user information for the specific user.
957 // Fields used in the request:
960 // Fields used in the reply:
962 // 101 Data User info text string
963 func HandleGetClientInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
964 if !cc.Authorize(accessGetClientInfo) {
965 res = append(res, cc.NewErrReply(t, "You are not allowed to get client info."))
969 clientID, _ := byteToInt(t.GetField(FieldUserID).Data)
971 clientConn := cc.Server.Clients[uint16(clientID)]
972 if clientConn == nil {
973 return append(res, cc.NewErrReply(t, "User not found.")), err
976 res = append(res, cc.NewReply(t,
977 NewField(FieldData, []byte(clientConn.String())),
978 NewField(FieldUserName, clientConn.UserName),
983 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
984 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
989 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
990 if t.GetField(FieldUserName).Data != nil {
991 if cc.Authorize(accessAnyName) {
992 cc.UserName = t.GetField(FieldUserName).Data
994 cc.UserName = []byte(cc.Account.Name)
998 cc.Icon = t.GetField(FieldUserIconID).Data
1000 cc.logger = cc.logger.With("name", string(cc.UserName))
1001 cc.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(cc.Version); return i }()))
1003 options := t.GetField(FieldOptions).Data
1004 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1006 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
1008 // Check refuse private PM option
1009 if optBitmap.Bit(refusePM) == 1 {
1010 flagBitmap.SetBit(flagBitmap, UserFlagRefusePM, 1)
1011 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1014 // Check refuse private chat option
1015 if optBitmap.Bit(refuseChat) == 1 {
1016 flagBitmap.SetBit(flagBitmap, UserFlagRefusePChat, 1)
1017 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1020 // Check auto response
1021 if optBitmap.Bit(autoResponse) == 1 {
1022 cc.AutoReply = t.GetField(FieldAutomaticResponse).Data
1024 cc.AutoReply = []byte{}
1027 trans := cc.notifyOthers(
1029 TranNotifyChangeUser, nil,
1030 NewField(FieldUserName, cc.UserName),
1031 NewField(FieldUserID, *cc.ID),
1032 NewField(FieldUserIconID, cc.Icon),
1033 NewField(FieldUserFlags, cc.Flags),
1036 res = append(res, trans...)
1038 if cc.Server.Config.BannerFile != "" {
1039 res = append(res, *NewTransaction(TranServerBanner, cc.ID, NewField(FieldBannerType, []byte("JPEG"))))
1042 res = append(res, cc.NewReply(t))
1047 // HandleTranOldPostNews updates the flat news
1048 // Fields used in this request:
1050 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1051 if !cc.Authorize(accessNewsPostArt) {
1052 res = append(res, cc.NewErrReply(t, "You are not allowed to post news."))
1056 cc.Server.flatNewsMux.Lock()
1057 defer cc.Server.flatNewsMux.Unlock()
1059 newsDateTemplate := defaultNewsDateFormat
1060 if cc.Server.Config.NewsDateFormat != "" {
1061 newsDateTemplate = cc.Server.Config.NewsDateFormat
1064 newsTemplate := defaultNewsTemplate
1065 if cc.Server.Config.NewsDelimiter != "" {
1066 newsTemplate = cc.Server.Config.NewsDelimiter
1069 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(FieldData).Data)
1070 newsPost = strings.ReplaceAll(newsPost, "\n", "\r")
1072 // update news in memory
1073 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
1075 // update news on disk
1076 if err := cc.Server.FS.WriteFile(filepath.Join(cc.Server.ConfigDir, "MessageBoard.txt"), cc.Server.FlatNews, 0644); err != nil {
1080 // Notify all clients of updated news
1083 NewField(FieldData, []byte(newsPost)),
1086 res = append(res, cc.NewReply(t))
1090 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1091 if !cc.Authorize(accessDisconUser) {
1092 res = append(res, cc.NewErrReply(t, "You are not allowed to disconnect users."))
1096 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(FieldUserID).Data)]
1098 if clientConn.Authorize(accessCannotBeDiscon) {
1099 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
1103 // If FieldOptions is set, then the client IP is banned in addition to disconnected.
1104 // 00 01 = temporary ban
1105 // 00 02 = permanent ban
1106 if t.GetField(FieldOptions).Data != nil {
1107 switch t.GetField(FieldOptions).Data[1] {
1109 // send message: "You are temporarily banned on this server"
1110 cc.logger.Infow("Disconnect & temporarily ban " + string(clientConn.UserName))
1112 res = append(res, *NewTransaction(
1115 NewField(FieldData, []byte("You are temporarily banned on this server")),
1116 NewField(FieldChatOptions, []byte{0, 0}),
1119 banUntil := time.Now().Add(tempBanDuration)
1120 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = &banUntil
1122 // send message: "You are permanently banned on this server"
1123 cc.logger.Infow("Disconnect & ban " + string(clientConn.UserName))
1125 res = append(res, *NewTransaction(
1128 NewField(FieldData, []byte("You are permanently banned on this server")),
1129 NewField(FieldChatOptions, []byte{0, 0}),
1132 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = nil
1135 err := cc.Server.writeBanList()
1141 // TODO: remove this awful hack
1143 time.Sleep(1 * time.Second)
1144 clientConn.Disconnect()
1147 return append(res, cc.NewReply(t)), err
1150 // HandleGetNewsCatNameList returns a list of news categories for a path
1151 // Fields used in the request:
1152 // 325 News path (Optional)
1153 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1154 if !cc.Authorize(accessNewsReadArt) {
1155 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1159 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1160 cats := cc.Server.GetNewsCatByPath(pathStrs)
1162 // To store the keys in slice in sorted order
1163 keys := make([]string, len(cats))
1165 for k := range cats {
1171 var fieldData []Field
1172 for _, k := range keys {
1174 b, _ := cat.MarshalBinary()
1175 fieldData = append(fieldData, NewField(
1176 FieldNewsCatListData15,
1181 res = append(res, cc.NewReply(t, fieldData...))
1185 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1186 if !cc.Authorize(accessNewsCreateCat) {
1187 res = append(res, cc.NewErrReply(t, "You are not allowed to create news categories."))
1191 name := string(t.GetField(FieldNewsCatName).Data)
1192 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1194 cats := cc.Server.GetNewsCatByPath(pathStrs)
1195 cats[name] = NewsCategoryListData15{
1197 Type: [2]byte{0, 3},
1198 Articles: map[uint32]*NewsArtData{},
1199 SubCats: make(map[string]NewsCategoryListData15),
1202 if err := cc.Server.writeThreadedNews(); err != nil {
1205 res = append(res, cc.NewReply(t))
1209 // Fields used in the request:
1210 // 322 News category name
1212 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1213 if !cc.Authorize(accessNewsCreateFldr) {
1214 res = append(res, cc.NewErrReply(t, "You are not allowed to create news folders."))
1218 name := string(t.GetField(FieldFileName).Data)
1219 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1221 cc.logger.Infof("Creating new news folder %s", name)
1223 cats := cc.Server.GetNewsCatByPath(pathStrs)
1224 cats[name] = NewsCategoryListData15{
1226 Type: [2]byte{0, 2},
1227 Articles: map[uint32]*NewsArtData{},
1228 SubCats: make(map[string]NewsCategoryListData15),
1230 if err := cc.Server.writeThreadedNews(); err != nil {
1233 res = append(res, cc.NewReply(t))
1237 // HandleGetNewsArtData gets the list of article names at the specified news path.
1239 // Fields used in the request:
1240 // 325 News path Optional
1242 // Fields used in the reply:
1243 // 321 News article list data Optional
1244 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1245 if !cc.Authorize(accessNewsReadArt) {
1246 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1249 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1251 var cat NewsCategoryListData15
1252 cats := cc.Server.ThreadedNews.Categories
1254 for _, fp := range pathStrs {
1256 cats = cats[fp].SubCats
1259 nald := cat.GetNewsArtListData()
1261 b, err := io.ReadAll(&nald)
1266 res = append(res, cc.NewReply(t, NewField(FieldNewsArtListData, b)))
1270 // HandleGetNewsArtData requests information about the specific news article.
1271 // Fields used in the request:
1275 // 326 News article ID
1276 // 327 News article data flavor
1278 // Fields used in the reply:
1279 // 328 News article title
1280 // 329 News article poster
1281 // 330 News article date
1282 // 331 Previous article ID
1283 // 332 Next article ID
1284 // 335 Parent article ID
1285 // 336 First child article ID
1286 // 327 News article data flavor "Should be “text/plain”
1287 // 333 News article data Optional (if data flavor is “text/plain”)
1288 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1289 if !cc.Authorize(accessNewsReadArt) {
1290 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1294 var cat NewsCategoryListData15
1295 cats := cc.Server.ThreadedNews.Categories
1297 for _, fp := range ReadNewsPath(t.GetField(FieldNewsPath).Data) {
1299 cats = cats[fp].SubCats
1302 // The official Hotline clients will send the article ID as 2 bytes if possible, but
1303 // some third party clients such as Frogblast and Heildrun will always send 4 bytes
1304 convertedID, err := byteToInt(t.GetField(FieldNewsArtID).Data)
1309 art := cat.Articles[uint32(convertedID)]
1311 res = append(res, cc.NewReply(t))
1315 res = append(res, cc.NewReply(t,
1316 NewField(FieldNewsArtTitle, []byte(art.Title)),
1317 NewField(FieldNewsArtPoster, []byte(art.Poster)),
1318 NewField(FieldNewsArtDate, art.Date),
1319 NewField(FieldNewsArtPrevArt, art.PrevArt),
1320 NewField(FieldNewsArtNextArt, art.NextArt),
1321 NewField(FieldNewsArtParentArt, art.ParentArt),
1322 NewField(FieldNewsArt1stChildArt, art.FirstChildArt),
1323 NewField(FieldNewsArtDataFlav, []byte("text/plain")),
1324 NewField(FieldNewsArtData, []byte(art.Data)),
1329 // HandleDelNewsItem deletes an existing threaded news folder or category from the server.
1330 // Fields used in the request:
1332 // Fields used in the reply:
1334 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1335 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1337 cats := cc.Server.ThreadedNews.Categories
1338 delName := pathStrs[len(pathStrs)-1]
1339 if len(pathStrs) > 1 {
1340 for _, fp := range pathStrs[0 : len(pathStrs)-1] {
1341 cats = cats[fp].SubCats
1345 if cats[delName].Type == [2]byte{0, 3} {
1346 if !cc.Authorize(accessNewsDeleteCat) {
1347 return append(res, cc.NewErrReply(t, "You are not allowed to delete news categories.")), nil
1350 if !cc.Authorize(accessNewsDeleteFldr) {
1351 return append(res, cc.NewErrReply(t, "You are not allowed to delete news folders.")), nil
1355 delete(cats, delName)
1357 if err := cc.Server.writeThreadedNews(); err != nil {
1361 return append(res, cc.NewReply(t)), nil
1364 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1365 if !cc.Authorize(accessNewsDeleteArt) {
1366 res = append(res, cc.NewErrReply(t, "You are not allowed to delete news articles."))
1372 // 326 News article ID
1373 // 337 News article – recursive delete Delete child articles (1) or not (0)
1374 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1375 ID, err := byteToInt(t.GetField(FieldNewsArtID).Data)
1380 // TODO: Delete recursive
1381 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1383 catName := pathStrs[len(pathStrs)-1]
1384 cat := cats[catName]
1386 delete(cat.Articles, uint32(ID))
1389 if err := cc.Server.writeThreadedNews(); err != nil {
1393 res = append(res, cc.NewReply(t))
1399 // 326 News article ID ID of the parent article?
1400 // 328 News article title
1401 // 334 News article flags
1402 // 327 News article data flavor Currently “text/plain”
1403 // 333 News article data
1404 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1405 if !cc.Authorize(accessNewsPostArt) {
1406 res = append(res, cc.NewErrReply(t, "You are not allowed to post news articles."))
1410 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1411 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1413 catName := pathStrs[len(pathStrs)-1]
1414 cat := cats[catName]
1416 artID, err := byteToInt(t.GetField(FieldNewsArtID).Data)
1420 convertedArtID := uint32(artID)
1421 bs := make([]byte, 4)
1422 binary.BigEndian.PutUint32(bs, convertedArtID)
1424 newArt := NewsArtData{
1425 Title: string(t.GetField(FieldNewsArtTitle).Data),
1426 Poster: string(cc.UserName),
1427 Date: toHotlineTime(time.Now()),
1428 PrevArt: []byte{0, 0, 0, 0},
1429 NextArt: []byte{0, 0, 0, 0},
1431 FirstChildArt: []byte{0, 0, 0, 0},
1432 DataFlav: []byte("text/plain"),
1433 Data: string(t.GetField(FieldNewsArtData).Data),
1437 for k := range cat.Articles {
1438 keys = append(keys, int(k))
1444 prevID := uint32(keys[len(keys)-1])
1447 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1449 // Set next article ID
1450 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1453 // Update parent article with first child reply
1454 parentID := convertedArtID
1456 parentArt := cat.Articles[parentID]
1458 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1459 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1463 cat.Articles[nextID] = &newArt
1466 if err := cc.Server.writeThreadedNews(); err != nil {
1470 res = append(res, cc.NewReply(t))
1474 // HandleGetMsgs returns the flat news data
1475 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1476 if !cc.Authorize(accessNewsReadArt) {
1477 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1481 res = append(res, cc.NewReply(t, NewField(FieldData, cc.Server.FlatNews)))
1486 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1487 if !cc.Authorize(accessDownloadFile) {
1488 res = append(res, cc.NewErrReply(t, "You are not allowed to download files."))
1492 fileName := t.GetField(FieldFileName).Data
1493 filePath := t.GetField(FieldFilePath).Data
1494 resumeData := t.GetField(FieldFileResumeData).Data
1496 var dataOffset int64
1497 var frd FileResumeData
1498 if resumeData != nil {
1499 if err := frd.UnmarshalBinary(t.GetField(FieldFileResumeData).Data); err != nil {
1502 // TODO: handle rsrc fork offset
1503 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1506 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1511 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, dataOffset)
1516 xferSize := hlFile.ffo.TransferSize(0)
1518 ft := cc.newFileTransfer(FileDownload, fileName, filePath, xferSize)
1520 // TODO: refactor to remove this
1521 if resumeData != nil {
1522 var frd FileResumeData
1523 if err := frd.UnmarshalBinary(t.GetField(FieldFileResumeData).Data); err != nil {
1526 ft.fileResumeData = &frd
1529 // Optional field for when a HL v1.5+ client requests file preview
1530 // Used only for TEXT, JPEG, GIFF, BMP or PICT files
1531 // The value will always be 2
1532 if t.GetField(FieldFileTransferOptions).Data != nil {
1533 ft.options = t.GetField(FieldFileTransferOptions).Data
1534 xferSize = hlFile.ffo.FlatFileDataForkHeader.DataSize[:]
1537 res = append(res, cc.NewReply(t,
1538 NewField(FieldRefNum, ft.refNum[:]),
1539 NewField(FieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1540 NewField(FieldTransferSize, xferSize),
1541 NewField(FieldFileSize, hlFile.ffo.FlatFileDataForkHeader.DataSize[:]),
1547 // Download all files from the specified folder and sub-folders
1548 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1549 if !cc.Authorize(accessDownloadFile) {
1550 res = append(res, cc.NewErrReply(t, "You are not allowed to download folders."))
1554 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(FieldFilePath).Data, t.GetField(FieldFileName).Data)
1559 transferSize, err := CalcTotalSize(fullFilePath)
1563 itemCount, err := CalcItemCount(fullFilePath)
1568 fileTransfer := cc.newFileTransfer(FolderDownload, t.GetField(FieldFileName).Data, t.GetField(FieldFilePath).Data, transferSize)
1571 _, err = fp.Write(t.GetField(FieldFilePath).Data)
1576 res = append(res, cc.NewReply(t,
1577 NewField(FieldRefNum, fileTransfer.ReferenceNumber),
1578 NewField(FieldTransferSize, transferSize),
1579 NewField(FieldFolderItemCount, itemCount),
1580 NewField(FieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1585 // Upload all files from the local folder and its subfolders to the specified path on the server
1586 // Fields used in the request
1589 // 108 transfer size Total size of all items in the folder
1590 // 220 Folder item count
1591 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1592 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1594 if t.GetField(FieldFilePath).Data != nil {
1595 if _, err = fp.Write(t.GetField(FieldFilePath).Data); err != nil {
1600 // Handle special cases for Upload and Drop Box folders
1601 if !cc.Authorize(accessUploadAnywhere) {
1602 if !fp.IsUploadDir() && !fp.IsDropbox() {
1603 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))))
1608 fileTransfer := cc.newFileTransfer(FolderUpload,
1609 t.GetField(FieldFileName).Data,
1610 t.GetField(FieldFilePath).Data,
1611 t.GetField(FieldTransferSize).Data,
1614 fileTransfer.FolderItemCount = t.GetField(FieldFolderItemCount).Data
1616 res = append(res, cc.NewReply(t, NewField(FieldRefNum, fileTransfer.ReferenceNumber)))
1621 // Fields used in the request:
1624 // 204 File transfer options "Optional
1625 // Used only to resume download, currently has value 2"
1626 // 108 File transfer size "Optional used if download is not resumed"
1627 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1628 if !cc.Authorize(accessUploadFile) {
1629 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1633 fileName := t.GetField(FieldFileName).Data
1634 filePath := t.GetField(FieldFilePath).Data
1635 transferOptions := t.GetField(FieldFileTransferOptions).Data
1636 transferSize := t.GetField(FieldTransferSize).Data // not sent for resume
1639 if filePath != nil {
1640 if _, err = fp.Write(filePath); err != nil {
1645 // Handle special cases for Upload and Drop Box folders
1646 if !cc.Authorize(accessUploadAnywhere) {
1647 if !fp.IsUploadDir() && !fp.IsDropbox() {
1648 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))))
1652 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1657 if _, err := cc.Server.FS.Stat(fullFilePath); err == nil {
1658 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))))
1662 ft := cc.newFileTransfer(FileUpload, fileName, filePath, transferSize)
1664 replyT := cc.NewReply(t, NewField(FieldRefNum, ft.ReferenceNumber))
1666 // client has requested to resume a partially transferred file
1667 if transferOptions != nil {
1668 fileInfo, err := cc.Server.FS.Stat(fullFilePath + incompleteFileSuffix)
1673 offset := make([]byte, 4)
1674 binary.BigEndian.PutUint32(offset, uint32(fileInfo.Size()))
1676 fileResumeData := NewFileResumeData([]ForkInfoList{
1677 *NewForkInfoList(offset),
1680 b, _ := fileResumeData.BinaryMarshal()
1682 ft.TransferSize = offset
1684 replyT.Fields = append(replyT.Fields, NewField(FieldFileResumeData, b))
1687 res = append(res, replyT)
1691 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1692 if len(t.GetField(FieldUserIconID).Data) == 4 {
1693 cc.Icon = t.GetField(FieldUserIconID).Data[2:]
1695 cc.Icon = t.GetField(FieldUserIconID).Data
1697 if cc.Authorize(accessAnyName) {
1698 cc.UserName = t.GetField(FieldUserName).Data
1701 // the options field is only passed by the client versions > 1.2.3.
1702 options := t.GetField(FieldOptions).Data
1704 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1705 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
1707 flagBitmap.SetBit(flagBitmap, UserFlagRefusePM, optBitmap.Bit(refusePM))
1708 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1710 flagBitmap.SetBit(flagBitmap, UserFlagRefusePChat, optBitmap.Bit(refuseChat))
1711 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1713 // Check auto response
1714 if optBitmap.Bit(autoResponse) == 1 {
1715 cc.AutoReply = t.GetField(FieldAutomaticResponse).Data
1717 cc.AutoReply = []byte{}
1721 for _, c := range sortedClients(cc.Server.Clients) {
1722 res = append(res, *NewTransaction(
1723 TranNotifyChangeUser,
1725 NewField(FieldUserID, *cc.ID),
1726 NewField(FieldUserIconID, cc.Icon),
1727 NewField(FieldUserFlags, cc.Flags),
1728 NewField(FieldUserName, cc.UserName),
1735 // HandleKeepAlive responds to keepalive transactions with an empty reply
1736 // * HL 1.9.2 Client sends keepalive msg every 3 minutes
1737 // * HL 1.2.3 Client doesn't send keepalives
1738 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1739 res = append(res, cc.NewReply(t))
1744 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1745 fullPath, err := readPath(
1746 cc.Server.Config.FileRoot,
1747 t.GetField(FieldFilePath).Data,
1755 if t.GetField(FieldFilePath).Data != nil {
1756 if _, err = fp.Write(t.GetField(FieldFilePath).Data); err != nil {
1761 // Handle special case for drop box folders
1762 if fp.IsDropbox() && !cc.Authorize(accessViewDropBoxes) {
1763 res = append(res, cc.NewErrReply(t, "You are not allowed to view drop boxes."))
1767 fileNames, err := getFileNameList(fullPath, cc.Server.Config.IgnoreFiles)
1772 res = append(res, cc.NewReply(t, fileNames...))
1777 // =================================
1778 // Hotline private chat flow
1779 // =================================
1780 // 1. ClientA sends TranInviteNewChat to server with user ID to invite
1781 // 2. Server creates new ChatID
1782 // 3. Server sends TranInviteToChat to invitee
1783 // 4. Server replies to ClientA with new Chat ID
1785 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1786 // If Accepted is clicked:
1787 // 1. ClientB sends TranJoinChat with FieldChatID
1789 // HandleInviteNewChat invites users to new private chat
1790 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1791 if !cc.Authorize(accessOpenChat) {
1792 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1797 targetID := t.GetField(FieldUserID).Data
1798 newChatID := cc.Server.NewPrivateChat(cc)
1800 // Check if target user has "Refuse private chat" flag
1801 binary.BigEndian.Uint16(targetID)
1802 targetClient := cc.Server.Clients[binary.BigEndian.Uint16(targetID)]
1804 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(targetClient.Flags)))
1805 if flagBitmap.Bit(UserFlagRefusePChat) == 1 {
1810 NewField(FieldData, []byte(string(targetClient.UserName)+" does not accept private chats.")),
1811 NewField(FieldUserName, targetClient.UserName),
1812 NewField(FieldUserID, *targetClient.ID),
1813 NewField(FieldOptions, []byte{0, 2}),
1821 NewField(FieldChatID, newChatID),
1822 NewField(FieldUserName, cc.UserName),
1823 NewField(FieldUserID, *cc.ID),
1830 NewField(FieldChatID, newChatID),
1831 NewField(FieldUserName, cc.UserName),
1832 NewField(FieldUserID, *cc.ID),
1833 NewField(FieldUserIconID, cc.Icon),
1834 NewField(FieldUserFlags, cc.Flags),
1841 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1842 if !cc.Authorize(accessOpenChat) {
1843 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1848 targetID := t.GetField(FieldUserID).Data
1849 chatID := t.GetField(FieldChatID).Data
1855 NewField(FieldChatID, chatID),
1856 NewField(FieldUserName, cc.UserName),
1857 NewField(FieldUserID, *cc.ID),
1863 NewField(FieldChatID, chatID),
1864 NewField(FieldUserName, cc.UserName),
1865 NewField(FieldUserID, *cc.ID),
1866 NewField(FieldUserIconID, cc.Icon),
1867 NewField(FieldUserFlags, cc.Flags),
1874 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1875 chatID := t.GetField(FieldChatID).Data
1876 chatInt := binary.BigEndian.Uint32(chatID)
1878 privChat := cc.Server.PrivateChats[chatInt]
1880 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1882 for _, c := range sortedClients(privChat.ClientConn) {
1887 NewField(FieldChatID, chatID),
1888 NewField(FieldData, resMsg),
1896 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1897 // Fields used in the reply:
1898 // * 115 Chat subject
1899 // * 300 User name with info (Optional)
1900 // * 300 (more user names with info)
1901 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1902 chatID := t.GetField(FieldChatID).Data
1903 chatInt := binary.BigEndian.Uint32(chatID)
1905 privChat := cc.Server.PrivateChats[chatInt]
1907 // Send TranNotifyChatChangeUser to current members of the chat to inform of new user
1908 for _, c := range sortedClients(privChat.ClientConn) {
1911 TranNotifyChatChangeUser,
1913 NewField(FieldChatID, chatID),
1914 NewField(FieldUserName, cc.UserName),
1915 NewField(FieldUserID, *cc.ID),
1916 NewField(FieldUserIconID, cc.Icon),
1917 NewField(FieldUserFlags, cc.Flags),
1922 privChat.ClientConn[cc.uint16ID()] = cc
1924 replyFields := []Field{NewField(FieldChatSubject, []byte(privChat.Subject))}
1925 for _, c := range sortedClients(privChat.ClientConn) {
1927 b, err := io.ReadAll(&User{
1931 Name: string(c.UserName),
1936 replyFields = append(replyFields, NewField(FieldUsernameWithInfo, b))
1939 res = append(res, cc.NewReply(t, replyFields...))
1943 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1944 // Fields used in the request:
1945 // - 114 FieldChatID
1947 // Reply is not expected.
1948 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1949 chatID := t.GetField(FieldChatID).Data
1950 chatInt := binary.BigEndian.Uint32(chatID)
1952 privChat, ok := cc.Server.PrivateChats[chatInt]
1957 delete(privChat.ClientConn, cc.uint16ID())
1959 // Notify members of the private chat that the user has left
1960 for _, c := range sortedClients(privChat.ClientConn) {
1963 TranNotifyChatDeleteUser,
1965 NewField(FieldChatID, chatID),
1966 NewField(FieldUserID, *cc.ID),
1974 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1975 // Fields used in the request:
1977 // * 115 Chat subject
1978 // Reply is not expected.
1979 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1980 chatID := t.GetField(FieldChatID).Data
1981 chatInt := binary.BigEndian.Uint32(chatID)
1983 privChat := cc.Server.PrivateChats[chatInt]
1984 privChat.Subject = string(t.GetField(FieldChatSubject).Data)
1986 for _, c := range sortedClients(privChat.ClientConn) {
1989 TranNotifyChatSubject,
1991 NewField(FieldChatID, chatID),
1992 NewField(FieldChatSubject, t.GetField(FieldChatSubject).Data),
2000 // HandleMakeAlias makes a file alias using the specified path.
2001 // Fields used in the request:
2004 // 212 File new path Destination path
2006 // Fields used in the reply:
2008 func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
2009 if !cc.Authorize(accessMakeAlias) {
2010 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
2013 fileName := t.GetField(FieldFileName).Data
2014 filePath := t.GetField(FieldFilePath).Data
2015 fileNewPath := t.GetField(FieldFileNewPath).Data
2017 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
2022 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
2027 cc.logger.Debugw("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
2029 if err := cc.Server.FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
2030 res = append(res, cc.NewErrReply(t, "Error creating alias"))
2034 res = append(res, cc.NewReply(t))
2038 // HandleDownloadBanner handles requests for a new banner from the server
2039 // Fields used in the request:
2041 // Fields used in the reply:
2042 // 107 FieldRefNum Used later for transfer
2043 // 108 FieldTransferSize Size of data to be downloaded
2044 func HandleDownloadBanner(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
2045 fi, err := cc.Server.FS.Stat(filepath.Join(cc.Server.ConfigDir, cc.Server.Config.BannerFile))
2050 ft := cc.newFileTransfer(bannerDownload, []byte{}, []byte{}, make([]byte, 4))
2052 binary.BigEndian.PutUint32(ft.TransferSize, uint32(fi.Size()))
2054 res = append(res, cc.NewReply(t,
2055 NewField(FieldRefNum, ft.refNum[:]),
2056 NewField(FieldTransferSize, ft.TransferSize),