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