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