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 chatID := t.GetField(fieldChatID).Data
257 // a non-nil chatID indicates the message belongs to a private chat
259 chatInt := binary.BigEndian.Uint32(chatID)
260 privChat := cc.Server.PrivateChats[chatInt]
262 clients := sortedClients(privChat.ClientConn)
264 // send the message to all connected clients of the private chat
265 for _, c := range clients {
266 res = append(res, *NewTransaction(
269 NewField(fieldChatID, chatID),
270 NewField(fieldData, []byte(formattedMsg)),
276 for _, c := range sortedClients(cc.Server.Clients) {
277 // Filter out clients that do not have the read chat permission
278 if c.Authorize(accessReadChat) {
279 res = append(res, *NewTransaction(tranChatMsg, c.ID, NewField(fieldData, []byte(formattedMsg))))
286 // HandleSendInstantMsg sends instant message to the user on the current server.
287 // Fields used in the request:
290 // One of the following values:
291 // - User message (myOpt_UserMessage = 1)
292 // - Refuse message (myOpt_RefuseMessage = 2)
293 // - Refuse chat (myOpt_RefuseChat = 3)
294 // - Automatic response (myOpt_AutomaticResponse = 4)"
296 // 214 Quoting message Optional
298 // Fields used in the reply:
300 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
301 if !cc.Authorize(accessSendPrivMsg) {
302 res = append(res, cc.NewErrReply(t, "You are not allowed to send private messages."))
306 msg := t.GetField(fieldData)
307 ID := t.GetField(fieldUserID)
309 reply := NewTransaction(
312 NewField(fieldData, msg.Data),
313 NewField(fieldUserName, cc.UserName),
314 NewField(fieldUserID, *cc.ID),
315 NewField(fieldOptions, []byte{0, 1}),
318 // Later versions of Hotline include the original message in the fieldQuotingMsg field so
319 // the receiving client can display both the received message and what it is in reply to
320 if t.GetField(fieldQuotingMsg).Data != nil {
321 reply.Fields = append(reply.Fields, NewField(fieldQuotingMsg, t.GetField(fieldQuotingMsg).Data))
324 id, _ := byteToInt(ID.Data)
325 otherClient, ok := cc.Server.Clients[uint16(id)]
327 return res, errors.New("invalid client ID")
330 // Check if target user has "Refuse private messages" flag
331 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(otherClient.Flags)))
332 if flagBitmap.Bit(userFLagRefusePChat) == 1 {
337 NewField(fieldData, []byte(string(otherClient.UserName)+" does not accept private messages.")),
338 NewField(fieldUserName, otherClient.UserName),
339 NewField(fieldUserID, *otherClient.ID),
340 NewField(fieldOptions, []byte{0, 2}),
344 res = append(res, *reply)
347 // Respond with auto reply if other client has it enabled
348 if len(otherClient.AutoReply) > 0 {
353 NewField(fieldData, otherClient.AutoReply),
354 NewField(fieldUserName, otherClient.UserName),
355 NewField(fieldUserID, *otherClient.ID),
356 NewField(fieldOptions, []byte{0, 1}),
361 res = append(res, cc.NewReply(t))
366 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
367 fileName := t.GetField(fieldFileName).Data
368 filePath := t.GetField(fieldFilePath).Data
370 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
375 fw, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
380 res = append(res, cc.NewReply(t,
381 NewField(fieldFileName, []byte(fw.name)),
382 NewField(fieldFileTypeString, fw.ffo.FlatFileInformationFork.friendlyType()),
383 NewField(fieldFileCreatorString, fw.ffo.FlatFileInformationFork.friendlyCreator()),
384 NewField(fieldFileComment, fw.ffo.FlatFileInformationFork.Comment),
385 NewField(fieldFileType, fw.ffo.FlatFileInformationFork.TypeSignature),
386 NewField(fieldFileCreateDate, fw.ffo.FlatFileInformationFork.CreateDate),
387 NewField(fieldFileModifyDate, fw.ffo.FlatFileInformationFork.ModifyDate),
388 NewField(fieldFileSize, fw.totalSize()),
393 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
394 // Fields used in the request:
396 // * 202 File path Optional
397 // * 211 File new name Optional
398 // * 210 File comment Optional
399 // Fields used in the reply: None
400 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
401 fileName := t.GetField(fieldFileName).Data
402 filePath := t.GetField(fieldFilePath).Data
404 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
409 fi, err := cc.Server.FS.Stat(fullFilePath)
414 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
418 if t.GetField(fieldFileComment).Data != nil {
419 switch mode := fi.Mode(); {
421 if !cc.Authorize(accessSetFolderComment) {
422 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for folders."))
425 case mode.IsRegular():
426 if !cc.Authorize(accessSetFileComment) {
427 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for files."))
432 if err := hlFile.ffo.FlatFileInformationFork.setComment(t.GetField(fieldFileComment).Data); err != nil {
435 w, err := hlFile.infoForkWriter()
439 _, err = w.Write(hlFile.ffo.FlatFileInformationFork.MarshalBinary())
445 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, t.GetField(fieldFileNewName).Data)
450 fileNewName := t.GetField(fieldFileNewName).Data
452 if fileNewName != nil {
453 switch mode := fi.Mode(); {
455 if !cc.Authorize(accessRenameFolder) {
456 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
459 err = os.Rename(fullFilePath, fullNewFilePath)
460 if os.IsNotExist(err) {
461 res = append(res, cc.NewErrReply(t, "Cannot rename folder "+string(fileName)+" because it does not exist or cannot be found."))
464 case mode.IsRegular():
465 if !cc.Authorize(accessRenameFile) {
466 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
469 fileDir, err := readPath(cc.Server.Config.FileRoot, filePath, []byte{})
473 hlFile.name = string(fileNewName)
474 err = hlFile.move(fileDir)
475 if os.IsNotExist(err) {
476 res = append(res, cc.NewErrReply(t, "Cannot rename file "+string(fileName)+" because it does not exist or cannot be found."))
485 res = append(res, cc.NewReply(t))
489 // HandleDeleteFile deletes a file or folder
490 // Fields used in the request:
493 // Fields used in the reply: none
494 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
495 fileName := t.GetField(fieldFileName).Data
496 filePath := t.GetField(fieldFilePath).Data
498 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
503 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
508 fi, err := hlFile.dataFile()
510 res = append(res, cc.NewErrReply(t, "Cannot delete file "+string(fileName)+" because it does not exist or cannot be found."))
514 switch mode := fi.Mode(); {
516 if !cc.Authorize(accessDeleteFolder) {
517 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
520 case mode.IsRegular():
521 if !cc.Authorize(accessDeleteFile) {
522 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
527 if err := hlFile.delete(); err != nil {
531 res = append(res, cc.NewReply(t))
535 // HandleMoveFile moves files or folders. Note: seemingly not documented
536 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
537 fileName := string(t.GetField(fieldFileName).Data)
539 filePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
544 fileNewPath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFileNewPath).Data, nil)
549 cc.logger.Infow("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
551 hlFile, err := newFileWrapper(cc.Server.FS, filePath, 0)
556 fi, err := hlFile.dataFile()
558 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
564 switch mode := fi.Mode(); {
566 if !cc.Authorize(accessMoveFolder) {
567 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
570 case mode.IsRegular():
571 if !cc.Authorize(accessMoveFile) {
572 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
576 if err := hlFile.move(fileNewPath); err != nil {
579 // TODO: handle other possible errors; e.g. fileWrapper delete fails due to fileWrapper permission issue
581 res = append(res, cc.NewReply(t))
585 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
586 if !cc.Authorize(accessCreateFolder) {
587 res = append(res, cc.NewErrReply(t, "You are not allowed to create folders."))
590 folderName := string(t.GetField(fieldFileName).Data)
592 folderName = path.Join("/", folderName)
596 // fieldFilePath is only present for nested paths
597 if t.GetField(fieldFilePath).Data != nil {
599 _, err := newFp.Write(t.GetField(fieldFilePath).Data)
604 for _, pathItem := range newFp.Items {
605 subPath = filepath.Join("/", subPath, string(pathItem.Name))
608 newFolderPath := path.Join(cc.Server.Config.FileRoot, subPath, folderName)
610 // TODO: check path and folder name lengths
612 if _, err := cc.Server.FS.Stat(newFolderPath); !os.IsNotExist(err) {
613 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that name.", folderName)
614 return []Transaction{cc.NewErrReply(t, msg)}, nil
617 // TODO: check for disallowed characters to maintain compatibility for original client
619 if err := cc.Server.FS.Mkdir(newFolderPath, 0777); err != nil {
620 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
621 return []Transaction{cc.NewErrReply(t, msg)}, nil
624 res = append(res, cc.NewReply(t))
628 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
629 if !cc.Authorize(accessModifyUser) {
630 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
634 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
635 userName := string(t.GetField(fieldUserName).Data)
637 newAccessLvl := t.GetField(fieldUserAccess).Data
639 account := cc.Server.Accounts[login]
640 account.Name = userName
641 copy(account.Access[:], newAccessLvl)
643 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
644 // not include fieldUserPassword
645 if t.GetField(fieldUserPassword).Data == nil {
646 account.Password = hashAndSalt([]byte(""))
648 if len(t.GetField(fieldUserPassword).Data) > 1 {
649 account.Password = hashAndSalt(t.GetField(fieldUserPassword).Data)
652 out, err := yaml.Marshal(&account)
656 if err := os.WriteFile(filepath.Join(cc.Server.ConfigDir, "Users", login+".yaml"), out, 0666); err != nil {
660 // Notify connected clients logged in as the user of the new access level
661 for _, c := range cc.Server.Clients {
662 if c.Account.Login == login {
663 // Note: comment out these two lines to test server-side deny messages
664 newT := NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, newAccessLvl))
665 res = append(res, *newT)
667 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
668 if c.Authorize(accessDisconUser) {
669 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 1)
671 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 0)
673 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
675 c.Account.Access = account.Access
678 tranNotifyChangeUser,
679 NewField(fieldUserID, *c.ID),
680 NewField(fieldUserFlags, c.Flags),
681 NewField(fieldUserName, c.UserName),
682 NewField(fieldUserIconID, c.Icon),
687 res = append(res, cc.NewReply(t))
691 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
692 if !cc.Authorize(accessOpenUser) {
693 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
697 account := cc.Server.Accounts[string(t.GetField(fieldUserLogin).Data)]
699 res = append(res, cc.NewErrReply(t, "Account does not exist."))
703 res = append(res, cc.NewReply(t,
704 NewField(fieldUserName, []byte(account.Name)),
705 NewField(fieldUserLogin, negateString(t.GetField(fieldUserLogin).Data)),
706 NewField(fieldUserPassword, []byte(account.Password)),
707 NewField(fieldUserAccess, account.Access[:]),
712 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
713 if !cc.Authorize(accessOpenUser) {
714 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
718 var userFields []Field
719 for _, acc := range cc.Server.Accounts {
720 b := make([]byte, 0, 100)
721 n, err := acc.Read(b)
726 userFields = append(userFields, NewField(fieldData, b[:n]))
729 res = append(res, cc.NewReply(t, userFields...))
733 // HandleUpdateUser is used by the v1.5+ multi-user editor to perform account editing for multiple users at a time.
734 // An update can be a mix of these actions:
737 // * Modify user (including renaming the account login)
739 // The Transaction sent by the client includes one data field per user that was modified. This data field in turn
740 // contains another data field encoded in its payload with a varying number of sub fields depending on which action is
741 // performed. This seems to be the only place in the Hotline protocol where a data field contains another data field.
742 func HandleUpdateUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
743 for _, field := range t.Fields {
744 subFields, err := ReadFields(field.Data[0:2], field.Data[2:])
749 if len(subFields) == 1 {
750 login := DecodeUserString(getField(fieldData, &subFields).Data)
751 cc.logger.Infow("DeleteUser", "login", login)
753 if !cc.Authorize(accessDeleteUser) {
754 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
758 if err := cc.Server.DeleteUser(login); err != nil {
764 login := DecodeUserString(getField(fieldUserLogin, &subFields).Data)
766 // check if the login dataFile; if so, we know we are updating an existing user
767 if acc, ok := cc.Server.Accounts[login]; ok {
768 cc.logger.Infow("UpdateUser", "login", login)
770 // account dataFile, so this is an update action
771 if !cc.Authorize(accessModifyUser) {
772 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
776 if getField(fieldUserPassword, &subFields) != nil {
777 newPass := getField(fieldUserPassword, &subFields).Data
778 acc.Password = hashAndSalt(newPass)
780 acc.Password = hashAndSalt([]byte(""))
783 if getField(fieldUserAccess, &subFields) != nil {
784 copy(acc.Access[:], getField(fieldUserAccess, &subFields).Data)
787 err = cc.Server.UpdateUser(
788 DecodeUserString(getField(fieldData, &subFields).Data),
789 DecodeUserString(getField(fieldUserLogin, &subFields).Data),
790 string(getField(fieldUserName, &subFields).Data),
798 cc.logger.Infow("CreateUser", "login", login)
800 if !cc.Authorize(accessCreateUser) {
801 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
805 newAccess := accessBitmap{}
806 copy(newAccess[:], getField(fieldUserAccess, &subFields).Data[:])
808 // Prevent account from creating new account with greater permission
809 for i := 0; i < 64; i++ {
810 if newAccess.IsSet(i) {
811 if !cc.Authorize(i) {
812 return append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself.")), err
817 err := cc.Server.NewUser(login, string(getField(fieldUserName, &subFields).Data), string(getField(fieldUserPassword, &subFields).Data), newAccess)
819 return []Transaction{}, err
824 res = append(res, cc.NewReply(t))
828 // HandleNewUser creates a new user account
829 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
830 if !cc.Authorize(accessCreateUser) {
831 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
835 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
837 // If the account already dataFile, reply with an error
838 if _, ok := cc.Server.Accounts[login]; ok {
839 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
843 newAccess := accessBitmap{}
844 copy(newAccess[:], t.GetField(fieldUserAccess).Data[:])
846 // Prevent account from creating new account with greater permission
847 for i := 0; i < 64; i++ {
848 if newAccess.IsSet(i) {
849 if !cc.Authorize(i) {
850 res = append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself."))
856 if err := cc.Server.NewUser(login, string(t.GetField(fieldUserName).Data), string(t.GetField(fieldUserPassword).Data), newAccess); err != nil {
857 return []Transaction{}, err
860 res = append(res, cc.NewReply(t))
864 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
865 if !cc.Authorize(accessDeleteUser) {
866 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
870 // TODO: Handle case where account doesn't exist; e.g. delete race condition
871 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
873 if err := cc.Server.DeleteUser(login); err != nil {
877 res = append(res, cc.NewReply(t))
881 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
882 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
883 if !cc.Authorize(accessBroadcast) {
884 res = append(res, cc.NewErrReply(t, "You are not allowed to send broadcast messages."))
890 NewField(fieldData, t.GetField(tranGetMsgs).Data),
891 NewField(fieldChatOptions, []byte{0}),
894 res = append(res, cc.NewReply(t))
898 func byteToInt(bytes []byte) (int, error) {
901 return int(binary.BigEndian.Uint16(bytes)), nil
903 return int(binary.BigEndian.Uint32(bytes)), nil
906 return 0, errors.New("unknown byte length")
909 // HandleGetClientInfoText returns user information for the specific user.
911 // Fields used in the request:
914 // Fields used in the reply:
916 // 101 Data User info text string
917 func HandleGetClientInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
918 if !cc.Authorize(accessGetClientInfo) {
919 res = append(res, cc.NewErrReply(t, "You are not allowed to get client info."))
923 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
925 clientConn := cc.Server.Clients[uint16(clientID)]
926 if clientConn == nil {
927 return append(res, cc.NewErrReply(t, "User not found.")), err
930 res = append(res, cc.NewReply(t,
931 NewField(fieldData, []byte(clientConn.String())),
932 NewField(fieldUserName, clientConn.UserName),
937 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
938 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
943 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
946 if t.GetField(fieldUserName).Data != nil {
947 if cc.Authorize(accessAnyName) {
948 cc.UserName = t.GetField(fieldUserName).Data
950 cc.UserName = []byte(cc.Account.Name)
954 cc.Icon = t.GetField(fieldUserIconID).Data
956 cc.logger = cc.logger.With("name", string(cc.UserName))
957 cc.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(cc.Version); return i }()))
959 options := t.GetField(fieldOptions).Data
960 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
962 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
964 // Check refuse private PM option
965 if optBitmap.Bit(refusePM) == 1 {
966 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
967 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
970 // Check refuse private chat option
971 if optBitmap.Bit(refuseChat) == 1 {
972 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
973 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
976 // Check auto response
977 if optBitmap.Bit(autoResponse) == 1 {
978 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
980 cc.AutoReply = []byte{}
983 trans := cc.notifyOthers(
985 tranNotifyChangeUser, nil,
986 NewField(fieldUserName, cc.UserName),
987 NewField(fieldUserID, *cc.ID),
988 NewField(fieldUserIconID, cc.Icon),
989 NewField(fieldUserFlags, cc.Flags),
992 res = append(res, trans...)
994 if cc.Server.Config.BannerFile != "" {
995 res = append(res, *NewTransaction(tranServerBanner, cc.ID, NewField(fieldBannerType, []byte("JPEG"))))
998 res = append(res, cc.NewReply(t))
1003 const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
1004 // "Mon, 02 Jan 2006 15:04:05 MST"
1006 const defaultNewsTemplate = `From %s (%s):
1010 __________________________________________________________`
1012 // HandleTranOldPostNews updates the flat news
1013 // Fields used in this request:
1015 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1016 if !cc.Authorize(accessNewsPostArt) {
1017 res = append(res, cc.NewErrReply(t, "You are not allowed to post news."))
1021 cc.Server.flatNewsMux.Lock()
1022 defer cc.Server.flatNewsMux.Unlock()
1024 newsDateTemplate := defaultNewsDateFormat
1025 if cc.Server.Config.NewsDateFormat != "" {
1026 newsDateTemplate = cc.Server.Config.NewsDateFormat
1029 newsTemplate := defaultNewsTemplate
1030 if cc.Server.Config.NewsDelimiter != "" {
1031 newsTemplate = cc.Server.Config.NewsDelimiter
1034 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
1035 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
1037 // update news in memory
1038 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
1040 // update news on disk
1041 if err := cc.Server.FS.WriteFile(filepath.Join(cc.Server.ConfigDir, "MessageBoard.txt"), cc.Server.FlatNews, 0644); err != nil {
1045 // Notify all clients of updated news
1048 NewField(fieldData, []byte(newsPost)),
1051 res = append(res, cc.NewReply(t))
1055 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1056 if !cc.Authorize(accessDisconUser) {
1057 res = append(res, cc.NewErrReply(t, "You are not allowed to disconnect users."))
1061 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
1063 if clientConn.Authorize(accessCannotBeDiscon) {
1064 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
1068 // If fieldOptions is set, then the client IP is banned in addition to disconnected.
1069 // 00 01 = temporary ban
1070 // 00 02 = permanent ban
1071 if t.GetField(fieldOptions).Data != nil {
1072 switch t.GetField(fieldOptions).Data[1] {
1074 // send message: "You are temporarily banned on this server"
1075 cc.logger.Infow("Disconnect & temporarily ban " + string(clientConn.UserName))
1077 res = append(res, *NewTransaction(
1080 NewField(fieldData, []byte("You are temporarily banned on this server")),
1081 NewField(fieldChatOptions, []byte{0, 0}),
1084 banUntil := time.Now().Add(tempBanDuration)
1085 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = &banUntil
1086 cc.Server.writeBanList()
1088 // send message: "You are permanently banned on this server"
1089 cc.logger.Infow("Disconnect & ban " + string(clientConn.UserName))
1091 res = append(res, *NewTransaction(
1094 NewField(fieldData, []byte("You are permanently banned on this server")),
1095 NewField(fieldChatOptions, []byte{0, 0}),
1098 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = nil
1099 cc.Server.writeBanList()
1103 // TODO: remove this awful hack
1105 time.Sleep(1 * time.Second)
1106 clientConn.Disconnect()
1109 return append(res, cc.NewReply(t)), err
1112 // HandleGetNewsCatNameList returns a list of news categories for a path
1113 // Fields used in the request:
1114 // 325 News path (Optional)
1115 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1116 if !cc.Authorize(accessNewsReadArt) {
1117 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1121 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1122 cats := cc.Server.GetNewsCatByPath(pathStrs)
1124 // To store the keys in slice in sorted order
1125 keys := make([]string, len(cats))
1127 for k := range cats {
1133 var fieldData []Field
1134 for _, k := range keys {
1136 b, _ := cat.MarshalBinary()
1137 fieldData = append(fieldData, NewField(
1138 fieldNewsCatListData15,
1143 res = append(res, cc.NewReply(t, fieldData...))
1147 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1148 if !cc.Authorize(accessNewsCreateCat) {
1149 res = append(res, cc.NewErrReply(t, "You are not allowed to create news categories."))
1153 name := string(t.GetField(fieldNewsCatName).Data)
1154 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1156 cats := cc.Server.GetNewsCatByPath(pathStrs)
1157 cats[name] = NewsCategoryListData15{
1160 Articles: map[uint32]*NewsArtData{},
1161 SubCats: make(map[string]NewsCategoryListData15),
1164 if err := cc.Server.writeThreadedNews(); err != nil {
1167 res = append(res, cc.NewReply(t))
1171 // Fields used in the request:
1172 // 322 News category name
1174 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1175 if !cc.Authorize(accessNewsCreateFldr) {
1176 res = append(res, cc.NewErrReply(t, "You are not allowed to create news folders."))
1180 name := string(t.GetField(fieldFileName).Data)
1181 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1183 cc.logger.Infof("Creating new news folder %s", name)
1185 cats := cc.Server.GetNewsCatByPath(pathStrs)
1186 cats[name] = NewsCategoryListData15{
1189 Articles: map[uint32]*NewsArtData{},
1190 SubCats: make(map[string]NewsCategoryListData15),
1192 if err := cc.Server.writeThreadedNews(); err != nil {
1195 res = append(res, cc.NewReply(t))
1199 // Fields used in the request:
1200 // 325 News path Optional
1203 // 321 News article list data Optional
1204 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1205 if !cc.Authorize(accessNewsReadArt) {
1206 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1209 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1211 var cat NewsCategoryListData15
1212 cats := cc.Server.ThreadedNews.Categories
1214 for _, fp := range pathStrs {
1216 cats = cats[fp].SubCats
1219 nald := cat.GetNewsArtListData()
1221 res = append(res, cc.NewReply(t, NewField(fieldNewsArtListData, nald.Payload())))
1225 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1226 if !cc.Authorize(accessNewsReadArt) {
1227 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1233 // 326 News article ID
1234 // 327 News article data flavor
1236 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1238 var cat NewsCategoryListData15
1239 cats := cc.Server.ThreadedNews.Categories
1241 for _, fp := range pathStrs {
1243 cats = cats[fp].SubCats
1245 newsArtID := t.GetField(fieldNewsArtID).Data
1247 convertedArtID := binary.BigEndian.Uint16(newsArtID)
1249 art := cat.Articles[uint32(convertedArtID)]
1251 res = append(res, cc.NewReply(t))
1256 // 328 News article title
1257 // 329 News article poster
1258 // 330 News article date
1259 // 331 Previous article ID
1260 // 332 Next article ID
1261 // 335 Parent article ID
1262 // 336 First child article ID
1263 // 327 News article data flavor "Should be “text/plain”
1264 // 333 News article data Optional (if data flavor is “text/plain”)
1266 res = append(res, cc.NewReply(t,
1267 NewField(fieldNewsArtTitle, []byte(art.Title)),
1268 NewField(fieldNewsArtPoster, []byte(art.Poster)),
1269 NewField(fieldNewsArtDate, art.Date),
1270 NewField(fieldNewsArtPrevArt, art.PrevArt),
1271 NewField(fieldNewsArtNextArt, art.NextArt),
1272 NewField(fieldNewsArtParentArt, art.ParentArt),
1273 NewField(fieldNewsArt1stChildArt, art.FirstChildArt),
1274 NewField(fieldNewsArtDataFlav, []byte("text/plain")),
1275 NewField(fieldNewsArtData, []byte(art.Data)),
1280 // HandleDelNewsItem deletes an existing threaded news folder or category from the server.
1281 // Fields used in the request:
1283 // Fields used in the reply:
1285 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1286 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1288 cats := cc.Server.ThreadedNews.Categories
1289 delName := pathStrs[len(pathStrs)-1]
1290 if len(pathStrs) > 1 {
1291 for _, fp := range pathStrs[0 : len(pathStrs)-1] {
1292 cats = cats[fp].SubCats
1296 if bytes.Compare(cats[delName].Type, []byte{0, 3}) == 0 {
1297 if !cc.Authorize(accessNewsDeleteCat) {
1298 return append(res, cc.NewErrReply(t, "You are not allowed to delete news categories.")), nil
1301 if !cc.Authorize(accessNewsDeleteFldr) {
1302 return append(res, cc.NewErrReply(t, "You are not allowed to delete news folders.")), nil
1306 delete(cats, delName)
1308 if err := cc.Server.writeThreadedNews(); err != nil {
1312 return append(res, cc.NewReply(t)), nil
1315 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1316 if !cc.Authorize(accessNewsDeleteArt) {
1317 res = append(res, cc.NewErrReply(t, "You are not allowed to delete news articles."))
1323 // 326 News article ID
1324 // 337 News article – recursive delete Delete child articles (1) or not (0)
1325 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1326 ID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1328 // TODO: Delete recursive
1329 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1331 catName := pathStrs[len(pathStrs)-1]
1332 cat := cats[catName]
1334 delete(cat.Articles, uint32(ID))
1337 if err := cc.Server.writeThreadedNews(); err != nil {
1341 res = append(res, cc.NewReply(t))
1347 // 326 News article ID ID of the parent article?
1348 // 328 News article title
1349 // 334 News article flags
1350 // 327 News article data flavor Currently “text/plain”
1351 // 333 News article data
1352 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1353 if !cc.Authorize(accessNewsPostArt) {
1354 res = append(res, cc.NewErrReply(t, "You are not allowed to post news articles."))
1358 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1359 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1361 catName := pathStrs[len(pathStrs)-1]
1362 cat := cats[catName]
1364 newArt := NewsArtData{
1365 Title: string(t.GetField(fieldNewsArtTitle).Data),
1366 Poster: string(cc.UserName),
1367 Date: toHotlineTime(time.Now()),
1368 PrevArt: []byte{0, 0, 0, 0},
1369 NextArt: []byte{0, 0, 0, 0},
1370 ParentArt: append([]byte{0, 0}, t.GetField(fieldNewsArtID).Data...),
1371 FirstChildArt: []byte{0, 0, 0, 0},
1372 DataFlav: []byte("text/plain"),
1373 Data: string(t.GetField(fieldNewsArtData).Data),
1377 for k := range cat.Articles {
1378 keys = append(keys, int(k))
1384 prevID := uint32(keys[len(keys)-1])
1387 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1389 // Set next article ID
1390 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1393 // Update parent article with first child reply
1394 parentID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1396 parentArt := cat.Articles[uint32(parentID)]
1398 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1399 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1403 cat.Articles[nextID] = &newArt
1406 if err := cc.Server.writeThreadedNews(); err != nil {
1410 res = append(res, cc.NewReply(t))
1414 // HandleGetMsgs returns the flat news data
1415 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1416 if !cc.Authorize(accessNewsReadArt) {
1417 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1421 res = append(res, cc.NewReply(t, NewField(fieldData, cc.Server.FlatNews)))
1426 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1427 if !cc.Authorize(accessDownloadFile) {
1428 res = append(res, cc.NewErrReply(t, "You are not allowed to download files."))
1432 fileName := t.GetField(fieldFileName).Data
1433 filePath := t.GetField(fieldFilePath).Data
1434 resumeData := t.GetField(fieldFileResumeData).Data
1436 var dataOffset int64
1437 var frd FileResumeData
1438 if resumeData != nil {
1439 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1442 // TODO: handle rsrc fork offset
1443 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1446 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1451 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, dataOffset)
1456 xferSize := hlFile.ffo.TransferSize(0)
1458 ft := cc.newFileTransfer(FileDownload, fileName, filePath, xferSize)
1460 // TODO: refactor to remove this
1461 if resumeData != nil {
1462 var frd FileResumeData
1463 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1466 ft.fileResumeData = &frd
1469 // Optional field for when a HL v1.5+ client requests file preview
1470 // Used only for TEXT, JPEG, GIFF, BMP or PICT files
1471 // The value will always be 2
1472 if t.GetField(fieldFileTransferOptions).Data != nil {
1473 ft.options = t.GetField(fieldFileTransferOptions).Data
1474 xferSize = hlFile.ffo.FlatFileDataForkHeader.DataSize[:]
1477 res = append(res, cc.NewReply(t,
1478 NewField(fieldRefNum, ft.refNum[:]),
1479 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1480 NewField(fieldTransferSize, xferSize),
1481 NewField(fieldFileSize, hlFile.ffo.FlatFileDataForkHeader.DataSize[:]),
1487 // Download all files from the specified folder and sub-folders
1488 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1489 if !cc.Authorize(accessDownloadFile) {
1490 res = append(res, cc.NewErrReply(t, "You are not allowed to download folders."))
1494 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
1499 transferSize, err := CalcTotalSize(fullFilePath)
1503 itemCount, err := CalcItemCount(fullFilePath)
1508 fileTransfer := cc.newFileTransfer(FolderDownload, t.GetField(fieldFileName).Data, t.GetField(fieldFilePath).Data, transferSize)
1511 _, err = fp.Write(t.GetField(fieldFilePath).Data)
1516 res = append(res, cc.NewReply(t,
1517 NewField(fieldRefNum, fileTransfer.ReferenceNumber),
1518 NewField(fieldTransferSize, transferSize),
1519 NewField(fieldFolderItemCount, itemCount),
1520 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1525 // Upload all files from the local folder and its subfolders to the specified path on the server
1526 // Fields used in the request
1529 // 108 transfer size Total size of all items in the folder
1530 // 220 Folder item count
1531 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1532 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1534 if t.GetField(fieldFilePath).Data != nil {
1535 if _, err = fp.Write(t.GetField(fieldFilePath).Data); err != nil {
1540 // Handle special cases for Upload and Drop Box folders
1541 if !cc.Authorize(accessUploadAnywhere) {
1542 if !fp.IsUploadDir() && !fp.IsDropbox() {
1543 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))))
1548 fileTransfer := cc.newFileTransfer(FolderUpload,
1549 t.GetField(fieldFileName).Data,
1550 t.GetField(fieldFilePath).Data,
1551 t.GetField(fieldTransferSize).Data,
1554 fileTransfer.FolderItemCount = t.GetField(fieldFolderItemCount).Data
1556 res = append(res, cc.NewReply(t, NewField(fieldRefNum, fileTransfer.ReferenceNumber)))
1561 // Fields used in the request:
1564 // 204 File transfer options "Optional
1565 // Used only to resume download, currently has value 2"
1566 // 108 File transfer size "Optional used if download is not resumed"
1567 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1568 if !cc.Authorize(accessUploadFile) {
1569 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1573 fileName := t.GetField(fieldFileName).Data
1574 filePath := t.GetField(fieldFilePath).Data
1575 transferOptions := t.GetField(fieldFileTransferOptions).Data
1576 transferSize := t.GetField(fieldTransferSize).Data // not sent for resume
1579 if filePath != nil {
1580 if _, err = fp.Write(filePath); err != nil {
1585 // Handle special cases for Upload and Drop Box folders
1586 if !cc.Authorize(accessUploadAnywhere) {
1587 if !fp.IsUploadDir() && !fp.IsDropbox() {
1588 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))))
1592 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1597 if _, err := cc.Server.FS.Stat(fullFilePath); err == nil {
1598 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))))
1602 ft := cc.newFileTransfer(FileUpload, fileName, filePath, transferSize)
1604 replyT := cc.NewReply(t, NewField(fieldRefNum, ft.ReferenceNumber))
1606 // client has requested to resume a partially transferred file
1607 if transferOptions != nil {
1609 fileInfo, err := cc.Server.FS.Stat(fullFilePath + incompleteFileSuffix)
1614 offset := make([]byte, 4)
1615 binary.BigEndian.PutUint32(offset, uint32(fileInfo.Size()))
1617 fileResumeData := NewFileResumeData([]ForkInfoList{
1618 *NewForkInfoList(offset),
1621 b, _ := fileResumeData.BinaryMarshal()
1623 ft.TransferSize = offset
1625 replyT.Fields = append(replyT.Fields, NewField(fieldFileResumeData, b))
1628 res = append(res, replyT)
1632 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1633 if len(t.GetField(fieldUserIconID).Data) == 4 {
1634 cc.Icon = t.GetField(fieldUserIconID).Data[2:]
1636 cc.Icon = t.GetField(fieldUserIconID).Data
1638 if cc.Authorize(accessAnyName) {
1639 cc.UserName = t.GetField(fieldUserName).Data
1642 // the options field is only passed by the client versions > 1.2.3.
1643 options := t.GetField(fieldOptions).Data
1645 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1646 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
1648 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, optBitmap.Bit(refusePM))
1649 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1651 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, optBitmap.Bit(refuseChat))
1652 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1654 // Check auto response
1655 if optBitmap.Bit(autoResponse) == 1 {
1656 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
1658 cc.AutoReply = []byte{}
1662 for _, c := range sortedClients(cc.Server.Clients) {
1663 res = append(res, *NewTransaction(
1664 tranNotifyChangeUser,
1666 NewField(fieldUserID, *cc.ID),
1667 NewField(fieldUserIconID, cc.Icon),
1668 NewField(fieldUserFlags, cc.Flags),
1669 NewField(fieldUserName, cc.UserName),
1676 // HandleKeepAlive responds to keepalive transactions with an empty reply
1677 // * HL 1.9.2 Client sends keepalive msg every 3 minutes
1678 // * HL 1.2.3 Client doesn't send keepalives
1679 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1680 res = append(res, cc.NewReply(t))
1685 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1686 fullPath, err := readPath(
1687 cc.Server.Config.FileRoot,
1688 t.GetField(fieldFilePath).Data,
1696 if t.GetField(fieldFilePath).Data != nil {
1697 if _, err = fp.Write(t.GetField(fieldFilePath).Data); err != nil {
1702 // Handle special case for drop box folders
1703 if fp.IsDropbox() && !cc.Authorize(accessViewDropBoxes) {
1704 res = append(res, cc.NewErrReply(t, "You are not allowed to view drop boxes."))
1708 fileNames, err := getFileNameList(fullPath, cc.Server.Config.IgnoreFiles)
1713 res = append(res, cc.NewReply(t, fileNames...))
1718 // =================================
1719 // Hotline private chat flow
1720 // =================================
1721 // 1. ClientA sends tranInviteNewChat to server with user ID to invite
1722 // 2. Server creates new ChatID
1723 // 3. Server sends tranInviteToChat to invitee
1724 // 4. Server replies to ClientA with new Chat ID
1726 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1727 // If Accepted is clicked:
1728 // 1. ClientB sends tranJoinChat with fieldChatID
1730 // HandleInviteNewChat invites users to new private chat
1731 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1732 if !cc.Authorize(accessOpenChat) {
1733 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1738 targetID := t.GetField(fieldUserID).Data
1739 newChatID := cc.Server.NewPrivateChat(cc)
1741 // Check if target user has "Refuse private chat" flag
1742 binary.BigEndian.Uint16(targetID)
1743 targetClient := cc.Server.Clients[binary.BigEndian.Uint16(targetID)]
1745 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(targetClient.Flags)))
1746 if flagBitmap.Bit(userFLagRefusePChat) == 1 {
1751 NewField(fieldData, []byte(string(targetClient.UserName)+" does not accept private chats.")),
1752 NewField(fieldUserName, targetClient.UserName),
1753 NewField(fieldUserID, *targetClient.ID),
1754 NewField(fieldOptions, []byte{0, 2}),
1762 NewField(fieldChatID, newChatID),
1763 NewField(fieldUserName, cc.UserName),
1764 NewField(fieldUserID, *cc.ID),
1771 NewField(fieldChatID, newChatID),
1772 NewField(fieldUserName, cc.UserName),
1773 NewField(fieldUserID, *cc.ID),
1774 NewField(fieldUserIconID, cc.Icon),
1775 NewField(fieldUserFlags, cc.Flags),
1782 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1783 if !cc.Authorize(accessOpenChat) {
1784 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1789 targetID := t.GetField(fieldUserID).Data
1790 chatID := t.GetField(fieldChatID).Data
1796 NewField(fieldChatID, chatID),
1797 NewField(fieldUserName, cc.UserName),
1798 NewField(fieldUserID, *cc.ID),
1804 NewField(fieldChatID, chatID),
1805 NewField(fieldUserName, cc.UserName),
1806 NewField(fieldUserID, *cc.ID),
1807 NewField(fieldUserIconID, cc.Icon),
1808 NewField(fieldUserFlags, cc.Flags),
1815 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1816 chatID := t.GetField(fieldChatID).Data
1817 chatInt := binary.BigEndian.Uint32(chatID)
1819 privChat := cc.Server.PrivateChats[chatInt]
1821 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1823 for _, c := range sortedClients(privChat.ClientConn) {
1828 NewField(fieldChatID, chatID),
1829 NewField(fieldData, resMsg),
1837 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1838 // Fields used in the reply:
1839 // * 115 Chat subject
1840 // * 300 User name with info (Optional)
1841 // * 300 (more user names with info)
1842 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1843 chatID := t.GetField(fieldChatID).Data
1844 chatInt := binary.BigEndian.Uint32(chatID)
1846 privChat := cc.Server.PrivateChats[chatInt]
1848 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1849 for _, c := range sortedClients(privChat.ClientConn) {
1852 tranNotifyChatChangeUser,
1854 NewField(fieldChatID, chatID),
1855 NewField(fieldUserName, cc.UserName),
1856 NewField(fieldUserID, *cc.ID),
1857 NewField(fieldUserIconID, cc.Icon),
1858 NewField(fieldUserFlags, cc.Flags),
1863 privChat.ClientConn[cc.uint16ID()] = cc
1865 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1866 for _, c := range sortedClients(privChat.ClientConn) {
1871 Name: string(c.UserName),
1874 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1877 res = append(res, cc.NewReply(t, replyFields...))
1881 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1882 // Fields used in the request:
1883 // * 114 fieldChatID
1884 // Reply is not expected.
1885 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1886 chatID := t.GetField(fieldChatID).Data
1887 chatInt := binary.BigEndian.Uint32(chatID)
1889 privChat, ok := cc.Server.PrivateChats[chatInt]
1894 delete(privChat.ClientConn, cc.uint16ID())
1896 // Notify members of the private chat that the user has left
1897 for _, c := range sortedClients(privChat.ClientConn) {
1900 tranNotifyChatDeleteUser,
1902 NewField(fieldChatID, chatID),
1903 NewField(fieldUserID, *cc.ID),
1911 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1912 // Fields used in the request:
1914 // * 115 Chat subject Chat subject string
1915 // Reply is not expected.
1916 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1917 chatID := t.GetField(fieldChatID).Data
1918 chatInt := binary.BigEndian.Uint32(chatID)
1920 privChat := cc.Server.PrivateChats[chatInt]
1921 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1923 for _, c := range sortedClients(privChat.ClientConn) {
1926 tranNotifyChatSubject,
1928 NewField(fieldChatID, chatID),
1929 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),
1937 // HandleMakeAlias makes a filer alias using the specified path.
1938 // Fields used in the request:
1941 // 212 File new path Destination path
1943 // Fields used in the reply:
1945 func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1946 if !cc.Authorize(accessMakeAlias) {
1947 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
1950 fileName := t.GetField(fieldFileName).Data
1951 filePath := t.GetField(fieldFilePath).Data
1952 fileNewPath := t.GetField(fieldFileNewPath).Data
1954 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1959 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
1964 cc.logger.Debugw("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
1966 if err := cc.Server.FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
1967 res = append(res, cc.NewErrReply(t, "Error creating alias"))
1971 res = append(res, cc.NewReply(t))
1975 // HandleDownloadBanner handles requests for a new banner from the server
1976 // Fields used in the request:
1978 // Fields used in the reply:
1979 // 107 fieldRefNum Used later for transfer
1980 // 108 fieldTransferSize Size of data to be downloaded
1981 func HandleDownloadBanner(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1982 fi, err := cc.Server.FS.Stat(filepath.Join(cc.Server.ConfigDir, cc.Server.Config.BannerFile))
1987 ft := cc.newFileTransfer(bannerDownload, []byte{}, []byte{}, make([]byte, 4))
1989 binary.BigEndian.PutUint32(ft.TransferSize, uint32(fi.Size()))
1991 res = append(res, cc.NewReply(t,
1992 NewField(fieldRefNum, ft.refNum[:]),
1993 NewField(fieldTransferSize, ft.TransferSize),