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,
260 Access: accessAlwaysAllow,
261 Name: "tranMakeFileAlias",
262 Handler: HandleMakeAlias,
263 RequiredFields: []requiredField{
264 {ID: fieldFileName, minLen: 1},
265 {ID: fieldFilePath, minLen: 1},
266 {ID: fieldFileNewPath, minLen: 1},
269 tranSetClientUserInfo: {
270 Access: accessAlwaysAllow,
271 Name: "tranSetClientUserInfo",
272 Handler: HandleSetClientUserInfo,
275 Access: accessAlwaysAllow, // granular access is in the handler
276 Name: "tranSetFileInfo",
277 Handler: HandleSetFileInfo,
280 Access: accessModifyUser,
281 DenyMsg: "You are not allowed to modify accounts.",
283 Handler: HandleSetUser,
286 Access: accessAlwaysAllow,
287 DenyMsg: "You are not allowed to upload files.",
288 Name: "tranUploadFile",
289 Handler: HandleUploadFile,
292 Access: accessAlwaysAllow, // TODO: what should this be?
293 Name: "tranUploadFldr",
294 Handler: HandleUploadFolder,
297 Access: accessBroadcast,
298 DenyMsg: "You are not allowed to send broadcast messages.",
299 Name: "tranUserBroadcast",
300 Handler: HandleUserBroadcast,
304 func HandleChatSend(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
305 // Truncate long usernames
306 trunc := fmt.Sprintf("%13s", cc.UserName)
307 formattedMsg := fmt.Sprintf("\r%.14s: %s", trunc, t.GetField(fieldData).Data)
309 // By holding the option key, Hotline chat allows users to send /me formatted messages like:
310 // *** Halcyon does stuff
311 // This is indicated by the presence of the optional field fieldChatOptions in the transaction payload
312 if t.GetField(fieldChatOptions).Data != nil {
313 formattedMsg = fmt.Sprintf("\r*** %s %s", cc.UserName, t.GetField(fieldData).Data)
316 if bytes.Equal(t.GetField(fieldData).Data, []byte("/stats")) {
317 formattedMsg = strings.Replace(cc.Server.Stats.String(), "\n", "\r", -1)
320 chatID := t.GetField(fieldChatID).Data
321 // a non-nil chatID indicates the message belongs to a private chat
323 chatInt := binary.BigEndian.Uint32(chatID)
324 privChat := cc.Server.PrivateChats[chatInt]
326 // send the message to all connected clients of the private chat
327 for _, c := range privChat.ClientConn {
328 res = append(res, *NewTransaction(
331 NewField(fieldChatID, chatID),
332 NewField(fieldData, []byte(formattedMsg)),
338 for _, c := range sortedClients(cc.Server.Clients) {
339 // Filter out clients that do not have the read chat permission
340 if authorize(c.Account.Access, accessReadChat) {
341 res = append(res, *NewTransaction(tranChatMsg, c.ID, NewField(fieldData, []byte(formattedMsg))))
348 // HandleSendInstantMsg sends instant message to the user on the current server.
349 // Fields used in the request:
352 // One of the following values:
353 // - User message (myOpt_UserMessage = 1)
354 // - Refuse message (myOpt_RefuseMessage = 2)
355 // - Refuse chat (myOpt_RefuseChat = 3)
356 // - Automatic response (myOpt_AutomaticResponse = 4)"
358 // 214 Quoting message Optional
360 //Fields used in the reply:
362 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
363 msg := t.GetField(fieldData)
364 ID := t.GetField(fieldUserID)
365 // TODO: Implement reply quoting
366 //options := transaction.GetField(hotline.fieldOptions)
372 NewField(fieldData, msg.Data),
373 NewField(fieldUserName, cc.UserName),
374 NewField(fieldUserID, *cc.ID),
375 NewField(fieldOptions, []byte{0, 1}),
378 id, _ := byteToInt(ID.Data)
380 //keys := make([]uint16, 0, len(cc.Server.Clients))
381 //for k := range cc.Server.Clients {
382 // keys = append(keys, k)
385 otherClient := cc.Server.Clients[uint16(id)]
386 if otherClient == nil {
387 return res, errors.New("ohno")
390 // Respond with auto reply if other client has it enabled
391 if len(*otherClient.AutoReply) > 0 {
396 NewField(fieldData, *otherClient.AutoReply),
397 NewField(fieldUserName, otherClient.UserName),
398 NewField(fieldUserID, *otherClient.ID),
399 NewField(fieldOptions, []byte{0, 1}),
404 res = append(res, cc.NewReply(t))
409 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
410 fileName := t.GetField(fieldFileName).Data
411 filePath := t.GetField(fieldFilePath).Data
413 ffo, err := NewFlattenedFileObject(cc.Server.Config.FileRoot, filePath, fileName)
418 res = append(res, cc.NewReply(t,
419 NewField(fieldFileName, fileName),
420 NewField(fieldFileTypeString, ffo.FlatFileInformationFork.TypeSignature),
421 NewField(fieldFileCreatorString, ffo.FlatFileInformationFork.CreatorSignature),
422 NewField(fieldFileComment, ffo.FlatFileInformationFork.Comment),
423 NewField(fieldFileType, ffo.FlatFileInformationFork.TypeSignature),
424 NewField(fieldFileCreateDate, ffo.FlatFileInformationFork.CreateDate),
425 NewField(fieldFileModifyDate, ffo.FlatFileInformationFork.ModifyDate),
426 NewField(fieldFileSize, ffo.FlatFileDataForkHeader.DataSize),
431 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
432 // TODO: Implement support for comments
433 // Fields used in the request:
435 // * 202 File path Optional
436 // * 211 File new name Optional
437 // * 210 File comment Optional
438 // Fields used in the reply: None
439 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
440 fileName := t.GetField(fieldFileName).Data
441 filePath := t.GetField(fieldFilePath).Data
443 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
448 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, t.GetField(fieldFileNewName).Data)
453 //fileComment := t.GetField(fieldFileComment).Data
454 fileNewName := t.GetField(fieldFileNewName).Data
456 if fileNewName != nil {
457 fi, err := FS.Stat(fullFilePath)
461 switch mode := fi.Mode(); {
463 if !authorize(cc.Account.Access, accessRenameFolder) {
464 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
467 case mode.IsRegular():
468 if !authorize(cc.Account.Access, accessRenameFile) {
469 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
474 err = os.Rename(fullFilePath, fullNewFilePath)
475 if os.IsNotExist(err) {
476 res = append(res, cc.NewErrReply(t, "Cannot rename file "+string(fileName)+" because it does not exist or cannot be found."))
481 res = append(res, cc.NewReply(t))
485 // HandleDeleteFile deletes a file or folder
486 // Fields used in the request:
489 // Fields used in the reply: none
490 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
491 fileName := t.GetField(fieldFileName).Data
492 filePath := t.GetField(fieldFilePath).Data
494 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
499 cc.Server.Logger.Debugw("Delete file", "src", fullFilePath)
501 fi, err := os.Stat(fullFilePath)
503 res = append(res, cc.NewErrReply(t, "Cannot delete file "+string(fileName)+" because it does not exist or cannot be found."))
506 switch mode := fi.Mode(); {
508 if !authorize(cc.Account.Access, accessDeleteFolder) {
509 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
512 case mode.IsRegular():
513 if !authorize(cc.Account.Access, accessDeleteFile) {
514 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
519 if err := os.RemoveAll(fullFilePath); err != nil {
523 res = append(res, cc.NewReply(t))
527 // HandleMoveFile moves files or folders. Note: seemingly not documented
528 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
529 fileName := string(t.GetField(fieldFileName).Data)
530 filePath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
531 fileNewPath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFileNewPath).Data)
533 cc.Server.Logger.Debugw("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
535 path := filePath + "/" + fileName
536 fi, err := os.Stat(path)
540 switch mode := fi.Mode(); {
542 if !authorize(cc.Account.Access, accessMoveFolder) {
543 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
546 case mode.IsRegular():
547 if !authorize(cc.Account.Access, accessMoveFile) {
548 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
553 err = os.Rename(filePath+"/"+fileName, fileNewPath+"/"+fileName)
554 if os.IsNotExist(err) {
555 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
559 return []Transaction{}, err
561 // TODO: handle other possible errors; e.g. file delete fails due to file permission issue
563 res = append(res, cc.NewReply(t))
567 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
568 newFolderPath := cc.Server.Config.FileRoot
569 folderName := string(t.GetField(fieldFileName).Data)
571 folderName = path.Join("/", folderName)
573 // fieldFilePath is only present for nested paths
574 if t.GetField(fieldFilePath).Data != nil {
576 err := newFp.UnmarshalBinary(t.GetField(fieldFilePath).Data)
580 newFolderPath += newFp.String()
582 newFolderPath = path.Join(newFolderPath, folderName)
584 // TODO: check path and folder name lengths
586 if _, err := FS.Stat(newFolderPath); !os.IsNotExist(err) {
587 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that name.", folderName)
588 return []Transaction{cc.NewErrReply(t, msg)}, nil
591 // TODO: check for disallowed characters to maintain compatibility for original client
593 if err := FS.Mkdir(newFolderPath, 0777); err != nil {
594 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
595 return []Transaction{cc.NewErrReply(t, msg)}, nil
598 res = append(res, cc.NewReply(t))
602 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
603 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
604 userName := string(t.GetField(fieldUserName).Data)
606 newAccessLvl := t.GetField(fieldUserAccess).Data
608 account := cc.Server.Accounts[login]
609 account.Access = &newAccessLvl
610 account.Name = userName
612 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
613 // not include fieldUserPassword
614 if t.GetField(fieldUserPassword).Data == nil {
615 account.Password = hashAndSalt([]byte(""))
617 if len(t.GetField(fieldUserPassword).Data) > 1 {
618 account.Password = hashAndSalt(t.GetField(fieldUserPassword).Data)
621 file := cc.Server.ConfigDir + "Users/" + login + ".yaml"
622 out, err := yaml.Marshal(&account)
626 if err := ioutil.WriteFile(file, out, 0666); err != nil {
630 // Notify connected clients logged in as the user of the new access level
631 for _, c := range cc.Server.Clients {
632 if c.Account.Login == login {
633 // Note: comment out these two lines to test server-side deny messages
634 newT := NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, newAccessLvl))
635 res = append(res, *newT)
637 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
638 if authorize(c.Account.Access, accessDisconUser) {
639 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 1)
641 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 0)
643 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
645 c.Account.Access = account.Access
648 tranNotifyChangeUser,
649 NewField(fieldUserID, *c.ID),
650 NewField(fieldUserFlags, *c.Flags),
651 NewField(fieldUserName, c.UserName),
652 NewField(fieldUserIconID, *c.Icon),
657 // TODO: If we have just promoted a connected user to admin, notify
658 // connected clients to turn the user red
660 res = append(res, cc.NewReply(t))
664 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
665 userLogin := string(t.GetField(fieldUserLogin).Data)
666 account := cc.Server.Accounts[userLogin]
668 errorT := cc.NewErrReply(t, "Account does not exist.")
669 res = append(res, errorT)
673 res = append(res, cc.NewReply(t,
674 NewField(fieldUserName, []byte(account.Name)),
675 NewField(fieldUserLogin, negateString(t.GetField(fieldUserLogin).Data)),
676 NewField(fieldUserPassword, []byte(account.Password)),
677 NewField(fieldUserAccess, *account.Access),
682 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
683 var userFields []Field
684 // TODO: make order deterministic
685 for _, acc := range cc.Server.Accounts {
686 userField := acc.MarshalBinary()
687 userFields = append(userFields, NewField(fieldData, userField))
690 res = append(res, cc.NewReply(t, userFields...))
694 // HandleNewUser creates a new user account
695 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
696 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
698 // If the account already exists, reply with an error
699 // TODO: make order deterministic
700 if _, ok := cc.Server.Accounts[login]; ok {
701 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
705 if err := cc.Server.NewUser(
707 string(t.GetField(fieldUserName).Data),
708 string(t.GetField(fieldUserPassword).Data),
709 t.GetField(fieldUserAccess).Data,
711 return []Transaction{}, err
714 res = append(res, cc.NewReply(t))
718 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
719 // TODO: Handle case where account doesn't exist; e.g. delete race condition
720 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
722 if err := cc.Server.DeleteUser(login); err != nil {
726 res = append(res, cc.NewReply(t))
730 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
731 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
734 NewField(fieldData, t.GetField(tranGetMsgs).Data),
735 NewField(fieldChatOptions, []byte{0}),
738 res = append(res, cc.NewReply(t))
742 func byteToInt(bytes []byte) (int, error) {
745 return int(binary.BigEndian.Uint16(bytes)), nil
747 return int(binary.BigEndian.Uint32(bytes)), nil
750 return 0, errors.New("unknown byte length")
753 func HandleGetClientConnInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
754 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
756 clientConn := cc.Server.Clients[uint16(clientID)]
757 if clientConn == nil {
758 return res, errors.New("invalid client")
761 // TODO: Implement non-hardcoded values
762 template := `Nickname: %s
767 -------- File Downloads ---------
771 ------- Folder Downloads --------
775 --------- File Uploads ----------
779 -------- Folder Uploads ---------
783 ------- Waiting Downloads -------
789 activeDownloads := clientConn.Transfers[FileDownload]
790 activeDownloadList := "None."
791 for _, dl := range activeDownloads {
792 activeDownloadList += dl.String() + "\n"
795 template = fmt.Sprintf(
798 clientConn.Account.Name,
799 clientConn.Account.Login,
800 clientConn.Connection.RemoteAddr().String(),
803 template = strings.Replace(template, "\n", "\r", -1)
805 res = append(res, cc.NewReply(t,
806 NewField(fieldData, []byte(template)),
807 NewField(fieldUserName, clientConn.UserName),
812 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
813 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
818 func (cc *ClientConn) notifyNewUserHasJoined() (res []Transaction, err error) {
819 // Notify other ccs that a new user has connected
822 tranNotifyChangeUser, nil,
823 NewField(fieldUserName, cc.UserName),
824 NewField(fieldUserID, *cc.ID),
825 NewField(fieldUserIconID, *cc.Icon),
826 NewField(fieldUserFlags, *cc.Flags),
833 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
835 cc.UserName = t.GetField(fieldUserName).Data
836 *cc.Icon = t.GetField(fieldUserIconID).Data
838 options := t.GetField(fieldOptions).Data
839 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
841 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
843 // Check refuse private PM option
844 if optBitmap.Bit(refusePM) == 1 {
845 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
846 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
849 // Check refuse private chat option
850 if optBitmap.Bit(refuseChat) == 1 {
851 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
852 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
855 // Check auto response
856 if optBitmap.Bit(autoResponse) == 1 {
857 *cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
859 *cc.AutoReply = []byte{}
862 _, _ = cc.notifyNewUserHasJoined()
864 res = append(res, cc.NewReply(t))
869 const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
870 // "Mon, 02 Jan 2006 15:04:05 MST"
872 const defaultNewsTemplate = `From %s (%s):
876 __________________________________________________________`
878 // HandleTranOldPostNews updates the flat news
879 // Fields used in this request:
881 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
882 cc.Server.flatNewsMux.Lock()
883 defer cc.Server.flatNewsMux.Unlock()
885 newsDateTemplate := defaultNewsDateFormat
886 if cc.Server.Config.NewsDateFormat != "" {
887 newsDateTemplate = cc.Server.Config.NewsDateFormat
890 newsTemplate := defaultNewsTemplate
891 if cc.Server.Config.NewsDelimiter != "" {
892 newsTemplate = cc.Server.Config.NewsDelimiter
895 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
896 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
898 // update news in memory
899 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
901 // update news on disk
902 if err := ioutil.WriteFile(cc.Server.ConfigDir+"MessageBoard.txt", cc.Server.FlatNews, 0644); err != nil {
906 // Notify all clients of updated news
909 NewField(fieldData, []byte(newsPost)),
912 res = append(res, cc.NewReply(t))
916 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
917 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
919 if authorize(clientConn.Account.Access, accessCannotBeDiscon) {
920 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
924 if err := clientConn.Connection.Close(); err != nil {
928 res = append(res, cc.NewReply(t))
932 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
933 // Fields used in the request:
934 // 325 News path (Optional)
936 newsPath := t.GetField(fieldNewsPath).Data
937 cc.Server.Logger.Infow("NewsPath: ", "np", string(newsPath))
939 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
940 cats := cc.Server.GetNewsCatByPath(pathStrs)
942 // To store the keys in slice in sorted order
943 keys := make([]string, len(cats))
945 for k := range cats {
951 var fieldData []Field
952 for _, k := range keys {
954 b, _ := cat.MarshalBinary()
955 fieldData = append(fieldData, NewField(
956 fieldNewsCatListData15,
961 res = append(res, cc.NewReply(t, fieldData...))
965 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
966 name := string(t.GetField(fieldNewsCatName).Data)
967 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
969 cats := cc.Server.GetNewsCatByPath(pathStrs)
970 cats[name] = NewsCategoryListData15{
973 Articles: map[uint32]*NewsArtData{},
974 SubCats: make(map[string]NewsCategoryListData15),
977 if err := cc.Server.writeThreadedNews(); err != nil {
980 res = append(res, cc.NewReply(t))
984 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
985 // Fields used in the request:
986 // 322 News category name
988 name := string(t.GetField(fieldFileName).Data)
989 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
991 cc.Server.Logger.Infof("Creating new news folder %s", name)
993 cats := cc.Server.GetNewsCatByPath(pathStrs)
994 cats[name] = NewsCategoryListData15{
997 Articles: map[uint32]*NewsArtData{},
998 SubCats: make(map[string]NewsCategoryListData15),
1000 if err := cc.Server.writeThreadedNews(); err != nil {
1003 res = append(res, cc.NewReply(t))
1007 // Fields used in the request:
1008 // 325 News path Optional
1011 // 321 News article list data Optional
1012 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1013 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1015 var cat NewsCategoryListData15
1016 cats := cc.Server.ThreadedNews.Categories
1018 for _, path := range pathStrs {
1020 cats = cats[path].SubCats
1023 nald := cat.GetNewsArtListData()
1025 res = append(res, cc.NewReply(t, NewField(fieldNewsArtListData, nald.Payload())))
1029 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1032 // 326 News article ID
1033 // 327 News article data flavor
1035 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1037 var cat NewsCategoryListData15
1038 cats := cc.Server.ThreadedNews.Categories
1040 for _, path := range pathStrs {
1042 cats = cats[path].SubCats
1044 newsArtID := t.GetField(fieldNewsArtID).Data
1046 convertedArtID := binary.BigEndian.Uint16(newsArtID)
1048 art := cat.Articles[uint32(convertedArtID)]
1050 res = append(res, cc.NewReply(t))
1055 // 328 News article title
1056 // 329 News article poster
1057 // 330 News article date
1058 // 331 Previous article ID
1059 // 332 Next article ID
1060 // 335 Parent article ID
1061 // 336 First child article ID
1062 // 327 News article data flavor "Should be “text/plain”
1063 // 333 News article data Optional (if data flavor is “text/plain”)
1065 res = append(res, cc.NewReply(t,
1066 NewField(fieldNewsArtTitle, []byte(art.Title)),
1067 NewField(fieldNewsArtPoster, []byte(art.Poster)),
1068 NewField(fieldNewsArtDate, art.Date),
1069 NewField(fieldNewsArtPrevArt, art.PrevArt),
1070 NewField(fieldNewsArtNextArt, art.NextArt),
1071 NewField(fieldNewsArtParentArt, art.ParentArt),
1072 NewField(fieldNewsArt1stChildArt, art.FirstChildArt),
1073 NewField(fieldNewsArtDataFlav, []byte("text/plain")),
1074 NewField(fieldNewsArtData, []byte(art.Data)),
1079 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1080 // Access: News Delete Folder (37) or News Delete Category (35)
1082 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1084 // TODO: determine if path is a Folder (Bundle) or Category and check for permission
1086 cc.Server.Logger.Infof("DelNewsItem %v", pathStrs)
1088 cats := cc.Server.ThreadedNews.Categories
1090 delName := pathStrs[len(pathStrs)-1]
1091 if len(pathStrs) > 1 {
1092 for _, path := range pathStrs[0 : len(pathStrs)-1] {
1093 cats = cats[path].SubCats
1097 delete(cats, delName)
1099 err = cc.Server.writeThreadedNews()
1104 // Reply params: none
1105 res = append(res, cc.NewReply(t))
1110 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1113 // 326 News article ID
1114 // 337 News article – recursive delete Delete child articles (1) or not (0)
1115 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1116 ID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1118 // TODO: Delete recursive
1119 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1121 catName := pathStrs[len(pathStrs)-1]
1122 cat := cats[catName]
1124 delete(cat.Articles, uint32(ID))
1127 if err := cc.Server.writeThreadedNews(); err != nil {
1131 res = append(res, cc.NewReply(t))
1135 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1138 // 326 News article ID ID of the parent article?
1139 // 328 News article title
1140 // 334 News article flags
1141 // 327 News article data flavor Currently “text/plain”
1142 // 333 News article data
1144 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1145 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1147 catName := pathStrs[len(pathStrs)-1]
1148 cat := cats[catName]
1150 newArt := NewsArtData{
1151 Title: string(t.GetField(fieldNewsArtTitle).Data),
1152 Poster: string(cc.UserName),
1153 Date: toHotlineTime(time.Now()),
1154 PrevArt: []byte{0, 0, 0, 0},
1155 NextArt: []byte{0, 0, 0, 0},
1156 ParentArt: append([]byte{0, 0}, t.GetField(fieldNewsArtID).Data...),
1157 FirstChildArt: []byte{0, 0, 0, 0},
1158 DataFlav: []byte("text/plain"),
1159 Data: string(t.GetField(fieldNewsArtData).Data),
1163 for k := range cat.Articles {
1164 keys = append(keys, int(k))
1170 prevID := uint32(keys[len(keys)-1])
1173 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1175 // Set next article ID
1176 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1179 // Update parent article with first child reply
1180 parentID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1182 parentArt := cat.Articles[uint32(parentID)]
1184 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1185 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1189 cat.Articles[nextID] = &newArt
1192 if err := cc.Server.writeThreadedNews(); err != nil {
1196 res = append(res, cc.NewReply(t))
1200 // HandleGetMsgs returns the flat news data
1201 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1202 res = append(res, cc.NewReply(t, NewField(fieldData, cc.Server.FlatNews)))
1207 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1208 fileName := t.GetField(fieldFileName).Data
1209 filePath := t.GetField(fieldFilePath).Data
1212 err = fp.UnmarshalBinary(filePath)
1217 ffo, err := NewFlattenedFileObject(cc.Server.Config.FileRoot, filePath, fileName)
1222 transactionRef := cc.Server.NewTransactionRef()
1223 data := binary.BigEndian.Uint32(transactionRef)
1225 ft := &FileTransfer{
1228 ReferenceNumber: transactionRef,
1232 cc.Server.FileTransfers[data] = ft
1233 cc.Transfers[FileDownload] = append(cc.Transfers[FileDownload], ft)
1235 res = append(res, cc.NewReply(t,
1236 NewField(fieldRefNum, transactionRef),
1237 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1238 NewField(fieldTransferSize, ffo.TransferSize()),
1239 NewField(fieldFileSize, ffo.FlatFileDataForkHeader.DataSize),
1245 // Download all files from the specified folder and sub-folders
1258 // 00 6c // transfer size
1262 // 00 dc // field Folder item count
1266 // 00 6b // ref number
1269 func HandleDownloadFolder(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,
1277 Type: FolderDownload,
1279 cc.Server.FileTransfers[data] = fileTransfer
1280 cc.Transfers[FolderDownload] = append(cc.Transfers[FolderDownload], fileTransfer)
1283 err = fp.UnmarshalBinary(t.GetField(fieldFilePath).Data)
1288 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
1290 transferSize, err := CalcTotalSize(fullFilePath)
1294 itemCount, err := CalcItemCount(fullFilePath)
1298 res = append(res, cc.NewReply(t,
1299 NewField(fieldRefNum, transactionRef),
1300 NewField(fieldTransferSize, transferSize),
1301 NewField(fieldFolderItemCount, itemCount),
1302 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1307 // Upload all files from the local folder and its subfolders to the specified path on the server
1308 // Fields used in the request
1311 // 108 transfer size Total size of all items in the folder
1312 // 220 Folder item count
1313 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1314 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1315 transactionRef := cc.Server.NewTransactionRef()
1316 data := binary.BigEndian.Uint32(transactionRef)
1318 fileTransfer := &FileTransfer{
1319 FileName: t.GetField(fieldFileName).Data,
1320 FilePath: t.GetField(fieldFilePath).Data,
1321 ReferenceNumber: transactionRef,
1323 FolderItemCount: t.GetField(fieldFolderItemCount).Data,
1324 TransferSize: t.GetField(fieldTransferSize).Data,
1326 cc.Server.FileTransfers[data] = fileTransfer
1328 res = append(res, cc.NewReply(t, NewField(fieldRefNum, transactionRef)))
1332 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1333 // TODO: add permission handing for upload folders and drop boxes
1334 if !authorize(cc.Account.Access, accessUploadFile) {
1335 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1339 fileName := t.GetField(fieldFileName).Data
1340 filePath := t.GetField(fieldFilePath).Data
1342 transactionRef := cc.Server.NewTransactionRef()
1343 data := binary.BigEndian.Uint32(transactionRef)
1345 cc.Server.FileTransfers[data] = &FileTransfer{
1348 ReferenceNumber: transactionRef,
1352 res = append(res, cc.NewReply(t, NewField(fieldRefNum, transactionRef)))
1363 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1365 if len(t.GetField(fieldUserIconID).Data) == 4 {
1366 icon = t.GetField(fieldUserIconID).Data[2:]
1368 icon = t.GetField(fieldUserIconID).Data
1371 cc.UserName = t.GetField(fieldUserName).Data
1373 // the options field is only passed by the client versions > 1.2.3.
1374 options := t.GetField(fieldOptions).Data
1377 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1378 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
1380 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, optBitmap.Bit(refusePM))
1381 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
1383 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, optBitmap.Bit(refuseChat))
1384 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
1386 // Check auto response
1387 if optBitmap.Bit(autoResponse) == 1 {
1388 *cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
1390 *cc.AutoReply = []byte{}
1394 // Notify all clients of updated user info
1396 tranNotifyChangeUser,
1397 NewField(fieldUserID, *cc.ID),
1398 NewField(fieldUserIconID, *cc.Icon),
1399 NewField(fieldUserFlags, *cc.Flags),
1400 NewField(fieldUserName, cc.UserName),
1406 // HandleKeepAlive responds to keepalive transactions with an empty reply
1407 // * HL 1.9.2 Client sends keepalive msg every 3 minutes
1408 // * HL 1.2.3 Client doesn't send keepalives
1409 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1410 res = append(res, cc.NewReply(t))
1415 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1416 fullPath, err := readPath(
1417 cc.Server.Config.FileRoot,
1418 t.GetField(fieldFilePath).Data,
1425 fileNames, err := getFileNameList(fullPath)
1430 res = append(res, cc.NewReply(t, fileNames...))
1435 // =================================
1436 // Hotline private chat flow
1437 // =================================
1438 // 1. ClientA sends tranInviteNewChat to server with user ID to invite
1439 // 2. Server creates new ChatID
1440 // 3. Server sends tranInviteToChat to invitee
1441 // 4. Server replies to ClientA with new Chat ID
1443 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1444 // If Accepted is clicked:
1445 // 1. ClientB sends tranJoinChat with fieldChatID
1447 // HandleInviteNewChat invites users to new private chat
1448 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1450 targetID := t.GetField(fieldUserID).Data
1451 newChatID := cc.Server.NewPrivateChat(cc)
1457 NewField(fieldChatID, newChatID),
1458 NewField(fieldUserName, cc.UserName),
1459 NewField(fieldUserID, *cc.ID),
1465 NewField(fieldChatID, newChatID),
1466 NewField(fieldUserName, cc.UserName),
1467 NewField(fieldUserID, *cc.ID),
1468 NewField(fieldUserIconID, *cc.Icon),
1469 NewField(fieldUserFlags, *cc.Flags),
1476 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1478 targetID := t.GetField(fieldUserID).Data
1479 chatID := t.GetField(fieldChatID).Data
1485 NewField(fieldChatID, chatID),
1486 NewField(fieldUserName, cc.UserName),
1487 NewField(fieldUserID, *cc.ID),
1493 NewField(fieldChatID, chatID),
1494 NewField(fieldUserName, cc.UserName),
1495 NewField(fieldUserID, *cc.ID),
1496 NewField(fieldUserIconID, *cc.Icon),
1497 NewField(fieldUserFlags, *cc.Flags),
1504 func HandleRejectChatInvite(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 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1512 for _, c := range sortedClients(privChat.ClientConn) {
1517 NewField(fieldChatID, chatID),
1518 NewField(fieldData, resMsg),
1526 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1527 // Fields used in the reply:
1528 // * 115 Chat subject
1529 // * 300 User name with info (Optional)
1530 // * 300 (more user names with info)
1531 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1532 chatID := t.GetField(fieldChatID).Data
1533 chatInt := binary.BigEndian.Uint32(chatID)
1535 privChat := cc.Server.PrivateChats[chatInt]
1537 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1538 for _, c := range sortedClients(privChat.ClientConn) {
1541 tranNotifyChatChangeUser,
1543 NewField(fieldChatID, chatID),
1544 NewField(fieldUserName, cc.UserName),
1545 NewField(fieldUserID, *cc.ID),
1546 NewField(fieldUserIconID, *cc.Icon),
1547 NewField(fieldUserFlags, *cc.Flags),
1552 privChat.ClientConn[cc.uint16ID()] = cc
1554 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1555 for _, c := range sortedClients(privChat.ClientConn) {
1560 Name: string(c.UserName),
1563 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1566 res = append(res, cc.NewReply(t, replyFields...))
1570 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1571 // Fields used in the request:
1572 // * 114 fieldChatID
1573 // Reply is not expected.
1574 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1575 chatID := t.GetField(fieldChatID).Data
1576 chatInt := binary.BigEndian.Uint32(chatID)
1578 privChat := cc.Server.PrivateChats[chatInt]
1580 delete(privChat.ClientConn, cc.uint16ID())
1582 // Notify members of the private chat that the user has left
1583 for _, c := range sortedClients(privChat.ClientConn) {
1586 tranNotifyChatDeleteUser,
1588 NewField(fieldChatID, chatID),
1589 NewField(fieldUserID, *cc.ID),
1597 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1598 // Fields used in the request:
1600 // * 115 Chat subject Chat subject string
1601 // Reply is not expected.
1602 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1603 chatID := t.GetField(fieldChatID).Data
1604 chatInt := binary.BigEndian.Uint32(chatID)
1606 privChat := cc.Server.PrivateChats[chatInt]
1607 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1609 for _, c := range sortedClients(privChat.ClientConn) {
1612 tranNotifyChatSubject,
1614 NewField(fieldChatID, chatID),
1615 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),
1623 // HandleMakeAlias makes a file alias using the specified path.
1624 // Fields used in the request:
1627 // 212 File new path Destination path
1629 // Fields used in the reply:
1631 func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1632 if !authorize(cc.Account.Access, accessMakeAlias) {
1633 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
1636 fileName := t.GetField(fieldFileName).Data
1637 filePath := t.GetField(fieldFilePath).Data
1638 fileNewPath := t.GetField(fieldFileNewPath).Data
1640 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1645 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
1650 cc.Server.Logger.Debugw("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
1652 if err := FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
1653 res = append(res, cc.NewErrReply(t, "Error creating alias"))
1657 res = append(res, cc.NewReply(t))