]> git.r.bdr.sh - rbdr/mobius/blob - hotline/transaction_handlers.go
Use fixed size array types in Transaction fields
[rbdr/mobius] / hotline / transaction_handlers.go
1 package hotline
2
3 import (
4 "bufio"
5 "bytes"
6 "encoding/binary"
7 "errors"
8 "fmt"
9 "gopkg.in/yaml.v3"
10 "io"
11 "math/big"
12 "os"
13 "path"
14 "path/filepath"
15 "sort"
16 "strings"
17 "time"
18 )
19
20 type HandlerFunc func(*ClientConn, *Transaction) ([]Transaction, error)
21
22 type TransactionType struct {
23 Handler HandlerFunc // function for handling the transaction type
24 Name string // Name of transaction as it will appear in logging
25 RequiredFields []requiredField
26 }
27
28 var TransactionHandlers = map[uint16]TransactionType{
29 // Server initiated
30 TranChatMsg: {
31 Name: "TranChatMsg",
32 },
33 // Server initiated
34 TranNotifyChangeUser: {
35 Name: "TranNotifyChangeUser",
36 },
37 TranError: {
38 Name: "TranError",
39 },
40 TranShowAgreement: {
41 Name: "TranShowAgreement",
42 },
43 TranUserAccess: {
44 Name: "TranUserAccess",
45 },
46 TranNotifyDeleteUser: {
47 Name: "TranNotifyDeleteUser",
48 },
49 TranAgreed: {
50 Name: "TranAgreed",
51 Handler: HandleTranAgreed,
52 },
53 TranChatSend: {
54 Name: "TranChatSend",
55 Handler: HandleChatSend,
56 RequiredFields: []requiredField{
57 {
58 ID: FieldData,
59 minLen: 0,
60 },
61 },
62 },
63 TranDelNewsArt: {
64 Name: "TranDelNewsArt",
65 Handler: HandleDelNewsArt,
66 },
67 TranDelNewsItem: {
68 Name: "TranDelNewsItem",
69 Handler: HandleDelNewsItem,
70 },
71 TranDeleteFile: {
72 Name: "TranDeleteFile",
73 Handler: HandleDeleteFile,
74 },
75 TranDeleteUser: {
76 Name: "TranDeleteUser",
77 Handler: HandleDeleteUser,
78 },
79 TranDisconnectUser: {
80 Name: "TranDisconnectUser",
81 Handler: HandleDisconnectUser,
82 },
83 TranDownloadFile: {
84 Name: "TranDownloadFile",
85 Handler: HandleDownloadFile,
86 },
87 TranDownloadFldr: {
88 Name: "TranDownloadFldr",
89 Handler: HandleDownloadFolder,
90 },
91 TranGetClientInfoText: {
92 Name: "TranGetClientInfoText",
93 Handler: HandleGetClientInfoText,
94 },
95 TranGetFileInfo: {
96 Name: "TranGetFileInfo",
97 Handler: HandleGetFileInfo,
98 },
99 TranGetFileNameList: {
100 Name: "TranGetFileNameList",
101 Handler: HandleGetFileNameList,
102 },
103 TranGetMsgs: {
104 Name: "TranGetMsgs",
105 Handler: HandleGetMsgs,
106 },
107 TranGetNewsArtData: {
108 Name: "TranGetNewsArtData",
109 Handler: HandleGetNewsArtData,
110 },
111 TranGetNewsArtNameList: {
112 Name: "TranGetNewsArtNameList",
113 Handler: HandleGetNewsArtNameList,
114 },
115 TranGetNewsCatNameList: {
116 Name: "TranGetNewsCatNameList",
117 Handler: HandleGetNewsCatNameList,
118 },
119 TranGetUser: {
120 Name: "TranGetUser",
121 Handler: HandleGetUser,
122 },
123 TranGetUserNameList: {
124 Name: "tranHandleGetUserNameList",
125 Handler: HandleGetUserNameList,
126 },
127 TranInviteNewChat: {
128 Name: "TranInviteNewChat",
129 Handler: HandleInviteNewChat,
130 },
131 TranInviteToChat: {
132 Name: "TranInviteToChat",
133 Handler: HandleInviteToChat,
134 },
135 TranJoinChat: {
136 Name: "TranJoinChat",
137 Handler: HandleJoinChat,
138 },
139 TranKeepAlive: {
140 Name: "TranKeepAlive",
141 Handler: HandleKeepAlive,
142 },
143 TranLeaveChat: {
144 Name: "TranJoinChat",
145 Handler: HandleLeaveChat,
146 },
147 TranListUsers: {
148 Name: "TranListUsers",
149 Handler: HandleListUsers,
150 },
151 TranMoveFile: {
152 Name: "TranMoveFile",
153 Handler: HandleMoveFile,
154 },
155 TranNewFolder: {
156 Name: "TranNewFolder",
157 Handler: HandleNewFolder,
158 },
159 TranNewNewsCat: {
160 Name: "TranNewNewsCat",
161 Handler: HandleNewNewsCat,
162 },
163 TranNewNewsFldr: {
164 Name: "TranNewNewsFldr",
165 Handler: HandleNewNewsFldr,
166 },
167 TranNewUser: {
168 Name: "TranNewUser",
169 Handler: HandleNewUser,
170 },
171 TranUpdateUser: {
172 Name: "TranUpdateUser",
173 Handler: HandleUpdateUser,
174 },
175 TranOldPostNews: {
176 Name: "TranOldPostNews",
177 Handler: HandleTranOldPostNews,
178 },
179 TranPostNewsArt: {
180 Name: "TranPostNewsArt",
181 Handler: HandlePostNewsArt,
182 },
183 TranRejectChatInvite: {
184 Name: "TranRejectChatInvite",
185 Handler: HandleRejectChatInvite,
186 },
187 TranSendInstantMsg: {
188 Name: "TranSendInstantMsg",
189 Handler: HandleSendInstantMsg,
190 RequiredFields: []requiredField{
191 {
192 ID: FieldData,
193 minLen: 0,
194 },
195 {
196 ID: FieldUserID,
197 },
198 },
199 },
200 TranSetChatSubject: {
201 Name: "TranSetChatSubject",
202 Handler: HandleSetChatSubject,
203 },
204 TranMakeFileAlias: {
205 Name: "TranMakeFileAlias",
206 Handler: HandleMakeAlias,
207 RequiredFields: []requiredField{
208 {ID: FieldFileName, minLen: 1},
209 {ID: FieldFilePath, minLen: 1},
210 {ID: FieldFileNewPath, minLen: 1},
211 },
212 },
213 TranSetClientUserInfo: {
214 Name: "TranSetClientUserInfo",
215 Handler: HandleSetClientUserInfo,
216 },
217 TranSetFileInfo: {
218 Name: "TranSetFileInfo",
219 Handler: HandleSetFileInfo,
220 },
221 TranSetUser: {
222 Name: "TranSetUser",
223 Handler: HandleSetUser,
224 },
225 TranUploadFile: {
226 Name: "TranUploadFile",
227 Handler: HandleUploadFile,
228 },
229 TranUploadFldr: {
230 Name: "TranUploadFldr",
231 Handler: HandleUploadFolder,
232 },
233 TranUserBroadcast: {
234 Name: "TranUserBroadcast",
235 Handler: HandleUserBroadcast,
236 },
237 TranDownloadBanner: {
238 Name: "TranDownloadBanner",
239 Handler: HandleDownloadBanner,
240 },
241 }
242
243 func HandleChatSend(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
244 if !cc.Authorize(accessSendChat) {
245 res = append(res, cc.NewErrReply(t, "You are not allowed to participate in chat."))
246 return res, err
247 }
248
249 // Truncate long usernames
250 trunc := fmt.Sprintf("%13s", cc.UserName)
251 formattedMsg := fmt.Sprintf("\r%.14s: %s", trunc, t.GetField(FieldData).Data)
252
253 // By holding the option key, Hotline chat allows users to send /me formatted messages like:
254 // *** Halcyon does stuff
255 // This is indicated by the presence of the optional field FieldChatOptions set to a value of 1.
256 // Most clients do not send this option for normal chat messages.
257 if t.GetField(FieldChatOptions).Data != nil && bytes.Equal(t.GetField(FieldChatOptions).Data, []byte{0, 1}) {
258 formattedMsg = fmt.Sprintf("\r*** %s %s", cc.UserName, t.GetField(FieldData).Data)
259 }
260
261 // The ChatID field is used to identify messages as belonging to a private chat.
262 // All clients *except* Frogblast omit this field for public chat, but Frogblast sends a value of 00 00 00 00.
263 chatID := t.GetField(FieldChatID).Data
264 if chatID != nil && !bytes.Equal([]byte{0, 0, 0, 0}, chatID) {
265 chatInt := binary.BigEndian.Uint32(chatID)
266 privChat := cc.Server.PrivateChats[chatInt]
267
268 clients := sortedClients(privChat.ClientConn)
269
270 // send the message to all connected clients of the private chat
271 for _, c := range clients {
272 res = append(res, *NewTransaction(
273 TranChatMsg,
274 c.ID,
275 NewField(FieldChatID, chatID),
276 NewField(FieldData, []byte(formattedMsg)),
277 ))
278 }
279 return res, err
280 }
281
282 for _, c := range sortedClients(cc.Server.Clients) {
283 // Filter out clients that do not have the read chat permission
284 if c.Authorize(accessReadChat) {
285 res = append(res, *NewTransaction(TranChatMsg, c.ID, NewField(FieldData, []byte(formattedMsg))))
286 }
287 }
288
289 return res, err
290 }
291
292 // HandleSendInstantMsg sends instant message to the user on the current server.
293 // Fields used in the request:
294 //
295 // 103 User ID
296 // 113 Options
297 // One of the following values:
298 // - User message (myOpt_UserMessage = 1)
299 // - Refuse message (myOpt_RefuseMessage = 2)
300 // - Refuse chat (myOpt_RefuseChat = 3)
301 // - Automatic response (myOpt_AutomaticResponse = 4)"
302 // 101 Data Optional
303 // 214 Quoting message Optional
304 //
305 // Fields used in the reply:
306 // None
307 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
308 if !cc.Authorize(accessSendPrivMsg) {
309 res = append(res, cc.NewErrReply(t, "You are not allowed to send private messages."))
310 return res, errors.New("user is not allowed to send private messages")
311 }
312
313 msg := t.GetField(FieldData)
314 ID := t.GetField(FieldUserID)
315
316 reply := NewTransaction(
317 TranServerMsg,
318 &ID.Data,
319 NewField(FieldData, msg.Data),
320 NewField(FieldUserName, cc.UserName),
321 NewField(FieldUserID, *cc.ID),
322 NewField(FieldOptions, []byte{0, 1}),
323 )
324
325 // Later versions of Hotline include the original message in the FieldQuotingMsg field so
326 // the receiving client can display both the received message and what it is in reply to
327 if t.GetField(FieldQuotingMsg).Data != nil {
328 reply.Fields = append(reply.Fields, NewField(FieldQuotingMsg, t.GetField(FieldQuotingMsg).Data))
329 }
330
331 id, err := byteToInt(ID.Data)
332 if err != nil {
333 return res, errors.New("invalid client ID")
334 }
335 otherClient, ok := cc.Server.Clients[uint16(id)]
336 if !ok {
337 return res, errors.New("invalid client ID")
338 }
339
340 // Check if target user has "Refuse private messages" flag
341 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(otherClient.Flags)))
342 if flagBitmap.Bit(UserFlagRefusePM) == 1 {
343 res = append(res,
344 *NewTransaction(
345 TranServerMsg,
346 cc.ID,
347 NewField(FieldData, []byte(string(otherClient.UserName)+" does not accept private messages.")),
348 NewField(FieldUserName, otherClient.UserName),
349 NewField(FieldUserID, *otherClient.ID),
350 NewField(FieldOptions, []byte{0, 2}),
351 ),
352 )
353 } else {
354 res = append(res, *reply)
355 }
356
357 // Respond with auto reply if other client has it enabled
358 if len(otherClient.AutoReply) > 0 {
359 res = append(res,
360 *NewTransaction(
361 TranServerMsg,
362 cc.ID,
363 NewField(FieldData, otherClient.AutoReply),
364 NewField(FieldUserName, otherClient.UserName),
365 NewField(FieldUserID, *otherClient.ID),
366 NewField(FieldOptions, []byte{0, 1}),
367 ),
368 )
369 }
370
371 res = append(res, cc.NewReply(t))
372
373 return res, err
374 }
375
376 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
377 fileName := t.GetField(FieldFileName).Data
378 filePath := t.GetField(FieldFilePath).Data
379
380 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
381 if err != nil {
382 return res, err
383 }
384
385 fw, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
386 if err != nil {
387 return res, err
388 }
389
390 encodedName, err := txtEncoder.String(fw.name)
391 if err != nil {
392 return res, fmt.Errorf("invalid filepath encoding: %w", err)
393 }
394
395 fields := []Field{
396 NewField(FieldFileName, []byte(encodedName)),
397 NewField(FieldFileTypeString, fw.ffo.FlatFileInformationFork.friendlyType()),
398 NewField(FieldFileCreatorString, fw.ffo.FlatFileInformationFork.friendlyCreator()),
399 NewField(FieldFileType, fw.ffo.FlatFileInformationFork.TypeSignature),
400 NewField(FieldFileCreateDate, fw.ffo.FlatFileInformationFork.CreateDate),
401 NewField(FieldFileModifyDate, fw.ffo.FlatFileInformationFork.ModifyDate),
402 }
403
404 // Include the optional FileComment field if there is a comment.
405 if len(fw.ffo.FlatFileInformationFork.Comment) != 0 {
406 fields = append(fields, NewField(FieldFileComment, fw.ffo.FlatFileInformationFork.Comment))
407 }
408
409 // Include the FileSize field for files.
410 if !bytes.Equal(fw.ffo.FlatFileInformationFork.TypeSignature, []byte{0x66, 0x6c, 0x64, 0x72}) {
411 fields = append(fields, NewField(FieldFileSize, fw.totalSize()))
412 }
413
414 res = append(res, cc.NewReply(t, fields...))
415 return res, err
416 }
417
418 // HandleSetFileInfo updates a file or folder Name and/or comment from the Get Info window
419 // Fields used in the request:
420 // * 201 File Name
421 // * 202 File path Optional
422 // * 211 File new Name Optional
423 // * 210 File comment Optional
424 // Fields used in the reply: None
425 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
426 fileName := t.GetField(FieldFileName).Data
427 filePath := t.GetField(FieldFilePath).Data
428
429 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
430 if err != nil {
431 return res, err
432 }
433
434 fi, err := cc.Server.FS.Stat(fullFilePath)
435 if err != nil {
436 return res, err
437 }
438
439 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
440 if err != nil {
441 return res, err
442 }
443 if t.GetField(FieldFileComment).Data != nil {
444 switch mode := fi.Mode(); {
445 case mode.IsDir():
446 if !cc.Authorize(accessSetFolderComment) {
447 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for folders."))
448 return res, err
449 }
450 case mode.IsRegular():
451 if !cc.Authorize(accessSetFileComment) {
452 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for files."))
453 return res, err
454 }
455 }
456
457 if err := hlFile.ffo.FlatFileInformationFork.setComment(t.GetField(FieldFileComment).Data); err != nil {
458 return res, err
459 }
460 w, err := hlFile.infoForkWriter()
461 if err != nil {
462 return res, err
463 }
464 _, err = io.Copy(w, &hlFile.ffo.FlatFileInformationFork)
465 if err != nil {
466 return res, err
467 }
468 }
469
470 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, t.GetField(FieldFileNewName).Data)
471 if err != nil {
472 return nil, err
473 }
474
475 fileNewName := t.GetField(FieldFileNewName).Data
476
477 if fileNewName != nil {
478 switch mode := fi.Mode(); {
479 case mode.IsDir():
480 if !cc.Authorize(accessRenameFolder) {
481 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
482 return res, err
483 }
484 err = os.Rename(fullFilePath, fullNewFilePath)
485 if os.IsNotExist(err) {
486 res = append(res, cc.NewErrReply(t, "Cannot rename folder "+string(fileName)+" because it does not exist or cannot be found."))
487 return res, err
488 }
489 case mode.IsRegular():
490 if !cc.Authorize(accessRenameFile) {
491 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
492 return res, err
493 }
494 fileDir, err := readPath(cc.Server.Config.FileRoot, filePath, []byte{})
495 if err != nil {
496 return nil, err
497 }
498 hlFile.name, err = txtDecoder.String(string(fileNewName))
499 if err != nil {
500 return res, fmt.Errorf("invalid filepath encoding: %w", err)
501 }
502
503 err = hlFile.move(fileDir)
504 if os.IsNotExist(err) {
505 res = append(res, cc.NewErrReply(t, "Cannot rename file "+string(fileName)+" because it does not exist or cannot be found."))
506 return res, err
507 }
508 if err != nil {
509 return res, err
510 }
511 }
512 }
513
514 res = append(res, cc.NewReply(t))
515 return res, err
516 }
517
518 // HandleDeleteFile deletes a file or folder
519 // Fields used in the request:
520 // * 201 File Name
521 // * 202 File path
522 // Fields used in the reply: none
523 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
524 fileName := t.GetField(FieldFileName).Data
525 filePath := t.GetField(FieldFilePath).Data
526
527 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
528 if err != nil {
529 return res, err
530 }
531
532 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
533 if err != nil {
534 return res, err
535 }
536
537 fi, err := hlFile.dataFile()
538 if err != nil {
539 res = append(res, cc.NewErrReply(t, "Cannot delete file "+string(fileName)+" because it does not exist or cannot be found."))
540 return res, nil
541 }
542
543 switch mode := fi.Mode(); {
544 case mode.IsDir():
545 if !cc.Authorize(accessDeleteFolder) {
546 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
547 return res, err
548 }
549 case mode.IsRegular():
550 if !cc.Authorize(accessDeleteFile) {
551 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
552 return res, err
553 }
554 }
555
556 if err := hlFile.delete(); err != nil {
557 return res, err
558 }
559
560 res = append(res, cc.NewReply(t))
561 return res, err
562 }
563
564 // HandleMoveFile moves files or folders. Note: seemingly not documented
565 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
566 fileName := string(t.GetField(FieldFileName).Data)
567
568 filePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(FieldFilePath).Data, t.GetField(FieldFileName).Data)
569 if err != nil {
570 return res, err
571 }
572
573 fileNewPath, err := readPath(cc.Server.Config.FileRoot, t.GetField(FieldFileNewPath).Data, nil)
574 if err != nil {
575 return res, err
576 }
577
578 cc.logger.Info("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
579
580 hlFile, err := newFileWrapper(cc.Server.FS, filePath, 0)
581 if err != nil {
582 return res, err
583 }
584
585 fi, err := hlFile.dataFile()
586 if err != nil {
587 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
588 return res, err
589 }
590 switch mode := fi.Mode(); {
591 case mode.IsDir():
592 if !cc.Authorize(accessMoveFolder) {
593 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
594 return res, err
595 }
596 case mode.IsRegular():
597 if !cc.Authorize(accessMoveFile) {
598 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
599 return res, err
600 }
601 }
602 if err := hlFile.move(fileNewPath); err != nil {
603 return res, err
604 }
605 // TODO: handle other possible errors; e.g. fileWrapper delete fails due to fileWrapper permission issue
606
607 res = append(res, cc.NewReply(t))
608 return res, err
609 }
610
611 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
612 if !cc.Authorize(accessCreateFolder) {
613 res = append(res, cc.NewErrReply(t, "You are not allowed to create folders."))
614 return res, err
615 }
616 folderName := string(t.GetField(FieldFileName).Data)
617
618 folderName = path.Join("/", folderName)
619
620 var subPath string
621
622 // FieldFilePath is only present for nested paths
623 if t.GetField(FieldFilePath).Data != nil {
624 var newFp FilePath
625 _, err := newFp.Write(t.GetField(FieldFilePath).Data)
626 if err != nil {
627 return nil, err
628 }
629
630 for _, pathItem := range newFp.Items {
631 subPath = filepath.Join("/", subPath, string(pathItem.Name))
632 }
633 }
634 newFolderPath := path.Join(cc.Server.Config.FileRoot, subPath, folderName)
635 newFolderPath, err = txtDecoder.String(newFolderPath)
636 if err != nil {
637 return res, fmt.Errorf("invalid filepath encoding: %w", err)
638 }
639
640 // TODO: check path and folder Name lengths
641
642 if _, err := cc.Server.FS.Stat(newFolderPath); !os.IsNotExist(err) {
643 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that Name.", folderName)
644 return []Transaction{cc.NewErrReply(t, msg)}, nil
645 }
646
647 if err := cc.Server.FS.Mkdir(newFolderPath, 0777); err != nil {
648 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
649 return []Transaction{cc.NewErrReply(t, msg)}, nil
650 }
651
652 res = append(res, cc.NewReply(t))
653 return res, err
654 }
655
656 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
657 if !cc.Authorize(accessModifyUser) {
658 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
659 return res, err
660 }
661
662 login := string(encodeString(t.GetField(FieldUserLogin).Data))
663 userName := string(t.GetField(FieldUserName).Data)
664
665 newAccessLvl := t.GetField(FieldUserAccess).Data
666
667 account := cc.Server.Accounts[login]
668 if account == nil {
669 return append(res, cc.NewErrReply(t, "Account not found.")), nil
670 }
671 account.Name = userName
672 copy(account.Access[:], newAccessLvl)
673
674 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
675 // not include FieldUserPassword
676 if t.GetField(FieldUserPassword).Data == nil {
677 account.Password = hashAndSalt([]byte(""))
678 }
679
680 if !bytes.Equal([]byte{0}, t.GetField(FieldUserPassword).Data) {
681 account.Password = hashAndSalt(t.GetField(FieldUserPassword).Data)
682 }
683
684 out, err := yaml.Marshal(&account)
685 if err != nil {
686 return res, err
687 }
688 if err := os.WriteFile(filepath.Join(cc.Server.ConfigDir, "Users", login+".yaml"), out, 0666); err != nil {
689 return res, err
690 }
691
692 // Notify connected clients logged in as the user of the new access level
693 for _, c := range cc.Server.Clients {
694 if c.Account.Login == login {
695 // Note: comment out these two lines to test server-side deny messages
696 newT := NewTransaction(TranUserAccess, c.ID, NewField(FieldUserAccess, newAccessLvl))
697 res = append(res, *newT)
698
699 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
700 if c.Authorize(accessDisconUser) {
701 flagBitmap.SetBit(flagBitmap, UserFlagAdmin, 1)
702 } else {
703 flagBitmap.SetBit(flagBitmap, UserFlagAdmin, 0)
704 }
705 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
706
707 c.Account.Access = account.Access
708
709 cc.sendAll(
710 TranNotifyChangeUser,
711 NewField(FieldUserID, *c.ID),
712 NewField(FieldUserFlags, c.Flags),
713 NewField(FieldUserName, c.UserName),
714 NewField(FieldUserIconID, c.Icon),
715 )
716 }
717 }
718
719 res = append(res, cc.NewReply(t))
720 return res, err
721 }
722
723 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
724 if !cc.Authorize(accessOpenUser) {
725 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
726 return res, err
727 }
728
729 account := cc.Server.Accounts[string(t.GetField(FieldUserLogin).Data)]
730 if account == nil {
731 res = append(res, cc.NewErrReply(t, "Account does not exist."))
732 return res, err
733 }
734
735 res = append(res, cc.NewReply(t,
736 NewField(FieldUserName, []byte(account.Name)),
737 NewField(FieldUserLogin, encodeString(t.GetField(FieldUserLogin).Data)),
738 NewField(FieldUserPassword, []byte(account.Password)),
739 NewField(FieldUserAccess, account.Access[:]),
740 ))
741 return res, err
742 }
743
744 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
745 if !cc.Authorize(accessOpenUser) {
746 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
747 return res, err
748 }
749
750 var userFields []Field
751 for _, acc := range cc.Server.Accounts {
752 accCopy := *acc
753 b, err := io.ReadAll(&accCopy)
754 if err != nil {
755 return res, err
756 }
757
758 userFields = append(userFields, NewField(FieldData, b))
759 }
760
761 res = append(res, cc.NewReply(t, userFields...))
762 return res, err
763 }
764
765 // HandleUpdateUser is used by the v1.5+ multi-user editor to perform account editing for multiple users at a time.
766 // An update can be a mix of these actions:
767 // * Create user
768 // * Delete user
769 // * Modify user (including renaming the account login)
770 //
771 // The Transaction sent by the client includes one data field per user that was modified. This data field in turn
772 // contains another data field encoded in its payload with a varying number of sub fields depending on which action is
773 // performed. This seems to be the only place in the Hotline protocol where a data field contains another data field.
774 func HandleUpdateUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
775 for _, field := range t.Fields {
776
777 var subFields []Field
778
779 // Create a new scanner for parsing incoming bytes into transaction tokens
780 scanner := bufio.NewScanner(bytes.NewReader(field.Data[2:]))
781 scanner.Split(fieldScanner)
782
783 for i := 0; i < int(binary.BigEndian.Uint16(field.Data[0:2])); i++ {
784 scanner.Scan()
785
786 var field Field
787 if _, err := field.Write(scanner.Bytes()); err != nil {
788 return res, fmt.Errorf("error reading field: %w", err)
789 }
790 subFields = append(subFields, field)
791 }
792
793 // If there's only one subfield, that indicates this is a delete operation for the login in FieldData
794 if len(subFields) == 1 {
795 if !cc.Authorize(accessDeleteUser) {
796 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
797 return res, err
798 }
799
800 login := string(encodeString(getField(FieldData, &subFields).Data))
801 cc.logger.Info("DeleteUser", "login", login)
802
803 if err := cc.Server.DeleteUser(login); err != nil {
804 return res, err
805 }
806 continue
807 }
808
809 // login of the account to update
810 var accountToUpdate, loginToRename string
811
812 // If FieldData is included, this is a rename operation where FieldData contains the login of the existing
813 // account and FieldUserLogin contains the new login.
814 if getField(FieldData, &subFields) != nil {
815 loginToRename = string(encodeString(getField(FieldData, &subFields).Data))
816 }
817 userLogin := string(encodeString(getField(FieldUserLogin, &subFields).Data))
818 if loginToRename != "" {
819 accountToUpdate = loginToRename
820 } else {
821 accountToUpdate = userLogin
822 }
823
824 // Check if accountToUpdate has an existing account. If so, we know we are updating an existing user.
825 if acc, ok := cc.Server.Accounts[accountToUpdate]; ok {
826 if loginToRename != "" {
827 cc.logger.Info("RenameUser", "prevLogin", accountToUpdate, "newLogin", userLogin)
828 } else {
829 cc.logger.Info("UpdateUser", "login", accountToUpdate)
830 }
831
832 // account exists, so this is an update action
833 if !cc.Authorize(accessModifyUser) {
834 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
835 return res, nil
836 }
837
838 // This part is a bit tricky. There are three possibilities:
839 // 1) The transaction is intended to update the password.
840 // In this case, FieldUserPassword is sent with the new password.
841 // 2) The transaction is intended to remove the password.
842 // In this case, FieldUserPassword is not sent.
843 // 3) The transaction updates the users access bits, but not the password.
844 // In this case, FieldUserPassword is sent with zero as the only byte.
845 if getField(FieldUserPassword, &subFields) != nil {
846 newPass := getField(FieldUserPassword, &subFields).Data
847 if !bytes.Equal([]byte{0}, newPass) {
848 acc.Password = hashAndSalt(newPass)
849 }
850 } else {
851 acc.Password = hashAndSalt([]byte(""))
852 }
853
854 if getField(FieldUserAccess, &subFields) != nil {
855 copy(acc.Access[:], getField(FieldUserAccess, &subFields).Data)
856 }
857
858 err = cc.Server.UpdateUser(
859 string(encodeString(getField(FieldData, &subFields).Data)),
860 string(encodeString(getField(FieldUserLogin, &subFields).Data)),
861 string(getField(FieldUserName, &subFields).Data),
862 acc.Password,
863 acc.Access,
864 )
865 if err != nil {
866 return res, err
867 }
868 } else {
869 if !cc.Authorize(accessCreateUser) {
870 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
871 return res, nil
872 }
873
874 cc.logger.Info("CreateUser", "login", userLogin)
875
876 newAccess := accessBitmap{}
877 copy(newAccess[:], getField(FieldUserAccess, &subFields).Data)
878
879 // Prevent account from creating new account with greater permission
880 for i := 0; i < 64; i++ {
881 if newAccess.IsSet(i) {
882 if !cc.Authorize(i) {
883 return append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself.")), nil
884 }
885 }
886 }
887
888 err = cc.Server.NewUser(userLogin, string(getField(FieldUserName, &subFields).Data), string(getField(FieldUserPassword, &subFields).Data), newAccess)
889 if err != nil {
890 return append(res, cc.NewErrReply(t, "Cannot create account because there is already an account with that login.")), nil
891 }
892 }
893 }
894
895 res = append(res, cc.NewReply(t))
896 return res, err
897 }
898
899 // HandleNewUser creates a new user account
900 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
901 if !cc.Authorize(accessCreateUser) {
902 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
903 return res, err
904 }
905
906 login := string(encodeString(t.GetField(FieldUserLogin).Data))
907
908 // If the account already dataFile, reply with an error
909 if _, ok := cc.Server.Accounts[login]; ok {
910 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
911 return res, err
912 }
913
914 newAccess := accessBitmap{}
915 copy(newAccess[:], t.GetField(FieldUserAccess).Data)
916
917 // Prevent account from creating new account with greater permission
918 for i := 0; i < 64; i++ {
919 if newAccess.IsSet(i) {
920 if !cc.Authorize(i) {
921 res = append(res, cc.NewErrReply(t, "Cannot create account with more access than yourself."))
922 return res, err
923 }
924 }
925 }
926
927 if err := cc.Server.NewUser(login, string(t.GetField(FieldUserName).Data), string(t.GetField(FieldUserPassword).Data), newAccess); err != nil {
928 res = append(res, cc.NewErrReply(t, "Cannot create account because there is already an account with that login."))
929 return res, err
930 }
931
932 res = append(res, cc.NewReply(t))
933 return res, err
934 }
935
936 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
937 if !cc.Authorize(accessDeleteUser) {
938 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
939 return res, nil
940 }
941
942 login := string(encodeString(t.GetField(FieldUserLogin).Data))
943
944 if err := cc.Server.DeleteUser(login); err != nil {
945 return res, err
946 }
947
948 res = append(res, cc.NewReply(t))
949 return res, err
950 }
951
952 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
953 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
954 if !cc.Authorize(accessBroadcast) {
955 res = append(res, cc.NewErrReply(t, "You are not allowed to send broadcast messages."))
956 return res, err
957 }
958
959 cc.sendAll(
960 TranServerMsg,
961 NewField(FieldData, t.GetField(TranGetMsgs).Data),
962 NewField(FieldChatOptions, []byte{0}),
963 )
964
965 res = append(res, cc.NewReply(t))
966 return res, err
967 }
968
969 // HandleGetClientInfoText returns user information for the specific user.
970 //
971 // Fields used in the request:
972 // 103 User ID
973 //
974 // Fields used in the reply:
975 // 102 User Name
976 // 101 Data User info text string
977 func HandleGetClientInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
978 if !cc.Authorize(accessGetClientInfo) {
979 res = append(res, cc.NewErrReply(t, "You are not allowed to get client info."))
980 return res, err
981 }
982
983 clientID, _ := byteToInt(t.GetField(FieldUserID).Data)
984
985 clientConn := cc.Server.Clients[uint16(clientID)]
986 if clientConn == nil {
987 return append(res, cc.NewErrReply(t, "User not found.")), err
988 }
989
990 res = append(res, cc.NewReply(t,
991 NewField(FieldData, []byte(clientConn.String())),
992 NewField(FieldUserName, clientConn.UserName),
993 ))
994 return res, err
995 }
996
997 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
998 return []Transaction{cc.NewReply(t, cc.Server.connectedUsers()...)}, nil
999 }
1000
1001 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1002 if t.GetField(FieldUserName).Data != nil {
1003 if cc.Authorize(accessAnyName) {
1004 cc.UserName = t.GetField(FieldUserName).Data
1005 } else {
1006 cc.UserName = []byte(cc.Account.Name)
1007 }
1008 }
1009
1010 cc.Icon = t.GetField(FieldUserIconID).Data
1011
1012 cc.logger = cc.logger.With("Name", string(cc.UserName))
1013 cc.logger.Info("Login successful", "clientVersion", fmt.Sprintf("%v", func() int { i, _ := byteToInt(cc.Version); return i }()))
1014
1015 options := t.GetField(FieldOptions).Data
1016 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1017
1018 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
1019
1020 // Check refuse private PM option
1021 if optBitmap.Bit(UserOptRefusePM) == 1 {
1022 flagBitmap.SetBit(flagBitmap, UserFlagRefusePM, 1)
1023 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1024 }
1025
1026 // Check refuse private chat option
1027 if optBitmap.Bit(UserOptRefuseChat) == 1 {
1028 flagBitmap.SetBit(flagBitmap, UserFlagRefusePChat, 1)
1029 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1030 }
1031
1032 // Check auto response
1033 if optBitmap.Bit(UserOptAutoResponse) == 1 {
1034 cc.AutoReply = t.GetField(FieldAutomaticResponse).Data
1035 } else {
1036 cc.AutoReply = []byte{}
1037 }
1038
1039 trans := cc.notifyOthers(
1040 *NewTransaction(
1041 TranNotifyChangeUser, nil,
1042 NewField(FieldUserName, cc.UserName),
1043 NewField(FieldUserID, *cc.ID),
1044 NewField(FieldUserIconID, cc.Icon),
1045 NewField(FieldUserFlags, cc.Flags),
1046 ),
1047 )
1048 res = append(res, trans...)
1049
1050 if cc.Server.Config.BannerFile != "" {
1051 res = append(res, *NewTransaction(TranServerBanner, cc.ID, NewField(FieldBannerType, []byte("JPEG"))))
1052 }
1053
1054 res = append(res, cc.NewReply(t))
1055
1056 return res, err
1057 }
1058
1059 // HandleTranOldPostNews updates the flat news
1060 // Fields used in this request:
1061 // 101 Data
1062 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1063 if !cc.Authorize(accessNewsPostArt) {
1064 res = append(res, cc.NewErrReply(t, "You are not allowed to post news."))
1065 return res, err
1066 }
1067
1068 cc.Server.flatNewsMux.Lock()
1069 defer cc.Server.flatNewsMux.Unlock()
1070
1071 newsDateTemplate := defaultNewsDateFormat
1072 if cc.Server.Config.NewsDateFormat != "" {
1073 newsDateTemplate = cc.Server.Config.NewsDateFormat
1074 }
1075
1076 newsTemplate := defaultNewsTemplate
1077 if cc.Server.Config.NewsDelimiter != "" {
1078 newsTemplate = cc.Server.Config.NewsDelimiter
1079 }
1080
1081 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(FieldData).Data)
1082 newsPost = strings.ReplaceAll(newsPost, "\n", "\r")
1083
1084 // update news in memory
1085 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
1086
1087 // update news on disk
1088 if err := cc.Server.FS.WriteFile(filepath.Join(cc.Server.ConfigDir, "MessageBoard.txt"), cc.Server.FlatNews, 0644); err != nil {
1089 return res, err
1090 }
1091
1092 // Notify all clients of updated news
1093 cc.sendAll(
1094 TranNewMsg,
1095 NewField(FieldData, []byte(newsPost)),
1096 )
1097
1098 res = append(res, cc.NewReply(t))
1099 return res, err
1100 }
1101
1102 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1103 if !cc.Authorize(accessDisconUser) {
1104 res = append(res, cc.NewErrReply(t, "You are not allowed to disconnect users."))
1105 return res, err
1106 }
1107
1108 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(FieldUserID).Data)]
1109
1110 if clientConn.Authorize(accessCannotBeDiscon) {
1111 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
1112 return res, err
1113 }
1114
1115 // If FieldOptions is set, then the client IP is banned in addition to disconnected.
1116 // 00 01 = temporary ban
1117 // 00 02 = permanent ban
1118 if t.GetField(FieldOptions).Data != nil {
1119 switch t.GetField(FieldOptions).Data[1] {
1120 case 1:
1121 // send message: "You are temporarily banned on this server"
1122 cc.logger.Info("Disconnect & temporarily ban " + string(clientConn.UserName))
1123
1124 res = append(res, *NewTransaction(
1125 TranServerMsg,
1126 clientConn.ID,
1127 NewField(FieldData, []byte("You are temporarily banned on this server")),
1128 NewField(FieldChatOptions, []byte{0, 0}),
1129 ))
1130
1131 banUntil := time.Now().Add(tempBanDuration)
1132 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = &banUntil
1133 case 2:
1134 // send message: "You are permanently banned on this server"
1135 cc.logger.Info("Disconnect & ban " + string(clientConn.UserName))
1136
1137 res = append(res, *NewTransaction(
1138 TranServerMsg,
1139 clientConn.ID,
1140 NewField(FieldData, []byte("You are permanently banned on this server")),
1141 NewField(FieldChatOptions, []byte{0, 0}),
1142 ))
1143
1144 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = nil
1145 }
1146
1147 err := cc.Server.writeBanList()
1148 if err != nil {
1149 return res, err
1150 }
1151 }
1152
1153 // TODO: remove this awful hack
1154 go func() {
1155 time.Sleep(1 * time.Second)
1156 clientConn.Disconnect()
1157 }()
1158
1159 return append(res, cc.NewReply(t)), err
1160 }
1161
1162 // HandleGetNewsCatNameList returns a list of news categories for a path
1163 // Fields used in the request:
1164 // 325 News path (Optional)
1165 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1166 if !cc.Authorize(accessNewsReadArt) {
1167 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1168 return res, err
1169 }
1170
1171 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1172 cats := cc.Server.GetNewsCatByPath(pathStrs)
1173
1174 // To store the keys in slice in sorted order
1175 keys := make([]string, len(cats))
1176 i := 0
1177 for k := range cats {
1178 keys[i] = k
1179 i++
1180 }
1181 sort.Strings(keys)
1182
1183 var fieldData []Field
1184 for _, k := range keys {
1185 cat := cats[k]
1186 b, _ := cat.MarshalBinary()
1187 fieldData = append(fieldData, NewField(
1188 FieldNewsCatListData15,
1189 b,
1190 ))
1191 }
1192
1193 res = append(res, cc.NewReply(t, fieldData...))
1194 return res, err
1195 }
1196
1197 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1198 if !cc.Authorize(accessNewsCreateCat) {
1199 res = append(res, cc.NewErrReply(t, "You are not allowed to create news categories."))
1200 return res, err
1201 }
1202
1203 name := string(t.GetField(FieldNewsCatName).Data)
1204 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1205
1206 cats := cc.Server.GetNewsCatByPath(pathStrs)
1207 cats[name] = NewsCategoryListData15{
1208 Name: name,
1209 Type: [2]byte{0, 3},
1210 Articles: map[uint32]*NewsArtData{},
1211 SubCats: make(map[string]NewsCategoryListData15),
1212 }
1213
1214 if err := cc.Server.writeThreadedNews(); err != nil {
1215 return res, err
1216 }
1217 res = append(res, cc.NewReply(t))
1218 return res, err
1219 }
1220
1221 // Fields used in the request:
1222 // 322 News category Name
1223 // 325 News path
1224 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1225 if !cc.Authorize(accessNewsCreateFldr) {
1226 res = append(res, cc.NewErrReply(t, "You are not allowed to create news folders."))
1227 return res, err
1228 }
1229
1230 name := string(t.GetField(FieldFileName).Data)
1231 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1232
1233 cats := cc.Server.GetNewsCatByPath(pathStrs)
1234 cats[name] = NewsCategoryListData15{
1235 Name: name,
1236 Type: [2]byte{0, 2},
1237 Articles: map[uint32]*NewsArtData{},
1238 SubCats: make(map[string]NewsCategoryListData15),
1239 }
1240 if err := cc.Server.writeThreadedNews(); err != nil {
1241 return res, err
1242 }
1243 res = append(res, cc.NewReply(t))
1244 return res, err
1245 }
1246
1247 // HandleGetNewsArtData gets the list of article names at the specified news path.
1248
1249 // Fields used in the request:
1250 // 325 News path Optional
1251
1252 // Fields used in the reply:
1253 // 321 News article list data Optional
1254 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1255 if !cc.Authorize(accessNewsReadArt) {
1256 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1257 return res, nil
1258 }
1259
1260 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1261
1262 var cat NewsCategoryListData15
1263 cats := cc.Server.ThreadedNews.Categories
1264
1265 for _, fp := range pathStrs {
1266 cat = cats[fp]
1267 cats = cats[fp].SubCats
1268 }
1269
1270 nald := cat.GetNewsArtListData()
1271
1272 b, err := io.ReadAll(&nald)
1273 if err != nil {
1274 return res, fmt.Errorf("error loading news articles: %w", err)
1275 }
1276
1277 res = append(res, cc.NewReply(t, NewField(FieldNewsArtListData, b)))
1278 return res, nil
1279 }
1280
1281 // HandleGetNewsArtData requests information about the specific news article.
1282 // Fields used in the request:
1283 //
1284 // Request fields
1285 // 325 News path
1286 // 326 News article ID
1287 // 327 News article data flavor
1288 //
1289 // Fields used in the reply:
1290 // 328 News article title
1291 // 329 News article poster
1292 // 330 News article date
1293 // 331 Previous article ID
1294 // 332 Next article ID
1295 // 335 Parent article ID
1296 // 336 First child article ID
1297 // 327 News article data flavor "Should be “text/plain”
1298 // 333 News article data Optional (if data flavor is “text/plain”)
1299 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1300 if !cc.Authorize(accessNewsReadArt) {
1301 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1302 return res, err
1303 }
1304
1305 var cat NewsCategoryListData15
1306 cats := cc.Server.ThreadedNews.Categories
1307
1308 for _, fp := range ReadNewsPath(t.GetField(FieldNewsPath).Data) {
1309 cat = cats[fp]
1310 cats = cats[fp].SubCats
1311 }
1312
1313 // The official Hotline clients will send the article ID as 2 bytes if possible, but
1314 // some third party clients such as Frogblast and Heildrun will always send 4 bytes
1315 convertedID, err := byteToInt(t.GetField(FieldNewsArtID).Data)
1316 if err != nil {
1317 return res, err
1318 }
1319
1320 art := cat.Articles[uint32(convertedID)]
1321 if art == nil {
1322 res = append(res, cc.NewReply(t))
1323 return res, err
1324 }
1325
1326 res = append(res, cc.NewReply(t,
1327 NewField(FieldNewsArtTitle, []byte(art.Title)),
1328 NewField(FieldNewsArtPoster, []byte(art.Poster)),
1329 NewField(FieldNewsArtDate, art.Date[:]),
1330 NewField(FieldNewsArtPrevArt, art.PrevArt[:]),
1331 NewField(FieldNewsArtNextArt, art.NextArt[:]),
1332 NewField(FieldNewsArtParentArt, art.ParentArt[:]),
1333 NewField(FieldNewsArt1stChildArt, art.FirstChildArt[:]),
1334 NewField(FieldNewsArtDataFlav, []byte("text/plain")),
1335 NewField(FieldNewsArtData, []byte(art.Data)),
1336 ))
1337 return res, err
1338 }
1339
1340 // HandleDelNewsItem deletes an existing threaded news folder or category from the server.
1341 // Fields used in the request:
1342 // 325 News path
1343 // Fields used in the reply:
1344 // None
1345 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1346 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1347
1348 cats := cc.Server.ThreadedNews.Categories
1349 delName := pathStrs[len(pathStrs)-1]
1350 if len(pathStrs) > 1 {
1351 for _, fp := range pathStrs[0 : len(pathStrs)-1] {
1352 cats = cats[fp].SubCats
1353 }
1354 }
1355
1356 if cats[delName].Type == [2]byte{0, 3} {
1357 if !cc.Authorize(accessNewsDeleteCat) {
1358 return append(res, cc.NewErrReply(t, "You are not allowed to delete news categories.")), nil
1359 }
1360 } else {
1361 if !cc.Authorize(accessNewsDeleteFldr) {
1362 return append(res, cc.NewErrReply(t, "You are not allowed to delete news folders.")), nil
1363 }
1364 }
1365
1366 delete(cats, delName)
1367
1368 if err := cc.Server.writeThreadedNews(); err != nil {
1369 return res, err
1370 }
1371
1372 return append(res, cc.NewReply(t)), nil
1373 }
1374
1375 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1376 if !cc.Authorize(accessNewsDeleteArt) {
1377 res = append(res, cc.NewErrReply(t, "You are not allowed to delete news articles."))
1378 return res, err
1379 }
1380
1381 // Request Fields
1382 // 325 News path
1383 // 326 News article ID
1384 // 337 News article – recursive delete Delete child articles (1) or not (0)
1385 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1386 ID, err := byteToInt(t.GetField(FieldNewsArtID).Data)
1387 if err != nil {
1388 return res, err
1389 }
1390
1391 // TODO: Delete recursive
1392 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1393
1394 catName := pathStrs[len(pathStrs)-1]
1395 cat := cats[catName]
1396
1397 delete(cat.Articles, uint32(ID))
1398
1399 cats[catName] = cat
1400 if err := cc.Server.writeThreadedNews(); err != nil {
1401 return res, err
1402 }
1403
1404 res = append(res, cc.NewReply(t))
1405 return res, err
1406 }
1407
1408 // Request fields
1409 // 325 News path
1410 // 326 News article ID ID of the parent article?
1411 // 328 News article title
1412 // 334 News article flags
1413 // 327 News article data flavor Currently “text/plain”
1414 // 333 News article data
1415 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1416 if !cc.Authorize(accessNewsPostArt) {
1417 res = append(res, cc.NewErrReply(t, "You are not allowed to post news articles."))
1418 return res, err
1419 }
1420
1421 pathStrs := ReadNewsPath(t.GetField(FieldNewsPath).Data)
1422 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1423
1424 catName := pathStrs[len(pathStrs)-1]
1425 cat := cats[catName]
1426
1427 artID, err := byteToInt(t.GetField(FieldNewsArtID).Data)
1428 if err != nil {
1429 return res, err
1430 }
1431 convertedArtID := uint32(artID)
1432 bs := make([]byte, 4)
1433 binary.BigEndian.PutUint32(bs, convertedArtID)
1434
1435 cc.Server.mux.Lock()
1436 defer cc.Server.mux.Unlock()
1437
1438 newArt := NewsArtData{
1439 Title: string(t.GetField(FieldNewsArtTitle).Data),
1440 Poster: string(cc.UserName),
1441 Date: toHotlineTime(time.Now()),
1442 PrevArt: [4]byte{},
1443 NextArt: [4]byte{},
1444 ParentArt: [4]byte(bs),
1445 FirstChildArt: [4]byte{},
1446 DataFlav: []byte("text/plain"),
1447 Data: string(t.GetField(FieldNewsArtData).Data),
1448 }
1449
1450 var keys []int
1451 for k := range cat.Articles {
1452 keys = append(keys, int(k))
1453 }
1454
1455 nextID := uint32(1)
1456 if len(keys) > 0 {
1457 sort.Ints(keys)
1458 prevID := uint32(keys[len(keys)-1])
1459 nextID = prevID + 1
1460
1461 binary.BigEndian.PutUint32(newArt.PrevArt[:], prevID)
1462
1463 // Set next article ID
1464 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt[:], nextID)
1465 }
1466
1467 // Update parent article with first child reply
1468 parentID := convertedArtID
1469 if parentID != 0 {
1470 parentArt := cat.Articles[parentID]
1471
1472 if parentArt.FirstChildArt == [4]byte{0, 0, 0, 0} {
1473 binary.BigEndian.PutUint32(parentArt.FirstChildArt[:], nextID)
1474 }
1475 }
1476
1477 cat.Articles[nextID] = &newArt
1478
1479 cats[catName] = cat
1480 if err := cc.Server.writeThreadedNews(); err != nil {
1481 return res, err
1482 }
1483
1484 res = append(res, cc.NewReply(t))
1485 return res, err
1486 }
1487
1488 // HandleGetMsgs returns the flat news data
1489 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1490 if !cc.Authorize(accessNewsReadArt) {
1491 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1492 return res, err
1493 }
1494
1495 res = append(res, cc.NewReply(t, NewField(FieldData, cc.Server.FlatNews)))
1496
1497 return res, err
1498 }
1499
1500 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1501 if !cc.Authorize(accessDownloadFile) {
1502 res = append(res, cc.NewErrReply(t, "You are not allowed to download files."))
1503 return res, err
1504 }
1505
1506 fileName := t.GetField(FieldFileName).Data
1507 filePath := t.GetField(FieldFilePath).Data
1508 resumeData := t.GetField(FieldFileResumeData).Data
1509
1510 var dataOffset int64
1511 var frd FileResumeData
1512 if resumeData != nil {
1513 if err := frd.UnmarshalBinary(t.GetField(FieldFileResumeData).Data); err != nil {
1514 return res, err
1515 }
1516 // TODO: handle rsrc fork offset
1517 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1518 }
1519
1520 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1521 if err != nil {
1522 return res, err
1523 }
1524
1525 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, dataOffset)
1526 if err != nil {
1527 return res, err
1528 }
1529
1530 xferSize := hlFile.ffo.TransferSize(0)
1531
1532 ft := cc.newFileTransfer(FileDownload, fileName, filePath, xferSize)
1533
1534 // TODO: refactor to remove this
1535 if resumeData != nil {
1536 var frd FileResumeData
1537 if err := frd.UnmarshalBinary(t.GetField(FieldFileResumeData).Data); err != nil {
1538 return res, err
1539 }
1540 ft.fileResumeData = &frd
1541 }
1542
1543 // Optional field for when a HL v1.5+ client requests file preview
1544 // Used only for TEXT, JPEG, GIFF, BMP or PICT files
1545 // The value will always be 2
1546 if t.GetField(FieldFileTransferOptions).Data != nil {
1547 ft.options = t.GetField(FieldFileTransferOptions).Data
1548 xferSize = hlFile.ffo.FlatFileDataForkHeader.DataSize[:]
1549 }
1550
1551 res = append(res, cc.NewReply(t,
1552 NewField(FieldRefNum, ft.refNum[:]),
1553 NewField(FieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1554 NewField(FieldTransferSize, xferSize),
1555 NewField(FieldFileSize, hlFile.ffo.FlatFileDataForkHeader.DataSize[:]),
1556 ))
1557
1558 return res, err
1559 }
1560
1561 // Download all files from the specified folder and sub-folders
1562 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1563 if !cc.Authorize(accessDownloadFile) {
1564 res = append(res, cc.NewErrReply(t, "You are not allowed to download folders."))
1565 return res, err
1566 }
1567
1568 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(FieldFilePath).Data, t.GetField(FieldFileName).Data)
1569 if err != nil {
1570 return res, err
1571 }
1572
1573 transferSize, err := CalcTotalSize(fullFilePath)
1574 if err != nil {
1575 return res, err
1576 }
1577 itemCount, err := CalcItemCount(fullFilePath)
1578 if err != nil {
1579 return res, err
1580 }
1581
1582 fileTransfer := cc.newFileTransfer(FolderDownload, t.GetField(FieldFileName).Data, t.GetField(FieldFilePath).Data, transferSize)
1583
1584 var fp FilePath
1585 _, err = fp.Write(t.GetField(FieldFilePath).Data)
1586 if err != nil {
1587 return res, err
1588 }
1589
1590 res = append(res, cc.NewReply(t,
1591 NewField(FieldRefNum, fileTransfer.ReferenceNumber),
1592 NewField(FieldTransferSize, transferSize),
1593 NewField(FieldFolderItemCount, itemCount),
1594 NewField(FieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1595 ))
1596 return res, err
1597 }
1598
1599 // Upload all files from the local folder and its subfolders to the specified path on the server
1600 // Fields used in the request
1601 // 201 File Name
1602 // 202 File path
1603 // 108 transfer size Total size of all items in the folder
1604 // 220 Folder item count
1605 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1606 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1607 var fp FilePath
1608 if t.GetField(FieldFilePath).Data != nil {
1609 if _, err = fp.Write(t.GetField(FieldFilePath).Data); err != nil {
1610 return res, err
1611 }
1612 }
1613
1614 // Handle special cases for Upload and Drop Box folders
1615 if !cc.Authorize(accessUploadAnywhere) {
1616 if !fp.IsUploadDir() && !fp.IsDropbox() {
1617 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))))
1618 return res, err
1619 }
1620 }
1621
1622 fileTransfer := cc.newFileTransfer(FolderUpload,
1623 t.GetField(FieldFileName).Data,
1624 t.GetField(FieldFilePath).Data,
1625 t.GetField(FieldTransferSize).Data,
1626 )
1627
1628 fileTransfer.FolderItemCount = t.GetField(FieldFolderItemCount).Data
1629
1630 res = append(res, cc.NewReply(t, NewField(FieldRefNum, fileTransfer.ReferenceNumber)))
1631 return res, err
1632 }
1633
1634 // HandleUploadFile
1635 // Fields used in the request:
1636 // 201 File Name
1637 // 202 File path
1638 // 204 File transfer options "Optional
1639 // Used only to resume download, currently has value 2"
1640 // 108 File transfer size "Optional used if download is not resumed"
1641 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1642 if !cc.Authorize(accessUploadFile) {
1643 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1644 return res, err
1645 }
1646
1647 fileName := t.GetField(FieldFileName).Data
1648 filePath := t.GetField(FieldFilePath).Data
1649 transferOptions := t.GetField(FieldFileTransferOptions).Data
1650 transferSize := t.GetField(FieldTransferSize).Data // not sent for resume
1651
1652 var fp FilePath
1653 if filePath != nil {
1654 if _, err = fp.Write(filePath); err != nil {
1655 return res, err
1656 }
1657 }
1658
1659 // Handle special cases for Upload and Drop Box folders
1660 if !cc.Authorize(accessUploadAnywhere) {
1661 if !fp.IsUploadDir() && !fp.IsDropbox() {
1662 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))))
1663 return res, err
1664 }
1665 }
1666 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1667 if err != nil {
1668 return res, err
1669 }
1670
1671 if _, err := cc.Server.FS.Stat(fullFilePath); err == nil {
1672 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))))
1673 return res, err
1674 }
1675
1676 ft := cc.newFileTransfer(FileUpload, fileName, filePath, transferSize)
1677
1678 replyT := cc.NewReply(t, NewField(FieldRefNum, ft.ReferenceNumber))
1679
1680 // client has requested to resume a partially transferred file
1681 if transferOptions != nil {
1682 fileInfo, err := cc.Server.FS.Stat(fullFilePath + incompleteFileSuffix)
1683 if err != nil {
1684 return res, err
1685 }
1686
1687 offset := make([]byte, 4)
1688 binary.BigEndian.PutUint32(offset, uint32(fileInfo.Size()))
1689
1690 fileResumeData := NewFileResumeData([]ForkInfoList{
1691 *NewForkInfoList(offset),
1692 })
1693
1694 b, _ := fileResumeData.BinaryMarshal()
1695
1696 ft.TransferSize = offset
1697
1698 replyT.Fields = append(replyT.Fields, NewField(FieldFileResumeData, b))
1699 }
1700
1701 res = append(res, replyT)
1702 return res, err
1703 }
1704
1705 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1706 if len(t.GetField(FieldUserIconID).Data) == 4 {
1707 cc.Icon = t.GetField(FieldUserIconID).Data[2:]
1708 } else {
1709 cc.Icon = t.GetField(FieldUserIconID).Data
1710 }
1711 if cc.Authorize(accessAnyName) {
1712 cc.UserName = t.GetField(FieldUserName).Data
1713 }
1714
1715 // the options field is only passed by the client versions > 1.2.3.
1716 options := t.GetField(FieldOptions).Data
1717 if options != nil {
1718 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1719 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
1720
1721 flagBitmap.SetBit(flagBitmap, UserFlagRefusePM, optBitmap.Bit(UserOptRefusePM))
1722 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1723
1724 flagBitmap.SetBit(flagBitmap, UserFlagRefusePChat, optBitmap.Bit(UserOptRefuseChat))
1725 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1726
1727 // Check auto response
1728 if optBitmap.Bit(UserOptAutoResponse) == 1 {
1729 cc.AutoReply = t.GetField(FieldAutomaticResponse).Data
1730 } else {
1731 cc.AutoReply = []byte{}
1732 }
1733 }
1734
1735 for _, c := range sortedClients(cc.Server.Clients) {
1736 res = append(res, *NewTransaction(
1737 TranNotifyChangeUser,
1738 c.ID,
1739 NewField(FieldUserID, *cc.ID),
1740 NewField(FieldUserIconID, cc.Icon),
1741 NewField(FieldUserFlags, cc.Flags),
1742 NewField(FieldUserName, cc.UserName),
1743 ))
1744 }
1745
1746 return res, err
1747 }
1748
1749 // HandleKeepAlive responds to keepalive transactions with an empty reply
1750 // * HL 1.9.2 Client sends keepalive msg every 3 minutes
1751 // * HL 1.2.3 Client doesn't send keepalives
1752 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1753 res = append(res, cc.NewReply(t))
1754
1755 return res, err
1756 }
1757
1758 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1759 fullPath, err := readPath(
1760 cc.Server.Config.FileRoot,
1761 t.GetField(FieldFilePath).Data,
1762 nil,
1763 )
1764 if err != nil {
1765 return res, fmt.Errorf("error reading file path: %w", err)
1766 }
1767
1768 var fp FilePath
1769 if t.GetField(FieldFilePath).Data != nil {
1770 if _, err = fp.Write(t.GetField(FieldFilePath).Data); err != nil {
1771 return res, fmt.Errorf("error writing file path: %w", err)
1772 }
1773 }
1774
1775 // Handle special case for drop box folders
1776 if fp.IsDropbox() && !cc.Authorize(accessViewDropBoxes) {
1777 res = append(res, cc.NewErrReply(t, "You are not allowed to view drop boxes."))
1778 return res, err
1779 }
1780
1781 fileNames, err := getFileNameList(fullPath, cc.Server.Config.IgnoreFiles)
1782 if err != nil {
1783 return res, fmt.Errorf("getFileNameList: %w", err)
1784 }
1785
1786 res = append(res, cc.NewReply(t, fileNames...))
1787
1788 return res, err
1789 }
1790
1791 // =================================
1792 // Hotline private chat flow
1793 // =================================
1794 // 1. ClientA sends TranInviteNewChat to server with user ID to invite
1795 // 2. Server creates new ChatID
1796 // 3. Server sends TranInviteToChat to invitee
1797 // 4. Server replies to ClientA with new Chat ID
1798 //
1799 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1800 // If Accepted is clicked:
1801 // 1. ClientB sends TranJoinChat with FieldChatID
1802
1803 // HandleInviteNewChat invites users to new private chat
1804 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1805 if !cc.Authorize(accessOpenChat) {
1806 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1807 return res, err
1808 }
1809
1810 // Client to Invite
1811 targetID := t.GetField(FieldUserID).Data
1812 newChatID := cc.Server.NewPrivateChat(cc)
1813
1814 // Check if target user has "Refuse private chat" flag
1815 binary.BigEndian.Uint16(targetID)
1816 targetClient := cc.Server.Clients[binary.BigEndian.Uint16(targetID)]
1817
1818 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(targetClient.Flags)))
1819 if flagBitmap.Bit(UserFlagRefusePChat) == 1 {
1820 res = append(res,
1821 *NewTransaction(
1822 TranServerMsg,
1823 cc.ID,
1824 NewField(FieldData, []byte(string(targetClient.UserName)+" does not accept private chats.")),
1825 NewField(FieldUserName, targetClient.UserName),
1826 NewField(FieldUserID, *targetClient.ID),
1827 NewField(FieldOptions, []byte{0, 2}),
1828 ),
1829 )
1830 } else {
1831 res = append(res,
1832 *NewTransaction(
1833 TranInviteToChat,
1834 &targetID,
1835 NewField(FieldChatID, newChatID),
1836 NewField(FieldUserName, cc.UserName),
1837 NewField(FieldUserID, *cc.ID),
1838 ),
1839 )
1840 }
1841
1842 res = append(res,
1843 cc.NewReply(t,
1844 NewField(FieldChatID, newChatID),
1845 NewField(FieldUserName, cc.UserName),
1846 NewField(FieldUserID, *cc.ID),
1847 NewField(FieldUserIconID, cc.Icon),
1848 NewField(FieldUserFlags, cc.Flags),
1849 ),
1850 )
1851
1852 return res, err
1853 }
1854
1855 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1856 if !cc.Authorize(accessOpenChat) {
1857 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1858 return res, err
1859 }
1860
1861 // Client to Invite
1862 targetID := t.GetField(FieldUserID).Data
1863 chatID := t.GetField(FieldChatID).Data
1864
1865 res = append(res,
1866 *NewTransaction(
1867 TranInviteToChat,
1868 &targetID,
1869 NewField(FieldChatID, chatID),
1870 NewField(FieldUserName, cc.UserName),
1871 NewField(FieldUserID, *cc.ID),
1872 ),
1873 )
1874 res = append(res,
1875 cc.NewReply(
1876 t,
1877 NewField(FieldChatID, chatID),
1878 NewField(FieldUserName, cc.UserName),
1879 NewField(FieldUserID, *cc.ID),
1880 NewField(FieldUserIconID, cc.Icon),
1881 NewField(FieldUserFlags, cc.Flags),
1882 ),
1883 )
1884
1885 return res, err
1886 }
1887
1888 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1889 chatID := t.GetField(FieldChatID).Data
1890 chatInt := binary.BigEndian.Uint32(chatID)
1891
1892 privChat := cc.Server.PrivateChats[chatInt]
1893
1894 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1895
1896 for _, c := range sortedClients(privChat.ClientConn) {
1897 res = append(res,
1898 *NewTransaction(
1899 TranChatMsg,
1900 c.ID,
1901 NewField(FieldChatID, chatID),
1902 NewField(FieldData, resMsg),
1903 ),
1904 )
1905 }
1906
1907 return res, err
1908 }
1909
1910 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1911 // Fields used in the reply:
1912 // * 115 Chat subject
1913 // * 300 User Name with info (Optional)
1914 // * 300 (more user names with info)
1915 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1916 chatID := t.GetField(FieldChatID).Data
1917 chatInt := binary.BigEndian.Uint32(chatID)
1918
1919 privChat := cc.Server.PrivateChats[chatInt]
1920
1921 // Send TranNotifyChatChangeUser to current members of the chat to inform of new user
1922 for _, c := range sortedClients(privChat.ClientConn) {
1923 res = append(res,
1924 *NewTransaction(
1925 TranNotifyChatChangeUser,
1926 c.ID,
1927 NewField(FieldChatID, chatID),
1928 NewField(FieldUserName, cc.UserName),
1929 NewField(FieldUserID, *cc.ID),
1930 NewField(FieldUserIconID, cc.Icon),
1931 NewField(FieldUserFlags, cc.Flags),
1932 ),
1933 )
1934 }
1935
1936 privChat.ClientConn[cc.uint16ID()] = cc
1937
1938 replyFields := []Field{NewField(FieldChatSubject, []byte(privChat.Subject))}
1939 for _, c := range sortedClients(privChat.ClientConn) {
1940
1941 b, err := io.ReadAll(&User{
1942 ID: *c.ID,
1943 Icon: c.Icon,
1944 Flags: c.Flags,
1945 Name: string(c.UserName),
1946 })
1947 if err != nil {
1948 return res, nil
1949 }
1950 replyFields = append(replyFields, NewField(FieldUsernameWithInfo, b))
1951 }
1952
1953 res = append(res, cc.NewReply(t, replyFields...))
1954 return res, err
1955 }
1956
1957 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1958 // Fields used in the request:
1959 // - 114 FieldChatID
1960 //
1961 // Reply is not expected.
1962 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1963 chatID := t.GetField(FieldChatID).Data
1964 chatInt := binary.BigEndian.Uint32(chatID)
1965
1966 privChat, ok := cc.Server.PrivateChats[chatInt]
1967 if !ok {
1968 return res, nil
1969 }
1970
1971 delete(privChat.ClientConn, cc.uint16ID())
1972
1973 // Notify members of the private chat that the user has left
1974 for _, c := range sortedClients(privChat.ClientConn) {
1975 res = append(res,
1976 *NewTransaction(
1977 TranNotifyChatDeleteUser,
1978 c.ID,
1979 NewField(FieldChatID, chatID),
1980 NewField(FieldUserID, *cc.ID),
1981 ),
1982 )
1983 }
1984
1985 return res, err
1986 }
1987
1988 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1989 // Fields used in the request:
1990 // * 114 Chat ID
1991 // * 115 Chat subject
1992 // Reply is not expected.
1993 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1994 chatID := t.GetField(FieldChatID).Data
1995 chatInt := binary.BigEndian.Uint32(chatID)
1996
1997 privChat := cc.Server.PrivateChats[chatInt]
1998 privChat.Subject = string(t.GetField(FieldChatSubject).Data)
1999
2000 for _, c := range sortedClients(privChat.ClientConn) {
2001 res = append(res,
2002 *NewTransaction(
2003 TranNotifyChatSubject,
2004 c.ID,
2005 NewField(FieldChatID, chatID),
2006 NewField(FieldChatSubject, t.GetField(FieldChatSubject).Data),
2007 ),
2008 )
2009 }
2010
2011 return res, err
2012 }
2013
2014 // HandleMakeAlias makes a file alias using the specified path.
2015 // Fields used in the request:
2016 // 201 File Name
2017 // 202 File path
2018 // 212 File new path Destination path
2019 //
2020 // Fields used in the reply:
2021 // None
2022 func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
2023 if !cc.Authorize(accessMakeAlias) {
2024 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
2025 return res, err
2026 }
2027 fileName := t.GetField(FieldFileName).Data
2028 filePath := t.GetField(FieldFilePath).Data
2029 fileNewPath := t.GetField(FieldFileNewPath).Data
2030
2031 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
2032 if err != nil {
2033 return res, err
2034 }
2035
2036 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
2037 if err != nil {
2038 return res, err
2039 }
2040
2041 cc.logger.Debug("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
2042
2043 if err := cc.Server.FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
2044 res = append(res, cc.NewErrReply(t, "Error creating alias"))
2045 return res, nil
2046 }
2047
2048 res = append(res, cc.NewReply(t))
2049 return res, err
2050 }
2051
2052 // HandleDownloadBanner handles requests for a new banner from the server
2053 // Fields used in the request:
2054 // None
2055 // Fields used in the reply:
2056 // 107 FieldRefNum Used later for transfer
2057 // 108 FieldTransferSize Size of data to be downloaded
2058 func HandleDownloadBanner(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
2059 ft := cc.newFileTransfer(bannerDownload, []byte{}, []byte{}, make([]byte, 4))
2060 binary.BigEndian.PutUint32(ft.TransferSize, uint32(len(cc.Server.banner)))
2061
2062 return append(res, cc.NewReply(t,
2063 NewField(FieldRefNum, ft.refNum[:]),
2064 NewField(FieldTransferSize, ft.TransferSize),
2065 )), err
2066 }