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: accessAlwaysAllow,
54 Handler: HandleChatSend,
56 RequiredFields: []requiredField{
64 Access: accessNewsDeleteArt,
65 DenyMsg: "You are not allowed to delete news articles.",
66 Name: "tranDelNewsArt",
67 Handler: HandleDelNewsArt,
70 Access: accessAlwaysAllow, // Granular access enforced inside the handler
71 // Has multiple access flags: News Delete Folder (37) or News Delete Category (35)
72 // TODO: Implement inside the handler
73 Name: "tranDelNewsItem",
74 Handler: HandleDelNewsItem,
77 Access: accessAlwaysAllow, // Granular access enforced inside the handler
78 Name: "tranDeleteFile",
79 Handler: HandleDeleteFile,
82 Access: accessAlwaysAllow,
83 Name: "tranDeleteUser",
84 Handler: HandleDeleteUser,
87 Access: accessDisconUser,
88 DenyMsg: "You are not allowed to disconnect users.",
89 Name: "tranDisconnectUser",
90 Handler: HandleDisconnectUser,
93 Access: accessAlwaysAllow,
94 Name: "tranDownloadFile",
95 Handler: HandleDownloadFile,
98 Access: accessDownloadFile, // There is no specific access flag for folder vs file download
99 DenyMsg: "You are not allowed to download files.",
100 Name: "tranDownloadFldr",
101 Handler: HandleDownloadFolder,
103 tranGetClientInfoText: {
104 Access: accessGetClientInfo,
105 DenyMsg: "You are not allowed to get client info",
106 Name: "tranGetClientInfoText",
107 Handler: HandleGetClientConnInfoText,
110 Access: accessAlwaysAllow,
111 Name: "tranGetFileInfo",
112 Handler: HandleGetFileInfo,
114 tranGetFileNameList: {
115 Access: accessAlwaysAllow,
116 Name: "tranGetFileNameList",
117 Handler: HandleGetFileNameList,
120 Access: accessAlwaysAllow,
122 Handler: HandleGetMsgs,
124 tranGetNewsArtData: {
125 Access: accessNewsReadArt,
126 DenyMsg: "You are not allowed to read news.",
127 Name: "tranGetNewsArtData",
128 Handler: HandleGetNewsArtData,
130 tranGetNewsArtNameList: {
131 Access: accessNewsReadArt,
132 DenyMsg: "You are not allowed to read news.",
133 Name: "tranGetNewsArtNameList",
134 Handler: HandleGetNewsArtNameList,
136 tranGetNewsCatNameList: {
137 Access: accessNewsReadArt,
138 DenyMsg: "You are not allowed to read news.",
139 Name: "tranGetNewsCatNameList",
140 Handler: HandleGetNewsCatNameList,
143 Access: accessAlwaysAllow,
145 Handler: HandleGetUser,
147 tranGetUserNameList: {
148 Access: accessAlwaysAllow,
149 Name: "tranHandleGetUserNameList",
150 Handler: HandleGetUserNameList,
153 Access: accessOpenChat,
154 DenyMsg: "You are not allowed to request private chat.",
155 Name: "tranInviteNewChat",
156 Handler: HandleInviteNewChat,
159 Access: accessOpenChat,
160 DenyMsg: "You are not allowed to request private chat.",
161 Name: "tranInviteToChat",
162 Handler: HandleInviteToChat,
165 Access: accessAlwaysAllow,
166 Name: "tranJoinChat",
167 Handler: HandleJoinChat,
170 Access: accessAlwaysAllow,
171 Name: "tranKeepAlive",
172 Handler: HandleKeepAlive,
175 Access: accessAlwaysAllow,
176 Name: "tranJoinChat",
177 Handler: HandleLeaveChat,
180 Access: accessAlwaysAllow,
181 Name: "tranListUsers",
182 Handler: HandleListUsers,
185 Access: accessMoveFile,
186 DenyMsg: "You are not allowed to move files.",
187 Name: "tranMoveFile",
188 Handler: HandleMoveFile,
191 Access: accessCreateFolder,
192 DenyMsg: "You are not allow to create folders.",
193 Name: "tranNewFolder",
194 Handler: HandleNewFolder,
197 Access: accessNewsCreateCat,
198 DenyMsg: "You are not allowed to create news categories.",
199 Name: "tranNewNewsCat",
200 Handler: HandleNewNewsCat,
203 Access: accessNewsCreateFldr,
204 DenyMsg: "You are not allowed to create news folders.",
205 Name: "tranNewNewsFldr",
206 Handler: HandleNewNewsFldr,
209 Access: accessAlwaysAllow,
211 Handler: HandleNewUser,
214 Access: accessAlwaysAllow,
215 Name: "tranUpdateUser",
216 Handler: HandleUpdateUser,
219 Access: accessNewsPostArt,
220 DenyMsg: "You are not allowed to post news.",
221 Name: "tranOldPostNews",
222 Handler: HandleTranOldPostNews,
225 Access: accessNewsPostArt,
226 DenyMsg: "You are not allowed to post news articles.",
227 Name: "tranPostNewsArt",
228 Handler: HandlePostNewsArt,
230 tranRejectChatInvite: {
231 Access: accessAlwaysAllow,
232 Name: "tranRejectChatInvite",
233 Handler: HandleRejectChatInvite,
235 tranSendInstantMsg: {
236 Access: accessAlwaysAllow,
237 // Access: accessSendPrivMsg,
238 // DenyMsg: "You are not allowed to send private messages",
239 Name: "tranSendInstantMsg",
240 Handler: HandleSendInstantMsg,
241 RequiredFields: []requiredField{
251 tranSetChatSubject: {
252 Access: accessAlwaysAllow,
253 Name: "tranSetChatSubject",
254 Handler: HandleSetChatSubject,
257 Access: accessAlwaysAllow,
258 Name: "tranMakeFileAlias",
259 Handler: HandleMakeAlias,
260 RequiredFields: []requiredField{
261 {ID: fieldFileName, minLen: 1},
262 {ID: fieldFilePath, minLen: 1},
263 {ID: fieldFileNewPath, minLen: 1},
266 tranSetClientUserInfo: {
267 Access: accessAlwaysAllow,
268 Name: "tranSetClientUserInfo",
269 Handler: HandleSetClientUserInfo,
272 Access: accessAlwaysAllow,
273 Name: "tranSetFileInfo",
274 Handler: HandleSetFileInfo,
277 Access: accessModifyUser,
278 DenyMsg: "You are not allowed to modify accounts.",
280 Handler: HandleSetUser,
283 Access: accessAlwaysAllow,
284 Name: "tranUploadFile",
285 Handler: HandleUploadFile,
288 Access: accessAlwaysAllow,
289 Name: "tranUploadFldr",
290 Handler: HandleUploadFolder,
293 Access: accessBroadcast,
294 DenyMsg: "You are not allowed to send broadcast messages.",
295 Name: "tranUserBroadcast",
296 Handler: HandleUserBroadcast,
300 func HandleChatSend(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
301 if !authorize(cc.Account.Access, accessSendChat) {
302 res = append(res, cc.NewErrReply(t, "You are not allowed to participate in chat."))
306 // Truncate long usernames
307 trunc := fmt.Sprintf("%13s", cc.UserName)
308 formattedMsg := fmt.Sprintf("\r%.14s: %s", trunc, t.GetField(fieldData).Data)
310 // By holding the option key, Hotline chat allows users to send /me formatted messages like:
311 // *** Halcyon does stuff
312 // This is indicated by the presence of the optional field fieldChatOptions in the transaction payload
313 if t.GetField(fieldChatOptions).Data != nil {
314 formattedMsg = fmt.Sprintf("\r*** %s %s", cc.UserName, t.GetField(fieldData).Data)
317 if bytes.Equal(t.GetField(fieldData).Data, []byte("/stats")) {
318 formattedMsg = strings.Replace(cc.Server.Stats.String(), "\n", "\r", -1)
321 chatID := t.GetField(fieldChatID).Data
322 // a non-nil chatID indicates the message belongs to a private chat
324 chatInt := binary.BigEndian.Uint32(chatID)
325 privChat := cc.Server.PrivateChats[chatInt]
327 clients := sortedClients(privChat.ClientConn)
329 // send the message to all connected clients of the private chat
330 for _, c := range clients {
331 res = append(res, *NewTransaction(
334 NewField(fieldChatID, chatID),
335 NewField(fieldData, []byte(formattedMsg)),
341 for _, c := range sortedClients(cc.Server.Clients) {
342 // Filter out clients that do not have the read chat permission
343 if authorize(c.Account.Access, accessReadChat) {
344 res = append(res, *NewTransaction(tranChatMsg, c.ID, NewField(fieldData, []byte(formattedMsg))))
351 // HandleSendInstantMsg sends instant message to the user on the current server.
352 // Fields used in the request:
355 // One of the following values:
356 // - User message (myOpt_UserMessage = 1)
357 // - Refuse message (myOpt_RefuseMessage = 2)
358 // - Refuse chat (myOpt_RefuseChat = 3)
359 // - Automatic response (myOpt_AutomaticResponse = 4)"
361 // 214 Quoting message Optional
363 // Fields used in the reply:
365 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
366 msg := t.GetField(fieldData)
367 ID := t.GetField(fieldUserID)
369 reply := *NewTransaction(
372 NewField(fieldData, msg.Data),
373 NewField(fieldUserName, cc.UserName),
374 NewField(fieldUserID, *cc.ID),
375 NewField(fieldOptions, []byte{0, 1}),
378 // Later versions of Hotline include the original message in the fieldQuotingMsg field so
379 // the receiving client can display both the received message and what it is in reply to
380 if t.GetField(fieldQuotingMsg).Data != nil {
381 reply.Fields = append(reply.Fields, NewField(fieldQuotingMsg, t.GetField(fieldQuotingMsg).Data))
384 res = append(res, reply)
386 id, _ := byteToInt(ID.Data)
387 otherClient := cc.Server.Clients[uint16(id)]
388 if otherClient == nil {
389 return res, errors.New("ohno")
392 // Respond with auto reply if other client has it enabled
393 if len(otherClient.AutoReply) > 0 {
398 NewField(fieldData, otherClient.AutoReply),
399 NewField(fieldUserName, otherClient.UserName),
400 NewField(fieldUserID, *otherClient.ID),
401 NewField(fieldOptions, []byte{0, 1}),
406 res = append(res, cc.NewReply(t))
411 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
412 fileName := t.GetField(fieldFileName).Data
413 filePath := t.GetField(fieldFilePath).Data
415 ffo, err := NewFlattenedFileObject(cc.Server.Config.FileRoot, filePath, fileName, 0)
420 res = append(res, cc.NewReply(t,
421 NewField(fieldFileName, fileName),
422 NewField(fieldFileTypeString, ffo.FlatFileInformationFork.TypeSignature),
423 NewField(fieldFileCreatorString, ffo.FlatFileInformationFork.CreatorSignature),
424 NewField(fieldFileComment, ffo.FlatFileInformationFork.Comment),
425 NewField(fieldFileType, ffo.FlatFileInformationFork.TypeSignature),
426 NewField(fieldFileCreateDate, ffo.FlatFileInformationFork.CreateDate),
427 NewField(fieldFileModifyDate, ffo.FlatFileInformationFork.ModifyDate),
428 NewField(fieldFileSize, ffo.FlatFileDataForkHeader.DataSize[:]),
433 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
434 // TODO: Implement support for comments
435 // Fields used in the request:
437 // * 202 File path Optional
438 // * 211 File new name Optional
439 // * 210 File comment Optional
440 // Fields used in the reply: None
441 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
442 fileName := t.GetField(fieldFileName).Data
443 filePath := t.GetField(fieldFilePath).Data
445 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
450 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, t.GetField(fieldFileNewName).Data)
455 // fileComment := t.GetField(fieldFileComment).Data
456 fileNewName := t.GetField(fieldFileNewName).Data
458 if fileNewName != nil {
459 fi, err := FS.Stat(fullFilePath)
463 switch mode := fi.Mode(); {
465 if !authorize(cc.Account.Access, accessRenameFolder) {
466 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
469 case mode.IsRegular():
470 if !authorize(cc.Account.Access, accessRenameFile) {
471 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
476 err = os.Rename(fullFilePath, fullNewFilePath)
477 if os.IsNotExist(err) {
478 res = append(res, cc.NewErrReply(t, "Cannot rename file "+string(fileName)+" because it does not exist or cannot be found."))
483 res = append(res, cc.NewReply(t))
487 // HandleDeleteFile deletes a file or folder
488 // Fields used in the request:
491 // Fields used in the reply: none
492 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
493 fileName := t.GetField(fieldFileName).Data
494 filePath := t.GetField(fieldFilePath).Data
496 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
501 cc.Server.Logger.Debugw("Delete file", "src", fullFilePath)
503 fi, err := os.Stat(fullFilePath)
505 res = append(res, cc.NewErrReply(t, "Cannot delete file "+string(fileName)+" because it does not exist or cannot be found."))
508 switch mode := fi.Mode(); {
510 if !authorize(cc.Account.Access, accessDeleteFolder) {
511 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
514 case mode.IsRegular():
515 if !authorize(cc.Account.Access, accessDeleteFile) {
516 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
521 if err := os.RemoveAll(fullFilePath); err != nil {
525 res = append(res, cc.NewReply(t))
529 // HandleMoveFile moves files or folders. Note: seemingly not documented
530 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
531 fileName := string(t.GetField(fieldFileName).Data)
532 filePath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
533 fileNewPath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFileNewPath).Data)
535 cc.Server.Logger.Debugw("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
537 fp := filePath + "/" + fileName
538 fi, err := os.Stat(fp)
542 switch mode := fi.Mode(); {
544 if !authorize(cc.Account.Access, accessMoveFolder) {
545 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
548 case mode.IsRegular():
549 if !authorize(cc.Account.Access, accessMoveFile) {
550 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
555 err = os.Rename(filePath+"/"+fileName, fileNewPath+"/"+fileName)
556 if os.IsNotExist(err) {
557 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
561 return []Transaction{}, err
563 // TODO: handle other possible errors; e.g. file delete fails due to file permission issue
565 res = append(res, cc.NewReply(t))
569 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
570 newFolderPath := cc.Server.Config.FileRoot
571 folderName := string(t.GetField(fieldFileName).Data)
573 folderName = path.Join("/", folderName)
575 // fieldFilePath is only present for nested paths
576 if t.GetField(fieldFilePath).Data != nil {
578 err := newFp.UnmarshalBinary(t.GetField(fieldFilePath).Data)
582 newFolderPath += newFp.String()
584 newFolderPath = path.Join(newFolderPath, folderName)
586 // TODO: check path and folder name lengths
588 if _, err := FS.Stat(newFolderPath); !os.IsNotExist(err) {
589 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that name.", folderName)
590 return []Transaction{cc.NewErrReply(t, msg)}, nil
593 // TODO: check for disallowed characters to maintain compatibility for original client
595 if err := FS.Mkdir(newFolderPath, 0777); err != nil {
596 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
597 return []Transaction{cc.NewErrReply(t, msg)}, nil
600 res = append(res, cc.NewReply(t))
604 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
605 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
606 userName := string(t.GetField(fieldUserName).Data)
608 newAccessLvl := t.GetField(fieldUserAccess).Data
610 account := cc.Server.Accounts[login]
611 account.Access = &newAccessLvl
612 account.Name = userName
614 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
615 // not include fieldUserPassword
616 if t.GetField(fieldUserPassword).Data == nil {
617 account.Password = hashAndSalt([]byte(""))
619 if len(t.GetField(fieldUserPassword).Data) > 1 {
620 account.Password = hashAndSalt(t.GetField(fieldUserPassword).Data)
623 out, err := yaml.Marshal(&account)
627 if err := os.WriteFile(cc.Server.ConfigDir+"Users/"+login+".yaml", out, 0666); err != nil {
631 // Notify connected clients logged in as the user of the new access level
632 for _, c := range cc.Server.Clients {
633 if c.Account.Login == login {
634 // Note: comment out these two lines to test server-side deny messages
635 newT := NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, newAccessLvl))
636 res = append(res, *newT)
638 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
639 if authorize(c.Account.Access, accessDisconUser) {
640 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 1)
642 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 0)
644 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
646 c.Account.Access = account.Access
649 tranNotifyChangeUser,
650 NewField(fieldUserID, *c.ID),
651 NewField(fieldUserFlags, *c.Flags),
652 NewField(fieldUserName, c.UserName),
653 NewField(fieldUserIconID, *c.Icon),
658 res = append(res, cc.NewReply(t))
662 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
663 if !authorize(cc.Account.Access, accessOpenUser) {
664 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
668 account := cc.Server.Accounts[string(t.GetField(fieldUserLogin).Data)]
670 res = append(res, cc.NewErrReply(t, "Account does not exist."))
674 res = append(res, cc.NewReply(t,
675 NewField(fieldUserName, []byte(account.Name)),
676 NewField(fieldUserLogin, negateString(t.GetField(fieldUserLogin).Data)),
677 NewField(fieldUserPassword, []byte(account.Password)),
678 NewField(fieldUserAccess, *account.Access),
683 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
684 if !authorize(cc.Account.Access, accessOpenUser) {
685 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
689 var userFields []Field
690 for _, acc := range cc.Server.Accounts {
691 userField := acc.MarshalBinary()
692 userFields = append(userFields, NewField(fieldData, userField))
695 res = append(res, cc.NewReply(t, userFields...))
699 // HandleUpdateUser is used by the v1.5+ multi-user editor to perform account editing for multiple users at a time.
700 // An update can be a mix of these actions:
703 // * Modify user (including renaming the account login)
705 // The Transaction sent by the client includes one data field per user that was modified. This data field in turn
706 // contains another data field encoded in its payload with a varying number of sub fields depending on which action is
707 // performed. This seems to be the only place in the Hotline protocol where a data field contains another data field.
708 func HandleUpdateUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
709 for _, field := range t.Fields {
710 subFields, err := ReadFields(field.Data[0:2], field.Data[2:])
715 if len(subFields) == 1 {
716 login := DecodeUserString(getField(fieldData, &subFields).Data)
717 cc.Server.Logger.Infow("DeleteUser", "login", login)
719 if !authorize(cc.Account.Access, accessDeleteUser) {
720 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
724 if err := cc.Server.DeleteUser(login); err != nil {
730 login := DecodeUserString(getField(fieldUserLogin, &subFields).Data)
732 // check if the login exists; if so, we know we are updating an existing user
733 if acc, ok := cc.Server.Accounts[login]; ok {
734 cc.Server.Logger.Infow("UpdateUser", "login", login)
736 // account exists, so this is an update action
737 if !authorize(cc.Account.Access, accessModifyUser) {
738 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
742 if getField(fieldUserPassword, &subFields) != nil {
743 newPass := getField(fieldUserPassword, &subFields).Data
744 acc.Password = hashAndSalt(newPass)
746 acc.Password = hashAndSalt([]byte(""))
749 if getField(fieldUserAccess, &subFields) != nil {
750 acc.Access = &getField(fieldUserAccess, &subFields).Data
753 err = cc.Server.UpdateUser(
754 DecodeUserString(getField(fieldData, &subFields).Data),
755 DecodeUserString(getField(fieldUserLogin, &subFields).Data),
756 string(getField(fieldUserName, &subFields).Data),
764 cc.Server.Logger.Infow("CreateUser", "login", login)
766 if !authorize(cc.Account.Access, accessCreateUser) {
767 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
771 err := cc.Server.NewUser(
773 string(getField(fieldUserName, &subFields).Data),
774 string(getField(fieldUserPassword, &subFields).Data),
775 getField(fieldUserAccess, &subFields).Data,
778 return []Transaction{}, err
783 res = append(res, cc.NewReply(t))
787 // HandleNewUser creates a new user account
788 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
789 if !authorize(cc.Account.Access, accessCreateUser) {
790 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
794 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
796 // If the account already exists, reply with an error
797 if _, ok := cc.Server.Accounts[login]; ok {
798 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
802 if err := cc.Server.NewUser(
804 string(t.GetField(fieldUserName).Data),
805 string(t.GetField(fieldUserPassword).Data),
806 t.GetField(fieldUserAccess).Data,
808 return []Transaction{}, err
811 res = append(res, cc.NewReply(t))
815 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
816 if !authorize(cc.Account.Access, accessDeleteUser) {
817 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
821 // TODO: Handle case where account doesn't exist; e.g. delete race condition
822 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
824 if err := cc.Server.DeleteUser(login); err != nil {
828 res = append(res, cc.NewReply(t))
832 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
833 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
836 NewField(fieldData, t.GetField(tranGetMsgs).Data),
837 NewField(fieldChatOptions, []byte{0}),
840 res = append(res, cc.NewReply(t))
844 func byteToInt(bytes []byte) (int, error) {
847 return int(binary.BigEndian.Uint16(bytes)), nil
849 return int(binary.BigEndian.Uint32(bytes)), nil
852 return 0, errors.New("unknown byte length")
855 func HandleGetClientConnInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
856 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
858 clientConn := cc.Server.Clients[uint16(clientID)]
859 if clientConn == nil {
860 return res, errors.New("invalid client")
863 // TODO: Implement non-hardcoded values
864 template := `Nickname: %s
869 -------- File Downloads ---------
873 ------- Folder Downloads --------
877 --------- File Uploads ----------
881 -------- Folder Uploads ---------
885 ------- Waiting Downloads -------
891 activeDownloads := clientConn.Transfers[FileDownload]
892 activeDownloadList := "None."
893 for _, dl := range activeDownloads {
894 activeDownloadList += dl.String() + "\n"
897 template = fmt.Sprintf(
900 clientConn.Account.Name,
901 clientConn.Account.Login,
902 clientConn.Connection.RemoteAddr().String(),
905 template = strings.Replace(template, "\n", "\r", -1)
907 res = append(res, cc.NewReply(t,
908 NewField(fieldData, []byte(template)),
909 NewField(fieldUserName, clientConn.UserName),
914 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
915 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
920 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
922 cc.UserName = t.GetField(fieldUserName).Data
923 *cc.Icon = t.GetField(fieldUserIconID).Data
925 options := t.GetField(fieldOptions).Data
926 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
928 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
930 // Check refuse private PM option
931 if optBitmap.Bit(refusePM) == 1 {
932 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
933 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
936 // Check refuse private chat option
937 if optBitmap.Bit(refuseChat) == 1 {
938 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
939 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
942 // Check auto response
943 if optBitmap.Bit(autoResponse) == 1 {
944 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
946 cc.AutoReply = []byte{}
951 tranNotifyChangeUser, nil,
952 NewField(fieldUserName, cc.UserName),
953 NewField(fieldUserID, *cc.ID),
954 NewField(fieldUserIconID, *cc.Icon),
955 NewField(fieldUserFlags, *cc.Flags),
959 res = append(res, cc.NewReply(t))
964 const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
965 // "Mon, 02 Jan 2006 15:04:05 MST"
967 const defaultNewsTemplate = `From %s (%s):
971 __________________________________________________________`
973 // HandleTranOldPostNews updates the flat news
974 // Fields used in this request:
976 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
977 cc.Server.flatNewsMux.Lock()
978 defer cc.Server.flatNewsMux.Unlock()
980 newsDateTemplate := defaultNewsDateFormat
981 if cc.Server.Config.NewsDateFormat != "" {
982 newsDateTemplate = cc.Server.Config.NewsDateFormat
985 newsTemplate := defaultNewsTemplate
986 if cc.Server.Config.NewsDelimiter != "" {
987 newsTemplate = cc.Server.Config.NewsDelimiter
990 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
991 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
993 // update news in memory
994 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
996 // update news on disk
997 if err := ioutil.WriteFile(cc.Server.ConfigDir+"MessageBoard.txt", cc.Server.FlatNews, 0644); err != nil {
1001 // Notify all clients of updated news
1004 NewField(fieldData, []byte(newsPost)),
1007 res = append(res, cc.NewReply(t))
1011 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1012 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
1014 if authorize(clientConn.Account.Access, accessCannotBeDiscon) {
1015 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
1019 if err := clientConn.Connection.Close(); err != nil {
1023 res = append(res, cc.NewReply(t))
1027 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1028 // Fields used in the request:
1029 // 325 News path (Optional)
1031 newsPath := t.GetField(fieldNewsPath).Data
1032 cc.Server.Logger.Infow("NewsPath: ", "np", string(newsPath))
1034 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1035 cats := cc.Server.GetNewsCatByPath(pathStrs)
1037 // To store the keys in slice in sorted order
1038 keys := make([]string, len(cats))
1040 for k := range cats {
1046 var fieldData []Field
1047 for _, k := range keys {
1049 b, _ := cat.MarshalBinary()
1050 fieldData = append(fieldData, NewField(
1051 fieldNewsCatListData15,
1056 res = append(res, cc.NewReply(t, fieldData...))
1060 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1061 name := string(t.GetField(fieldNewsCatName).Data)
1062 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1064 cats := cc.Server.GetNewsCatByPath(pathStrs)
1065 cats[name] = NewsCategoryListData15{
1068 Articles: map[uint32]*NewsArtData{},
1069 SubCats: make(map[string]NewsCategoryListData15),
1072 if err := cc.Server.writeThreadedNews(); err != nil {
1075 res = append(res, cc.NewReply(t))
1079 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1080 // Fields used in the request:
1081 // 322 News category name
1083 name := string(t.GetField(fieldFileName).Data)
1084 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1086 cc.Server.Logger.Infof("Creating new news folder %s", name)
1088 cats := cc.Server.GetNewsCatByPath(pathStrs)
1089 cats[name] = NewsCategoryListData15{
1092 Articles: map[uint32]*NewsArtData{},
1093 SubCats: make(map[string]NewsCategoryListData15),
1095 if err := cc.Server.writeThreadedNews(); err != nil {
1098 res = append(res, cc.NewReply(t))
1102 // Fields used in the request:
1103 // 325 News path Optional
1106 // 321 News article list data Optional
1107 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1108 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1110 var cat NewsCategoryListData15
1111 cats := cc.Server.ThreadedNews.Categories
1113 for _, fp := range pathStrs {
1115 cats = cats[fp].SubCats
1118 nald := cat.GetNewsArtListData()
1120 res = append(res, cc.NewReply(t, NewField(fieldNewsArtListData, nald.Payload())))
1124 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1127 // 326 News article ID
1128 // 327 News article data flavor
1130 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1132 var cat NewsCategoryListData15
1133 cats := cc.Server.ThreadedNews.Categories
1135 for _, fp := range pathStrs {
1137 cats = cats[fp].SubCats
1139 newsArtID := t.GetField(fieldNewsArtID).Data
1141 convertedArtID := binary.BigEndian.Uint16(newsArtID)
1143 art := cat.Articles[uint32(convertedArtID)]
1145 res = append(res, cc.NewReply(t))
1150 // 328 News article title
1151 // 329 News article poster
1152 // 330 News article date
1153 // 331 Previous article ID
1154 // 332 Next article ID
1155 // 335 Parent article ID
1156 // 336 First child article ID
1157 // 327 News article data flavor "Should be “text/plain”
1158 // 333 News article data Optional (if data flavor is “text/plain”)
1160 res = append(res, cc.NewReply(t,
1161 NewField(fieldNewsArtTitle, []byte(art.Title)),
1162 NewField(fieldNewsArtPoster, []byte(art.Poster)),
1163 NewField(fieldNewsArtDate, art.Date),
1164 NewField(fieldNewsArtPrevArt, art.PrevArt),
1165 NewField(fieldNewsArtNextArt, art.NextArt),
1166 NewField(fieldNewsArtParentArt, art.ParentArt),
1167 NewField(fieldNewsArt1stChildArt, art.FirstChildArt),
1168 NewField(fieldNewsArtDataFlav, []byte("text/plain")),
1169 NewField(fieldNewsArtData, []byte(art.Data)),
1174 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1175 // Access: News Delete Folder (37) or News Delete Category (35)
1177 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1179 // TODO: determine if path is a Folder (Bundle) or Category and check for permission
1181 cc.Server.Logger.Infof("DelNewsItem %v", pathStrs)
1183 cats := cc.Server.ThreadedNews.Categories
1185 delName := pathStrs[len(pathStrs)-1]
1186 if len(pathStrs) > 1 {
1187 for _, fp := range pathStrs[0 : len(pathStrs)-1] {
1188 cats = cats[fp].SubCats
1192 delete(cats, delName)
1194 err = cc.Server.writeThreadedNews()
1199 // Reply params: none
1200 res = append(res, cc.NewReply(t))
1205 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1208 // 326 News article ID
1209 // 337 News article – recursive delete Delete child articles (1) or not (0)
1210 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1211 ID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1213 // TODO: Delete recursive
1214 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1216 catName := pathStrs[len(pathStrs)-1]
1217 cat := cats[catName]
1219 delete(cat.Articles, uint32(ID))
1222 if err := cc.Server.writeThreadedNews(); err != nil {
1226 res = append(res, cc.NewReply(t))
1230 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1233 // 326 News article ID ID of the parent article?
1234 // 328 News article title
1235 // 334 News article flags
1236 // 327 News article data flavor Currently “text/plain”
1237 // 333 News article data
1239 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1240 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1242 catName := pathStrs[len(pathStrs)-1]
1243 cat := cats[catName]
1245 newArt := NewsArtData{
1246 Title: string(t.GetField(fieldNewsArtTitle).Data),
1247 Poster: string(cc.UserName),
1248 Date: toHotlineTime(time.Now()),
1249 PrevArt: []byte{0, 0, 0, 0},
1250 NextArt: []byte{0, 0, 0, 0},
1251 ParentArt: append([]byte{0, 0}, t.GetField(fieldNewsArtID).Data...),
1252 FirstChildArt: []byte{0, 0, 0, 0},
1253 DataFlav: []byte("text/plain"),
1254 Data: string(t.GetField(fieldNewsArtData).Data),
1258 for k := range cat.Articles {
1259 keys = append(keys, int(k))
1265 prevID := uint32(keys[len(keys)-1])
1268 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1270 // Set next article ID
1271 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1274 // Update parent article with first child reply
1275 parentID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1277 parentArt := cat.Articles[uint32(parentID)]
1279 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1280 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1284 cat.Articles[nextID] = &newArt
1287 if err := cc.Server.writeThreadedNews(); err != nil {
1291 res = append(res, cc.NewReply(t))
1295 // HandleGetMsgs returns the flat news data
1296 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1297 if !authorize(cc.Account.Access, accessNewsReadArt) {
1298 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1302 res = append(res, cc.NewReply(t, NewField(fieldData, cc.Server.FlatNews)))
1307 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1308 if !authorize(cc.Account.Access, accessDownloadFile) {
1309 res = append(res, cc.NewErrReply(t, "You are not allowed to download files."))
1313 fileName := t.GetField(fieldFileName).Data
1314 filePath := t.GetField(fieldFilePath).Data
1316 resumeData := t.GetField(fieldFileResumeData).Data
1318 var dataOffset int64
1319 var frd FileResumeData
1320 if resumeData != nil {
1321 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1324 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1328 err = fp.UnmarshalBinary(filePath)
1333 ffo, err := NewFlattenedFileObject(cc.Server.Config.FileRoot, filePath, fileName, dataOffset)
1338 transactionRef := cc.Server.NewTransactionRef()
1339 data := binary.BigEndian.Uint32(transactionRef)
1341 ft := &FileTransfer{
1344 ReferenceNumber: transactionRef,
1348 if resumeData != nil {
1349 var frd FileResumeData
1350 frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data)
1351 ft.fileResumeData = &frd
1354 xferSize := ffo.TransferSize()
1356 // Optional field for when a HL v1.5+ client requests file preview
1357 // Used only for TEXT, JPEG, GIFF, BMP or PICT files
1358 // The value will always be 2
1359 if t.GetField(fieldFileTransferOptions).Data != nil {
1360 ft.options = t.GetField(fieldFileTransferOptions).Data
1361 xferSize = ffo.FlatFileDataForkHeader.DataSize[:]
1364 cc.Server.mux.Lock()
1365 defer cc.Server.mux.Unlock()
1366 cc.Server.FileTransfers[data] = ft
1368 cc.Transfers[FileDownload] = append(cc.Transfers[FileDownload], ft)
1370 res = append(res, cc.NewReply(t,
1371 NewField(fieldRefNum, transactionRef),
1372 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1373 NewField(fieldTransferSize, xferSize),
1374 NewField(fieldFileSize, ffo.FlatFileDataForkHeader.DataSize[:]),
1380 // Download all files from the specified folder and sub-folders
1393 // 00 6c // transfer size
1397 // 00 dc // field Folder item count
1401 // 00 6b // ref number
1404 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1405 transactionRef := cc.Server.NewTransactionRef()
1406 data := binary.BigEndian.Uint32(transactionRef)
1408 fileTransfer := &FileTransfer{
1409 FileName: t.GetField(fieldFileName).Data,
1410 FilePath: t.GetField(fieldFilePath).Data,
1411 ReferenceNumber: transactionRef,
1412 Type: FolderDownload,
1414 cc.Server.FileTransfers[data] = fileTransfer
1415 cc.Transfers[FolderDownload] = append(cc.Transfers[FolderDownload], fileTransfer)
1418 err = fp.UnmarshalBinary(t.GetField(fieldFilePath).Data)
1423 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
1428 transferSize, err := CalcTotalSize(fullFilePath)
1432 itemCount, err := CalcItemCount(fullFilePath)
1436 res = append(res, cc.NewReply(t,
1437 NewField(fieldRefNum, transactionRef),
1438 NewField(fieldTransferSize, transferSize),
1439 NewField(fieldFolderItemCount, itemCount),
1440 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1445 // Upload all files from the local folder and its subfolders to the specified path on the server
1446 // Fields used in the request
1449 // 108 transfer size Total size of all items in the folder
1450 // 220 Folder item count
1451 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1452 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1453 transactionRef := cc.Server.NewTransactionRef()
1454 data := binary.BigEndian.Uint32(transactionRef)
1457 if t.GetField(fieldFilePath).Data != nil {
1458 if err = fp.UnmarshalBinary(t.GetField(fieldFilePath).Data); err != nil {
1463 // Handle special cases for Upload and Drop Box folders
1464 if !authorize(cc.Account.Access, accessUploadAnywhere) {
1465 if !fp.IsUploadDir() && !fp.IsDropbox() {
1466 res = append(res, cc.NewErrReply(t, fmt.Sprintf("Cannot accept upload of the folder \"%v\" because you are only allowed to upload to the \"Uploads\" folder.", string(t.GetField(fieldFileName).Data))))
1471 fileTransfer := &FileTransfer{
1472 FileName: t.GetField(fieldFileName).Data,
1473 FilePath: t.GetField(fieldFilePath).Data,
1474 ReferenceNumber: transactionRef,
1476 FolderItemCount: t.GetField(fieldFolderItemCount).Data,
1477 TransferSize: t.GetField(fieldTransferSize).Data,
1479 cc.Server.FileTransfers[data] = fileTransfer
1481 res = append(res, cc.NewReply(t, NewField(fieldRefNum, transactionRef)))
1486 // Fields used in the request:
1489 // 204 File transfer options "Optional
1490 // Used only to resume download, currently has value 2"
1491 // 108 File transfer size "Optional used if download is not resumed"
1492 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1493 if !authorize(cc.Account.Access, accessUploadFile) {
1494 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1498 fileName := t.GetField(fieldFileName).Data
1499 filePath := t.GetField(fieldFilePath).Data
1501 transferOptions := t.GetField(fieldFileTransferOptions).Data
1503 // TODO: is this field useful for anything?
1504 // transferSize := t.GetField(fieldTransferSize).Data
1507 if filePath != nil {
1508 if err = fp.UnmarshalBinary(filePath); err != nil {
1513 // Handle special cases for Upload and Drop Box folders
1514 if !authorize(cc.Account.Access, accessUploadAnywhere) {
1515 if !fp.IsUploadDir() && !fp.IsDropbox() {
1516 res = append(res, cc.NewErrReply(t, fmt.Sprintf("Cannot accept upload of the file \"%v\" because you are only allowed to upload to the \"Uploads\" folder.", string(fileName))))
1521 transactionRef := cc.Server.NewTransactionRef()
1522 data := binary.BigEndian.Uint32(transactionRef)
1524 cc.Server.FileTransfers[data] = &FileTransfer{
1527 ReferenceNumber: transactionRef,
1531 replyT := cc.NewReply(t, NewField(fieldRefNum, transactionRef))
1533 // client has requested to resume a partially transfered file
1534 if transferOptions != nil {
1535 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1540 fileInfo, err := FS.Stat(fullFilePath + incompleteFileSuffix)
1545 offset := make([]byte, 4)
1546 binary.BigEndian.PutUint32(offset, uint32(fileInfo.Size()))
1548 fileResumeData := NewFileResumeData([]ForkInfoList{
1549 *NewForkInfoList(offset),
1552 b, _ := fileResumeData.BinaryMarshal()
1554 replyT.Fields = append(replyT.Fields, NewField(fieldFileResumeData, b))
1557 res = append(res, replyT)
1561 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1563 if len(t.GetField(fieldUserIconID).Data) == 4 {
1564 icon = t.GetField(fieldUserIconID).Data[2:]
1566 icon = t.GetField(fieldUserIconID).Data
1569 cc.UserName = t.GetField(fieldUserName).Data
1571 // the options field is only passed by the client versions > 1.2.3.
1572 options := t.GetField(fieldOptions).Data
1575 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1576 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
1578 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, optBitmap.Bit(refusePM))
1579 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
1581 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, optBitmap.Bit(refuseChat))
1582 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
1584 // Check auto response
1585 if optBitmap.Bit(autoResponse) == 1 {
1586 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
1588 cc.AutoReply = []byte{}
1592 // Notify all clients of updated user info
1594 tranNotifyChangeUser,
1595 NewField(fieldUserID, *cc.ID),
1596 NewField(fieldUserIconID, *cc.Icon),
1597 NewField(fieldUserFlags, *cc.Flags),
1598 NewField(fieldUserName, cc.UserName),
1604 // HandleKeepAlive responds to keepalive transactions with an empty reply
1605 // * HL 1.9.2 Client sends keepalive msg every 3 minutes
1606 // * HL 1.2.3 Client doesn't send keepalives
1607 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1608 res = append(res, cc.NewReply(t))
1613 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1614 fullPath, err := readPath(
1615 cc.Server.Config.FileRoot,
1616 t.GetField(fieldFilePath).Data,
1624 if t.GetField(fieldFilePath).Data != nil {
1625 if err = fp.UnmarshalBinary(t.GetField(fieldFilePath).Data); err != nil {
1630 // Handle special case for drop box folders
1631 if fp.IsDropbox() && !authorize(cc.Account.Access, accessViewDropBoxes) {
1632 res = append(res, cc.NewReply(t))
1636 fileNames, err := getFileNameList(fullPath)
1641 res = append(res, cc.NewReply(t, fileNames...))
1646 // =================================
1647 // Hotline private chat flow
1648 // =================================
1649 // 1. ClientA sends tranInviteNewChat to server with user ID to invite
1650 // 2. Server creates new ChatID
1651 // 3. Server sends tranInviteToChat to invitee
1652 // 4. Server replies to ClientA with new Chat ID
1654 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1655 // If Accepted is clicked:
1656 // 1. ClientB sends tranJoinChat with fieldChatID
1658 // HandleInviteNewChat invites users to new private chat
1659 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1661 targetID := t.GetField(fieldUserID).Data
1662 newChatID := cc.Server.NewPrivateChat(cc)
1668 NewField(fieldChatID, newChatID),
1669 NewField(fieldUserName, cc.UserName),
1670 NewField(fieldUserID, *cc.ID),
1676 NewField(fieldChatID, newChatID),
1677 NewField(fieldUserName, cc.UserName),
1678 NewField(fieldUserID, *cc.ID),
1679 NewField(fieldUserIconID, *cc.Icon),
1680 NewField(fieldUserFlags, *cc.Flags),
1687 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1689 targetID := t.GetField(fieldUserID).Data
1690 chatID := t.GetField(fieldChatID).Data
1696 NewField(fieldChatID, chatID),
1697 NewField(fieldUserName, cc.UserName),
1698 NewField(fieldUserID, *cc.ID),
1704 NewField(fieldChatID, chatID),
1705 NewField(fieldUserName, cc.UserName),
1706 NewField(fieldUserID, *cc.ID),
1707 NewField(fieldUserIconID, *cc.Icon),
1708 NewField(fieldUserFlags, *cc.Flags),
1715 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1716 chatID := t.GetField(fieldChatID).Data
1717 chatInt := binary.BigEndian.Uint32(chatID)
1719 privChat := cc.Server.PrivateChats[chatInt]
1721 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1723 for _, c := range sortedClients(privChat.ClientConn) {
1728 NewField(fieldChatID, chatID),
1729 NewField(fieldData, resMsg),
1737 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1738 // Fields used in the reply:
1739 // * 115 Chat subject
1740 // * 300 User name with info (Optional)
1741 // * 300 (more user names with info)
1742 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1743 chatID := t.GetField(fieldChatID).Data
1744 chatInt := binary.BigEndian.Uint32(chatID)
1746 privChat := cc.Server.PrivateChats[chatInt]
1748 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1749 for _, c := range sortedClients(privChat.ClientConn) {
1752 tranNotifyChatChangeUser,
1754 NewField(fieldChatID, chatID),
1755 NewField(fieldUserName, cc.UserName),
1756 NewField(fieldUserID, *cc.ID),
1757 NewField(fieldUserIconID, *cc.Icon),
1758 NewField(fieldUserFlags, *cc.Flags),
1763 privChat.ClientConn[cc.uint16ID()] = cc
1765 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1766 for _, c := range sortedClients(privChat.ClientConn) {
1771 Name: string(c.UserName),
1774 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1777 res = append(res, cc.NewReply(t, replyFields...))
1781 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1782 // Fields used in the request:
1783 // * 114 fieldChatID
1784 // Reply is not expected.
1785 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1786 chatID := t.GetField(fieldChatID).Data
1787 chatInt := binary.BigEndian.Uint32(chatID)
1789 privChat := cc.Server.PrivateChats[chatInt]
1791 delete(privChat.ClientConn, cc.uint16ID())
1793 // Notify members of the private chat that the user has left
1794 for _, c := range sortedClients(privChat.ClientConn) {
1797 tranNotifyChatDeleteUser,
1799 NewField(fieldChatID, chatID),
1800 NewField(fieldUserID, *cc.ID),
1808 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1809 // Fields used in the request:
1811 // * 115 Chat subject Chat subject string
1812 // Reply is not expected.
1813 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1814 chatID := t.GetField(fieldChatID).Data
1815 chatInt := binary.BigEndian.Uint32(chatID)
1817 privChat := cc.Server.PrivateChats[chatInt]
1818 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1820 for _, c := range sortedClients(privChat.ClientConn) {
1823 tranNotifyChatSubject,
1825 NewField(fieldChatID, chatID),
1826 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),
1834 // HandleMakeAlias makes a file alias using the specified path.
1835 // Fields used in the request:
1838 // 212 File new path Destination path
1840 // Fields used in the reply:
1842 func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1843 if !authorize(cc.Account.Access, accessMakeAlias) {
1844 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
1847 fileName := t.GetField(fieldFileName).Data
1848 filePath := t.GetField(fieldFilePath).Data
1849 fileNewPath := t.GetField(fieldFileNewPath).Data
1851 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1856 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
1861 cc.Server.Logger.Debugw("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
1863 if err := FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
1864 res = append(res, cc.NewErrReply(t, "Error creating alias"))
1868 res = append(res, cc.NewReply(t))