19 type TransactionType struct {
20 Handler func(*ClientConn, *Transaction) ([]Transaction, error) // function for handling the transaction type
21 Name string // Name of transaction as it will appear in logging
22 RequiredFields []requiredField
25 var TransactionHandlers = map[uint16]TransactionType{
31 tranNotifyChangeUser: {
32 Name: "tranNotifyChangeUser",
38 Name: "tranShowAgreement",
41 Name: "tranUserAccess",
43 tranNotifyDeleteUser: {
44 Name: "tranNotifyDeleteUser",
48 Handler: HandleTranAgreed,
52 Handler: HandleChatSend,
53 RequiredFields: []requiredField{
61 Name: "tranDelNewsArt",
62 Handler: HandleDelNewsArt,
65 Name: "tranDelNewsItem",
66 Handler: HandleDelNewsItem,
69 Name: "tranDeleteFile",
70 Handler: HandleDeleteFile,
73 Name: "tranDeleteUser",
74 Handler: HandleDeleteUser,
77 Name: "tranDisconnectUser",
78 Handler: HandleDisconnectUser,
81 Name: "tranDownloadFile",
82 Handler: HandleDownloadFile,
85 Name: "tranDownloadFldr",
86 Handler: HandleDownloadFolder,
88 tranGetClientInfoText: {
89 Name: "tranGetClientInfoText",
90 Handler: HandleGetClientInfoText,
93 Name: "tranGetFileInfo",
94 Handler: HandleGetFileInfo,
96 tranGetFileNameList: {
97 Name: "tranGetFileNameList",
98 Handler: HandleGetFileNameList,
102 Handler: HandleGetMsgs,
104 tranGetNewsArtData: {
105 Name: "tranGetNewsArtData",
106 Handler: HandleGetNewsArtData,
108 tranGetNewsArtNameList: {
109 Name: "tranGetNewsArtNameList",
110 Handler: HandleGetNewsArtNameList,
112 tranGetNewsCatNameList: {
113 Name: "tranGetNewsCatNameList",
114 Handler: HandleGetNewsCatNameList,
118 Handler: HandleGetUser,
120 tranGetUserNameList: {
121 Name: "tranHandleGetUserNameList",
122 Handler: HandleGetUserNameList,
125 Name: "tranInviteNewChat",
126 Handler: HandleInviteNewChat,
129 Name: "tranInviteToChat",
130 Handler: HandleInviteToChat,
133 Name: "tranJoinChat",
134 Handler: HandleJoinChat,
137 Name: "tranKeepAlive",
138 Handler: HandleKeepAlive,
141 Name: "tranJoinChat",
142 Handler: HandleLeaveChat,
145 Name: "tranListUsers",
146 Handler: HandleListUsers,
149 Name: "tranMoveFile",
150 Handler: HandleMoveFile,
153 Name: "tranNewFolder",
154 Handler: HandleNewFolder,
157 Name: "tranNewNewsCat",
158 Handler: HandleNewNewsCat,
161 Name: "tranNewNewsFldr",
162 Handler: HandleNewNewsFldr,
166 Handler: HandleNewUser,
169 Name: "tranUpdateUser",
170 Handler: HandleUpdateUser,
173 Name: "tranOldPostNews",
174 Handler: HandleTranOldPostNews,
177 Name: "tranPostNewsArt",
178 Handler: HandlePostNewsArt,
180 tranRejectChatInvite: {
181 Name: "tranRejectChatInvite",
182 Handler: HandleRejectChatInvite,
184 tranSendInstantMsg: {
185 Name: "tranSendInstantMsg",
186 Handler: HandleSendInstantMsg,
187 RequiredFields: []requiredField{
197 tranSetChatSubject: {
198 Name: "tranSetChatSubject",
199 Handler: HandleSetChatSubject,
202 Name: "tranMakeFileAlias",
203 Handler: HandleMakeAlias,
204 RequiredFields: []requiredField{
205 {ID: fieldFileName, minLen: 1},
206 {ID: fieldFilePath, minLen: 1},
207 {ID: fieldFileNewPath, minLen: 1},
210 tranSetClientUserInfo: {
211 Name: "tranSetClientUserInfo",
212 Handler: HandleSetClientUserInfo,
215 Name: "tranSetFileInfo",
216 Handler: HandleSetFileInfo,
220 Handler: HandleSetUser,
223 Name: "tranUploadFile",
224 Handler: HandleUploadFile,
227 Name: "tranUploadFldr",
228 Handler: HandleUploadFolder,
231 Name: "tranUserBroadcast",
232 Handler: HandleUserBroadcast,
234 tranDownloadBanner: {
235 Name: "tranDownloadBanner",
236 Handler: HandleDownloadBanner,
240 func HandleChatSend(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
241 if !cc.Authorize(accessSendChat) {
242 res = append(res, cc.NewErrReply(t, "You are not allowed to participate in chat."))
246 // Truncate long usernames
247 trunc := fmt.Sprintf("%13s", cc.UserName)
248 formattedMsg := fmt.Sprintf("\r%.14s: %s", trunc, t.GetField(fieldData).Data)
250 // By holding the option key, Hotline chat allows users to send /me formatted messages like:
251 // *** Halcyon does stuff
252 // This is indicated by the presence of the optional field fieldChatOptions in the transaction payload
253 if t.GetField(fieldChatOptions).Data != nil {
254 formattedMsg = fmt.Sprintf("\r*** %s %s", cc.UserName, t.GetField(fieldData).Data)
257 chatID := t.GetField(fieldChatID).Data
258 // a non-nil chatID indicates the message belongs to a private chat
260 chatInt := binary.BigEndian.Uint32(chatID)
261 privChat := cc.Server.PrivateChats[chatInt]
263 clients := sortedClients(privChat.ClientConn)
265 // send the message to all connected clients of the private chat
266 for _, c := range clients {
267 res = append(res, *NewTransaction(
270 NewField(fieldChatID, chatID),
271 NewField(fieldData, []byte(formattedMsg)),
277 for _, c := range sortedClients(cc.Server.Clients) {
278 // Filter out clients that do not have the read chat permission
279 if c.Authorize(accessReadChat) {
280 res = append(res, *NewTransaction(tranChatMsg, c.ID, NewField(fieldData, []byte(formattedMsg))))
287 // HandleSendInstantMsg sends instant message to the user on the current server.
288 // Fields used in the request:
291 // One of the following values:
292 // - User message (myOpt_UserMessage = 1)
293 // - Refuse message (myOpt_RefuseMessage = 2)
294 // - Refuse chat (myOpt_RefuseChat = 3)
295 // - Automatic response (myOpt_AutomaticResponse = 4)"
297 // 214 Quoting message Optional
299 // Fields used in the reply:
301 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
302 if !cc.Authorize(accessSendPrivMsg) {
303 res = append(res, cc.NewErrReply(t, "You are not allowed to send private messages."))
307 msg := t.GetField(fieldData)
308 ID := t.GetField(fieldUserID)
310 reply := NewTransaction(
313 NewField(fieldData, msg.Data),
314 NewField(fieldUserName, cc.UserName),
315 NewField(fieldUserID, *cc.ID),
316 NewField(fieldOptions, []byte{0, 1}),
319 // Later versions of Hotline include the original message in the fieldQuotingMsg field so
320 // the receiving client can display both the received message and what it is in reply to
321 if t.GetField(fieldQuotingMsg).Data != nil {
322 reply.Fields = append(reply.Fields, NewField(fieldQuotingMsg, t.GetField(fieldQuotingMsg).Data))
325 res = append(res, *reply)
327 id, _ := byteToInt(ID.Data)
328 otherClient, ok := cc.Server.Clients[uint16(id)]
330 return res, errors.New("invalid client ID")
333 // Respond with auto reply if other client has it enabled
334 if len(otherClient.AutoReply) > 0 {
339 NewField(fieldData, otherClient.AutoReply),
340 NewField(fieldUserName, otherClient.UserName),
341 NewField(fieldUserID, *otherClient.ID),
342 NewField(fieldOptions, []byte{0, 1}),
347 res = append(res, cc.NewReply(t))
352 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
353 fileName := t.GetField(fieldFileName).Data
354 filePath := t.GetField(fieldFilePath).Data
356 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
361 fw, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
366 res = append(res, cc.NewReply(t,
367 NewField(fieldFileName, []byte(fw.name)),
368 NewField(fieldFileTypeString, fw.ffo.FlatFileInformationFork.friendlyType()),
369 NewField(fieldFileCreatorString, fw.ffo.FlatFileInformationFork.friendlyCreator()),
370 NewField(fieldFileComment, fw.ffo.FlatFileInformationFork.Comment),
371 NewField(fieldFileType, fw.ffo.FlatFileInformationFork.TypeSignature),
372 NewField(fieldFileCreateDate, fw.ffo.FlatFileInformationFork.CreateDate),
373 NewField(fieldFileModifyDate, fw.ffo.FlatFileInformationFork.ModifyDate),
374 NewField(fieldFileSize, fw.totalSize()),
379 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
380 // Fields used in the request:
382 // * 202 File path Optional
383 // * 211 File new name Optional
384 // * 210 File comment Optional
385 // Fields used in the reply: None
386 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
387 fileName := t.GetField(fieldFileName).Data
388 filePath := t.GetField(fieldFilePath).Data
390 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
395 fi, err := cc.Server.FS.Stat(fullFilePath)
400 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
404 if t.GetField(fieldFileComment).Data != nil {
405 switch mode := fi.Mode(); {
407 if !cc.Authorize(accessSetFolderComment) {
408 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for folders."))
411 case mode.IsRegular():
412 if !cc.Authorize(accessSetFileComment) {
413 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for files."))
418 if err := hlFile.ffo.FlatFileInformationFork.setComment(t.GetField(fieldFileComment).Data); err != nil {
421 w, err := hlFile.infoForkWriter()
425 _, err = w.Write(hlFile.ffo.FlatFileInformationFork.MarshalBinary())
431 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, t.GetField(fieldFileNewName).Data)
436 fileNewName := t.GetField(fieldFileNewName).Data
438 if fileNewName != nil {
439 switch mode := fi.Mode(); {
441 if !cc.Authorize(accessRenameFolder) {
442 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
445 err = os.Rename(fullFilePath, fullNewFilePath)
446 if os.IsNotExist(err) {
447 res = append(res, cc.NewErrReply(t, "Cannot rename folder "+string(fileName)+" because it does not exist or cannot be found."))
450 case mode.IsRegular():
451 if !cc.Authorize(accessRenameFile) {
452 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
455 fileDir, err := readPath(cc.Server.Config.FileRoot, filePath, []byte{})
459 hlFile.name = string(fileNewName)
460 err = hlFile.move(fileDir)
461 if os.IsNotExist(err) {
462 res = append(res, cc.NewErrReply(t, "Cannot rename file "+string(fileName)+" because it does not exist or cannot be found."))
471 res = append(res, cc.NewReply(t))
475 // HandleDeleteFile deletes a file or folder
476 // Fields used in the request:
479 // Fields used in the reply: none
480 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
481 fileName := t.GetField(fieldFileName).Data
482 filePath := t.GetField(fieldFilePath).Data
484 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
489 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
494 fi, err := hlFile.dataFile()
496 res = append(res, cc.NewErrReply(t, "Cannot delete file "+string(fileName)+" because it does not exist or cannot be found."))
500 switch mode := fi.Mode(); {
502 if !cc.Authorize(accessDeleteFolder) {
503 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
506 case mode.IsRegular():
507 if !cc.Authorize(accessDeleteFile) {
508 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
513 if err := hlFile.delete(); err != nil {
517 res = append(res, cc.NewReply(t))
521 // HandleMoveFile moves files or folders. Note: seemingly not documented
522 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
523 fileName := string(t.GetField(fieldFileName).Data)
525 filePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
530 fileNewPath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFileNewPath).Data, nil)
535 cc.logger.Infow("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
537 hlFile, err := newFileWrapper(cc.Server.FS, filePath, 0)
542 fi, err := hlFile.dataFile()
544 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
550 switch mode := fi.Mode(); {
552 if !cc.Authorize(accessMoveFolder) {
553 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
556 case mode.IsRegular():
557 if !cc.Authorize(accessMoveFile) {
558 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
562 if err := hlFile.move(fileNewPath); err != nil {
565 // TODO: handle other possible errors; e.g. fileWrapper delete fails due to fileWrapper permission issue
567 res = append(res, cc.NewReply(t))
571 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
572 if !cc.Authorize(accessCreateFolder) {
573 res = append(res, cc.NewErrReply(t, "You are not allowed to create folders."))
576 folderName := string(t.GetField(fieldFileName).Data)
578 folderName = path.Join("/", folderName)
582 // fieldFilePath is only present for nested paths
583 if t.GetField(fieldFilePath).Data != nil {
585 err := newFp.UnmarshalBinary(t.GetField(fieldFilePath).Data)
590 for _, pathItem := range newFp.Items {
591 subPath = filepath.Join("/", subPath, string(pathItem.Name))
594 newFolderPath := path.Join(cc.Server.Config.FileRoot, subPath, folderName)
596 // TODO: check path and folder name lengths
598 if _, err := cc.Server.FS.Stat(newFolderPath); !os.IsNotExist(err) {
599 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that name.", folderName)
600 return []Transaction{cc.NewErrReply(t, msg)}, nil
603 // TODO: check for disallowed characters to maintain compatibility for original client
605 if err := cc.Server.FS.Mkdir(newFolderPath, 0777); err != nil {
606 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
607 return []Transaction{cc.NewErrReply(t, msg)}, nil
610 res = append(res, cc.NewReply(t))
614 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
615 if !cc.Authorize(accessModifyUser) {
616 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
620 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
621 userName := string(t.GetField(fieldUserName).Data)
623 newAccessLvl := t.GetField(fieldUserAccess).Data
625 account := cc.Server.Accounts[login]
626 account.Name = userName
627 copy(account.Access[:], newAccessLvl)
629 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
630 // not include fieldUserPassword
631 if t.GetField(fieldUserPassword).Data == nil {
632 account.Password = hashAndSalt([]byte(""))
634 if len(t.GetField(fieldUserPassword).Data) > 1 {
635 account.Password = hashAndSalt(t.GetField(fieldUserPassword).Data)
638 out, err := yaml.Marshal(&account)
642 if err := os.WriteFile(filepath.Join(cc.Server.ConfigDir, "Users", login+".yaml"), out, 0666); err != nil {
646 // Notify connected clients logged in as the user of the new access level
647 for _, c := range cc.Server.Clients {
648 if c.Account.Login == login {
649 // Note: comment out these two lines to test server-side deny messages
650 newT := NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, newAccessLvl))
651 res = append(res, *newT)
653 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
654 if c.Authorize(accessDisconUser) {
655 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 1)
657 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 0)
659 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
661 c.Account.Access = account.Access
664 tranNotifyChangeUser,
665 NewField(fieldUserID, *c.ID),
666 NewField(fieldUserFlags, c.Flags),
667 NewField(fieldUserName, c.UserName),
668 NewField(fieldUserIconID, c.Icon),
673 res = append(res, cc.NewReply(t))
677 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
678 if !cc.Authorize(accessOpenUser) {
679 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
683 account := cc.Server.Accounts[string(t.GetField(fieldUserLogin).Data)]
685 res = append(res, cc.NewErrReply(t, "Account does not exist."))
689 res = append(res, cc.NewReply(t,
690 NewField(fieldUserName, []byte(account.Name)),
691 NewField(fieldUserLogin, negateString(t.GetField(fieldUserLogin).Data)),
692 NewField(fieldUserPassword, []byte(account.Password)),
693 NewField(fieldUserAccess, account.Access[:]),
698 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
699 if !cc.Authorize(accessOpenUser) {
700 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
704 var userFields []Field
705 for _, acc := range cc.Server.Accounts {
706 b := make([]byte, 0, 100)
707 n, err := acc.Read(b)
712 userFields = append(userFields, NewField(fieldData, b[:n]))
715 res = append(res, cc.NewReply(t, userFields...))
719 // HandleUpdateUser is used by the v1.5+ multi-user editor to perform account editing for multiple users at a time.
720 // An update can be a mix of these actions:
723 // * Modify user (including renaming the account login)
725 // The Transaction sent by the client includes one data field per user that was modified. This data field in turn
726 // contains another data field encoded in its payload with a varying number of sub fields depending on which action is
727 // performed. This seems to be the only place in the Hotline protocol where a data field contains another data field.
728 func HandleUpdateUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
729 for _, field := range t.Fields {
730 subFields, err := ReadFields(field.Data[0:2], field.Data[2:])
735 if len(subFields) == 1 {
736 login := DecodeUserString(getField(fieldData, &subFields).Data)
737 cc.logger.Infow("DeleteUser", "login", login)
739 if !cc.Authorize(accessDeleteUser) {
740 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
744 if err := cc.Server.DeleteUser(login); err != nil {
750 login := DecodeUserString(getField(fieldUserLogin, &subFields).Data)
752 // check if the login dataFile; if so, we know we are updating an existing user
753 if acc, ok := cc.Server.Accounts[login]; ok {
754 cc.logger.Infow("UpdateUser", "login", login)
756 // account dataFile, so this is an update action
757 if !cc.Authorize(accessModifyUser) {
758 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
762 if getField(fieldUserPassword, &subFields) != nil {
763 newPass := getField(fieldUserPassword, &subFields).Data
764 acc.Password = hashAndSalt(newPass)
766 acc.Password = hashAndSalt([]byte(""))
769 if getField(fieldUserAccess, &subFields) != nil {
770 copy(acc.Access[:], getField(fieldUserAccess, &subFields).Data)
773 err = cc.Server.UpdateUser(
774 DecodeUserString(getField(fieldData, &subFields).Data),
775 DecodeUserString(getField(fieldUserLogin, &subFields).Data),
776 string(getField(fieldUserName, &subFields).Data),
784 cc.logger.Infow("CreateUser", "login", login)
786 if !cc.Authorize(accessCreateUser) {
787 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
791 newAccess := accessBitmap{}
792 copy(newAccess[:], getField(fieldUserAccess, &subFields).Data[:])
794 err := cc.Server.NewUser(login, string(getField(fieldUserName, &subFields).Data), string(getField(fieldUserPassword, &subFields).Data), newAccess)
796 return []Transaction{}, err
801 res = append(res, cc.NewReply(t))
805 // HandleNewUser creates a new user account
806 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
807 if !cc.Authorize(accessCreateUser) {
808 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
812 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
814 // If the account already dataFile, reply with an error
815 if _, ok := cc.Server.Accounts[login]; ok {
816 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
820 newAccess := accessBitmap{}
821 copy(newAccess[:], t.GetField(fieldUserAccess).Data[:])
823 if err := cc.Server.NewUser(login, string(t.GetField(fieldUserName).Data), string(t.GetField(fieldUserPassword).Data), newAccess); err != nil {
824 return []Transaction{}, err
827 res = append(res, cc.NewReply(t))
831 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
832 if !cc.Authorize(accessDeleteUser) {
833 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
837 // TODO: Handle case where account doesn't exist; e.g. delete race condition
838 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
840 if err := cc.Server.DeleteUser(login); err != nil {
844 res = append(res, cc.NewReply(t))
848 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
849 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
850 if !cc.Authorize(accessBroadcast) {
851 res = append(res, cc.NewErrReply(t, "You are not allowed to send broadcast messages."))
857 NewField(fieldData, t.GetField(tranGetMsgs).Data),
858 NewField(fieldChatOptions, []byte{0}),
861 res = append(res, cc.NewReply(t))
865 func byteToInt(bytes []byte) (int, error) {
868 return int(binary.BigEndian.Uint16(bytes)), nil
870 return int(binary.BigEndian.Uint32(bytes)), nil
873 return 0, errors.New("unknown byte length")
876 // HandleGetClientInfoText returns user information for the specific user.
878 // Fields used in the request:
881 // Fields used in the reply:
883 // 101 Data User info text string
884 func HandleGetClientInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
885 if !cc.Authorize(accessGetClientInfo) {
886 res = append(res, cc.NewErrReply(t, "You are not allowed to get client info."))
890 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
892 clientConn := cc.Server.Clients[uint16(clientID)]
893 if clientConn == nil {
894 return append(res, cc.NewErrReply(t, "User not found.")), err
897 res = append(res, cc.NewReply(t,
898 NewField(fieldData, []byte(clientConn.String())),
899 NewField(fieldUserName, clientConn.UserName),
904 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
905 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
910 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
913 if t.GetField(fieldUserName).Data != nil {
914 if cc.Authorize(accessAnyName) {
915 cc.UserName = t.GetField(fieldUserName).Data
917 cc.UserName = []byte(cc.Account.Name)
921 cc.Icon = t.GetField(fieldUserIconID).Data
923 cc.logger = cc.logger.With("name", string(cc.UserName))
924 cc.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%x", cc.Version))
926 options := t.GetField(fieldOptions).Data
927 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
929 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
931 // Check refuse private PM option
932 if optBitmap.Bit(refusePM) == 1 {
933 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
934 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
937 // Check refuse private chat option
938 if optBitmap.Bit(refuseChat) == 1 {
939 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
940 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
943 // Check auto response
944 if optBitmap.Bit(autoResponse) == 1 {
945 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
947 cc.AutoReply = []byte{}
950 trans := cc.notifyOthers(
952 tranNotifyChangeUser, nil,
953 NewField(fieldUserName, cc.UserName),
954 NewField(fieldUserID, *cc.ID),
955 NewField(fieldUserIconID, cc.Icon),
956 NewField(fieldUserFlags, cc.Flags),
959 res = append(res, trans...)
961 if cc.Server.Config.BannerFile != "" {
962 res = append(res, *NewTransaction(tranServerBanner, cc.ID, NewField(fieldBannerType, []byte("JPEG"))))
965 res = append(res, cc.NewReply(t))
970 const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
971 // "Mon, 02 Jan 2006 15:04:05 MST"
973 const defaultNewsTemplate = `From %s (%s):
977 __________________________________________________________`
979 // HandleTranOldPostNews updates the flat news
980 // Fields used in this request:
982 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
983 if !cc.Authorize(accessNewsPostArt) {
984 res = append(res, cc.NewErrReply(t, "You are not allowed to post news."))
988 cc.Server.flatNewsMux.Lock()
989 defer cc.Server.flatNewsMux.Unlock()
991 newsDateTemplate := defaultNewsDateFormat
992 if cc.Server.Config.NewsDateFormat != "" {
993 newsDateTemplate = cc.Server.Config.NewsDateFormat
996 newsTemplate := defaultNewsTemplate
997 if cc.Server.Config.NewsDelimiter != "" {
998 newsTemplate = cc.Server.Config.NewsDelimiter
1001 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
1002 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
1004 // update news in memory
1005 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
1007 // update news on disk
1008 if err := ioutil.WriteFile(cc.Server.ConfigDir+"MessageBoard.txt", cc.Server.FlatNews, 0644); err != nil {
1012 // Notify all clients of updated news
1015 NewField(fieldData, []byte(newsPost)),
1018 res = append(res, cc.NewReply(t))
1022 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1023 if !cc.Authorize(accessDisconUser) {
1024 res = append(res, cc.NewErrReply(t, "You are not allowed to disconnect users."))
1028 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
1030 if clientConn.Authorize(accessCannotBeDiscon) {
1031 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
1035 // If fieldOptions is set, then the client IP is banned in addition to disconnected.
1036 // 00 01 = temporary ban
1037 // 00 02 = permanent ban
1038 if t.GetField(fieldOptions).Data != nil {
1039 switch t.GetField(fieldOptions).Data[1] {
1041 // send message: "You are temporarily banned on this server"
1042 cc.logger.Infow("Disconnect & temporarily ban " + string(clientConn.UserName))
1044 res = append(res, *NewTransaction(
1047 NewField(fieldData, []byte("You are temporarily banned on this server")),
1048 NewField(fieldChatOptions, []byte{0, 0}),
1051 banUntil := time.Now().Add(tempBanDuration)
1052 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = &banUntil
1053 cc.Server.writeBanList()
1055 // send message: "You are permanently banned on this server"
1056 cc.logger.Infow("Disconnect & ban " + string(clientConn.UserName))
1058 res = append(res, *NewTransaction(
1061 NewField(fieldData, []byte("You are permanently banned on this server")),
1062 NewField(fieldChatOptions, []byte{0, 0}),
1065 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = nil
1066 cc.Server.writeBanList()
1070 // TODO: remove this awful hack
1072 time.Sleep(1 * time.Second)
1073 clientConn.Disconnect()
1076 return append(res, cc.NewReply(t)), err
1079 // HandleGetNewsCatNameList returns a list of news categories for a path
1080 // Fields used in the request:
1081 // 325 News path (Optional)
1082 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1083 if !cc.Authorize(accessNewsReadArt) {
1084 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1088 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1089 cats := cc.Server.GetNewsCatByPath(pathStrs)
1091 // To store the keys in slice in sorted order
1092 keys := make([]string, len(cats))
1094 for k := range cats {
1100 var fieldData []Field
1101 for _, k := range keys {
1103 b, _ := cat.MarshalBinary()
1104 fieldData = append(fieldData, NewField(
1105 fieldNewsCatListData15,
1110 res = append(res, cc.NewReply(t, fieldData...))
1114 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1115 if !cc.Authorize(accessNewsCreateCat) {
1116 res = append(res, cc.NewErrReply(t, "You are not allowed to create news categories."))
1120 name := string(t.GetField(fieldNewsCatName).Data)
1121 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1123 cats := cc.Server.GetNewsCatByPath(pathStrs)
1124 cats[name] = NewsCategoryListData15{
1127 Articles: map[uint32]*NewsArtData{},
1128 SubCats: make(map[string]NewsCategoryListData15),
1131 if err := cc.Server.writeThreadedNews(); err != nil {
1134 res = append(res, cc.NewReply(t))
1138 // Fields used in the request:
1139 // 322 News category name
1141 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1142 if !cc.Authorize(accessNewsCreateFldr) {
1143 res = append(res, cc.NewErrReply(t, "You are not allowed to create news folders."))
1147 name := string(t.GetField(fieldFileName).Data)
1148 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1150 cc.logger.Infof("Creating new news folder %s", name)
1152 cats := cc.Server.GetNewsCatByPath(pathStrs)
1153 cats[name] = NewsCategoryListData15{
1156 Articles: map[uint32]*NewsArtData{},
1157 SubCats: make(map[string]NewsCategoryListData15),
1159 if err := cc.Server.writeThreadedNews(); err != nil {
1162 res = append(res, cc.NewReply(t))
1166 // Fields used in the request:
1167 // 325 News path Optional
1170 // 321 News article list data Optional
1171 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1172 if !cc.Authorize(accessNewsReadArt) {
1173 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1176 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1178 var cat NewsCategoryListData15
1179 cats := cc.Server.ThreadedNews.Categories
1181 for _, fp := range pathStrs {
1183 cats = cats[fp].SubCats
1186 nald := cat.GetNewsArtListData()
1188 res = append(res, cc.NewReply(t, NewField(fieldNewsArtListData, nald.Payload())))
1192 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1193 if !cc.Authorize(accessNewsReadArt) {
1194 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1200 // 326 News article ID
1201 // 327 News article data flavor
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
1212 newsArtID := t.GetField(fieldNewsArtID).Data
1214 convertedArtID := binary.BigEndian.Uint16(newsArtID)
1216 art := cat.Articles[uint32(convertedArtID)]
1218 res = append(res, cc.NewReply(t))
1223 // 328 News article title
1224 // 329 News article poster
1225 // 330 News article date
1226 // 331 Previous article ID
1227 // 332 Next article ID
1228 // 335 Parent article ID
1229 // 336 First child article ID
1230 // 327 News article data flavor "Should be “text/plain”
1231 // 333 News article data Optional (if data flavor is “text/plain”)
1233 res = append(res, cc.NewReply(t,
1234 NewField(fieldNewsArtTitle, []byte(art.Title)),
1235 NewField(fieldNewsArtPoster, []byte(art.Poster)),
1236 NewField(fieldNewsArtDate, art.Date),
1237 NewField(fieldNewsArtPrevArt, art.PrevArt),
1238 NewField(fieldNewsArtNextArt, art.NextArt),
1239 NewField(fieldNewsArtParentArt, art.ParentArt),
1240 NewField(fieldNewsArt1stChildArt, art.FirstChildArt),
1241 NewField(fieldNewsArtDataFlav, []byte("text/plain")),
1242 NewField(fieldNewsArtData, []byte(art.Data)),
1247 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1248 // Has multiple access flags: News Delete Folder (37) or News Delete Category (35)
1251 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1253 // TODO: determine if path is a Folder (Bundle) or Category and check for permission
1255 cc.logger.Infof("DelNewsItem %v", pathStrs)
1257 cats := cc.Server.ThreadedNews.Categories
1259 delName := pathStrs[len(pathStrs)-1]
1260 if len(pathStrs) > 1 {
1261 for _, fp := range pathStrs[0 : len(pathStrs)-1] {
1262 cats = cats[fp].SubCats
1266 delete(cats, delName)
1268 err = cc.Server.writeThreadedNews()
1273 // Reply params: none
1274 res = append(res, cc.NewReply(t))
1279 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1280 if !cc.Authorize(accessNewsDeleteArt) {
1281 res = append(res, cc.NewErrReply(t, "You are not allowed to delete news articles."))
1287 // 326 News article ID
1288 // 337 News article – recursive delete Delete child articles (1) or not (0)
1289 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1290 ID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1292 // TODO: Delete recursive
1293 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1295 catName := pathStrs[len(pathStrs)-1]
1296 cat := cats[catName]
1298 delete(cat.Articles, uint32(ID))
1301 if err := cc.Server.writeThreadedNews(); err != nil {
1305 res = append(res, cc.NewReply(t))
1311 // 326 News article ID ID of the parent article?
1312 // 328 News article title
1313 // 334 News article flags
1314 // 327 News article data flavor Currently “text/plain”
1315 // 333 News article data
1316 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1317 if !cc.Authorize(accessNewsPostArt) {
1318 res = append(res, cc.NewErrReply(t, "You are not allowed to post news articles."))
1322 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1323 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1325 catName := pathStrs[len(pathStrs)-1]
1326 cat := cats[catName]
1328 newArt := NewsArtData{
1329 Title: string(t.GetField(fieldNewsArtTitle).Data),
1330 Poster: string(cc.UserName),
1331 Date: toHotlineTime(time.Now()),
1332 PrevArt: []byte{0, 0, 0, 0},
1333 NextArt: []byte{0, 0, 0, 0},
1334 ParentArt: append([]byte{0, 0}, t.GetField(fieldNewsArtID).Data...),
1335 FirstChildArt: []byte{0, 0, 0, 0},
1336 DataFlav: []byte("text/plain"),
1337 Data: string(t.GetField(fieldNewsArtData).Data),
1341 for k := range cat.Articles {
1342 keys = append(keys, int(k))
1348 prevID := uint32(keys[len(keys)-1])
1351 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1353 // Set next article ID
1354 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1357 // Update parent article with first child reply
1358 parentID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1360 parentArt := cat.Articles[uint32(parentID)]
1362 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1363 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1367 cat.Articles[nextID] = &newArt
1370 if err := cc.Server.writeThreadedNews(); err != nil {
1374 res = append(res, cc.NewReply(t))
1378 // HandleGetMsgs returns the flat news data
1379 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1380 if !cc.Authorize(accessNewsReadArt) {
1381 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1385 res = append(res, cc.NewReply(t, NewField(fieldData, cc.Server.FlatNews)))
1390 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1391 if !cc.Authorize(accessDownloadFile) {
1392 res = append(res, cc.NewErrReply(t, "You are not allowed to download files."))
1396 fileName := t.GetField(fieldFileName).Data
1397 filePath := t.GetField(fieldFilePath).Data
1398 resumeData := t.GetField(fieldFileResumeData).Data
1400 var dataOffset int64
1401 var frd FileResumeData
1402 if resumeData != nil {
1403 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1406 // TODO: handle rsrc fork offset
1407 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1410 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1415 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, dataOffset)
1420 xferSize := hlFile.ffo.TransferSize(0)
1422 ft := cc.newFileTransfer(FileDownload, fileName, filePath, xferSize)
1424 // TODO: refactor to remove this
1425 if resumeData != nil {
1426 var frd FileResumeData
1427 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1430 ft.fileResumeData = &frd
1433 // Optional field for when a HL v1.5+ client requests file preview
1434 // Used only for TEXT, JPEG, GIFF, BMP or PICT files
1435 // The value will always be 2
1436 if t.GetField(fieldFileTransferOptions).Data != nil {
1437 ft.options = t.GetField(fieldFileTransferOptions).Data
1438 xferSize = hlFile.ffo.FlatFileDataForkHeader.DataSize[:]
1441 res = append(res, cc.NewReply(t,
1442 NewField(fieldRefNum, ft.refNum[:]),
1443 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1444 NewField(fieldTransferSize, xferSize),
1445 NewField(fieldFileSize, hlFile.ffo.FlatFileDataForkHeader.DataSize[:]),
1451 // Download all files from the specified folder and sub-folders
1452 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1453 if !cc.Authorize(accessDownloadFile) {
1454 res = append(res, cc.NewErrReply(t, "You are not allowed to download folders."))
1458 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
1463 transferSize, err := CalcTotalSize(fullFilePath)
1467 itemCount, err := CalcItemCount(fullFilePath)
1472 fileTransfer := cc.newFileTransfer(FolderDownload, t.GetField(fieldFileName).Data, t.GetField(fieldFilePath).Data, transferSize)
1475 err = fp.UnmarshalBinary(t.GetField(fieldFilePath).Data)
1480 res = append(res, cc.NewReply(t,
1481 NewField(fieldRefNum, fileTransfer.ReferenceNumber),
1482 NewField(fieldTransferSize, transferSize),
1483 NewField(fieldFolderItemCount, itemCount),
1484 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1489 // Upload all files from the local folder and its subfolders to the specified path on the server
1490 // Fields used in the request
1493 // 108 transfer size Total size of all items in the folder
1494 // 220 Folder item count
1495 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1496 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1498 if t.GetField(fieldFilePath).Data != nil {
1499 if err = fp.UnmarshalBinary(t.GetField(fieldFilePath).Data); err != nil {
1504 // Handle special cases for Upload and Drop Box folders
1505 if !cc.Authorize(accessUploadAnywhere) {
1506 if !fp.IsUploadDir() && !fp.IsDropbox() {
1507 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))))
1512 fileTransfer := cc.newFileTransfer(FolderUpload,
1513 t.GetField(fieldFileName).Data,
1514 t.GetField(fieldFilePath).Data,
1515 t.GetField(fieldTransferSize).Data,
1518 fileTransfer.FolderItemCount = t.GetField(fieldFolderItemCount).Data
1520 res = append(res, cc.NewReply(t, NewField(fieldRefNum, fileTransfer.ReferenceNumber)))
1525 // Fields used in the request:
1528 // 204 File transfer options "Optional
1529 // Used only to resume download, currently has value 2"
1530 // 108 File transfer size "Optional used if download is not resumed"
1531 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1532 if !cc.Authorize(accessUploadFile) {
1533 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1537 fileName := t.GetField(fieldFileName).Data
1538 filePath := t.GetField(fieldFilePath).Data
1539 transferOptions := t.GetField(fieldFileTransferOptions).Data
1540 transferSize := t.GetField(fieldTransferSize).Data // not sent for resume
1543 if filePath != nil {
1544 if err = fp.UnmarshalBinary(filePath); err != nil {
1549 // Handle special cases for Upload and Drop Box folders
1550 if !cc.Authorize(accessUploadAnywhere) {
1551 if !fp.IsUploadDir() && !fp.IsDropbox() {
1552 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))))
1556 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1561 if _, err := cc.Server.FS.Stat(fullFilePath); err == nil {
1562 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))))
1566 ft := cc.newFileTransfer(FileUpload, fileName, filePath, transferSize)
1568 replyT := cc.NewReply(t, NewField(fieldRefNum, ft.ReferenceNumber))
1570 // client has requested to resume a partially transferred file
1571 if transferOptions != nil {
1573 fileInfo, err := cc.Server.FS.Stat(fullFilePath + incompleteFileSuffix)
1578 offset := make([]byte, 4)
1579 binary.BigEndian.PutUint32(offset, uint32(fileInfo.Size()))
1581 fileResumeData := NewFileResumeData([]ForkInfoList{
1582 *NewForkInfoList(offset),
1585 b, _ := fileResumeData.BinaryMarshal()
1587 ft.TransferSize = offset
1589 replyT.Fields = append(replyT.Fields, NewField(fieldFileResumeData, b))
1592 res = append(res, replyT)
1596 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1597 if len(t.GetField(fieldUserIconID).Data) == 4 {
1598 cc.Icon = t.GetField(fieldUserIconID).Data[2:]
1600 cc.Icon = t.GetField(fieldUserIconID).Data
1602 if cc.Authorize(accessAnyName) {
1603 cc.UserName = t.GetField(fieldUserName).Data
1606 // the options field is only passed by the client versions > 1.2.3.
1607 options := t.GetField(fieldOptions).Data
1609 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1610 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
1612 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, optBitmap.Bit(refusePM))
1613 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1615 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, optBitmap.Bit(refuseChat))
1616 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1618 // Check auto response
1619 if optBitmap.Bit(autoResponse) == 1 {
1620 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
1622 cc.AutoReply = []byte{}
1626 for _, c := range sortedClients(cc.Server.Clients) {
1627 res = append(res, *NewTransaction(
1628 tranNotifyChangeUser,
1630 NewField(fieldUserID, *cc.ID),
1631 NewField(fieldUserIconID, cc.Icon),
1632 NewField(fieldUserFlags, cc.Flags),
1633 NewField(fieldUserName, cc.UserName),
1640 // HandleKeepAlive responds to keepalive transactions with an empty reply
1641 // * HL 1.9.2 Client sends keepalive msg every 3 minutes
1642 // * HL 1.2.3 Client doesn't send keepalives
1643 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1644 res = append(res, cc.NewReply(t))
1649 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1650 fullPath, err := readPath(
1651 cc.Server.Config.FileRoot,
1652 t.GetField(fieldFilePath).Data,
1660 if t.GetField(fieldFilePath).Data != nil {
1661 if err = fp.UnmarshalBinary(t.GetField(fieldFilePath).Data); err != nil {
1666 // Handle special case for drop box folders
1667 if fp.IsDropbox() && !cc.Authorize(accessViewDropBoxes) {
1668 res = append(res, cc.NewErrReply(t, "You are not allowed to view drop boxes."))
1672 fileNames, err := getFileNameList(fullPath, cc.Server.Config.IgnoreFiles)
1677 res = append(res, cc.NewReply(t, fileNames...))
1682 // =================================
1683 // Hotline private chat flow
1684 // =================================
1685 // 1. ClientA sends tranInviteNewChat to server with user ID to invite
1686 // 2. Server creates new ChatID
1687 // 3. Server sends tranInviteToChat to invitee
1688 // 4. Server replies to ClientA with new Chat ID
1690 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1691 // If Accepted is clicked:
1692 // 1. ClientB sends tranJoinChat with fieldChatID
1694 // HandleInviteNewChat invites users to new private chat
1695 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1696 if !cc.Authorize(accessOpenChat) {
1697 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1702 targetID := t.GetField(fieldUserID).Data
1703 newChatID := cc.Server.NewPrivateChat(cc)
1709 NewField(fieldChatID, newChatID),
1710 NewField(fieldUserName, cc.UserName),
1711 NewField(fieldUserID, *cc.ID),
1717 NewField(fieldChatID, newChatID),
1718 NewField(fieldUserName, cc.UserName),
1719 NewField(fieldUserID, *cc.ID),
1720 NewField(fieldUserIconID, cc.Icon),
1721 NewField(fieldUserFlags, cc.Flags),
1728 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1729 if !cc.Authorize(accessOpenChat) {
1730 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1735 targetID := t.GetField(fieldUserID).Data
1736 chatID := t.GetField(fieldChatID).Data
1742 NewField(fieldChatID, chatID),
1743 NewField(fieldUserName, cc.UserName),
1744 NewField(fieldUserID, *cc.ID),
1750 NewField(fieldChatID, chatID),
1751 NewField(fieldUserName, cc.UserName),
1752 NewField(fieldUserID, *cc.ID),
1753 NewField(fieldUserIconID, cc.Icon),
1754 NewField(fieldUserFlags, cc.Flags),
1761 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1762 chatID := t.GetField(fieldChatID).Data
1763 chatInt := binary.BigEndian.Uint32(chatID)
1765 privChat := cc.Server.PrivateChats[chatInt]
1767 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1769 for _, c := range sortedClients(privChat.ClientConn) {
1774 NewField(fieldChatID, chatID),
1775 NewField(fieldData, resMsg),
1783 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1784 // Fields used in the reply:
1785 // * 115 Chat subject
1786 // * 300 User name with info (Optional)
1787 // * 300 (more user names with info)
1788 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1789 chatID := t.GetField(fieldChatID).Data
1790 chatInt := binary.BigEndian.Uint32(chatID)
1792 privChat := cc.Server.PrivateChats[chatInt]
1794 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1795 for _, c := range sortedClients(privChat.ClientConn) {
1798 tranNotifyChatChangeUser,
1800 NewField(fieldChatID, chatID),
1801 NewField(fieldUserName, cc.UserName),
1802 NewField(fieldUserID, *cc.ID),
1803 NewField(fieldUserIconID, cc.Icon),
1804 NewField(fieldUserFlags, cc.Flags),
1809 privChat.ClientConn[cc.uint16ID()] = cc
1811 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1812 for _, c := range sortedClients(privChat.ClientConn) {
1817 Name: string(c.UserName),
1820 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1823 res = append(res, cc.NewReply(t, replyFields...))
1827 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1828 // Fields used in the request:
1829 // * 114 fieldChatID
1830 // Reply is not expected.
1831 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1832 chatID := t.GetField(fieldChatID).Data
1833 chatInt := binary.BigEndian.Uint32(chatID)
1835 privChat, ok := cc.Server.PrivateChats[chatInt]
1840 delete(privChat.ClientConn, cc.uint16ID())
1842 // Notify members of the private chat that the user has left
1843 for _, c := range sortedClients(privChat.ClientConn) {
1846 tranNotifyChatDeleteUser,
1848 NewField(fieldChatID, chatID),
1849 NewField(fieldUserID, *cc.ID),
1857 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1858 // Fields used in the request:
1860 // * 115 Chat subject Chat subject string
1861 // Reply is not expected.
1862 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1863 chatID := t.GetField(fieldChatID).Data
1864 chatInt := binary.BigEndian.Uint32(chatID)
1866 privChat := cc.Server.PrivateChats[chatInt]
1867 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1869 for _, c := range sortedClients(privChat.ClientConn) {
1872 tranNotifyChatSubject,
1874 NewField(fieldChatID, chatID),
1875 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),
1883 // HandleMakeAlias makes a filer alias using the specified path.
1884 // Fields used in the request:
1887 // 212 File new path Destination path
1889 // Fields used in the reply:
1891 func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1892 if !cc.Authorize(accessMakeAlias) {
1893 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
1896 fileName := t.GetField(fieldFileName).Data
1897 filePath := t.GetField(fieldFilePath).Data
1898 fileNewPath := t.GetField(fieldFileNewPath).Data
1900 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1905 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
1910 cc.logger.Debugw("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
1912 if err := cc.Server.FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
1913 res = append(res, cc.NewErrReply(t, "Error creating alias"))
1917 res = append(res, cc.NewReply(t))
1921 func HandleDownloadBanner(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1922 fi, err := cc.Server.FS.Stat(filepath.Join(cc.Server.ConfigDir, cc.Server.Config.BannerFile))
1927 ft := cc.newFileTransfer(bannerDownload, []byte{}, []byte{}, make([]byte, 4))
1929 binary.BigEndian.PutUint32(ft.TransferSize, uint32(fi.Size()))
1931 res = append(res, cc.NewReply(t,
1932 NewField(fieldRefNum, ft.refNum[:]),
1933 NewField(fieldTransferSize, ft.TransferSize),