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