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