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