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