20 type HandlerFunc func(*ClientConn, *Transaction) ([]Transaction, error)
22 type TransactionType struct {
23 Handler HandlerFunc // function for handling the transaction type
24 Name string // Name of transaction as it will appear in logging
25 RequiredFields []requiredField
28 var TransactionHandlers = map[uint16]TransactionType{
34 TranNotifyChangeUser: {
35 Name: "TranNotifyChangeUser",
41 Name: "TranShowAgreement",
44 Name: "TranUserAccess",
46 TranNotifyDeleteUser: {
47 Name: "TranNotifyDeleteUser",
51 Handler: HandleTranAgreed,
55 Handler: HandleChatSend,
56 RequiredFields: []requiredField{
64 Name: "TranDelNewsArt",
65 Handler: HandleDelNewsArt,
68 Name: "TranDelNewsItem",
69 Handler: HandleDelNewsItem,
72 Name: "TranDeleteFile",
73 Handler: HandleDeleteFile,
76 Name: "TranDeleteUser",
77 Handler: HandleDeleteUser,
80 Name: "TranDisconnectUser",
81 Handler: HandleDisconnectUser,
84 Name: "TranDownloadFile",
85 Handler: HandleDownloadFile,
88 Name: "TranDownloadFldr",
89 Handler: HandleDownloadFolder,
91 TranGetClientInfoText: {
92 Name: "TranGetClientInfoText",
93 Handler: HandleGetClientInfoText,
96 Name: "TranGetFileInfo",
97 Handler: HandleGetFileInfo,
99 TranGetFileNameList: {
100 Name: "TranGetFileNameList",
101 Handler: HandleGetFileNameList,
105 Handler: HandleGetMsgs,
107 TranGetNewsArtData: {
108 Name: "TranGetNewsArtData",
109 Handler: HandleGetNewsArtData,
111 TranGetNewsArtNameList: {
112 Name: "TranGetNewsArtNameList",
113 Handler: HandleGetNewsArtNameList,
115 TranGetNewsCatNameList: {
116 Name: "TranGetNewsCatNameList",
117 Handler: HandleGetNewsCatNameList,
121 Handler: HandleGetUser,
123 TranGetUserNameList: {
124 Name: "tranHandleGetUserNameList",
125 Handler: HandleGetUserNameList,
128 Name: "TranInviteNewChat",
129 Handler: HandleInviteNewChat,
132 Name: "TranInviteToChat",
133 Handler: HandleInviteToChat,
136 Name: "TranJoinChat",
137 Handler: HandleJoinChat,
140 Name: "TranKeepAlive",
141 Handler: HandleKeepAlive,
144 Name: "TranJoinChat",
145 Handler: HandleLeaveChat,
148 Name: "TranListUsers",
149 Handler: HandleListUsers,
152 Name: "TranMoveFile",
153 Handler: HandleMoveFile,
156 Name: "TranNewFolder",
157 Handler: HandleNewFolder,
160 Name: "TranNewNewsCat",
161 Handler: HandleNewNewsCat,
164 Name: "TranNewNewsFldr",
165 Handler: HandleNewNewsFldr,
169 Handler: HandleNewUser,
172 Name: "TranUpdateUser",
173 Handler: HandleUpdateUser,
176 Name: "TranOldPostNews",
177 Handler: HandleTranOldPostNews,
180 Name: "TranPostNewsArt",
181 Handler: HandlePostNewsArt,
183 TranRejectChatInvite: {
184 Name: "TranRejectChatInvite",
185 Handler: HandleRejectChatInvite,
187 TranSendInstantMsg: {
188 Name: "TranSendInstantMsg",
189 Handler: HandleSendInstantMsg,
190 RequiredFields: []requiredField{
200 TranSetChatSubject: {
201 Name: "TranSetChatSubject",
202 Handler: HandleSetChatSubject,
205 Name: "TranMakeFileAlias",
206 Handler: HandleMakeAlias,
207 RequiredFields: []requiredField{
208 {ID: FieldFileName, minLen: 1},
209 {ID: FieldFilePath, minLen: 1},
210 {ID: FieldFileNewPath, minLen: 1},
213 TranSetClientUserInfo: {
214 Name: "TranSetClientUserInfo",
215 Handler: HandleSetClientUserInfo,
218 Name: "TranSetFileInfo",
219 Handler: HandleSetFileInfo,
223 Handler: HandleSetUser,
226 Name: "TranUploadFile",
227 Handler: HandleUploadFile,
230 Name: "TranUploadFldr",
231 Handler: HandleUploadFolder,
234 Name: "TranUserBroadcast",
235 Handler: HandleUserBroadcast,
237 TranDownloadBanner: {
238 Name: "TranDownloadBanner",
239 Handler: HandleDownloadBanner,
243 func HandleChatSend(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
244 if !cc.Authorize(accessSendChat) {
245 res = append(res, cc.NewErrReply(t, "You are not allowed to participate in chat."))
249 // Truncate long usernames
250 trunc := fmt.Sprintf("%13s", cc.UserName)
251 formattedMsg := fmt.Sprintf("\r%.14s: %s", trunc, t.GetField(FieldData).Data)
253 // By holding the option key, Hotline chat allows users to send /me formatted messages like:
254 // *** Halcyon does stuff
255 // This is indicated by the presence of the optional field FieldChatOptions set to a value of 1.
256 // Most clients do not send this option for normal chat messages.
257 if t.GetField(FieldChatOptions).Data != nil && bytes.Equal(t.GetField(FieldChatOptions).Data, []byte{0, 1}) {
258 formattedMsg = fmt.Sprintf("\r*** %s %s", cc.UserName, t.GetField(FieldData).Data)
261 // The ChatID field is used to identify messages as belonging to a private chat.
262 // All clients *except* Frogblast omit this field for public chat, but Frogblast sends a value of 00 00 00 00.
263 chatID := t.GetField(FieldChatID).Data
264 if chatID != nil && !bytes.Equal([]byte{0, 0, 0, 0}, chatID) {
265 chatInt := binary.BigEndian.Uint32(chatID)
266 privChat := cc.Server.PrivateChats[chatInt]
268 clients := sortedClients(privChat.ClientConn)
270 // send the message to all connected clients of the private chat
271 for _, c := range clients {
272 res = append(res, *NewTransaction(
275 NewField(FieldChatID, chatID),
276 NewField(FieldData, []byte(formattedMsg)),
282 for _, c := range sortedClients(cc.Server.Clients) {
283 // Filter out clients that do not have the read chat permission
284 if c.Authorize(accessReadChat) {
285 res = append(res, *NewTransaction(TranChatMsg, c.ID, NewField(FieldData, []byte(formattedMsg))))
292 // HandleSendInstantMsg sends instant message to the user on the current server.
293 // Fields used in the request:
297 // One of the following values:
298 // - User message (myOpt_UserMessage = 1)
299 // - Refuse message (myOpt_RefuseMessage = 2)
300 // - Refuse chat (myOpt_RefuseChat = 3)
301 // - Automatic response (myOpt_AutomaticResponse = 4)"
303 // 214 Quoting message Optional
305 // Fields used in the reply:
307 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
308 if !cc.Authorize(accessSendPrivMsg) {
309 res = append(res, cc.NewErrReply(t, "You are not allowed to send private messages."))
310 return res, errors.New("user is not allowed to send private messages")
313 msg := t.GetField(FieldData)
314 ID := t.GetField(FieldUserID)
316 reply := NewTransaction(
319 NewField(FieldData, msg.Data),
320 NewField(FieldUserName, cc.UserName),
321 NewField(FieldUserID, *cc.ID),
322 NewField(FieldOptions, []byte{0, 1}),
325 // Later versions of Hotline include the original message in the FieldQuotingMsg field so
326 // the receiving client can display both the received message and what it is in reply to
327 if t.GetField(FieldQuotingMsg).Data != nil {
328 reply.Fields = append(reply.Fields, NewField(FieldQuotingMsg, t.GetField(FieldQuotingMsg).Data))
331 id, err := byteToInt(ID.Data)
333 return res, errors.New("invalid client ID")
335 otherClient, ok := cc.Server.Clients[uint16(id)]
337 return res, errors.New("invalid client ID")
340 // Check if target user has "Refuse private messages" flag
341 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(otherClient.Flags)))
342 if flagBitmap.Bit(UserFlagRefusePM) == 1 {
347 NewField(FieldData, []byte(string(otherClient.UserName)+" does not accept private messages.")),
348 NewField(FieldUserName, otherClient.UserName),
349 NewField(FieldUserID, *otherClient.ID),
350 NewField(FieldOptions, []byte{0, 2}),
354 res = append(res, *reply)
357 // Respond with auto reply if other client has it enabled
358 if len(otherClient.AutoReply) > 0 {
363 NewField(FieldData, otherClient.AutoReply),
364 NewField(FieldUserName, otherClient.UserName),
365 NewField(FieldUserID, *otherClient.ID),
366 NewField(FieldOptions, []byte{0, 1}),
371 res = append(res, cc.NewReply(t))
376 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
377 fileName := t.GetField(FieldFileName).Data
378 filePath := t.GetField(FieldFilePath).Data
380 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
385 fw, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
390 encodedName, err := txtEncoder.String(fw.name)
392 return res, fmt.Errorf("invalid filepath encoding: %w", err)
396 NewField(FieldFileName, []byte(encodedName)),
397 NewField(FieldFileTypeString, fw.ffo.FlatFileInformationFork.friendlyType()),
398 NewField(FieldFileCreatorString, fw.ffo.FlatFileInformationFork.friendlyCreator()),
399 NewField(FieldFileType, fw.ffo.FlatFileInformationFork.TypeSignature),
400 NewField(FieldFileCreateDate, fw.ffo.FlatFileInformationFork.CreateDate),
401 NewField(FieldFileModifyDate, fw.ffo.FlatFileInformationFork.ModifyDate),
404 // Include the optional FileComment field if there is a comment.
405 if len(fw.ffo.FlatFileInformationFork.Comment) != 0 {
406 fields = append(fields, NewField(FieldFileComment, fw.ffo.FlatFileInformationFork.Comment))
409 // Include the FileSize field for files.
410 if !bytes.Equal(fw.ffo.FlatFileInformationFork.TypeSignature, []byte{0x66, 0x6c, 0x64, 0x72}) {
411 fields = append(fields, NewField(FieldFileSize, fw.totalSize()))
414 res = append(res, cc.NewReply(t, fields...))
418 // HandleSetFileInfo updates a file or folder Name and/or comment from the Get Info window
419 // Fields used in the request:
421 // * 202 File path Optional
422 // * 211 File new Name Optional
423 // * 210 File comment Optional
424 // Fields used in the reply: None
425 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
426 fileName := t.GetField(FieldFileName).Data
427 filePath := t.GetField(FieldFilePath).Data
429 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
434 fi, err := cc.Server.FS.Stat(fullFilePath)
439 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
443 if t.GetField(FieldFileComment).Data != nil {
444 switch mode := fi.Mode(); {
446 if !cc.Authorize(accessSetFolderComment) {
447 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for folders."))
450 case mode.IsRegular():
451 if !cc.Authorize(accessSetFileComment) {
452 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for files."))
457 if err := hlFile.ffo.FlatFileInformationFork.setComment(t.GetField(FieldFileComment).Data); err != nil {
460 w, err := hlFile.infoForkWriter()
464 _, err = io.Copy(w, &hlFile.ffo.FlatFileInformationFork)
470 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, t.GetField(FieldFileNewName).Data)
475 fileNewName := t.GetField(FieldFileNewName).Data
477 if fileNewName != nil {
478 switch mode := fi.Mode(); {
480 if !cc.Authorize(accessRenameFolder) {
481 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
484 err = os.Rename(fullFilePath, fullNewFilePath)
485 if os.IsNotExist(err) {
486 res = append(res, cc.NewErrReply(t, "Cannot rename folder "+string(fileName)+" because it does not exist or cannot be found."))
489 case mode.IsRegular():
490 if !cc.Authorize(accessRenameFile) {
491 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
494 fileDir, err := readPath(cc.Server.Config.FileRoot, filePath, []byte{})
498 hlFile.name, err = txtDecoder.String(string(fileNewName))
500 return res, fmt.Errorf("invalid filepath encoding: %w", err)
503 err = hlFile.move(fileDir)
504 if os.IsNotExist(err) {
505 res = append(res, cc.NewErrReply(t, "Cannot rename file "+string(fileName)+" because it does not exist or cannot be found."))
514 res = append(res, cc.NewReply(t))
518 // HandleDeleteFile deletes a file or folder
519 // Fields used in the request:
522 // Fields used in the reply: none
523 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
524 fileName := t.GetField(FieldFileName).Data
525 filePath := t.GetField(FieldFilePath).Data
527 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
532 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
537 fi, err := hlFile.dataFile()
539 res = append(res, cc.NewErrReply(t, "Cannot delete file "+string(fileName)+" because it does not exist or cannot be found."))
543 switch mode := fi.Mode(); {
545 if !cc.Authorize(accessDeleteFolder) {
546 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
549 case mode.IsRegular():
550 if !cc.Authorize(accessDeleteFile) {
551 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
556 if err := hlFile.delete(); err != nil {
560 res = append(res, cc.NewReply(t))
564 // HandleMoveFile moves files or folders. Note: seemingly not documented
565 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
566 fileName := string(t.GetField(FieldFileName).Data)
568 filePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(FieldFilePath).Data, t.GetField(FieldFileName).Data)
573 fileNewPath, err := readPath(cc.Server.Config.FileRoot, t.GetField(FieldFileNewPath).Data, nil)
578 cc.logger.Info("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
580 hlFile, err := newFileWrapper(cc.Server.FS, filePath, 0)
585 fi, err := hlFile.dataFile()
587 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
590 switch mode := fi.Mode(); {
592 if !cc.Authorize(accessMoveFolder) {
593 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
596 case mode.IsRegular():
597 if !cc.Authorize(accessMoveFile) {
598 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
602 if err := hlFile.move(fileNewPath); err != nil {
605 // TODO: handle other possible errors; e.g. fileWrapper delete fails due to fileWrapper permission issue
607 res = append(res, cc.NewReply(t))
611 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
612 if !cc.Authorize(accessCreateFolder) {
613 res = append(res, cc.NewErrReply(t, "You are not allowed to create folders."))
616 folderName := string(t.GetField(FieldFileName).Data)
618 folderName = path.Join("/", folderName)
622 // FieldFilePath is only present for nested paths
623 if t.GetField(FieldFilePath).Data != nil {
625 _, err := newFp.Write(t.GetField(FieldFilePath).Data)
630 for _, pathItem := range newFp.Items {
631 subPath = filepath.Join("/", subPath, string(pathItem.Name))
634 newFolderPath := path.Join(cc.Server.Config.FileRoot, subPath, folderName)
635 newFolderPath, err = txtDecoder.String(newFolderPath)
637 return res, fmt.Errorf("invalid filepath encoding: %w", err)
640 // TODO: check path and folder Name lengths
642 if _, err := cc.Server.FS.Stat(newFolderPath); !os.IsNotExist(err) {
643 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that Name.", folderName)
644 return []Transaction{cc.NewErrReply(t, msg)}, nil
647 if err := cc.Server.FS.Mkdir(newFolderPath, 0777); err != nil {
648 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
649 return []Transaction{cc.NewErrReply(t, msg)}, nil
652 res = append(res, cc.NewReply(t))
656 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
657 if !cc.Authorize(accessModifyUser) {
658 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
662 login := string(encodeString(t.GetField(FieldUserLogin).Data))
663 userName := string(t.GetField(FieldUserName).Data)
665 newAccessLvl := t.GetField(FieldUserAccess).Data
667 account := cc.Server.Accounts[login]
669 return append(res, cc.NewErrReply(t, "Account not found.")), nil
671 account.Name = userName
672 copy(account.Access[:], newAccessLvl)
674 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
675 // not include FieldUserPassword
676 if t.GetField(FieldUserPassword).Data == nil {
677 account.Password = hashAndSalt([]byte(""))
680 if !bytes.Equal([]byte{0}, t.GetField(FieldUserPassword).Data) {
681 account.Password = hashAndSalt(t.GetField(FieldUserPassword).Data)
684 out, err := yaml.Marshal(&account)
688 if err := os.WriteFile(filepath.Join(cc.Server.ConfigDir, "Users", login+".yaml"), out, 0666); err != nil {
692 // Notify connected clients logged in as the user of the new access level
693 for _, c := range cc.Server.Clients {
694 if c.Account.Login == login {
695 // Note: comment out these two lines to test server-side deny messages
696 newT := NewTransaction(TranUserAccess, c.ID, NewField(FieldUserAccess, newAccessLvl))
697 res = append(res, *newT)
699 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
700 if c.Authorize(accessDisconUser) {
701 flagBitmap.SetBit(flagBitmap, UserFlagAdmin, 1)
703 flagBitmap.SetBit(flagBitmap, UserFlagAdmin, 0)
705 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
707 c.Account.Access = account.Access
710 TranNotifyChangeUser,
711 NewField(FieldUserID, *c.ID),
712 NewField(FieldUserFlags, c.Flags),
713 NewField(FieldUserName, c.UserName),
714 NewField(FieldUserIconID, c.Icon),
719 res = append(res, cc.NewReply(t))
723 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
724 if !cc.Authorize(accessOpenUser) {
725 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
729 account := cc.Server.Accounts[string(t.GetField(FieldUserLogin).Data)]
731 res = append(res, cc.NewErrReply(t, "Account does not exist."))
735 res = append(res, cc.NewReply(t,
736 NewField(FieldUserName, []byte(account.Name)),
737 NewField(FieldUserLogin, encodeString(t.GetField(FieldUserLogin).Data)),
738 NewField(FieldUserPassword, []byte(account.Password)),
739 NewField(FieldUserAccess, account.Access[:]),
744 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
745 if !cc.Authorize(accessOpenUser) {
746 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
750 var userFields []Field
751 for _, acc := range cc.Server.Accounts {
753 b, err := io.ReadAll(&accCopy)
758 userFields = append(userFields, NewField(FieldData, b))
761 res = append(res, cc.NewReply(t, userFields...))
765 // HandleUpdateUser is used by the v1.5+ multi-user editor to perform account editing for multiple users at a time.
766 // An update can be a mix of these actions:
769 // * Modify user (including renaming the account login)
771 // The Transaction sent by the client includes one data field per user that was modified. This data field in turn
772 // contains another data field encoded in its payload with a varying number of sub fields depending on which action is
773 // performed. This seems to be the only place in the Hotline protocol where a data field contains another data field.
774 func HandleUpdateUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
775 for _, field := range t.Fields {
777 var subFields []Field
779 // Create a new scanner for parsing incoming bytes into transaction tokens
780 scanner := bufio.NewScanner(bytes.NewReader(field.Data[2:]))
781 scanner.Split(fieldScanner)
783 for i := 0; i < int(binary.BigEndian.Uint16(field.Data[0:2])); i++ {
787 if _, err := field.Write(scanner.Bytes()); err != nil {
788 return res, fmt.Errorf("error reading field: %w", err)
790 subFields = append(subFields, field)
793 // If there's only one subfield, that indicates this is a delete operation for the login in FieldData
794 if len(subFields) == 1 {
795 if !cc.Authorize(accessDeleteUser) {
796 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
800 login := string(encodeString(getField(FieldData, &subFields).Data))
801 cc.logger.Info("DeleteUser", "login", login)
803 if err := cc.Server.DeleteUser(login); err != nil {
809 // login of the account to update
810 var accountToUpdate, loginToRename string
812 // If FieldData is included, this is a rename operation where FieldData contains the login of the existing
813 // account and FieldUserLogin contains the new login.
814 if getField(FieldData, &subFields) != nil {
815 loginToRename = string(encodeString(getField(FieldData, &subFields).Data))
817 userLogin := string(encodeString(getField(FieldUserLogin, &subFields).Data))
818 if loginToRename != "" {
819 accountToUpdate = loginToRename
821 accountToUpdate = userLogin
824 // Check if accountToUpdate has an existing account. If so, we know we are updating an existing user.
825 if acc, ok := cc.Server.Accounts[accountToUpdate]; ok {
826 if loginToRename != "" {
827 cc.logger.Info("RenameUser", "prevLogin", accountToUpdate, "newLogin", userLogin)
829 cc.logger.Info("UpdateUser", "login", accountToUpdate)
832 // account exists, so this is an update action
833 if !cc.Authorize(accessModifyUser) {
834 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
838 // This part is a bit tricky. There are three possibilities:
839 // 1) The transaction is intended to update the password.
840 // In this case, FieldUserPassword is sent with the new password.
841 // 2) The transaction is intended to remove the password.
842 // In this case, FieldUserPassword is not sent.
843 // 3) The transaction updates the users access bits, but not the password.
844 // In this case, FieldUserPassword is sent with zero as the only byte.
845 if getField(FieldUserPassword, &subFields) != nil {
846 newPass := getField(FieldUserPassword, &subFields).Data
847 if !bytes.Equal([]byte{0}, newPass) {
848 acc.Password = hashAndSalt(newPass)
851 acc.Password = hashAndSalt([]byte(""))
854 if getField(FieldUserAccess, &subFields) != nil {
855 copy(acc.Access[:], getField(FieldUserAccess, &subFields).Data)
858 err = cc.Server.UpdateUser(
859 string(encodeString(getField(FieldData, &subFields).Data)),
860 string(encodeString(getField(FieldUserLogin, &subFields).Data)),
861 string(getField(FieldUserName, &subFields).Data),
869 if !cc.Authorize(accessCreateUser) {
870 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
874 cc.logger.Info("CreateUser", "login", userLogin)
876 newAccess := accessBitmap{}
877 copy(newAccess[:], getField(FieldUserAccess, &subFields).Data)
879 // Prevent account from creating new account with greater permission
880 for i := 0; i < 64; i++ {
881 if newAccess.IsSet(i) {
882 if !cc.Authorize(i) {
883 return append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself.")), nil
888 err = cc.Server.NewUser(userLogin, string(getField(FieldUserName, &subFields).Data), string(getField(FieldUserPassword, &subFields).Data), newAccess)
890 return append(res, cc.NewErrReply(t, "Cannot create account because there is already an account with that login.")), nil
895 res = append(res, cc.NewReply(t))
899 // HandleNewUser creates a new user account
900 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
901 if !cc.Authorize(accessCreateUser) {
902 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
906 login := string(encodeString(t.GetField(FieldUserLogin).Data))
908 // If the account already dataFile, reply with an error
909 if _, ok := cc.Server.Accounts[login]; ok {
910 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
914 newAccess := accessBitmap{}
915 copy(newAccess[:], t.GetField(FieldUserAccess).Data)
917 // Prevent account from creating new account with greater permission
918 for i := 0; i < 64; i++ {
919 if newAccess.IsSet(i) {
920 if !cc.Authorize(i) {
921 res = append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself."))
927 if err := cc.Server.NewUser(login, string(t.GetField(FieldUserName).Data), string(t.GetField(FieldUserPassword).Data), newAccess); err != nil {
928 res = append(res, cc.NewErrReply(t, "Cannot create account because there is already an account with that login."))
932 res = append(res, cc.NewReply(t))
936 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
937 if !cc.Authorize(accessDeleteUser) {
938 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
942 login := string(encodeString(t.GetField(FieldUserLogin).Data))
944 if err := cc.Server.DeleteUser(login); err != nil {
948 res = append(res, cc.NewReply(t))
952 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
953 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
954 if !cc.Authorize(accessBroadcast) {
955 res = append(res, cc.NewErrReply(t, "You are not allowed to send broadcast messages."))
961 NewField(FieldData, t.GetField(TranGetMsgs).Data),
962 NewField(FieldChatOptions, []byte{0}),
965 res = append(res, cc.NewReply(t))
969 // HandleGetClientInfoText returns user information for the specific user.
971 // Fields used in the request:
974 // Fields used in the reply:
976 // 101 Data User info text string
977 func HandleGetClientInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
978 if !cc.Authorize(accessGetClientInfo) {
979 res = append(res, cc.NewErrReply(t, "You are not allowed to get client info."))
983 clientID, _ := byteToInt(t.GetField(FieldUserID).Data)
985 clientConn := cc.Server.Clients[uint16(clientID)]
986 if clientConn == nil {
987 return append(res, cc.NewErrReply(t, "User not found.")), err
990 res = append(res, cc.NewReply(t,
991 NewField(FieldData, []byte(clientConn.String())),
992 NewField(FieldUserName, clientConn.UserName),
997 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
998 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
1003 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1004 if t.GetField(FieldUserName).Data != nil {
1005 if cc.Authorize(accessAnyName) {
1006 cc.UserName = t.GetField(FieldUserName).Data
1008 cc.UserName = []byte(cc.Account.Name)
1012 cc.Icon = t.GetField(FieldUserIconID).Data
1014 cc.logger = cc.logger.With("Name", string(cc.UserName))
1015 cc.logger.Info("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(cc.Version); return i }()))
1017 options := t.GetField(FieldOptions).Data
1018 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1020 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
1022 // Check refuse private PM option
1023 if optBitmap.Bit(UserOptRefusePM) == 1 {
1024 flagBitmap.SetBit(flagBitmap, UserFlagRefusePM, 1)
1025 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1028 // Check refuse private chat option
1029 if optBitmap.Bit(UserOptRefuseChat) == 1 {
1030 flagBitmap.SetBit(flagBitmap, UserFlagRefusePChat, 1)
1031 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1034 // Check auto response
1035 if optBitmap.Bit(UserOptAutoResponse) == 1 {
1036 cc.AutoReply = t.GetField(FieldAutomaticResponse).Data
1038 cc.AutoReply = []byte{}
1041 trans := cc.notifyOthers(
1043 TranNotifyChangeUser, nil,
1044 NewField(FieldUserName, cc.UserName),
1045 NewField(FieldUserID, *cc.ID),
1046 NewField(FieldUserIconID, cc.Icon),
1047 NewField(FieldUserFlags, cc.Flags),
1050 res = append(res, trans...)
1052 if cc.Server.Config.BannerFile != "" {
1053 res = append(res, *NewTransaction(TranServerBanner, cc.ID, NewField(FieldBannerType, []byte("JPEG"))))
1056 res = append(res, cc.NewReply(t))
1061 // HandleTranOldPostNews updates the flat news
1062 // Fields used in this request:
1064 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1065 if !cc.Authorize(accessNewsPostArt) {
1066 res = append(res, cc.NewErrReply(t, "You are not allowed to post news."))
1070 cc.Server.flatNewsMux.Lock()
1071 defer cc.Server.flatNewsMux.Unlock()
1073 newsDateTemplate := defaultNewsDateFormat
1074 if cc.Server.Config.NewsDateFormat != "" {
1075 newsDateTemplate = cc.Server.Config.NewsDateFormat
1078 newsTemplate := defaultNewsTemplate
1079 if cc.Server.Config.NewsDelimiter != "" {
1080 newsTemplate = cc.Server.Config.NewsDelimiter
1083 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(FieldData).Data)
1084 newsPost = strings.ReplaceAll(newsPost, "\n", "\r")
1086 // update news in memory
1087 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
1089 // update news on disk
1090 if err := cc.Server.FS.WriteFile(filepath.Join(cc.Server.ConfigDir, "MessageBoard.txt"), cc.Server.FlatNews, 0644); err != nil {
1094 // Notify all clients of updated news
1097 NewField(FieldData, []byte(newsPost)),
1100 res = append(res, cc.NewReply(t))
1104 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1105 if !cc.Authorize(accessDisconUser) {
1106 res = append(res, cc.NewErrReply(t, "You are not allowed to disconnect users."))
1110 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(FieldUserID).Data)]
1112 if clientConn.Authorize(accessCannotBeDiscon) {
1113 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
1117 // If FieldOptions is set, then the client IP is banned in addition to disconnected.
1118 // 00 01 = temporary ban
1119 // 00 02 = permanent ban
1120 if t.GetField(FieldOptions).Data != nil {
1121 switch t.GetField(FieldOptions).Data[1] {
1123 // send message: "You are temporarily banned on this server"
1124 cc.logger.Info("Disconnect & temporarily ban " + string(clientConn.UserName))
1126 res = append(res, *NewTransaction(
1129 NewField(FieldData, []byte("You are temporarily banned on this server")),
1130 NewField(FieldChatOptions, []byte{0, 0}),
1133 banUntil := time.Now().Add(tempBanDuration)
1134 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = &banUntil
1136 // send message: "You are permanently banned on this server"
1137 cc.logger.Info("Disconnect & ban " + string(clientConn.UserName))
1139 res = append(res, *NewTransaction(
1142 NewField(FieldData, []byte("You are permanently banned on this server")),
1143 NewField(FieldChatOptions, []byte{0, 0}),
1146 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = nil
1149 err := cc.Server.writeBanList()
1155 // TODO: remove this awful hack
1157 time.Sleep(1 * time.Second)
1158 clientConn.Disconnect()
1161 return append(res, cc.NewReply(t)), err
1164 // HandleGetNewsCatNameList returns a list of news categories for a path
1165 // Fields used in the request:
1166 // 325 News path (Optional)
1167 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1168 if !cc.Authorize(accessNewsReadArt) {
1169 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1173 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1174 cats := cc.Server.GetNewsCatByPath(pathStrs)
1176 // To store the keys in slice in sorted order
1177 keys := make([]string, len(cats))
1179 for k := range cats {
1185 var fieldData []Field
1186 for _, k := range keys {
1188 b, _ := cat.MarshalBinary()
1189 fieldData = append(fieldData, NewField(
1190 FieldNewsCatListData15,
1195 res = append(res, cc.NewReply(t, fieldData...))
1199 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1200 if !cc.Authorize(accessNewsCreateCat) {
1201 res = append(res, cc.NewErrReply(t, "You are not allowed to create news categories."))
1205 name := string(t.GetField(FieldNewsCatName).Data)
1206 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1208 cats := cc.Server.GetNewsCatByPath(pathStrs)
1209 cats[name] = NewsCategoryListData15{
1211 Type: [2]byte{0, 3},
1212 Articles: map[uint32]*NewsArtData{},
1213 SubCats: make(map[string]NewsCategoryListData15),
1216 if err := cc.Server.writeThreadedNews(); err != nil {
1219 res = append(res, cc.NewReply(t))
1223 // Fields used in the request:
1224 // 322 News category Name
1226 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1227 if !cc.Authorize(accessNewsCreateFldr) {
1228 res = append(res, cc.NewErrReply(t, "You are not allowed to create news folders."))
1232 name := string(t.GetField(FieldFileName).Data)
1233 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1235 cats := cc.Server.GetNewsCatByPath(pathStrs)
1236 cats[name] = NewsCategoryListData15{
1238 Type: [2]byte{0, 2},
1239 Articles: map[uint32]*NewsArtData{},
1240 SubCats: make(map[string]NewsCategoryListData15),
1242 if err := cc.Server.writeThreadedNews(); err != nil {
1245 res = append(res, cc.NewReply(t))
1249 // HandleGetNewsArtData gets the list of article names at the specified news path.
1251 // Fields used in the request:
1252 // 325 News path Optional
1254 // Fields used in the reply:
1255 // 321 News article list data Optional
1256 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1257 if !cc.Authorize(accessNewsReadArt) {
1258 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1262 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1264 var cat NewsCategoryListData15
1265 cats := cc.Server.ThreadedNews.Categories
1267 for _, fp := range pathStrs {
1269 cats = cats[fp].SubCats
1272 nald := cat.GetNewsArtListData()
1274 b, err := io.ReadAll(&nald)
1276 return res, fmt.Errorf("error loading news articles: %w", err)
1279 res = append(res, cc.NewReply(t, NewField(FieldNewsArtListData, b)))
1283 // HandleGetNewsArtData requests information about the specific news article.
1284 // Fields used in the request:
1288 // 326 News article ID
1289 // 327 News article data flavor
1291 // Fields used in the reply:
1292 // 328 News article title
1293 // 329 News article poster
1294 // 330 News article date
1295 // 331 Previous article ID
1296 // 332 Next article ID
1297 // 335 Parent article ID
1298 // 336 First child article ID
1299 // 327 News article data flavor "Should be “text/plain”
1300 // 333 News article data Optional (if data flavor is “text/plain”)
1301 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1302 if !cc.Authorize(accessNewsReadArt) {
1303 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1307 var cat NewsCategoryListData15
1308 cats := cc.Server.ThreadedNews.Categories
1310 for _, fp := range ReadNewsPath(t.GetField(FieldNewsPath).Data) {
1312 cats = cats[fp].SubCats
1315 // The official Hotline clients will send the article ID as 2 bytes if possible, but
1316 // some third party clients such as Frogblast and Heildrun will always send 4 bytes
1317 convertedID, err := byteToInt(t.GetField(FieldNewsArtID).Data)
1322 art := cat.Articles[uint32(convertedID)]
1324 res = append(res, cc.NewReply(t))
1328 res = append(res, cc.NewReply(t,
1329 NewField(FieldNewsArtTitle, []byte(art.Title)),
1330 NewField(FieldNewsArtPoster, []byte(art.Poster)),
1331 NewField(FieldNewsArtDate, art.Date[:]),
1332 NewField(FieldNewsArtPrevArt, art.PrevArt[:]),
1333 NewField(FieldNewsArtNextArt, art.NextArt[:]),
1334 NewField(FieldNewsArtParentArt, art.ParentArt[:]),
1335 NewField(FieldNewsArt1stChildArt, art.FirstChildArt[:]),
1336 NewField(FieldNewsArtDataFlav, []byte("text/plain")),
1337 NewField(FieldNewsArtData, []byte(art.Data)),
1342 // HandleDelNewsItem deletes an existing threaded news folder or category from the server.
1343 // Fields used in the request:
1345 // Fields used in the reply:
1347 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1348 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1350 cats := cc.Server.ThreadedNews.Categories
1351 delName := pathStrs[len(pathStrs)-1]
1352 if len(pathStrs) > 1 {
1353 for _, fp := range pathStrs[0 : len(pathStrs)-1] {
1354 cats = cats[fp].SubCats
1358 if cats[delName].Type == [2]byte{0, 3} {
1359 if !cc.Authorize(accessNewsDeleteCat) {
1360 return append(res, cc.NewErrReply(t, "You are not allowed to delete news categories.")), nil
1363 if !cc.Authorize(accessNewsDeleteFldr) {
1364 return append(res, cc.NewErrReply(t, "You are not allowed to delete news folders.")), nil
1368 delete(cats, delName)
1370 if err := cc.Server.writeThreadedNews(); err != nil {
1374 return append(res, cc.NewReply(t)), nil
1377 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1378 if !cc.Authorize(accessNewsDeleteArt) {
1379 res = append(res, cc.NewErrReply(t, "You are not allowed to delete news articles."))
1385 // 326 News article ID
1386 // 337 News article – recursive delete Delete child articles (1) or not (0)
1387 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1388 ID, err := byteToInt(t.GetField(FieldNewsArtID).Data)
1393 // TODO: Delete recursive
1394 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1396 catName := pathStrs[len(pathStrs)-1]
1397 cat := cats[catName]
1399 delete(cat.Articles, uint32(ID))
1402 if err := cc.Server.writeThreadedNews(); err != nil {
1406 res = append(res, cc.NewReply(t))
1412 // 326 News article ID ID of the parent article?
1413 // 328 News article title
1414 // 334 News article flags
1415 // 327 News article data flavor Currently “text/plain”
1416 // 333 News article data
1417 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1418 if !cc.Authorize(accessNewsPostArt) {
1419 res = append(res, cc.NewErrReply(t, "You are not allowed to post news articles."))
1423 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1424 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1426 catName := pathStrs[len(pathStrs)-1]
1427 cat := cats[catName]
1429 artID, err := byteToInt(t.GetField(FieldNewsArtID).Data)
1433 convertedArtID := uint32(artID)
1434 bs := make([]byte, 4)
1435 binary.BigEndian.PutUint32(bs, convertedArtID)
1437 cc.Server.mux.Lock()
1438 defer cc.Server.mux.Unlock()
1440 newArt := NewsArtData{
1441 Title: string(t.GetField(FieldNewsArtTitle).Data),
1442 Poster: string(cc.UserName),
1443 Date: toHotlineTime(time.Now()),
1446 ParentArt: [4]byte(bs),
1447 FirstChildArt: [4]byte{},
1448 DataFlav: []byte("text/plain"),
1449 Data: string(t.GetField(FieldNewsArtData).Data),
1453 for k := range cat.Articles {
1454 keys = append(keys, int(k))
1460 prevID := uint32(keys[len(keys)-1])
1463 binary.BigEndian.PutUint32(newArt.PrevArt[:], prevID)
1465 // Set next article ID
1466 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt[:], nextID)
1469 // Update parent article with first child reply
1470 parentID := convertedArtID
1472 parentArt := cat.Articles[parentID]
1474 if parentArt.FirstChildArt == [4]byte{0, 0, 0, 0} {
1475 binary.BigEndian.PutUint32(parentArt.FirstChildArt[:], nextID)
1479 cat.Articles[nextID] = &newArt
1482 if err := cc.Server.writeThreadedNews(); err != nil {
1486 res = append(res, cc.NewReply(t))
1490 // HandleGetMsgs returns the flat news data
1491 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1492 if !cc.Authorize(accessNewsReadArt) {
1493 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1497 res = append(res, cc.NewReply(t, NewField(FieldData, cc.Server.FlatNews)))
1502 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1503 if !cc.Authorize(accessDownloadFile) {
1504 res = append(res, cc.NewErrReply(t, "You are not allowed to download files."))
1508 fileName := t.GetField(FieldFileName).Data
1509 filePath := t.GetField(FieldFilePath).Data
1510 resumeData := t.GetField(FieldFileResumeData).Data
1512 var dataOffset int64
1513 var frd FileResumeData
1514 if resumeData != nil {
1515 if err := frd.UnmarshalBinary(t.GetField(FieldFileResumeData).Data); err != nil {
1518 // TODO: handle rsrc fork offset
1519 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1522 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1527 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, dataOffset)
1532 xferSize := hlFile.ffo.TransferSize(0)
1534 ft := cc.newFileTransfer(FileDownload, fileName, filePath, xferSize)
1536 // TODO: refactor to remove this
1537 if resumeData != nil {
1538 var frd FileResumeData
1539 if err := frd.UnmarshalBinary(t.GetField(FieldFileResumeData).Data); err != nil {
1542 ft.fileResumeData = &frd
1545 // Optional field for when a HL v1.5+ client requests file preview
1546 // Used only for TEXT, JPEG, GIFF, BMP or PICT files
1547 // The value will always be 2
1548 if t.GetField(FieldFileTransferOptions).Data != nil {
1549 ft.options = t.GetField(FieldFileTransferOptions).Data
1550 xferSize = hlFile.ffo.FlatFileDataForkHeader.DataSize[:]
1553 res = append(res, cc.NewReply(t,
1554 NewField(FieldRefNum, ft.refNum[:]),
1555 NewField(FieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1556 NewField(FieldTransferSize, xferSize),
1557 NewField(FieldFileSize, hlFile.ffo.FlatFileDataForkHeader.DataSize[:]),
1563 // Download all files from the specified folder and sub-folders
1564 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1565 if !cc.Authorize(accessDownloadFile) {
1566 res = append(res, cc.NewErrReply(t, "You are not allowed to download folders."))
1570 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(FieldFilePath).Data, t.GetField(FieldFileName).Data)
1575 transferSize, err := CalcTotalSize(fullFilePath)
1579 itemCount, err := CalcItemCount(fullFilePath)
1584 fileTransfer := cc.newFileTransfer(FolderDownload, t.GetField(FieldFileName).Data, t.GetField(FieldFilePath).Data, transferSize)
1587 _, err = fp.Write(t.GetField(FieldFilePath).Data)
1592 res = append(res, cc.NewReply(t,
1593 NewField(FieldRefNum, fileTransfer.ReferenceNumber),
1594 NewField(FieldTransferSize, transferSize),
1595 NewField(FieldFolderItemCount, itemCount),
1596 NewField(FieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1601 // Upload all files from the local folder and its subfolders to the specified path on the server
1602 // Fields used in the request
1605 // 108 transfer size Total size of all items in the folder
1606 // 220 Folder item count
1607 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1608 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1610 if t.GetField(FieldFilePath).Data != nil {
1611 if _, err = fp.Write(t.GetField(FieldFilePath).Data); err != nil {
1616 // Handle special cases for Upload and Drop Box folders
1617 if !cc.Authorize(accessUploadAnywhere) {
1618 if !fp.IsUploadDir() && !fp.IsDropbox() {
1619 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))))
1624 fileTransfer := cc.newFileTransfer(FolderUpload,
1625 t.GetField(FieldFileName).Data,
1626 t.GetField(FieldFilePath).Data,
1627 t.GetField(FieldTransferSize).Data,
1630 fileTransfer.FolderItemCount = t.GetField(FieldFolderItemCount).Data
1632 res = append(res, cc.NewReply(t, NewField(FieldRefNum, fileTransfer.ReferenceNumber)))
1637 // Fields used in the request:
1640 // 204 File transfer options "Optional
1641 // Used only to resume download, currently has value 2"
1642 // 108 File transfer size "Optional used if download is not resumed"
1643 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1644 if !cc.Authorize(accessUploadFile) {
1645 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1649 fileName := t.GetField(FieldFileName).Data
1650 filePath := t.GetField(FieldFilePath).Data
1651 transferOptions := t.GetField(FieldFileTransferOptions).Data
1652 transferSize := t.GetField(FieldTransferSize).Data // not sent for resume
1655 if filePath != nil {
1656 if _, err = fp.Write(filePath); err != nil {
1661 // Handle special cases for Upload and Drop Box folders
1662 if !cc.Authorize(accessUploadAnywhere) {
1663 if !fp.IsUploadDir() && !fp.IsDropbox() {
1664 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))))
1668 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1673 if _, err := cc.Server.FS.Stat(fullFilePath); err == nil {
1674 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))))
1678 ft := cc.newFileTransfer(FileUpload, fileName, filePath, transferSize)
1680 replyT := cc.NewReply(t, NewField(FieldRefNum, ft.ReferenceNumber))
1682 // client has requested to resume a partially transferred file
1683 if transferOptions != nil {
1684 fileInfo, err := cc.Server.FS.Stat(fullFilePath + incompleteFileSuffix)
1689 offset := make([]byte, 4)
1690 binary.BigEndian.PutUint32(offset, uint32(fileInfo.Size()))
1692 fileResumeData := NewFileResumeData([]ForkInfoList{
1693 *NewForkInfoList(offset),
1696 b, _ := fileResumeData.BinaryMarshal()
1698 ft.TransferSize = offset
1700 replyT.Fields = append(replyT.Fields, NewField(FieldFileResumeData, b))
1703 res = append(res, replyT)
1707 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1708 if len(t.GetField(FieldUserIconID).Data) == 4 {
1709 cc.Icon = t.GetField(FieldUserIconID).Data[2:]
1711 cc.Icon = t.GetField(FieldUserIconID).Data
1713 if cc.Authorize(accessAnyName) {
1714 cc.UserName = t.GetField(FieldUserName).Data
1717 // the options field is only passed by the client versions > 1.2.3.
1718 options := t.GetField(FieldOptions).Data
1720 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1721 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
1723 flagBitmap.SetBit(flagBitmap, UserFlagRefusePM, optBitmap.Bit(UserOptRefusePM))
1724 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1726 flagBitmap.SetBit(flagBitmap, UserFlagRefusePChat, optBitmap.Bit(UserOptRefuseChat))
1727 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1729 // Check auto response
1730 if optBitmap.Bit(UserOptAutoResponse) == 1 {
1731 cc.AutoReply = t.GetField(FieldAutomaticResponse).Data
1733 cc.AutoReply = []byte{}
1737 for _, c := range sortedClients(cc.Server.Clients) {
1738 res = append(res, *NewTransaction(
1739 TranNotifyChangeUser,
1741 NewField(FieldUserID, *cc.ID),
1742 NewField(FieldUserIconID, cc.Icon),
1743 NewField(FieldUserFlags, cc.Flags),
1744 NewField(FieldUserName, cc.UserName),
1751 // HandleKeepAlive responds to keepalive transactions with an empty reply
1752 // * HL 1.9.2 Client sends keepalive msg every 3 minutes
1753 // * HL 1.2.3 Client doesn't send keepalives
1754 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1755 res = append(res, cc.NewReply(t))
1760 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1761 fullPath, err := readPath(
1762 cc.Server.Config.FileRoot,
1763 t.GetField(FieldFilePath).Data,
1767 return res, fmt.Errorf("error reading file path: %w", err)
1771 if t.GetField(FieldFilePath).Data != nil {
1772 if _, err = fp.Write(t.GetField(FieldFilePath).Data); err != nil {
1773 return res, fmt.Errorf("error writing file path: %w", err)
1777 // Handle special case for drop box folders
1778 if fp.IsDropbox() && !cc.Authorize(accessViewDropBoxes) {
1779 res = append(res, cc.NewErrReply(t, "You are not allowed to view drop boxes."))
1783 fileNames, err := getFileNameList(fullPath, cc.Server.Config.IgnoreFiles)
1785 return res, fmt.Errorf("getFileNameList: %w", err)
1788 res = append(res, cc.NewReply(t, fileNames...))
1793 // =================================
1794 // Hotline private chat flow
1795 // =================================
1796 // 1. ClientA sends TranInviteNewChat to server with user ID to invite
1797 // 2. Server creates new ChatID
1798 // 3. Server sends TranInviteToChat to invitee
1799 // 4. Server replies to ClientA with new Chat ID
1801 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1802 // If Accepted is clicked:
1803 // 1. ClientB sends TranJoinChat with FieldChatID
1805 // HandleInviteNewChat invites users to new private chat
1806 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1807 if !cc.Authorize(accessOpenChat) {
1808 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1813 targetID := t.GetField(FieldUserID).Data
1814 newChatID := cc.Server.NewPrivateChat(cc)
1816 // Check if target user has "Refuse private chat" flag
1817 binary.BigEndian.Uint16(targetID)
1818 targetClient := cc.Server.Clients[binary.BigEndian.Uint16(targetID)]
1820 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(targetClient.Flags)))
1821 if flagBitmap.Bit(UserFlagRefusePChat) == 1 {
1826 NewField(FieldData, []byte(string(targetClient.UserName)+" does not accept private chats.")),
1827 NewField(FieldUserName, targetClient.UserName),
1828 NewField(FieldUserID, *targetClient.ID),
1829 NewField(FieldOptions, []byte{0, 2}),
1837 NewField(FieldChatID, newChatID),
1838 NewField(FieldUserName, cc.UserName),
1839 NewField(FieldUserID, *cc.ID),
1846 NewField(FieldChatID, newChatID),
1847 NewField(FieldUserName, cc.UserName),
1848 NewField(FieldUserID, *cc.ID),
1849 NewField(FieldUserIconID, cc.Icon),
1850 NewField(FieldUserFlags, cc.Flags),
1857 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1858 if !cc.Authorize(accessOpenChat) {
1859 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1864 targetID := t.GetField(FieldUserID).Data
1865 chatID := t.GetField(FieldChatID).Data
1871 NewField(FieldChatID, chatID),
1872 NewField(FieldUserName, cc.UserName),
1873 NewField(FieldUserID, *cc.ID),
1879 NewField(FieldChatID, chatID),
1880 NewField(FieldUserName, cc.UserName),
1881 NewField(FieldUserID, *cc.ID),
1882 NewField(FieldUserIconID, cc.Icon),
1883 NewField(FieldUserFlags, cc.Flags),
1890 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1891 chatID := t.GetField(FieldChatID).Data
1892 chatInt := binary.BigEndian.Uint32(chatID)
1894 privChat := cc.Server.PrivateChats[chatInt]
1896 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1898 for _, c := range sortedClients(privChat.ClientConn) {
1903 NewField(FieldChatID, chatID),
1904 NewField(FieldData, resMsg),
1912 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1913 // Fields used in the reply:
1914 // * 115 Chat subject
1915 // * 300 User Name with info (Optional)
1916 // * 300 (more user names with info)
1917 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1918 chatID := t.GetField(FieldChatID).Data
1919 chatInt := binary.BigEndian.Uint32(chatID)
1921 privChat := cc.Server.PrivateChats[chatInt]
1923 // Send TranNotifyChatChangeUser to current members of the chat to inform of new user
1924 for _, c := range sortedClients(privChat.ClientConn) {
1927 TranNotifyChatChangeUser,
1929 NewField(FieldChatID, chatID),
1930 NewField(FieldUserName, cc.UserName),
1931 NewField(FieldUserID, *cc.ID),
1932 NewField(FieldUserIconID, cc.Icon),
1933 NewField(FieldUserFlags, cc.Flags),
1938 privChat.ClientConn[cc.uint16ID()] = cc
1940 replyFields := []Field{NewField(FieldChatSubject, []byte(privChat.Subject))}
1941 for _, c := range sortedClients(privChat.ClientConn) {
1943 b, err := io.ReadAll(&User{
1947 Name: string(c.UserName),
1952 replyFields = append(replyFields, NewField(FieldUsernameWithInfo, b))
1955 res = append(res, cc.NewReply(t, replyFields...))
1959 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1960 // Fields used in the request:
1961 // - 114 FieldChatID
1963 // Reply is not expected.
1964 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1965 chatID := t.GetField(FieldChatID).Data
1966 chatInt := binary.BigEndian.Uint32(chatID)
1968 privChat, ok := cc.Server.PrivateChats[chatInt]
1973 delete(privChat.ClientConn, cc.uint16ID())
1975 // Notify members of the private chat that the user has left
1976 for _, c := range sortedClients(privChat.ClientConn) {
1979 TranNotifyChatDeleteUser,
1981 NewField(FieldChatID, chatID),
1982 NewField(FieldUserID, *cc.ID),
1990 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1991 // Fields used in the request:
1993 // * 115 Chat subject
1994 // Reply is not expected.
1995 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1996 chatID := t.GetField(FieldChatID).Data
1997 chatInt := binary.BigEndian.Uint32(chatID)
1999 privChat := cc.Server.PrivateChats[chatInt]
2000 privChat.Subject = string(t.GetField(FieldChatSubject).Data)
2002 for _, c := range sortedClients(privChat.ClientConn) {
2005 TranNotifyChatSubject,
2007 NewField(FieldChatID, chatID),
2008 NewField(FieldChatSubject, t.GetField(FieldChatSubject).Data),
2016 // HandleMakeAlias makes a file alias using the specified path.
2017 // Fields used in the request:
2020 // 212 File new path Destination path
2022 // Fields used in the reply:
2024 func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
2025 if !cc.Authorize(accessMakeAlias) {
2026 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
2029 fileName := t.GetField(FieldFileName).Data
2030 filePath := t.GetField(FieldFilePath).Data
2031 fileNewPath := t.GetField(FieldFileNewPath).Data
2033 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
2038 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
2043 cc.logger.Debug("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
2045 if err := cc.Server.FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
2046 res = append(res, cc.NewErrReply(t, "Error creating alias"))
2050 res = append(res, cc.NewReply(t))
2054 // HandleDownloadBanner handles requests for a new banner from the server
2055 // Fields used in the request:
2057 // Fields used in the reply:
2058 // 107 FieldRefNum Used later for transfer
2059 // 108 FieldTransferSize Size of data to be downloaded
2060 func HandleDownloadBanner(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
2061 ft := cc.newFileTransfer(bannerDownload, []byte{}, []byte{}, make([]byte, 4))
2062 binary.BigEndian.PutUint32(ft.TransferSize, uint32(len(cc.Server.banner)))
2064 return append(res, cc.NewReply(t,
2065 NewField(FieldRefNum, ft.refNum[:]),
2066 NewField(FieldTransferSize, ft.TransferSize),