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]
666 account.Name = userName
667 copy(account.Access[:], newAccessLvl)
669 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
670 // not include FieldUserPassword
671 if t.GetField(FieldUserPassword).Data == nil {
672 account.Password = hashAndSalt([]byte(""))
674 if len(t.GetField(FieldUserPassword).Data) > 1 {
675 account.Password = hashAndSalt(t.GetField(FieldUserPassword).Data)
678 out, err := yaml.Marshal(&account)
682 if err := os.WriteFile(filepath.Join(cc.Server.ConfigDir, "Users", login+".yaml"), out, 0666); err != nil {
686 // Notify connected clients logged in as the user of the new access level
687 for _, c := range cc.Server.Clients {
688 if c.Account.Login == login {
689 // Note: comment out these two lines to test server-side deny messages
690 newT := NewTransaction(TranUserAccess, c.ID, NewField(FieldUserAccess, newAccessLvl))
691 res = append(res, *newT)
693 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
694 if c.Authorize(accessDisconUser) {
695 flagBitmap.SetBit(flagBitmap, UserFlagAdmin, 1)
697 flagBitmap.SetBit(flagBitmap, UserFlagAdmin, 0)
699 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
701 c.Account.Access = account.Access
704 TranNotifyChangeUser,
705 NewField(FieldUserID, *c.ID),
706 NewField(FieldUserFlags, c.Flags),
707 NewField(FieldUserName, c.UserName),
708 NewField(FieldUserIconID, c.Icon),
713 res = append(res, cc.NewReply(t))
717 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
718 if !cc.Authorize(accessOpenUser) {
719 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
723 account := cc.Server.Accounts[string(t.GetField(FieldUserLogin).Data)]
725 res = append(res, cc.NewErrReply(t, "Account does not exist."))
729 res = append(res, cc.NewReply(t,
730 NewField(FieldUserName, []byte(account.Name)),
731 NewField(FieldUserLogin, encodeString(t.GetField(FieldUserLogin).Data)),
732 NewField(FieldUserPassword, []byte(account.Password)),
733 NewField(FieldUserAccess, account.Access[:]),
738 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
739 if !cc.Authorize(accessOpenUser) {
740 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
744 var userFields []Field
745 for _, acc := range cc.Server.Accounts {
746 b := make([]byte, 0, 100)
747 n, err := acc.Read(b)
752 userFields = append(userFields, NewField(FieldData, b[:n]))
755 res = append(res, cc.NewReply(t, userFields...))
759 // HandleUpdateUser is used by the v1.5+ multi-user editor to perform account editing for multiple users at a time.
760 // An update can be a mix of these actions:
763 // * Modify user (including renaming the account login)
765 // The Transaction sent by the client includes one data field per user that was modified. This data field in turn
766 // contains another data field encoded in its payload with a varying number of sub fields depending on which action is
767 // performed. This seems to be the only place in the Hotline protocol where a data field contains another data field.
768 func HandleUpdateUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
769 for _, field := range t.Fields {
770 subFields, err := ReadFields(field.Data[0:2], field.Data[2:])
775 if len(subFields) == 1 {
776 login := decodeString(getField(FieldData, &subFields).Data)
777 cc.logger.Infow("DeleteUser", "login", login)
779 if !cc.Authorize(accessDeleteUser) {
780 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
784 if err := cc.Server.DeleteUser(login); err != nil {
790 login := decodeString(getField(FieldUserLogin, &subFields).Data)
792 // check if the login dataFile; if so, we know we are updating an existing user
793 if acc, ok := cc.Server.Accounts[login]; ok {
794 cc.logger.Infow("UpdateUser", "login", login)
796 // account exists, so this is an update action
797 if !cc.Authorize(accessModifyUser) {
798 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
802 // This part is a bit tricky. There are three possibilities:
803 // 1) The transaction is intended to update the password.
804 // In this case, FieldUserPassword is sent with the new password.
805 // 2) The transaction is intended to remove the password.
806 // In this case, FieldUserPassword is not sent.
807 // 3) The transaction updates the users access bits, but not the password.
808 // In this case, FieldUserPassword is sent with zero as the only byte..
809 if getField(FieldUserPassword, &subFields) != nil {
810 newPass := getField(FieldUserPassword, &subFields).Data
811 if !bytes.Equal([]byte{0}, newPass) {
812 acc.Password = hashAndSalt(newPass)
815 acc.Password = hashAndSalt([]byte(""))
818 if getField(FieldUserAccess, &subFields) != nil {
819 copy(acc.Access[:], getField(FieldUserAccess, &subFields).Data)
822 err = cc.Server.UpdateUser(
823 decodeString(getField(FieldData, &subFields).Data),
824 decodeString(getField(FieldUserLogin, &subFields).Data),
825 string(getField(FieldUserName, &subFields).Data),
833 cc.logger.Infow("CreateUser", "login", login)
835 if !cc.Authorize(accessCreateUser) {
836 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
840 newAccess := accessBitmap{}
841 copy(newAccess[:], getField(FieldUserAccess, &subFields).Data)
843 // Prevent account from creating new account with greater permission
844 for i := 0; i < 64; i++ {
845 if newAccess.IsSet(i) {
846 if !cc.Authorize(i) {
847 return append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself.")), err
852 err := cc.Server.NewUser(login, string(getField(FieldUserName, &subFields).Data), string(getField(FieldUserPassword, &subFields).Data), newAccess)
854 return []Transaction{}, err
859 res = append(res, cc.NewReply(t))
863 // HandleNewUser creates a new user account
864 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
865 if !cc.Authorize(accessCreateUser) {
866 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
870 login := decodeString(t.GetField(FieldUserLogin).Data)
872 // If the account already dataFile, reply with an error
873 if _, ok := cc.Server.Accounts[login]; ok {
874 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
878 newAccess := accessBitmap{}
879 copy(newAccess[:], t.GetField(FieldUserAccess).Data)
881 // Prevent account from creating new account with greater permission
882 for i := 0; i < 64; i++ {
883 if newAccess.IsSet(i) {
884 if !cc.Authorize(i) {
885 res = append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself."))
891 if err := cc.Server.NewUser(login, string(t.GetField(FieldUserName).Data), string(t.GetField(FieldUserPassword).Data), newAccess); err != nil {
892 return []Transaction{}, err
895 res = append(res, cc.NewReply(t))
899 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
900 if !cc.Authorize(accessDeleteUser) {
901 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
905 // TODO: Handle case where account doesn't exist; e.g. delete race condition
906 login := decodeString(t.GetField(FieldUserLogin).Data)
908 if err := cc.Server.DeleteUser(login); err != nil {
912 res = append(res, cc.NewReply(t))
916 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
917 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
918 if !cc.Authorize(accessBroadcast) {
919 res = append(res, cc.NewErrReply(t, "You are not allowed to send broadcast messages."))
925 NewField(FieldData, t.GetField(TranGetMsgs).Data),
926 NewField(FieldChatOptions, []byte{0}),
929 res = append(res, cc.NewReply(t))
933 // HandleGetClientInfoText returns user information for the specific user.
935 // Fields used in the request:
938 // Fields used in the reply:
940 // 101 Data User info text string
941 func HandleGetClientInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
942 if !cc.Authorize(accessGetClientInfo) {
943 res = append(res, cc.NewErrReply(t, "You are not allowed to get client info."))
947 clientID, _ := byteToInt(t.GetField(FieldUserID).Data)
949 clientConn := cc.Server.Clients[uint16(clientID)]
950 if clientConn == nil {
951 return append(res, cc.NewErrReply(t, "User not found.")), err
954 res = append(res, cc.NewReply(t,
955 NewField(FieldData, []byte(clientConn.String())),
956 NewField(FieldUserName, clientConn.UserName),
961 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
962 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
967 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
968 if t.GetField(FieldUserName).Data != nil {
969 if cc.Authorize(accessAnyName) {
970 cc.UserName = t.GetField(FieldUserName).Data
972 cc.UserName = []byte(cc.Account.Name)
976 cc.Icon = t.GetField(FieldUserIconID).Data
978 cc.logger = cc.logger.With("name", string(cc.UserName))
979 cc.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(cc.Version); return i }()))
981 options := t.GetField(FieldOptions).Data
982 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
984 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
986 // Check refuse private PM option
987 if optBitmap.Bit(refusePM) == 1 {
988 flagBitmap.SetBit(flagBitmap, UserFlagRefusePM, 1)
989 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
992 // Check refuse private chat option
993 if optBitmap.Bit(refuseChat) == 1 {
994 flagBitmap.SetBit(flagBitmap, UserFlagRefusePChat, 1)
995 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
998 // Check auto response
999 if optBitmap.Bit(autoResponse) == 1 {
1000 cc.AutoReply = t.GetField(FieldAutomaticResponse).Data
1002 cc.AutoReply = []byte{}
1005 trans := cc.notifyOthers(
1007 TranNotifyChangeUser, nil,
1008 NewField(FieldUserName, cc.UserName),
1009 NewField(FieldUserID, *cc.ID),
1010 NewField(FieldUserIconID, cc.Icon),
1011 NewField(FieldUserFlags, cc.Flags),
1014 res = append(res, trans...)
1016 if cc.Server.Config.BannerFile != "" {
1017 res = append(res, *NewTransaction(TranServerBanner, cc.ID, NewField(FieldBannerType, []byte("JPEG"))))
1020 res = append(res, cc.NewReply(t))
1025 // HandleTranOldPostNews updates the flat news
1026 // Fields used in this request:
1028 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1029 if !cc.Authorize(accessNewsPostArt) {
1030 res = append(res, cc.NewErrReply(t, "You are not allowed to post news."))
1034 cc.Server.flatNewsMux.Lock()
1035 defer cc.Server.flatNewsMux.Unlock()
1037 newsDateTemplate := defaultNewsDateFormat
1038 if cc.Server.Config.NewsDateFormat != "" {
1039 newsDateTemplate = cc.Server.Config.NewsDateFormat
1042 newsTemplate := defaultNewsTemplate
1043 if cc.Server.Config.NewsDelimiter != "" {
1044 newsTemplate = cc.Server.Config.NewsDelimiter
1047 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(FieldData).Data)
1048 newsPost = strings.ReplaceAll(newsPost, "\n", "\r")
1050 // update news in memory
1051 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
1053 // update news on disk
1054 if err := cc.Server.FS.WriteFile(filepath.Join(cc.Server.ConfigDir, "MessageBoard.txt"), cc.Server.FlatNews, 0644); err != nil {
1058 // Notify all clients of updated news
1061 NewField(FieldData, []byte(newsPost)),
1064 res = append(res, cc.NewReply(t))
1068 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1069 if !cc.Authorize(accessDisconUser) {
1070 res = append(res, cc.NewErrReply(t, "You are not allowed to disconnect users."))
1074 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(FieldUserID).Data)]
1076 if clientConn.Authorize(accessCannotBeDiscon) {
1077 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
1081 // If FieldOptions is set, then the client IP is banned in addition to disconnected.
1082 // 00 01 = temporary ban
1083 // 00 02 = permanent ban
1084 if t.GetField(FieldOptions).Data != nil {
1085 switch t.GetField(FieldOptions).Data[1] {
1087 // send message: "You are temporarily banned on this server"
1088 cc.logger.Infow("Disconnect & temporarily ban " + string(clientConn.UserName))
1090 res = append(res, *NewTransaction(
1093 NewField(FieldData, []byte("You are temporarily banned on this server")),
1094 NewField(FieldChatOptions, []byte{0, 0}),
1097 banUntil := time.Now().Add(tempBanDuration)
1098 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = &banUntil
1100 // send message: "You are permanently banned on this server"
1101 cc.logger.Infow("Disconnect & ban " + string(clientConn.UserName))
1103 res = append(res, *NewTransaction(
1106 NewField(FieldData, []byte("You are permanently banned on this server")),
1107 NewField(FieldChatOptions, []byte{0, 0}),
1110 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = nil
1113 err := cc.Server.writeBanList()
1119 // TODO: remove this awful hack
1121 time.Sleep(1 * time.Second)
1122 clientConn.Disconnect()
1125 return append(res, cc.NewReply(t)), err
1128 // HandleGetNewsCatNameList returns a list of news categories for a path
1129 // Fields used in the request:
1130 // 325 News path (Optional)
1131 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1132 if !cc.Authorize(accessNewsReadArt) {
1133 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1137 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1138 cats := cc.Server.GetNewsCatByPath(pathStrs)
1140 // To store the keys in slice in sorted order
1141 keys := make([]string, len(cats))
1143 for k := range cats {
1149 var fieldData []Field
1150 for _, k := range keys {
1152 b, _ := cat.MarshalBinary()
1153 fieldData = append(fieldData, NewField(
1154 FieldNewsCatListData15,
1159 res = append(res, cc.NewReply(t, fieldData...))
1163 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1164 if !cc.Authorize(accessNewsCreateCat) {
1165 res = append(res, cc.NewErrReply(t, "You are not allowed to create news categories."))
1169 name := string(t.GetField(FieldNewsCatName).Data)
1170 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1172 cats := cc.Server.GetNewsCatByPath(pathStrs)
1173 cats[name] = NewsCategoryListData15{
1176 Articles: map[uint32]*NewsArtData{},
1177 SubCats: make(map[string]NewsCategoryListData15),
1180 if err := cc.Server.writeThreadedNews(); err != nil {
1183 res = append(res, cc.NewReply(t))
1187 // Fields used in the request:
1188 // 322 News category name
1190 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1191 if !cc.Authorize(accessNewsCreateFldr) {
1192 res = append(res, cc.NewErrReply(t, "You are not allowed to create news folders."))
1196 name := string(t.GetField(FieldFileName).Data)
1197 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1199 cc.logger.Infof("Creating new news folder %s", name)
1201 cats := cc.Server.GetNewsCatByPath(pathStrs)
1202 cats[name] = NewsCategoryListData15{
1205 Articles: map[uint32]*NewsArtData{},
1206 SubCats: make(map[string]NewsCategoryListData15),
1208 if err := cc.Server.writeThreadedNews(); err != nil {
1211 res = append(res, cc.NewReply(t))
1215 // HandleGetNewsArtData gets the list of article names at the specified news path.
1217 // Fields used in the request:
1218 // 325 News path Optional
1220 // Fields used in the reply:
1221 // 321 News article list data Optional
1222 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1223 if !cc.Authorize(accessNewsReadArt) {
1224 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1227 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1229 var cat NewsCategoryListData15
1230 cats := cc.Server.ThreadedNews.Categories
1232 for _, fp := range pathStrs {
1234 cats = cats[fp].SubCats
1237 nald := cat.GetNewsArtListData()
1239 res = append(res, cc.NewReply(t, NewField(FieldNewsArtListData, nald.Payload())))
1243 // HandleGetNewsArtData requests information about the specific news article.
1244 // Fields used in the request:
1248 // 326 News article ID
1249 // 327 News article data flavor
1251 // Fields used in the reply:
1252 // 328 News article title
1253 // 329 News article poster
1254 // 330 News article date
1255 // 331 Previous article ID
1256 // 332 Next article ID
1257 // 335 Parent article ID
1258 // 336 First child article ID
1259 // 327 News article data flavor "Should be “text/plain”
1260 // 333 News article data Optional (if data flavor is “text/plain”)
1261 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1262 if !cc.Authorize(accessNewsReadArt) {
1263 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1267 var cat NewsCategoryListData15
1268 cats := cc.Server.ThreadedNews.Categories
1270 for _, fp := range ReadNewsPath(t.GetField(FieldNewsPath).Data) {
1272 cats = cats[fp].SubCats
1275 // The official Hotline clients will send the article ID as 2 bytes if possible, but
1276 // some third party clients such as Frogblast and Heildrun will always send 4 bytes
1277 convertedID, err := byteToInt(t.GetField(FieldNewsArtID).Data)
1282 art := cat.Articles[uint32(convertedID)]
1284 res = append(res, cc.NewReply(t))
1288 res = append(res, cc.NewReply(t,
1289 NewField(FieldNewsArtTitle, []byte(art.Title)),
1290 NewField(FieldNewsArtPoster, []byte(art.Poster)),
1291 NewField(FieldNewsArtDate, art.Date),
1292 NewField(FieldNewsArtPrevArt, art.PrevArt),
1293 NewField(FieldNewsArtNextArt, art.NextArt),
1294 NewField(FieldNewsArtParentArt, art.ParentArt),
1295 NewField(FieldNewsArt1stChildArt, art.FirstChildArt),
1296 NewField(FieldNewsArtDataFlav, []byte("text/plain")),
1297 NewField(FieldNewsArtData, []byte(art.Data)),
1302 // HandleDelNewsItem deletes an existing threaded news folder or category from the server.
1303 // Fields used in the request:
1305 // Fields used in the reply:
1307 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1308 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1310 cats := cc.Server.ThreadedNews.Categories
1311 delName := pathStrs[len(pathStrs)-1]
1312 if len(pathStrs) > 1 {
1313 for _, fp := range pathStrs[0 : len(pathStrs)-1] {
1314 cats = cats[fp].SubCats
1318 if bytes.Equal(cats[delName].Type, []byte{0, 3}) {
1319 if !cc.Authorize(accessNewsDeleteCat) {
1320 return append(res, cc.NewErrReply(t, "You are not allowed to delete news categories.")), nil
1323 if !cc.Authorize(accessNewsDeleteFldr) {
1324 return append(res, cc.NewErrReply(t, "You are not allowed to delete news folders.")), nil
1328 delete(cats, delName)
1330 if err := cc.Server.writeThreadedNews(); err != nil {
1334 return append(res, cc.NewReply(t)), nil
1337 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1338 if !cc.Authorize(accessNewsDeleteArt) {
1339 res = append(res, cc.NewErrReply(t, "You are not allowed to delete news articles."))
1345 // 326 News article ID
1346 // 337 News article – recursive delete Delete child articles (1) or not (0)
1347 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1348 ID, err := byteToInt(t.GetField(FieldNewsArtID).Data)
1353 // TODO: Delete recursive
1354 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1356 catName := pathStrs[len(pathStrs)-1]
1357 cat := cats[catName]
1359 delete(cat.Articles, uint32(ID))
1362 if err := cc.Server.writeThreadedNews(); err != nil {
1366 res = append(res, cc.NewReply(t))
1372 // 326 News article ID ID of the parent article?
1373 // 328 News article title
1374 // 334 News article flags
1375 // 327 News article data flavor Currently “text/plain”
1376 // 333 News article data
1377 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1378 if !cc.Authorize(accessNewsPostArt) {
1379 res = append(res, cc.NewErrReply(t, "You are not allowed to post news articles."))
1383 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1384 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1386 catName := pathStrs[len(pathStrs)-1]
1387 cat := cats[catName]
1389 artID, err := byteToInt(t.GetField(FieldNewsArtID).Data)
1393 convertedArtID := uint32(artID)
1394 bs := make([]byte, 4)
1395 binary.BigEndian.PutUint32(bs, convertedArtID)
1397 newArt := NewsArtData{
1398 Title: string(t.GetField(FieldNewsArtTitle).Data),
1399 Poster: string(cc.UserName),
1400 Date: toHotlineTime(time.Now()),
1401 PrevArt: []byte{0, 0, 0, 0},
1402 NextArt: []byte{0, 0, 0, 0},
1404 FirstChildArt: []byte{0, 0, 0, 0},
1405 DataFlav: []byte("text/plain"),
1406 Data: string(t.GetField(FieldNewsArtData).Data),
1410 for k := range cat.Articles {
1411 keys = append(keys, int(k))
1417 prevID := uint32(keys[len(keys)-1])
1420 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1422 // Set next article ID
1423 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1426 // Update parent article with first child reply
1427 parentID := convertedArtID
1429 parentArt := cat.Articles[parentID]
1431 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1432 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1436 cat.Articles[nextID] = &newArt
1439 if err := cc.Server.writeThreadedNews(); err != nil {
1443 res = append(res, cc.NewReply(t))
1447 // HandleGetMsgs returns the flat news data
1448 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1449 if !cc.Authorize(accessNewsReadArt) {
1450 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1454 res = append(res, cc.NewReply(t, NewField(FieldData, cc.Server.FlatNews)))
1459 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1460 if !cc.Authorize(accessDownloadFile) {
1461 res = append(res, cc.NewErrReply(t, "You are not allowed to download files."))
1465 fileName := t.GetField(FieldFileName).Data
1466 filePath := t.GetField(FieldFilePath).Data
1467 resumeData := t.GetField(FieldFileResumeData).Data
1469 var dataOffset int64
1470 var frd FileResumeData
1471 if resumeData != nil {
1472 if err := frd.UnmarshalBinary(t.GetField(FieldFileResumeData).Data); err != nil {
1475 // TODO: handle rsrc fork offset
1476 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1479 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1484 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, dataOffset)
1489 xferSize := hlFile.ffo.TransferSize(0)
1491 ft := cc.newFileTransfer(FileDownload, fileName, filePath, xferSize)
1493 // TODO: refactor to remove this
1494 if resumeData != nil {
1495 var frd FileResumeData
1496 if err := frd.UnmarshalBinary(t.GetField(FieldFileResumeData).Data); err != nil {
1499 ft.fileResumeData = &frd
1502 // Optional field for when a HL v1.5+ client requests file preview
1503 // Used only for TEXT, JPEG, GIFF, BMP or PICT files
1504 // The value will always be 2
1505 if t.GetField(FieldFileTransferOptions).Data != nil {
1506 ft.options = t.GetField(FieldFileTransferOptions).Data
1507 xferSize = hlFile.ffo.FlatFileDataForkHeader.DataSize[:]
1510 res = append(res, cc.NewReply(t,
1511 NewField(FieldRefNum, ft.refNum[:]),
1512 NewField(FieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1513 NewField(FieldTransferSize, xferSize),
1514 NewField(FieldFileSize, hlFile.ffo.FlatFileDataForkHeader.DataSize[:]),
1520 // Download all files from the specified folder and sub-folders
1521 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1522 if !cc.Authorize(accessDownloadFile) {
1523 res = append(res, cc.NewErrReply(t, "You are not allowed to download folders."))
1527 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(FieldFilePath).Data, t.GetField(FieldFileName).Data)
1532 transferSize, err := CalcTotalSize(fullFilePath)
1536 itemCount, err := CalcItemCount(fullFilePath)
1541 fileTransfer := cc.newFileTransfer(FolderDownload, t.GetField(FieldFileName).Data, t.GetField(FieldFilePath).Data, transferSize)
1544 _, err = fp.Write(t.GetField(FieldFilePath).Data)
1549 res = append(res, cc.NewReply(t,
1550 NewField(FieldRefNum, fileTransfer.ReferenceNumber),
1551 NewField(FieldTransferSize, transferSize),
1552 NewField(FieldFolderItemCount, itemCount),
1553 NewField(FieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1558 // Upload all files from the local folder and its subfolders to the specified path on the server
1559 // Fields used in the request
1562 // 108 transfer size Total size of all items in the folder
1563 // 220 Folder item count
1564 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1565 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1567 if t.GetField(FieldFilePath).Data != nil {
1568 if _, err = fp.Write(t.GetField(FieldFilePath).Data); err != nil {
1573 // Handle special cases for Upload and Drop Box folders
1574 if !cc.Authorize(accessUploadAnywhere) {
1575 if !fp.IsUploadDir() && !fp.IsDropbox() {
1576 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))))
1581 fileTransfer := cc.newFileTransfer(FolderUpload,
1582 t.GetField(FieldFileName).Data,
1583 t.GetField(FieldFilePath).Data,
1584 t.GetField(FieldTransferSize).Data,
1587 fileTransfer.FolderItemCount = t.GetField(FieldFolderItemCount).Data
1589 res = append(res, cc.NewReply(t, NewField(FieldRefNum, fileTransfer.ReferenceNumber)))
1594 // Fields used in the request:
1597 // 204 File transfer options "Optional
1598 // Used only to resume download, currently has value 2"
1599 // 108 File transfer size "Optional used if download is not resumed"
1600 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1601 if !cc.Authorize(accessUploadFile) {
1602 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1606 fileName := t.GetField(FieldFileName).Data
1607 filePath := t.GetField(FieldFilePath).Data
1608 transferOptions := t.GetField(FieldFileTransferOptions).Data
1609 transferSize := t.GetField(FieldTransferSize).Data // not sent for resume
1612 if filePath != nil {
1613 if _, err = fp.Write(filePath); err != nil {
1618 // Handle special cases for Upload and Drop Box folders
1619 if !cc.Authorize(accessUploadAnywhere) {
1620 if !fp.IsUploadDir() && !fp.IsDropbox() {
1621 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))))
1625 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1630 if _, err := cc.Server.FS.Stat(fullFilePath); err == nil {
1631 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))))
1635 ft := cc.newFileTransfer(FileUpload, fileName, filePath, transferSize)
1637 replyT := cc.NewReply(t, NewField(FieldRefNum, ft.ReferenceNumber))
1639 // client has requested to resume a partially transferred file
1640 if transferOptions != nil {
1641 fileInfo, err := cc.Server.FS.Stat(fullFilePath + incompleteFileSuffix)
1646 offset := make([]byte, 4)
1647 binary.BigEndian.PutUint32(offset, uint32(fileInfo.Size()))
1649 fileResumeData := NewFileResumeData([]ForkInfoList{
1650 *NewForkInfoList(offset),
1653 b, _ := fileResumeData.BinaryMarshal()
1655 ft.TransferSize = offset
1657 replyT.Fields = append(replyT.Fields, NewField(FieldFileResumeData, b))
1660 res = append(res, replyT)
1664 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1665 if len(t.GetField(FieldUserIconID).Data) == 4 {
1666 cc.Icon = t.GetField(FieldUserIconID).Data[2:]
1668 cc.Icon = t.GetField(FieldUserIconID).Data
1670 if cc.Authorize(accessAnyName) {
1671 cc.UserName = t.GetField(FieldUserName).Data
1674 // the options field is only passed by the client versions > 1.2.3.
1675 options := t.GetField(FieldOptions).Data
1677 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1678 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
1680 flagBitmap.SetBit(flagBitmap, UserFlagRefusePM, optBitmap.Bit(refusePM))
1681 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1683 flagBitmap.SetBit(flagBitmap, UserFlagRefusePChat, optBitmap.Bit(refuseChat))
1684 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1686 // Check auto response
1687 if optBitmap.Bit(autoResponse) == 1 {
1688 cc.AutoReply = t.GetField(FieldAutomaticResponse).Data
1690 cc.AutoReply = []byte{}
1694 for _, c := range sortedClients(cc.Server.Clients) {
1695 res = append(res, *NewTransaction(
1696 TranNotifyChangeUser,
1698 NewField(FieldUserID, *cc.ID),
1699 NewField(FieldUserIconID, cc.Icon),
1700 NewField(FieldUserFlags, cc.Flags),
1701 NewField(FieldUserName, cc.UserName),
1708 // HandleKeepAlive responds to keepalive transactions with an empty reply
1709 // * HL 1.9.2 Client sends keepalive msg every 3 minutes
1710 // * HL 1.2.3 Client doesn't send keepalives
1711 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1712 res = append(res, cc.NewReply(t))
1717 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1718 fullPath, err := readPath(
1719 cc.Server.Config.FileRoot,
1720 t.GetField(FieldFilePath).Data,
1728 if t.GetField(FieldFilePath).Data != nil {
1729 if _, err = fp.Write(t.GetField(FieldFilePath).Data); err != nil {
1734 // Handle special case for drop box folders
1735 if fp.IsDropbox() && !cc.Authorize(accessViewDropBoxes) {
1736 res = append(res, cc.NewErrReply(t, "You are not allowed to view drop boxes."))
1740 fileNames, err := getFileNameList(fullPath, cc.Server.Config.IgnoreFiles)
1745 res = append(res, cc.NewReply(t, fileNames...))
1750 // =================================
1751 // Hotline private chat flow
1752 // =================================
1753 // 1. ClientA sends TranInviteNewChat to server with user ID to invite
1754 // 2. Server creates new ChatID
1755 // 3. Server sends TranInviteToChat to invitee
1756 // 4. Server replies to ClientA with new Chat ID
1758 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1759 // If Accepted is clicked:
1760 // 1. ClientB sends TranJoinChat with FieldChatID
1762 // HandleInviteNewChat invites users to new private chat
1763 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1764 if !cc.Authorize(accessOpenChat) {
1765 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1770 targetID := t.GetField(FieldUserID).Data
1771 newChatID := cc.Server.NewPrivateChat(cc)
1773 // Check if target user has "Refuse private chat" flag
1774 binary.BigEndian.Uint16(targetID)
1775 targetClient := cc.Server.Clients[binary.BigEndian.Uint16(targetID)]
1777 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(targetClient.Flags)))
1778 if flagBitmap.Bit(UserFlagRefusePChat) == 1 {
1783 NewField(FieldData, []byte(string(targetClient.UserName)+" does not accept private chats.")),
1784 NewField(FieldUserName, targetClient.UserName),
1785 NewField(FieldUserID, *targetClient.ID),
1786 NewField(FieldOptions, []byte{0, 2}),
1794 NewField(FieldChatID, newChatID),
1795 NewField(FieldUserName, cc.UserName),
1796 NewField(FieldUserID, *cc.ID),
1803 NewField(FieldChatID, newChatID),
1804 NewField(FieldUserName, cc.UserName),
1805 NewField(FieldUserID, *cc.ID),
1806 NewField(FieldUserIconID, cc.Icon),
1807 NewField(FieldUserFlags, cc.Flags),
1814 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1815 if !cc.Authorize(accessOpenChat) {
1816 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1821 targetID := t.GetField(FieldUserID).Data
1822 chatID := t.GetField(FieldChatID).Data
1828 NewField(FieldChatID, chatID),
1829 NewField(FieldUserName, cc.UserName),
1830 NewField(FieldUserID, *cc.ID),
1836 NewField(FieldChatID, chatID),
1837 NewField(FieldUserName, cc.UserName),
1838 NewField(FieldUserID, *cc.ID),
1839 NewField(FieldUserIconID, cc.Icon),
1840 NewField(FieldUserFlags, cc.Flags),
1847 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1848 chatID := t.GetField(FieldChatID).Data
1849 chatInt := binary.BigEndian.Uint32(chatID)
1851 privChat := cc.Server.PrivateChats[chatInt]
1853 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1855 for _, c := range sortedClients(privChat.ClientConn) {
1860 NewField(FieldChatID, chatID),
1861 NewField(FieldData, resMsg),
1869 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1870 // Fields used in the reply:
1871 // * 115 Chat subject
1872 // * 300 User name with info (Optional)
1873 // * 300 (more user names with info)
1874 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1875 chatID := t.GetField(FieldChatID).Data
1876 chatInt := binary.BigEndian.Uint32(chatID)
1878 privChat := cc.Server.PrivateChats[chatInt]
1880 // Send TranNotifyChatChangeUser to current members of the chat to inform of new user
1881 for _, c := range sortedClients(privChat.ClientConn) {
1884 TranNotifyChatChangeUser,
1886 NewField(FieldChatID, chatID),
1887 NewField(FieldUserName, cc.UserName),
1888 NewField(FieldUserID, *cc.ID),
1889 NewField(FieldUserIconID, cc.Icon),
1890 NewField(FieldUserFlags, cc.Flags),
1895 privChat.ClientConn[cc.uint16ID()] = cc
1897 replyFields := []Field{NewField(FieldChatSubject, []byte(privChat.Subject))}
1898 for _, c := range sortedClients(privChat.ClientConn) {
1903 Name: string(c.UserName),
1906 replyFields = append(replyFields, NewField(FieldUsernameWithInfo, user.Payload()))
1909 res = append(res, cc.NewReply(t, replyFields...))
1913 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1914 // Fields used in the request:
1915 // - 114 FieldChatID
1917 // Reply is not expected.
1918 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1919 chatID := t.GetField(FieldChatID).Data
1920 chatInt := binary.BigEndian.Uint32(chatID)
1922 privChat, ok := cc.Server.PrivateChats[chatInt]
1927 delete(privChat.ClientConn, cc.uint16ID())
1929 // Notify members of the private chat that the user has left
1930 for _, c := range sortedClients(privChat.ClientConn) {
1933 TranNotifyChatDeleteUser,
1935 NewField(FieldChatID, chatID),
1936 NewField(FieldUserID, *cc.ID),
1944 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1945 // Fields used in the request:
1947 // * 115 Chat subject
1948 // Reply is not expected.
1949 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1950 chatID := t.GetField(FieldChatID).Data
1951 chatInt := binary.BigEndian.Uint32(chatID)
1953 privChat := cc.Server.PrivateChats[chatInt]
1954 privChat.Subject = string(t.GetField(FieldChatSubject).Data)
1956 for _, c := range sortedClients(privChat.ClientConn) {
1959 TranNotifyChatSubject,
1961 NewField(FieldChatID, chatID),
1962 NewField(FieldChatSubject, t.GetField(FieldChatSubject).Data),
1970 // HandleMakeAlias makes a file alias using the specified path.
1971 // Fields used in the request:
1974 // 212 File new path Destination path
1976 // Fields used in the reply:
1978 func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1979 if !cc.Authorize(accessMakeAlias) {
1980 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
1983 fileName := t.GetField(FieldFileName).Data
1984 filePath := t.GetField(FieldFilePath).Data
1985 fileNewPath := t.GetField(FieldFileNewPath).Data
1987 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1992 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
1997 cc.logger.Debugw("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
1999 if err := cc.Server.FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
2000 res = append(res, cc.NewErrReply(t, "Error creating alias"))
2004 res = append(res, cc.NewReply(t))
2008 // HandleDownloadBanner handles requests for a new banner from the server
2009 // Fields used in the request:
2011 // Fields used in the reply:
2012 // 107 FieldRefNum Used later for transfer
2013 // 108 FieldTransferSize Size of data to be downloaded
2014 func HandleDownloadBanner(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
2015 fi, err := cc.Server.FS.Stat(filepath.Join(cc.Server.ConfigDir, cc.Server.Config.BannerFile))
2020 ft := cc.newFileTransfer(bannerDownload, []byte{}, []byte{}, make([]byte, 4))
2022 binary.BigEndian.PutUint32(ft.TransferSize, uint32(fi.Size()))
2024 res = append(res, cc.NewReply(t,
2025 NewField(FieldRefNum, ft.refNum[:]),
2026 NewField(FieldTransferSize, ft.TransferSize),