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