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",
49 Handler: HandleTranAgreed,
52 Handler: HandleChatSend,
54 RequiredFields: []requiredField{
62 Access: accessNewsDeleteArt,
63 DenyMsg: "You are not allowed to delete news articles.",
64 Name: "tranDelNewsArt",
65 Handler: HandleDelNewsArt,
68 // Has multiple access flags: News Delete Folder (37) or News Delete Category (35)
69 // TODO: Implement inside the handler
70 Name: "tranDelNewsItem",
71 Handler: HandleDelNewsItem,
74 Name: "tranDeleteFile",
75 Handler: HandleDeleteFile,
78 Name: "tranDeleteUser",
79 Handler: HandleDeleteUser,
82 Access: accessDisconUser,
83 DenyMsg: "You are not allowed to disconnect users.",
84 Name: "tranDisconnectUser",
85 Handler: HandleDisconnectUser,
88 Access: accessDownloadFile,
89 DenyMsg: "You are not allowed to download files.",
90 Name: "tranDownloadFile",
91 Handler: HandleDownloadFile,
94 Access: accessDownloadFile, // There is no specific access flag for folder vs file download
95 DenyMsg: "You are not allowed to download files.",
96 Name: "tranDownloadFldr",
97 Handler: HandleDownloadFolder,
99 tranGetClientInfoText: {
100 Access: accessGetClientInfo,
101 DenyMsg: "You are not allowed to get client info",
102 Name: "tranGetClientInfoText",
103 Handler: HandleGetClientConnInfoText,
106 Name: "tranGetFileInfo",
107 Handler: HandleGetFileInfo,
109 tranGetFileNameList: {
110 Name: "tranGetFileNameList",
111 Handler: HandleGetFileNameList,
114 Access: accessNewsReadArt,
115 DenyMsg: "You are not allowed to read news.",
117 Handler: HandleGetMsgs,
119 tranGetNewsArtData: {
120 Access: accessNewsReadArt,
121 DenyMsg: "You are not allowed to read news.",
122 Name: "tranGetNewsArtData",
123 Handler: HandleGetNewsArtData,
125 tranGetNewsArtNameList: {
126 Access: accessNewsReadArt,
127 DenyMsg: "You are not allowed to read news.",
128 Name: "tranGetNewsArtNameList",
129 Handler: HandleGetNewsArtNameList,
131 tranGetNewsCatNameList: {
132 Access: accessNewsReadArt,
133 DenyMsg: "You are not allowed to read news.",
134 Name: "tranGetNewsCatNameList",
135 Handler: HandleGetNewsCatNameList,
138 DenyMsg: "You are not allowed to view accounts.",
140 Handler: HandleGetUser,
142 tranGetUserNameList: {
143 Name: "tranHandleGetUserNameList",
144 Handler: HandleGetUserNameList,
147 Access: accessOpenChat,
148 DenyMsg: "You are not allowed to request private chat.",
149 Name: "tranInviteNewChat",
150 Handler: HandleInviteNewChat,
153 Access: accessOpenChat,
154 DenyMsg: "You are not allowed to request private chat.",
155 Name: "tranInviteToChat",
156 Handler: HandleInviteToChat,
159 Name: "tranJoinChat",
160 Handler: HandleJoinChat,
163 Name: "tranKeepAlive",
164 Handler: HandleKeepAlive,
167 Name: "tranJoinChat",
168 Handler: HandleLeaveChat,
172 Access: accessOpenUser,
173 DenyMsg: "You are not allowed to view accounts.",
174 Name: "tranListUsers",
175 Handler: HandleListUsers,
178 Access: accessMoveFile,
179 DenyMsg: "You are not allowed to move files.",
180 Name: "tranMoveFile",
181 Handler: HandleMoveFile,
184 Access: accessCreateFolder,
185 DenyMsg: "You are not allow to create folders.",
186 Name: "tranNewFolder",
187 Handler: HandleNewFolder,
190 Access: accessNewsCreateCat,
191 DenyMsg: "You are not allowed to create news categories.",
192 Name: "tranNewNewsCat",
193 Handler: HandleNewNewsCat,
196 Access: accessNewsCreateFldr,
197 DenyMsg: "You are not allowed to create news folders.",
198 Name: "tranNewNewsFldr",
199 Handler: HandleNewNewsFldr,
202 Access: accessCreateUser,
203 DenyMsg: "You are not allowed to create new accounts.",
205 Handler: HandleNewUser,
208 Access: accessNewsPostArt,
209 DenyMsg: "You are not allowed to post news.",
210 Name: "tranOldPostNews",
211 Handler: HandleTranOldPostNews,
214 Access: accessNewsPostArt,
215 DenyMsg: "You are not allowed to post news articles.",
216 Name: "tranPostNewsArt",
217 Handler: HandlePostNewsArt,
219 tranRejectChatInvite: {
220 Name: "tranRejectChatInvite",
221 Handler: HandleRejectChatInvite,
223 tranSendInstantMsg: {
224 Access: accessAlwaysAllow,
225 // Access: accessSendPrivMsg,
226 // DenyMsg: "You are not allowed to send private messages",
227 Name: "tranSendInstantMsg",
228 Handler: HandleSendInstantMsg,
229 RequiredFields: []requiredField{
239 tranSetChatSubject: {
240 Name: "tranSetChatSubject",
241 Handler: HandleSetChatSubject,
244 Name: "tranMakeFileAlias",
245 Handler: HandleMakeAlias,
246 RequiredFields: []requiredField{
247 {ID: fieldFileName, minLen: 1},
248 {ID: fieldFilePath, minLen: 1},
249 {ID: fieldFileNewPath, minLen: 1},
252 tranSetClientUserInfo: {
253 Name: "tranSetClientUserInfo",
254 Handler: HandleSetClientUserInfo,
257 Name: "tranSetFileInfo",
258 Handler: HandleSetFileInfo,
261 Access: accessModifyUser,
262 DenyMsg: "You are not allowed to modify accounts.",
264 Handler: HandleSetUser,
267 Name: "tranUploadFile",
268 Handler: HandleUploadFile,
271 Name: "tranUploadFldr",
272 Handler: HandleUploadFolder,
275 Access: accessBroadcast,
276 DenyMsg: "You are not allowed to send broadcast messages.",
277 Name: "tranUserBroadcast",
278 Handler: HandleUserBroadcast,
282 func HandleChatSend(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
283 if !authorize(cc.Account.Access, accessSendChat) {
284 res = append(res, cc.NewErrReply(t, "You are not allowed to participate in chat."))
288 // Truncate long usernames
289 trunc := fmt.Sprintf("%13s", cc.UserName)
290 formattedMsg := fmt.Sprintf("\r%.14s: %s", trunc, t.GetField(fieldData).Data)
292 // By holding the option key, Hotline chat allows users to send /me formatted messages like:
293 // *** Halcyon does stuff
294 // This is indicated by the presence of the optional field fieldChatOptions in the transaction payload
295 if t.GetField(fieldChatOptions).Data != nil {
296 formattedMsg = fmt.Sprintf("\r*** %s %s", cc.UserName, t.GetField(fieldData).Data)
299 if bytes.Equal(t.GetField(fieldData).Data, []byte("/stats")) {
300 formattedMsg = strings.Replace(cc.Server.Stats.String(), "\n", "\r", -1)
303 chatID := t.GetField(fieldChatID).Data
304 // a non-nil chatID indicates the message belongs to a private chat
306 chatInt := binary.BigEndian.Uint32(chatID)
307 privChat := cc.Server.PrivateChats[chatInt]
309 // send the message to all connected clients of the private chat
310 for _, c := range privChat.ClientConn {
311 res = append(res, *NewTransaction(
314 NewField(fieldChatID, chatID),
315 NewField(fieldData, []byte(formattedMsg)),
321 for _, c := range sortedClients(cc.Server.Clients) {
322 // Filter out clients that do not have the read chat permission
323 if authorize(c.Account.Access, accessReadChat) {
324 res = append(res, *NewTransaction(tranChatMsg, c.ID, NewField(fieldData, []byte(formattedMsg))))
331 // HandleSendInstantMsg sends instant message to the user on the current server.
332 // Fields used in the request:
335 // One of the following values:
336 // - User message (myOpt_UserMessage = 1)
337 // - Refuse message (myOpt_RefuseMessage = 2)
338 // - Refuse chat (myOpt_RefuseChat = 3)
339 // - Automatic response (myOpt_AutomaticResponse = 4)"
341 // 214 Quoting message Optional
343 // Fields used in the reply:
345 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
346 msg := t.GetField(fieldData)
347 ID := t.GetField(fieldUserID)
348 // TODO: Implement reply quoting
349 // options := transaction.GetField(hotline.fieldOptions)
355 NewField(fieldData, msg.Data),
356 NewField(fieldUserName, cc.UserName),
357 NewField(fieldUserID, *cc.ID),
358 NewField(fieldOptions, []byte{0, 1}),
361 id, _ := byteToInt(ID.Data)
363 otherClient := cc.Server.Clients[uint16(id)]
364 if otherClient == nil {
365 return res, errors.New("ohno")
368 // Respond with auto reply if other client has it enabled
369 if len(otherClient.AutoReply) > 0 {
374 NewField(fieldData, otherClient.AutoReply),
375 NewField(fieldUserName, otherClient.UserName),
376 NewField(fieldUserID, *otherClient.ID),
377 NewField(fieldOptions, []byte{0, 1}),
382 res = append(res, cc.NewReply(t))
387 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
388 fileName := t.GetField(fieldFileName).Data
389 filePath := t.GetField(fieldFilePath).Data
391 ffo, err := NewFlattenedFileObject(cc.Server.Config.FileRoot, filePath, fileName)
396 res = append(res, cc.NewReply(t,
397 NewField(fieldFileName, fileName),
398 NewField(fieldFileTypeString, ffo.FlatFileInformationFork.TypeSignature),
399 NewField(fieldFileCreatorString, ffo.FlatFileInformationFork.CreatorSignature),
400 NewField(fieldFileComment, ffo.FlatFileInformationFork.Comment),
401 NewField(fieldFileType, ffo.FlatFileInformationFork.TypeSignature),
402 NewField(fieldFileCreateDate, ffo.FlatFileInformationFork.CreateDate),
403 NewField(fieldFileModifyDate, ffo.FlatFileInformationFork.ModifyDate),
404 NewField(fieldFileSize, ffo.FlatFileDataForkHeader.DataSize),
409 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
410 // TODO: Implement support for comments
411 // Fields used in the request:
413 // * 202 File path Optional
414 // * 211 File new name Optional
415 // * 210 File comment Optional
416 // Fields used in the reply: None
417 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
418 fileName := t.GetField(fieldFileName).Data
419 filePath := t.GetField(fieldFilePath).Data
421 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
426 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, t.GetField(fieldFileNewName).Data)
431 // fileComment := t.GetField(fieldFileComment).Data
432 fileNewName := t.GetField(fieldFileNewName).Data
434 if fileNewName != nil {
435 fi, err := FS.Stat(fullFilePath)
439 switch mode := fi.Mode(); {
441 if !authorize(cc.Account.Access, accessRenameFolder) {
442 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
445 case mode.IsRegular():
446 if !authorize(cc.Account.Access, accessRenameFile) {
447 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
452 err = os.Rename(fullFilePath, fullNewFilePath)
453 if os.IsNotExist(err) {
454 res = append(res, cc.NewErrReply(t, "Cannot rename file "+string(fileName)+" because it does not exist or cannot be found."))
459 res = append(res, cc.NewReply(t))
463 // HandleDeleteFile deletes a file or folder
464 // Fields used in the request:
467 // Fields used in the reply: none
468 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
469 fileName := t.GetField(fieldFileName).Data
470 filePath := t.GetField(fieldFilePath).Data
472 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
477 cc.Server.Logger.Debugw("Delete file", "src", fullFilePath)
479 fi, err := os.Stat(fullFilePath)
481 res = append(res, cc.NewErrReply(t, "Cannot delete file "+string(fileName)+" because it does not exist or cannot be found."))
484 switch mode := fi.Mode(); {
486 if !authorize(cc.Account.Access, accessDeleteFolder) {
487 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
490 case mode.IsRegular():
491 if !authorize(cc.Account.Access, accessDeleteFile) {
492 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
497 if err := os.RemoveAll(fullFilePath); err != nil {
501 res = append(res, cc.NewReply(t))
505 // HandleMoveFile moves files or folders. Note: seemingly not documented
506 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
507 fileName := string(t.GetField(fieldFileName).Data)
508 filePath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
509 fileNewPath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFileNewPath).Data)
511 cc.Server.Logger.Debugw("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
513 fp := filePath + "/" + fileName
514 fi, err := os.Stat(fp)
518 switch mode := fi.Mode(); {
520 if !authorize(cc.Account.Access, accessMoveFolder) {
521 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
524 case mode.IsRegular():
525 if !authorize(cc.Account.Access, accessMoveFile) {
526 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
531 err = os.Rename(filePath+"/"+fileName, fileNewPath+"/"+fileName)
532 if os.IsNotExist(err) {
533 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
537 return []Transaction{}, err
539 // TODO: handle other possible errors; e.g. file delete fails due to file permission issue
541 res = append(res, cc.NewReply(t))
545 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
546 newFolderPath := cc.Server.Config.FileRoot
547 folderName := string(t.GetField(fieldFileName).Data)
549 folderName = path.Join("/", folderName)
551 // fieldFilePath is only present for nested paths
552 if t.GetField(fieldFilePath).Data != nil {
554 err := newFp.UnmarshalBinary(t.GetField(fieldFilePath).Data)
558 newFolderPath += newFp.String()
560 newFolderPath = path.Join(newFolderPath, folderName)
562 // TODO: check path and folder name lengths
564 if _, err := FS.Stat(newFolderPath); !os.IsNotExist(err) {
565 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that name.", folderName)
566 return []Transaction{cc.NewErrReply(t, msg)}, nil
569 // TODO: check for disallowed characters to maintain compatibility for original client
571 if err := FS.Mkdir(newFolderPath, 0777); err != nil {
572 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
573 return []Transaction{cc.NewErrReply(t, msg)}, nil
576 res = append(res, cc.NewReply(t))
580 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
581 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
582 userName := string(t.GetField(fieldUserName).Data)
584 newAccessLvl := t.GetField(fieldUserAccess).Data
586 account := cc.Server.Accounts[login]
587 account.Access = &newAccessLvl
588 account.Name = userName
590 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
591 // not include fieldUserPassword
592 if t.GetField(fieldUserPassword).Data == nil {
593 account.Password = hashAndSalt([]byte(""))
595 if len(t.GetField(fieldUserPassword).Data) > 1 {
596 account.Password = hashAndSalt(t.GetField(fieldUserPassword).Data)
599 file := cc.Server.ConfigDir + "Users/" + login + ".yaml"
600 out, err := yaml.Marshal(&account)
604 if err := ioutil.WriteFile(file, out, 0666); err != nil {
608 // Notify connected clients logged in as the user of the new access level
609 for _, c := range cc.Server.Clients {
610 if c.Account.Login == login {
611 // Note: comment out these two lines to test server-side deny messages
612 newT := NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, newAccessLvl))
613 res = append(res, *newT)
615 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
616 if authorize(c.Account.Access, accessDisconUser) {
617 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 1)
619 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 0)
621 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
623 c.Account.Access = account.Access
626 tranNotifyChangeUser,
627 NewField(fieldUserID, *c.ID),
628 NewField(fieldUserFlags, *c.Flags),
629 NewField(fieldUserName, c.UserName),
630 NewField(fieldUserIconID, *c.Icon),
635 res = append(res, cc.NewReply(t))
639 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
640 if !authorize(cc.Account.Access, accessOpenUser) {
641 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
645 account := cc.Server.Accounts[string(t.GetField(fieldUserLogin).Data)]
647 errorT := cc.NewErrReply(t, "Account does not exist.")
648 res = append(res, errorT)
652 res = append(res, cc.NewReply(t,
653 NewField(fieldUserName, []byte(account.Name)),
654 NewField(fieldUserLogin, negateString(t.GetField(fieldUserLogin).Data)),
655 NewField(fieldUserPassword, []byte(account.Password)),
656 NewField(fieldUserAccess, *account.Access),
661 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
662 var userFields []Field
663 // TODO: make order deterministic
664 for _, acc := range cc.Server.Accounts {
665 userField := acc.MarshalBinary()
666 userFields = append(userFields, NewField(fieldData, userField))
669 res = append(res, cc.NewReply(t, userFields...))
673 // HandleNewUser creates a new user account
674 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
675 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
677 // If the account already exists, reply with an error
678 // TODO: make order deterministic
679 if _, ok := cc.Server.Accounts[login]; ok {
680 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
684 if err := cc.Server.NewUser(
686 string(t.GetField(fieldUserName).Data),
687 string(t.GetField(fieldUserPassword).Data),
688 t.GetField(fieldUserAccess).Data,
690 return []Transaction{}, err
693 res = append(res, cc.NewReply(t))
697 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
698 if !authorize(cc.Account.Access, accessDeleteUser) {
699 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
703 // TODO: Handle case where account doesn't exist; e.g. delete race condition
704 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
706 if err := cc.Server.DeleteUser(login); err != nil {
710 res = append(res, cc.NewReply(t))
714 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
715 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
718 NewField(fieldData, t.GetField(tranGetMsgs).Data),
719 NewField(fieldChatOptions, []byte{0}),
722 res = append(res, cc.NewReply(t))
726 func byteToInt(bytes []byte) (int, error) {
729 return int(binary.BigEndian.Uint16(bytes)), nil
731 return int(binary.BigEndian.Uint32(bytes)), nil
734 return 0, errors.New("unknown byte length")
737 func HandleGetClientConnInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
738 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
740 clientConn := cc.Server.Clients[uint16(clientID)]
741 if clientConn == nil {
742 return res, errors.New("invalid client")
745 // TODO: Implement non-hardcoded values
746 template := `Nickname: %s
751 -------- File Downloads ---------
755 ------- Folder Downloads --------
759 --------- File Uploads ----------
763 -------- Folder Uploads ---------
767 ------- Waiting Downloads -------
773 activeDownloads := clientConn.Transfers[FileDownload]
774 activeDownloadList := "None."
775 for _, dl := range activeDownloads {
776 activeDownloadList += dl.String() + "\n"
779 template = fmt.Sprintf(
782 clientConn.Account.Name,
783 clientConn.Account.Login,
784 clientConn.Connection.RemoteAddr().String(),
787 template = strings.Replace(template, "\n", "\r", -1)
789 res = append(res, cc.NewReply(t,
790 NewField(fieldData, []byte(template)),
791 NewField(fieldUserName, clientConn.UserName),
796 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
797 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
802 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
804 cc.UserName = t.GetField(fieldUserName).Data
805 *cc.Icon = t.GetField(fieldUserIconID).Data
807 options := t.GetField(fieldOptions).Data
808 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
810 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
812 // Check refuse private PM option
813 if optBitmap.Bit(refusePM) == 1 {
814 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
815 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
818 // Check refuse private chat option
819 if optBitmap.Bit(refuseChat) == 1 {
820 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
821 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
824 // Check auto response
825 if optBitmap.Bit(autoResponse) == 1 {
826 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
828 cc.AutoReply = []byte{}
833 tranNotifyChangeUser, nil,
834 NewField(fieldUserName, cc.UserName),
835 NewField(fieldUserID, *cc.ID),
836 NewField(fieldUserIconID, *cc.Icon),
837 NewField(fieldUserFlags, *cc.Flags),
841 res = append(res, cc.NewReply(t))
846 const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
847 // "Mon, 02 Jan 2006 15:04:05 MST"
849 const defaultNewsTemplate = `From %s (%s):
853 __________________________________________________________`
855 // HandleTranOldPostNews updates the flat news
856 // Fields used in this request:
858 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
859 cc.Server.flatNewsMux.Lock()
860 defer cc.Server.flatNewsMux.Unlock()
862 newsDateTemplate := defaultNewsDateFormat
863 if cc.Server.Config.NewsDateFormat != "" {
864 newsDateTemplate = cc.Server.Config.NewsDateFormat
867 newsTemplate := defaultNewsTemplate
868 if cc.Server.Config.NewsDelimiter != "" {
869 newsTemplate = cc.Server.Config.NewsDelimiter
872 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
873 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
875 // update news in memory
876 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
878 // update news on disk
879 if err := ioutil.WriteFile(cc.Server.ConfigDir+"MessageBoard.txt", cc.Server.FlatNews, 0644); err != nil {
883 // Notify all clients of updated news
886 NewField(fieldData, []byte(newsPost)),
889 res = append(res, cc.NewReply(t))
893 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
894 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
896 if authorize(clientConn.Account.Access, accessCannotBeDiscon) {
897 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
901 if err := clientConn.Connection.Close(); err != nil {
905 res = append(res, cc.NewReply(t))
909 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
910 // Fields used in the request:
911 // 325 News path (Optional)
913 newsPath := t.GetField(fieldNewsPath).Data
914 cc.Server.Logger.Infow("NewsPath: ", "np", string(newsPath))
916 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
917 cats := cc.Server.GetNewsCatByPath(pathStrs)
919 // To store the keys in slice in sorted order
920 keys := make([]string, len(cats))
922 for k := range cats {
928 var fieldData []Field
929 for _, k := range keys {
931 b, _ := cat.MarshalBinary()
932 fieldData = append(fieldData, NewField(
933 fieldNewsCatListData15,
938 res = append(res, cc.NewReply(t, fieldData...))
942 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
943 name := string(t.GetField(fieldNewsCatName).Data)
944 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
946 cats := cc.Server.GetNewsCatByPath(pathStrs)
947 cats[name] = NewsCategoryListData15{
950 Articles: map[uint32]*NewsArtData{},
951 SubCats: make(map[string]NewsCategoryListData15),
954 if err := cc.Server.writeThreadedNews(); err != nil {
957 res = append(res, cc.NewReply(t))
961 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
962 // Fields used in the request:
963 // 322 News category name
965 name := string(t.GetField(fieldFileName).Data)
966 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
968 cc.Server.Logger.Infof("Creating new news folder %s", name)
970 cats := cc.Server.GetNewsCatByPath(pathStrs)
971 cats[name] = NewsCategoryListData15{
974 Articles: map[uint32]*NewsArtData{},
975 SubCats: make(map[string]NewsCategoryListData15),
977 if err := cc.Server.writeThreadedNews(); err != nil {
980 res = append(res, cc.NewReply(t))
984 // Fields used in the request:
985 // 325 News path Optional
988 // 321 News article list data Optional
989 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
990 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
992 var cat NewsCategoryListData15
993 cats := cc.Server.ThreadedNews.Categories
995 for _, fp := range pathStrs {
997 cats = cats[fp].SubCats
1000 nald := cat.GetNewsArtListData()
1002 res = append(res, cc.NewReply(t, NewField(fieldNewsArtListData, nald.Payload())))
1006 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1009 // 326 News article ID
1010 // 327 News article data flavor
1012 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1014 var cat NewsCategoryListData15
1015 cats := cc.Server.ThreadedNews.Categories
1017 for _, fp := range pathStrs {
1019 cats = cats[fp].SubCats
1021 newsArtID := t.GetField(fieldNewsArtID).Data
1023 convertedArtID := binary.BigEndian.Uint16(newsArtID)
1025 art := cat.Articles[uint32(convertedArtID)]
1027 res = append(res, cc.NewReply(t))
1032 // 328 News article title
1033 // 329 News article poster
1034 // 330 News article date
1035 // 331 Previous article ID
1036 // 332 Next article ID
1037 // 335 Parent article ID
1038 // 336 First child article ID
1039 // 327 News article data flavor "Should be “text/plain”
1040 // 333 News article data Optional (if data flavor is “text/plain”)
1042 res = append(res, cc.NewReply(t,
1043 NewField(fieldNewsArtTitle, []byte(art.Title)),
1044 NewField(fieldNewsArtPoster, []byte(art.Poster)),
1045 NewField(fieldNewsArtDate, art.Date),
1046 NewField(fieldNewsArtPrevArt, art.PrevArt),
1047 NewField(fieldNewsArtNextArt, art.NextArt),
1048 NewField(fieldNewsArtParentArt, art.ParentArt),
1049 NewField(fieldNewsArt1stChildArt, art.FirstChildArt),
1050 NewField(fieldNewsArtDataFlav, []byte("text/plain")),
1051 NewField(fieldNewsArtData, []byte(art.Data)),
1056 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1057 // Access: News Delete Folder (37) or News Delete Category (35)
1059 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1061 // TODO: determine if path is a Folder (Bundle) or Category and check for permission
1063 cc.Server.Logger.Infof("DelNewsItem %v", pathStrs)
1065 cats := cc.Server.ThreadedNews.Categories
1067 delName := pathStrs[len(pathStrs)-1]
1068 if len(pathStrs) > 1 {
1069 for _, path := range pathStrs[0 : len(pathStrs)-1] {
1070 cats = cats[path].SubCats
1074 delete(cats, delName)
1076 err = cc.Server.writeThreadedNews()
1081 // Reply params: none
1082 res = append(res, cc.NewReply(t))
1087 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1090 // 326 News article ID
1091 // 337 News article – recursive delete Delete child articles (1) or not (0)
1092 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1093 ID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1095 // TODO: Delete recursive
1096 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1098 catName := pathStrs[len(pathStrs)-1]
1099 cat := cats[catName]
1101 delete(cat.Articles, uint32(ID))
1104 if err := cc.Server.writeThreadedNews(); err != nil {
1108 res = append(res, cc.NewReply(t))
1112 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1115 // 326 News article ID ID of the parent article?
1116 // 328 News article title
1117 // 334 News article flags
1118 // 327 News article data flavor Currently “text/plain”
1119 // 333 News article data
1121 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1122 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1124 catName := pathStrs[len(pathStrs)-1]
1125 cat := cats[catName]
1127 newArt := NewsArtData{
1128 Title: string(t.GetField(fieldNewsArtTitle).Data),
1129 Poster: string(cc.UserName),
1130 Date: toHotlineTime(time.Now()),
1131 PrevArt: []byte{0, 0, 0, 0},
1132 NextArt: []byte{0, 0, 0, 0},
1133 ParentArt: append([]byte{0, 0}, t.GetField(fieldNewsArtID).Data...),
1134 FirstChildArt: []byte{0, 0, 0, 0},
1135 DataFlav: []byte("text/plain"),
1136 Data: string(t.GetField(fieldNewsArtData).Data),
1140 for k := range cat.Articles {
1141 keys = append(keys, int(k))
1147 prevID := uint32(keys[len(keys)-1])
1150 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1152 // Set next article ID
1153 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1156 // Update parent article with first child reply
1157 parentID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1159 parentArt := cat.Articles[uint32(parentID)]
1161 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1162 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1166 cat.Articles[nextID] = &newArt
1169 if err := cc.Server.writeThreadedNews(); err != nil {
1173 res = append(res, cc.NewReply(t))
1177 // HandleGetMsgs returns the flat news data
1178 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1179 res = append(res, cc.NewReply(t, NewField(fieldData, cc.Server.FlatNews)))
1184 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1185 fileName := t.GetField(fieldFileName).Data
1186 filePath := t.GetField(fieldFilePath).Data
1189 err = fp.UnmarshalBinary(filePath)
1194 ffo, err := NewFlattenedFileObject(cc.Server.Config.FileRoot, filePath, fileName)
1199 transactionRef := cc.Server.NewTransactionRef()
1200 data := binary.BigEndian.Uint32(transactionRef)
1202 ft := &FileTransfer{
1205 ReferenceNumber: transactionRef,
1209 cc.Server.FileTransfers[data] = ft
1210 cc.Transfers[FileDownload] = append(cc.Transfers[FileDownload], ft)
1212 res = append(res, cc.NewReply(t,
1213 NewField(fieldRefNum, transactionRef),
1214 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1215 NewField(fieldTransferSize, ffo.TransferSize()),
1216 NewField(fieldFileSize, ffo.FlatFileDataForkHeader.DataSize),
1222 // Download all files from the specified folder and sub-folders
1235 // 00 6c // transfer size
1239 // 00 dc // field Folder item count
1243 // 00 6b // ref number
1246 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1247 transactionRef := cc.Server.NewTransactionRef()
1248 data := binary.BigEndian.Uint32(transactionRef)
1250 fileTransfer := &FileTransfer{
1251 FileName: t.GetField(fieldFileName).Data,
1252 FilePath: t.GetField(fieldFilePath).Data,
1253 ReferenceNumber: transactionRef,
1254 Type: FolderDownload,
1256 cc.Server.FileTransfers[data] = fileTransfer
1257 cc.Transfers[FolderDownload] = append(cc.Transfers[FolderDownload], fileTransfer)
1260 err = fp.UnmarshalBinary(t.GetField(fieldFilePath).Data)
1265 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
1270 transferSize, err := CalcTotalSize(fullFilePath)
1274 itemCount, err := CalcItemCount(fullFilePath)
1278 res = append(res, cc.NewReply(t,
1279 NewField(fieldRefNum, transactionRef),
1280 NewField(fieldTransferSize, transferSize),
1281 NewField(fieldFolderItemCount, itemCount),
1282 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1287 // Upload all files from the local folder and its subfolders to the specified path on the server
1288 // Fields used in the request
1291 // 108 transfer size Total size of all items in the folder
1292 // 220 Folder item count
1293 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1294 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1295 transactionRef := cc.Server.NewTransactionRef()
1296 data := binary.BigEndian.Uint32(transactionRef)
1298 fileTransfer := &FileTransfer{
1299 FileName: t.GetField(fieldFileName).Data,
1300 FilePath: t.GetField(fieldFilePath).Data,
1301 ReferenceNumber: transactionRef,
1303 FolderItemCount: t.GetField(fieldFolderItemCount).Data,
1304 TransferSize: t.GetField(fieldTransferSize).Data,
1306 cc.Server.FileTransfers[data] = fileTransfer
1308 res = append(res, cc.NewReply(t, NewField(fieldRefNum, transactionRef)))
1312 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1313 // TODO: add permission handing for upload folders and drop boxes
1314 if !authorize(cc.Account.Access, accessUploadFile) {
1315 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1319 fileName := t.GetField(fieldFileName).Data
1320 filePath := t.GetField(fieldFilePath).Data
1322 transactionRef := cc.Server.NewTransactionRef()
1323 data := binary.BigEndian.Uint32(transactionRef)
1325 cc.Server.FileTransfers[data] = &FileTransfer{
1328 ReferenceNumber: transactionRef,
1332 res = append(res, cc.NewReply(t, NewField(fieldRefNum, transactionRef)))
1336 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1338 if len(t.GetField(fieldUserIconID).Data) == 4 {
1339 icon = t.GetField(fieldUserIconID).Data[2:]
1341 icon = t.GetField(fieldUserIconID).Data
1344 cc.UserName = t.GetField(fieldUserName).Data
1346 // the options field is only passed by the client versions > 1.2.3.
1347 options := t.GetField(fieldOptions).Data
1350 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1351 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
1353 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, optBitmap.Bit(refusePM))
1354 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
1356 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, optBitmap.Bit(refuseChat))
1357 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
1359 // Check auto response
1360 if optBitmap.Bit(autoResponse) == 1 {
1361 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
1363 cc.AutoReply = []byte{}
1367 // Notify all clients of updated user info
1369 tranNotifyChangeUser,
1370 NewField(fieldUserID, *cc.ID),
1371 NewField(fieldUserIconID, *cc.Icon),
1372 NewField(fieldUserFlags, *cc.Flags),
1373 NewField(fieldUserName, cc.UserName),
1379 // HandleKeepAlive responds to keepalive transactions with an empty reply
1380 // * HL 1.9.2 Client sends keepalive msg every 3 minutes
1381 // * HL 1.2.3 Client doesn't send keepalives
1382 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1383 res = append(res, cc.NewReply(t))
1388 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1389 fullPath, err := readPath(
1390 cc.Server.Config.FileRoot,
1391 t.GetField(fieldFilePath).Data,
1398 fileNames, err := getFileNameList(fullPath)
1403 res = append(res, cc.NewReply(t, fileNames...))
1408 // =================================
1409 // Hotline private chat flow
1410 // =================================
1411 // 1. ClientA sends tranInviteNewChat to server with user ID to invite
1412 // 2. Server creates new ChatID
1413 // 3. Server sends tranInviteToChat to invitee
1414 // 4. Server replies to ClientA with new Chat ID
1416 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1417 // If Accepted is clicked:
1418 // 1. ClientB sends tranJoinChat with fieldChatID
1420 // HandleInviteNewChat invites users to new private chat
1421 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1423 targetID := t.GetField(fieldUserID).Data
1424 newChatID := cc.Server.NewPrivateChat(cc)
1430 NewField(fieldChatID, newChatID),
1431 NewField(fieldUserName, cc.UserName),
1432 NewField(fieldUserID, *cc.ID),
1438 NewField(fieldChatID, newChatID),
1439 NewField(fieldUserName, cc.UserName),
1440 NewField(fieldUserID, *cc.ID),
1441 NewField(fieldUserIconID, *cc.Icon),
1442 NewField(fieldUserFlags, *cc.Flags),
1449 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1451 targetID := t.GetField(fieldUserID).Data
1452 chatID := t.GetField(fieldChatID).Data
1458 NewField(fieldChatID, chatID),
1459 NewField(fieldUserName, cc.UserName),
1460 NewField(fieldUserID, *cc.ID),
1466 NewField(fieldChatID, chatID),
1467 NewField(fieldUserName, cc.UserName),
1468 NewField(fieldUserID, *cc.ID),
1469 NewField(fieldUserIconID, *cc.Icon),
1470 NewField(fieldUserFlags, *cc.Flags),
1477 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1478 chatID := t.GetField(fieldChatID).Data
1479 chatInt := binary.BigEndian.Uint32(chatID)
1481 privChat := cc.Server.PrivateChats[chatInt]
1483 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1485 for _, c := range sortedClients(privChat.ClientConn) {
1490 NewField(fieldChatID, chatID),
1491 NewField(fieldData, resMsg),
1499 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1500 // Fields used in the reply:
1501 // * 115 Chat subject
1502 // * 300 User name with info (Optional)
1503 // * 300 (more user names with info)
1504 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1505 chatID := t.GetField(fieldChatID).Data
1506 chatInt := binary.BigEndian.Uint32(chatID)
1508 privChat := cc.Server.PrivateChats[chatInt]
1510 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1511 for _, c := range sortedClients(privChat.ClientConn) {
1514 tranNotifyChatChangeUser,
1516 NewField(fieldChatID, chatID),
1517 NewField(fieldUserName, cc.UserName),
1518 NewField(fieldUserID, *cc.ID),
1519 NewField(fieldUserIconID, *cc.Icon),
1520 NewField(fieldUserFlags, *cc.Flags),
1525 privChat.ClientConn[cc.uint16ID()] = cc
1527 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1528 for _, c := range sortedClients(privChat.ClientConn) {
1533 Name: string(c.UserName),
1536 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1539 res = append(res, cc.NewReply(t, replyFields...))
1543 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1544 // Fields used in the request:
1545 // * 114 fieldChatID
1546 // Reply is not expected.
1547 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1548 chatID := t.GetField(fieldChatID).Data
1549 chatInt := binary.BigEndian.Uint32(chatID)
1551 privChat := cc.Server.PrivateChats[chatInt]
1553 delete(privChat.ClientConn, cc.uint16ID())
1555 // Notify members of the private chat that the user has left
1556 for _, c := range sortedClients(privChat.ClientConn) {
1559 tranNotifyChatDeleteUser,
1561 NewField(fieldChatID, chatID),
1562 NewField(fieldUserID, *cc.ID),
1570 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1571 // Fields used in the request:
1573 // * 115 Chat subject Chat subject string
1574 // Reply is not expected.
1575 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1576 chatID := t.GetField(fieldChatID).Data
1577 chatInt := binary.BigEndian.Uint32(chatID)
1579 privChat := cc.Server.PrivateChats[chatInt]
1580 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1582 for _, c := range sortedClients(privChat.ClientConn) {
1585 tranNotifyChatSubject,
1587 NewField(fieldChatID, chatID),
1588 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),
1596 // HandleMakeAlias makes a file alias using the specified path.
1597 // Fields used in the request:
1600 // 212 File new path Destination path
1602 // Fields used in the reply:
1604 func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1605 if !authorize(cc.Account.Access, accessMakeAlias) {
1606 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
1609 fileName := t.GetField(fieldFileName).Data
1610 filePath := t.GetField(fieldFilePath).Data
1611 fileNewPath := t.GetField(fieldFileNewPath).Data
1613 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1618 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
1623 cc.Server.Logger.Debugw("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
1625 if err := FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
1626 res = append(res, cc.NewErrReply(t, "Error creating alias"))
1630 res = append(res, cc.NewReply(t))