8 "github.com/davecgh/go-spew/spew"
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("*** %s %s\r", *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 := string(t.GetField(fieldFileName).Data)
401 filePath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
402 spew.Dump(cc.Server.Config.FileRoot)
404 ffo, err := NewFlattenedFileObject(filePath, fileName)
409 res = append(res, cc.NewReply(t,
410 NewField(fieldFileName, []byte(fileName)),
411 NewField(fieldFileTypeString, ffo.FlatFileInformationFork.TypeSignature),
412 NewField(fieldFileCreatorString, ffo.FlatFileInformationFork.CreatorSignature),
413 NewField(fieldFileComment, ffo.FlatFileInformationFork.Comment),
414 NewField(fieldFileType, ffo.FlatFileInformationFork.TypeSignature),
415 NewField(fieldFileCreateDate, ffo.FlatFileInformationFork.CreateDate),
416 NewField(fieldFileModifyDate, ffo.FlatFileInformationFork.ModifyDate),
417 NewField(fieldFileSize, ffo.FlatFileDataForkHeader.DataSize),
422 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
423 // TODO: Implement support for comments
424 // Fields used in the request:
426 // * 202 File path Optional
427 // * 211 File new name Optional
428 // * 210 File comment Optional
429 // Fields used in the reply: None
430 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
431 fileName := string(t.GetField(fieldFileName).Data)
432 filePath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
433 //fileComment := t.GetField(fieldFileComment).Data
434 fileNewName := t.GetField(fieldFileNewName).Data
436 if fileNewName != nil {
437 path := filePath + "/" + fileName
438 fi, err := os.Stat(path)
442 switch mode := fi.Mode(); {
444 if !authorize(cc.Account.Access, accessRenameFolder) {
445 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
448 case mode.IsRegular():
449 if !authorize(cc.Account.Access, accessRenameFile) {
450 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
455 err = os.Rename(filePath+"/"+fileName, filePath+"/"+string(fileNewName))
456 if os.IsNotExist(err) {
457 res = append(res, cc.NewErrReply(t, "Cannot rename file "+fileName+" because it does not exist or cannot be found."))
462 res = append(res, cc.NewReply(t))
466 // HandleDeleteFile deletes a file or folder
467 // Fields used in the request:
470 // Fields used in the reply: none
471 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
472 fileName := string(t.GetField(fieldFileName).Data)
473 filePath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
475 path := "./" + filePath + "/" + fileName
477 cc.Server.Logger.Debugw("Delete file", "src", filePath+"/"+fileName)
479 fi, err := os.Stat(path)
481 res = append(res, cc.NewErrReply(t, "Cannot delete file "+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(path); 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 path := filePath + "/" + fileName
514 fi, err := os.Stat(path)
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
548 // fieldFilePath is only present for nested paths
549 if t.GetField(fieldFilePath).Data != nil {
550 newFp := NewFilePath(t.GetField(fieldFilePath).Data)
551 newFolderPath += newFp.String()
553 newFolderPath += "/" + string(t.GetField(fieldFileName).Data)
555 if err := os.Mkdir(newFolderPath, 0777); err != nil {
556 // TODO: Send error response to client
557 return []Transaction{}, err
560 res = append(res, cc.NewReply(t))
564 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
565 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
566 userName := string(t.GetField(fieldUserName).Data)
568 newAccessLvl := t.GetField(fieldUserAccess).Data
570 account := cc.Server.Accounts[login]
571 account.Access = &newAccessLvl
572 account.Name = userName
574 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
575 // not include fieldUserPassword
576 if t.GetField(fieldUserPassword).Data == nil {
577 account.Password = hashAndSalt([]byte(""))
579 if len(t.GetField(fieldUserPassword).Data) > 1 {
580 account.Password = hashAndSalt(t.GetField(fieldUserPassword).Data)
583 file := cc.Server.ConfigDir + "Users/" + login + ".yaml"
584 out, err := yaml.Marshal(&account)
588 if err := ioutil.WriteFile(file, out, 0666); err != nil {
592 // Notify connected clients logged in as the user of the new access level
593 for _, c := range cc.Server.Clients {
594 if c.Account.Login == login {
595 // Note: comment out these two lines to test server-side deny messages
596 newT := NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, newAccessLvl))
597 res = append(res, *newT)
599 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
600 if authorize(c.Account.Access, accessDisconUser) {
601 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 1)
603 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 0)
605 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
607 c.Account.Access = account.Access
610 tranNotifyChangeUser,
611 NewField(fieldUserID, *c.ID),
612 NewField(fieldUserFlags, *c.Flags),
613 NewField(fieldUserName, *c.UserName),
614 NewField(fieldUserIconID, *c.Icon),
619 // TODO: If we have just promoted a connected user to admin, notify
620 // connected clients to turn the user red
622 res = append(res, cc.NewReply(t))
626 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
627 userLogin := string(t.GetField(fieldUserLogin).Data)
628 decodedUserLogin := NegatedUserString(t.GetField(fieldUserLogin).Data)
629 account := cc.Server.Accounts[userLogin]
631 errorT := cc.NewErrReply(t, "Account does not exist.")
632 res = append(res, errorT)
636 res = append(res, cc.NewReply(t,
637 NewField(fieldUserName, []byte(account.Name)),
638 NewField(fieldUserLogin, []byte(decodedUserLogin)),
639 NewField(fieldUserPassword, []byte(account.Password)),
640 NewField(fieldUserAccess, *account.Access),
645 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
646 var userFields []Field
647 // TODO: make order deterministic
648 for _, acc := range cc.Server.Accounts {
649 userField := acc.Payload()
650 userFields = append(userFields, NewField(fieldData, userField))
653 res = append(res, cc.NewReply(t, userFields...))
657 // HandleNewUser creates a new user account
658 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
659 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
661 // If the account already exists, reply with an error
662 // TODO: make order deterministic
663 if _, ok := cc.Server.Accounts[login]; ok {
664 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
668 if err := cc.Server.NewUser(
670 string(t.GetField(fieldUserName).Data),
671 string(t.GetField(fieldUserPassword).Data),
672 t.GetField(fieldUserAccess).Data,
674 return []Transaction{}, err
677 res = append(res, cc.NewReply(t))
681 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
682 // TODO: Handle case where account doesn't exist; e.g. delete race condition
683 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
685 if err := cc.Server.DeleteUser(login); err != nil {
689 res = append(res, cc.NewReply(t))
693 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
694 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
697 NewField(fieldData, t.GetField(tranGetMsgs).Data),
698 NewField(fieldChatOptions, []byte{0}),
701 res = append(res, cc.NewReply(t))
705 func byteToInt(bytes []byte) (int, error) {
708 return int(binary.BigEndian.Uint16(bytes)), nil
710 return int(binary.BigEndian.Uint32(bytes)), nil
713 return 0, errors.New("unknown byte length")
716 func HandleGetClientConnInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
717 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
719 clientConn := cc.Server.Clients[uint16(clientID)]
720 if clientConn == nil {
721 return res, errors.New("invalid client")
724 // TODO: Implement non-hardcoded values
725 template := `Nickname: %s
730 -------- File Downloads ---------
734 ------- Folder Downloads --------
738 --------- File Uploads ----------
742 -------- Folder Uploads ---------
746 ------- Waiting Downloads -------
752 activeDownloads := clientConn.Transfers[FileDownload]
753 activeDownloadList := "None."
754 for _, dl := range activeDownloads {
755 activeDownloadList += dl.String() + "\n"
758 template = fmt.Sprintf(
760 *clientConn.UserName,
761 clientConn.Account.Name,
762 clientConn.Account.Login,
763 clientConn.Connection.RemoteAddr().String(),
766 template = strings.Replace(template, "\n", "\r", -1)
768 res = append(res, cc.NewReply(t,
769 NewField(fieldData, []byte(template)),
770 NewField(fieldUserName, *clientConn.UserName),
775 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
776 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
781 func (cc *ClientConn) notifyNewUserHasJoined() (res []Transaction, err error) {
782 // Notify other ccs that a new user has connected
785 tranNotifyChangeUser, nil,
786 NewField(fieldUserName, *cc.UserName),
787 NewField(fieldUserID, *cc.ID),
788 NewField(fieldUserIconID, *cc.Icon),
789 NewField(fieldUserFlags, *cc.Flags),
796 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
797 bs := make([]byte, 2)
798 binary.BigEndian.PutUint16(bs, *cc.Server.NextGuestID)
800 *cc.UserName = t.GetField(fieldUserName).Data
802 *cc.Icon = t.GetField(fieldUserIconID).Data
804 options := t.GetField(fieldOptions).Data
805 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
807 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
809 // Check refuse private PM option
810 if optBitmap.Bit(refusePM) == 1 {
811 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
812 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
815 // Check refuse private chat option
816 if optBitmap.Bit(refuseChat) == 1 {
817 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
818 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
821 // Check auto response
822 if optBitmap.Bit(autoResponse) == 1 {
823 *cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
825 *cc.AutoReply = []byte{}
828 _, _ = cc.notifyNewUserHasJoined()
830 res = append(res, cc.NewReply(t))
835 const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
836 // "Mon, 02 Jan 2006 15:04:05 MST"
838 const defaultNewsTemplate = `From %s (%s):
842 __________________________________________________________`
844 // HandleTranOldPostNews updates the flat news
845 // Fields used in this request:
847 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
848 cc.Server.flatNewsMux.Lock()
849 defer cc.Server.flatNewsMux.Unlock()
851 newsDateTemplate := defaultNewsDateFormat
852 if cc.Server.Config.NewsDateFormat != "" {
853 newsDateTemplate = cc.Server.Config.NewsDateFormat
856 newsTemplate := defaultNewsTemplate
857 if cc.Server.Config.NewsDelimiter != "" {
858 newsTemplate = cc.Server.Config.NewsDelimiter
861 newsPost := fmt.Sprintf(newsTemplate+"\r", *cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
862 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
864 // update news in memory
865 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
867 // update news on disk
868 if err := ioutil.WriteFile(cc.Server.ConfigDir+"MessageBoard.txt", cc.Server.FlatNews, 0644); err != nil {
872 // Notify all clients of updated news
875 NewField(fieldData, []byte(newsPost)),
878 res = append(res, cc.NewReply(t))
882 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
883 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
885 if authorize(clientConn.Account.Access, accessCannotBeDiscon) {
886 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
890 if err := clientConn.Connection.Close(); err != nil {
894 res = append(res, cc.NewReply(t))
898 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
899 // Fields used in the request:
900 // 325 News path (Optional)
902 newsPath := t.GetField(fieldNewsPath).Data
903 cc.Server.Logger.Infow("NewsPath: ", "np", string(newsPath))
905 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
906 cats := cc.Server.GetNewsCatByPath(pathStrs)
908 // To store the keys in slice in sorted order
909 keys := make([]string, len(cats))
911 for k := range cats {
917 var fieldData []Field
918 for _, k := range keys {
920 fieldData = append(fieldData, NewField(
921 fieldNewsCatListData15,
926 res = append(res, cc.NewReply(t, fieldData...))
930 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
931 name := string(t.GetField(fieldNewsCatName).Data)
932 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
934 cats := cc.Server.GetNewsCatByPath(pathStrs)
935 cats[name] = NewsCategoryListData15{
938 Articles: map[uint32]*NewsArtData{},
939 SubCats: make(map[string]NewsCategoryListData15),
942 if err := cc.Server.writeThreadedNews(); err != nil {
945 res = append(res, cc.NewReply(t))
949 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
950 // Fields used in the request:
951 // 322 News category name
953 name := string(t.GetField(fieldFileName).Data)
954 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
956 cc.Server.Logger.Infof("Creating new news folder %s", name)
958 cats := cc.Server.GetNewsCatByPath(pathStrs)
959 cats[name] = NewsCategoryListData15{
962 Articles: map[uint32]*NewsArtData{},
963 SubCats: make(map[string]NewsCategoryListData15),
965 if err := cc.Server.writeThreadedNews(); err != nil {
968 res = append(res, cc.NewReply(t))
972 // Fields used in the request:
973 // 325 News path Optional
976 // 321 News article list data Optional
977 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
978 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
980 var cat NewsCategoryListData15
981 cats := cc.Server.ThreadedNews.Categories
983 for _, path := range pathStrs {
985 cats = cats[path].SubCats
988 nald := cat.GetNewsArtListData()
990 res = append(res, cc.NewReply(t, NewField(fieldNewsArtListData, nald.Payload())))
994 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
997 // 326 News article ID
998 // 327 News article data flavor
1000 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1002 var cat NewsCategoryListData15
1003 cats := cc.Server.ThreadedNews.Categories
1005 for _, path := range pathStrs {
1007 cats = cats[path].SubCats
1009 newsArtID := t.GetField(fieldNewsArtID).Data
1011 convertedArtID := binary.BigEndian.Uint16(newsArtID)
1013 art := cat.Articles[uint32(convertedArtID)]
1015 res = append(res, cc.NewReply(t))
1020 // 328 News article title
1021 // 329 News article poster
1022 // 330 News article date
1023 // 331 Previous article ID
1024 // 332 Next article ID
1025 // 335 Parent article ID
1026 // 336 First child article ID
1027 // 327 News article data flavor "Should be “text/plain”
1028 // 333 News article data Optional (if data flavor is “text/plain”)
1030 res = append(res, cc.NewReply(t,
1031 NewField(fieldNewsArtTitle, []byte(art.Title)),
1032 NewField(fieldNewsArtPoster, []byte(art.Poster)),
1033 NewField(fieldNewsArtDate, art.Date),
1034 NewField(fieldNewsArtPrevArt, art.PrevArt),
1035 NewField(fieldNewsArtNextArt, art.NextArt),
1036 NewField(fieldNewsArtParentArt, art.ParentArt),
1037 NewField(fieldNewsArt1stChildArt, art.FirstChildArt),
1038 NewField(fieldNewsArtDataFlav, []byte("text/plain")),
1039 NewField(fieldNewsArtData, []byte(art.Data)),
1044 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1045 // Access: News Delete Folder (37) or News Delete Category (35)
1047 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1049 // TODO: determine if path is a Folder (Bundle) or Category and check for permission
1051 cc.Server.Logger.Infof("DelNewsItem %v", pathStrs)
1053 cats := cc.Server.ThreadedNews.Categories
1055 delName := pathStrs[len(pathStrs)-1]
1056 if len(pathStrs) > 1 {
1057 for _, path := range pathStrs[0 : len(pathStrs)-1] {
1058 cats = cats[path].SubCats
1062 delete(cats, delName)
1064 err = cc.Server.writeThreadedNews()
1069 // Reply params: none
1070 res = append(res, cc.NewReply(t))
1075 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1078 // 326 News article ID
1079 // 337 News article – recursive delete Delete child articles (1) or not (0)
1080 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1081 ID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1083 // TODO: Delete recursive
1084 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1086 catName := pathStrs[len(pathStrs)-1]
1087 cat := cats[catName]
1089 delete(cat.Articles, uint32(ID))
1092 if err := cc.Server.writeThreadedNews(); err != nil {
1096 res = append(res, cc.NewReply(t))
1100 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1103 // 326 News article ID ID of the parent article?
1104 // 328 News article title
1105 // 334 News article flags
1106 // 327 News article data flavor Currently “text/plain”
1107 // 333 News article data
1109 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1110 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1112 catName := pathStrs[len(pathStrs)-1]
1113 cat := cats[catName]
1115 newArt := NewsArtData{
1116 Title: string(t.GetField(fieldNewsArtTitle).Data),
1117 Poster: string(*cc.UserName),
1119 PrevArt: []byte{0, 0, 0, 0},
1120 NextArt: []byte{0, 0, 0, 0},
1121 ParentArt: append([]byte{0, 0}, t.GetField(fieldNewsArtID).Data...),
1122 FirstChildArt: []byte{0, 0, 0, 0},
1123 DataFlav: []byte("text/plain"),
1124 Data: string(t.GetField(fieldNewsArtData).Data),
1128 for k := range cat.Articles {
1129 keys = append(keys, int(k))
1135 prevID := uint32(keys[len(keys)-1])
1138 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1140 // Set next article ID
1141 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1144 // Update parent article with first child reply
1145 parentID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1147 parentArt := cat.Articles[uint32(parentID)]
1149 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1150 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1154 cat.Articles[nextID] = &newArt
1157 if err := cc.Server.writeThreadedNews(); err != nil {
1161 res = append(res, cc.NewReply(t))
1165 // HandleGetMsgs returns the flat news data
1166 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1167 res = append(res, cc.NewReply(t, NewField(fieldData, cc.Server.FlatNews)))
1172 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1173 fileName := t.GetField(fieldFileName).Data
1174 filePath := ReadFilePath(t.GetField(fieldFilePath).Data)
1176 ffo, err := NewFlattenedFileObject(cc.Server.Config.FileRoot+filePath, string(fileName))
1181 transactionRef := cc.Server.NewTransactionRef()
1182 data := binary.BigEndian.Uint32(transactionRef)
1184 cc.Server.Logger.Infow("File download", "path", filePath)
1186 ft := &FileTransfer{
1188 FilePath: []byte(filePath),
1189 ReferenceNumber: transactionRef,
1193 cc.Server.FileTransfers[data] = ft
1194 cc.Transfers[FileDownload] = append(cc.Transfers[FileDownload], ft)
1196 res = append(res, cc.NewReply(t,
1197 NewField(fieldRefNum, transactionRef),
1198 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1199 NewField(fieldTransferSize, ffo.TransferSize()),
1200 NewField(fieldFileSize, ffo.FlatFileDataForkHeader.DataSize),
1206 // Download all files from the specified folder and sub-folders
1219 // 00 6c // transfer size
1223 // 00 dc // field Folder item count
1227 // 00 6b // ref number
1230 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1231 transactionRef := cc.Server.NewTransactionRef()
1232 data := binary.BigEndian.Uint32(transactionRef)
1234 fileTransfer := &FileTransfer{
1235 FileName: t.GetField(fieldFileName).Data,
1236 FilePath: t.GetField(fieldFilePath).Data,
1237 ReferenceNumber: transactionRef,
1238 Type: FolderDownload,
1240 cc.Server.FileTransfers[data] = fileTransfer
1241 cc.Transfers[FolderDownload] = append(cc.Transfers[FolderDownload], fileTransfer)
1243 fp := NewFilePath(t.GetField(fieldFilePath).Data)
1245 fullFilePath := fmt.Sprintf("./%v/%v", cc.Server.Config.FileRoot+fp.String(), string(fileTransfer.FileName))
1246 transferSize, err := CalcTotalSize(fullFilePath)
1250 itemCount, err := CalcItemCount(fullFilePath)
1254 res = append(res, cc.NewReply(t,
1255 NewField(fieldRefNum, transactionRef),
1256 NewField(fieldTransferSize, transferSize),
1257 NewField(fieldFolderItemCount, itemCount),
1258 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1263 // Upload all files from the local folder and its subfolders to the specified path on the server
1264 // Fields used in the request
1267 // 108 Transfer size Total size of all items in the folder
1268 // 220 Folder item count
1269 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1270 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1271 transactionRef := cc.Server.NewTransactionRef()
1272 data := binary.BigEndian.Uint32(transactionRef)
1274 fileTransfer := &FileTransfer{
1275 FileName: t.GetField(fieldFileName).Data,
1276 FilePath: t.GetField(fieldFilePath).Data,
1277 ReferenceNumber: transactionRef,
1279 FolderItemCount: t.GetField(fieldFolderItemCount).Data,
1280 TransferSize: t.GetField(fieldTransferSize).Data,
1282 cc.Server.FileTransfers[data] = fileTransfer
1284 res = append(res, cc.NewReply(t, NewField(fieldRefNum, transactionRef)))
1288 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1289 fileName := t.GetField(fieldFileName).Data
1290 filePath := t.GetField(fieldFilePath).Data
1292 transactionRef := cc.Server.NewTransactionRef()
1293 data := binary.BigEndian.Uint32(transactionRef)
1295 fileTransfer := &FileTransfer{
1298 ReferenceNumber: transactionRef,
1302 cc.Server.FileTransfers[data] = fileTransfer
1304 res = append(res, cc.NewReply(t, NewField(fieldRefNum, transactionRef)))
1315 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1317 if len(t.GetField(fieldUserIconID).Data) == 4 {
1318 icon = t.GetField(fieldUserIconID).Data[2:]
1320 icon = t.GetField(fieldUserIconID).Data
1323 *cc.UserName = t.GetField(fieldUserName).Data
1325 // the options field is only passed by the client versions > 1.2.3.
1326 options := t.GetField(fieldOptions).Data
1329 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1330 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
1332 // Check refuse private PM option
1333 if optBitmap.Bit(refusePM) == 1 {
1334 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
1335 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
1338 // Check refuse private chat option
1339 if optBitmap.Bit(refuseChat) == 1 {
1340 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
1341 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
1344 // Check auto response
1345 if optBitmap.Bit(autoResponse) == 1 {
1346 *cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
1348 *cc.AutoReply = []byte{}
1352 // Notify all clients of updated user info
1354 tranNotifyChangeUser,
1355 NewField(fieldUserID, *cc.ID),
1356 NewField(fieldUserIconID, *cc.Icon),
1357 NewField(fieldUserFlags, *cc.Flags),
1358 NewField(fieldUserName, *cc.UserName),
1364 // HandleKeepAlive response to keepalive transactions with an empty reply
1365 // HL 1.9.2 Client sends keepalive msg every 3 minutes
1366 // HL 1.2.3 Client doesn't send keepalives
1367 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1368 res = append(res, cc.NewReply(t))
1373 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1374 filePath := cc.Server.Config.FileRoot
1376 path := t.GetField(fieldFilePath).Data
1378 filePath = cc.Server.Config.FileRoot + ReadFilePath(path)
1381 fileNames, err := getFileNameList(filePath)
1386 res = append(res, cc.NewReply(t, fileNames...))
1391 // =================================
1392 // Hotline private chat flow
1393 // =================================
1394 // 1. ClientA sends tranInviteNewChat to server with user ID to invite
1395 // 2. Server creates new ChatID
1396 // 3. Server sends tranInviteToChat to invitee
1397 // 4. Server replies to ClientA with new Chat ID
1399 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1400 // If Accepted is clicked:
1401 // 1. ClientB sends tranJoinChat with fieldChatID
1403 // HandleInviteNewChat invites users to new private chat
1404 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1406 targetID := t.GetField(fieldUserID).Data
1407 newChatID := cc.Server.NewPrivateChat(cc)
1413 NewField(fieldChatID, newChatID),
1414 NewField(fieldUserName, *cc.UserName),
1415 NewField(fieldUserID, *cc.ID),
1421 NewField(fieldChatID, newChatID),
1422 NewField(fieldUserName, *cc.UserName),
1423 NewField(fieldUserID, *cc.ID),
1424 NewField(fieldUserIconID, *cc.Icon),
1425 NewField(fieldUserFlags, *cc.Flags),
1432 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1434 targetID := t.GetField(fieldUserID).Data
1435 chatID := t.GetField(fieldChatID).Data
1441 NewField(fieldChatID, chatID),
1442 NewField(fieldUserName, *cc.UserName),
1443 NewField(fieldUserID, *cc.ID),
1449 NewField(fieldChatID, chatID),
1450 NewField(fieldUserName, *cc.UserName),
1451 NewField(fieldUserID, *cc.ID),
1452 NewField(fieldUserIconID, *cc.Icon),
1453 NewField(fieldUserFlags, *cc.Flags),
1460 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1461 chatID := t.GetField(fieldChatID).Data
1462 chatInt := binary.BigEndian.Uint32(chatID)
1464 privChat := cc.Server.PrivateChats[chatInt]
1466 resMsg := append(*cc.UserName, []byte(" declined invitation to chat")...)
1468 for _, c := range sortedClients(privChat.ClientConn) {
1473 NewField(fieldChatID, chatID),
1474 NewField(fieldData, resMsg),
1482 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1483 // Fields used in the reply:
1484 // * 115 Chat subject
1485 // * 300 User name with info (Optional)
1486 // * 300 (more user names with info)
1487 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1488 chatID := t.GetField(fieldChatID).Data
1489 chatInt := binary.BigEndian.Uint32(chatID)
1491 privChat := cc.Server.PrivateChats[chatInt]
1493 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1494 for _, c := range sortedClients(privChat.ClientConn) {
1497 tranNotifyChatChangeUser,
1499 NewField(fieldChatID, chatID),
1500 NewField(fieldUserName, *cc.UserName),
1501 NewField(fieldUserID, *cc.ID),
1502 NewField(fieldUserIconID, *cc.Icon),
1503 NewField(fieldUserFlags, *cc.Flags),
1508 privChat.ClientConn[cc.uint16ID()] = cc
1510 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1511 for _, c := range sortedClients(privChat.ClientConn) {
1516 Name: string(*c.UserName),
1519 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1522 res = append(res, cc.NewReply(t, replyFields...))
1526 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1527 // Fields used in the request:
1528 // * 114 fieldChatID
1529 // Reply is not expected.
1530 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1531 chatID := t.GetField(fieldChatID).Data
1532 chatInt := binary.BigEndian.Uint32(chatID)
1534 privChat := cc.Server.PrivateChats[chatInt]
1536 delete(privChat.ClientConn, cc.uint16ID())
1538 // Notify members of the private chat that the user has left
1539 for _, c := range sortedClients(privChat.ClientConn) {
1542 tranNotifyChatDeleteUser,
1544 NewField(fieldChatID, chatID),
1545 NewField(fieldUserID, *cc.ID),
1553 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1554 // Fields used in the request:
1556 // * 115 Chat subject Chat subject string
1557 // Reply is not expected.
1558 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1559 chatID := t.GetField(fieldChatID).Data
1560 chatInt := binary.BigEndian.Uint32(chatID)
1562 privChat := cc.Server.PrivateChats[chatInt]
1563 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1565 for _, c := range sortedClients(privChat.ClientConn) {
1568 tranNotifyChatSubject,
1570 NewField(fieldChatID, chatID),
1571 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),