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 in the transaction payload
252 if t.GetField(fieldChatOptions).Data != nil {
253 formattedMsg = fmt.Sprintf("\r*** %s %s", cc.UserName, t.GetField(fieldData).Data)
256 chatID := t.GetField(fieldChatID).Data
257 // a non-nil chatID indicates the message belongs to a private chat
259 chatInt := binary.BigEndian.Uint32(chatID)
260 privChat := cc.Server.PrivateChats[chatInt]
262 clients := sortedClients(privChat.ClientConn)
264 // send the message to all connected clients of the private chat
265 for _, c := range clients {
266 res = append(res, *NewTransaction(
269 NewField(fieldChatID, chatID),
270 NewField(fieldData, []byte(formattedMsg)),
276 for _, c := range sortedClients(cc.Server.Clients) {
277 // Filter out clients that do not have the read chat permission
278 if c.Authorize(accessReadChat) {
279 res = append(res, *NewTransaction(tranChatMsg, c.ID, NewField(fieldData, []byte(formattedMsg))))
286 // HandleSendInstantMsg sends instant message to the user on the current server.
287 // Fields used in the request:
290 // One of the following values:
291 // - User message (myOpt_UserMessage = 1)
292 // - Refuse message (myOpt_RefuseMessage = 2)
293 // - Refuse chat (myOpt_RefuseChat = 3)
294 // - Automatic response (myOpt_AutomaticResponse = 4)"
296 // 214 Quoting message Optional
298 // Fields used in the reply:
300 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
301 if !cc.Authorize(accessSendPrivMsg) {
302 res = append(res, cc.NewErrReply(t, "You are not allowed to send private messages."))
306 msg := t.GetField(fieldData)
307 ID := t.GetField(fieldUserID)
309 reply := NewTransaction(
312 NewField(fieldData, msg.Data),
313 NewField(fieldUserName, cc.UserName),
314 NewField(fieldUserID, *cc.ID),
315 NewField(fieldOptions, []byte{0, 1}),
318 // Later versions of Hotline include the original message in the fieldQuotingMsg field so
319 // the receiving client can display both the received message and what it is in reply to
320 if t.GetField(fieldQuotingMsg).Data != nil {
321 reply.Fields = append(reply.Fields, NewField(fieldQuotingMsg, t.GetField(fieldQuotingMsg).Data))
324 res = append(res, *reply)
326 id, _ := byteToInt(ID.Data)
327 otherClient, ok := cc.Server.Clients[uint16(id)]
329 return res, errors.New("invalid client ID")
332 // Respond with auto reply if other client has it enabled
333 if len(otherClient.AutoReply) > 0 {
338 NewField(fieldData, otherClient.AutoReply),
339 NewField(fieldUserName, otherClient.UserName),
340 NewField(fieldUserID, *otherClient.ID),
341 NewField(fieldOptions, []byte{0, 1}),
346 res = append(res, cc.NewReply(t))
351 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
352 fileName := t.GetField(fieldFileName).Data
353 filePath := t.GetField(fieldFilePath).Data
355 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
360 fw, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
365 res = append(res, cc.NewReply(t,
366 NewField(fieldFileName, []byte(fw.name)),
367 NewField(fieldFileTypeString, fw.ffo.FlatFileInformationFork.friendlyType()),
368 NewField(fieldFileCreatorString, fw.ffo.FlatFileInformationFork.friendlyCreator()),
369 NewField(fieldFileComment, fw.ffo.FlatFileInformationFork.Comment),
370 NewField(fieldFileType, fw.ffo.FlatFileInformationFork.TypeSignature),
371 NewField(fieldFileCreateDate, fw.ffo.FlatFileInformationFork.CreateDate),
372 NewField(fieldFileModifyDate, fw.ffo.FlatFileInformationFork.ModifyDate),
373 NewField(fieldFileSize, fw.totalSize()),
378 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
379 // Fields used in the request:
381 // * 202 File path Optional
382 // * 211 File new name Optional
383 // * 210 File comment Optional
384 // Fields used in the reply: None
385 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
386 fileName := t.GetField(fieldFileName).Data
387 filePath := t.GetField(fieldFilePath).Data
389 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
394 fi, err := cc.Server.FS.Stat(fullFilePath)
399 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
403 if t.GetField(fieldFileComment).Data != nil {
404 switch mode := fi.Mode(); {
406 if !cc.Authorize(accessSetFolderComment) {
407 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for folders."))
410 case mode.IsRegular():
411 if !cc.Authorize(accessSetFileComment) {
412 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for files."))
417 if err := hlFile.ffo.FlatFileInformationFork.setComment(t.GetField(fieldFileComment).Data); err != nil {
420 w, err := hlFile.infoForkWriter()
424 _, err = w.Write(hlFile.ffo.FlatFileInformationFork.MarshalBinary())
430 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, t.GetField(fieldFileNewName).Data)
435 fileNewName := t.GetField(fieldFileNewName).Data
437 if fileNewName != nil {
438 switch mode := fi.Mode(); {
440 if !cc.Authorize(accessRenameFolder) {
441 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
444 err = os.Rename(fullFilePath, fullNewFilePath)
445 if os.IsNotExist(err) {
446 res = append(res, cc.NewErrReply(t, "Cannot rename folder "+string(fileName)+" because it does not exist or cannot be found."))
449 case mode.IsRegular():
450 if !cc.Authorize(accessRenameFile) {
451 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
454 fileDir, err := readPath(cc.Server.Config.FileRoot, filePath, []byte{})
458 hlFile.name = string(fileNewName)
459 err = hlFile.move(fileDir)
460 if os.IsNotExist(err) {
461 res = append(res, cc.NewErrReply(t, "Cannot rename file "+string(fileName)+" because it does not exist or cannot be found."))
470 res = append(res, cc.NewReply(t))
474 // HandleDeleteFile deletes a file or folder
475 // Fields used in the request:
478 // Fields used in the reply: none
479 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
480 fileName := t.GetField(fieldFileName).Data
481 filePath := t.GetField(fieldFilePath).Data
483 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
488 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
493 fi, err := hlFile.dataFile()
495 res = append(res, cc.NewErrReply(t, "Cannot delete file "+string(fileName)+" because it does not exist or cannot be found."))
499 switch mode := fi.Mode(); {
501 if !cc.Authorize(accessDeleteFolder) {
502 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
505 case mode.IsRegular():
506 if !cc.Authorize(accessDeleteFile) {
507 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
512 if err := hlFile.delete(); err != nil {
516 res = append(res, cc.NewReply(t))
520 // HandleMoveFile moves files or folders. Note: seemingly not documented
521 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
522 fileName := string(t.GetField(fieldFileName).Data)
524 filePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
529 fileNewPath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFileNewPath).Data, nil)
534 cc.logger.Infow("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
536 hlFile, err := newFileWrapper(cc.Server.FS, filePath, 0)
541 fi, err := hlFile.dataFile()
543 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
549 switch mode := fi.Mode(); {
551 if !cc.Authorize(accessMoveFolder) {
552 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
555 case mode.IsRegular():
556 if !cc.Authorize(accessMoveFile) {
557 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
561 if err := hlFile.move(fileNewPath); err != nil {
564 // TODO: handle other possible errors; e.g. fileWrapper delete fails due to fileWrapper permission issue
566 res = append(res, cc.NewReply(t))
570 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
571 if !cc.Authorize(accessCreateFolder) {
572 res = append(res, cc.NewErrReply(t, "You are not allowed to create folders."))
575 folderName := string(t.GetField(fieldFileName).Data)
577 folderName = path.Join("/", folderName)
581 // fieldFilePath is only present for nested paths
582 if t.GetField(fieldFilePath).Data != nil {
584 _, err := newFp.Write(t.GetField(fieldFilePath).Data)
589 for _, pathItem := range newFp.Items {
590 subPath = filepath.Join("/", subPath, string(pathItem.Name))
593 newFolderPath := path.Join(cc.Server.Config.FileRoot, subPath, folderName)
595 // TODO: check path and folder name lengths
597 if _, err := cc.Server.FS.Stat(newFolderPath); !os.IsNotExist(err) {
598 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that name.", folderName)
599 return []Transaction{cc.NewErrReply(t, msg)}, nil
602 // TODO: check for disallowed characters to maintain compatibility for original client
604 if err := cc.Server.FS.Mkdir(newFolderPath, 0777); err != nil {
605 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
606 return []Transaction{cc.NewErrReply(t, msg)}, nil
609 res = append(res, cc.NewReply(t))
613 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
614 if !cc.Authorize(accessModifyUser) {
615 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
619 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
620 userName := string(t.GetField(fieldUserName).Data)
622 newAccessLvl := t.GetField(fieldUserAccess).Data
624 account := cc.Server.Accounts[login]
625 account.Name = userName
626 copy(account.Access[:], newAccessLvl)
628 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
629 // not include fieldUserPassword
630 if t.GetField(fieldUserPassword).Data == nil {
631 account.Password = hashAndSalt([]byte(""))
633 if len(t.GetField(fieldUserPassword).Data) > 1 {
634 account.Password = hashAndSalt(t.GetField(fieldUserPassword).Data)
637 out, err := yaml.Marshal(&account)
641 if err := os.WriteFile(filepath.Join(cc.Server.ConfigDir, "Users", login+".yaml"), out, 0666); err != nil {
645 // Notify connected clients logged in as the user of the new access level
646 for _, c := range cc.Server.Clients {
647 if c.Account.Login == login {
648 // Note: comment out these two lines to test server-side deny messages
649 newT := NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, newAccessLvl))
650 res = append(res, *newT)
652 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
653 if c.Authorize(accessDisconUser) {
654 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 1)
656 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 0)
658 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
660 c.Account.Access = account.Access
663 tranNotifyChangeUser,
664 NewField(fieldUserID, *c.ID),
665 NewField(fieldUserFlags, c.Flags),
666 NewField(fieldUserName, c.UserName),
667 NewField(fieldUserIconID, c.Icon),
672 res = append(res, cc.NewReply(t))
676 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
677 if !cc.Authorize(accessOpenUser) {
678 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
682 account := cc.Server.Accounts[string(t.GetField(fieldUserLogin).Data)]
684 res = append(res, cc.NewErrReply(t, "Account does not exist."))
688 res = append(res, cc.NewReply(t,
689 NewField(fieldUserName, []byte(account.Name)),
690 NewField(fieldUserLogin, negateString(t.GetField(fieldUserLogin).Data)),
691 NewField(fieldUserPassword, []byte(account.Password)),
692 NewField(fieldUserAccess, account.Access[:]),
697 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
698 if !cc.Authorize(accessOpenUser) {
699 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
703 var userFields []Field
704 for _, acc := range cc.Server.Accounts {
705 b := make([]byte, 0, 100)
706 n, err := acc.Read(b)
711 userFields = append(userFields, NewField(fieldData, b[:n]))
714 res = append(res, cc.NewReply(t, userFields...))
718 // HandleUpdateUser is used by the v1.5+ multi-user editor to perform account editing for multiple users at a time.
719 // An update can be a mix of these actions:
722 // * Modify user (including renaming the account login)
724 // The Transaction sent by the client includes one data field per user that was modified. This data field in turn
725 // contains another data field encoded in its payload with a varying number of sub fields depending on which action is
726 // performed. This seems to be the only place in the Hotline protocol where a data field contains another data field.
727 func HandleUpdateUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
728 for _, field := range t.Fields {
729 subFields, err := ReadFields(field.Data[0:2], field.Data[2:])
734 if len(subFields) == 1 {
735 login := DecodeUserString(getField(fieldData, &subFields).Data)
736 cc.logger.Infow("DeleteUser", "login", login)
738 if !cc.Authorize(accessDeleteUser) {
739 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
743 if err := cc.Server.DeleteUser(login); err != nil {
749 login := DecodeUserString(getField(fieldUserLogin, &subFields).Data)
751 // check if the login dataFile; if so, we know we are updating an existing user
752 if acc, ok := cc.Server.Accounts[login]; ok {
753 cc.logger.Infow("UpdateUser", "login", login)
755 // account dataFile, so this is an update action
756 if !cc.Authorize(accessModifyUser) {
757 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
761 if getField(fieldUserPassword, &subFields) != nil {
762 newPass := getField(fieldUserPassword, &subFields).Data
763 acc.Password = hashAndSalt(newPass)
765 acc.Password = hashAndSalt([]byte(""))
768 if getField(fieldUserAccess, &subFields) != nil {
769 copy(acc.Access[:], getField(fieldUserAccess, &subFields).Data)
772 err = cc.Server.UpdateUser(
773 DecodeUserString(getField(fieldData, &subFields).Data),
774 DecodeUserString(getField(fieldUserLogin, &subFields).Data),
775 string(getField(fieldUserName, &subFields).Data),
783 cc.logger.Infow("CreateUser", "login", login)
785 if !cc.Authorize(accessCreateUser) {
786 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
790 newAccess := accessBitmap{}
791 copy(newAccess[:], getField(fieldUserAccess, &subFields).Data[:])
793 err := cc.Server.NewUser(login, string(getField(fieldUserName, &subFields).Data), string(getField(fieldUserPassword, &subFields).Data), newAccess)
795 return []Transaction{}, err
800 res = append(res, cc.NewReply(t))
804 // HandleNewUser creates a new user account
805 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
806 if !cc.Authorize(accessCreateUser) {
807 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
811 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
813 // If the account already dataFile, reply with an error
814 if _, ok := cc.Server.Accounts[login]; ok {
815 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
819 newAccess := accessBitmap{}
820 copy(newAccess[:], t.GetField(fieldUserAccess).Data[:])
822 if err := cc.Server.NewUser(login, string(t.GetField(fieldUserName).Data), string(t.GetField(fieldUserPassword).Data), newAccess); err != nil {
823 return []Transaction{}, err
826 res = append(res, cc.NewReply(t))
830 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
831 if !cc.Authorize(accessDeleteUser) {
832 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
836 // TODO: Handle case where account doesn't exist; e.g. delete race condition
837 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
839 if err := cc.Server.DeleteUser(login); err != nil {
843 res = append(res, cc.NewReply(t))
847 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
848 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
849 if !cc.Authorize(accessBroadcast) {
850 res = append(res, cc.NewErrReply(t, "You are not allowed to send broadcast messages."))
856 NewField(fieldData, t.GetField(tranGetMsgs).Data),
857 NewField(fieldChatOptions, []byte{0}),
860 res = append(res, cc.NewReply(t))
864 func byteToInt(bytes []byte) (int, error) {
867 return int(binary.BigEndian.Uint16(bytes)), nil
869 return int(binary.BigEndian.Uint32(bytes)), nil
872 return 0, errors.New("unknown byte length")
875 // HandleGetClientInfoText returns user information for the specific user.
877 // Fields used in the request:
880 // Fields used in the reply:
882 // 101 Data User info text string
883 func HandleGetClientInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
884 if !cc.Authorize(accessGetClientInfo) {
885 res = append(res, cc.NewErrReply(t, "You are not allowed to get client info."))
889 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
891 clientConn := cc.Server.Clients[uint16(clientID)]
892 if clientConn == nil {
893 return append(res, cc.NewErrReply(t, "User not found.")), err
896 res = append(res, cc.NewReply(t,
897 NewField(fieldData, []byte(clientConn.String())),
898 NewField(fieldUserName, clientConn.UserName),
903 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
904 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
909 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
912 if t.GetField(fieldUserName).Data != nil {
913 if cc.Authorize(accessAnyName) {
914 cc.UserName = t.GetField(fieldUserName).Data
916 cc.UserName = []byte(cc.Account.Name)
920 cc.Icon = t.GetField(fieldUserIconID).Data
922 cc.logger = cc.logger.With("name", string(cc.UserName))
923 cc.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(cc.Version); return i }()))
925 options := t.GetField(fieldOptions).Data
926 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
928 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
930 // Check refuse private PM option
931 if optBitmap.Bit(refusePM) == 1 {
932 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
933 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
936 // Check refuse private chat option
937 if optBitmap.Bit(refuseChat) == 1 {
938 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
939 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
942 // Check auto response
943 if optBitmap.Bit(autoResponse) == 1 {
944 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
946 cc.AutoReply = []byte{}
949 trans := cc.notifyOthers(
951 tranNotifyChangeUser, nil,
952 NewField(fieldUserName, cc.UserName),
953 NewField(fieldUserID, *cc.ID),
954 NewField(fieldUserIconID, cc.Icon),
955 NewField(fieldUserFlags, cc.Flags),
958 res = append(res, trans...)
960 if cc.Server.Config.BannerFile != "" {
961 res = append(res, *NewTransaction(tranServerBanner, cc.ID, NewField(fieldBannerType, []byte("JPEG"))))
964 res = append(res, cc.NewReply(t))
969 const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
970 // "Mon, 02 Jan 2006 15:04:05 MST"
972 const defaultNewsTemplate = `From %s (%s):
976 __________________________________________________________`
978 // HandleTranOldPostNews updates the flat news
979 // Fields used in this request:
981 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
982 if !cc.Authorize(accessNewsPostArt) {
983 res = append(res, cc.NewErrReply(t, "You are not allowed to post news."))
987 cc.Server.flatNewsMux.Lock()
988 defer cc.Server.flatNewsMux.Unlock()
990 newsDateTemplate := defaultNewsDateFormat
991 if cc.Server.Config.NewsDateFormat != "" {
992 newsDateTemplate = cc.Server.Config.NewsDateFormat
995 newsTemplate := defaultNewsTemplate
996 if cc.Server.Config.NewsDelimiter != "" {
997 newsTemplate = cc.Server.Config.NewsDelimiter
1000 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
1001 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
1003 // update news on disk
1004 if err := cc.Server.FS.WriteFile(filepath.Join(cc.Server.ConfigDir, "MessageBoard.txt"), cc.Server.FlatNews, 0644); err != nil {
1008 // update news in memory
1009 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
1011 // Notify all clients of updated news
1014 NewField(fieldData, []byte(newsPost)),
1017 res = append(res, cc.NewReply(t))
1021 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1022 if !cc.Authorize(accessDisconUser) {
1023 res = append(res, cc.NewErrReply(t, "You are not allowed to disconnect users."))
1027 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
1029 if clientConn.Authorize(accessCannotBeDiscon) {
1030 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
1034 // If fieldOptions is set, then the client IP is banned in addition to disconnected.
1035 // 00 01 = temporary ban
1036 // 00 02 = permanent ban
1037 if t.GetField(fieldOptions).Data != nil {
1038 switch t.GetField(fieldOptions).Data[1] {
1040 // send message: "You are temporarily banned on this server"
1041 cc.logger.Infow("Disconnect & temporarily ban " + string(clientConn.UserName))
1043 res = append(res, *NewTransaction(
1046 NewField(fieldData, []byte("You are temporarily banned on this server")),
1047 NewField(fieldChatOptions, []byte{0, 0}),
1050 banUntil := time.Now().Add(tempBanDuration)
1051 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = &banUntil
1052 cc.Server.writeBanList()
1054 // send message: "You are permanently banned on this server"
1055 cc.logger.Infow("Disconnect & ban " + string(clientConn.UserName))
1057 res = append(res, *NewTransaction(
1060 NewField(fieldData, []byte("You are permanently banned on this server")),
1061 NewField(fieldChatOptions, []byte{0, 0}),
1064 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = nil
1065 cc.Server.writeBanList()
1069 // TODO: remove this awful hack
1071 time.Sleep(1 * time.Second)
1072 clientConn.Disconnect()
1075 return append(res, cc.NewReply(t)), err
1078 // HandleGetNewsCatNameList returns a list of news categories for a path
1079 // Fields used in the request:
1080 // 325 News path (Optional)
1081 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1082 if !cc.Authorize(accessNewsReadArt) {
1083 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1087 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1088 cats := cc.Server.GetNewsCatByPath(pathStrs)
1090 // To store the keys in slice in sorted order
1091 keys := make([]string, len(cats))
1093 for k := range cats {
1099 var fieldData []Field
1100 for _, k := range keys {
1102 b, _ := cat.MarshalBinary()
1103 fieldData = append(fieldData, NewField(
1104 fieldNewsCatListData15,
1109 res = append(res, cc.NewReply(t, fieldData...))
1113 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1114 if !cc.Authorize(accessNewsCreateCat) {
1115 res = append(res, cc.NewErrReply(t, "You are not allowed to create news categories."))
1119 name := string(t.GetField(fieldNewsCatName).Data)
1120 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1122 cats := cc.Server.GetNewsCatByPath(pathStrs)
1123 cats[name] = NewsCategoryListData15{
1126 Articles: map[uint32]*NewsArtData{},
1127 SubCats: make(map[string]NewsCategoryListData15),
1130 if err := cc.Server.writeThreadedNews(); err != nil {
1133 res = append(res, cc.NewReply(t))
1137 // Fields used in the request:
1138 // 322 News category name
1140 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1141 if !cc.Authorize(accessNewsCreateFldr) {
1142 res = append(res, cc.NewErrReply(t, "You are not allowed to create news folders."))
1146 name := string(t.GetField(fieldFileName).Data)
1147 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1149 cc.logger.Infof("Creating new news folder %s", name)
1151 cats := cc.Server.GetNewsCatByPath(pathStrs)
1152 cats[name] = NewsCategoryListData15{
1155 Articles: map[uint32]*NewsArtData{},
1156 SubCats: make(map[string]NewsCategoryListData15),
1158 if err := cc.Server.writeThreadedNews(); err != nil {
1161 res = append(res, cc.NewReply(t))
1165 // Fields used in the request:
1166 // 325 News path Optional
1169 // 321 News article list data Optional
1170 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1171 if !cc.Authorize(accessNewsReadArt) {
1172 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1175 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1177 var cat NewsCategoryListData15
1178 cats := cc.Server.ThreadedNews.Categories
1180 for _, fp := range pathStrs {
1182 cats = cats[fp].SubCats
1185 nald := cat.GetNewsArtListData()
1187 res = append(res, cc.NewReply(t, NewField(fieldNewsArtListData, nald.Payload())))
1191 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1192 if !cc.Authorize(accessNewsReadArt) {
1193 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1199 // 326 News article ID
1200 // 327 News article data flavor
1202 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1204 var cat NewsCategoryListData15
1205 cats := cc.Server.ThreadedNews.Categories
1207 for _, fp := range pathStrs {
1209 cats = cats[fp].SubCats
1211 newsArtID := t.GetField(fieldNewsArtID).Data
1213 convertedArtID := binary.BigEndian.Uint16(newsArtID)
1215 art := cat.Articles[uint32(convertedArtID)]
1217 res = append(res, cc.NewReply(t))
1222 // 328 News article title
1223 // 329 News article poster
1224 // 330 News article date
1225 // 331 Previous article ID
1226 // 332 Next article ID
1227 // 335 Parent article ID
1228 // 336 First child article ID
1229 // 327 News article data flavor "Should be “text/plain”
1230 // 333 News article data Optional (if data flavor is “text/plain”)
1232 res = append(res, cc.NewReply(t,
1233 NewField(fieldNewsArtTitle, []byte(art.Title)),
1234 NewField(fieldNewsArtPoster, []byte(art.Poster)),
1235 NewField(fieldNewsArtDate, art.Date),
1236 NewField(fieldNewsArtPrevArt, art.PrevArt),
1237 NewField(fieldNewsArtNextArt, art.NextArt),
1238 NewField(fieldNewsArtParentArt, art.ParentArt),
1239 NewField(fieldNewsArt1stChildArt, art.FirstChildArt),
1240 NewField(fieldNewsArtDataFlav, []byte("text/plain")),
1241 NewField(fieldNewsArtData, []byte(art.Data)),
1246 // HandleDelNewsItem deletes an existing threaded news folder or category from the server.
1247 // Fields used in the request:
1249 // Fields used in the reply:
1251 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1252 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1254 cats := cc.Server.ThreadedNews.Categories
1255 delName := pathStrs[len(pathStrs)-1]
1256 if len(pathStrs) > 1 {
1257 for _, fp := range pathStrs[0 : len(pathStrs)-1] {
1258 cats = cats[fp].SubCats
1262 if bytes.Compare(cats[delName].Type, []byte{0, 3}) == 0 {
1263 if !cc.Authorize(accessNewsDeleteCat) {
1264 return append(res, cc.NewErrReply(t, "You are not allowed to delete news categories.")), nil
1267 if !cc.Authorize(accessNewsDeleteFldr) {
1268 return append(res, cc.NewErrReply(t, "You are not allowed to delete news folders.")), nil
1272 delete(cats, delName)
1274 if err := cc.Server.writeThreadedNews(); err != nil {
1278 return append(res, cc.NewReply(t)), nil
1281 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1282 if !cc.Authorize(accessNewsDeleteArt) {
1283 res = append(res, cc.NewErrReply(t, "You are not allowed to delete news articles."))
1289 // 326 News article ID
1290 // 337 News article – recursive delete Delete child articles (1) or not (0)
1291 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1292 ID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1294 // TODO: Delete recursive
1295 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1297 catName := pathStrs[len(pathStrs)-1]
1298 cat := cats[catName]
1300 delete(cat.Articles, uint32(ID))
1303 if err := cc.Server.writeThreadedNews(); err != nil {
1307 res = append(res, cc.NewReply(t))
1313 // 326 News article ID ID of the parent article?
1314 // 328 News article title
1315 // 334 News article flags
1316 // 327 News article data flavor Currently “text/plain”
1317 // 333 News article data
1318 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1319 if !cc.Authorize(accessNewsPostArt) {
1320 res = append(res, cc.NewErrReply(t, "You are not allowed to post news articles."))
1324 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1325 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1327 catName := pathStrs[len(pathStrs)-1]
1328 cat := cats[catName]
1330 newArt := NewsArtData{
1331 Title: string(t.GetField(fieldNewsArtTitle).Data),
1332 Poster: string(cc.UserName),
1333 Date: toHotlineTime(time.Now()),
1334 PrevArt: []byte{0, 0, 0, 0},
1335 NextArt: []byte{0, 0, 0, 0},
1336 ParentArt: append([]byte{0, 0}, t.GetField(fieldNewsArtID).Data...),
1337 FirstChildArt: []byte{0, 0, 0, 0},
1338 DataFlav: []byte("text/plain"),
1339 Data: string(t.GetField(fieldNewsArtData).Data),
1343 for k := range cat.Articles {
1344 keys = append(keys, int(k))
1350 prevID := uint32(keys[len(keys)-1])
1353 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1355 // Set next article ID
1356 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1359 // Update parent article with first child reply
1360 parentID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1362 parentArt := cat.Articles[uint32(parentID)]
1364 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1365 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1369 cat.Articles[nextID] = &newArt
1372 if err := cc.Server.writeThreadedNews(); err != nil {
1376 res = append(res, cc.NewReply(t))
1380 // HandleGetMsgs returns the flat news data
1381 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1382 if !cc.Authorize(accessNewsReadArt) {
1383 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1387 res = append(res, cc.NewReply(t, NewField(fieldData, cc.Server.FlatNews)))
1392 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1393 if !cc.Authorize(accessDownloadFile) {
1394 res = append(res, cc.NewErrReply(t, "You are not allowed to download files."))
1398 fileName := t.GetField(fieldFileName).Data
1399 filePath := t.GetField(fieldFilePath).Data
1400 resumeData := t.GetField(fieldFileResumeData).Data
1402 var dataOffset int64
1403 var frd FileResumeData
1404 if resumeData != nil {
1405 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1408 // TODO: handle rsrc fork offset
1409 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1412 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1417 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, dataOffset)
1422 xferSize := hlFile.ffo.TransferSize(0)
1424 ft := cc.newFileTransfer(FileDownload, fileName, filePath, xferSize)
1426 // TODO: refactor to remove this
1427 if resumeData != nil {
1428 var frd FileResumeData
1429 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1432 ft.fileResumeData = &frd
1435 // Optional field for when a HL v1.5+ client requests file preview
1436 // Used only for TEXT, JPEG, GIFF, BMP or PICT files
1437 // The value will always be 2
1438 if t.GetField(fieldFileTransferOptions).Data != nil {
1439 ft.options = t.GetField(fieldFileTransferOptions).Data
1440 xferSize = hlFile.ffo.FlatFileDataForkHeader.DataSize[:]
1443 res = append(res, cc.NewReply(t,
1444 NewField(fieldRefNum, ft.refNum[:]),
1445 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1446 NewField(fieldTransferSize, xferSize),
1447 NewField(fieldFileSize, hlFile.ffo.FlatFileDataForkHeader.DataSize[:]),
1453 // Download all files from the specified folder and sub-folders
1454 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1455 if !cc.Authorize(accessDownloadFile) {
1456 res = append(res, cc.NewErrReply(t, "You are not allowed to download folders."))
1460 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
1465 transferSize, err := CalcTotalSize(fullFilePath)
1469 itemCount, err := CalcItemCount(fullFilePath)
1474 fileTransfer := cc.newFileTransfer(FolderDownload, t.GetField(fieldFileName).Data, t.GetField(fieldFilePath).Data, transferSize)
1477 _, err = fp.Write(t.GetField(fieldFilePath).Data)
1482 res = append(res, cc.NewReply(t,
1483 NewField(fieldRefNum, fileTransfer.ReferenceNumber),
1484 NewField(fieldTransferSize, transferSize),
1485 NewField(fieldFolderItemCount, itemCount),
1486 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1491 // Upload all files from the local folder and its subfolders to the specified path on the server
1492 // Fields used in the request
1495 // 108 transfer size Total size of all items in the folder
1496 // 220 Folder item count
1497 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1498 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1500 if t.GetField(fieldFilePath).Data != nil {
1501 if _, err = fp.Write(t.GetField(fieldFilePath).Data); err != nil {
1506 // Handle special cases for Upload and Drop Box folders
1507 if !cc.Authorize(accessUploadAnywhere) {
1508 if !fp.IsUploadDir() && !fp.IsDropbox() {
1509 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))))
1514 fileTransfer := cc.newFileTransfer(FolderUpload,
1515 t.GetField(fieldFileName).Data,
1516 t.GetField(fieldFilePath).Data,
1517 t.GetField(fieldTransferSize).Data,
1520 fileTransfer.FolderItemCount = t.GetField(fieldFolderItemCount).Data
1522 res = append(res, cc.NewReply(t, NewField(fieldRefNum, fileTransfer.ReferenceNumber)))
1527 // Fields used in the request:
1530 // 204 File transfer options "Optional
1531 // Used only to resume download, currently has value 2"
1532 // 108 File transfer size "Optional used if download is not resumed"
1533 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1534 if !cc.Authorize(accessUploadFile) {
1535 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1539 fileName := t.GetField(fieldFileName).Data
1540 filePath := t.GetField(fieldFilePath).Data
1541 transferOptions := t.GetField(fieldFileTransferOptions).Data
1542 transferSize := t.GetField(fieldTransferSize).Data // not sent for resume
1545 if filePath != nil {
1546 if _, err = fp.Write(filePath); err != nil {
1551 // Handle special cases for Upload and Drop Box folders
1552 if !cc.Authorize(accessUploadAnywhere) {
1553 if !fp.IsUploadDir() && !fp.IsDropbox() {
1554 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))))
1558 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1563 if _, err := cc.Server.FS.Stat(fullFilePath); err == nil {
1564 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))))
1568 ft := cc.newFileTransfer(FileUpload, fileName, filePath, transferSize)
1570 replyT := cc.NewReply(t, NewField(fieldRefNum, ft.ReferenceNumber))
1572 // client has requested to resume a partially transferred file
1573 if transferOptions != nil {
1575 fileInfo, err := cc.Server.FS.Stat(fullFilePath + incompleteFileSuffix)
1580 offset := make([]byte, 4)
1581 binary.BigEndian.PutUint32(offset, uint32(fileInfo.Size()))
1583 fileResumeData := NewFileResumeData([]ForkInfoList{
1584 *NewForkInfoList(offset),
1587 b, _ := fileResumeData.BinaryMarshal()
1589 ft.TransferSize = offset
1591 replyT.Fields = append(replyT.Fields, NewField(fieldFileResumeData, b))
1594 res = append(res, replyT)
1598 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1599 if len(t.GetField(fieldUserIconID).Data) == 4 {
1600 cc.Icon = t.GetField(fieldUserIconID).Data[2:]
1602 cc.Icon = t.GetField(fieldUserIconID).Data
1604 if cc.Authorize(accessAnyName) {
1605 cc.UserName = t.GetField(fieldUserName).Data
1608 // the options field is only passed by the client versions > 1.2.3.
1609 options := t.GetField(fieldOptions).Data
1611 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1612 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
1614 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, optBitmap.Bit(refusePM))
1615 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1617 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, optBitmap.Bit(refuseChat))
1618 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1620 // Check auto response
1621 if optBitmap.Bit(autoResponse) == 1 {
1622 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
1624 cc.AutoReply = []byte{}
1628 for _, c := range sortedClients(cc.Server.Clients) {
1629 res = append(res, *NewTransaction(
1630 tranNotifyChangeUser,
1632 NewField(fieldUserID, *cc.ID),
1633 NewField(fieldUserIconID, cc.Icon),
1634 NewField(fieldUserFlags, cc.Flags),
1635 NewField(fieldUserName, cc.UserName),
1642 // HandleKeepAlive responds to keepalive transactions with an empty reply
1643 // * HL 1.9.2 Client sends keepalive msg every 3 minutes
1644 // * HL 1.2.3 Client doesn't send keepalives
1645 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1646 res = append(res, cc.NewReply(t))
1651 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1652 fullPath, err := readPath(
1653 cc.Server.Config.FileRoot,
1654 t.GetField(fieldFilePath).Data,
1662 if t.GetField(fieldFilePath).Data != nil {
1663 if _, err = fp.Write(t.GetField(fieldFilePath).Data); err != nil {
1668 // Handle special case for drop box folders
1669 if fp.IsDropbox() && !cc.Authorize(accessViewDropBoxes) {
1670 res = append(res, cc.NewErrReply(t, "You are not allowed to view drop boxes."))
1674 fileNames, err := getFileNameList(fullPath, cc.Server.Config.IgnoreFiles)
1679 res = append(res, cc.NewReply(t, fileNames...))
1684 // =================================
1685 // Hotline private chat flow
1686 // =================================
1687 // 1. ClientA sends tranInviteNewChat to server with user ID to invite
1688 // 2. Server creates new ChatID
1689 // 3. Server sends tranInviteToChat to invitee
1690 // 4. Server replies to ClientA with new Chat ID
1692 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1693 // If Accepted is clicked:
1694 // 1. ClientB sends tranJoinChat with fieldChatID
1696 // HandleInviteNewChat invites users to new private chat
1697 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1698 if !cc.Authorize(accessOpenChat) {
1699 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1704 targetID := t.GetField(fieldUserID).Data
1705 newChatID := cc.Server.NewPrivateChat(cc)
1707 // Check if target user has "Refuse private chat" flag
1708 binary.BigEndian.Uint16(targetID)
1709 targetClient := cc.Server.Clients[binary.BigEndian.Uint16(targetID)]
1711 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(targetClient.Flags)))
1712 if flagBitmap.Bit(userFLagRefusePChat) == 1 {
1717 NewField(fieldData, []byte(string(targetClient.UserName)+" does not accept private chats.")),
1718 NewField(fieldUserName, targetClient.UserName),
1719 NewField(fieldUserID, *targetClient.ID),
1720 NewField(fieldOptions, []byte{0, 2}),
1728 NewField(fieldChatID, newChatID),
1729 NewField(fieldUserName, cc.UserName),
1730 NewField(fieldUserID, *cc.ID),
1737 NewField(fieldChatID, newChatID),
1738 NewField(fieldUserName, cc.UserName),
1739 NewField(fieldUserID, *cc.ID),
1740 NewField(fieldUserIconID, cc.Icon),
1741 NewField(fieldUserFlags, cc.Flags),
1748 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1749 if !cc.Authorize(accessOpenChat) {
1750 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1755 targetID := t.GetField(fieldUserID).Data
1756 chatID := t.GetField(fieldChatID).Data
1762 NewField(fieldChatID, chatID),
1763 NewField(fieldUserName, cc.UserName),
1764 NewField(fieldUserID, *cc.ID),
1770 NewField(fieldChatID, chatID),
1771 NewField(fieldUserName, cc.UserName),
1772 NewField(fieldUserID, *cc.ID),
1773 NewField(fieldUserIconID, cc.Icon),
1774 NewField(fieldUserFlags, cc.Flags),
1781 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1782 chatID := t.GetField(fieldChatID).Data
1783 chatInt := binary.BigEndian.Uint32(chatID)
1785 privChat := cc.Server.PrivateChats[chatInt]
1787 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1789 for _, c := range sortedClients(privChat.ClientConn) {
1794 NewField(fieldChatID, chatID),
1795 NewField(fieldData, resMsg),
1803 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1804 // Fields used in the reply:
1805 // * 115 Chat subject
1806 // * 300 User name with info (Optional)
1807 // * 300 (more user names with info)
1808 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1809 chatID := t.GetField(fieldChatID).Data
1810 chatInt := binary.BigEndian.Uint32(chatID)
1812 privChat := cc.Server.PrivateChats[chatInt]
1814 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1815 for _, c := range sortedClients(privChat.ClientConn) {
1818 tranNotifyChatChangeUser,
1820 NewField(fieldChatID, chatID),
1821 NewField(fieldUserName, cc.UserName),
1822 NewField(fieldUserID, *cc.ID),
1823 NewField(fieldUserIconID, cc.Icon),
1824 NewField(fieldUserFlags, cc.Flags),
1829 privChat.ClientConn[cc.uint16ID()] = cc
1831 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1832 for _, c := range sortedClients(privChat.ClientConn) {
1837 Name: string(c.UserName),
1840 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1843 res = append(res, cc.NewReply(t, replyFields...))
1847 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1848 // Fields used in the request:
1849 // * 114 fieldChatID
1850 // Reply is not expected.
1851 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1852 chatID := t.GetField(fieldChatID).Data
1853 chatInt := binary.BigEndian.Uint32(chatID)
1855 privChat, ok := cc.Server.PrivateChats[chatInt]
1860 delete(privChat.ClientConn, cc.uint16ID())
1862 // Notify members of the private chat that the user has left
1863 for _, c := range sortedClients(privChat.ClientConn) {
1866 tranNotifyChatDeleteUser,
1868 NewField(fieldChatID, chatID),
1869 NewField(fieldUserID, *cc.ID),
1877 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1878 // Fields used in the request:
1880 // * 115 Chat subject Chat subject string
1881 // Reply is not expected.
1882 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1883 chatID := t.GetField(fieldChatID).Data
1884 chatInt := binary.BigEndian.Uint32(chatID)
1886 privChat := cc.Server.PrivateChats[chatInt]
1887 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1889 for _, c := range sortedClients(privChat.ClientConn) {
1892 tranNotifyChatSubject,
1894 NewField(fieldChatID, chatID),
1895 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),
1903 // HandleMakeAlias makes a filer alias using the specified path.
1904 // Fields used in the request:
1907 // 212 File new path Destination path
1909 // Fields used in the reply:
1911 func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1912 if !cc.Authorize(accessMakeAlias) {
1913 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
1916 fileName := t.GetField(fieldFileName).Data
1917 filePath := t.GetField(fieldFilePath).Data
1918 fileNewPath := t.GetField(fieldFileNewPath).Data
1920 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1925 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
1930 cc.logger.Debugw("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
1932 if err := cc.Server.FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
1933 res = append(res, cc.NewErrReply(t, "Error creating alias"))
1937 res = append(res, cc.NewReply(t))
1941 // HandleDownloadBanner handles requests for a new banner from the server
1942 // Fields used in the request:
1944 // Fields used in the reply:
1945 // 107 fieldRefNum Used later for transfer
1946 // 108 fieldTransferSize Size of data to be downloaded
1947 func HandleDownloadBanner(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1948 fi, err := cc.Server.FS.Stat(filepath.Join(cc.Server.ConfigDir, cc.Server.Config.BannerFile))
1953 ft := cc.newFileTransfer(bannerDownload, []byte{}, []byte{}, make([]byte, 4))
1955 binary.BigEndian.PutUint32(ft.TransferSize, uint32(fi.Size()))
1957 res = append(res, cc.NewReply(t,
1958 NewField(fieldRefNum, ft.refNum[:]),
1959 NewField(fieldTransferSize, ft.TransferSize),