18 type TransactionType struct {
19 Handler func(*ClientConn, *Transaction) ([]Transaction, error) // function for handling the transaction type
20 Name string // Name of transaction as it will appear in logging
21 RequiredFields []requiredField
24 var TransactionHandlers = map[uint16]TransactionType{
30 tranNotifyChangeUser: {
31 Name: "tranNotifyChangeUser",
37 Name: "tranShowAgreement",
40 Name: "tranUserAccess",
42 tranNotifyDeleteUser: {
43 Name: "tranNotifyDeleteUser",
47 Handler: HandleTranAgreed,
51 Handler: HandleChatSend,
52 RequiredFields: []requiredField{
60 Name: "tranDelNewsArt",
61 Handler: HandleDelNewsArt,
64 Name: "tranDelNewsItem",
65 Handler: HandleDelNewsItem,
68 Name: "tranDeleteFile",
69 Handler: HandleDeleteFile,
72 Name: "tranDeleteUser",
73 Handler: HandleDeleteUser,
76 Name: "tranDisconnectUser",
77 Handler: HandleDisconnectUser,
80 Name: "tranDownloadFile",
81 Handler: HandleDownloadFile,
84 Name: "tranDownloadFldr",
85 Handler: HandleDownloadFolder,
87 tranGetClientInfoText: {
88 Name: "tranGetClientInfoText",
89 Handler: HandleGetClientInfoText,
92 Name: "tranGetFileInfo",
93 Handler: HandleGetFileInfo,
95 tranGetFileNameList: {
96 Name: "tranGetFileNameList",
97 Handler: HandleGetFileNameList,
101 Handler: HandleGetMsgs,
103 tranGetNewsArtData: {
104 Name: "tranGetNewsArtData",
105 Handler: HandleGetNewsArtData,
107 tranGetNewsArtNameList: {
108 Name: "tranGetNewsArtNameList",
109 Handler: HandleGetNewsArtNameList,
111 tranGetNewsCatNameList: {
112 Name: "tranGetNewsCatNameList",
113 Handler: HandleGetNewsCatNameList,
117 Handler: HandleGetUser,
119 tranGetUserNameList: {
120 Name: "tranHandleGetUserNameList",
121 Handler: HandleGetUserNameList,
124 Name: "tranInviteNewChat",
125 Handler: HandleInviteNewChat,
128 Name: "tranInviteToChat",
129 Handler: HandleInviteToChat,
132 Name: "tranJoinChat",
133 Handler: HandleJoinChat,
136 Name: "tranKeepAlive",
137 Handler: HandleKeepAlive,
140 Name: "tranJoinChat",
141 Handler: HandleLeaveChat,
144 Name: "tranListUsers",
145 Handler: HandleListUsers,
148 Name: "tranMoveFile",
149 Handler: HandleMoveFile,
152 Name: "tranNewFolder",
153 Handler: HandleNewFolder,
156 Name: "tranNewNewsCat",
157 Handler: HandleNewNewsCat,
160 Name: "tranNewNewsFldr",
161 Handler: HandleNewNewsFldr,
165 Handler: HandleNewUser,
168 Name: "tranUpdateUser",
169 Handler: HandleUpdateUser,
172 Name: "tranOldPostNews",
173 Handler: HandleTranOldPostNews,
176 Name: "tranPostNewsArt",
177 Handler: HandlePostNewsArt,
179 tranRejectChatInvite: {
180 Name: "tranRejectChatInvite",
181 Handler: HandleRejectChatInvite,
183 tranSendInstantMsg: {
184 Name: "tranSendInstantMsg",
185 Handler: HandleSendInstantMsg,
186 RequiredFields: []requiredField{
196 tranSetChatSubject: {
197 Name: "tranSetChatSubject",
198 Handler: HandleSetChatSubject,
201 Name: "tranMakeFileAlias",
202 Handler: HandleMakeAlias,
203 RequiredFields: []requiredField{
204 {ID: fieldFileName, minLen: 1},
205 {ID: fieldFilePath, minLen: 1},
206 {ID: fieldFileNewPath, minLen: 1},
209 tranSetClientUserInfo: {
210 Name: "tranSetClientUserInfo",
211 Handler: HandleSetClientUserInfo,
214 Name: "tranSetFileInfo",
215 Handler: HandleSetFileInfo,
219 Handler: HandleSetUser,
222 Name: "tranUploadFile",
223 Handler: HandleUploadFile,
226 Name: "tranUploadFldr",
227 Handler: HandleUploadFolder,
230 Name: "tranUserBroadcast",
231 Handler: HandleUserBroadcast,
233 tranDownloadBanner: {
234 Name: "tranDownloadBanner",
235 Handler: HandleDownloadBanner,
239 func HandleChatSend(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
240 if !cc.Authorize(accessSendChat) {
241 res = append(res, cc.NewErrReply(t, "You are not allowed to participate in chat."))
245 // Truncate long usernames
246 trunc := fmt.Sprintf("%13s", cc.UserName)
247 formattedMsg := fmt.Sprintf("\r%.14s: %s", trunc, t.GetField(fieldData).Data)
249 // By holding the option key, Hotline chat allows users to send /me formatted messages like:
250 // *** Halcyon does stuff
251 // This is indicated by the presence of the optional field fieldChatOptions set to a value of 1.
252 // Most clients do not send this option for normal chat messages.
253 if t.GetField(fieldChatOptions).Data != nil && bytes.Equal(t.GetField(fieldChatOptions).Data, []byte{0, 1}) {
254 formattedMsg = fmt.Sprintf("\r*** %s %s", cc.UserName, t.GetField(fieldData).Data)
257 // The ChatID field is used to identify messages as belonging to a private chat.
258 // All clients *except* Frogblast omit this field for public chat, but Frogblast sends a value of 00 00 00 00.
259 chatID := t.GetField(fieldChatID).Data
260 if chatID != nil && !bytes.Equal([]byte{0, 0, 0, 0}, chatID) {
261 chatInt := binary.BigEndian.Uint32(chatID)
262 privChat := cc.Server.PrivateChats[chatInt]
264 clients := sortedClients(privChat.ClientConn)
266 // send the message to all connected clients of the private chat
267 for _, c := range clients {
268 res = append(res, *NewTransaction(
271 NewField(fieldChatID, chatID),
272 NewField(fieldData, []byte(formattedMsg)),
278 for _, c := range sortedClients(cc.Server.Clients) {
279 // Filter out clients that do not have the read chat permission
280 if c.Authorize(accessReadChat) {
281 res = append(res, *NewTransaction(tranChatMsg, c.ID, NewField(fieldData, []byte(formattedMsg))))
288 // HandleSendInstantMsg sends instant message to the user on the current server.
289 // Fields used in the request:
293 // One of the following values:
294 // - User message (myOpt_UserMessage = 1)
295 // - Refuse message (myOpt_RefuseMessage = 2)
296 // - Refuse chat (myOpt_RefuseChat = 3)
297 // - Automatic response (myOpt_AutomaticResponse = 4)"
299 // 214 Quoting message Optional
301 // Fields used in the reply:
303 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
304 if !cc.Authorize(accessSendPrivMsg) {
305 res = append(res, cc.NewErrReply(t, "You are not allowed to send private messages."))
309 msg := t.GetField(fieldData)
310 ID := t.GetField(fieldUserID)
312 reply := NewTransaction(
315 NewField(fieldData, msg.Data),
316 NewField(fieldUserName, cc.UserName),
317 NewField(fieldUserID, *cc.ID),
318 NewField(fieldOptions, []byte{0, 1}),
321 // Later versions of Hotline include the original message in the fieldQuotingMsg field so
322 // the receiving client can display both the received message and what it is in reply to
323 if t.GetField(fieldQuotingMsg).Data != nil {
324 reply.Fields = append(reply.Fields, NewField(fieldQuotingMsg, t.GetField(fieldQuotingMsg).Data))
327 id, _ := byteToInt(ID.Data)
328 otherClient, ok := cc.Server.Clients[uint16(id)]
330 return res, errors.New("invalid client ID")
333 // Check if target user has "Refuse private messages" flag
334 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(otherClient.Flags)))
335 if flagBitmap.Bit(userFLagRefusePChat) == 1 {
340 NewField(fieldData, []byte(string(otherClient.UserName)+" does not accept private messages.")),
341 NewField(fieldUserName, otherClient.UserName),
342 NewField(fieldUserID, *otherClient.ID),
343 NewField(fieldOptions, []byte{0, 2}),
347 res = append(res, *reply)
350 // Respond with auto reply if other client has it enabled
351 if len(otherClient.AutoReply) > 0 {
356 NewField(fieldData, otherClient.AutoReply),
357 NewField(fieldUserName, otherClient.UserName),
358 NewField(fieldUserID, *otherClient.ID),
359 NewField(fieldOptions, []byte{0, 1}),
364 res = append(res, cc.NewReply(t))
369 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
370 fileName := t.GetField(fieldFileName).Data
371 filePath := t.GetField(fieldFilePath).Data
373 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
378 fw, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
383 res = append(res, cc.NewReply(t,
384 NewField(fieldFileName, []byte(fw.name)),
385 NewField(fieldFileTypeString, fw.ffo.FlatFileInformationFork.friendlyType()),
386 NewField(fieldFileCreatorString, fw.ffo.FlatFileInformationFork.friendlyCreator()),
387 NewField(fieldFileComment, fw.ffo.FlatFileInformationFork.Comment),
388 NewField(fieldFileType, fw.ffo.FlatFileInformationFork.TypeSignature),
389 NewField(fieldFileCreateDate, fw.ffo.FlatFileInformationFork.CreateDate),
390 NewField(fieldFileModifyDate, fw.ffo.FlatFileInformationFork.ModifyDate),
391 NewField(fieldFileSize, fw.totalSize()),
396 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
397 // Fields used in the request:
399 // * 202 File path Optional
400 // * 211 File new name Optional
401 // * 210 File comment Optional
402 // Fields used in the reply: None
403 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
404 fileName := t.GetField(fieldFileName).Data
405 filePath := t.GetField(fieldFilePath).Data
407 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
412 fi, err := cc.Server.FS.Stat(fullFilePath)
417 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
421 if t.GetField(fieldFileComment).Data != nil {
422 switch mode := fi.Mode(); {
424 if !cc.Authorize(accessSetFolderComment) {
425 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for folders."))
428 case mode.IsRegular():
429 if !cc.Authorize(accessSetFileComment) {
430 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for files."))
435 if err := hlFile.ffo.FlatFileInformationFork.setComment(t.GetField(fieldFileComment).Data); err != nil {
438 w, err := hlFile.infoForkWriter()
442 _, err = w.Write(hlFile.ffo.FlatFileInformationFork.MarshalBinary())
448 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, t.GetField(fieldFileNewName).Data)
453 fileNewName := t.GetField(fieldFileNewName).Data
455 if fileNewName != nil {
456 switch mode := fi.Mode(); {
458 if !cc.Authorize(accessRenameFolder) {
459 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
462 err = os.Rename(fullFilePath, fullNewFilePath)
463 if os.IsNotExist(err) {
464 res = append(res, cc.NewErrReply(t, "Cannot rename folder "+string(fileName)+" because it does not exist or cannot be found."))
467 case mode.IsRegular():
468 if !cc.Authorize(accessRenameFile) {
469 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
472 fileDir, err := readPath(cc.Server.Config.FileRoot, filePath, []byte{})
476 hlFile.name = string(fileNewName)
477 err = hlFile.move(fileDir)
478 if os.IsNotExist(err) {
479 res = append(res, cc.NewErrReply(t, "Cannot rename file "+string(fileName)+" because it does not exist or cannot be found."))
488 res = append(res, cc.NewReply(t))
492 // HandleDeleteFile deletes a file or folder
493 // Fields used in the request:
496 // Fields used in the reply: none
497 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
498 fileName := t.GetField(fieldFileName).Data
499 filePath := t.GetField(fieldFilePath).Data
501 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
506 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
511 fi, err := hlFile.dataFile()
513 res = append(res, cc.NewErrReply(t, "Cannot delete file "+string(fileName)+" because it does not exist or cannot be found."))
517 switch mode := fi.Mode(); {
519 if !cc.Authorize(accessDeleteFolder) {
520 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
523 case mode.IsRegular():
524 if !cc.Authorize(accessDeleteFile) {
525 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
530 if err := hlFile.delete(); err != nil {
534 res = append(res, cc.NewReply(t))
538 // HandleMoveFile moves files or folders. Note: seemingly not documented
539 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
540 fileName := string(t.GetField(fieldFileName).Data)
542 filePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
547 fileNewPath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFileNewPath).Data, nil)
552 cc.logger.Infow("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
554 hlFile, err := newFileWrapper(cc.Server.FS, filePath, 0)
559 fi, err := hlFile.dataFile()
561 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
567 switch mode := fi.Mode(); {
569 if !cc.Authorize(accessMoveFolder) {
570 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
573 case mode.IsRegular():
574 if !cc.Authorize(accessMoveFile) {
575 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
579 if err := hlFile.move(fileNewPath); err != nil {
582 // TODO: handle other possible errors; e.g. fileWrapper delete fails due to fileWrapper permission issue
584 res = append(res, cc.NewReply(t))
588 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
589 if !cc.Authorize(accessCreateFolder) {
590 res = append(res, cc.NewErrReply(t, "You are not allowed to create folders."))
593 folderName := string(t.GetField(fieldFileName).Data)
595 folderName = path.Join("/", folderName)
599 // fieldFilePath is only present for nested paths
600 if t.GetField(fieldFilePath).Data != nil {
602 _, err := newFp.Write(t.GetField(fieldFilePath).Data)
607 for _, pathItem := range newFp.Items {
608 subPath = filepath.Join("/", subPath, string(pathItem.Name))
611 newFolderPath := path.Join(cc.Server.Config.FileRoot, subPath, folderName)
613 // TODO: check path and folder name lengths
615 if _, err := cc.Server.FS.Stat(newFolderPath); !os.IsNotExist(err) {
616 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that name.", folderName)
617 return []Transaction{cc.NewErrReply(t, msg)}, nil
620 // TODO: check for disallowed characters to maintain compatibility for original client
622 if err := cc.Server.FS.Mkdir(newFolderPath, 0777); err != nil {
623 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
624 return []Transaction{cc.NewErrReply(t, msg)}, nil
627 res = append(res, cc.NewReply(t))
631 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
632 if !cc.Authorize(accessModifyUser) {
633 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
637 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
638 userName := string(t.GetField(fieldUserName).Data)
640 newAccessLvl := t.GetField(fieldUserAccess).Data
642 account := cc.Server.Accounts[login]
643 account.Name = userName
644 copy(account.Access[:], newAccessLvl)
646 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
647 // not include fieldUserPassword
648 if t.GetField(fieldUserPassword).Data == nil {
649 account.Password = hashAndSalt([]byte(""))
651 if len(t.GetField(fieldUserPassword).Data) > 1 {
652 account.Password = hashAndSalt(t.GetField(fieldUserPassword).Data)
655 out, err := yaml.Marshal(&account)
659 if err := os.WriteFile(filepath.Join(cc.Server.ConfigDir, "Users", login+".yaml"), out, 0666); err != nil {
663 // Notify connected clients logged in as the user of the new access level
664 for _, c := range cc.Server.Clients {
665 if c.Account.Login == login {
666 // Note: comment out these two lines to test server-side deny messages
667 newT := NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, newAccessLvl))
668 res = append(res, *newT)
670 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
671 if c.Authorize(accessDisconUser) {
672 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 1)
674 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 0)
676 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
678 c.Account.Access = account.Access
681 tranNotifyChangeUser,
682 NewField(fieldUserID, *c.ID),
683 NewField(fieldUserFlags, c.Flags),
684 NewField(fieldUserName, c.UserName),
685 NewField(fieldUserIconID, c.Icon),
690 res = append(res, cc.NewReply(t))
694 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
695 if !cc.Authorize(accessOpenUser) {
696 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
700 account := cc.Server.Accounts[string(t.GetField(fieldUserLogin).Data)]
702 res = append(res, cc.NewErrReply(t, "Account does not exist."))
706 res = append(res, cc.NewReply(t,
707 NewField(fieldUserName, []byte(account.Name)),
708 NewField(fieldUserLogin, negateString(t.GetField(fieldUserLogin).Data)),
709 NewField(fieldUserPassword, []byte(account.Password)),
710 NewField(fieldUserAccess, account.Access[:]),
715 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
716 if !cc.Authorize(accessOpenUser) {
717 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
721 var userFields []Field
722 for _, acc := range cc.Server.Accounts {
723 b := make([]byte, 0, 100)
724 n, err := acc.Read(b)
729 userFields = append(userFields, NewField(fieldData, b[:n]))
732 res = append(res, cc.NewReply(t, userFields...))
736 // HandleUpdateUser is used by the v1.5+ multi-user editor to perform account editing for multiple users at a time.
737 // An update can be a mix of these actions:
740 // * Modify user (including renaming the account login)
742 // The Transaction sent by the client includes one data field per user that was modified. This data field in turn
743 // contains another data field encoded in its payload with a varying number of sub fields depending on which action is
744 // performed. This seems to be the only place in the Hotline protocol where a data field contains another data field.
745 func HandleUpdateUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
746 for _, field := range t.Fields {
747 subFields, err := ReadFields(field.Data[0:2], field.Data[2:])
752 if len(subFields) == 1 {
753 login := DecodeUserString(getField(fieldData, &subFields).Data)
754 cc.logger.Infow("DeleteUser", "login", login)
756 if !cc.Authorize(accessDeleteUser) {
757 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
761 if err := cc.Server.DeleteUser(login); err != nil {
767 login := DecodeUserString(getField(fieldUserLogin, &subFields).Data)
769 // check if the login dataFile; if so, we know we are updating an existing user
770 if acc, ok := cc.Server.Accounts[login]; ok {
771 cc.logger.Infow("UpdateUser", "login", login)
773 // account dataFile, so this is an update action
774 if !cc.Authorize(accessModifyUser) {
775 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
779 if getField(fieldUserPassword, &subFields) != nil {
780 newPass := getField(fieldUserPassword, &subFields).Data
781 acc.Password = hashAndSalt(newPass)
783 acc.Password = hashAndSalt([]byte(""))
786 if getField(fieldUserAccess, &subFields) != nil {
787 copy(acc.Access[:], getField(fieldUserAccess, &subFields).Data)
790 err = cc.Server.UpdateUser(
791 DecodeUserString(getField(fieldData, &subFields).Data),
792 DecodeUserString(getField(fieldUserLogin, &subFields).Data),
793 string(getField(fieldUserName, &subFields).Data),
801 cc.logger.Infow("CreateUser", "login", login)
803 if !cc.Authorize(accessCreateUser) {
804 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
808 newAccess := accessBitmap{}
809 copy(newAccess[:], getField(fieldUserAccess, &subFields).Data[:])
811 // Prevent account from creating new account with greater permission
812 for i := 0; i < 64; i++ {
813 if newAccess.IsSet(i) {
814 if !cc.Authorize(i) {
815 return append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself.")), err
820 err := cc.Server.NewUser(login, string(getField(fieldUserName, &subFields).Data), string(getField(fieldUserPassword, &subFields).Data), newAccess)
822 return []Transaction{}, err
827 res = append(res, cc.NewReply(t))
831 // HandleNewUser creates a new user account
832 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
833 if !cc.Authorize(accessCreateUser) {
834 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
838 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
840 // If the account already dataFile, reply with an error
841 if _, ok := cc.Server.Accounts[login]; ok {
842 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
846 newAccess := accessBitmap{}
847 copy(newAccess[:], t.GetField(fieldUserAccess).Data[:])
849 // Prevent account from creating new account with greater permission
850 for i := 0; i < 64; i++ {
851 if newAccess.IsSet(i) {
852 if !cc.Authorize(i) {
853 res = append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself."))
859 if err := cc.Server.NewUser(login, string(t.GetField(fieldUserName).Data), string(t.GetField(fieldUserPassword).Data), newAccess); err != nil {
860 return []Transaction{}, err
863 res = append(res, cc.NewReply(t))
867 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
868 if !cc.Authorize(accessDeleteUser) {
869 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
873 // TODO: Handle case where account doesn't exist; e.g. delete race condition
874 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
876 if err := cc.Server.DeleteUser(login); err != nil {
880 res = append(res, cc.NewReply(t))
884 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
885 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
886 if !cc.Authorize(accessBroadcast) {
887 res = append(res, cc.NewErrReply(t, "You are not allowed to send broadcast messages."))
893 NewField(fieldData, t.GetField(tranGetMsgs).Data),
894 NewField(fieldChatOptions, []byte{0}),
897 res = append(res, cc.NewReply(t))
901 // HandleGetClientInfoText returns user information for the specific user.
903 // Fields used in the request:
906 // Fields used in the reply:
908 // 101 Data User info text string
909 func HandleGetClientInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
910 if !cc.Authorize(accessGetClientInfo) {
911 res = append(res, cc.NewErrReply(t, "You are not allowed to get client info."))
915 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
917 clientConn := cc.Server.Clients[uint16(clientID)]
918 if clientConn == nil {
919 return append(res, cc.NewErrReply(t, "User not found.")), err
922 res = append(res, cc.NewReply(t,
923 NewField(fieldData, []byte(clientConn.String())),
924 NewField(fieldUserName, clientConn.UserName),
929 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
930 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
935 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
938 if t.GetField(fieldUserName).Data != nil {
939 if cc.Authorize(accessAnyName) {
940 cc.UserName = t.GetField(fieldUserName).Data
942 cc.UserName = []byte(cc.Account.Name)
946 cc.Icon = t.GetField(fieldUserIconID).Data
948 cc.logger = cc.logger.With("name", string(cc.UserName))
949 cc.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(cc.Version); return i }()))
951 options := t.GetField(fieldOptions).Data
952 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
954 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
956 // Check refuse private PM option
957 if optBitmap.Bit(refusePM) == 1 {
958 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
959 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
962 // Check refuse private chat option
963 if optBitmap.Bit(refuseChat) == 1 {
964 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
965 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
968 // Check auto response
969 if optBitmap.Bit(autoResponse) == 1 {
970 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
972 cc.AutoReply = []byte{}
975 trans := cc.notifyOthers(
977 tranNotifyChangeUser, nil,
978 NewField(fieldUserName, cc.UserName),
979 NewField(fieldUserID, *cc.ID),
980 NewField(fieldUserIconID, cc.Icon),
981 NewField(fieldUserFlags, cc.Flags),
984 res = append(res, trans...)
986 if cc.Server.Config.BannerFile != "" {
987 res = append(res, *NewTransaction(tranServerBanner, cc.ID, NewField(fieldBannerType, []byte("JPEG"))))
990 res = append(res, cc.NewReply(t))
995 const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
996 // "Mon, 02 Jan 2006 15:04:05 MST"
998 const defaultNewsTemplate = `From %s (%s):
1002 __________________________________________________________`
1004 // HandleTranOldPostNews updates the flat news
1005 // Fields used in this request:
1007 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1008 if !cc.Authorize(accessNewsPostArt) {
1009 res = append(res, cc.NewErrReply(t, "You are not allowed to post news."))
1013 cc.Server.flatNewsMux.Lock()
1014 defer cc.Server.flatNewsMux.Unlock()
1016 newsDateTemplate := defaultNewsDateFormat
1017 if cc.Server.Config.NewsDateFormat != "" {
1018 newsDateTemplate = cc.Server.Config.NewsDateFormat
1021 newsTemplate := defaultNewsTemplate
1022 if cc.Server.Config.NewsDelimiter != "" {
1023 newsTemplate = cc.Server.Config.NewsDelimiter
1026 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
1027 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
1029 // update news in memory
1030 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
1032 // update news on disk
1033 if err := cc.Server.FS.WriteFile(filepath.Join(cc.Server.ConfigDir, "MessageBoard.txt"), cc.Server.FlatNews, 0644); err != nil {
1037 // Notify all clients of updated news
1040 NewField(fieldData, []byte(newsPost)),
1043 res = append(res, cc.NewReply(t))
1047 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1048 if !cc.Authorize(accessDisconUser) {
1049 res = append(res, cc.NewErrReply(t, "You are not allowed to disconnect users."))
1053 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
1055 if clientConn.Authorize(accessCannotBeDiscon) {
1056 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
1060 // If fieldOptions is set, then the client IP is banned in addition to disconnected.
1061 // 00 01 = temporary ban
1062 // 00 02 = permanent ban
1063 if t.GetField(fieldOptions).Data != nil {
1064 switch t.GetField(fieldOptions).Data[1] {
1066 // send message: "You are temporarily banned on this server"
1067 cc.logger.Infow("Disconnect & temporarily ban " + string(clientConn.UserName))
1069 res = append(res, *NewTransaction(
1072 NewField(fieldData, []byte("You are temporarily banned on this server")),
1073 NewField(fieldChatOptions, []byte{0, 0}),
1076 banUntil := time.Now().Add(tempBanDuration)
1077 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = &banUntil
1078 cc.Server.writeBanList()
1080 // send message: "You are permanently banned on this server"
1081 cc.logger.Infow("Disconnect & ban " + string(clientConn.UserName))
1083 res = append(res, *NewTransaction(
1086 NewField(fieldData, []byte("You are permanently banned on this server")),
1087 NewField(fieldChatOptions, []byte{0, 0}),
1090 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = nil
1091 cc.Server.writeBanList()
1095 // TODO: remove this awful hack
1097 time.Sleep(1 * time.Second)
1098 clientConn.Disconnect()
1101 return append(res, cc.NewReply(t)), err
1104 // HandleGetNewsCatNameList returns a list of news categories for a path
1105 // Fields used in the request:
1106 // 325 News path (Optional)
1107 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1108 if !cc.Authorize(accessNewsReadArt) {
1109 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1113 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1114 cats := cc.Server.GetNewsCatByPath(pathStrs)
1116 // To store the keys in slice in sorted order
1117 keys := make([]string, len(cats))
1119 for k := range cats {
1125 var fieldData []Field
1126 for _, k := range keys {
1128 b, _ := cat.MarshalBinary()
1129 fieldData = append(fieldData, NewField(
1130 fieldNewsCatListData15,
1135 res = append(res, cc.NewReply(t, fieldData...))
1139 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1140 if !cc.Authorize(accessNewsCreateCat) {
1141 res = append(res, cc.NewErrReply(t, "You are not allowed to create news categories."))
1145 name := string(t.GetField(fieldNewsCatName).Data)
1146 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1148 cats := cc.Server.GetNewsCatByPath(pathStrs)
1149 cats[name] = NewsCategoryListData15{
1152 Articles: map[uint32]*NewsArtData{},
1153 SubCats: make(map[string]NewsCategoryListData15),
1156 if err := cc.Server.writeThreadedNews(); err != nil {
1159 res = append(res, cc.NewReply(t))
1163 // Fields used in the request:
1164 // 322 News category name
1166 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1167 if !cc.Authorize(accessNewsCreateFldr) {
1168 res = append(res, cc.NewErrReply(t, "You are not allowed to create news folders."))
1172 name := string(t.GetField(fieldFileName).Data)
1173 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1175 cc.logger.Infof("Creating new news folder %s", name)
1177 cats := cc.Server.GetNewsCatByPath(pathStrs)
1178 cats[name] = NewsCategoryListData15{
1181 Articles: map[uint32]*NewsArtData{},
1182 SubCats: make(map[string]NewsCategoryListData15),
1184 if err := cc.Server.writeThreadedNews(); err != nil {
1187 res = append(res, cc.NewReply(t))
1191 // HandleGetNewsArtData gets the list of article names at the specified news path.
1193 // Fields used in the request:
1194 // 325 News path Optional
1196 // Fields used in the reply:
1197 // 321 News article list data Optional
1198 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1199 if !cc.Authorize(accessNewsReadArt) {
1200 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1203 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1205 var cat NewsCategoryListData15
1206 cats := cc.Server.ThreadedNews.Categories
1208 for _, fp := range pathStrs {
1210 cats = cats[fp].SubCats
1213 nald := cat.GetNewsArtListData()
1215 res = append(res, cc.NewReply(t, NewField(fieldNewsArtListData, nald.Payload())))
1219 // HandleGetNewsArtData requests information about the specific news article.
1220 // Fields used in the request:
1224 // 326 News article ID
1225 // 327 News article data flavor
1227 // Fields used in the reply:
1228 // 328 News article title
1229 // 329 News article poster
1230 // 330 News article date
1231 // 331 Previous article ID
1232 // 332 Next article ID
1233 // 335 Parent article ID
1234 // 336 First child article ID
1235 // 327 News article data flavor "Should be “text/plain”
1236 // 333 News article data Optional (if data flavor is “text/plain”)
1237 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1238 if !cc.Authorize(accessNewsReadArt) {
1239 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1243 var cat NewsCategoryListData15
1244 cats := cc.Server.ThreadedNews.Categories
1246 for _, fp := range ReadNewsPath(t.GetField(fieldNewsPath).Data) {
1248 cats = cats[fp].SubCats
1251 // The official Hotline clients will send the article ID as 2 bytes if possible, but
1252 // some third party clients such as Frogblast and Heildrun will always send 4 bytes
1253 convertedID, err := byteToInt(t.GetField(fieldNewsArtID).Data)
1258 art := cat.Articles[uint32(convertedID)]
1260 res = append(res, cc.NewReply(t))
1264 res = append(res, cc.NewReply(t,
1265 NewField(fieldNewsArtTitle, []byte(art.Title)),
1266 NewField(fieldNewsArtPoster, []byte(art.Poster)),
1267 NewField(fieldNewsArtDate, art.Date),
1268 NewField(fieldNewsArtPrevArt, art.PrevArt),
1269 NewField(fieldNewsArtNextArt, art.NextArt),
1270 NewField(fieldNewsArtParentArt, art.ParentArt),
1271 NewField(fieldNewsArt1stChildArt, art.FirstChildArt),
1272 NewField(fieldNewsArtDataFlav, []byte("text/plain")),
1273 NewField(fieldNewsArtData, []byte(art.Data)),
1278 // HandleDelNewsItem deletes an existing threaded news folder or category from the server.
1279 // Fields used in the request:
1281 // Fields used in the reply:
1283 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1284 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1286 cats := cc.Server.ThreadedNews.Categories
1287 delName := pathStrs[len(pathStrs)-1]
1288 if len(pathStrs) > 1 {
1289 for _, fp := range pathStrs[0 : len(pathStrs)-1] {
1290 cats = cats[fp].SubCats
1294 if bytes.Equal(cats[delName].Type, []byte{0, 3}) {
1295 if !cc.Authorize(accessNewsDeleteCat) {
1296 return append(res, cc.NewErrReply(t, "You are not allowed to delete news categories.")), nil
1299 if !cc.Authorize(accessNewsDeleteFldr) {
1300 return append(res, cc.NewErrReply(t, "You are not allowed to delete news folders.")), nil
1304 delete(cats, delName)
1306 if err := cc.Server.writeThreadedNews(); err != nil {
1310 return append(res, cc.NewReply(t)), nil
1313 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1314 if !cc.Authorize(accessNewsDeleteArt) {
1315 res = append(res, cc.NewErrReply(t, "You are not allowed to delete news articles."))
1321 // 326 News article ID
1322 // 337 News article – recursive delete Delete child articles (1) or not (0)
1323 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1324 ID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1326 // TODO: Delete recursive
1327 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1329 catName := pathStrs[len(pathStrs)-1]
1330 cat := cats[catName]
1332 delete(cat.Articles, uint32(ID))
1335 if err := cc.Server.writeThreadedNews(); err != nil {
1339 res = append(res, cc.NewReply(t))
1345 // 326 News article ID ID of the parent article?
1346 // 328 News article title
1347 // 334 News article flags
1348 // 327 News article data flavor Currently “text/plain”
1349 // 333 News article data
1350 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1351 if !cc.Authorize(accessNewsPostArt) {
1352 res = append(res, cc.NewErrReply(t, "You are not allowed to post news articles."))
1356 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1357 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1359 catName := pathStrs[len(pathStrs)-1]
1360 cat := cats[catName]
1362 newArt := NewsArtData{
1363 Title: string(t.GetField(fieldNewsArtTitle).Data),
1364 Poster: string(cc.UserName),
1365 Date: toHotlineTime(time.Now()),
1366 PrevArt: []byte{0, 0, 0, 0},
1367 NextArt: []byte{0, 0, 0, 0},
1368 ParentArt: append([]byte{0, 0}, t.GetField(fieldNewsArtID).Data...),
1369 FirstChildArt: []byte{0, 0, 0, 0},
1370 DataFlav: []byte("text/plain"),
1371 Data: string(t.GetField(fieldNewsArtData).Data),
1375 for k := range cat.Articles {
1376 keys = append(keys, int(k))
1382 prevID := uint32(keys[len(keys)-1])
1385 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1387 // Set next article ID
1388 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1391 // Update parent article with first child reply
1392 parentID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1394 parentArt := cat.Articles[uint32(parentID)]
1396 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1397 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1401 cat.Articles[nextID] = &newArt
1404 if err := cc.Server.writeThreadedNews(); err != nil {
1408 res = append(res, cc.NewReply(t))
1412 // HandleGetMsgs returns the flat news data
1413 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1414 if !cc.Authorize(accessNewsReadArt) {
1415 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1419 res = append(res, cc.NewReply(t, NewField(fieldData, cc.Server.FlatNews)))
1424 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1425 if !cc.Authorize(accessDownloadFile) {
1426 res = append(res, cc.NewErrReply(t, "You are not allowed to download files."))
1430 fileName := t.GetField(fieldFileName).Data
1431 filePath := t.GetField(fieldFilePath).Data
1432 resumeData := t.GetField(fieldFileResumeData).Data
1434 var dataOffset int64
1435 var frd FileResumeData
1436 if resumeData != nil {
1437 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1440 // TODO: handle rsrc fork offset
1441 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1444 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1449 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, dataOffset)
1454 xferSize := hlFile.ffo.TransferSize(0)
1456 ft := cc.newFileTransfer(FileDownload, fileName, filePath, xferSize)
1458 // TODO: refactor to remove this
1459 if resumeData != nil {
1460 var frd FileResumeData
1461 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1464 ft.fileResumeData = &frd
1467 // Optional field for when a HL v1.5+ client requests file preview
1468 // Used only for TEXT, JPEG, GIFF, BMP or PICT files
1469 // The value will always be 2
1470 if t.GetField(fieldFileTransferOptions).Data != nil {
1471 ft.options = t.GetField(fieldFileTransferOptions).Data
1472 xferSize = hlFile.ffo.FlatFileDataForkHeader.DataSize[:]
1475 res = append(res, cc.NewReply(t,
1476 NewField(fieldRefNum, ft.refNum[:]),
1477 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1478 NewField(fieldTransferSize, xferSize),
1479 NewField(fieldFileSize, hlFile.ffo.FlatFileDataForkHeader.DataSize[:]),
1485 // Download all files from the specified folder and sub-folders
1486 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1487 if !cc.Authorize(accessDownloadFile) {
1488 res = append(res, cc.NewErrReply(t, "You are not allowed to download folders."))
1492 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
1497 transferSize, err := CalcTotalSize(fullFilePath)
1501 itemCount, err := CalcItemCount(fullFilePath)
1506 fileTransfer := cc.newFileTransfer(FolderDownload, t.GetField(fieldFileName).Data, t.GetField(fieldFilePath).Data, transferSize)
1509 _, err = fp.Write(t.GetField(fieldFilePath).Data)
1514 res = append(res, cc.NewReply(t,
1515 NewField(fieldRefNum, fileTransfer.ReferenceNumber),
1516 NewField(fieldTransferSize, transferSize),
1517 NewField(fieldFolderItemCount, itemCount),
1518 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1523 // Upload all files from the local folder and its subfolders to the specified path on the server
1524 // Fields used in the request
1527 // 108 transfer size Total size of all items in the folder
1528 // 220 Folder item count
1529 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1530 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1532 if t.GetField(fieldFilePath).Data != nil {
1533 if _, err = fp.Write(t.GetField(fieldFilePath).Data); err != nil {
1538 // Handle special cases for Upload and Drop Box folders
1539 if !cc.Authorize(accessUploadAnywhere) {
1540 if !fp.IsUploadDir() && !fp.IsDropbox() {
1541 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))))
1546 fileTransfer := cc.newFileTransfer(FolderUpload,
1547 t.GetField(fieldFileName).Data,
1548 t.GetField(fieldFilePath).Data,
1549 t.GetField(fieldTransferSize).Data,
1552 fileTransfer.FolderItemCount = t.GetField(fieldFolderItemCount).Data
1554 res = append(res, cc.NewReply(t, NewField(fieldRefNum, fileTransfer.ReferenceNumber)))
1559 // Fields used in the request:
1562 // 204 File transfer options "Optional
1563 // Used only to resume download, currently has value 2"
1564 // 108 File transfer size "Optional used if download is not resumed"
1565 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1566 if !cc.Authorize(accessUploadFile) {
1567 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1571 fileName := t.GetField(fieldFileName).Data
1572 filePath := t.GetField(fieldFilePath).Data
1573 transferOptions := t.GetField(fieldFileTransferOptions).Data
1574 transferSize := t.GetField(fieldTransferSize).Data // not sent for resume
1577 if filePath != nil {
1578 if _, err = fp.Write(filePath); err != nil {
1583 // Handle special cases for Upload and Drop Box folders
1584 if !cc.Authorize(accessUploadAnywhere) {
1585 if !fp.IsUploadDir() && !fp.IsDropbox() {
1586 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))))
1590 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1595 if _, err := cc.Server.FS.Stat(fullFilePath); err == nil {
1596 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))))
1600 ft := cc.newFileTransfer(FileUpload, fileName, filePath, transferSize)
1602 replyT := cc.NewReply(t, NewField(fieldRefNum, ft.ReferenceNumber))
1604 // client has requested to resume a partially transferred file
1605 if transferOptions != nil {
1607 fileInfo, err := cc.Server.FS.Stat(fullFilePath + incompleteFileSuffix)
1612 offset := make([]byte, 4)
1613 binary.BigEndian.PutUint32(offset, uint32(fileInfo.Size()))
1615 fileResumeData := NewFileResumeData([]ForkInfoList{
1616 *NewForkInfoList(offset),
1619 b, _ := fileResumeData.BinaryMarshal()
1621 ft.TransferSize = offset
1623 replyT.Fields = append(replyT.Fields, NewField(fieldFileResumeData, b))
1626 res = append(res, replyT)
1630 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1631 if len(t.GetField(fieldUserIconID).Data) == 4 {
1632 cc.Icon = t.GetField(fieldUserIconID).Data[2:]
1634 cc.Icon = t.GetField(fieldUserIconID).Data
1636 if cc.Authorize(accessAnyName) {
1637 cc.UserName = t.GetField(fieldUserName).Data
1640 // the options field is only passed by the client versions > 1.2.3.
1641 options := t.GetField(fieldOptions).Data
1643 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1644 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
1646 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, optBitmap.Bit(refusePM))
1647 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1649 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, optBitmap.Bit(refuseChat))
1650 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1652 // Check auto response
1653 if optBitmap.Bit(autoResponse) == 1 {
1654 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
1656 cc.AutoReply = []byte{}
1660 for _, c := range sortedClients(cc.Server.Clients) {
1661 res = append(res, *NewTransaction(
1662 tranNotifyChangeUser,
1664 NewField(fieldUserID, *cc.ID),
1665 NewField(fieldUserIconID, cc.Icon),
1666 NewField(fieldUserFlags, cc.Flags),
1667 NewField(fieldUserName, cc.UserName),
1674 // HandleKeepAlive responds to keepalive transactions with an empty reply
1675 // * HL 1.9.2 Client sends keepalive msg every 3 minutes
1676 // * HL 1.2.3 Client doesn't send keepalives
1677 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1678 res = append(res, cc.NewReply(t))
1683 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1684 fullPath, err := readPath(
1685 cc.Server.Config.FileRoot,
1686 t.GetField(fieldFilePath).Data,
1694 if t.GetField(fieldFilePath).Data != nil {
1695 if _, err = fp.Write(t.GetField(fieldFilePath).Data); err != nil {
1700 // Handle special case for drop box folders
1701 if fp.IsDropbox() && !cc.Authorize(accessViewDropBoxes) {
1702 res = append(res, cc.NewErrReply(t, "You are not allowed to view drop boxes."))
1706 fileNames, err := getFileNameList(fullPath, cc.Server.Config.IgnoreFiles)
1711 res = append(res, cc.NewReply(t, fileNames...))
1716 // =================================
1717 // Hotline private chat flow
1718 // =================================
1719 // 1. ClientA sends tranInviteNewChat to server with user ID to invite
1720 // 2. Server creates new ChatID
1721 // 3. Server sends tranInviteToChat to invitee
1722 // 4. Server replies to ClientA with new Chat ID
1724 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1725 // If Accepted is clicked:
1726 // 1. ClientB sends tranJoinChat with fieldChatID
1728 // HandleInviteNewChat invites users to new private chat
1729 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1730 if !cc.Authorize(accessOpenChat) {
1731 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1736 targetID := t.GetField(fieldUserID).Data
1737 newChatID := cc.Server.NewPrivateChat(cc)
1739 // Check if target user has "Refuse private chat" flag
1740 binary.BigEndian.Uint16(targetID)
1741 targetClient := cc.Server.Clients[binary.BigEndian.Uint16(targetID)]
1743 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(targetClient.Flags)))
1744 if flagBitmap.Bit(userFLagRefusePChat) == 1 {
1749 NewField(fieldData, []byte(string(targetClient.UserName)+" does not accept private chats.")),
1750 NewField(fieldUserName, targetClient.UserName),
1751 NewField(fieldUserID, *targetClient.ID),
1752 NewField(fieldOptions, []byte{0, 2}),
1760 NewField(fieldChatID, newChatID),
1761 NewField(fieldUserName, cc.UserName),
1762 NewField(fieldUserID, *cc.ID),
1769 NewField(fieldChatID, newChatID),
1770 NewField(fieldUserName, cc.UserName),
1771 NewField(fieldUserID, *cc.ID),
1772 NewField(fieldUserIconID, cc.Icon),
1773 NewField(fieldUserFlags, cc.Flags),
1780 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1781 if !cc.Authorize(accessOpenChat) {
1782 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1787 targetID := t.GetField(fieldUserID).Data
1788 chatID := t.GetField(fieldChatID).Data
1794 NewField(fieldChatID, chatID),
1795 NewField(fieldUserName, cc.UserName),
1796 NewField(fieldUserID, *cc.ID),
1802 NewField(fieldChatID, chatID),
1803 NewField(fieldUserName, cc.UserName),
1804 NewField(fieldUserID, *cc.ID),
1805 NewField(fieldUserIconID, cc.Icon),
1806 NewField(fieldUserFlags, cc.Flags),
1813 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1814 chatID := t.GetField(fieldChatID).Data
1815 chatInt := binary.BigEndian.Uint32(chatID)
1817 privChat := cc.Server.PrivateChats[chatInt]
1819 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1821 for _, c := range sortedClients(privChat.ClientConn) {
1826 NewField(fieldChatID, chatID),
1827 NewField(fieldData, resMsg),
1835 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1836 // Fields used in the reply:
1837 // * 115 Chat subject
1838 // * 300 User name with info (Optional)
1839 // * 300 (more user names with info)
1840 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1841 chatID := t.GetField(fieldChatID).Data
1842 chatInt := binary.BigEndian.Uint32(chatID)
1844 privChat := cc.Server.PrivateChats[chatInt]
1846 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1847 for _, c := range sortedClients(privChat.ClientConn) {
1850 tranNotifyChatChangeUser,
1852 NewField(fieldChatID, chatID),
1853 NewField(fieldUserName, cc.UserName),
1854 NewField(fieldUserID, *cc.ID),
1855 NewField(fieldUserIconID, cc.Icon),
1856 NewField(fieldUserFlags, cc.Flags),
1861 privChat.ClientConn[cc.uint16ID()] = cc
1863 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1864 for _, c := range sortedClients(privChat.ClientConn) {
1869 Name: string(c.UserName),
1872 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1875 res = append(res, cc.NewReply(t, replyFields...))
1879 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1880 // Fields used in the request:
1881 // - 114 fieldChatID
1883 // Reply is not expected.
1884 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1885 chatID := t.GetField(fieldChatID).Data
1886 chatInt := binary.BigEndian.Uint32(chatID)
1888 privChat, ok := cc.Server.PrivateChats[chatInt]
1893 delete(privChat.ClientConn, cc.uint16ID())
1895 // Notify members of the private chat that the user has left
1896 for _, c := range sortedClients(privChat.ClientConn) {
1899 tranNotifyChatDeleteUser,
1901 NewField(fieldChatID, chatID),
1902 NewField(fieldUserID, *cc.ID),
1910 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1911 // Fields used in the request:
1913 // * 115 Chat subject Chat subject string
1914 // Reply is not expected.
1915 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1916 chatID := t.GetField(fieldChatID).Data
1917 chatInt := binary.BigEndian.Uint32(chatID)
1919 privChat := cc.Server.PrivateChats[chatInt]
1920 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1922 for _, c := range sortedClients(privChat.ClientConn) {
1925 tranNotifyChatSubject,
1927 NewField(fieldChatID, chatID),
1928 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),
1936 // HandleMakeAlias makes a filer alias using the specified path.
1937 // Fields used in the request:
1940 // 212 File new path Destination path
1942 // Fields used in the reply:
1944 func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1945 if !cc.Authorize(accessMakeAlias) {
1946 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
1949 fileName := t.GetField(fieldFileName).Data
1950 filePath := t.GetField(fieldFilePath).Data
1951 fileNewPath := t.GetField(fieldFileNewPath).Data
1953 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1958 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
1963 cc.logger.Debugw("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
1965 if err := cc.Server.FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
1966 res = append(res, cc.NewErrReply(t, "Error creating alias"))
1970 res = append(res, cc.NewReply(t))
1974 // HandleDownloadBanner handles requests for a new banner from the server
1975 // Fields used in the request:
1977 // Fields used in the reply:
1978 // 107 fieldRefNum Used later for transfer
1979 // 108 fieldTransferSize Size of data to be downloaded
1980 func HandleDownloadBanner(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1981 fi, err := cc.Server.FS.Stat(filepath.Join(cc.Server.ConfigDir, cc.Server.Config.BannerFile))
1986 ft := cc.newFileTransfer(bannerDownload, []byte{}, []byte{}, make([]byte, 4))
1988 binary.BigEndian.PutUint32(ft.TransferSize, uint32(fi.Size()))
1990 res = append(res, cc.NewReply(t,
1991 NewField(fieldRefNum, ft.refNum[:]),
1992 NewField(fieldTransferSize, ft.TransferSize),