17 type TransactionType struct {
18 Access int // Specifies access privilege required to perform the transaction
19 DenyMsg string // The error reply message when user does not have access
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",
47 Access: accessAlwaysAllow,
49 Handler: HandleTranAgreed,
52 Access: accessSendChat,
53 DenyMsg: "You are not allowed to participate in chat.",
54 Handler: HandleChatSend,
56 RequiredFields: []requiredField{
64 Access: accessNewsDeleteArt,
65 DenyMsg: "You are not allowed to delete news articles.",
66 Name: "tranDelNewsArt",
67 Handler: HandleDelNewsArt,
70 Access: accessAlwaysAllow, // Granular access enforced inside the handler
71 // Has multiple access flags: News Delete Folder (37) or News Delete Category (35)
72 // TODO: Implement inside the handler
73 Name: "tranDelNewsItem",
74 Handler: HandleDelNewsItem,
77 Access: accessAlwaysAllow, // Granular access enforced inside the handler
78 Name: "tranDeleteFile",
79 Handler: HandleDeleteFile,
82 Access: accessDeleteUser,
83 DenyMsg: "You are not allowed to delete accounts.",
84 Name: "tranDeleteUser",
85 Handler: HandleDeleteUser,
88 Access: accessDisconUser,
89 DenyMsg: "You are not allowed to disconnect users.",
90 Name: "tranDisconnectUser",
91 Handler: HandleDisconnectUser,
94 Access: accessDownloadFile,
95 DenyMsg: "You are not allowed to download files.",
96 Name: "tranDownloadFile",
97 Handler: HandleDownloadFile,
100 Access: accessDownloadFile, // There is no specific access flag for folder vs file download
101 DenyMsg: "You are not allowed to download files.",
102 Name: "tranDownloadFldr",
103 Handler: HandleDownloadFolder,
105 tranGetClientInfoText: {
106 Access: accessGetClientInfo,
107 DenyMsg: "You are not allowed to get client info",
108 Name: "tranGetClientInfoText",
109 Handler: HandleGetClientConnInfoText,
112 Access: accessAlwaysAllow,
113 Name: "tranGetFileInfo",
114 Handler: HandleGetFileInfo,
116 tranGetFileNameList: {
117 Access: accessAlwaysAllow,
118 Name: "tranGetFileNameList",
119 Handler: HandleGetFileNameList,
122 Access: accessNewsReadArt,
123 DenyMsg: "You are not allowed to read news.",
125 Handler: HandleGetMsgs,
127 tranGetNewsArtData: {
128 Access: accessNewsReadArt,
129 DenyMsg: "You are not allowed to read news.",
130 Name: "tranGetNewsArtData",
131 Handler: HandleGetNewsArtData,
133 tranGetNewsArtNameList: {
134 Access: accessNewsReadArt,
135 DenyMsg: "You are not allowed to read news.",
136 Name: "tranGetNewsArtNameList",
137 Handler: HandleGetNewsArtNameList,
139 tranGetNewsCatNameList: {
140 Access: accessNewsReadArt,
141 DenyMsg: "You are not allowed to read news.",
142 Name: "tranGetNewsCatNameList",
143 Handler: HandleGetNewsCatNameList,
146 Access: accessOpenUser,
147 DenyMsg: "You are not allowed to view accounts.",
149 Handler: HandleGetUser,
151 tranGetUserNameList: {
152 Access: accessAlwaysAllow,
153 Name: "tranHandleGetUserNameList",
154 Handler: HandleGetUserNameList,
157 Access: accessOpenChat,
158 DenyMsg: "You are not allowed to request private chat.",
159 Name: "tranInviteNewChat",
160 Handler: HandleInviteNewChat,
163 Access: accessOpenChat,
164 DenyMsg: "You are not allowed to request private chat.",
165 Name: "tranInviteToChat",
166 Handler: HandleInviteToChat,
169 Access: accessAlwaysAllow,
170 Name: "tranJoinChat",
171 Handler: HandleJoinChat,
174 Access: accessAlwaysAllow,
175 Name: "tranKeepAlive",
176 Handler: HandleKeepAlive,
179 Access: accessAlwaysAllow,
180 Name: "tranJoinChat",
181 Handler: HandleLeaveChat,
185 Access: accessOpenUser,
186 DenyMsg: "You are not allowed to view accounts.",
187 Name: "tranListUsers",
188 Handler: HandleListUsers,
191 Access: accessMoveFile,
192 DenyMsg: "You are not allowed to move files.",
193 Name: "tranMoveFile",
194 Handler: HandleMoveFile,
197 Access: accessCreateFolder,
198 DenyMsg: "You are not allow to create folders.",
199 Name: "tranNewFolder",
200 Handler: HandleNewFolder,
203 Access: accessNewsCreateCat,
204 DenyMsg: "You are not allowed to create news categories.",
205 Name: "tranNewNewsCat",
206 Handler: HandleNewNewsCat,
209 Access: accessNewsCreateFldr,
210 DenyMsg: "You are not allowed to create news folders.",
211 Name: "tranNewNewsFldr",
212 Handler: HandleNewNewsFldr,
215 Access: accessCreateUser,
216 DenyMsg: "You are not allowed to create new accounts.",
218 Handler: HandleNewUser,
221 Access: accessNewsPostArt,
222 DenyMsg: "You are not allowed to post news.",
223 Name: "tranOldPostNews",
224 Handler: HandleTranOldPostNews,
227 Access: accessNewsPostArt,
228 DenyMsg: "You are not allowed to post news articles.",
229 Name: "tranPostNewsArt",
230 Handler: HandlePostNewsArt,
232 tranRejectChatInvite: {
233 Access: accessAlwaysAllow,
234 Name: "tranRejectChatInvite",
235 Handler: HandleRejectChatInvite,
237 tranSendInstantMsg: {
238 Access: accessAlwaysAllow,
239 //Access: accessSendPrivMsg,
240 //DenyMsg: "You are not allowed to send private messages",
241 Name: "tranSendInstantMsg",
242 Handler: HandleSendInstantMsg,
243 RequiredFields: []requiredField{
253 tranSetChatSubject: {
254 Access: accessAlwaysAllow,
255 Name: "tranSetChatSubject",
256 Handler: HandleSetChatSubject,
258 tranSetClientUserInfo: {
259 Access: accessAlwaysAllow,
260 Name: "tranSetClientUserInfo",
261 Handler: HandleSetClientUserInfo,
264 Access: accessAlwaysAllow, // granular access is in the handler
265 Name: "tranSetFileInfo",
266 Handler: HandleSetFileInfo,
269 Access: accessModifyUser,
270 DenyMsg: "You are not allowed to modify accounts.",
272 Handler: HandleSetUser,
275 Access: accessUploadFile,
276 DenyMsg: "You are not allowed to upload files.",
277 Name: "tranUploadFile",
278 Handler: HandleUploadFile,
281 Access: accessAlwaysAllow, // TODO: what should this be?
282 Name: "tranUploadFldr",
283 Handler: HandleUploadFolder,
286 Access: accessBroadcast,
287 DenyMsg: "You are not allowed to send broadcast messages.",
288 Name: "tranUserBroadcast",
289 Handler: HandleUserBroadcast,
293 func HandleChatSend(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
294 // Truncate long usernames
295 trunc := fmt.Sprintf("%13s", cc.UserName)
296 formattedMsg := fmt.Sprintf("\r%.14s: %s", trunc, t.GetField(fieldData).Data)
298 // By holding the option key, Hotline chat allows users to send /me formatted messages like:
299 // *** Halcyon does stuff
300 // This is indicated by the presence of the optional field fieldChatOptions in the transaction payload
301 if t.GetField(fieldChatOptions).Data != nil {
302 formattedMsg = fmt.Sprintf("\r*** %s %s", cc.UserName, t.GetField(fieldData).Data)
305 if bytes.Equal(t.GetField(fieldData).Data, []byte("/stats")) {
306 formattedMsg = strings.Replace(cc.Server.Stats.String(), "\n", "\r", -1)
309 chatID := t.GetField(fieldChatID).Data
310 // a non-nil chatID indicates the message belongs to a private chat
312 chatInt := binary.BigEndian.Uint32(chatID)
313 privChat := cc.Server.PrivateChats[chatInt]
315 // send the message to all connected clients of the private chat
316 for _, c := range privChat.ClientConn {
317 res = append(res, *NewTransaction(
320 NewField(fieldChatID, chatID),
321 NewField(fieldData, []byte(formattedMsg)),
327 for _, c := range sortedClients(cc.Server.Clients) {
328 // Filter out clients that do not have the read chat permission
329 if authorize(c.Account.Access, accessReadChat) {
330 res = append(res, *NewTransaction(tranChatMsg, c.ID, NewField(fieldData, []byte(formattedMsg))))
337 // HandleSendInstantMsg sends instant message to the user on the current server.
338 // Fields used in the request:
341 // One of the following values:
342 // - User message (myOpt_UserMessage = 1)
343 // - Refuse message (myOpt_RefuseMessage = 2)
344 // - Refuse chat (myOpt_RefuseChat = 3)
345 // - Automatic response (myOpt_AutomaticResponse = 4)"
347 // 214 Quoting message Optional
349 //Fields used in the reply:
351 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
352 msg := t.GetField(fieldData)
353 ID := t.GetField(fieldUserID)
354 // TODO: Implement reply quoting
355 //options := transaction.GetField(hotline.fieldOptions)
361 NewField(fieldData, msg.Data),
362 NewField(fieldUserName, cc.UserName),
363 NewField(fieldUserID, *cc.ID),
364 NewField(fieldOptions, []byte{0, 1}),
367 id, _ := byteToInt(ID.Data)
369 //keys := make([]uint16, 0, len(cc.Server.Clients))
370 //for k := range cc.Server.Clients {
371 // keys = append(keys, k)
374 otherClient := cc.Server.Clients[uint16(id)]
375 if otherClient == nil {
376 return res, errors.New("ohno")
379 // Respond with auto reply if other client has it enabled
380 if len(*otherClient.AutoReply) > 0 {
385 NewField(fieldData, *otherClient.AutoReply),
386 NewField(fieldUserName, otherClient.UserName),
387 NewField(fieldUserID, *otherClient.ID),
388 NewField(fieldOptions, []byte{0, 1}),
393 res = append(res, cc.NewReply(t))
398 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
399 fileName := string(t.GetField(fieldFileName).Data)
400 filePath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
402 ffo, err := NewFlattenedFileObject(filePath, fileName)
407 res = append(res, cc.NewReply(t,
408 NewField(fieldFileName, []byte(fileName)),
409 NewField(fieldFileTypeString, ffo.FlatFileInformationFork.TypeSignature),
410 NewField(fieldFileCreatorString, ffo.FlatFileInformationFork.CreatorSignature),
411 NewField(fieldFileComment, ffo.FlatFileInformationFork.Comment),
412 NewField(fieldFileType, ffo.FlatFileInformationFork.TypeSignature),
413 NewField(fieldFileCreateDate, ffo.FlatFileInformationFork.CreateDate),
414 NewField(fieldFileModifyDate, ffo.FlatFileInformationFork.ModifyDate),
415 NewField(fieldFileSize, ffo.FlatFileDataForkHeader.DataSize),
420 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
421 // TODO: Implement support for comments
422 // Fields used in the request:
424 // * 202 File path Optional
425 // * 211 File new name Optional
426 // * 210 File comment Optional
427 // Fields used in the reply: None
428 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
429 fileName := string(t.GetField(fieldFileName).Data)
430 filePath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
431 //fileComment := t.GetField(fieldFileComment).Data
432 fileNewName := t.GetField(fieldFileNewName).Data
434 if fileNewName != nil {
435 path := filePath + "/" + fileName
436 fi, err := os.Stat(path)
440 switch mode := fi.Mode(); {
442 if !authorize(cc.Account.Access, accessRenameFolder) {
443 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
446 case mode.IsRegular():
447 if !authorize(cc.Account.Access, accessRenameFile) {
448 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
453 err = os.Rename(filePath+"/"+fileName, filePath+"/"+string(fileNewName))
454 if os.IsNotExist(err) {
455 res = append(res, cc.NewErrReply(t, "Cannot rename file "+fileName+" because it does not exist or cannot be found."))
460 res = append(res, cc.NewReply(t))
464 // HandleDeleteFile deletes a file or folder
465 // Fields used in the request:
468 // Fields used in the reply: none
469 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
470 fileName := string(t.GetField(fieldFileName).Data)
471 filePath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
473 path := filePath + fileName
475 cc.Server.Logger.Debugw("Delete file", "src", path)
477 fi, err := os.Stat(path)
479 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
482 switch mode := fi.Mode(); {
484 if !authorize(cc.Account.Access, accessDeleteFolder) {
485 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
488 case mode.IsRegular():
489 if !authorize(cc.Account.Access, accessDeleteFile) {
490 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
495 if err := os.RemoveAll(path); err != nil {
499 res = append(res, cc.NewReply(t))
503 // HandleMoveFile moves files or folders. Note: seemingly not documented
504 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
505 fileName := string(t.GetField(fieldFileName).Data)
506 filePath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
507 fileNewPath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFileNewPath).Data)
509 cc.Server.Logger.Debugw("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
511 path := filePath + "/" + fileName
512 fi, err := os.Stat(path)
516 switch mode := fi.Mode(); {
518 if !authorize(cc.Account.Access, accessMoveFolder) {
519 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
522 case mode.IsRegular():
523 if !authorize(cc.Account.Access, accessMoveFile) {
524 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
529 err = os.Rename(filePath+"/"+fileName, fileNewPath+"/"+fileName)
530 if os.IsNotExist(err) {
531 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
535 return []Transaction{}, err
537 // TODO: handle other possible errors; e.g. file delete fails due to file permission issue
539 res = append(res, cc.NewReply(t))
543 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
544 newFolderPath := cc.Server.Config.FileRoot
546 // fieldFilePath is only present for nested paths
547 if t.GetField(fieldFilePath).Data != nil {
549 newFp.UnmarshalBinary(t.GetField(fieldFilePath).Data)
550 newFolderPath += newFp.String()
552 newFolderPath += "/" + string(t.GetField(fieldFileName).Data)
554 if err := os.Mkdir(newFolderPath, 0777); err != nil {
555 // TODO: Send error response to client
556 return []Transaction{}, err
559 res = append(res, cc.NewReply(t))
563 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
564 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
565 userName := string(t.GetField(fieldUserName).Data)
567 newAccessLvl := t.GetField(fieldUserAccess).Data
569 account := cc.Server.Accounts[login]
570 account.Access = &newAccessLvl
571 account.Name = userName
573 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
574 // not include fieldUserPassword
575 if t.GetField(fieldUserPassword).Data == nil {
576 account.Password = hashAndSalt([]byte(""))
578 if len(t.GetField(fieldUserPassword).Data) > 1 {
579 account.Password = hashAndSalt(t.GetField(fieldUserPassword).Data)
582 file := cc.Server.ConfigDir + "Users/" + login + ".yaml"
583 out, err := yaml.Marshal(&account)
587 if err := ioutil.WriteFile(file, out, 0666); err != nil {
591 // Notify connected clients logged in as the user of the new access level
592 for _, c := range cc.Server.Clients {
593 if c.Account.Login == login {
594 // Note: comment out these two lines to test server-side deny messages
595 newT := NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, newAccessLvl))
596 res = append(res, *newT)
598 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
599 if authorize(c.Account.Access, accessDisconUser) {
600 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 1)
602 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 0)
604 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
606 c.Account.Access = account.Access
609 tranNotifyChangeUser,
610 NewField(fieldUserID, *c.ID),
611 NewField(fieldUserFlags, *c.Flags),
612 NewField(fieldUserName, c.UserName),
613 NewField(fieldUserIconID, *c.Icon),
618 // TODO: If we have just promoted a connected user to admin, notify
619 // connected clients to turn the user red
621 res = append(res, cc.NewReply(t))
625 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
626 userLogin := string(t.GetField(fieldUserLogin).Data)
627 account := cc.Server.Accounts[userLogin]
629 errorT := cc.NewErrReply(t, "Account does not exist.")
630 res = append(res, errorT)
634 res = append(res, cc.NewReply(t,
635 NewField(fieldUserName, []byte(account.Name)),
636 NewField(fieldUserLogin, negateString(t.GetField(fieldUserLogin).Data)),
637 NewField(fieldUserPassword, []byte(account.Password)),
638 NewField(fieldUserAccess, *account.Access),
643 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
644 var userFields []Field
645 // TODO: make order deterministic
646 for _, acc := range cc.Server.Accounts {
647 userField := acc.MarshalBinary()
648 userFields = append(userFields, NewField(fieldData, userField))
651 res = append(res, cc.NewReply(t, userFields...))
655 // HandleNewUser creates a new user account
656 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
657 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
659 // If the account already exists, reply with an error
660 // TODO: make order deterministic
661 if _, ok := cc.Server.Accounts[login]; ok {
662 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
666 if err := cc.Server.NewUser(
668 string(t.GetField(fieldUserName).Data),
669 string(t.GetField(fieldUserPassword).Data),
670 t.GetField(fieldUserAccess).Data,
672 return []Transaction{}, err
675 res = append(res, cc.NewReply(t))
679 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
680 // TODO: Handle case where account doesn't exist; e.g. delete race condition
681 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
683 if err := cc.Server.DeleteUser(login); err != nil {
687 res = append(res, cc.NewReply(t))
691 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
692 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
695 NewField(fieldData, t.GetField(tranGetMsgs).Data),
696 NewField(fieldChatOptions, []byte{0}),
699 res = append(res, cc.NewReply(t))
703 func byteToInt(bytes []byte) (int, error) {
706 return int(binary.BigEndian.Uint16(bytes)), nil
708 return int(binary.BigEndian.Uint32(bytes)), nil
711 return 0, errors.New("unknown byte length")
714 func HandleGetClientConnInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
715 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
717 clientConn := cc.Server.Clients[uint16(clientID)]
718 if clientConn == nil {
719 return res, errors.New("invalid client")
722 // TODO: Implement non-hardcoded values
723 template := `Nickname: %s
728 -------- File Downloads ---------
732 ------- Folder Downloads --------
736 --------- File Uploads ----------
740 -------- Folder Uploads ---------
744 ------- Waiting Downloads -------
750 activeDownloads := clientConn.Transfers[FileDownload]
751 activeDownloadList := "None."
752 for _, dl := range activeDownloads {
753 activeDownloadList += dl.String() + "\n"
756 template = fmt.Sprintf(
759 clientConn.Account.Name,
760 clientConn.Account.Login,
761 clientConn.Connection.RemoteAddr().String(),
764 template = strings.Replace(template, "\n", "\r", -1)
766 res = append(res, cc.NewReply(t,
767 NewField(fieldData, []byte(template)),
768 NewField(fieldUserName, clientConn.UserName),
773 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
774 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
779 func (cc *ClientConn) notifyNewUserHasJoined() (res []Transaction, err error) {
780 // Notify other ccs that a new user has connected
783 tranNotifyChangeUser, nil,
784 NewField(fieldUserName, cc.UserName),
785 NewField(fieldUserID, *cc.ID),
786 NewField(fieldUserIconID, *cc.Icon),
787 NewField(fieldUserFlags, *cc.Flags),
794 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
795 bs := make([]byte, 2)
796 binary.BigEndian.PutUint16(bs, *cc.Server.NextGuestID)
798 cc.UserName = t.GetField(fieldUserName).Data
800 *cc.Icon = t.GetField(fieldUserIconID).Data
802 options := t.GetField(fieldOptions).Data
803 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
805 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
807 // Check refuse private PM option
808 if optBitmap.Bit(refusePM) == 1 {
809 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
810 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
813 // Check refuse private chat option
814 if optBitmap.Bit(refuseChat) == 1 {
815 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
816 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
819 // Check auto response
820 if optBitmap.Bit(autoResponse) == 1 {
821 *cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
823 *cc.AutoReply = []byte{}
826 _, _ = cc.notifyNewUserHasJoined()
828 res = append(res, cc.NewReply(t))
833 const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
834 // "Mon, 02 Jan 2006 15:04:05 MST"
836 const defaultNewsTemplate = `From %s (%s):
840 __________________________________________________________`
842 // HandleTranOldPostNews updates the flat news
843 // Fields used in this request:
845 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
846 cc.Server.flatNewsMux.Lock()
847 defer cc.Server.flatNewsMux.Unlock()
849 newsDateTemplate := defaultNewsDateFormat
850 if cc.Server.Config.NewsDateFormat != "" {
851 newsDateTemplate = cc.Server.Config.NewsDateFormat
854 newsTemplate := defaultNewsTemplate
855 if cc.Server.Config.NewsDelimiter != "" {
856 newsTemplate = cc.Server.Config.NewsDelimiter
859 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
860 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
862 // update news in memory
863 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
865 // update news on disk
866 if err := ioutil.WriteFile(cc.Server.ConfigDir+"MessageBoard.txt", cc.Server.FlatNews, 0644); err != nil {
870 // Notify all clients of updated news
873 NewField(fieldData, []byte(newsPost)),
876 res = append(res, cc.NewReply(t))
880 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
881 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
883 if authorize(clientConn.Account.Access, accessCannotBeDiscon) {
884 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
888 if err := clientConn.Connection.Close(); err != nil {
892 res = append(res, cc.NewReply(t))
896 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
897 // Fields used in the request:
898 // 325 News path (Optional)
900 newsPath := t.GetField(fieldNewsPath).Data
901 cc.Server.Logger.Infow("NewsPath: ", "np", string(newsPath))
903 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
904 cats := cc.Server.GetNewsCatByPath(pathStrs)
906 // To store the keys in slice in sorted order
907 keys := make([]string, len(cats))
909 for k := range cats {
915 var fieldData []Field
916 for _, k := range keys {
918 b, _ := cat.MarshalBinary()
919 fieldData = append(fieldData, NewField(
920 fieldNewsCatListData15,
925 res = append(res, cc.NewReply(t, fieldData...))
929 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
930 name := string(t.GetField(fieldNewsCatName).Data)
931 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
933 cats := cc.Server.GetNewsCatByPath(pathStrs)
934 cats[name] = NewsCategoryListData15{
937 Articles: map[uint32]*NewsArtData{},
938 SubCats: make(map[string]NewsCategoryListData15),
941 if err := cc.Server.writeThreadedNews(); err != nil {
944 res = append(res, cc.NewReply(t))
948 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
949 // Fields used in the request:
950 // 322 News category name
952 name := string(t.GetField(fieldFileName).Data)
953 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
955 cc.Server.Logger.Infof("Creating new news folder %s", name)
957 cats := cc.Server.GetNewsCatByPath(pathStrs)
958 cats[name] = NewsCategoryListData15{
961 Articles: map[uint32]*NewsArtData{},
962 SubCats: make(map[string]NewsCategoryListData15),
964 if err := cc.Server.writeThreadedNews(); err != nil {
967 res = append(res, cc.NewReply(t))
971 // Fields used in the request:
972 // 325 News path Optional
975 // 321 News article list data Optional
976 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
977 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
979 var cat NewsCategoryListData15
980 cats := cc.Server.ThreadedNews.Categories
982 for _, path := range pathStrs {
984 cats = cats[path].SubCats
987 nald := cat.GetNewsArtListData()
989 res = append(res, cc.NewReply(t, NewField(fieldNewsArtListData, nald.Payload())))
993 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
996 // 326 News article ID
997 // 327 News article data flavor
999 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1001 var cat NewsCategoryListData15
1002 cats := cc.Server.ThreadedNews.Categories
1004 for _, path := range pathStrs {
1006 cats = cats[path].SubCats
1008 newsArtID := t.GetField(fieldNewsArtID).Data
1010 convertedArtID := binary.BigEndian.Uint16(newsArtID)
1012 art := cat.Articles[uint32(convertedArtID)]
1014 res = append(res, cc.NewReply(t))
1019 // 328 News article title
1020 // 329 News article poster
1021 // 330 News article date
1022 // 331 Previous article ID
1023 // 332 Next article ID
1024 // 335 Parent article ID
1025 // 336 First child article ID
1026 // 327 News article data flavor "Should be “text/plain”
1027 // 333 News article data Optional (if data flavor is “text/plain”)
1029 res = append(res, cc.NewReply(t,
1030 NewField(fieldNewsArtTitle, []byte(art.Title)),
1031 NewField(fieldNewsArtPoster, []byte(art.Poster)),
1032 NewField(fieldNewsArtDate, art.Date),
1033 NewField(fieldNewsArtPrevArt, art.PrevArt),
1034 NewField(fieldNewsArtNextArt, art.NextArt),
1035 NewField(fieldNewsArtParentArt, art.ParentArt),
1036 NewField(fieldNewsArt1stChildArt, art.FirstChildArt),
1037 NewField(fieldNewsArtDataFlav, []byte("text/plain")),
1038 NewField(fieldNewsArtData, []byte(art.Data)),
1043 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1044 // Access: News Delete Folder (37) or News Delete Category (35)
1046 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1048 // TODO: determine if path is a Folder (Bundle) or Category and check for permission
1050 cc.Server.Logger.Infof("DelNewsItem %v", pathStrs)
1052 cats := cc.Server.ThreadedNews.Categories
1054 delName := pathStrs[len(pathStrs)-1]
1055 if len(pathStrs) > 1 {
1056 for _, path := range pathStrs[0 : len(pathStrs)-1] {
1057 cats = cats[path].SubCats
1061 delete(cats, delName)
1063 err = cc.Server.writeThreadedNews()
1068 // Reply params: none
1069 res = append(res, cc.NewReply(t))
1074 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1077 // 326 News article ID
1078 // 337 News article – recursive delete Delete child articles (1) or not (0)
1079 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1080 ID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1082 // TODO: Delete recursive
1083 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1085 catName := pathStrs[len(pathStrs)-1]
1086 cat := cats[catName]
1088 delete(cat.Articles, uint32(ID))
1091 if err := cc.Server.writeThreadedNews(); err != nil {
1095 res = append(res, cc.NewReply(t))
1099 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1102 // 326 News article ID ID of the parent article?
1103 // 328 News article title
1104 // 334 News article flags
1105 // 327 News article data flavor Currently “text/plain”
1106 // 333 News article data
1108 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1109 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1111 catName := pathStrs[len(pathStrs)-1]
1112 cat := cats[catName]
1114 newArt := NewsArtData{
1115 Title: string(t.GetField(fieldNewsArtTitle).Data),
1116 Poster: string(cc.UserName),
1118 PrevArt: []byte{0, 0, 0, 0},
1119 NextArt: []byte{0, 0, 0, 0},
1120 ParentArt: append([]byte{0, 0}, t.GetField(fieldNewsArtID).Data...),
1121 FirstChildArt: []byte{0, 0, 0, 0},
1122 DataFlav: []byte("text/plain"),
1123 Data: string(t.GetField(fieldNewsArtData).Data),
1127 for k := range cat.Articles {
1128 keys = append(keys, int(k))
1134 prevID := uint32(keys[len(keys)-1])
1137 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1139 // Set next article ID
1140 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1143 // Update parent article with first child reply
1144 parentID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1146 parentArt := cat.Articles[uint32(parentID)]
1148 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1149 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1153 cat.Articles[nextID] = &newArt
1156 if err := cc.Server.writeThreadedNews(); err != nil {
1160 res = append(res, cc.NewReply(t))
1164 // HandleGetMsgs returns the flat news data
1165 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1166 res = append(res, cc.NewReply(t, NewField(fieldData, cc.Server.FlatNews)))
1171 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1172 fileName := t.GetField(fieldFileName).Data
1173 filePath := ReadFilePath(t.GetField(fieldFilePath).Data)
1175 ffo, err := NewFlattenedFileObject(cc.Server.Config.FileRoot+filePath, string(fileName))
1180 transactionRef := cc.Server.NewTransactionRef()
1181 data := binary.BigEndian.Uint32(transactionRef)
1183 cc.Server.Logger.Infow("File download", "path", filePath)
1185 ft := &FileTransfer{
1187 FilePath: []byte(filePath),
1188 ReferenceNumber: transactionRef,
1192 cc.Server.FileTransfers[data] = ft
1193 cc.Transfers[FileDownload] = append(cc.Transfers[FileDownload], ft)
1195 res = append(res, cc.NewReply(t,
1196 NewField(fieldRefNum, transactionRef),
1197 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1198 NewField(fieldTransferSize, ffo.TransferSize()),
1199 NewField(fieldFileSize, ffo.FlatFileDataForkHeader.DataSize),
1205 // Download all files from the specified folder and sub-folders
1218 // 00 6c // transfer size
1222 // 00 dc // field Folder item count
1226 // 00 6b // ref number
1229 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1230 transactionRef := cc.Server.NewTransactionRef()
1231 data := binary.BigEndian.Uint32(transactionRef)
1233 fileTransfer := &FileTransfer{
1234 FileName: t.GetField(fieldFileName).Data,
1235 FilePath: t.GetField(fieldFilePath).Data,
1236 ReferenceNumber: transactionRef,
1237 Type: FolderDownload,
1239 cc.Server.FileTransfers[data] = fileTransfer
1240 cc.Transfers[FolderDownload] = append(cc.Transfers[FolderDownload], fileTransfer)
1243 err = fp.UnmarshalBinary(t.GetField(fieldFilePath).Data)
1248 fullFilePath := fmt.Sprintf("%v%v", cc.Server.Config.FileRoot+fp.String(), string(fileTransfer.FileName))
1249 transferSize, err := CalcTotalSize(fullFilePath)
1253 itemCount, err := CalcItemCount(fullFilePath)
1257 res = append(res, cc.NewReply(t,
1258 NewField(fieldRefNum, transactionRef),
1259 NewField(fieldTransferSize, transferSize),
1260 NewField(fieldFolderItemCount, itemCount),
1261 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1266 // Upload all files from the local folder and its subfolders to the specified path on the server
1267 // Fields used in the request
1270 // 108 transfer size Total size of all items in the folder
1271 // 220 Folder item count
1272 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1273 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1274 transactionRef := cc.Server.NewTransactionRef()
1275 data := binary.BigEndian.Uint32(transactionRef)
1277 fileTransfer := &FileTransfer{
1278 FileName: t.GetField(fieldFileName).Data,
1279 FilePath: t.GetField(fieldFilePath).Data,
1280 ReferenceNumber: transactionRef,
1282 FolderItemCount: t.GetField(fieldFolderItemCount).Data,
1283 TransferSize: t.GetField(fieldTransferSize).Data,
1285 cc.Server.FileTransfers[data] = fileTransfer
1287 res = append(res, cc.NewReply(t, NewField(fieldRefNum, transactionRef)))
1291 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1292 fileName := t.GetField(fieldFileName).Data
1293 filePath := t.GetField(fieldFilePath).Data
1295 transactionRef := cc.Server.NewTransactionRef()
1296 data := binary.BigEndian.Uint32(transactionRef)
1298 fileTransfer := &FileTransfer{
1301 ReferenceNumber: transactionRef,
1305 cc.Server.FileTransfers[data] = fileTransfer
1307 res = append(res, cc.NewReply(t, NewField(fieldRefNum, transactionRef)))
1318 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1320 if len(t.GetField(fieldUserIconID).Data) == 4 {
1321 icon = t.GetField(fieldUserIconID).Data[2:]
1323 icon = t.GetField(fieldUserIconID).Data
1326 cc.UserName = t.GetField(fieldUserName).Data
1328 // the options field is only passed by the client versions > 1.2.3.
1329 options := t.GetField(fieldOptions).Data
1332 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1333 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
1335 // Check refuse private PM option
1336 if optBitmap.Bit(refusePM) == 1 {
1337 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
1338 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
1341 // Check refuse private chat option
1342 if optBitmap.Bit(refuseChat) == 1 {
1343 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
1344 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
1347 // Check auto response
1348 if optBitmap.Bit(autoResponse) == 1 {
1349 *cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
1351 *cc.AutoReply = []byte{}
1355 // Notify all clients of updated user info
1357 tranNotifyChangeUser,
1358 NewField(fieldUserID, *cc.ID),
1359 NewField(fieldUserIconID, *cc.Icon),
1360 NewField(fieldUserFlags, *cc.Flags),
1361 NewField(fieldUserName, cc.UserName),
1367 // HandleKeepAlive response to keepalive transactions with an empty reply
1368 // HL 1.9.2 Client sends keepalive msg every 3 minutes
1369 // HL 1.2.3 Client doesn't send keepalives
1370 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1371 res = append(res, cc.NewReply(t))
1376 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1377 filePath := cc.Server.Config.FileRoot
1379 path := t.GetField(fieldFilePath).Data
1381 filePath = cc.Server.Config.FileRoot + ReadFilePath(path)
1384 fileNames, err := getFileNameList(filePath)
1389 res = append(res, cc.NewReply(t, fileNames...))
1394 // =================================
1395 // Hotline private chat flow
1396 // =================================
1397 // 1. ClientA sends tranInviteNewChat to server with user ID to invite
1398 // 2. Server creates new ChatID
1399 // 3. Server sends tranInviteToChat to invitee
1400 // 4. Server replies to ClientA with new Chat ID
1402 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1403 // If Accepted is clicked:
1404 // 1. ClientB sends tranJoinChat with fieldChatID
1406 // HandleInviteNewChat invites users to new private chat
1407 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1409 targetID := t.GetField(fieldUserID).Data
1410 newChatID := cc.Server.NewPrivateChat(cc)
1416 NewField(fieldChatID, newChatID),
1417 NewField(fieldUserName, cc.UserName),
1418 NewField(fieldUserID, *cc.ID),
1424 NewField(fieldChatID, newChatID),
1425 NewField(fieldUserName, cc.UserName),
1426 NewField(fieldUserID, *cc.ID),
1427 NewField(fieldUserIconID, *cc.Icon),
1428 NewField(fieldUserFlags, *cc.Flags),
1435 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1437 targetID := t.GetField(fieldUserID).Data
1438 chatID := t.GetField(fieldChatID).Data
1444 NewField(fieldChatID, chatID),
1445 NewField(fieldUserName, cc.UserName),
1446 NewField(fieldUserID, *cc.ID),
1452 NewField(fieldChatID, chatID),
1453 NewField(fieldUserName, cc.UserName),
1454 NewField(fieldUserID, *cc.ID),
1455 NewField(fieldUserIconID, *cc.Icon),
1456 NewField(fieldUserFlags, *cc.Flags),
1463 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1464 chatID := t.GetField(fieldChatID).Data
1465 chatInt := binary.BigEndian.Uint32(chatID)
1467 privChat := cc.Server.PrivateChats[chatInt]
1469 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1471 for _, c := range sortedClients(privChat.ClientConn) {
1476 NewField(fieldChatID, chatID),
1477 NewField(fieldData, resMsg),
1485 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1486 // Fields used in the reply:
1487 // * 115 Chat subject
1488 // * 300 User name with info (Optional)
1489 // * 300 (more user names with info)
1490 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1491 chatID := t.GetField(fieldChatID).Data
1492 chatInt := binary.BigEndian.Uint32(chatID)
1494 privChat := cc.Server.PrivateChats[chatInt]
1496 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1497 for _, c := range sortedClients(privChat.ClientConn) {
1500 tranNotifyChatChangeUser,
1502 NewField(fieldChatID, chatID),
1503 NewField(fieldUserName, cc.UserName),
1504 NewField(fieldUserID, *cc.ID),
1505 NewField(fieldUserIconID, *cc.Icon),
1506 NewField(fieldUserFlags, *cc.Flags),
1511 privChat.ClientConn[cc.uint16ID()] = cc
1513 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1514 for _, c := range sortedClients(privChat.ClientConn) {
1519 Name: string(c.UserName),
1522 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1525 res = append(res, cc.NewReply(t, replyFields...))
1529 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1530 // Fields used in the request:
1531 // * 114 fieldChatID
1532 // Reply is not expected.
1533 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1534 chatID := t.GetField(fieldChatID).Data
1535 chatInt := binary.BigEndian.Uint32(chatID)
1537 privChat := cc.Server.PrivateChats[chatInt]
1539 delete(privChat.ClientConn, cc.uint16ID())
1541 // Notify members of the private chat that the user has left
1542 for _, c := range sortedClients(privChat.ClientConn) {
1545 tranNotifyChatDeleteUser,
1547 NewField(fieldChatID, chatID),
1548 NewField(fieldUserID, *cc.ID),
1556 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1557 // Fields used in the request:
1559 // * 115 Chat subject Chat subject string
1560 // Reply is not expected.
1561 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1562 chatID := t.GetField(fieldChatID).Data
1563 chatInt := binary.BigEndian.Uint32(chatID)
1565 privChat := cc.Server.PrivateChats[chatInt]
1566 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1568 for _, c := range sortedClients(privChat.ClientConn) {
1571 tranNotifyChatSubject,
1573 NewField(fieldChatID, chatID),
1574 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),