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