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