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 in the transaction payload
252 if t.GetField(fieldChatOptions).Data != nil {
253 formattedMsg = fmt.Sprintf("\r*** %s %s", cc.UserName, t.GetField(fieldData).Data)
256 // The ChatID field is used to identify messages as belonging to a private chat.
257 // All clients *except* Frogblast omit this field for public chat, but Frogblast sends a value of 00 00 00 00.
258 chatID := t.GetField(fieldChatID).Data
259 if chatID != nil && !bytes.Equal([]byte{0, 0, 0, 0}, chatID) {
260 chatInt := binary.BigEndian.Uint32(chatID)
261 privChat := cc.Server.PrivateChats[chatInt]
263 clients := sortedClients(privChat.ClientConn)
265 // send the message to all connected clients of the private chat
266 for _, c := range clients {
267 res = append(res, *NewTransaction(
270 NewField(fieldChatID, chatID),
271 NewField(fieldData, []byte(formattedMsg)),
277 for _, c := range sortedClients(cc.Server.Clients) {
278 // Filter out clients that do not have the read chat permission
279 if c.Authorize(accessReadChat) {
280 res = append(res, *NewTransaction(tranChatMsg, c.ID, NewField(fieldData, []byte(formattedMsg))))
287 // HandleSendInstantMsg sends instant message to the user on the current server.
288 // Fields used in the request:
291 // One of the following values:
292 // - User message (myOpt_UserMessage = 1)
293 // - Refuse message (myOpt_RefuseMessage = 2)
294 // - Refuse chat (myOpt_RefuseChat = 3)
295 // - Automatic response (myOpt_AutomaticResponse = 4)"
297 // 214 Quoting message Optional
299 // Fields used in the reply:
301 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
302 if !cc.Authorize(accessSendPrivMsg) {
303 res = append(res, cc.NewErrReply(t, "You are not allowed to send private messages."))
307 msg := t.GetField(fieldData)
308 ID := t.GetField(fieldUserID)
310 reply := NewTransaction(
313 NewField(fieldData, msg.Data),
314 NewField(fieldUserName, cc.UserName),
315 NewField(fieldUserID, *cc.ID),
316 NewField(fieldOptions, []byte{0, 1}),
319 // Later versions of Hotline include the original message in the fieldQuotingMsg field so
320 // the receiving client can display both the received message and what it is in reply to
321 if t.GetField(fieldQuotingMsg).Data != nil {
322 reply.Fields = append(reply.Fields, NewField(fieldQuotingMsg, t.GetField(fieldQuotingMsg).Data))
325 id, _ := byteToInt(ID.Data)
326 otherClient, ok := cc.Server.Clients[uint16(id)]
328 return res, errors.New("invalid client ID")
331 // Check if target user has "Refuse private messages" flag
332 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(otherClient.Flags)))
333 if flagBitmap.Bit(userFLagRefusePChat) == 1 {
338 NewField(fieldData, []byte(string(otherClient.UserName)+" does not accept private messages.")),
339 NewField(fieldUserName, otherClient.UserName),
340 NewField(fieldUserID, *otherClient.ID),
341 NewField(fieldOptions, []byte{0, 2}),
345 res = append(res, *reply)
348 // Respond with auto reply if other client has it enabled
349 if len(otherClient.AutoReply) > 0 {
354 NewField(fieldData, otherClient.AutoReply),
355 NewField(fieldUserName, otherClient.UserName),
356 NewField(fieldUserID, *otherClient.ID),
357 NewField(fieldOptions, []byte{0, 1}),
362 res = append(res, cc.NewReply(t))
367 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
368 fileName := t.GetField(fieldFileName).Data
369 filePath := t.GetField(fieldFilePath).Data
371 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
376 fw, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
381 res = append(res, cc.NewReply(t,
382 NewField(fieldFileName, []byte(fw.name)),
383 NewField(fieldFileTypeString, fw.ffo.FlatFileInformationFork.friendlyType()),
384 NewField(fieldFileCreatorString, fw.ffo.FlatFileInformationFork.friendlyCreator()),
385 NewField(fieldFileComment, fw.ffo.FlatFileInformationFork.Comment),
386 NewField(fieldFileType, fw.ffo.FlatFileInformationFork.TypeSignature),
387 NewField(fieldFileCreateDate, fw.ffo.FlatFileInformationFork.CreateDate),
388 NewField(fieldFileModifyDate, fw.ffo.FlatFileInformationFork.ModifyDate),
389 NewField(fieldFileSize, fw.totalSize()),
394 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
395 // Fields used in the request:
397 // * 202 File path Optional
398 // * 211 File new name Optional
399 // * 210 File comment Optional
400 // Fields used in the reply: None
401 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
402 fileName := t.GetField(fieldFileName).Data
403 filePath := t.GetField(fieldFilePath).Data
405 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
410 fi, err := cc.Server.FS.Stat(fullFilePath)
415 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
419 if t.GetField(fieldFileComment).Data != nil {
420 switch mode := fi.Mode(); {
422 if !cc.Authorize(accessSetFolderComment) {
423 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for folders."))
426 case mode.IsRegular():
427 if !cc.Authorize(accessSetFileComment) {
428 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for files."))
433 if err := hlFile.ffo.FlatFileInformationFork.setComment(t.GetField(fieldFileComment).Data); err != nil {
436 w, err := hlFile.infoForkWriter()
440 _, err = w.Write(hlFile.ffo.FlatFileInformationFork.MarshalBinary())
446 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, t.GetField(fieldFileNewName).Data)
451 fileNewName := t.GetField(fieldFileNewName).Data
453 if fileNewName != nil {
454 switch mode := fi.Mode(); {
456 if !cc.Authorize(accessRenameFolder) {
457 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
460 err = os.Rename(fullFilePath, fullNewFilePath)
461 if os.IsNotExist(err) {
462 res = append(res, cc.NewErrReply(t, "Cannot rename folder "+string(fileName)+" because it does not exist or cannot be found."))
465 case mode.IsRegular():
466 if !cc.Authorize(accessRenameFile) {
467 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
470 fileDir, err := readPath(cc.Server.Config.FileRoot, filePath, []byte{})
474 hlFile.name = string(fileNewName)
475 err = hlFile.move(fileDir)
476 if os.IsNotExist(err) {
477 res = append(res, cc.NewErrReply(t, "Cannot rename file "+string(fileName)+" because it does not exist or cannot be found."))
486 res = append(res, cc.NewReply(t))
490 // HandleDeleteFile deletes a file or folder
491 // Fields used in the request:
494 // Fields used in the reply: none
495 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
496 fileName := t.GetField(fieldFileName).Data
497 filePath := t.GetField(fieldFilePath).Data
499 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
504 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
509 fi, err := hlFile.dataFile()
511 res = append(res, cc.NewErrReply(t, "Cannot delete file "+string(fileName)+" because it does not exist or cannot be found."))
515 switch mode := fi.Mode(); {
517 if !cc.Authorize(accessDeleteFolder) {
518 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
521 case mode.IsRegular():
522 if !cc.Authorize(accessDeleteFile) {
523 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
528 if err := hlFile.delete(); err != nil {
532 res = append(res, cc.NewReply(t))
536 // HandleMoveFile moves files or folders. Note: seemingly not documented
537 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
538 fileName := string(t.GetField(fieldFileName).Data)
540 filePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
545 fileNewPath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFileNewPath).Data, nil)
550 cc.logger.Infow("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
552 hlFile, err := newFileWrapper(cc.Server.FS, filePath, 0)
557 fi, err := hlFile.dataFile()
559 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
565 switch mode := fi.Mode(); {
567 if !cc.Authorize(accessMoveFolder) {
568 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
571 case mode.IsRegular():
572 if !cc.Authorize(accessMoveFile) {
573 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
577 if err := hlFile.move(fileNewPath); err != nil {
580 // TODO: handle other possible errors; e.g. fileWrapper delete fails due to fileWrapper permission issue
582 res = append(res, cc.NewReply(t))
586 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
587 if !cc.Authorize(accessCreateFolder) {
588 res = append(res, cc.NewErrReply(t, "You are not allowed to create folders."))
591 folderName := string(t.GetField(fieldFileName).Data)
593 folderName = path.Join("/", folderName)
597 // fieldFilePath is only present for nested paths
598 if t.GetField(fieldFilePath).Data != nil {
600 _, err := newFp.Write(t.GetField(fieldFilePath).Data)
605 for _, pathItem := range newFp.Items {
606 subPath = filepath.Join("/", subPath, string(pathItem.Name))
609 newFolderPath := path.Join(cc.Server.Config.FileRoot, subPath, folderName)
611 // TODO: check path and folder name lengths
613 if _, err := cc.Server.FS.Stat(newFolderPath); !os.IsNotExist(err) {
614 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that name.", folderName)
615 return []Transaction{cc.NewErrReply(t, msg)}, nil
618 // TODO: check for disallowed characters to maintain compatibility for original client
620 if err := cc.Server.FS.Mkdir(newFolderPath, 0777); err != nil {
621 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
622 return []Transaction{cc.NewErrReply(t, msg)}, nil
625 res = append(res, cc.NewReply(t))
629 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
630 if !cc.Authorize(accessModifyUser) {
631 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
635 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
636 userName := string(t.GetField(fieldUserName).Data)
638 newAccessLvl := t.GetField(fieldUserAccess).Data
640 account := cc.Server.Accounts[login]
641 account.Name = userName
642 copy(account.Access[:], newAccessLvl)
644 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
645 // not include fieldUserPassword
646 if t.GetField(fieldUserPassword).Data == nil {
647 account.Password = hashAndSalt([]byte(""))
649 if len(t.GetField(fieldUserPassword).Data) > 1 {
650 account.Password = hashAndSalt(t.GetField(fieldUserPassword).Data)
653 out, err := yaml.Marshal(&account)
657 if err := os.WriteFile(filepath.Join(cc.Server.ConfigDir, "Users", login+".yaml"), out, 0666); err != nil {
661 // Notify connected clients logged in as the user of the new access level
662 for _, c := range cc.Server.Clients {
663 if c.Account.Login == login {
664 // Note: comment out these two lines to test server-side deny messages
665 newT := NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, newAccessLvl))
666 res = append(res, *newT)
668 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
669 if c.Authorize(accessDisconUser) {
670 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 1)
672 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 0)
674 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
676 c.Account.Access = account.Access
679 tranNotifyChangeUser,
680 NewField(fieldUserID, *c.ID),
681 NewField(fieldUserFlags, c.Flags),
682 NewField(fieldUserName, c.UserName),
683 NewField(fieldUserIconID, c.Icon),
688 res = append(res, cc.NewReply(t))
692 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
693 if !cc.Authorize(accessOpenUser) {
694 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
698 account := cc.Server.Accounts[string(t.GetField(fieldUserLogin).Data)]
700 res = append(res, cc.NewErrReply(t, "Account does not exist."))
704 res = append(res, cc.NewReply(t,
705 NewField(fieldUserName, []byte(account.Name)),
706 NewField(fieldUserLogin, negateString(t.GetField(fieldUserLogin).Data)),
707 NewField(fieldUserPassword, []byte(account.Password)),
708 NewField(fieldUserAccess, account.Access[:]),
713 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
714 if !cc.Authorize(accessOpenUser) {
715 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
719 var userFields []Field
720 for _, acc := range cc.Server.Accounts {
721 b := make([]byte, 0, 100)
722 n, err := acc.Read(b)
727 userFields = append(userFields, NewField(fieldData, b[:n]))
730 res = append(res, cc.NewReply(t, userFields...))
734 // HandleUpdateUser is used by the v1.5+ multi-user editor to perform account editing for multiple users at a time.
735 // An update can be a mix of these actions:
738 // * Modify user (including renaming the account login)
740 // The Transaction sent by the client includes one data field per user that was modified. This data field in turn
741 // contains another data field encoded in its payload with a varying number of sub fields depending on which action is
742 // performed. This seems to be the only place in the Hotline protocol where a data field contains another data field.
743 func HandleUpdateUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
744 for _, field := range t.Fields {
745 subFields, err := ReadFields(field.Data[0:2], field.Data[2:])
750 if len(subFields) == 1 {
751 login := DecodeUserString(getField(fieldData, &subFields).Data)
752 cc.logger.Infow("DeleteUser", "login", login)
754 if !cc.Authorize(accessDeleteUser) {
755 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
759 if err := cc.Server.DeleteUser(login); err != nil {
765 login := DecodeUserString(getField(fieldUserLogin, &subFields).Data)
767 // check if the login dataFile; if so, we know we are updating an existing user
768 if acc, ok := cc.Server.Accounts[login]; ok {
769 cc.logger.Infow("UpdateUser", "login", login)
771 // account dataFile, so this is an update action
772 if !cc.Authorize(accessModifyUser) {
773 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
777 if getField(fieldUserPassword, &subFields) != nil {
778 newPass := getField(fieldUserPassword, &subFields).Data
779 acc.Password = hashAndSalt(newPass)
781 acc.Password = hashAndSalt([]byte(""))
784 if getField(fieldUserAccess, &subFields) != nil {
785 copy(acc.Access[:], getField(fieldUserAccess, &subFields).Data)
788 err = cc.Server.UpdateUser(
789 DecodeUserString(getField(fieldData, &subFields).Data),
790 DecodeUserString(getField(fieldUserLogin, &subFields).Data),
791 string(getField(fieldUserName, &subFields).Data),
799 cc.logger.Infow("CreateUser", "login", login)
801 if !cc.Authorize(accessCreateUser) {
802 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
806 newAccess := accessBitmap{}
807 copy(newAccess[:], getField(fieldUserAccess, &subFields).Data[:])
809 // Prevent account from creating new account with greater permission
810 for i := 0; i < 64; i++ {
811 if newAccess.IsSet(i) {
812 if !cc.Authorize(i) {
813 return append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself.")), err
818 err := cc.Server.NewUser(login, string(getField(fieldUserName, &subFields).Data), string(getField(fieldUserPassword, &subFields).Data), newAccess)
820 return []Transaction{}, err
825 res = append(res, cc.NewReply(t))
829 // HandleNewUser creates a new user account
830 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
831 if !cc.Authorize(accessCreateUser) {
832 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
836 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
838 // If the account already dataFile, reply with an error
839 if _, ok := cc.Server.Accounts[login]; ok {
840 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
844 newAccess := accessBitmap{}
845 copy(newAccess[:], t.GetField(fieldUserAccess).Data[:])
847 // Prevent account from creating new account with greater permission
848 for i := 0; i < 64; i++ {
849 if newAccess.IsSet(i) {
850 if !cc.Authorize(i) {
851 res = append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself."))
857 if err := cc.Server.NewUser(login, string(t.GetField(fieldUserName).Data), string(t.GetField(fieldUserPassword).Data), newAccess); err != nil {
858 return []Transaction{}, err
861 res = append(res, cc.NewReply(t))
865 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
866 if !cc.Authorize(accessDeleteUser) {
867 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
871 // TODO: Handle case where account doesn't exist; e.g. delete race condition
872 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
874 if err := cc.Server.DeleteUser(login); err != nil {
878 res = append(res, cc.NewReply(t))
882 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
883 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
884 if !cc.Authorize(accessBroadcast) {
885 res = append(res, cc.NewErrReply(t, "You are not allowed to send broadcast messages."))
891 NewField(fieldData, t.GetField(tranGetMsgs).Data),
892 NewField(fieldChatOptions, []byte{0}),
895 res = append(res, cc.NewReply(t))
899 func byteToInt(bytes []byte) (int, error) {
902 return int(binary.BigEndian.Uint16(bytes)), nil
904 return int(binary.BigEndian.Uint32(bytes)), nil
907 return 0, errors.New("unknown byte length")
910 // HandleGetClientInfoText returns user information for the specific user.
912 // Fields used in the request:
915 // Fields used in the reply:
917 // 101 Data User info text string
918 func HandleGetClientInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
919 if !cc.Authorize(accessGetClientInfo) {
920 res = append(res, cc.NewErrReply(t, "You are not allowed to get client info."))
924 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
926 clientConn := cc.Server.Clients[uint16(clientID)]
927 if clientConn == nil {
928 return append(res, cc.NewErrReply(t, "User not found.")), err
931 res = append(res, cc.NewReply(t,
932 NewField(fieldData, []byte(clientConn.String())),
933 NewField(fieldUserName, clientConn.UserName),
938 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
939 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
944 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
947 if t.GetField(fieldUserName).Data != nil {
948 if cc.Authorize(accessAnyName) {
949 cc.UserName = t.GetField(fieldUserName).Data
951 cc.UserName = []byte(cc.Account.Name)
955 cc.Icon = t.GetField(fieldUserIconID).Data
957 cc.logger = cc.logger.With("name", string(cc.UserName))
958 cc.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(cc.Version); return i }()))
960 options := t.GetField(fieldOptions).Data
961 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
963 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
965 // Check refuse private PM option
966 if optBitmap.Bit(refusePM) == 1 {
967 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
968 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
971 // Check refuse private chat option
972 if optBitmap.Bit(refuseChat) == 1 {
973 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
974 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
977 // Check auto response
978 if optBitmap.Bit(autoResponse) == 1 {
979 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
981 cc.AutoReply = []byte{}
984 trans := cc.notifyOthers(
986 tranNotifyChangeUser, nil,
987 NewField(fieldUserName, cc.UserName),
988 NewField(fieldUserID, *cc.ID),
989 NewField(fieldUserIconID, cc.Icon),
990 NewField(fieldUserFlags, cc.Flags),
993 res = append(res, trans...)
995 if cc.Server.Config.BannerFile != "" {
996 res = append(res, *NewTransaction(tranServerBanner, cc.ID, NewField(fieldBannerType, []byte("JPEG"))))
999 res = append(res, cc.NewReply(t))
1004 const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
1005 // "Mon, 02 Jan 2006 15:04:05 MST"
1007 const defaultNewsTemplate = `From %s (%s):
1011 __________________________________________________________`
1013 // HandleTranOldPostNews updates the flat news
1014 // Fields used in this request:
1016 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1017 if !cc.Authorize(accessNewsPostArt) {
1018 res = append(res, cc.NewErrReply(t, "You are not allowed to post news."))
1022 cc.Server.flatNewsMux.Lock()
1023 defer cc.Server.flatNewsMux.Unlock()
1025 newsDateTemplate := defaultNewsDateFormat
1026 if cc.Server.Config.NewsDateFormat != "" {
1027 newsDateTemplate = cc.Server.Config.NewsDateFormat
1030 newsTemplate := defaultNewsTemplate
1031 if cc.Server.Config.NewsDelimiter != "" {
1032 newsTemplate = cc.Server.Config.NewsDelimiter
1035 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
1036 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
1038 // update news in memory
1039 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
1041 // update news on disk
1042 if err := cc.Server.FS.WriteFile(filepath.Join(cc.Server.ConfigDir, "MessageBoard.txt"), cc.Server.FlatNews, 0644); err != nil {
1046 // Notify all clients of updated news
1049 NewField(fieldData, []byte(newsPost)),
1052 res = append(res, cc.NewReply(t))
1056 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1057 if !cc.Authorize(accessDisconUser) {
1058 res = append(res, cc.NewErrReply(t, "You are not allowed to disconnect users."))
1062 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
1064 if clientConn.Authorize(accessCannotBeDiscon) {
1065 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
1069 // If fieldOptions is set, then the client IP is banned in addition to disconnected.
1070 // 00 01 = temporary ban
1071 // 00 02 = permanent ban
1072 if t.GetField(fieldOptions).Data != nil {
1073 switch t.GetField(fieldOptions).Data[1] {
1075 // send message: "You are temporarily banned on this server"
1076 cc.logger.Infow("Disconnect & temporarily ban " + string(clientConn.UserName))
1078 res = append(res, *NewTransaction(
1081 NewField(fieldData, []byte("You are temporarily banned on this server")),
1082 NewField(fieldChatOptions, []byte{0, 0}),
1085 banUntil := time.Now().Add(tempBanDuration)
1086 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = &banUntil
1087 cc.Server.writeBanList()
1089 // send message: "You are permanently banned on this server"
1090 cc.logger.Infow("Disconnect & ban " + string(clientConn.UserName))
1092 res = append(res, *NewTransaction(
1095 NewField(fieldData, []byte("You are permanently banned on this server")),
1096 NewField(fieldChatOptions, []byte{0, 0}),
1099 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = nil
1100 cc.Server.writeBanList()
1104 // TODO: remove this awful hack
1106 time.Sleep(1 * time.Second)
1107 clientConn.Disconnect()
1110 return append(res, cc.NewReply(t)), err
1113 // HandleGetNewsCatNameList returns a list of news categories for a path
1114 // Fields used in the request:
1115 // 325 News path (Optional)
1116 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1117 if !cc.Authorize(accessNewsReadArt) {
1118 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1122 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1123 cats := cc.Server.GetNewsCatByPath(pathStrs)
1125 // To store the keys in slice in sorted order
1126 keys := make([]string, len(cats))
1128 for k := range cats {
1134 var fieldData []Field
1135 for _, k := range keys {
1137 b, _ := cat.MarshalBinary()
1138 fieldData = append(fieldData, NewField(
1139 fieldNewsCatListData15,
1144 res = append(res, cc.NewReply(t, fieldData...))
1148 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1149 if !cc.Authorize(accessNewsCreateCat) {
1150 res = append(res, cc.NewErrReply(t, "You are not allowed to create news categories."))
1154 name := string(t.GetField(fieldNewsCatName).Data)
1155 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1157 cats := cc.Server.GetNewsCatByPath(pathStrs)
1158 cats[name] = NewsCategoryListData15{
1161 Articles: map[uint32]*NewsArtData{},
1162 SubCats: make(map[string]NewsCategoryListData15),
1165 if err := cc.Server.writeThreadedNews(); err != nil {
1168 res = append(res, cc.NewReply(t))
1172 // Fields used in the request:
1173 // 322 News category name
1175 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1176 if !cc.Authorize(accessNewsCreateFldr) {
1177 res = append(res, cc.NewErrReply(t, "You are not allowed to create news folders."))
1181 name := string(t.GetField(fieldFileName).Data)
1182 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1184 cc.logger.Infof("Creating new news folder %s", name)
1186 cats := cc.Server.GetNewsCatByPath(pathStrs)
1187 cats[name] = NewsCategoryListData15{
1190 Articles: map[uint32]*NewsArtData{},
1191 SubCats: make(map[string]NewsCategoryListData15),
1193 if err := cc.Server.writeThreadedNews(); err != nil {
1196 res = append(res, cc.NewReply(t))
1200 // Fields used in the request:
1201 // 325 News path Optional
1204 // 321 News article list data Optional
1205 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1206 if !cc.Authorize(accessNewsReadArt) {
1207 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1210 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1212 var cat NewsCategoryListData15
1213 cats := cc.Server.ThreadedNews.Categories
1215 for _, fp := range pathStrs {
1217 cats = cats[fp].SubCats
1220 nald := cat.GetNewsArtListData()
1222 res = append(res, cc.NewReply(t, NewField(fieldNewsArtListData, nald.Payload())))
1226 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1227 if !cc.Authorize(accessNewsReadArt) {
1228 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1234 // 326 News article ID
1235 // 327 News article data flavor
1237 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1239 var cat NewsCategoryListData15
1240 cats := cc.Server.ThreadedNews.Categories
1242 for _, fp := range pathStrs {
1244 cats = cats[fp].SubCats
1246 newsArtID := t.GetField(fieldNewsArtID).Data
1248 convertedArtID := binary.BigEndian.Uint16(newsArtID)
1250 art := cat.Articles[uint32(convertedArtID)]
1252 res = append(res, cc.NewReply(t))
1257 // 328 News article title
1258 // 329 News article poster
1259 // 330 News article date
1260 // 331 Previous article ID
1261 // 332 Next article ID
1262 // 335 Parent article ID
1263 // 336 First child article ID
1264 // 327 News article data flavor "Should be “text/plain”
1265 // 333 News article data Optional (if data flavor is “text/plain”)
1267 res = append(res, cc.NewReply(t,
1268 NewField(fieldNewsArtTitle, []byte(art.Title)),
1269 NewField(fieldNewsArtPoster, []byte(art.Poster)),
1270 NewField(fieldNewsArtDate, art.Date),
1271 NewField(fieldNewsArtPrevArt, art.PrevArt),
1272 NewField(fieldNewsArtNextArt, art.NextArt),
1273 NewField(fieldNewsArtParentArt, art.ParentArt),
1274 NewField(fieldNewsArt1stChildArt, art.FirstChildArt),
1275 NewField(fieldNewsArtDataFlav, []byte("text/plain")),
1276 NewField(fieldNewsArtData, []byte(art.Data)),
1281 // HandleDelNewsItem deletes an existing threaded news folder or category from the server.
1282 // Fields used in the request:
1284 // Fields used in the reply:
1286 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1287 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1289 cats := cc.Server.ThreadedNews.Categories
1290 delName := pathStrs[len(pathStrs)-1]
1291 if len(pathStrs) > 1 {
1292 for _, fp := range pathStrs[0 : len(pathStrs)-1] {
1293 cats = cats[fp].SubCats
1297 if bytes.Equal(cats[delName].Type, []byte{0, 3}) {
1298 if !cc.Authorize(accessNewsDeleteCat) {
1299 return append(res, cc.NewErrReply(t, "You are not allowed to delete news categories.")), nil
1302 if !cc.Authorize(accessNewsDeleteFldr) {
1303 return append(res, cc.NewErrReply(t, "You are not allowed to delete news folders.")), nil
1307 delete(cats, delName)
1309 if err := cc.Server.writeThreadedNews(); err != nil {
1313 return append(res, cc.NewReply(t)), nil
1316 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1317 if !cc.Authorize(accessNewsDeleteArt) {
1318 res = append(res, cc.NewErrReply(t, "You are not allowed to delete news articles."))
1324 // 326 News article ID
1325 // 337 News article – recursive delete Delete child articles (1) or not (0)
1326 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1327 ID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1329 // TODO: Delete recursive
1330 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1332 catName := pathStrs[len(pathStrs)-1]
1333 cat := cats[catName]
1335 delete(cat.Articles, uint32(ID))
1338 if err := cc.Server.writeThreadedNews(); err != nil {
1342 res = append(res, cc.NewReply(t))
1348 // 326 News article ID ID of the parent article?
1349 // 328 News article title
1350 // 334 News article flags
1351 // 327 News article data flavor Currently “text/plain”
1352 // 333 News article data
1353 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1354 if !cc.Authorize(accessNewsPostArt) {
1355 res = append(res, cc.NewErrReply(t, "You are not allowed to post news articles."))
1359 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1360 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1362 catName := pathStrs[len(pathStrs)-1]
1363 cat := cats[catName]
1365 newArt := NewsArtData{
1366 Title: string(t.GetField(fieldNewsArtTitle).Data),
1367 Poster: string(cc.UserName),
1368 Date: toHotlineTime(time.Now()),
1369 PrevArt: []byte{0, 0, 0, 0},
1370 NextArt: []byte{0, 0, 0, 0},
1371 ParentArt: append([]byte{0, 0}, t.GetField(fieldNewsArtID).Data...),
1372 FirstChildArt: []byte{0, 0, 0, 0},
1373 DataFlav: []byte("text/plain"),
1374 Data: string(t.GetField(fieldNewsArtData).Data),
1378 for k := range cat.Articles {
1379 keys = append(keys, int(k))
1385 prevID := uint32(keys[len(keys)-1])
1388 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1390 // Set next article ID
1391 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1394 // Update parent article with first child reply
1395 parentID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1397 parentArt := cat.Articles[uint32(parentID)]
1399 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1400 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1404 cat.Articles[nextID] = &newArt
1407 if err := cc.Server.writeThreadedNews(); err != nil {
1411 res = append(res, cc.NewReply(t))
1415 // HandleGetMsgs returns the flat news data
1416 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1417 if !cc.Authorize(accessNewsReadArt) {
1418 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1422 res = append(res, cc.NewReply(t, NewField(fieldData, cc.Server.FlatNews)))
1427 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1428 if !cc.Authorize(accessDownloadFile) {
1429 res = append(res, cc.NewErrReply(t, "You are not allowed to download files."))
1433 fileName := t.GetField(fieldFileName).Data
1434 filePath := t.GetField(fieldFilePath).Data
1435 resumeData := t.GetField(fieldFileResumeData).Data
1437 var dataOffset int64
1438 var frd FileResumeData
1439 if resumeData != nil {
1440 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1443 // TODO: handle rsrc fork offset
1444 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1447 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1452 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, dataOffset)
1457 xferSize := hlFile.ffo.TransferSize(0)
1459 ft := cc.newFileTransfer(FileDownload, fileName, filePath, xferSize)
1461 // TODO: refactor to remove this
1462 if resumeData != nil {
1463 var frd FileResumeData
1464 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1467 ft.fileResumeData = &frd
1470 // Optional field for when a HL v1.5+ client requests file preview
1471 // Used only for TEXT, JPEG, GIFF, BMP or PICT files
1472 // The value will always be 2
1473 if t.GetField(fieldFileTransferOptions).Data != nil {
1474 ft.options = t.GetField(fieldFileTransferOptions).Data
1475 xferSize = hlFile.ffo.FlatFileDataForkHeader.DataSize[:]
1478 res = append(res, cc.NewReply(t,
1479 NewField(fieldRefNum, ft.refNum[:]),
1480 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1481 NewField(fieldTransferSize, xferSize),
1482 NewField(fieldFileSize, hlFile.ffo.FlatFileDataForkHeader.DataSize[:]),
1488 // Download all files from the specified folder and sub-folders
1489 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1490 if !cc.Authorize(accessDownloadFile) {
1491 res = append(res, cc.NewErrReply(t, "You are not allowed to download folders."))
1495 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
1500 transferSize, err := CalcTotalSize(fullFilePath)
1504 itemCount, err := CalcItemCount(fullFilePath)
1509 fileTransfer := cc.newFileTransfer(FolderDownload, t.GetField(fieldFileName).Data, t.GetField(fieldFilePath).Data, transferSize)
1512 _, err = fp.Write(t.GetField(fieldFilePath).Data)
1517 res = append(res, cc.NewReply(t,
1518 NewField(fieldRefNum, fileTransfer.ReferenceNumber),
1519 NewField(fieldTransferSize, transferSize),
1520 NewField(fieldFolderItemCount, itemCount),
1521 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1526 // Upload all files from the local folder and its subfolders to the specified path on the server
1527 // Fields used in the request
1530 // 108 transfer size Total size of all items in the folder
1531 // 220 Folder item count
1532 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1533 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1535 if t.GetField(fieldFilePath).Data != nil {
1536 if _, err = fp.Write(t.GetField(fieldFilePath).Data); err != nil {
1541 // Handle special cases for Upload and Drop Box folders
1542 if !cc.Authorize(accessUploadAnywhere) {
1543 if !fp.IsUploadDir() && !fp.IsDropbox() {
1544 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))))
1549 fileTransfer := cc.newFileTransfer(FolderUpload,
1550 t.GetField(fieldFileName).Data,
1551 t.GetField(fieldFilePath).Data,
1552 t.GetField(fieldTransferSize).Data,
1555 fileTransfer.FolderItemCount = t.GetField(fieldFolderItemCount).Data
1557 res = append(res, cc.NewReply(t, NewField(fieldRefNum, fileTransfer.ReferenceNumber)))
1562 // Fields used in the request:
1565 // 204 File transfer options "Optional
1566 // Used only to resume download, currently has value 2"
1567 // 108 File transfer size "Optional used if download is not resumed"
1568 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1569 if !cc.Authorize(accessUploadFile) {
1570 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1574 fileName := t.GetField(fieldFileName).Data
1575 filePath := t.GetField(fieldFilePath).Data
1576 transferOptions := t.GetField(fieldFileTransferOptions).Data
1577 transferSize := t.GetField(fieldTransferSize).Data // not sent for resume
1580 if filePath != nil {
1581 if _, err = fp.Write(filePath); err != nil {
1586 // Handle special cases for Upload and Drop Box folders
1587 if !cc.Authorize(accessUploadAnywhere) {
1588 if !fp.IsUploadDir() && !fp.IsDropbox() {
1589 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))))
1593 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1598 if _, err := cc.Server.FS.Stat(fullFilePath); err == nil {
1599 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))))
1603 ft := cc.newFileTransfer(FileUpload, fileName, filePath, transferSize)
1605 replyT := cc.NewReply(t, NewField(fieldRefNum, ft.ReferenceNumber))
1607 // client has requested to resume a partially transferred file
1608 if transferOptions != nil {
1610 fileInfo, err := cc.Server.FS.Stat(fullFilePath + incompleteFileSuffix)
1615 offset := make([]byte, 4)
1616 binary.BigEndian.PutUint32(offset, uint32(fileInfo.Size()))
1618 fileResumeData := NewFileResumeData([]ForkInfoList{
1619 *NewForkInfoList(offset),
1622 b, _ := fileResumeData.BinaryMarshal()
1624 ft.TransferSize = offset
1626 replyT.Fields = append(replyT.Fields, NewField(fieldFileResumeData, b))
1629 res = append(res, replyT)
1633 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1634 if len(t.GetField(fieldUserIconID).Data) == 4 {
1635 cc.Icon = t.GetField(fieldUserIconID).Data[2:]
1637 cc.Icon = t.GetField(fieldUserIconID).Data
1639 if cc.Authorize(accessAnyName) {
1640 cc.UserName = t.GetField(fieldUserName).Data
1643 // the options field is only passed by the client versions > 1.2.3.
1644 options := t.GetField(fieldOptions).Data
1646 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1647 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
1649 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, optBitmap.Bit(refusePM))
1650 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1652 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, optBitmap.Bit(refuseChat))
1653 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1655 // Check auto response
1656 if optBitmap.Bit(autoResponse) == 1 {
1657 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
1659 cc.AutoReply = []byte{}
1663 for _, c := range sortedClients(cc.Server.Clients) {
1664 res = append(res, *NewTransaction(
1665 tranNotifyChangeUser,
1667 NewField(fieldUserID, *cc.ID),
1668 NewField(fieldUserIconID, cc.Icon),
1669 NewField(fieldUserFlags, cc.Flags),
1670 NewField(fieldUserName, cc.UserName),
1677 // HandleKeepAlive responds to keepalive transactions with an empty reply
1678 // * HL 1.9.2 Client sends keepalive msg every 3 minutes
1679 // * HL 1.2.3 Client doesn't send keepalives
1680 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1681 res = append(res, cc.NewReply(t))
1686 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1687 fullPath, err := readPath(
1688 cc.Server.Config.FileRoot,
1689 t.GetField(fieldFilePath).Data,
1697 if t.GetField(fieldFilePath).Data != nil {
1698 if _, err = fp.Write(t.GetField(fieldFilePath).Data); err != nil {
1703 // Handle special case for drop box folders
1704 if fp.IsDropbox() && !cc.Authorize(accessViewDropBoxes) {
1705 res = append(res, cc.NewErrReply(t, "You are not allowed to view drop boxes."))
1709 fileNames, err := getFileNameList(fullPath, cc.Server.Config.IgnoreFiles)
1714 res = append(res, cc.NewReply(t, fileNames...))
1719 // =================================
1720 // Hotline private chat flow
1721 // =================================
1722 // 1. ClientA sends tranInviteNewChat to server with user ID to invite
1723 // 2. Server creates new ChatID
1724 // 3. Server sends tranInviteToChat to invitee
1725 // 4. Server replies to ClientA with new Chat ID
1727 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1728 // If Accepted is clicked:
1729 // 1. ClientB sends tranJoinChat with fieldChatID
1731 // HandleInviteNewChat invites users to new private chat
1732 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1733 if !cc.Authorize(accessOpenChat) {
1734 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1739 targetID := t.GetField(fieldUserID).Data
1740 newChatID := cc.Server.NewPrivateChat(cc)
1742 // Check if target user has "Refuse private chat" flag
1743 binary.BigEndian.Uint16(targetID)
1744 targetClient := cc.Server.Clients[binary.BigEndian.Uint16(targetID)]
1746 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(targetClient.Flags)))
1747 if flagBitmap.Bit(userFLagRefusePChat) == 1 {
1752 NewField(fieldData, []byte(string(targetClient.UserName)+" does not accept private chats.")),
1753 NewField(fieldUserName, targetClient.UserName),
1754 NewField(fieldUserID, *targetClient.ID),
1755 NewField(fieldOptions, []byte{0, 2}),
1763 NewField(fieldChatID, newChatID),
1764 NewField(fieldUserName, cc.UserName),
1765 NewField(fieldUserID, *cc.ID),
1772 NewField(fieldChatID, newChatID),
1773 NewField(fieldUserName, cc.UserName),
1774 NewField(fieldUserID, *cc.ID),
1775 NewField(fieldUserIconID, cc.Icon),
1776 NewField(fieldUserFlags, cc.Flags),
1783 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1784 if !cc.Authorize(accessOpenChat) {
1785 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1790 targetID := t.GetField(fieldUserID).Data
1791 chatID := t.GetField(fieldChatID).Data
1797 NewField(fieldChatID, chatID),
1798 NewField(fieldUserName, cc.UserName),
1799 NewField(fieldUserID, *cc.ID),
1805 NewField(fieldChatID, chatID),
1806 NewField(fieldUserName, cc.UserName),
1807 NewField(fieldUserID, *cc.ID),
1808 NewField(fieldUserIconID, cc.Icon),
1809 NewField(fieldUserFlags, cc.Flags),
1816 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1817 chatID := t.GetField(fieldChatID).Data
1818 chatInt := binary.BigEndian.Uint32(chatID)
1820 privChat := cc.Server.PrivateChats[chatInt]
1822 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1824 for _, c := range sortedClients(privChat.ClientConn) {
1829 NewField(fieldChatID, chatID),
1830 NewField(fieldData, resMsg),
1838 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1839 // Fields used in the reply:
1840 // * 115 Chat subject
1841 // * 300 User name with info (Optional)
1842 // * 300 (more user names with info)
1843 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1844 chatID := t.GetField(fieldChatID).Data
1845 chatInt := binary.BigEndian.Uint32(chatID)
1847 privChat := cc.Server.PrivateChats[chatInt]
1849 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1850 for _, c := range sortedClients(privChat.ClientConn) {
1853 tranNotifyChatChangeUser,
1855 NewField(fieldChatID, chatID),
1856 NewField(fieldUserName, cc.UserName),
1857 NewField(fieldUserID, *cc.ID),
1858 NewField(fieldUserIconID, cc.Icon),
1859 NewField(fieldUserFlags, cc.Flags),
1864 privChat.ClientConn[cc.uint16ID()] = cc
1866 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1867 for _, c := range sortedClients(privChat.ClientConn) {
1872 Name: string(c.UserName),
1875 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1878 res = append(res, cc.NewReply(t, replyFields...))
1882 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1883 // Fields used in the request:
1884 // * 114 fieldChatID
1885 // Reply is not expected.
1886 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1887 chatID := t.GetField(fieldChatID).Data
1888 chatInt := binary.BigEndian.Uint32(chatID)
1890 privChat, ok := cc.Server.PrivateChats[chatInt]
1895 delete(privChat.ClientConn, cc.uint16ID())
1897 // Notify members of the private chat that the user has left
1898 for _, c := range sortedClients(privChat.ClientConn) {
1901 tranNotifyChatDeleteUser,
1903 NewField(fieldChatID, chatID),
1904 NewField(fieldUserID, *cc.ID),
1912 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1913 // Fields used in the request:
1915 // * 115 Chat subject Chat subject string
1916 // Reply is not expected.
1917 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1918 chatID := t.GetField(fieldChatID).Data
1919 chatInt := binary.BigEndian.Uint32(chatID)
1921 privChat := cc.Server.PrivateChats[chatInt]
1922 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1924 for _, c := range sortedClients(privChat.ClientConn) {
1927 tranNotifyChatSubject,
1929 NewField(fieldChatID, chatID),
1930 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),
1938 // HandleMakeAlias makes a filer alias using the specified path.
1939 // Fields used in the request:
1942 // 212 File new path Destination path
1944 // Fields used in the reply:
1946 func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1947 if !cc.Authorize(accessMakeAlias) {
1948 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
1951 fileName := t.GetField(fieldFileName).Data
1952 filePath := t.GetField(fieldFilePath).Data
1953 fileNewPath := t.GetField(fieldFileNewPath).Data
1955 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1960 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
1965 cc.logger.Debugw("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
1967 if err := cc.Server.FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
1968 res = append(res, cc.NewErrReply(t, "Error creating alias"))
1972 res = append(res, cc.NewReply(t))
1976 // HandleDownloadBanner handles requests for a new banner from the server
1977 // Fields used in the request:
1979 // Fields used in the reply:
1980 // 107 fieldRefNum Used later for transfer
1981 // 108 fieldTransferSize Size of data to be downloaded
1982 func HandleDownloadBanner(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1983 fi, err := cc.Server.FS.Stat(filepath.Join(cc.Server.ConfigDir, cc.Server.Config.BannerFile))
1988 ft := cc.newFileTransfer(bannerDownload, []byte{}, []byte{}, make([]byte, 4))
1990 binary.BigEndian.PutUint32(ft.TransferSize, uint32(fi.Size()))
1992 res = append(res, cc.NewReply(t,
1993 NewField(fieldRefNum, ft.refNum[:]),
1994 NewField(fieldTransferSize, ft.TransferSize),