18 type TransactionType struct {
19 Handler func(*ClientConn, *Transaction) ([]Transaction, error) // function for handling the transaction type
20 Name string // Name of transaction as it will appear in logging
21 RequiredFields []requiredField
24 var TransactionHandlers = map[uint16]TransactionType{
30 tranNotifyChangeUser: {
31 Name: "tranNotifyChangeUser",
37 Name: "tranShowAgreement",
40 Name: "tranUserAccess",
42 tranNotifyDeleteUser: {
43 Name: "tranNotifyDeleteUser",
47 Handler: HandleTranAgreed,
51 Handler: HandleChatSend,
52 RequiredFields: []requiredField{
60 Name: "tranDelNewsArt",
61 Handler: HandleDelNewsArt,
64 Name: "tranDelNewsItem",
65 Handler: HandleDelNewsItem,
68 Name: "tranDeleteFile",
69 Handler: HandleDeleteFile,
72 Name: "tranDeleteUser",
73 Handler: HandleDeleteUser,
76 Name: "tranDisconnectUser",
77 Handler: HandleDisconnectUser,
80 Name: "tranDownloadFile",
81 Handler: HandleDownloadFile,
84 Name: "tranDownloadFldr",
85 Handler: HandleDownloadFolder,
87 tranGetClientInfoText: {
88 Name: "tranGetClientInfoText",
89 Handler: HandleGetClientInfoText,
92 Name: "tranGetFileInfo",
93 Handler: HandleGetFileInfo,
95 tranGetFileNameList: {
96 Name: "tranGetFileNameList",
97 Handler: HandleGetFileNameList,
101 Handler: HandleGetMsgs,
103 tranGetNewsArtData: {
104 Name: "tranGetNewsArtData",
105 Handler: HandleGetNewsArtData,
107 tranGetNewsArtNameList: {
108 Name: "tranGetNewsArtNameList",
109 Handler: HandleGetNewsArtNameList,
111 tranGetNewsCatNameList: {
112 Name: "tranGetNewsCatNameList",
113 Handler: HandleGetNewsCatNameList,
117 Handler: HandleGetUser,
119 tranGetUserNameList: {
120 Name: "tranHandleGetUserNameList",
121 Handler: HandleGetUserNameList,
124 Name: "tranInviteNewChat",
125 Handler: HandleInviteNewChat,
128 Name: "tranInviteToChat",
129 Handler: HandleInviteToChat,
132 Name: "tranJoinChat",
133 Handler: HandleJoinChat,
136 Name: "tranKeepAlive",
137 Handler: HandleKeepAlive,
140 Name: "tranJoinChat",
141 Handler: HandleLeaveChat,
144 Name: "tranListUsers",
145 Handler: HandleListUsers,
148 Name: "tranMoveFile",
149 Handler: HandleMoveFile,
152 Name: "tranNewFolder",
153 Handler: HandleNewFolder,
156 Name: "tranNewNewsCat",
157 Handler: HandleNewNewsCat,
160 Name: "tranNewNewsFldr",
161 Handler: HandleNewNewsFldr,
165 Handler: HandleNewUser,
168 Name: "tranUpdateUser",
169 Handler: HandleUpdateUser,
172 Name: "tranOldPostNews",
173 Handler: HandleTranOldPostNews,
176 Name: "tranPostNewsArt",
177 Handler: HandlePostNewsArt,
179 tranRejectChatInvite: {
180 Name: "tranRejectChatInvite",
181 Handler: HandleRejectChatInvite,
183 tranSendInstantMsg: {
184 Name: "tranSendInstantMsg",
185 Handler: HandleSendInstantMsg,
186 RequiredFields: []requiredField{
196 tranSetChatSubject: {
197 Name: "tranSetChatSubject",
198 Handler: HandleSetChatSubject,
201 Name: "tranMakeFileAlias",
202 Handler: HandleMakeAlias,
203 RequiredFields: []requiredField{
204 {ID: fieldFileName, minLen: 1},
205 {ID: fieldFilePath, minLen: 1},
206 {ID: fieldFileNewPath, minLen: 1},
209 tranSetClientUserInfo: {
210 Name: "tranSetClientUserInfo",
211 Handler: HandleSetClientUserInfo,
214 Name: "tranSetFileInfo",
215 Handler: HandleSetFileInfo,
219 Handler: HandleSetUser,
222 Name: "tranUploadFile",
223 Handler: HandleUploadFile,
226 Name: "tranUploadFldr",
227 Handler: HandleUploadFolder,
230 Name: "tranUserBroadcast",
231 Handler: HandleUserBroadcast,
233 tranDownloadBanner: {
234 Name: "tranDownloadBanner",
235 Handler: HandleDownloadBanner,
239 func HandleChatSend(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
240 if !cc.Authorize(accessSendChat) {
241 res = append(res, cc.NewErrReply(t, "You are not allowed to participate in chat."))
245 // Truncate long usernames
246 trunc := fmt.Sprintf("%13s", cc.UserName)
247 formattedMsg := fmt.Sprintf("\r%.14s: %s", trunc, t.GetField(fieldData).Data)
249 // By holding the option key, Hotline chat allows users to send /me formatted messages like:
250 // *** Halcyon does stuff
251 // This is indicated by the presence of the optional field fieldChatOptions set to a value of 1.
252 // Most clients do not send this option for normal chat messages.
253 if t.GetField(fieldChatOptions).Data != nil && bytes.Equal(t.GetField(fieldChatOptions).Data, []byte{0, 1}) {
254 formattedMsg = fmt.Sprintf("\r*** %s %s", cc.UserName, t.GetField(fieldData).Data)
257 // The ChatID field is used to identify messages as belonging to a private chat.
258 // All clients *except* Frogblast omit this field for public chat, but Frogblast sends a value of 00 00 00 00.
259 chatID := t.GetField(fieldChatID).Data
260 if chatID != nil && !bytes.Equal([]byte{0, 0, 0, 0}, chatID) {
261 chatInt := binary.BigEndian.Uint32(chatID)
262 privChat := cc.Server.PrivateChats[chatInt]
264 clients := sortedClients(privChat.ClientConn)
266 // send the message to all connected clients of the private chat
267 for _, c := range clients {
268 res = append(res, *NewTransaction(
271 NewField(fieldChatID, chatID),
272 NewField(fieldData, []byte(formattedMsg)),
278 for _, c := range sortedClients(cc.Server.Clients) {
279 // Filter out clients that do not have the read chat permission
280 if c.Authorize(accessReadChat) {
281 res = append(res, *NewTransaction(tranChatMsg, c.ID, NewField(fieldData, []byte(formattedMsg))))
288 // HandleSendInstantMsg sends instant message to the user on the current server.
289 // Fields used in the request:
292 // One of the following values:
293 // - User message (myOpt_UserMessage = 1)
294 // - Refuse message (myOpt_RefuseMessage = 2)
295 // - Refuse chat (myOpt_RefuseChat = 3)
296 // - Automatic response (myOpt_AutomaticResponse = 4)"
298 // 214 Quoting message Optional
300 // Fields used in the reply:
302 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
303 if !cc.Authorize(accessSendPrivMsg) {
304 res = append(res, cc.NewErrReply(t, "You are not allowed to send private messages."))
308 msg := t.GetField(fieldData)
309 ID := t.GetField(fieldUserID)
311 reply := NewTransaction(
314 NewField(fieldData, msg.Data),
315 NewField(fieldUserName, cc.UserName),
316 NewField(fieldUserID, *cc.ID),
317 NewField(fieldOptions, []byte{0, 1}),
320 // Later versions of Hotline include the original message in the fieldQuotingMsg field so
321 // the receiving client can display both the received message and what it is in reply to
322 if t.GetField(fieldQuotingMsg).Data != nil {
323 reply.Fields = append(reply.Fields, NewField(fieldQuotingMsg, t.GetField(fieldQuotingMsg).Data))
326 id, _ := byteToInt(ID.Data)
327 otherClient, ok := cc.Server.Clients[uint16(id)]
329 return res, errors.New("invalid client ID")
332 // Check if target user has "Refuse private messages" flag
333 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(otherClient.Flags)))
334 if flagBitmap.Bit(userFLagRefusePChat) == 1 {
339 NewField(fieldData, []byte(string(otherClient.UserName)+" does not accept private messages.")),
340 NewField(fieldUserName, otherClient.UserName),
341 NewField(fieldUserID, *otherClient.ID),
342 NewField(fieldOptions, []byte{0, 2}),
346 res = append(res, *reply)
349 // Respond with auto reply if other client has it enabled
350 if len(otherClient.AutoReply) > 0 {
355 NewField(fieldData, otherClient.AutoReply),
356 NewField(fieldUserName, otherClient.UserName),
357 NewField(fieldUserID, *otherClient.ID),
358 NewField(fieldOptions, []byte{0, 1}),
363 res = append(res, cc.NewReply(t))
368 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
369 fileName := t.GetField(fieldFileName).Data
370 filePath := t.GetField(fieldFilePath).Data
372 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
377 fw, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
382 res = append(res, cc.NewReply(t,
383 NewField(fieldFileName, []byte(fw.name)),
384 NewField(fieldFileTypeString, fw.ffo.FlatFileInformationFork.friendlyType()),
385 NewField(fieldFileCreatorString, fw.ffo.FlatFileInformationFork.friendlyCreator()),
386 NewField(fieldFileComment, fw.ffo.FlatFileInformationFork.Comment),
387 NewField(fieldFileType, fw.ffo.FlatFileInformationFork.TypeSignature),
388 NewField(fieldFileCreateDate, fw.ffo.FlatFileInformationFork.CreateDate),
389 NewField(fieldFileModifyDate, fw.ffo.FlatFileInformationFork.ModifyDate),
390 NewField(fieldFileSize, fw.totalSize()),
395 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
396 // Fields used in the request:
398 // * 202 File path Optional
399 // * 211 File new name Optional
400 // * 210 File comment Optional
401 // Fields used in the reply: None
402 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
403 fileName := t.GetField(fieldFileName).Data
404 filePath := t.GetField(fieldFilePath).Data
406 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
411 fi, err := cc.Server.FS.Stat(fullFilePath)
416 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
420 if t.GetField(fieldFileComment).Data != nil {
421 switch mode := fi.Mode(); {
423 if !cc.Authorize(accessSetFolderComment) {
424 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for folders."))
427 case mode.IsRegular():
428 if !cc.Authorize(accessSetFileComment) {
429 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for files."))
434 if err := hlFile.ffo.FlatFileInformationFork.setComment(t.GetField(fieldFileComment).Data); err != nil {
437 w, err := hlFile.infoForkWriter()
441 _, err = w.Write(hlFile.ffo.FlatFileInformationFork.MarshalBinary())
447 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, t.GetField(fieldFileNewName).Data)
452 fileNewName := t.GetField(fieldFileNewName).Data
454 if fileNewName != nil {
455 switch mode := fi.Mode(); {
457 if !cc.Authorize(accessRenameFolder) {
458 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
461 err = os.Rename(fullFilePath, fullNewFilePath)
462 if os.IsNotExist(err) {
463 res = append(res, cc.NewErrReply(t, "Cannot rename folder "+string(fileName)+" because it does not exist or cannot be found."))
466 case mode.IsRegular():
467 if !cc.Authorize(accessRenameFile) {
468 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
471 fileDir, err := readPath(cc.Server.Config.FileRoot, filePath, []byte{})
475 hlFile.name = string(fileNewName)
476 err = hlFile.move(fileDir)
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."))
487 res = append(res, cc.NewReply(t))
491 // HandleDeleteFile deletes a file or folder
492 // Fields used in the request:
495 // Fields used in the reply: none
496 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
497 fileName := t.GetField(fieldFileName).Data
498 filePath := t.GetField(fieldFilePath).Data
500 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
505 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
510 fi, err := hlFile.dataFile()
512 res = append(res, cc.NewErrReply(t, "Cannot delete file "+string(fileName)+" because it does not exist or cannot be found."))
516 switch mode := fi.Mode(); {
518 if !cc.Authorize(accessDeleteFolder) {
519 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
522 case mode.IsRegular():
523 if !cc.Authorize(accessDeleteFile) {
524 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
529 if err := hlFile.delete(); err != nil {
533 res = append(res, cc.NewReply(t))
537 // HandleMoveFile moves files or folders. Note: seemingly not documented
538 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
539 fileName := string(t.GetField(fieldFileName).Data)
541 filePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
546 fileNewPath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFileNewPath).Data, nil)
551 cc.logger.Infow("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
553 hlFile, err := newFileWrapper(cc.Server.FS, filePath, 0)
558 fi, err := hlFile.dataFile()
560 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
566 switch mode := fi.Mode(); {
568 if !cc.Authorize(accessMoveFolder) {
569 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
572 case mode.IsRegular():
573 if !cc.Authorize(accessMoveFile) {
574 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
578 if err := hlFile.move(fileNewPath); err != nil {
581 // TODO: handle other possible errors; e.g. fileWrapper delete fails due to fileWrapper permission issue
583 res = append(res, cc.NewReply(t))
587 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
588 if !cc.Authorize(accessCreateFolder) {
589 res = append(res, cc.NewErrReply(t, "You are not allowed to create folders."))
592 folderName := string(t.GetField(fieldFileName).Data)
594 folderName = path.Join("/", folderName)
598 // fieldFilePath is only present for nested paths
599 if t.GetField(fieldFilePath).Data != nil {
601 _, err := newFp.Write(t.GetField(fieldFilePath).Data)
606 for _, pathItem := range newFp.Items {
607 subPath = filepath.Join("/", subPath, string(pathItem.Name))
610 newFolderPath := path.Join(cc.Server.Config.FileRoot, subPath, folderName)
612 // TODO: check path and folder name lengths
614 if _, err := cc.Server.FS.Stat(newFolderPath); !os.IsNotExist(err) {
615 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that name.", folderName)
616 return []Transaction{cc.NewErrReply(t, msg)}, nil
619 // TODO: check for disallowed characters to maintain compatibility for original client
621 if err := cc.Server.FS.Mkdir(newFolderPath, 0777); err != nil {
622 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
623 return []Transaction{cc.NewErrReply(t, msg)}, nil
626 res = append(res, cc.NewReply(t))
630 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
631 if !cc.Authorize(accessModifyUser) {
632 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
636 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
637 userName := string(t.GetField(fieldUserName).Data)
639 newAccessLvl := t.GetField(fieldUserAccess).Data
641 account := cc.Server.Accounts[login]
642 account.Name = userName
643 copy(account.Access[:], newAccessLvl)
645 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
646 // not include fieldUserPassword
647 if t.GetField(fieldUserPassword).Data == nil {
648 account.Password = hashAndSalt([]byte(""))
650 if len(t.GetField(fieldUserPassword).Data) > 1 {
651 account.Password = hashAndSalt(t.GetField(fieldUserPassword).Data)
654 out, err := yaml.Marshal(&account)
658 if err := os.WriteFile(filepath.Join(cc.Server.ConfigDir, "Users", login+".yaml"), out, 0666); err != nil {
662 // Notify connected clients logged in as the user of the new access level
663 for _, c := range cc.Server.Clients {
664 if c.Account.Login == login {
665 // Note: comment out these two lines to test server-side deny messages
666 newT := NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, newAccessLvl))
667 res = append(res, *newT)
669 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
670 if c.Authorize(accessDisconUser) {
671 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 1)
673 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 0)
675 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
677 c.Account.Access = account.Access
680 tranNotifyChangeUser,
681 NewField(fieldUserID, *c.ID),
682 NewField(fieldUserFlags, c.Flags),
683 NewField(fieldUserName, c.UserName),
684 NewField(fieldUserIconID, c.Icon),
689 res = append(res, cc.NewReply(t))
693 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
694 if !cc.Authorize(accessOpenUser) {
695 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
699 account := cc.Server.Accounts[string(t.GetField(fieldUserLogin).Data)]
701 res = append(res, cc.NewErrReply(t, "Account does not exist."))
705 res = append(res, cc.NewReply(t,
706 NewField(fieldUserName, []byte(account.Name)),
707 NewField(fieldUserLogin, negateString(t.GetField(fieldUserLogin).Data)),
708 NewField(fieldUserPassword, []byte(account.Password)),
709 NewField(fieldUserAccess, account.Access[:]),
714 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
715 if !cc.Authorize(accessOpenUser) {
716 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
720 var userFields []Field
721 for _, acc := range cc.Server.Accounts {
722 b := make([]byte, 0, 100)
723 n, err := acc.Read(b)
728 userFields = append(userFields, NewField(fieldData, b[:n]))
731 res = append(res, cc.NewReply(t, userFields...))
735 // HandleUpdateUser is used by the v1.5+ multi-user editor to perform account editing for multiple users at a time.
736 // An update can be a mix of these actions:
739 // * Modify user (including renaming the account login)
741 // The Transaction sent by the client includes one data field per user that was modified. This data field in turn
742 // contains another data field encoded in its payload with a varying number of sub fields depending on which action is
743 // performed. This seems to be the only place in the Hotline protocol where a data field contains another data field.
744 func HandleUpdateUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
745 for _, field := range t.Fields {
746 subFields, err := ReadFields(field.Data[0:2], field.Data[2:])
751 if len(subFields) == 1 {
752 login := DecodeUserString(getField(fieldData, &subFields).Data)
753 cc.logger.Infow("DeleteUser", "login", login)
755 if !cc.Authorize(accessDeleteUser) {
756 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
760 if err := cc.Server.DeleteUser(login); err != nil {
766 login := DecodeUserString(getField(fieldUserLogin, &subFields).Data)
768 // check if the login dataFile; if so, we know we are updating an existing user
769 if acc, ok := cc.Server.Accounts[login]; ok {
770 cc.logger.Infow("UpdateUser", "login", login)
772 // account dataFile, so this is an update action
773 if !cc.Authorize(accessModifyUser) {
774 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
778 if getField(fieldUserPassword, &subFields) != nil {
779 newPass := getField(fieldUserPassword, &subFields).Data
780 acc.Password = hashAndSalt(newPass)
782 acc.Password = hashAndSalt([]byte(""))
785 if getField(fieldUserAccess, &subFields) != nil {
786 copy(acc.Access[:], getField(fieldUserAccess, &subFields).Data)
789 err = cc.Server.UpdateUser(
790 DecodeUserString(getField(fieldData, &subFields).Data),
791 DecodeUserString(getField(fieldUserLogin, &subFields).Data),
792 string(getField(fieldUserName, &subFields).Data),
800 cc.logger.Infow("CreateUser", "login", login)
802 if !cc.Authorize(accessCreateUser) {
803 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
807 newAccess := accessBitmap{}
808 copy(newAccess[:], getField(fieldUserAccess, &subFields).Data[:])
810 // Prevent account from creating new account with greater permission
811 for i := 0; i < 64; i++ {
812 if newAccess.IsSet(i) {
813 if !cc.Authorize(i) {
814 return append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself.")), err
819 err := cc.Server.NewUser(login, string(getField(fieldUserName, &subFields).Data), string(getField(fieldUserPassword, &subFields).Data), newAccess)
821 return []Transaction{}, err
826 res = append(res, cc.NewReply(t))
830 // HandleNewUser creates a new user account
831 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
832 if !cc.Authorize(accessCreateUser) {
833 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
837 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
839 // If the account already dataFile, reply with an error
840 if _, ok := cc.Server.Accounts[login]; ok {
841 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
845 newAccess := accessBitmap{}
846 copy(newAccess[:], t.GetField(fieldUserAccess).Data[:])
848 // Prevent account from creating new account with greater permission
849 for i := 0; i < 64; i++ {
850 if newAccess.IsSet(i) {
851 if !cc.Authorize(i) {
852 res = append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself."))
858 if err := cc.Server.NewUser(login, string(t.GetField(fieldUserName).Data), string(t.GetField(fieldUserPassword).Data), newAccess); err != nil {
859 return []Transaction{}, err
862 res = append(res, cc.NewReply(t))
866 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
867 if !cc.Authorize(accessDeleteUser) {
868 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
872 // TODO: Handle case where account doesn't exist; e.g. delete race condition
873 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
875 if err := cc.Server.DeleteUser(login); err != nil {
879 res = append(res, cc.NewReply(t))
883 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
884 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
885 if !cc.Authorize(accessBroadcast) {
886 res = append(res, cc.NewErrReply(t, "You are not allowed to send broadcast messages."))
892 NewField(fieldData, t.GetField(tranGetMsgs).Data),
893 NewField(fieldChatOptions, []byte{0}),
896 res = append(res, cc.NewReply(t))
900 func byteToInt(bytes []byte) (int, error) {
903 return int(binary.BigEndian.Uint16(bytes)), nil
905 return int(binary.BigEndian.Uint32(bytes)), nil
908 return 0, errors.New("unknown byte length")
911 // HandleGetClientInfoText returns user information for the specific user.
913 // Fields used in the request:
916 // Fields used in the reply:
918 // 101 Data User info text string
919 func HandleGetClientInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
920 if !cc.Authorize(accessGetClientInfo) {
921 res = append(res, cc.NewErrReply(t, "You are not allowed to get client info."))
925 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
927 clientConn := cc.Server.Clients[uint16(clientID)]
928 if clientConn == nil {
929 return append(res, cc.NewErrReply(t, "User not found.")), err
932 res = append(res, cc.NewReply(t,
933 NewField(fieldData, []byte(clientConn.String())),
934 NewField(fieldUserName, clientConn.UserName),
939 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
940 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
945 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
948 if t.GetField(fieldUserName).Data != nil {
949 if cc.Authorize(accessAnyName) {
950 cc.UserName = t.GetField(fieldUserName).Data
952 cc.UserName = []byte(cc.Account.Name)
956 cc.Icon = t.GetField(fieldUserIconID).Data
958 cc.logger = cc.logger.With("name", string(cc.UserName))
959 cc.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(cc.Version); return i }()))
961 options := t.GetField(fieldOptions).Data
962 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
964 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
966 // Check refuse private PM option
967 if optBitmap.Bit(refusePM) == 1 {
968 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
969 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
972 // Check refuse private chat option
973 if optBitmap.Bit(refuseChat) == 1 {
974 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
975 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
978 // Check auto response
979 if optBitmap.Bit(autoResponse) == 1 {
980 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
982 cc.AutoReply = []byte{}
985 trans := cc.notifyOthers(
987 tranNotifyChangeUser, nil,
988 NewField(fieldUserName, cc.UserName),
989 NewField(fieldUserID, *cc.ID),
990 NewField(fieldUserIconID, cc.Icon),
991 NewField(fieldUserFlags, cc.Flags),
994 res = append(res, trans...)
996 if cc.Server.Config.BannerFile != "" {
997 res = append(res, *NewTransaction(tranServerBanner, cc.ID, NewField(fieldBannerType, []byte("JPEG"))))
1000 res = append(res, cc.NewReply(t))
1005 const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
1006 // "Mon, 02 Jan 2006 15:04:05 MST"
1008 const defaultNewsTemplate = `From %s (%s):
1012 __________________________________________________________`
1014 // HandleTranOldPostNews updates the flat news
1015 // Fields used in this request:
1017 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1018 if !cc.Authorize(accessNewsPostArt) {
1019 res = append(res, cc.NewErrReply(t, "You are not allowed to post news."))
1023 cc.Server.flatNewsMux.Lock()
1024 defer cc.Server.flatNewsMux.Unlock()
1026 newsDateTemplate := defaultNewsDateFormat
1027 if cc.Server.Config.NewsDateFormat != "" {
1028 newsDateTemplate = cc.Server.Config.NewsDateFormat
1031 newsTemplate := defaultNewsTemplate
1032 if cc.Server.Config.NewsDelimiter != "" {
1033 newsTemplate = cc.Server.Config.NewsDelimiter
1036 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
1037 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
1039 // update news in memory
1040 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
1042 // update news on disk
1043 if err := cc.Server.FS.WriteFile(filepath.Join(cc.Server.ConfigDir, "MessageBoard.txt"), cc.Server.FlatNews, 0644); err != nil {
1047 // Notify all clients of updated news
1050 NewField(fieldData, []byte(newsPost)),
1053 res = append(res, cc.NewReply(t))
1057 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1058 if !cc.Authorize(accessDisconUser) {
1059 res = append(res, cc.NewErrReply(t, "You are not allowed to disconnect users."))
1063 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
1065 if clientConn.Authorize(accessCannotBeDiscon) {
1066 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
1070 // If fieldOptions is set, then the client IP is banned in addition to disconnected.
1071 // 00 01 = temporary ban
1072 // 00 02 = permanent ban
1073 if t.GetField(fieldOptions).Data != nil {
1074 switch t.GetField(fieldOptions).Data[1] {
1076 // send message: "You are temporarily banned on this server"
1077 cc.logger.Infow("Disconnect & temporarily ban " + string(clientConn.UserName))
1079 res = append(res, *NewTransaction(
1082 NewField(fieldData, []byte("You are temporarily banned on this server")),
1083 NewField(fieldChatOptions, []byte{0, 0}),
1086 banUntil := time.Now().Add(tempBanDuration)
1087 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = &banUntil
1088 cc.Server.writeBanList()
1090 // send message: "You are permanently banned on this server"
1091 cc.logger.Infow("Disconnect & ban " + string(clientConn.UserName))
1093 res = append(res, *NewTransaction(
1096 NewField(fieldData, []byte("You are permanently banned on this server")),
1097 NewField(fieldChatOptions, []byte{0, 0}),
1100 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = nil
1101 cc.Server.writeBanList()
1105 // TODO: remove this awful hack
1107 time.Sleep(1 * time.Second)
1108 clientConn.Disconnect()
1111 return append(res, cc.NewReply(t)), err
1114 // HandleGetNewsCatNameList returns a list of news categories for a path
1115 // Fields used in the request:
1116 // 325 News path (Optional)
1117 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1118 if !cc.Authorize(accessNewsReadArt) {
1119 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1123 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1124 cats := cc.Server.GetNewsCatByPath(pathStrs)
1126 // To store the keys in slice in sorted order
1127 keys := make([]string, len(cats))
1129 for k := range cats {
1135 var fieldData []Field
1136 for _, k := range keys {
1138 b, _ := cat.MarshalBinary()
1139 fieldData = append(fieldData, NewField(
1140 fieldNewsCatListData15,
1145 res = append(res, cc.NewReply(t, fieldData...))
1149 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1150 if !cc.Authorize(accessNewsCreateCat) {
1151 res = append(res, cc.NewErrReply(t, "You are not allowed to create news categories."))
1155 name := string(t.GetField(fieldNewsCatName).Data)
1156 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1158 cats := cc.Server.GetNewsCatByPath(pathStrs)
1159 cats[name] = NewsCategoryListData15{
1162 Articles: map[uint32]*NewsArtData{},
1163 SubCats: make(map[string]NewsCategoryListData15),
1166 if err := cc.Server.writeThreadedNews(); err != nil {
1169 res = append(res, cc.NewReply(t))
1173 // Fields used in the request:
1174 // 322 News category name
1176 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1177 if !cc.Authorize(accessNewsCreateFldr) {
1178 res = append(res, cc.NewErrReply(t, "You are not allowed to create news folders."))
1182 name := string(t.GetField(fieldFileName).Data)
1183 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1185 cc.logger.Infof("Creating new news folder %s", name)
1187 cats := cc.Server.GetNewsCatByPath(pathStrs)
1188 cats[name] = NewsCategoryListData15{
1191 Articles: map[uint32]*NewsArtData{},
1192 SubCats: make(map[string]NewsCategoryListData15),
1194 if err := cc.Server.writeThreadedNews(); err != nil {
1197 res = append(res, cc.NewReply(t))
1201 // Fields used in the request:
1202 // 325 News path Optional
1205 // 321 News article list data Optional
1206 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1207 if !cc.Authorize(accessNewsReadArt) {
1208 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1211 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1213 var cat NewsCategoryListData15
1214 cats := cc.Server.ThreadedNews.Categories
1216 for _, fp := range pathStrs {
1218 cats = cats[fp].SubCats
1221 nald := cat.GetNewsArtListData()
1223 res = append(res, cc.NewReply(t, NewField(fieldNewsArtListData, nald.Payload())))
1227 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1228 if !cc.Authorize(accessNewsReadArt) {
1229 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1235 // 326 News article ID
1236 // 327 News article data flavor
1238 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1240 var cat NewsCategoryListData15
1241 cats := cc.Server.ThreadedNews.Categories
1243 for _, fp := range pathStrs {
1245 cats = cats[fp].SubCats
1247 newsArtID := t.GetField(fieldNewsArtID).Data
1249 convertedArtID := binary.BigEndian.Uint16(newsArtID)
1251 art := cat.Articles[uint32(convertedArtID)]
1253 res = append(res, cc.NewReply(t))
1258 // 328 News article title
1259 // 329 News article poster
1260 // 330 News article date
1261 // 331 Previous article ID
1262 // 332 Next article ID
1263 // 335 Parent article ID
1264 // 336 First child article ID
1265 // 327 News article data flavor "Should be “text/plain”
1266 // 333 News article data Optional (if data flavor is “text/plain”)
1268 res = append(res, cc.NewReply(t,
1269 NewField(fieldNewsArtTitle, []byte(art.Title)),
1270 NewField(fieldNewsArtPoster, []byte(art.Poster)),
1271 NewField(fieldNewsArtDate, art.Date),
1272 NewField(fieldNewsArtPrevArt, art.PrevArt),
1273 NewField(fieldNewsArtNextArt, art.NextArt),
1274 NewField(fieldNewsArtParentArt, art.ParentArt),
1275 NewField(fieldNewsArt1stChildArt, art.FirstChildArt),
1276 NewField(fieldNewsArtDataFlav, []byte("text/plain")),
1277 NewField(fieldNewsArtData, []byte(art.Data)),
1282 // HandleDelNewsItem deletes an existing threaded news folder or category from the server.
1283 // Fields used in the request:
1285 // Fields used in the reply:
1287 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1288 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1290 cats := cc.Server.ThreadedNews.Categories
1291 delName := pathStrs[len(pathStrs)-1]
1292 if len(pathStrs) > 1 {
1293 for _, fp := range pathStrs[0 : len(pathStrs)-1] {
1294 cats = cats[fp].SubCats
1298 if bytes.Equal(cats[delName].Type, []byte{0, 3}) {
1299 if !cc.Authorize(accessNewsDeleteCat) {
1300 return append(res, cc.NewErrReply(t, "You are not allowed to delete news categories.")), nil
1303 if !cc.Authorize(accessNewsDeleteFldr) {
1304 return append(res, cc.NewErrReply(t, "You are not allowed to delete news folders.")), nil
1308 delete(cats, delName)
1310 if err := cc.Server.writeThreadedNews(); err != nil {
1314 return append(res, cc.NewReply(t)), nil
1317 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1318 if !cc.Authorize(accessNewsDeleteArt) {
1319 res = append(res, cc.NewErrReply(t, "You are not allowed to delete news articles."))
1325 // 326 News article ID
1326 // 337 News article – recursive delete Delete child articles (1) or not (0)
1327 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1328 ID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1330 // TODO: Delete recursive
1331 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1333 catName := pathStrs[len(pathStrs)-1]
1334 cat := cats[catName]
1336 delete(cat.Articles, uint32(ID))
1339 if err := cc.Server.writeThreadedNews(); err != nil {
1343 res = append(res, cc.NewReply(t))
1349 // 326 News article ID ID of the parent article?
1350 // 328 News article title
1351 // 334 News article flags
1352 // 327 News article data flavor Currently “text/plain”
1353 // 333 News article data
1354 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1355 if !cc.Authorize(accessNewsPostArt) {
1356 res = append(res, cc.NewErrReply(t, "You are not allowed to post news articles."))
1360 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1361 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1363 catName := pathStrs[len(pathStrs)-1]
1364 cat := cats[catName]
1366 newArt := NewsArtData{
1367 Title: string(t.GetField(fieldNewsArtTitle).Data),
1368 Poster: string(cc.UserName),
1369 Date: toHotlineTime(time.Now()),
1370 PrevArt: []byte{0, 0, 0, 0},
1371 NextArt: []byte{0, 0, 0, 0},
1372 ParentArt: append([]byte{0, 0}, t.GetField(fieldNewsArtID).Data...),
1373 FirstChildArt: []byte{0, 0, 0, 0},
1374 DataFlav: []byte("text/plain"),
1375 Data: string(t.GetField(fieldNewsArtData).Data),
1379 for k := range cat.Articles {
1380 keys = append(keys, int(k))
1386 prevID := uint32(keys[len(keys)-1])
1389 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1391 // Set next article ID
1392 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1395 // Update parent article with first child reply
1396 parentID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1398 parentArt := cat.Articles[uint32(parentID)]
1400 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1401 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1405 cat.Articles[nextID] = &newArt
1408 if err := cc.Server.writeThreadedNews(); err != nil {
1412 res = append(res, cc.NewReply(t))
1416 // HandleGetMsgs returns the flat news data
1417 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1418 if !cc.Authorize(accessNewsReadArt) {
1419 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1423 res = append(res, cc.NewReply(t, NewField(fieldData, cc.Server.FlatNews)))
1428 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1429 if !cc.Authorize(accessDownloadFile) {
1430 res = append(res, cc.NewErrReply(t, "You are not allowed to download files."))
1434 fileName := t.GetField(fieldFileName).Data
1435 filePath := t.GetField(fieldFilePath).Data
1436 resumeData := t.GetField(fieldFileResumeData).Data
1438 var dataOffset int64
1439 var frd FileResumeData
1440 if resumeData != nil {
1441 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1444 // TODO: handle rsrc fork offset
1445 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1448 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1453 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, dataOffset)
1458 xferSize := hlFile.ffo.TransferSize(0)
1460 ft := cc.newFileTransfer(FileDownload, fileName, filePath, xferSize)
1462 // TODO: refactor to remove this
1463 if resumeData != nil {
1464 var frd FileResumeData
1465 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1468 ft.fileResumeData = &frd
1471 // Optional field for when a HL v1.5+ client requests file preview
1472 // Used only for TEXT, JPEG, GIFF, BMP or PICT files
1473 // The value will always be 2
1474 if t.GetField(fieldFileTransferOptions).Data != nil {
1475 ft.options = t.GetField(fieldFileTransferOptions).Data
1476 xferSize = hlFile.ffo.FlatFileDataForkHeader.DataSize[:]
1479 res = append(res, cc.NewReply(t,
1480 NewField(fieldRefNum, ft.refNum[:]),
1481 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1482 NewField(fieldTransferSize, xferSize),
1483 NewField(fieldFileSize, hlFile.ffo.FlatFileDataForkHeader.DataSize[:]),
1489 // Download all files from the specified folder and sub-folders
1490 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1491 if !cc.Authorize(accessDownloadFile) {
1492 res = append(res, cc.NewErrReply(t, "You are not allowed to download folders."))
1496 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
1501 transferSize, err := CalcTotalSize(fullFilePath)
1505 itemCount, err := CalcItemCount(fullFilePath)
1510 fileTransfer := cc.newFileTransfer(FolderDownload, t.GetField(fieldFileName).Data, t.GetField(fieldFilePath).Data, transferSize)
1513 _, err = fp.Write(t.GetField(fieldFilePath).Data)
1518 res = append(res, cc.NewReply(t,
1519 NewField(fieldRefNum, fileTransfer.ReferenceNumber),
1520 NewField(fieldTransferSize, transferSize),
1521 NewField(fieldFolderItemCount, itemCount),
1522 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1527 // Upload all files from the local folder and its subfolders to the specified path on the server
1528 // Fields used in the request
1531 // 108 transfer size Total size of all items in the folder
1532 // 220 Folder item count
1533 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1534 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1536 if t.GetField(fieldFilePath).Data != nil {
1537 if _, err = fp.Write(t.GetField(fieldFilePath).Data); err != nil {
1542 // Handle special cases for Upload and Drop Box folders
1543 if !cc.Authorize(accessUploadAnywhere) {
1544 if !fp.IsUploadDir() && !fp.IsDropbox() {
1545 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))))
1550 fileTransfer := cc.newFileTransfer(FolderUpload,
1551 t.GetField(fieldFileName).Data,
1552 t.GetField(fieldFilePath).Data,
1553 t.GetField(fieldTransferSize).Data,
1556 fileTransfer.FolderItemCount = t.GetField(fieldFolderItemCount).Data
1558 res = append(res, cc.NewReply(t, NewField(fieldRefNum, fileTransfer.ReferenceNumber)))
1563 // Fields used in the request:
1566 // 204 File transfer options "Optional
1567 // Used only to resume download, currently has value 2"
1568 // 108 File transfer size "Optional used if download is not resumed"
1569 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1570 if !cc.Authorize(accessUploadFile) {
1571 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1575 fileName := t.GetField(fieldFileName).Data
1576 filePath := t.GetField(fieldFilePath).Data
1577 transferOptions := t.GetField(fieldFileTransferOptions).Data
1578 transferSize := t.GetField(fieldTransferSize).Data // not sent for resume
1581 if filePath != nil {
1582 if _, err = fp.Write(filePath); err != nil {
1587 // Handle special cases for Upload and Drop Box folders
1588 if !cc.Authorize(accessUploadAnywhere) {
1589 if !fp.IsUploadDir() && !fp.IsDropbox() {
1590 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))))
1594 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1599 if _, err := cc.Server.FS.Stat(fullFilePath); err == nil {
1600 res = append(res, cc.NewErrReply(t, fmt.Sprintf("Cannot accept upload because there is already a file named \"%v\". Try choosing a different name.", string(fileName))))
1604 ft := cc.newFileTransfer(FileUpload, fileName, filePath, transferSize)
1606 replyT := cc.NewReply(t, NewField(fieldRefNum, ft.ReferenceNumber))
1608 // client has requested to resume a partially transferred file
1609 if transferOptions != nil {
1611 fileInfo, err := cc.Server.FS.Stat(fullFilePath + incompleteFileSuffix)
1616 offset := make([]byte, 4)
1617 binary.BigEndian.PutUint32(offset, uint32(fileInfo.Size()))
1619 fileResumeData := NewFileResumeData([]ForkInfoList{
1620 *NewForkInfoList(offset),
1623 b, _ := fileResumeData.BinaryMarshal()
1625 ft.TransferSize = offset
1627 replyT.Fields = append(replyT.Fields, NewField(fieldFileResumeData, b))
1630 res = append(res, replyT)
1634 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1635 if len(t.GetField(fieldUserIconID).Data) == 4 {
1636 cc.Icon = t.GetField(fieldUserIconID).Data[2:]
1638 cc.Icon = t.GetField(fieldUserIconID).Data
1640 if cc.Authorize(accessAnyName) {
1641 cc.UserName = t.GetField(fieldUserName).Data
1644 // the options field is only passed by the client versions > 1.2.3.
1645 options := t.GetField(fieldOptions).Data
1647 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1648 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
1650 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, optBitmap.Bit(refusePM))
1651 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1653 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, optBitmap.Bit(refuseChat))
1654 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1656 // Check auto response
1657 if optBitmap.Bit(autoResponse) == 1 {
1658 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
1660 cc.AutoReply = []byte{}
1664 for _, c := range sortedClients(cc.Server.Clients) {
1665 res = append(res, *NewTransaction(
1666 tranNotifyChangeUser,
1668 NewField(fieldUserID, *cc.ID),
1669 NewField(fieldUserIconID, cc.Icon),
1670 NewField(fieldUserFlags, cc.Flags),
1671 NewField(fieldUserName, cc.UserName),
1678 // HandleKeepAlive responds to keepalive transactions with an empty reply
1679 // * HL 1.9.2 Client sends keepalive msg every 3 minutes
1680 // * HL 1.2.3 Client doesn't send keepalives
1681 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1682 res = append(res, cc.NewReply(t))
1687 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1688 fullPath, err := readPath(
1689 cc.Server.Config.FileRoot,
1690 t.GetField(fieldFilePath).Data,
1698 if t.GetField(fieldFilePath).Data != nil {
1699 if _, err = fp.Write(t.GetField(fieldFilePath).Data); err != nil {
1704 // Handle special case for drop box folders
1705 if fp.IsDropbox() && !cc.Authorize(accessViewDropBoxes) {
1706 res = append(res, cc.NewErrReply(t, "You are not allowed to view drop boxes."))
1710 fileNames, err := getFileNameList(fullPath, cc.Server.Config.IgnoreFiles)
1715 res = append(res, cc.NewReply(t, fileNames...))
1720 // =================================
1721 // Hotline private chat flow
1722 // =================================
1723 // 1. ClientA sends tranInviteNewChat to server with user ID to invite
1724 // 2. Server creates new ChatID
1725 // 3. Server sends tranInviteToChat to invitee
1726 // 4. Server replies to ClientA with new Chat ID
1728 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1729 // If Accepted is clicked:
1730 // 1. ClientB sends tranJoinChat with fieldChatID
1732 // HandleInviteNewChat invites users to new private chat
1733 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1734 if !cc.Authorize(accessOpenChat) {
1735 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1740 targetID := t.GetField(fieldUserID).Data
1741 newChatID := cc.Server.NewPrivateChat(cc)
1743 // Check if target user has "Refuse private chat" flag
1744 binary.BigEndian.Uint16(targetID)
1745 targetClient := cc.Server.Clients[binary.BigEndian.Uint16(targetID)]
1747 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(targetClient.Flags)))
1748 if flagBitmap.Bit(userFLagRefusePChat) == 1 {
1753 NewField(fieldData, []byte(string(targetClient.UserName)+" does not accept private chats.")),
1754 NewField(fieldUserName, targetClient.UserName),
1755 NewField(fieldUserID, *targetClient.ID),
1756 NewField(fieldOptions, []byte{0, 2}),
1764 NewField(fieldChatID, newChatID),
1765 NewField(fieldUserName, cc.UserName),
1766 NewField(fieldUserID, *cc.ID),
1773 NewField(fieldChatID, newChatID),
1774 NewField(fieldUserName, cc.UserName),
1775 NewField(fieldUserID, *cc.ID),
1776 NewField(fieldUserIconID, cc.Icon),
1777 NewField(fieldUserFlags, cc.Flags),
1784 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1785 if !cc.Authorize(accessOpenChat) {
1786 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1791 targetID := t.GetField(fieldUserID).Data
1792 chatID := t.GetField(fieldChatID).Data
1798 NewField(fieldChatID, chatID),
1799 NewField(fieldUserName, cc.UserName),
1800 NewField(fieldUserID, *cc.ID),
1806 NewField(fieldChatID, chatID),
1807 NewField(fieldUserName, cc.UserName),
1808 NewField(fieldUserID, *cc.ID),
1809 NewField(fieldUserIconID, cc.Icon),
1810 NewField(fieldUserFlags, cc.Flags),
1817 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1818 chatID := t.GetField(fieldChatID).Data
1819 chatInt := binary.BigEndian.Uint32(chatID)
1821 privChat := cc.Server.PrivateChats[chatInt]
1823 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1825 for _, c := range sortedClients(privChat.ClientConn) {
1830 NewField(fieldChatID, chatID),
1831 NewField(fieldData, resMsg),
1839 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1840 // Fields used in the reply:
1841 // * 115 Chat subject
1842 // * 300 User name with info (Optional)
1843 // * 300 (more user names with info)
1844 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1845 chatID := t.GetField(fieldChatID).Data
1846 chatInt := binary.BigEndian.Uint32(chatID)
1848 privChat := cc.Server.PrivateChats[chatInt]
1850 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1851 for _, c := range sortedClients(privChat.ClientConn) {
1854 tranNotifyChatChangeUser,
1856 NewField(fieldChatID, chatID),
1857 NewField(fieldUserName, cc.UserName),
1858 NewField(fieldUserID, *cc.ID),
1859 NewField(fieldUserIconID, cc.Icon),
1860 NewField(fieldUserFlags, cc.Flags),
1865 privChat.ClientConn[cc.uint16ID()] = cc
1867 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1868 for _, c := range sortedClients(privChat.ClientConn) {
1873 Name: string(c.UserName),
1876 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1879 res = append(res, cc.NewReply(t, replyFields...))
1883 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1884 // Fields used in the request:
1885 // * 114 fieldChatID
1886 // Reply is not expected.
1887 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1888 chatID := t.GetField(fieldChatID).Data
1889 chatInt := binary.BigEndian.Uint32(chatID)
1891 privChat, ok := cc.Server.PrivateChats[chatInt]
1896 delete(privChat.ClientConn, cc.uint16ID())
1898 // Notify members of the private chat that the user has left
1899 for _, c := range sortedClients(privChat.ClientConn) {
1902 tranNotifyChatDeleteUser,
1904 NewField(fieldChatID, chatID),
1905 NewField(fieldUserID, *cc.ID),
1913 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1914 // Fields used in the request:
1916 // * 115 Chat subject Chat subject string
1917 // Reply is not expected.
1918 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1919 chatID := t.GetField(fieldChatID).Data
1920 chatInt := binary.BigEndian.Uint32(chatID)
1922 privChat := cc.Server.PrivateChats[chatInt]
1923 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1925 for _, c := range sortedClients(privChat.ClientConn) {
1928 tranNotifyChatSubject,
1930 NewField(fieldChatID, chatID),
1931 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),
1939 // HandleMakeAlias makes a filer alias using the specified path.
1940 // Fields used in the request:
1943 // 212 File new path Destination path
1945 // Fields used in the reply:
1947 func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1948 if !cc.Authorize(accessMakeAlias) {
1949 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
1952 fileName := t.GetField(fieldFileName).Data
1953 filePath := t.GetField(fieldFilePath).Data
1954 fileNewPath := t.GetField(fieldFileNewPath).Data
1956 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1961 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
1966 cc.logger.Debugw("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
1968 if err := cc.Server.FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
1969 res = append(res, cc.NewErrReply(t, "Error creating alias"))
1973 res = append(res, cc.NewReply(t))
1977 // HandleDownloadBanner handles requests for a new banner from the server
1978 // Fields used in the request:
1980 // Fields used in the reply:
1981 // 107 fieldRefNum Used later for transfer
1982 // 108 fieldTransferSize Size of data to be downloaded
1983 func HandleDownloadBanner(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1984 fi, err := cc.Server.FS.Stat(filepath.Join(cc.Server.ConfigDir, cc.Server.Config.BannerFile))
1989 ft := cc.newFileTransfer(bannerDownload, []byte{}, []byte{}, make([]byte, 4))
1991 binary.BigEndian.PutUint32(ft.TransferSize, uint32(fi.Size()))
1993 res = append(res, cc.NewReply(t,
1994 NewField(fieldRefNum, ft.refNum[:]),
1995 NewField(fieldTransferSize, ft.TransferSize),