18 type HandlerFunc func(*ClientConn, *Transaction) ([]Transaction, error)
20 type TransactionType struct {
21 Handler HandlerFunc // function for handling the transaction type
22 Name string // Name of transaction as it will appear in logging
23 RequiredFields []requiredField
26 var TransactionHandlers = map[uint16]TransactionType{
32 TranNotifyChangeUser: {
33 Name: "TranNotifyChangeUser",
39 Name: "TranShowAgreement",
42 Name: "TranUserAccess",
44 TranNotifyDeleteUser: {
45 Name: "TranNotifyDeleteUser",
49 Handler: HandleTranAgreed,
53 Handler: HandleChatSend,
54 RequiredFields: []requiredField{
62 Name: "TranDelNewsArt",
63 Handler: HandleDelNewsArt,
66 Name: "TranDelNewsItem",
67 Handler: HandleDelNewsItem,
70 Name: "TranDeleteFile",
71 Handler: HandleDeleteFile,
74 Name: "TranDeleteUser",
75 Handler: HandleDeleteUser,
78 Name: "TranDisconnectUser",
79 Handler: HandleDisconnectUser,
82 Name: "TranDownloadFile",
83 Handler: HandleDownloadFile,
86 Name: "TranDownloadFldr",
87 Handler: HandleDownloadFolder,
89 TranGetClientInfoText: {
90 Name: "TranGetClientInfoText",
91 Handler: HandleGetClientInfoText,
94 Name: "TranGetFileInfo",
95 Handler: HandleGetFileInfo,
97 TranGetFileNameList: {
98 Name: "TranGetFileNameList",
99 Handler: HandleGetFileNameList,
103 Handler: HandleGetMsgs,
105 TranGetNewsArtData: {
106 Name: "TranGetNewsArtData",
107 Handler: HandleGetNewsArtData,
109 TranGetNewsArtNameList: {
110 Name: "TranGetNewsArtNameList",
111 Handler: HandleGetNewsArtNameList,
113 TranGetNewsCatNameList: {
114 Name: "TranGetNewsCatNameList",
115 Handler: HandleGetNewsCatNameList,
119 Handler: HandleGetUser,
121 TranGetUserNameList: {
122 Name: "tranHandleGetUserNameList",
123 Handler: HandleGetUserNameList,
126 Name: "TranInviteNewChat",
127 Handler: HandleInviteNewChat,
130 Name: "TranInviteToChat",
131 Handler: HandleInviteToChat,
134 Name: "TranJoinChat",
135 Handler: HandleJoinChat,
138 Name: "TranKeepAlive",
139 Handler: HandleKeepAlive,
142 Name: "TranJoinChat",
143 Handler: HandleLeaveChat,
146 Name: "TranListUsers",
147 Handler: HandleListUsers,
150 Name: "TranMoveFile",
151 Handler: HandleMoveFile,
154 Name: "TranNewFolder",
155 Handler: HandleNewFolder,
158 Name: "TranNewNewsCat",
159 Handler: HandleNewNewsCat,
162 Name: "TranNewNewsFldr",
163 Handler: HandleNewNewsFldr,
167 Handler: HandleNewUser,
170 Name: "TranUpdateUser",
171 Handler: HandleUpdateUser,
174 Name: "TranOldPostNews",
175 Handler: HandleTranOldPostNews,
178 Name: "TranPostNewsArt",
179 Handler: HandlePostNewsArt,
181 TranRejectChatInvite: {
182 Name: "TranRejectChatInvite",
183 Handler: HandleRejectChatInvite,
185 TranSendInstantMsg: {
186 Name: "TranSendInstantMsg",
187 Handler: HandleSendInstantMsg,
188 RequiredFields: []requiredField{
198 TranSetChatSubject: {
199 Name: "TranSetChatSubject",
200 Handler: HandleSetChatSubject,
203 Name: "TranMakeFileAlias",
204 Handler: HandleMakeAlias,
205 RequiredFields: []requiredField{
206 {ID: FieldFileName, minLen: 1},
207 {ID: FieldFilePath, minLen: 1},
208 {ID: FieldFileNewPath, minLen: 1},
211 TranSetClientUserInfo: {
212 Name: "TranSetClientUserInfo",
213 Handler: HandleSetClientUserInfo,
216 Name: "TranSetFileInfo",
217 Handler: HandleSetFileInfo,
221 Handler: HandleSetUser,
224 Name: "TranUploadFile",
225 Handler: HandleUploadFile,
228 Name: "TranUploadFldr",
229 Handler: HandleUploadFolder,
232 Name: "TranUserBroadcast",
233 Handler: HandleUserBroadcast,
235 TranDownloadBanner: {
236 Name: "TranDownloadBanner",
237 Handler: HandleDownloadBanner,
241 func HandleChatSend(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
242 if !cc.Authorize(accessSendChat) {
243 res = append(res, cc.NewErrReply(t, "You are not allowed to participate in chat."))
247 // Truncate long usernames
248 trunc := fmt.Sprintf("%13s", cc.UserName)
249 formattedMsg := fmt.Sprintf("\r%.14s: %s", trunc, t.GetField(FieldData).Data)
251 // By holding the option key, Hotline chat allows users to send /me formatted messages like:
252 // *** Halcyon does stuff
253 // This is indicated by the presence of the optional field FieldChatOptions set to a value of 1.
254 // Most clients do not send this option for normal chat messages.
255 if t.GetField(FieldChatOptions).Data != nil && bytes.Equal(t.GetField(FieldChatOptions).Data, []byte{0, 1}) {
256 formattedMsg = fmt.Sprintf("\r*** %s %s", cc.UserName, t.GetField(FieldData).Data)
259 // The ChatID field is used to identify messages as belonging to a private chat.
260 // All clients *except* Frogblast omit this field for public chat, but Frogblast sends a value of 00 00 00 00.
261 chatID := t.GetField(FieldChatID).Data
262 if chatID != nil && !bytes.Equal([]byte{0, 0, 0, 0}, chatID) {
263 chatInt := binary.BigEndian.Uint32(chatID)
264 privChat := cc.Server.PrivateChats[chatInt]
266 clients := sortedClients(privChat.ClientConn)
268 // send the message to all connected clients of the private chat
269 for _, c := range clients {
270 res = append(res, *NewTransaction(
273 NewField(FieldChatID, chatID),
274 NewField(FieldData, []byte(formattedMsg)),
280 for _, c := range sortedClients(cc.Server.Clients) {
281 // Filter out clients that do not have the read chat permission
282 if c.Authorize(accessReadChat) {
283 res = append(res, *NewTransaction(TranChatMsg, c.ID, NewField(FieldData, []byte(formattedMsg))))
290 // HandleSendInstantMsg sends instant message to the user on the current server.
291 // Fields used in the request:
295 // One of the following values:
296 // - User message (myOpt_UserMessage = 1)
297 // - Refuse message (myOpt_RefuseMessage = 2)
298 // - Refuse chat (myOpt_RefuseChat = 3)
299 // - Automatic response (myOpt_AutomaticResponse = 4)"
301 // 214 Quoting message Optional
303 // Fields used in the reply:
305 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
306 if !cc.Authorize(accessSendPrivMsg) {
307 res = append(res, cc.NewErrReply(t, "You are not allowed to send private messages."))
308 return res, errors.New("user is not allowed to send private messages")
311 msg := t.GetField(FieldData)
312 ID := t.GetField(FieldUserID)
314 reply := NewTransaction(
317 NewField(FieldData, msg.Data),
318 NewField(FieldUserName, cc.UserName),
319 NewField(FieldUserID, *cc.ID),
320 NewField(FieldOptions, []byte{0, 1}),
323 // Later versions of Hotline include the original message in the FieldQuotingMsg field so
324 // the receiving client can display both the received message and what it is in reply to
325 if t.GetField(FieldQuotingMsg).Data != nil {
326 reply.Fields = append(reply.Fields, NewField(FieldQuotingMsg, t.GetField(FieldQuotingMsg).Data))
329 id, err := byteToInt(ID.Data)
331 return res, errors.New("invalid client ID")
333 otherClient, ok := cc.Server.Clients[uint16(id)]
335 return res, errors.New("invalid client ID")
338 // Check if target user has "Refuse private messages" flag
339 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(otherClient.Flags)))
340 if flagBitmap.Bit(UserFlagRefusePM) == 1 {
345 NewField(FieldData, []byte(string(otherClient.UserName)+" does not accept private messages.")),
346 NewField(FieldUserName, otherClient.UserName),
347 NewField(FieldUserID, *otherClient.ID),
348 NewField(FieldOptions, []byte{0, 2}),
352 res = append(res, *reply)
355 // Respond with auto reply if other client has it enabled
356 if len(otherClient.AutoReply) > 0 {
361 NewField(FieldData, otherClient.AutoReply),
362 NewField(FieldUserName, otherClient.UserName),
363 NewField(FieldUserID, *otherClient.ID),
364 NewField(FieldOptions, []byte{0, 1}),
369 res = append(res, cc.NewReply(t))
374 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
375 fileName := t.GetField(FieldFileName).Data
376 filePath := t.GetField(FieldFilePath).Data
378 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
383 fw, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
388 encodedName, err := txtEncoder.String(fw.name)
390 return res, fmt.Errorf("invalid filepath encoding: %w", err)
394 NewField(FieldFileName, []byte(encodedName)),
395 NewField(FieldFileTypeString, fw.ffo.FlatFileInformationFork.friendlyType()),
396 NewField(FieldFileCreatorString, fw.ffo.FlatFileInformationFork.friendlyCreator()),
397 NewField(FieldFileType, fw.ffo.FlatFileInformationFork.TypeSignature),
398 NewField(FieldFileCreateDate, fw.ffo.FlatFileInformationFork.CreateDate),
399 NewField(FieldFileModifyDate, fw.ffo.FlatFileInformationFork.ModifyDate),
402 // Include the optional FileComment field if there is a comment.
403 if len(fw.ffo.FlatFileInformationFork.Comment) != 0 {
404 fields = append(fields, NewField(FieldFileComment, fw.ffo.FlatFileInformationFork.Comment))
407 // Include the FileSize field for files.
408 if !bytes.Equal(fw.ffo.FlatFileInformationFork.TypeSignature, []byte{0x66, 0x6c, 0x64, 0x72}) {
409 fields = append(fields, NewField(FieldFileSize, fw.totalSize()))
412 res = append(res, cc.NewReply(t, fields...))
416 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
417 // Fields used in the request:
419 // * 202 File path Optional
420 // * 211 File new name Optional
421 // * 210 File comment Optional
422 // Fields used in the reply: None
423 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
424 fileName := t.GetField(FieldFileName).Data
425 filePath := t.GetField(FieldFilePath).Data
427 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
432 fi, err := cc.Server.FS.Stat(fullFilePath)
437 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
441 if t.GetField(FieldFileComment).Data != nil {
442 switch mode := fi.Mode(); {
444 if !cc.Authorize(accessSetFolderComment) {
445 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for folders."))
448 case mode.IsRegular():
449 if !cc.Authorize(accessSetFileComment) {
450 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for files."))
455 if err := hlFile.ffo.FlatFileInformationFork.setComment(t.GetField(FieldFileComment).Data); err != nil {
458 w, err := hlFile.infoForkWriter()
462 _, err = w.Write(hlFile.ffo.FlatFileInformationFork.MarshalBinary())
468 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, t.GetField(FieldFileNewName).Data)
473 fileNewName := t.GetField(FieldFileNewName).Data
475 if fileNewName != nil {
476 switch mode := fi.Mode(); {
478 if !cc.Authorize(accessRenameFolder) {
479 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
482 err = os.Rename(fullFilePath, fullNewFilePath)
483 if os.IsNotExist(err) {
484 res = append(res, cc.NewErrReply(t, "Cannot rename folder "+string(fileName)+" because it does not exist or cannot be found."))
487 case mode.IsRegular():
488 if !cc.Authorize(accessRenameFile) {
489 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
492 fileDir, err := readPath(cc.Server.Config.FileRoot, filePath, []byte{})
496 hlFile.name, err = txtDecoder.String(string(fileNewName))
498 return res, fmt.Errorf("invalid filepath encoding: %w", err)
501 err = hlFile.move(fileDir)
502 if os.IsNotExist(err) {
503 res = append(res, cc.NewErrReply(t, "Cannot rename file "+string(fileName)+" because it does not exist or cannot be found."))
512 res = append(res, cc.NewReply(t))
516 // HandleDeleteFile deletes a file or folder
517 // Fields used in the request:
520 // Fields used in the reply: none
521 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
522 fileName := t.GetField(FieldFileName).Data
523 filePath := t.GetField(FieldFilePath).Data
525 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
530 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
535 fi, err := hlFile.dataFile()
537 res = append(res, cc.NewErrReply(t, "Cannot delete file "+string(fileName)+" because it does not exist or cannot be found."))
541 switch mode := fi.Mode(); {
543 if !cc.Authorize(accessDeleteFolder) {
544 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
547 case mode.IsRegular():
548 if !cc.Authorize(accessDeleteFile) {
549 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
554 if err := hlFile.delete(); err != nil {
558 res = append(res, cc.NewReply(t))
562 // HandleMoveFile moves files or folders. Note: seemingly not documented
563 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
564 fileName := string(t.GetField(FieldFileName).Data)
566 filePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(FieldFilePath).Data, t.GetField(FieldFileName).Data)
571 fileNewPath, err := readPath(cc.Server.Config.FileRoot, t.GetField(FieldFileNewPath).Data, nil)
576 cc.logger.Infow("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
578 hlFile, err := newFileWrapper(cc.Server.FS, filePath, 0)
583 fi, err := hlFile.dataFile()
585 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
588 switch mode := fi.Mode(); {
590 if !cc.Authorize(accessMoveFolder) {
591 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
594 case mode.IsRegular():
595 if !cc.Authorize(accessMoveFile) {
596 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
600 if err := hlFile.move(fileNewPath); err != nil {
603 // TODO: handle other possible errors; e.g. fileWrapper delete fails due to fileWrapper permission issue
605 res = append(res, cc.NewReply(t))
609 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
610 if !cc.Authorize(accessCreateFolder) {
611 res = append(res, cc.NewErrReply(t, "You are not allowed to create folders."))
614 folderName := string(t.GetField(FieldFileName).Data)
616 folderName = path.Join("/", folderName)
620 // FieldFilePath is only present for nested paths
621 if t.GetField(FieldFilePath).Data != nil {
623 _, err := newFp.Write(t.GetField(FieldFilePath).Data)
628 for _, pathItem := range newFp.Items {
629 subPath = filepath.Join("/", subPath, string(pathItem.Name))
632 newFolderPath := path.Join(cc.Server.Config.FileRoot, subPath, folderName)
633 newFolderPath, err = txtDecoder.String(newFolderPath)
635 return res, fmt.Errorf("invalid filepath encoding: %w", err)
638 // TODO: check path and folder name lengths
640 if _, err := cc.Server.FS.Stat(newFolderPath); !os.IsNotExist(err) {
641 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that name.", folderName)
642 return []Transaction{cc.NewErrReply(t, msg)}, nil
645 if err := cc.Server.FS.Mkdir(newFolderPath, 0777); err != nil {
646 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
647 return []Transaction{cc.NewErrReply(t, msg)}, nil
650 res = append(res, cc.NewReply(t))
654 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
655 if !cc.Authorize(accessModifyUser) {
656 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
660 login := decodeString(t.GetField(FieldUserLogin).Data)
661 userName := string(t.GetField(FieldUserName).Data)
663 newAccessLvl := t.GetField(FieldUserAccess).Data
665 account := cc.Server.Accounts[login]
667 return append(res, cc.NewErrReply(t, "Account not found.")), nil
669 account.Name = userName
670 copy(account.Access[:], newAccessLvl)
672 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
673 // not include FieldUserPassword
674 if t.GetField(FieldUserPassword).Data == nil {
675 account.Password = hashAndSalt([]byte(""))
678 if !bytes.Equal([]byte{0}, t.GetField(FieldUserPassword).Data) {
679 account.Password = hashAndSalt(t.GetField(FieldUserPassword).Data)
682 out, err := yaml.Marshal(&account)
686 if err := os.WriteFile(filepath.Join(cc.Server.ConfigDir, "Users", login+".yaml"), out, 0666); err != nil {
690 // Notify connected clients logged in as the user of the new access level
691 for _, c := range cc.Server.Clients {
692 if c.Account.Login == login {
693 // Note: comment out these two lines to test server-side deny messages
694 newT := NewTransaction(TranUserAccess, c.ID, NewField(FieldUserAccess, newAccessLvl))
695 res = append(res, *newT)
697 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
698 if c.Authorize(accessDisconUser) {
699 flagBitmap.SetBit(flagBitmap, UserFlagAdmin, 1)
701 flagBitmap.SetBit(flagBitmap, UserFlagAdmin, 0)
703 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
705 c.Account.Access = account.Access
708 TranNotifyChangeUser,
709 NewField(FieldUserID, *c.ID),
710 NewField(FieldUserFlags, c.Flags),
711 NewField(FieldUserName, c.UserName),
712 NewField(FieldUserIconID, c.Icon),
717 res = append(res, cc.NewReply(t))
721 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
722 if !cc.Authorize(accessOpenUser) {
723 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
727 account := cc.Server.Accounts[string(t.GetField(FieldUserLogin).Data)]
729 res = append(res, cc.NewErrReply(t, "Account does not exist."))
733 res = append(res, cc.NewReply(t,
734 NewField(FieldUserName, []byte(account.Name)),
735 NewField(FieldUserLogin, encodeString(t.GetField(FieldUserLogin).Data)),
736 NewField(FieldUserPassword, []byte(account.Password)),
737 NewField(FieldUserAccess, account.Access[:]),
742 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
743 if !cc.Authorize(accessOpenUser) {
744 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
748 var userFields []Field
749 for _, acc := range cc.Server.Accounts {
750 b := make([]byte, 0, 100)
751 n, err := acc.Read(b)
756 userFields = append(userFields, NewField(FieldData, b[:n]))
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 len(subFields) == 1 {
780 login := decodeString(getField(FieldData, &subFields).Data)
781 cc.logger.Infow("DeleteUser", "login", login)
783 if !cc.Authorize(accessDeleteUser) {
784 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
788 if err := cc.Server.DeleteUser(login); err != nil {
794 login := decodeString(getField(FieldUserLogin, &subFields).Data)
796 // check if the login dataFile; if so, we know we are updating an existing user
797 if acc, ok := cc.Server.Accounts[login]; ok {
798 cc.logger.Infow("UpdateUser", "login", login)
800 // account exists, so this is an update action
801 if !cc.Authorize(accessModifyUser) {
802 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
806 // This part is a bit tricky. There are three possibilities:
807 // 1) The transaction is intended to update the password.
808 // In this case, FieldUserPassword is sent with the new password.
809 // 2) The transaction is intended to remove the password.
810 // In this case, FieldUserPassword is not sent.
811 // 3) The transaction updates the users access bits, but not the password.
812 // In this case, FieldUserPassword is sent with zero as the only byte.
813 if getField(FieldUserPassword, &subFields) != nil {
814 newPass := getField(FieldUserPassword, &subFields).Data
815 if !bytes.Equal([]byte{0}, newPass) {
816 acc.Password = hashAndSalt(newPass)
819 acc.Password = hashAndSalt([]byte(""))
822 if getField(FieldUserAccess, &subFields) != nil {
823 copy(acc.Access[:], getField(FieldUserAccess, &subFields).Data)
826 err = cc.Server.UpdateUser(
827 decodeString(getField(FieldData, &subFields).Data),
828 decodeString(getField(FieldUserLogin, &subFields).Data),
829 string(getField(FieldUserName, &subFields).Data),
837 cc.logger.Infow("CreateUser", "login", login)
839 if !cc.Authorize(accessCreateUser) {
840 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
844 newAccess := accessBitmap{}
845 copy(newAccess[:], getField(FieldUserAccess, &subFields).Data)
847 // Prevent account from creating new account with greater permission
848 for i := 0; i < 64; i++ {
849 if newAccess.IsSet(i) {
850 if !cc.Authorize(i) {
851 return append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself.")), nil
856 err = cc.Server.NewUser(login, string(getField(FieldUserName, &subFields).Data), string(getField(FieldUserPassword, &subFields).Data), newAccess)
858 return append(res, cc.NewErrReply(t, "Cannot create account because there is already an account with that login.")), nil
863 res = append(res, cc.NewReply(t))
867 // HandleNewUser creates a new user account
868 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
869 if !cc.Authorize(accessCreateUser) {
870 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
874 login := decodeString(t.GetField(FieldUserLogin).Data)
876 // If the account already dataFile, reply with an error
877 if _, ok := cc.Server.Accounts[login]; ok {
878 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
882 newAccess := accessBitmap{}
883 copy(newAccess[:], t.GetField(FieldUserAccess).Data)
885 // Prevent account from creating new account with greater permission
886 for i := 0; i < 64; i++ {
887 if newAccess.IsSet(i) {
888 if !cc.Authorize(i) {
889 res = append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself."))
895 if err := cc.Server.NewUser(login, string(t.GetField(FieldUserName).Data), string(t.GetField(FieldUserPassword).Data), newAccess); err != nil {
896 res = append(res, cc.NewErrReply(t, "Cannot create account because there is already an account with that login."))
900 res = append(res, cc.NewReply(t))
904 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
905 if !cc.Authorize(accessDeleteUser) {
906 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
910 login := decodeString(t.GetField(FieldUserLogin).Data)
912 if err := cc.Server.DeleteUser(login); err != nil {
916 res = append(res, cc.NewReply(t))
920 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
921 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
922 if !cc.Authorize(accessBroadcast) {
923 res = append(res, cc.NewErrReply(t, "You are not allowed to send broadcast messages."))
929 NewField(FieldData, t.GetField(TranGetMsgs).Data),
930 NewField(FieldChatOptions, []byte{0}),
933 res = append(res, cc.NewReply(t))
937 // HandleGetClientInfoText returns user information for the specific user.
939 // Fields used in the request:
942 // Fields used in the reply:
944 // 101 Data User info text string
945 func HandleGetClientInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
946 if !cc.Authorize(accessGetClientInfo) {
947 res = append(res, cc.NewErrReply(t, "You are not allowed to get client info."))
951 clientID, _ := byteToInt(t.GetField(FieldUserID).Data)
953 clientConn := cc.Server.Clients[uint16(clientID)]
954 if clientConn == nil {
955 return append(res, cc.NewErrReply(t, "User not found.")), err
958 res = append(res, cc.NewReply(t,
959 NewField(FieldData, []byte(clientConn.String())),
960 NewField(FieldUserName, clientConn.UserName),
965 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
966 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
971 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
972 if t.GetField(FieldUserName).Data != nil {
973 if cc.Authorize(accessAnyName) {
974 cc.UserName = t.GetField(FieldUserName).Data
976 cc.UserName = []byte(cc.Account.Name)
980 cc.Icon = t.GetField(FieldUserIconID).Data
982 cc.logger = cc.logger.With("name", string(cc.UserName))
983 cc.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(cc.Version); return i }()))
985 options := t.GetField(FieldOptions).Data
986 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
988 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
990 // Check refuse private PM option
991 if optBitmap.Bit(refusePM) == 1 {
992 flagBitmap.SetBit(flagBitmap, UserFlagRefusePM, 1)
993 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
996 // Check refuse private chat option
997 if optBitmap.Bit(refuseChat) == 1 {
998 flagBitmap.SetBit(flagBitmap, UserFlagRefusePChat, 1)
999 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1002 // Check auto response
1003 if optBitmap.Bit(autoResponse) == 1 {
1004 cc.AutoReply = t.GetField(FieldAutomaticResponse).Data
1006 cc.AutoReply = []byte{}
1009 trans := cc.notifyOthers(
1011 TranNotifyChangeUser, nil,
1012 NewField(FieldUserName, cc.UserName),
1013 NewField(FieldUserID, *cc.ID),
1014 NewField(FieldUserIconID, cc.Icon),
1015 NewField(FieldUserFlags, cc.Flags),
1018 res = append(res, trans...)
1020 if cc.Server.Config.BannerFile != "" {
1021 res = append(res, *NewTransaction(TranServerBanner, cc.ID, NewField(FieldBannerType, []byte("JPEG"))))
1024 res = append(res, cc.NewReply(t))
1029 // HandleTranOldPostNews updates the flat news
1030 // Fields used in this request:
1032 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1033 if !cc.Authorize(accessNewsPostArt) {
1034 res = append(res, cc.NewErrReply(t, "You are not allowed to post news."))
1038 cc.Server.flatNewsMux.Lock()
1039 defer cc.Server.flatNewsMux.Unlock()
1041 newsDateTemplate := defaultNewsDateFormat
1042 if cc.Server.Config.NewsDateFormat != "" {
1043 newsDateTemplate = cc.Server.Config.NewsDateFormat
1046 newsTemplate := defaultNewsTemplate
1047 if cc.Server.Config.NewsDelimiter != "" {
1048 newsTemplate = cc.Server.Config.NewsDelimiter
1051 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(FieldData).Data)
1052 newsPost = strings.ReplaceAll(newsPost, "\n", "\r")
1054 // update news in memory
1055 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
1057 // update news on disk
1058 if err := cc.Server.FS.WriteFile(filepath.Join(cc.Server.ConfigDir, "MessageBoard.txt"), cc.Server.FlatNews, 0644); err != nil {
1062 // Notify all clients of updated news
1065 NewField(FieldData, []byte(newsPost)),
1068 res = append(res, cc.NewReply(t))
1072 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1073 if !cc.Authorize(accessDisconUser) {
1074 res = append(res, cc.NewErrReply(t, "You are not allowed to disconnect users."))
1078 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(FieldUserID).Data)]
1080 if clientConn.Authorize(accessCannotBeDiscon) {
1081 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
1085 // If FieldOptions is set, then the client IP is banned in addition to disconnected.
1086 // 00 01 = temporary ban
1087 // 00 02 = permanent ban
1088 if t.GetField(FieldOptions).Data != nil {
1089 switch t.GetField(FieldOptions).Data[1] {
1091 // send message: "You are temporarily banned on this server"
1092 cc.logger.Infow("Disconnect & temporarily ban " + string(clientConn.UserName))
1094 res = append(res, *NewTransaction(
1097 NewField(FieldData, []byte("You are temporarily banned on this server")),
1098 NewField(FieldChatOptions, []byte{0, 0}),
1101 banUntil := time.Now().Add(tempBanDuration)
1102 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = &banUntil
1104 // send message: "You are permanently banned on this server"
1105 cc.logger.Infow("Disconnect & ban " + string(clientConn.UserName))
1107 res = append(res, *NewTransaction(
1110 NewField(FieldData, []byte("You are permanently banned on this server")),
1111 NewField(FieldChatOptions, []byte{0, 0}),
1114 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = nil
1117 err := cc.Server.writeBanList()
1123 // TODO: remove this awful hack
1125 time.Sleep(1 * time.Second)
1126 clientConn.Disconnect()
1129 return append(res, cc.NewReply(t)), err
1132 // HandleGetNewsCatNameList returns a list of news categories for a path
1133 // Fields used in the request:
1134 // 325 News path (Optional)
1135 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1136 if !cc.Authorize(accessNewsReadArt) {
1137 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1141 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1142 cats := cc.Server.GetNewsCatByPath(pathStrs)
1144 // To store the keys in slice in sorted order
1145 keys := make([]string, len(cats))
1147 for k := range cats {
1153 var fieldData []Field
1154 for _, k := range keys {
1156 b, _ := cat.MarshalBinary()
1157 fieldData = append(fieldData, NewField(
1158 FieldNewsCatListData15,
1163 res = append(res, cc.NewReply(t, fieldData...))
1167 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1168 if !cc.Authorize(accessNewsCreateCat) {
1169 res = append(res, cc.NewErrReply(t, "You are not allowed to create news categories."))
1173 name := string(t.GetField(FieldNewsCatName).Data)
1174 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1176 cats := cc.Server.GetNewsCatByPath(pathStrs)
1177 cats[name] = NewsCategoryListData15{
1180 Articles: map[uint32]*NewsArtData{},
1181 SubCats: make(map[string]NewsCategoryListData15),
1184 if err := cc.Server.writeThreadedNews(); err != nil {
1187 res = append(res, cc.NewReply(t))
1191 // Fields used in the request:
1192 // 322 News category name
1194 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1195 if !cc.Authorize(accessNewsCreateFldr) {
1196 res = append(res, cc.NewErrReply(t, "You are not allowed to create news folders."))
1200 name := string(t.GetField(FieldFileName).Data)
1201 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1203 cc.logger.Infof("Creating new news folder %s", name)
1205 cats := cc.Server.GetNewsCatByPath(pathStrs)
1206 cats[name] = NewsCategoryListData15{
1209 Articles: map[uint32]*NewsArtData{},
1210 SubCats: make(map[string]NewsCategoryListData15),
1212 if err := cc.Server.writeThreadedNews(); err != nil {
1215 res = append(res, cc.NewReply(t))
1219 // HandleGetNewsArtData gets the list of article names at the specified news path.
1221 // Fields used in the request:
1222 // 325 News path Optional
1224 // Fields used in the reply:
1225 // 321 News article list data Optional
1226 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1227 if !cc.Authorize(accessNewsReadArt) {
1228 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1231 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1233 var cat NewsCategoryListData15
1234 cats := cc.Server.ThreadedNews.Categories
1236 for _, fp := range pathStrs {
1238 cats = cats[fp].SubCats
1241 nald := cat.GetNewsArtListData()
1243 res = append(res, cc.NewReply(t, NewField(FieldNewsArtListData, nald.Payload())))
1247 // HandleGetNewsArtData requests information about the specific news article.
1248 // Fields used in the request:
1252 // 326 News article ID
1253 // 327 News article data flavor
1255 // Fields used in the reply:
1256 // 328 News article title
1257 // 329 News article poster
1258 // 330 News article date
1259 // 331 Previous article ID
1260 // 332 Next article ID
1261 // 335 Parent article ID
1262 // 336 First child article ID
1263 // 327 News article data flavor "Should be “text/plain”
1264 // 333 News article data Optional (if data flavor is “text/plain”)
1265 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1266 if !cc.Authorize(accessNewsReadArt) {
1267 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1271 var cat NewsCategoryListData15
1272 cats := cc.Server.ThreadedNews.Categories
1274 for _, fp := range ReadNewsPath(t.GetField(FieldNewsPath).Data) {
1276 cats = cats[fp].SubCats
1279 // The official Hotline clients will send the article ID as 2 bytes if possible, but
1280 // some third party clients such as Frogblast and Heildrun will always send 4 bytes
1281 convertedID, err := byteToInt(t.GetField(FieldNewsArtID).Data)
1286 art := cat.Articles[uint32(convertedID)]
1288 res = append(res, cc.NewReply(t))
1292 res = append(res, cc.NewReply(t,
1293 NewField(FieldNewsArtTitle, []byte(art.Title)),
1294 NewField(FieldNewsArtPoster, []byte(art.Poster)),
1295 NewField(FieldNewsArtDate, art.Date),
1296 NewField(FieldNewsArtPrevArt, art.PrevArt),
1297 NewField(FieldNewsArtNextArt, art.NextArt),
1298 NewField(FieldNewsArtParentArt, art.ParentArt),
1299 NewField(FieldNewsArt1stChildArt, art.FirstChildArt),
1300 NewField(FieldNewsArtDataFlav, []byte("text/plain")),
1301 NewField(FieldNewsArtData, []byte(art.Data)),
1306 // HandleDelNewsItem deletes an existing threaded news folder or category from the server.
1307 // Fields used in the request:
1309 // Fields used in the reply:
1311 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1312 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1314 cats := cc.Server.ThreadedNews.Categories
1315 delName := pathStrs[len(pathStrs)-1]
1316 if len(pathStrs) > 1 {
1317 for _, fp := range pathStrs[0 : len(pathStrs)-1] {
1318 cats = cats[fp].SubCats
1322 if bytes.Equal(cats[delName].Type, []byte{0, 3}) {
1323 if !cc.Authorize(accessNewsDeleteCat) {
1324 return append(res, cc.NewErrReply(t, "You are not allowed to delete news categories.")), nil
1327 if !cc.Authorize(accessNewsDeleteFldr) {
1328 return append(res, cc.NewErrReply(t, "You are not allowed to delete news folders.")), nil
1332 delete(cats, delName)
1334 if err := cc.Server.writeThreadedNews(); err != nil {
1338 return append(res, cc.NewReply(t)), nil
1341 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1342 if !cc.Authorize(accessNewsDeleteArt) {
1343 res = append(res, cc.NewErrReply(t, "You are not allowed to delete news articles."))
1349 // 326 News article ID
1350 // 337 News article – recursive delete Delete child articles (1) or not (0)
1351 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1352 ID, err := byteToInt(t.GetField(FieldNewsArtID).Data)
1357 // TODO: Delete recursive
1358 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1360 catName := pathStrs[len(pathStrs)-1]
1361 cat := cats[catName]
1363 delete(cat.Articles, uint32(ID))
1366 if err := cc.Server.writeThreadedNews(); err != nil {
1370 res = append(res, cc.NewReply(t))
1376 // 326 News article ID ID of the parent article?
1377 // 328 News article title
1378 // 334 News article flags
1379 // 327 News article data flavor Currently “text/plain”
1380 // 333 News article data
1381 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1382 if !cc.Authorize(accessNewsPostArt) {
1383 res = append(res, cc.NewErrReply(t, "You are not allowed to post news articles."))
1387 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1388 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1390 catName := pathStrs[len(pathStrs)-1]
1391 cat := cats[catName]
1393 artID, err := byteToInt(t.GetField(FieldNewsArtID).Data)
1397 convertedArtID := uint32(artID)
1398 bs := make([]byte, 4)
1399 binary.BigEndian.PutUint32(bs, convertedArtID)
1401 newArt := NewsArtData{
1402 Title: string(t.GetField(FieldNewsArtTitle).Data),
1403 Poster: string(cc.UserName),
1404 Date: toHotlineTime(time.Now()),
1405 PrevArt: []byte{0, 0, 0, 0},
1406 NextArt: []byte{0, 0, 0, 0},
1408 FirstChildArt: []byte{0, 0, 0, 0},
1409 DataFlav: []byte("text/plain"),
1410 Data: string(t.GetField(FieldNewsArtData).Data),
1414 for k := range cat.Articles {
1415 keys = append(keys, int(k))
1421 prevID := uint32(keys[len(keys)-1])
1424 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1426 // Set next article ID
1427 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1430 // Update parent article with first child reply
1431 parentID := convertedArtID
1433 parentArt := cat.Articles[parentID]
1435 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1436 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1440 cat.Articles[nextID] = &newArt
1443 if err := cc.Server.writeThreadedNews(); err != nil {
1447 res = append(res, cc.NewReply(t))
1451 // HandleGetMsgs returns the flat news data
1452 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1453 if !cc.Authorize(accessNewsReadArt) {
1454 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1458 res = append(res, cc.NewReply(t, NewField(FieldData, cc.Server.FlatNews)))
1463 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1464 if !cc.Authorize(accessDownloadFile) {
1465 res = append(res, cc.NewErrReply(t, "You are not allowed to download files."))
1469 fileName := t.GetField(FieldFileName).Data
1470 filePath := t.GetField(FieldFilePath).Data
1471 resumeData := t.GetField(FieldFileResumeData).Data
1473 var dataOffset int64
1474 var frd FileResumeData
1475 if resumeData != nil {
1476 if err := frd.UnmarshalBinary(t.GetField(FieldFileResumeData).Data); err != nil {
1479 // TODO: handle rsrc fork offset
1480 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1483 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1488 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, dataOffset)
1493 xferSize := hlFile.ffo.TransferSize(0)
1495 ft := cc.newFileTransfer(FileDownload, fileName, filePath, xferSize)
1497 // TODO: refactor to remove this
1498 if resumeData != nil {
1499 var frd FileResumeData
1500 if err := frd.UnmarshalBinary(t.GetField(FieldFileResumeData).Data); err != nil {
1503 ft.fileResumeData = &frd
1506 // Optional field for when a HL v1.5+ client requests file preview
1507 // Used only for TEXT, JPEG, GIFF, BMP or PICT files
1508 // The value will always be 2
1509 if t.GetField(FieldFileTransferOptions).Data != nil {
1510 ft.options = t.GetField(FieldFileTransferOptions).Data
1511 xferSize = hlFile.ffo.FlatFileDataForkHeader.DataSize[:]
1514 res = append(res, cc.NewReply(t,
1515 NewField(FieldRefNum, ft.refNum[:]),
1516 NewField(FieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1517 NewField(FieldTransferSize, xferSize),
1518 NewField(FieldFileSize, hlFile.ffo.FlatFileDataForkHeader.DataSize[:]),
1524 // Download all files from the specified folder and sub-folders
1525 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1526 if !cc.Authorize(accessDownloadFile) {
1527 res = append(res, cc.NewErrReply(t, "You are not allowed to download folders."))
1531 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(FieldFilePath).Data, t.GetField(FieldFileName).Data)
1536 transferSize, err := CalcTotalSize(fullFilePath)
1540 itemCount, err := CalcItemCount(fullFilePath)
1545 fileTransfer := cc.newFileTransfer(FolderDownload, t.GetField(FieldFileName).Data, t.GetField(FieldFilePath).Data, transferSize)
1548 _, err = fp.Write(t.GetField(FieldFilePath).Data)
1553 res = append(res, cc.NewReply(t,
1554 NewField(FieldRefNum, fileTransfer.ReferenceNumber),
1555 NewField(FieldTransferSize, transferSize),
1556 NewField(FieldFolderItemCount, itemCount),
1557 NewField(FieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1562 // Upload all files from the local folder and its subfolders to the specified path on the server
1563 // Fields used in the request
1566 // 108 transfer size Total size of all items in the folder
1567 // 220 Folder item count
1568 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1569 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1571 if t.GetField(FieldFilePath).Data != nil {
1572 if _, err = fp.Write(t.GetField(FieldFilePath).Data); err != nil {
1577 // Handle special cases for Upload and Drop Box folders
1578 if !cc.Authorize(accessUploadAnywhere) {
1579 if !fp.IsUploadDir() && !fp.IsDropbox() {
1580 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))))
1585 fileTransfer := cc.newFileTransfer(FolderUpload,
1586 t.GetField(FieldFileName).Data,
1587 t.GetField(FieldFilePath).Data,
1588 t.GetField(FieldTransferSize).Data,
1591 fileTransfer.FolderItemCount = t.GetField(FieldFolderItemCount).Data
1593 res = append(res, cc.NewReply(t, NewField(FieldRefNum, fileTransfer.ReferenceNumber)))
1598 // Fields used in the request:
1601 // 204 File transfer options "Optional
1602 // Used only to resume download, currently has value 2"
1603 // 108 File transfer size "Optional used if download is not resumed"
1604 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1605 if !cc.Authorize(accessUploadFile) {
1606 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1610 fileName := t.GetField(FieldFileName).Data
1611 filePath := t.GetField(FieldFilePath).Data
1612 transferOptions := t.GetField(FieldFileTransferOptions).Data
1613 transferSize := t.GetField(FieldTransferSize).Data // not sent for resume
1616 if filePath != nil {
1617 if _, err = fp.Write(filePath); err != nil {
1622 // Handle special cases for Upload and Drop Box folders
1623 if !cc.Authorize(accessUploadAnywhere) {
1624 if !fp.IsUploadDir() && !fp.IsDropbox() {
1625 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))))
1629 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1634 if _, err := cc.Server.FS.Stat(fullFilePath); err == nil {
1635 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))))
1639 ft := cc.newFileTransfer(FileUpload, fileName, filePath, transferSize)
1641 replyT := cc.NewReply(t, NewField(FieldRefNum, ft.ReferenceNumber))
1643 // client has requested to resume a partially transferred file
1644 if transferOptions != nil {
1645 fileInfo, err := cc.Server.FS.Stat(fullFilePath + incompleteFileSuffix)
1650 offset := make([]byte, 4)
1651 binary.BigEndian.PutUint32(offset, uint32(fileInfo.Size()))
1653 fileResumeData := NewFileResumeData([]ForkInfoList{
1654 *NewForkInfoList(offset),
1657 b, _ := fileResumeData.BinaryMarshal()
1659 ft.TransferSize = offset
1661 replyT.Fields = append(replyT.Fields, NewField(FieldFileResumeData, b))
1664 res = append(res, replyT)
1668 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1669 if len(t.GetField(FieldUserIconID).Data) == 4 {
1670 cc.Icon = t.GetField(FieldUserIconID).Data[2:]
1672 cc.Icon = t.GetField(FieldUserIconID).Data
1674 if cc.Authorize(accessAnyName) {
1675 cc.UserName = t.GetField(FieldUserName).Data
1678 // the options field is only passed by the client versions > 1.2.3.
1679 options := t.GetField(FieldOptions).Data
1681 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1682 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
1684 flagBitmap.SetBit(flagBitmap, UserFlagRefusePM, optBitmap.Bit(refusePM))
1685 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1687 flagBitmap.SetBit(flagBitmap, UserFlagRefusePChat, optBitmap.Bit(refuseChat))
1688 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1690 // Check auto response
1691 if optBitmap.Bit(autoResponse) == 1 {
1692 cc.AutoReply = t.GetField(FieldAutomaticResponse).Data
1694 cc.AutoReply = []byte{}
1698 for _, c := range sortedClients(cc.Server.Clients) {
1699 res = append(res, *NewTransaction(
1700 TranNotifyChangeUser,
1702 NewField(FieldUserID, *cc.ID),
1703 NewField(FieldUserIconID, cc.Icon),
1704 NewField(FieldUserFlags, cc.Flags),
1705 NewField(FieldUserName, cc.UserName),
1712 // HandleKeepAlive responds to keepalive transactions with an empty reply
1713 // * HL 1.9.2 Client sends keepalive msg every 3 minutes
1714 // * HL 1.2.3 Client doesn't send keepalives
1715 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1716 res = append(res, cc.NewReply(t))
1721 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1722 fullPath, err := readPath(
1723 cc.Server.Config.FileRoot,
1724 t.GetField(FieldFilePath).Data,
1732 if t.GetField(FieldFilePath).Data != nil {
1733 if _, err = fp.Write(t.GetField(FieldFilePath).Data); err != nil {
1738 // Handle special case for drop box folders
1739 if fp.IsDropbox() && !cc.Authorize(accessViewDropBoxes) {
1740 res = append(res, cc.NewErrReply(t, "You are not allowed to view drop boxes."))
1744 fileNames, err := getFileNameList(fullPath, cc.Server.Config.IgnoreFiles)
1749 res = append(res, cc.NewReply(t, fileNames...))
1754 // =================================
1755 // Hotline private chat flow
1756 // =================================
1757 // 1. ClientA sends TranInviteNewChat to server with user ID to invite
1758 // 2. Server creates new ChatID
1759 // 3. Server sends TranInviteToChat to invitee
1760 // 4. Server replies to ClientA with new Chat ID
1762 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1763 // If Accepted is clicked:
1764 // 1. ClientB sends TranJoinChat with FieldChatID
1766 // HandleInviteNewChat invites users to new private chat
1767 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1768 if !cc.Authorize(accessOpenChat) {
1769 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1774 targetID := t.GetField(FieldUserID).Data
1775 newChatID := cc.Server.NewPrivateChat(cc)
1777 // Check if target user has "Refuse private chat" flag
1778 binary.BigEndian.Uint16(targetID)
1779 targetClient := cc.Server.Clients[binary.BigEndian.Uint16(targetID)]
1781 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(targetClient.Flags)))
1782 if flagBitmap.Bit(UserFlagRefusePChat) == 1 {
1787 NewField(FieldData, []byte(string(targetClient.UserName)+" does not accept private chats.")),
1788 NewField(FieldUserName, targetClient.UserName),
1789 NewField(FieldUserID, *targetClient.ID),
1790 NewField(FieldOptions, []byte{0, 2}),
1798 NewField(FieldChatID, newChatID),
1799 NewField(FieldUserName, cc.UserName),
1800 NewField(FieldUserID, *cc.ID),
1807 NewField(FieldChatID, newChatID),
1808 NewField(FieldUserName, cc.UserName),
1809 NewField(FieldUserID, *cc.ID),
1810 NewField(FieldUserIconID, cc.Icon),
1811 NewField(FieldUserFlags, cc.Flags),
1818 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1819 if !cc.Authorize(accessOpenChat) {
1820 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1825 targetID := t.GetField(FieldUserID).Data
1826 chatID := t.GetField(FieldChatID).Data
1832 NewField(FieldChatID, chatID),
1833 NewField(FieldUserName, cc.UserName),
1834 NewField(FieldUserID, *cc.ID),
1840 NewField(FieldChatID, chatID),
1841 NewField(FieldUserName, cc.UserName),
1842 NewField(FieldUserID, *cc.ID),
1843 NewField(FieldUserIconID, cc.Icon),
1844 NewField(FieldUserFlags, cc.Flags),
1851 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1852 chatID := t.GetField(FieldChatID).Data
1853 chatInt := binary.BigEndian.Uint32(chatID)
1855 privChat := cc.Server.PrivateChats[chatInt]
1857 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1859 for _, c := range sortedClients(privChat.ClientConn) {
1864 NewField(FieldChatID, chatID),
1865 NewField(FieldData, resMsg),
1873 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1874 // Fields used in the reply:
1875 // * 115 Chat subject
1876 // * 300 User name with info (Optional)
1877 // * 300 (more user names with info)
1878 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1879 chatID := t.GetField(FieldChatID).Data
1880 chatInt := binary.BigEndian.Uint32(chatID)
1882 privChat := cc.Server.PrivateChats[chatInt]
1884 // Send TranNotifyChatChangeUser to current members of the chat to inform of new user
1885 for _, c := range sortedClients(privChat.ClientConn) {
1888 TranNotifyChatChangeUser,
1890 NewField(FieldChatID, chatID),
1891 NewField(FieldUserName, cc.UserName),
1892 NewField(FieldUserID, *cc.ID),
1893 NewField(FieldUserIconID, cc.Icon),
1894 NewField(FieldUserFlags, cc.Flags),
1899 privChat.ClientConn[cc.uint16ID()] = cc
1901 replyFields := []Field{NewField(FieldChatSubject, []byte(privChat.Subject))}
1902 for _, c := range sortedClients(privChat.ClientConn) {
1907 Name: string(c.UserName),
1910 replyFields = append(replyFields, NewField(FieldUsernameWithInfo, user.Payload()))
1913 res = append(res, cc.NewReply(t, replyFields...))
1917 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1918 // Fields used in the request:
1919 // - 114 FieldChatID
1921 // Reply is not expected.
1922 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1923 chatID := t.GetField(FieldChatID).Data
1924 chatInt := binary.BigEndian.Uint32(chatID)
1926 privChat, ok := cc.Server.PrivateChats[chatInt]
1931 delete(privChat.ClientConn, cc.uint16ID())
1933 // Notify members of the private chat that the user has left
1934 for _, c := range sortedClients(privChat.ClientConn) {
1937 TranNotifyChatDeleteUser,
1939 NewField(FieldChatID, chatID),
1940 NewField(FieldUserID, *cc.ID),
1948 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1949 // Fields used in the request:
1951 // * 115 Chat subject
1952 // Reply is not expected.
1953 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1954 chatID := t.GetField(FieldChatID).Data
1955 chatInt := binary.BigEndian.Uint32(chatID)
1957 privChat := cc.Server.PrivateChats[chatInt]
1958 privChat.Subject = string(t.GetField(FieldChatSubject).Data)
1960 for _, c := range sortedClients(privChat.ClientConn) {
1963 TranNotifyChatSubject,
1965 NewField(FieldChatID, chatID),
1966 NewField(FieldChatSubject, t.GetField(FieldChatSubject).Data),
1974 // HandleMakeAlias makes a file alias using the specified path.
1975 // Fields used in the request:
1978 // 212 File new path Destination path
1980 // Fields used in the reply:
1982 func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1983 if !cc.Authorize(accessMakeAlias) {
1984 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
1987 fileName := t.GetField(FieldFileName).Data
1988 filePath := t.GetField(FieldFilePath).Data
1989 fileNewPath := t.GetField(FieldFileNewPath).Data
1991 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1996 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
2001 cc.logger.Debugw("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
2003 if err := cc.Server.FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
2004 res = append(res, cc.NewErrReply(t, "Error creating alias"))
2008 res = append(res, cc.NewReply(t))
2012 // HandleDownloadBanner handles requests for a new banner from the server
2013 // Fields used in the request:
2015 // Fields used in the reply:
2016 // 107 FieldRefNum Used later for transfer
2017 // 108 FieldTransferSize Size of data to be downloaded
2018 func HandleDownloadBanner(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
2019 fi, err := cc.Server.FS.Stat(filepath.Join(cc.Server.ConfigDir, cc.Server.Config.BannerFile))
2024 ft := cc.newFileTransfer(bannerDownload, []byte{}, []byte{}, make([]byte, 4))
2026 binary.BigEndian.PutUint32(ft.TransferSize, uint32(fi.Size()))
2028 res = append(res, cc.NewReply(t,
2029 NewField(FieldRefNum, ft.refNum[:]),
2030 NewField(FieldTransferSize, ft.TransferSize),