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("\r*** %s %s", *cc.UserName, t.GetField(fieldData).Data)
306 if bytes.Equal(t.GetField(fieldData).Data, []byte("/stats")) {
307 formattedMsg = strings.Replace(cc.Server.Stats.String(), "\n", "\r", -1)
310 chatID := t.GetField(fieldChatID).Data
311 // a non-nil chatID indicates the message belongs to a private chat
313 chatInt := binary.BigEndian.Uint32(chatID)
314 privChat := cc.Server.PrivateChats[chatInt]
316 // send the message to all connected clients of the private chat
317 for _, c := range privChat.ClientConn {
318 res = append(res, *NewTransaction(
321 NewField(fieldChatID, chatID),
322 NewField(fieldData, []byte(formattedMsg)),
328 for _, c := range sortedClients(cc.Server.Clients) {
329 // Filter out clients that do not have the read chat permission
330 if authorize(c.Account.Access, accessReadChat) {
331 res = append(res, *NewTransaction(tranChatMsg, c.ID, NewField(fieldData, []byte(formattedMsg))))
338 // HandleSendInstantMsg sends instant message to the user on the current server.
339 // Fields used in the request:
342 // One of the following values:
343 // - User message (myOpt_UserMessage = 1)
344 // - Refuse message (myOpt_RefuseMessage = 2)
345 // - Refuse chat (myOpt_RefuseChat = 3)
346 // - Automatic response (myOpt_AutomaticResponse = 4)"
348 // 214 Quoting message Optional
350 //Fields used in the reply:
352 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
353 msg := t.GetField(fieldData)
354 ID := t.GetField(fieldUserID)
355 // TODO: Implement reply quoting
356 //options := transaction.GetField(hotline.fieldOptions)
362 NewField(fieldData, msg.Data),
363 NewField(fieldUserName, *cc.UserName),
364 NewField(fieldUserID, *cc.ID),
365 NewField(fieldOptions, []byte{0, 1}),
368 id, _ := byteToInt(ID.Data)
370 //keys := make([]uint16, 0, len(cc.Server.Clients))
371 //for k := range cc.Server.Clients {
372 // keys = append(keys, k)
375 otherClient := cc.Server.Clients[uint16(id)]
376 if otherClient == nil {
377 return res, errors.New("ohno")
380 // Respond with auto reply if other client has it enabled
381 if len(*otherClient.AutoReply) > 0 {
386 NewField(fieldData, *otherClient.AutoReply),
387 NewField(fieldUserName, *otherClient.UserName),
388 NewField(fieldUserID, *otherClient.ID),
389 NewField(fieldOptions, []byte{0, 1}),
394 res = append(res, cc.NewReply(t))
399 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
400 fileName := 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 account := cc.Server.Accounts[userLogin]
630 errorT := cc.NewErrReply(t, "Account does not exist.")
631 res = append(res, errorT)
635 res = append(res, cc.NewReply(t,
636 NewField(fieldUserName, []byte(account.Name)),
637 NewField(fieldUserLogin, negateString(t.GetField(fieldUserLogin).Data)),
638 NewField(fieldUserPassword, []byte(account.Password)),
639 NewField(fieldUserAccess, *account.Access),
644 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
645 var userFields []Field
646 // TODO: make order deterministic
647 for _, acc := range cc.Server.Accounts {
648 userField := acc.Payload()
649 userFields = append(userFields, NewField(fieldData, userField))
652 res = append(res, cc.NewReply(t, userFields...))
656 // HandleNewUser creates a new user account
657 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
658 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
660 // If the account already exists, reply with an error
661 // TODO: make order deterministic
662 if _, ok := cc.Server.Accounts[login]; ok {
663 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
667 if err := cc.Server.NewUser(
669 string(t.GetField(fieldUserName).Data),
670 string(t.GetField(fieldUserPassword).Data),
671 t.GetField(fieldUserAccess).Data,
673 return []Transaction{}, err
676 res = append(res, cc.NewReply(t))
680 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
681 // TODO: Handle case where account doesn't exist; e.g. delete race condition
682 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
684 if err := cc.Server.DeleteUser(login); err != nil {
688 res = append(res, cc.NewReply(t))
692 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
693 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
696 NewField(fieldData, t.GetField(tranGetMsgs).Data),
697 NewField(fieldChatOptions, []byte{0}),
700 res = append(res, cc.NewReply(t))
704 func byteToInt(bytes []byte) (int, error) {
707 return int(binary.BigEndian.Uint16(bytes)), nil
709 return int(binary.BigEndian.Uint32(bytes)), nil
712 return 0, errors.New("unknown byte length")
715 func HandleGetClientConnInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
716 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
718 clientConn := cc.Server.Clients[uint16(clientID)]
719 if clientConn == nil {
720 return res, errors.New("invalid client")
723 // TODO: Implement non-hardcoded values
724 template := `Nickname: %s
729 -------- File Downloads ---------
733 ------- Folder Downloads --------
737 --------- File Uploads ----------
741 -------- Folder Uploads ---------
745 ------- Waiting Downloads -------
751 activeDownloads := clientConn.Transfers[FileDownload]
752 activeDownloadList := "None."
753 for _, dl := range activeDownloads {
754 activeDownloadList += dl.String() + "\n"
757 template = fmt.Sprintf(
759 *clientConn.UserName,
760 clientConn.Account.Name,
761 clientConn.Account.Login,
762 clientConn.Connection.RemoteAddr().String(),
765 template = strings.Replace(template, "\n", "\r", -1)
767 res = append(res, cc.NewReply(t,
768 NewField(fieldData, []byte(template)),
769 NewField(fieldUserName, *clientConn.UserName),
774 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
775 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
780 func (cc *ClientConn) notifyNewUserHasJoined() (res []Transaction, err error) {
781 // Notify other ccs that a new user has connected
784 tranNotifyChangeUser, nil,
785 NewField(fieldUserName, *cc.UserName),
786 NewField(fieldUserID, *cc.ID),
787 NewField(fieldUserIconID, *cc.Icon),
788 NewField(fieldUserFlags, *cc.Flags),
795 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
796 bs := make([]byte, 2)
797 binary.BigEndian.PutUint16(bs, *cc.Server.NextGuestID)
799 *cc.UserName = t.GetField(fieldUserName).Data
801 *cc.Icon = t.GetField(fieldUserIconID).Data
803 options := t.GetField(fieldOptions).Data
804 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
806 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
808 // Check refuse private PM option
809 if optBitmap.Bit(refusePM) == 1 {
810 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
811 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
814 // Check refuse private chat option
815 if optBitmap.Bit(refuseChat) == 1 {
816 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
817 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
820 // Check auto response
821 if optBitmap.Bit(autoResponse) == 1 {
822 *cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
824 *cc.AutoReply = []byte{}
827 _, _ = cc.notifyNewUserHasJoined()
829 res = append(res, cc.NewReply(t))
834 const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
835 // "Mon, 02 Jan 2006 15:04:05 MST"
837 const defaultNewsTemplate = `From %s (%s):
841 __________________________________________________________`
843 // HandleTranOldPostNews updates the flat news
844 // Fields used in this request:
846 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
847 cc.Server.flatNewsMux.Lock()
848 defer cc.Server.flatNewsMux.Unlock()
850 newsDateTemplate := defaultNewsDateFormat
851 if cc.Server.Config.NewsDateFormat != "" {
852 newsDateTemplate = cc.Server.Config.NewsDateFormat
855 newsTemplate := defaultNewsTemplate
856 if cc.Server.Config.NewsDelimiter != "" {
857 newsTemplate = cc.Server.Config.NewsDelimiter
860 newsPost := fmt.Sprintf(newsTemplate+"\r", *cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
861 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
863 // update news in memory
864 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
866 // update news on disk
867 if err := ioutil.WriteFile(cc.Server.ConfigDir+"MessageBoard.txt", cc.Server.FlatNews, 0644); err != nil {
871 // Notify all clients of updated news
874 NewField(fieldData, []byte(newsPost)),
877 res = append(res, cc.NewReply(t))
881 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
882 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
884 if authorize(clientConn.Account.Access, accessCannotBeDiscon) {
885 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
889 if err := clientConn.Connection.Close(); err != nil {
893 res = append(res, cc.NewReply(t))
897 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
898 // Fields used in the request:
899 // 325 News path (Optional)
901 newsPath := t.GetField(fieldNewsPath).Data
902 cc.Server.Logger.Infow("NewsPath: ", "np", string(newsPath))
904 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
905 cats := cc.Server.GetNewsCatByPath(pathStrs)
907 // To store the keys in slice in sorted order
908 keys := make([]string, len(cats))
910 for k := range cats {
916 var fieldData []Field
917 for _, k := range keys {
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)
1242 fp := NewFilePath(t.GetField(fieldFilePath).Data)
1244 fullFilePath := fmt.Sprintf("./%v/%v", cc.Server.Config.FileRoot+fp.String(), string(fileTransfer.FileName))
1245 transferSize, err := CalcTotalSize(fullFilePath)
1249 itemCount, err := CalcItemCount(fullFilePath)
1253 res = append(res, cc.NewReply(t,
1254 NewField(fieldRefNum, transactionRef),
1255 NewField(fieldTransferSize, transferSize),
1256 NewField(fieldFolderItemCount, itemCount),
1257 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1262 // Upload all files from the local folder and its subfolders to the specified path on the server
1263 // Fields used in the request
1266 // 108 transfer size Total size of all items in the folder
1267 // 220 Folder item count
1268 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1269 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1270 transactionRef := cc.Server.NewTransactionRef()
1271 data := binary.BigEndian.Uint32(transactionRef)
1273 fileTransfer := &FileTransfer{
1274 FileName: t.GetField(fieldFileName).Data,
1275 FilePath: t.GetField(fieldFilePath).Data,
1276 ReferenceNumber: transactionRef,
1278 FolderItemCount: t.GetField(fieldFolderItemCount).Data,
1279 TransferSize: t.GetField(fieldTransferSize).Data,
1281 cc.Server.FileTransfers[data] = fileTransfer
1283 res = append(res, cc.NewReply(t, NewField(fieldRefNum, transactionRef)))
1287 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1288 fileName := t.GetField(fieldFileName).Data
1289 filePath := t.GetField(fieldFilePath).Data
1291 transactionRef := cc.Server.NewTransactionRef()
1292 data := binary.BigEndian.Uint32(transactionRef)
1294 fileTransfer := &FileTransfer{
1297 ReferenceNumber: transactionRef,
1301 cc.Server.FileTransfers[data] = fileTransfer
1303 res = append(res, cc.NewReply(t, NewField(fieldRefNum, transactionRef)))
1314 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1316 if len(t.GetField(fieldUserIconID).Data) == 4 {
1317 icon = t.GetField(fieldUserIconID).Data[2:]
1319 icon = t.GetField(fieldUserIconID).Data
1322 *cc.UserName = t.GetField(fieldUserName).Data
1324 // the options field is only passed by the client versions > 1.2.3.
1325 options := t.GetField(fieldOptions).Data
1328 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1329 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
1331 // Check refuse private PM option
1332 if optBitmap.Bit(refusePM) == 1 {
1333 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
1334 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
1337 // Check refuse private chat option
1338 if optBitmap.Bit(refuseChat) == 1 {
1339 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
1340 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
1343 // Check auto response
1344 if optBitmap.Bit(autoResponse) == 1 {
1345 *cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
1347 *cc.AutoReply = []byte{}
1351 // Notify all clients of updated user info
1353 tranNotifyChangeUser,
1354 NewField(fieldUserID, *cc.ID),
1355 NewField(fieldUserIconID, *cc.Icon),
1356 NewField(fieldUserFlags, *cc.Flags),
1357 NewField(fieldUserName, *cc.UserName),
1363 // HandleKeepAlive response to keepalive transactions with an empty reply
1364 // HL 1.9.2 Client sends keepalive msg every 3 minutes
1365 // HL 1.2.3 Client doesn't send keepalives
1366 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1367 res = append(res, cc.NewReply(t))
1372 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1373 filePath := cc.Server.Config.FileRoot
1375 path := t.GetField(fieldFilePath).Data
1377 filePath = cc.Server.Config.FileRoot + ReadFilePath(path)
1380 fileNames, err := getFileNameList(filePath)
1385 res = append(res, cc.NewReply(t, fileNames...))
1390 // =================================
1391 // Hotline private chat flow
1392 // =================================
1393 // 1. ClientA sends tranInviteNewChat to server with user ID to invite
1394 // 2. Server creates new ChatID
1395 // 3. Server sends tranInviteToChat to invitee
1396 // 4. Server replies to ClientA with new Chat ID
1398 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1399 // If Accepted is clicked:
1400 // 1. ClientB sends tranJoinChat with fieldChatID
1402 // HandleInviteNewChat invites users to new private chat
1403 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1405 targetID := t.GetField(fieldUserID).Data
1406 newChatID := cc.Server.NewPrivateChat(cc)
1412 NewField(fieldChatID, newChatID),
1413 NewField(fieldUserName, *cc.UserName),
1414 NewField(fieldUserID, *cc.ID),
1420 NewField(fieldChatID, newChatID),
1421 NewField(fieldUserName, *cc.UserName),
1422 NewField(fieldUserID, *cc.ID),
1423 NewField(fieldUserIconID, *cc.Icon),
1424 NewField(fieldUserFlags, *cc.Flags),
1431 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1433 targetID := t.GetField(fieldUserID).Data
1434 chatID := t.GetField(fieldChatID).Data
1440 NewField(fieldChatID, chatID),
1441 NewField(fieldUserName, *cc.UserName),
1442 NewField(fieldUserID, *cc.ID),
1448 NewField(fieldChatID, chatID),
1449 NewField(fieldUserName, *cc.UserName),
1450 NewField(fieldUserID, *cc.ID),
1451 NewField(fieldUserIconID, *cc.Icon),
1452 NewField(fieldUserFlags, *cc.Flags),
1459 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1460 chatID := t.GetField(fieldChatID).Data
1461 chatInt := binary.BigEndian.Uint32(chatID)
1463 privChat := cc.Server.PrivateChats[chatInt]
1465 resMsg := append(*cc.UserName, []byte(" declined invitation to chat")...)
1467 for _, c := range sortedClients(privChat.ClientConn) {
1472 NewField(fieldChatID, chatID),
1473 NewField(fieldData, resMsg),
1481 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1482 // Fields used in the reply:
1483 // * 115 Chat subject
1484 // * 300 User name with info (Optional)
1485 // * 300 (more user names with info)
1486 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1487 chatID := t.GetField(fieldChatID).Data
1488 chatInt := binary.BigEndian.Uint32(chatID)
1490 privChat := cc.Server.PrivateChats[chatInt]
1492 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1493 for _, c := range sortedClients(privChat.ClientConn) {
1496 tranNotifyChatChangeUser,
1498 NewField(fieldChatID, chatID),
1499 NewField(fieldUserName, *cc.UserName),
1500 NewField(fieldUserID, *cc.ID),
1501 NewField(fieldUserIconID, *cc.Icon),
1502 NewField(fieldUserFlags, *cc.Flags),
1507 privChat.ClientConn[cc.uint16ID()] = cc
1509 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1510 for _, c := range sortedClients(privChat.ClientConn) {
1515 Name: string(*c.UserName),
1518 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1521 res = append(res, cc.NewReply(t, replyFields...))
1525 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1526 // Fields used in the request:
1527 // * 114 fieldChatID
1528 // Reply is not expected.
1529 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1530 chatID := t.GetField(fieldChatID).Data
1531 chatInt := binary.BigEndian.Uint32(chatID)
1533 privChat := cc.Server.PrivateChats[chatInt]
1535 delete(privChat.ClientConn, cc.uint16ID())
1537 // Notify members of the private chat that the user has left
1538 for _, c := range sortedClients(privChat.ClientConn) {
1541 tranNotifyChatDeleteUser,
1543 NewField(fieldChatID, chatID),
1544 NewField(fieldUserID, *cc.ID),
1552 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1553 // Fields used in the request:
1555 // * 115 Chat subject Chat subject string
1556 // Reply is not expected.
1557 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1558 chatID := t.GetField(fieldChatID).Data
1559 chatInt := binary.BigEndian.Uint32(chatID)
1561 privChat := cc.Server.PrivateChats[chatInt]
1562 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1564 for _, c := range sortedClients(privChat.ClientConn) {
1567 tranNotifyChatSubject,
1569 NewField(fieldChatID, chatID),
1570 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),