18 type TransactionType struct {
19 Access int // Specifies access privilege required to perform the transaction
20 DenyMsg string // The error reply message when user does not have access
21 Handler func(*ClientConn, *Transaction) ([]Transaction, error) // function for handling the transaction type
22 Name string // Name of transaction as it will appear in logging
23 RequiredFields []requiredField
26 var TransactionHandlers = map[uint16]TransactionType{
32 tranNotifyChangeUser: {
33 Name: "tranNotifyChangeUser",
39 Name: "tranShowAgreement",
42 Name: "tranUserAccess",
44 tranNotifyDeleteUser: {
45 Name: "tranNotifyDeleteUser",
48 Access: accessAlwaysAllow,
50 Handler: HandleTranAgreed,
53 Access: accessSendChat,
54 DenyMsg: "You are not allowed to participate in chat.",
55 Handler: HandleChatSend,
57 RequiredFields: []requiredField{
65 Access: accessNewsDeleteArt,
66 DenyMsg: "You are not allowed to delete news articles.",
67 Name: "tranDelNewsArt",
68 Handler: HandleDelNewsArt,
71 Access: accessAlwaysAllow, // Granular access enforced inside the handler
72 // Has multiple access flags: News Delete Folder (37) or News Delete Category (35)
73 // TODO: Implement inside the handler
74 Name: "tranDelNewsItem",
75 Handler: HandleDelNewsItem,
78 Access: accessAlwaysAllow, // Granular access enforced inside the handler
79 Name: "tranDeleteFile",
80 Handler: HandleDeleteFile,
83 Access: accessDeleteUser,
84 DenyMsg: "You are not allowed to delete accounts.",
85 Name: "tranDeleteUser",
86 Handler: HandleDeleteUser,
89 Access: accessDisconUser,
90 DenyMsg: "You are not allowed to disconnect users.",
91 Name: "tranDisconnectUser",
92 Handler: HandleDisconnectUser,
95 Access: accessDownloadFile,
96 DenyMsg: "You are not allowed to download files.",
97 Name: "tranDownloadFile",
98 Handler: HandleDownloadFile,
101 Access: accessDownloadFile, // There is no specific access flag for folder vs file download
102 DenyMsg: "You are not allowed to download files.",
103 Name: "tranDownloadFldr",
104 Handler: HandleDownloadFolder,
106 tranGetClientInfoText: {
107 Access: accessGetClientInfo,
108 DenyMsg: "You are not allowed to get client info",
109 Name: "tranGetClientInfoText",
110 Handler: HandleGetClientConnInfoText,
113 Access: accessAlwaysAllow,
114 Name: "tranGetFileInfo",
115 Handler: HandleGetFileInfo,
117 tranGetFileNameList: {
118 Access: accessAlwaysAllow,
119 Name: "tranGetFileNameList",
120 Handler: HandleGetFileNameList,
123 Access: accessNewsReadArt,
124 DenyMsg: "You are not allowed to read news.",
126 Handler: HandleGetMsgs,
128 tranGetNewsArtData: {
129 Access: accessNewsReadArt,
130 DenyMsg: "You are not allowed to read news.",
131 Name: "tranGetNewsArtData",
132 Handler: HandleGetNewsArtData,
134 tranGetNewsArtNameList: {
135 Access: accessNewsReadArt,
136 DenyMsg: "You are not allowed to read news.",
137 Name: "tranGetNewsArtNameList",
138 Handler: HandleGetNewsArtNameList,
140 tranGetNewsCatNameList: {
141 Access: accessNewsReadArt,
142 DenyMsg: "You are not allowed to read news.",
143 Name: "tranGetNewsCatNameList",
144 Handler: HandleGetNewsCatNameList,
147 Access: accessOpenUser,
148 DenyMsg: "You are not allowed to view accounts.",
150 Handler: HandleGetUser,
152 tranGetUserNameList: {
153 Access: accessAlwaysAllow,
154 Name: "tranHandleGetUserNameList",
155 Handler: HandleGetUserNameList,
158 Access: accessOpenChat,
159 DenyMsg: "You are not allowed to request private chat.",
160 Name: "tranInviteNewChat",
161 Handler: HandleInviteNewChat,
164 Access: accessOpenChat,
165 DenyMsg: "You are not allowed to request private chat.",
166 Name: "tranInviteToChat",
167 Handler: HandleInviteToChat,
170 Access: accessAlwaysAllow,
171 Name: "tranJoinChat",
172 Handler: HandleJoinChat,
175 Access: accessAlwaysAllow,
176 Name: "tranKeepAlive",
177 Handler: HandleKeepAlive,
180 Access: accessAlwaysAllow,
181 Name: "tranJoinChat",
182 Handler: HandleLeaveChat,
186 Access: accessOpenUser,
187 DenyMsg: "You are not allowed to view accounts.",
188 Name: "tranListUsers",
189 Handler: HandleListUsers,
192 Access: accessMoveFile,
193 DenyMsg: "You are not allowed to move files.",
194 Name: "tranMoveFile",
195 Handler: HandleMoveFile,
198 Access: accessCreateFolder,
199 DenyMsg: "You are not allow to create folders.",
200 Name: "tranNewFolder",
201 Handler: HandleNewFolder,
204 Access: accessNewsCreateCat,
205 DenyMsg: "You are not allowed to create news categories.",
206 Name: "tranNewNewsCat",
207 Handler: HandleNewNewsCat,
210 Access: accessNewsCreateFldr,
211 DenyMsg: "You are not allowed to create news folders.",
212 Name: "tranNewNewsFldr",
213 Handler: HandleNewNewsFldr,
216 Access: accessCreateUser,
217 DenyMsg: "You are not allowed to create new accounts.",
219 Handler: HandleNewUser,
222 Access: accessNewsPostArt,
223 DenyMsg: "You are not allowed to post news.",
224 Name: "tranOldPostNews",
225 Handler: HandleTranOldPostNews,
228 Access: accessNewsPostArt,
229 DenyMsg: "You are not allowed to post news articles.",
230 Name: "tranPostNewsArt",
231 Handler: HandlePostNewsArt,
233 tranRejectChatInvite: {
234 Access: accessAlwaysAllow,
235 Name: "tranRejectChatInvite",
236 Handler: HandleRejectChatInvite,
238 tranSendInstantMsg: {
239 Access: accessAlwaysAllow,
240 //Access: accessSendPrivMsg,
241 //DenyMsg: "You are not allowed to send private messages",
242 Name: "tranSendInstantMsg",
243 Handler: HandleSendInstantMsg,
244 RequiredFields: []requiredField{
254 tranSetChatSubject: {
255 Access: accessAlwaysAllow,
256 Name: "tranSetChatSubject",
257 Handler: HandleSetChatSubject,
259 tranSetClientUserInfo: {
260 Access: accessAlwaysAllow,
261 Name: "tranSetClientUserInfo",
262 Handler: HandleSetClientUserInfo,
265 Access: accessAlwaysAllow, // granular access is in the handler
266 Name: "tranSetFileInfo",
267 Handler: HandleSetFileInfo,
270 Access: accessModifyUser,
271 DenyMsg: "You are not allowed to modify accounts.",
273 Handler: HandleSetUser,
276 Access: accessUploadFile,
277 DenyMsg: "You are not allowed to upload files.",
278 Name: "tranUploadFile",
279 Handler: HandleUploadFile,
282 Access: accessAlwaysAllow, // TODO: what should this be?
283 Name: "tranUploadFldr",
284 Handler: HandleUploadFolder,
287 Access: accessBroadcast,
288 DenyMsg: "You are not allowed to send broadcast messages.",
289 Name: "tranUserBroadcast",
290 Handler: HandleUserBroadcast,
294 func HandleChatSend(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
295 // Truncate long usernames
296 trunc := fmt.Sprintf("%13s", cc.UserName)
297 formattedMsg := fmt.Sprintf("\r%.14s: %s", trunc, t.GetField(fieldData).Data)
299 // By holding the option key, Hotline chat allows users to send /me formatted messages like:
300 // *** Halcyon does stuff
301 // This is indicated by the presence of the optional field fieldChatOptions in the transaction payload
302 if t.GetField(fieldChatOptions).Data != nil {
303 formattedMsg = fmt.Sprintf("\r*** %s %s", cc.UserName, t.GetField(fieldData).Data)
306 if bytes.Equal(t.GetField(fieldData).Data, []byte("/stats")) {
307 formattedMsg = strings.Replace(cc.Server.Stats.String(), "\n", "\r", -1)
310 chatID := t.GetField(fieldChatID).Data
311 // a non-nil chatID indicates the message belongs to a private chat
313 chatInt := binary.BigEndian.Uint32(chatID)
314 privChat := cc.Server.PrivateChats[chatInt]
316 // send the message to all connected clients of the private chat
317 for _, c := range privChat.ClientConn {
318 res = append(res, *NewTransaction(
321 NewField(fieldChatID, chatID),
322 NewField(fieldData, []byte(formattedMsg)),
328 for _, c := range sortedClients(cc.Server.Clients) {
329 // Filter out clients that do not have the read chat permission
330 if authorize(c.Account.Access, accessReadChat) {
331 res = append(res, *NewTransaction(tranChatMsg, c.ID, NewField(fieldData, []byte(formattedMsg))))
338 // HandleSendInstantMsg sends instant message to the user on the current server.
339 // Fields used in the request:
342 // One of the following values:
343 // - User message (myOpt_UserMessage = 1)
344 // - Refuse message (myOpt_RefuseMessage = 2)
345 // - Refuse chat (myOpt_RefuseChat = 3)
346 // - Automatic response (myOpt_AutomaticResponse = 4)"
348 // 214 Quoting message Optional
350 //Fields used in the reply:
352 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
353 msg := t.GetField(fieldData)
354 ID := t.GetField(fieldUserID)
355 // TODO: Implement reply quoting
356 //options := transaction.GetField(hotline.fieldOptions)
362 NewField(fieldData, msg.Data),
363 NewField(fieldUserName, cc.UserName),
364 NewField(fieldUserID, *cc.ID),
365 NewField(fieldOptions, []byte{0, 1}),
368 id, _ := byteToInt(ID.Data)
370 //keys := make([]uint16, 0, len(cc.Server.Clients))
371 //for k := range cc.Server.Clients {
372 // keys = append(keys, k)
375 otherClient := cc.Server.Clients[uint16(id)]
376 if otherClient == nil {
377 return res, errors.New("ohno")
380 // Respond with auto reply if other client has it enabled
381 if len(*otherClient.AutoReply) > 0 {
386 NewField(fieldData, *otherClient.AutoReply),
387 NewField(fieldUserName, otherClient.UserName),
388 NewField(fieldUserID, *otherClient.ID),
389 NewField(fieldOptions, []byte{0, 1}),
394 res = append(res, cc.NewReply(t))
399 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
400 fileName := t.GetField(fieldFileName).Data
401 filePath := t.GetField(fieldFilePath).Data
403 ffo, err := NewFlattenedFileObject(cc.Server.Config.FileRoot, filePath, fileName)
408 res = append(res, cc.NewReply(t,
409 NewField(fieldFileName, fileName),
410 NewField(fieldFileTypeString, ffo.FlatFileInformationFork.TypeSignature),
411 NewField(fieldFileCreatorString, ffo.FlatFileInformationFork.CreatorSignature),
412 NewField(fieldFileComment, ffo.FlatFileInformationFork.Comment),
413 NewField(fieldFileType, ffo.FlatFileInformationFork.TypeSignature),
414 NewField(fieldFileCreateDate, ffo.FlatFileInformationFork.CreateDate),
415 NewField(fieldFileModifyDate, ffo.FlatFileInformationFork.ModifyDate),
416 NewField(fieldFileSize, ffo.FlatFileDataForkHeader.DataSize),
421 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
422 // TODO: Implement support for comments
423 // Fields used in the request:
425 // * 202 File path Optional
426 // * 211 File new name Optional
427 // * 210 File comment Optional
428 // Fields used in the reply: None
429 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
430 fileName := t.GetField(fieldFileName).Data
431 filePath := t.GetField(fieldFilePath).Data
433 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
438 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, t.GetField(fieldFileNewName).Data)
443 //fileComment := t.GetField(fieldFileComment).Data
444 fileNewName := t.GetField(fieldFileNewName).Data
446 if fileNewName != nil {
447 fi, err := FS.Stat(fullFilePath)
451 switch mode := fi.Mode(); {
453 if !authorize(cc.Account.Access, accessRenameFolder) {
454 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
457 case mode.IsRegular():
458 if !authorize(cc.Account.Access, accessRenameFile) {
459 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
464 err = os.Rename(fullFilePath, fullNewFilePath)
465 if os.IsNotExist(err) {
466 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 cc.Server.Logger.Debugw("Delete file", "src", fullFilePath)
491 fi, err := os.Stat(fullFilePath)
493 res = append(res, cc.NewErrReply(t, "Cannot delete file "+string(fileName)+" because it does not exist or cannot be found."))
496 switch mode := fi.Mode(); {
498 if !authorize(cc.Account.Access, accessDeleteFolder) {
499 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
502 case mode.IsRegular():
503 if !authorize(cc.Account.Access, accessDeleteFile) {
504 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
509 if err := os.RemoveAll(fullFilePath); err != nil {
513 res = append(res, cc.NewReply(t))
517 // HandleMoveFile moves files or folders. Note: seemingly not documented
518 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
519 fileName := string(t.GetField(fieldFileName).Data)
520 filePath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
521 fileNewPath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFileNewPath).Data)
523 cc.Server.Logger.Debugw("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
525 path := filePath + "/" + fileName
526 fi, err := os.Stat(path)
530 switch mode := fi.Mode(); {
532 if !authorize(cc.Account.Access, accessMoveFolder) {
533 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
536 case mode.IsRegular():
537 if !authorize(cc.Account.Access, accessMoveFile) {
538 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
543 err = os.Rename(filePath+"/"+fileName, fileNewPath+"/"+fileName)
544 if os.IsNotExist(err) {
545 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
549 return []Transaction{}, err
551 // TODO: handle other possible errors; e.g. file delete fails due to file permission issue
553 res = append(res, cc.NewReply(t))
557 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
558 newFolderPath := cc.Server.Config.FileRoot
559 folderName := string(t.GetField(fieldFileName).Data)
561 folderName = path.Join("/", folderName)
563 // fieldFilePath is only present for nested paths
564 if t.GetField(fieldFilePath).Data != nil {
566 err := newFp.UnmarshalBinary(t.GetField(fieldFilePath).Data)
570 newFolderPath += newFp.String()
572 newFolderPath = path.Join(newFolderPath, folderName)
574 // TODO: check path and folder name lengths
576 if _, err := FS.Stat(newFolderPath); !os.IsNotExist(err) {
577 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that name.", folderName)
578 return []Transaction{cc.NewErrReply(t, msg)}, nil
581 // TODO: check for disallowed characters to maintain compatibility for original client
583 if err := FS.Mkdir(newFolderPath, 0777); err != nil {
584 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
585 return []Transaction{cc.NewErrReply(t, msg)}, nil
588 res = append(res, cc.NewReply(t))
592 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
593 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
594 userName := string(t.GetField(fieldUserName).Data)
596 newAccessLvl := t.GetField(fieldUserAccess).Data
598 account := cc.Server.Accounts[login]
599 account.Access = &newAccessLvl
600 account.Name = userName
602 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
603 // not include fieldUserPassword
604 if t.GetField(fieldUserPassword).Data == nil {
605 account.Password = hashAndSalt([]byte(""))
607 if len(t.GetField(fieldUserPassword).Data) > 1 {
608 account.Password = hashAndSalt(t.GetField(fieldUserPassword).Data)
611 file := cc.Server.ConfigDir + "Users/" + login + ".yaml"
612 out, err := yaml.Marshal(&account)
616 if err := ioutil.WriteFile(file, out, 0666); err != nil {
620 // Notify connected clients logged in as the user of the new access level
621 for _, c := range cc.Server.Clients {
622 if c.Account.Login == login {
623 // Note: comment out these two lines to test server-side deny messages
624 newT := NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, newAccessLvl))
625 res = append(res, *newT)
627 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
628 if authorize(c.Account.Access, accessDisconUser) {
629 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 1)
631 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 0)
633 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
635 c.Account.Access = account.Access
638 tranNotifyChangeUser,
639 NewField(fieldUserID, *c.ID),
640 NewField(fieldUserFlags, *c.Flags),
641 NewField(fieldUserName, c.UserName),
642 NewField(fieldUserIconID, *c.Icon),
647 // TODO: If we have just promoted a connected user to admin, notify
648 // connected clients to turn the user red
650 res = append(res, cc.NewReply(t))
654 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
655 userLogin := string(t.GetField(fieldUserLogin).Data)
656 account := cc.Server.Accounts[userLogin]
658 errorT := cc.NewErrReply(t, "Account does not exist.")
659 res = append(res, errorT)
663 res = append(res, cc.NewReply(t,
664 NewField(fieldUserName, []byte(account.Name)),
665 NewField(fieldUserLogin, negateString(t.GetField(fieldUserLogin).Data)),
666 NewField(fieldUserPassword, []byte(account.Password)),
667 NewField(fieldUserAccess, *account.Access),
672 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
673 var userFields []Field
674 // TODO: make order deterministic
675 for _, acc := range cc.Server.Accounts {
676 userField := acc.MarshalBinary()
677 userFields = append(userFields, NewField(fieldData, userField))
680 res = append(res, cc.NewReply(t, userFields...))
684 // HandleNewUser creates a new user account
685 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
686 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
688 // If the account already exists, reply with an error
689 // TODO: make order deterministic
690 if _, ok := cc.Server.Accounts[login]; ok {
691 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
695 if err := cc.Server.NewUser(
697 string(t.GetField(fieldUserName).Data),
698 string(t.GetField(fieldUserPassword).Data),
699 t.GetField(fieldUserAccess).Data,
701 return []Transaction{}, err
704 res = append(res, cc.NewReply(t))
708 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
709 // TODO: Handle case where account doesn't exist; e.g. delete race condition
710 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
712 if err := cc.Server.DeleteUser(login); err != nil {
716 res = append(res, cc.NewReply(t))
720 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
721 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
724 NewField(fieldData, t.GetField(tranGetMsgs).Data),
725 NewField(fieldChatOptions, []byte{0}),
728 res = append(res, cc.NewReply(t))
732 func byteToInt(bytes []byte) (int, error) {
735 return int(binary.BigEndian.Uint16(bytes)), nil
737 return int(binary.BigEndian.Uint32(bytes)), nil
740 return 0, errors.New("unknown byte length")
743 func HandleGetClientConnInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
744 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
746 clientConn := cc.Server.Clients[uint16(clientID)]
747 if clientConn == nil {
748 return res, errors.New("invalid client")
751 // TODO: Implement non-hardcoded values
752 template := `Nickname: %s
757 -------- File Downloads ---------
761 ------- Folder Downloads --------
765 --------- File Uploads ----------
769 -------- Folder Uploads ---------
773 ------- Waiting Downloads -------
779 activeDownloads := clientConn.Transfers[FileDownload]
780 activeDownloadList := "None."
781 for _, dl := range activeDownloads {
782 activeDownloadList += dl.String() + "\n"
785 template = fmt.Sprintf(
788 clientConn.Account.Name,
789 clientConn.Account.Login,
790 clientConn.Connection.RemoteAddr().String(),
793 template = strings.Replace(template, "\n", "\r", -1)
795 res = append(res, cc.NewReply(t,
796 NewField(fieldData, []byte(template)),
797 NewField(fieldUserName, clientConn.UserName),
802 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
803 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
808 func (cc *ClientConn) notifyNewUserHasJoined() (res []Transaction, err error) {
809 // Notify other ccs that a new user has connected
812 tranNotifyChangeUser, nil,
813 NewField(fieldUserName, cc.UserName),
814 NewField(fieldUserID, *cc.ID),
815 NewField(fieldUserIconID, *cc.Icon),
816 NewField(fieldUserFlags, *cc.Flags),
823 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
824 bs := make([]byte, 2)
825 binary.BigEndian.PutUint16(bs, *cc.Server.NextGuestID)
827 cc.UserName = t.GetField(fieldUserName).Data
829 *cc.Icon = t.GetField(fieldUserIconID).Data
831 options := t.GetField(fieldOptions).Data
832 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
834 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
836 // Check refuse private PM option
837 if optBitmap.Bit(refusePM) == 1 {
838 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
839 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
842 // Check refuse private chat option
843 if optBitmap.Bit(refuseChat) == 1 {
844 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
845 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
848 // Check auto response
849 if optBitmap.Bit(autoResponse) == 1 {
850 *cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
852 *cc.AutoReply = []byte{}
855 _, _ = cc.notifyNewUserHasJoined()
857 res = append(res, cc.NewReply(t))
862 const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
863 // "Mon, 02 Jan 2006 15:04:05 MST"
865 const defaultNewsTemplate = `From %s (%s):
869 __________________________________________________________`
871 // HandleTranOldPostNews updates the flat news
872 // Fields used in this request:
874 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
875 cc.Server.flatNewsMux.Lock()
876 defer cc.Server.flatNewsMux.Unlock()
878 newsDateTemplate := defaultNewsDateFormat
879 if cc.Server.Config.NewsDateFormat != "" {
880 newsDateTemplate = cc.Server.Config.NewsDateFormat
883 newsTemplate := defaultNewsTemplate
884 if cc.Server.Config.NewsDelimiter != "" {
885 newsTemplate = cc.Server.Config.NewsDelimiter
888 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
889 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
891 // update news in memory
892 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
894 // update news on disk
895 if err := ioutil.WriteFile(cc.Server.ConfigDir+"MessageBoard.txt", cc.Server.FlatNews, 0644); err != nil {
899 // Notify all clients of updated news
902 NewField(fieldData, []byte(newsPost)),
905 res = append(res, cc.NewReply(t))
909 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
910 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
912 if authorize(clientConn.Account.Access, accessCannotBeDiscon) {
913 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
917 if err := clientConn.Connection.Close(); err != nil {
921 res = append(res, cc.NewReply(t))
925 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
926 // Fields used in the request:
927 // 325 News path (Optional)
929 newsPath := t.GetField(fieldNewsPath).Data
930 cc.Server.Logger.Infow("NewsPath: ", "np", string(newsPath))
932 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
933 cats := cc.Server.GetNewsCatByPath(pathStrs)
935 // To store the keys in slice in sorted order
936 keys := make([]string, len(cats))
938 for k := range cats {
944 var fieldData []Field
945 for _, k := range keys {
947 b, _ := cat.MarshalBinary()
948 fieldData = append(fieldData, NewField(
949 fieldNewsCatListData15,
954 res = append(res, cc.NewReply(t, fieldData...))
958 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
959 name := string(t.GetField(fieldNewsCatName).Data)
960 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
962 cats := cc.Server.GetNewsCatByPath(pathStrs)
963 cats[name] = NewsCategoryListData15{
966 Articles: map[uint32]*NewsArtData{},
967 SubCats: make(map[string]NewsCategoryListData15),
970 if err := cc.Server.writeThreadedNews(); err != nil {
973 res = append(res, cc.NewReply(t))
977 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
978 // Fields used in the request:
979 // 322 News category name
981 name := string(t.GetField(fieldFileName).Data)
982 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
984 cc.Server.Logger.Infof("Creating new news folder %s", name)
986 cats := cc.Server.GetNewsCatByPath(pathStrs)
987 cats[name] = NewsCategoryListData15{
990 Articles: map[uint32]*NewsArtData{},
991 SubCats: make(map[string]NewsCategoryListData15),
993 if err := cc.Server.writeThreadedNews(); err != nil {
996 res = append(res, cc.NewReply(t))
1000 // Fields used in the request:
1001 // 325 News path Optional
1004 // 321 News article list data Optional
1005 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1006 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1008 var cat NewsCategoryListData15
1009 cats := cc.Server.ThreadedNews.Categories
1011 for _, path := range pathStrs {
1013 cats = cats[path].SubCats
1016 nald := cat.GetNewsArtListData()
1018 res = append(res, cc.NewReply(t, NewField(fieldNewsArtListData, nald.Payload())))
1022 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1025 // 326 News article ID
1026 // 327 News article data flavor
1028 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1030 var cat NewsCategoryListData15
1031 cats := cc.Server.ThreadedNews.Categories
1033 for _, path := range pathStrs {
1035 cats = cats[path].SubCats
1037 newsArtID := t.GetField(fieldNewsArtID).Data
1039 convertedArtID := binary.BigEndian.Uint16(newsArtID)
1041 art := cat.Articles[uint32(convertedArtID)]
1043 res = append(res, cc.NewReply(t))
1048 // 328 News article title
1049 // 329 News article poster
1050 // 330 News article date
1051 // 331 Previous article ID
1052 // 332 Next article ID
1053 // 335 Parent article ID
1054 // 336 First child article ID
1055 // 327 News article data flavor "Should be “text/plain”
1056 // 333 News article data Optional (if data flavor is “text/plain”)
1058 res = append(res, cc.NewReply(t,
1059 NewField(fieldNewsArtTitle, []byte(art.Title)),
1060 NewField(fieldNewsArtPoster, []byte(art.Poster)),
1061 NewField(fieldNewsArtDate, art.Date),
1062 NewField(fieldNewsArtPrevArt, art.PrevArt),
1063 NewField(fieldNewsArtNextArt, art.NextArt),
1064 NewField(fieldNewsArtParentArt, art.ParentArt),
1065 NewField(fieldNewsArt1stChildArt, art.FirstChildArt),
1066 NewField(fieldNewsArtDataFlav, []byte("text/plain")),
1067 NewField(fieldNewsArtData, []byte(art.Data)),
1072 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1073 // Access: News Delete Folder (37) or News Delete Category (35)
1075 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1077 // TODO: determine if path is a Folder (Bundle) or Category and check for permission
1079 cc.Server.Logger.Infof("DelNewsItem %v", pathStrs)
1081 cats := cc.Server.ThreadedNews.Categories
1083 delName := pathStrs[len(pathStrs)-1]
1084 if len(pathStrs) > 1 {
1085 for _, path := range pathStrs[0 : len(pathStrs)-1] {
1086 cats = cats[path].SubCats
1090 delete(cats, delName)
1092 err = cc.Server.writeThreadedNews()
1097 // Reply params: none
1098 res = append(res, cc.NewReply(t))
1103 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1106 // 326 News article ID
1107 // 337 News article – recursive delete Delete child articles (1) or not (0)
1108 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1109 ID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1111 // TODO: Delete recursive
1112 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1114 catName := pathStrs[len(pathStrs)-1]
1115 cat := cats[catName]
1117 delete(cat.Articles, uint32(ID))
1120 if err := cc.Server.writeThreadedNews(); err != nil {
1124 res = append(res, cc.NewReply(t))
1128 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1131 // 326 News article ID ID of the parent article?
1132 // 328 News article title
1133 // 334 News article flags
1134 // 327 News article data flavor Currently “text/plain”
1135 // 333 News article data
1137 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1138 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1140 catName := pathStrs[len(pathStrs)-1]
1141 cat := cats[catName]
1143 newArt := NewsArtData{
1144 Title: string(t.GetField(fieldNewsArtTitle).Data),
1145 Poster: string(cc.UserName),
1147 PrevArt: []byte{0, 0, 0, 0},
1148 NextArt: []byte{0, 0, 0, 0},
1149 ParentArt: append([]byte{0, 0}, t.GetField(fieldNewsArtID).Data...),
1150 FirstChildArt: []byte{0, 0, 0, 0},
1151 DataFlav: []byte("text/plain"),
1152 Data: string(t.GetField(fieldNewsArtData).Data),
1156 for k := range cat.Articles {
1157 keys = append(keys, int(k))
1163 prevID := uint32(keys[len(keys)-1])
1166 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1168 // Set next article ID
1169 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1172 // Update parent article with first child reply
1173 parentID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1175 parentArt := cat.Articles[uint32(parentID)]
1177 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1178 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1182 cat.Articles[nextID] = &newArt
1185 if err := cc.Server.writeThreadedNews(); err != nil {
1189 res = append(res, cc.NewReply(t))
1193 // HandleGetMsgs returns the flat news data
1194 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1195 res = append(res, cc.NewReply(t, NewField(fieldData, cc.Server.FlatNews)))
1200 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1201 fileName := t.GetField(fieldFileName).Data
1202 filePath := t.GetField(fieldFilePath).Data
1205 err = fp.UnmarshalBinary(filePath)
1210 ffo, err := NewFlattenedFileObject(cc.Server.Config.FileRoot, filePath, fileName)
1215 transactionRef := cc.Server.NewTransactionRef()
1216 data := binary.BigEndian.Uint32(transactionRef)
1218 ft := &FileTransfer{
1221 ReferenceNumber: transactionRef,
1225 cc.Server.FileTransfers[data] = ft
1226 cc.Transfers[FileDownload] = append(cc.Transfers[FileDownload], ft)
1228 res = append(res, cc.NewReply(t,
1229 NewField(fieldRefNum, transactionRef),
1230 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1231 NewField(fieldTransferSize, ffo.TransferSize()),
1232 NewField(fieldFileSize, ffo.FlatFileDataForkHeader.DataSize),
1238 // Download all files from the specified folder and sub-folders
1251 // 00 6c // transfer size
1255 // 00 dc // field Folder item count
1259 // 00 6b // ref number
1262 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1263 transactionRef := cc.Server.NewTransactionRef()
1264 data := binary.BigEndian.Uint32(transactionRef)
1266 fileTransfer := &FileTransfer{
1267 FileName: t.GetField(fieldFileName).Data,
1268 FilePath: t.GetField(fieldFilePath).Data,
1269 ReferenceNumber: transactionRef,
1270 Type: FolderDownload,
1272 cc.Server.FileTransfers[data] = fileTransfer
1273 cc.Transfers[FolderDownload] = append(cc.Transfers[FolderDownload], fileTransfer)
1276 err = fp.UnmarshalBinary(t.GetField(fieldFilePath).Data)
1281 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
1283 transferSize, err := CalcTotalSize(fullFilePath)
1287 itemCount, err := CalcItemCount(fullFilePath)
1291 res = append(res, cc.NewReply(t,
1292 NewField(fieldRefNum, transactionRef),
1293 NewField(fieldTransferSize, transferSize),
1294 NewField(fieldFolderItemCount, itemCount),
1295 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1300 // Upload all files from the local folder and its subfolders to the specified path on the server
1301 // Fields used in the request
1304 // 108 transfer size Total size of all items in the folder
1305 // 220 Folder item count
1306 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1307 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1308 transactionRef := cc.Server.NewTransactionRef()
1309 data := binary.BigEndian.Uint32(transactionRef)
1311 fileTransfer := &FileTransfer{
1312 FileName: t.GetField(fieldFileName).Data,
1313 FilePath: t.GetField(fieldFilePath).Data,
1314 ReferenceNumber: transactionRef,
1316 FolderItemCount: t.GetField(fieldFolderItemCount).Data,
1317 TransferSize: t.GetField(fieldTransferSize).Data,
1319 cc.Server.FileTransfers[data] = fileTransfer
1321 res = append(res, cc.NewReply(t, NewField(fieldRefNum, transactionRef)))
1325 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1326 fileName := t.GetField(fieldFileName).Data
1327 filePath := t.GetField(fieldFilePath).Data
1329 transactionRef := cc.Server.NewTransactionRef()
1330 data := binary.BigEndian.Uint32(transactionRef)
1332 fileTransfer := &FileTransfer{
1335 ReferenceNumber: transactionRef,
1339 cc.Server.FileTransfers[data] = fileTransfer
1341 res = append(res, cc.NewReply(t, NewField(fieldRefNum, transactionRef)))
1352 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1354 if len(t.GetField(fieldUserIconID).Data) == 4 {
1355 icon = t.GetField(fieldUserIconID).Data[2:]
1357 icon = t.GetField(fieldUserIconID).Data
1360 cc.UserName = t.GetField(fieldUserName).Data
1362 // the options field is only passed by the client versions > 1.2.3.
1363 options := t.GetField(fieldOptions).Data
1366 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1367 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
1369 // Check refuse private PM option
1370 if optBitmap.Bit(refusePM) == 1 {
1371 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
1372 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
1375 // Check refuse private chat option
1376 if optBitmap.Bit(refuseChat) == 1 {
1377 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
1378 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
1381 // Check auto response
1382 if optBitmap.Bit(autoResponse) == 1 {
1383 *cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
1385 *cc.AutoReply = []byte{}
1389 // Notify all clients of updated user info
1391 tranNotifyChangeUser,
1392 NewField(fieldUserID, *cc.ID),
1393 NewField(fieldUserIconID, *cc.Icon),
1394 NewField(fieldUserFlags, *cc.Flags),
1395 NewField(fieldUserName, cc.UserName),
1401 // HandleKeepAlive response to keepalive transactions with an empty reply
1402 // HL 1.9.2 Client sends keepalive msg every 3 minutes
1403 // HL 1.2.3 Client doesn't send keepalives
1404 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1405 res = append(res, cc.NewReply(t))
1410 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1411 fullPath, err := readPath(
1412 cc.Server.Config.FileRoot,
1413 t.GetField(fieldFilePath).Data,
1420 fileNames, err := getFileNameList(fullPath)
1425 res = append(res, cc.NewReply(t, fileNames...))
1430 // =================================
1431 // Hotline private chat flow
1432 // =================================
1433 // 1. ClientA sends tranInviteNewChat to server with user ID to invite
1434 // 2. Server creates new ChatID
1435 // 3. Server sends tranInviteToChat to invitee
1436 // 4. Server replies to ClientA with new Chat ID
1438 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1439 // If Accepted is clicked:
1440 // 1. ClientB sends tranJoinChat with fieldChatID
1442 // HandleInviteNewChat invites users to new private chat
1443 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1445 targetID := t.GetField(fieldUserID).Data
1446 newChatID := cc.Server.NewPrivateChat(cc)
1452 NewField(fieldChatID, newChatID),
1453 NewField(fieldUserName, cc.UserName),
1454 NewField(fieldUserID, *cc.ID),
1460 NewField(fieldChatID, newChatID),
1461 NewField(fieldUserName, cc.UserName),
1462 NewField(fieldUserID, *cc.ID),
1463 NewField(fieldUserIconID, *cc.Icon),
1464 NewField(fieldUserFlags, *cc.Flags),
1471 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1473 targetID := t.GetField(fieldUserID).Data
1474 chatID := t.GetField(fieldChatID).Data
1480 NewField(fieldChatID, chatID),
1481 NewField(fieldUserName, cc.UserName),
1482 NewField(fieldUserID, *cc.ID),
1488 NewField(fieldChatID, chatID),
1489 NewField(fieldUserName, cc.UserName),
1490 NewField(fieldUserID, *cc.ID),
1491 NewField(fieldUserIconID, *cc.Icon),
1492 NewField(fieldUserFlags, *cc.Flags),
1499 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1500 chatID := t.GetField(fieldChatID).Data
1501 chatInt := binary.BigEndian.Uint32(chatID)
1503 privChat := cc.Server.PrivateChats[chatInt]
1505 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1507 for _, c := range sortedClients(privChat.ClientConn) {
1512 NewField(fieldChatID, chatID),
1513 NewField(fieldData, resMsg),
1521 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1522 // Fields used in the reply:
1523 // * 115 Chat subject
1524 // * 300 User name with info (Optional)
1525 // * 300 (more user names with info)
1526 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1527 chatID := t.GetField(fieldChatID).Data
1528 chatInt := binary.BigEndian.Uint32(chatID)
1530 privChat := cc.Server.PrivateChats[chatInt]
1532 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1533 for _, c := range sortedClients(privChat.ClientConn) {
1536 tranNotifyChatChangeUser,
1538 NewField(fieldChatID, chatID),
1539 NewField(fieldUserName, cc.UserName),
1540 NewField(fieldUserID, *cc.ID),
1541 NewField(fieldUserIconID, *cc.Icon),
1542 NewField(fieldUserFlags, *cc.Flags),
1547 privChat.ClientConn[cc.uint16ID()] = cc
1549 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1550 for _, c := range sortedClients(privChat.ClientConn) {
1555 Name: string(c.UserName),
1558 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1561 res = append(res, cc.NewReply(t, replyFields...))
1565 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1566 // Fields used in the request:
1567 // * 114 fieldChatID
1568 // Reply is not expected.
1569 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1570 chatID := t.GetField(fieldChatID).Data
1571 chatInt := binary.BigEndian.Uint32(chatID)
1573 privChat := cc.Server.PrivateChats[chatInt]
1575 delete(privChat.ClientConn, cc.uint16ID())
1577 // Notify members of the private chat that the user has left
1578 for _, c := range sortedClients(privChat.ClientConn) {
1581 tranNotifyChatDeleteUser,
1583 NewField(fieldChatID, chatID),
1584 NewField(fieldUserID, *cc.ID),
1592 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1593 // Fields used in the request:
1595 // * 115 Chat subject Chat subject string
1596 // Reply is not expected.
1597 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1598 chatID := t.GetField(fieldChatID).Data
1599 chatInt := binary.BigEndian.Uint32(chatID)
1601 privChat := cc.Server.PrivateChats[chatInt]
1602 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1604 for _, c := range sortedClients(privChat.ClientConn) {
1607 tranNotifyChatSubject,
1609 NewField(fieldChatID, chatID),
1610 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),