]> git.r.bdr.sh - rbdr/mobius/blob - hotline/transaction_handlers.go
b06297dc6926169d2dceebcb69e96ad699b1e746
[rbdr/mobius] / hotline / transaction_handlers.go
1 package hotline
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7 "fmt"
8 "github.com/davecgh/go-spew/spew"
9 "gopkg.in/yaml.v2"
10 "io/ioutil"
11 "math/big"
12 "os"
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: accessSendChat,
54 DenyMsg: "You are not allowed to participate in chat.",
55 Handler: HandleChatSend,
56 Name: "tranChatSend",
57 RequiredFields: []requiredField{
58 {
59 ID: fieldData,
60 minLen: 0,
61 },
62 },
63 },
64 tranDelNewsArt: {
65 Access: accessNewsDeleteArt,
66 DenyMsg: "You are not allowed to delete news articles.",
67 Name: "tranDelNewsArt",
68 Handler: HandleDelNewsArt,
69 },
70 tranDelNewsItem: {
71 Access: accessAlwaysAllow, // Granular access enforced inside the handler
72 // Has multiple access flags: News Delete Folder (37) or News Delete Category (35)
73 // TODO: Implement inside the handler
74 Name: "tranDelNewsItem",
75 Handler: HandleDelNewsItem,
76 },
77 tranDeleteFile: {
78 Access: accessAlwaysAllow, // Granular access enforced inside the handler
79 Name: "tranDeleteFile",
80 Handler: HandleDeleteFile,
81 },
82 tranDeleteUser: {
83 Access: accessDeleteUser,
84 DenyMsg: "You are not allowed to delete accounts.",
85 Name: "tranDeleteUser",
86 Handler: HandleDeleteUser,
87 },
88 tranDisconnectUser: {
89 Access: accessDisconUser,
90 DenyMsg: "You are not allowed to disconnect users.",
91 Name: "tranDisconnectUser",
92 Handler: HandleDisconnectUser,
93 },
94 tranDownloadFile: {
95 Access: accessDownloadFile,
96 DenyMsg: "You are not allowed to download files.",
97 Name: "tranDownloadFile",
98 Handler: HandleDownloadFile,
99 },
100 tranDownloadFldr: {
101 Access: accessDownloadFile, // There is no specific access flag for folder vs file download
102 DenyMsg: "You are not allowed to download files.",
103 Name: "tranDownloadFldr",
104 Handler: HandleDownloadFolder,
105 },
106 tranGetClientInfoText: {
107 Access: accessGetClientInfo,
108 DenyMsg: "You are not allowed to get client info",
109 Name: "tranGetClientInfoText",
110 Handler: HandleGetClientConnInfoText,
111 },
112 tranGetFileInfo: {
113 Access: accessAlwaysAllow,
114 Name: "tranGetFileInfo",
115 Handler: HandleGetFileInfo,
116 },
117 tranGetFileNameList: {
118 Access: accessAlwaysAllow,
119 Name: "tranGetFileNameList",
120 Handler: HandleGetFileNameList,
121 },
122 tranGetMsgs: {
123 Access: accessNewsReadArt,
124 DenyMsg: "You are not allowed to read news.",
125 Name: "tranGetMsgs",
126 Handler: HandleGetMsgs,
127 },
128 tranGetNewsArtData: {
129 Access: accessNewsReadArt,
130 DenyMsg: "You are not allowed to read news.",
131 Name: "tranGetNewsArtData",
132 Handler: HandleGetNewsArtData,
133 },
134 tranGetNewsArtNameList: {
135 Access: accessNewsReadArt,
136 DenyMsg: "You are not allowed to read news.",
137 Name: "tranGetNewsArtNameList",
138 Handler: HandleGetNewsArtNameList,
139 },
140 tranGetNewsCatNameList: {
141 Access: accessNewsReadArt,
142 DenyMsg: "You are not allowed to read news.",
143 Name: "tranGetNewsCatNameList",
144 Handler: HandleGetNewsCatNameList,
145 },
146 tranGetUser: {
147 Access: accessOpenUser,
148 DenyMsg: "You are not allowed to view accounts.",
149 Name: "tranGetUser",
150 Handler: HandleGetUser,
151 },
152 tranGetUserNameList: {
153 Access: accessAlwaysAllow,
154 Name: "tranHandleGetUserNameList",
155 Handler: HandleGetUserNameList,
156 },
157 tranInviteNewChat: {
158 Access: accessOpenChat,
159 DenyMsg: "You are not allowed to request private chat.",
160 Name: "tranInviteNewChat",
161 Handler: HandleInviteNewChat,
162 },
163 tranInviteToChat: {
164 Access: accessOpenChat,
165 DenyMsg: "You are not allowed to request private chat.",
166 Name: "tranInviteToChat",
167 Handler: HandleInviteToChat,
168 },
169 tranJoinChat: {
170 Access: accessAlwaysAllow,
171 Name: "tranJoinChat",
172 Handler: HandleJoinChat,
173 },
174 tranKeepAlive: {
175 Access: accessAlwaysAllow,
176 Name: "tranKeepAlive",
177 Handler: HandleKeepAlive,
178 },
179 tranLeaveChat: {
180 Access: accessAlwaysAllow,
181 Name: "tranJoinChat",
182 Handler: HandleLeaveChat,
183 },
184
185 tranListUsers: {
186 Access: accessOpenUser,
187 DenyMsg: "You are not allowed to view accounts.",
188 Name: "tranListUsers",
189 Handler: HandleListUsers,
190 },
191 tranMoveFile: {
192 Access: accessMoveFile,
193 DenyMsg: "You are not allowed to move files.",
194 Name: "tranMoveFile",
195 Handler: HandleMoveFile,
196 },
197 tranNewFolder: {
198 Access: accessCreateFolder,
199 DenyMsg: "You are not allow to create folders.",
200 Name: "tranNewFolder",
201 Handler: HandleNewFolder,
202 },
203 tranNewNewsCat: {
204 Access: accessNewsCreateCat,
205 DenyMsg: "You are not allowed to create news categories.",
206 Name: "tranNewNewsCat",
207 Handler: HandleNewNewsCat,
208 },
209 tranNewNewsFldr: {
210 Access: accessNewsCreateFldr,
211 DenyMsg: "You are not allowed to create news folders.",
212 Name: "tranNewNewsFldr",
213 Handler: HandleNewNewsFldr,
214 },
215 tranNewUser: {
216 Access: accessCreateUser,
217 DenyMsg: "You are not allowed to create new accounts.",
218 Name: "tranNewUser",
219 Handler: HandleNewUser,
220 },
221 tranOldPostNews: {
222 Access: accessNewsPostArt,
223 DenyMsg: "You are not allowed to post news.",
224 Name: "tranOldPostNews",
225 Handler: HandleTranOldPostNews,
226 },
227 tranPostNewsArt: {
228 Access: accessNewsPostArt,
229 DenyMsg: "You are not allowed to post news articles.",
230 Name: "tranPostNewsArt",
231 Handler: HandlePostNewsArt,
232 },
233 tranRejectChatInvite: {
234 Access: accessAlwaysAllow,
235 Name: "tranRejectChatInvite",
236 Handler: HandleRejectChatInvite,
237 },
238 tranSendInstantMsg: {
239 Access: accessAlwaysAllow,
240 //Access: accessSendPrivMsg,
241 //DenyMsg: "You are not allowed to send private messages",
242 Name: "tranSendInstantMsg",
243 Handler: HandleSendInstantMsg,
244 RequiredFields: []requiredField{
245 {
246 ID: fieldData,
247 minLen: 0,
248 },
249 {
250 ID: fieldUserID,
251 },
252 },
253 },
254 tranSetChatSubject: {
255 Access: accessAlwaysAllow,
256 Name: "tranSetChatSubject",
257 Handler: HandleSetChatSubject,
258 },
259 tranSetClientUserInfo: {
260 Access: accessAlwaysAllow,
261 Name: "tranSetClientUserInfo",
262 Handler: HandleSetClientUserInfo,
263 },
264 tranSetFileInfo: {
265 Access: accessAlwaysAllow, // granular access is in the handler
266 Name: "tranSetFileInfo",
267 Handler: HandleSetFileInfo,
268 },
269 tranSetUser: {
270 Access: accessModifyUser,
271 DenyMsg: "You are not allowed to modify accounts.",
272 Name: "tranSetUser",
273 Handler: HandleSetUser,
274 },
275 tranUploadFile: {
276 Access: accessUploadFile,
277 DenyMsg: "You are not allowed to upload files.",
278 Name: "tranUploadFile",
279 Handler: HandleUploadFile,
280 },
281 tranUploadFldr: {
282 Access: accessAlwaysAllow, // TODO: what should this be?
283 Name: "tranUploadFldr",
284 Handler: HandleUploadFolder,
285 },
286 tranUserBroadcast: {
287 Access: accessBroadcast,
288 DenyMsg: "You are not allowed to send broadcast messages.",
289 Name: "tranUserBroadcast",
290 Handler: HandleUserBroadcast,
291 },
292 }
293
294 func HandleChatSend(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
295 // Truncate long usernames
296 trunc := fmt.Sprintf("%13s", *cc.UserName)
297 formattedMsg := fmt.Sprintf("\r%.14s: %s", trunc, t.GetField(fieldData).Data)
298
299 // By holding the option key, Hotline chat allows users to send /me formatted messages like:
300 // *** Halcyon does stuff
301 // This is indicated by the presence of the optional field fieldChatOptions in the transaction payload
302 if t.GetField(fieldChatOptions).Data != nil {
303 formattedMsg = fmt.Sprintf("*** %s %s\r", *cc.UserName, t.GetField(fieldData).Data)
304 }
305
306 if bytes.Equal(t.GetField(fieldData).Data, []byte("/stats")) {
307 formattedMsg = strings.Replace(cc.Server.Stats.String(), "\n", "\r", -1)
308 }
309
310 chatID := t.GetField(fieldChatID).Data
311 // a non-nil chatID indicates the message belongs to a private chat
312 if chatID != nil {
313 chatInt := binary.BigEndian.Uint32(chatID)
314 privChat := cc.Server.PrivateChats[chatInt]
315
316 // send the message to all connected clients of the private chat
317 for _, c := range privChat.ClientConn {
318 res = append(res, *NewTransaction(
319 tranChatMsg,
320 c.ID,
321 NewField(fieldChatID, chatID),
322 NewField(fieldData, []byte(formattedMsg)),
323 ))
324 }
325 return res, err
326 }
327
328 for _, c := range sortedClients(cc.Server.Clients) {
329 // Filter out clients that do not have the read chat permission
330 if authorize(c.Account.Access, accessReadChat) {
331 res = append(res, *NewTransaction(tranChatMsg, c.ID, NewField(fieldData, []byte(formattedMsg))))
332 }
333 }
334
335 return res, err
336 }
337
338 // HandleSendInstantMsg sends instant message to the user on the current server.
339 // Fields used in the request:
340 // 103 User ID
341 // 113 Options
342 // One of the following values:
343 // - User message (myOpt_UserMessage = 1)
344 // - Refuse message (myOpt_RefuseMessage = 2)
345 // - Refuse chat (myOpt_RefuseChat = 3)
346 // - Automatic response (myOpt_AutomaticResponse = 4)"
347 // 101 Data Optional
348 // 214 Quoting message Optional
349 //
350 //Fields used in the reply:
351 // None
352 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
353 msg := t.GetField(fieldData)
354 ID := t.GetField(fieldUserID)
355 // TODO: Implement reply quoting
356 //options := transaction.GetField(hotline.fieldOptions)
357
358 res = append(res,
359 *NewTransaction(
360 tranServerMsg,
361 &ID.Data,
362 NewField(fieldData, msg.Data),
363 NewField(fieldUserName, *cc.UserName),
364 NewField(fieldUserID, *cc.ID),
365 NewField(fieldOptions, []byte{0, 1}),
366 ),
367 )
368 id, _ := byteToInt(ID.Data)
369
370 //keys := make([]uint16, 0, len(cc.Server.Clients))
371 //for k := range cc.Server.Clients {
372 // keys = append(keys, k)
373 //}
374
375 otherClient := cc.Server.Clients[uint16(id)]
376 if otherClient == nil {
377 return res, errors.New("ohno")
378 }
379
380 // Respond with auto reply if other client has it enabled
381 if len(*otherClient.AutoReply) > 0 {
382 res = append(res,
383 *NewTransaction(
384 tranServerMsg,
385 cc.ID,
386 NewField(fieldData, *otherClient.AutoReply),
387 NewField(fieldUserName, *otherClient.UserName),
388 NewField(fieldUserID, *otherClient.ID),
389 NewField(fieldOptions, []byte{0, 1}),
390 ),
391 )
392 }
393
394 res = append(res, cc.NewReply(t))
395
396 return res, err
397 }
398
399 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
400 fileName := string(t.GetField(fieldFileName).Data)
401 filePath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
402 spew.Dump(cc.Server.Config.FileRoot)
403
404 ffo, err := NewFlattenedFileObject(filePath, fileName)
405 if err != nil {
406 return res, err
407 }
408
409 res = append(res, cc.NewReply(t,
410 NewField(fieldFileName, []byte(fileName)),
411 NewField(fieldFileTypeString, ffo.FlatFileInformationFork.TypeSignature),
412 NewField(fieldFileCreatorString, ffo.FlatFileInformationFork.CreatorSignature),
413 NewField(fieldFileComment, ffo.FlatFileInformationFork.Comment),
414 NewField(fieldFileType, ffo.FlatFileInformationFork.TypeSignature),
415 NewField(fieldFileCreateDate, ffo.FlatFileInformationFork.CreateDate),
416 NewField(fieldFileModifyDate, ffo.FlatFileInformationFork.ModifyDate),
417 NewField(fieldFileSize, ffo.FlatFileDataForkHeader.DataSize),
418 ))
419 return res, err
420 }
421
422 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
423 // TODO: Implement support for comments
424 // Fields used in the request:
425 // * 201 File name
426 // * 202 File path Optional
427 // * 211 File new name Optional
428 // * 210 File comment Optional
429 // Fields used in the reply: None
430 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
431 fileName := string(t.GetField(fieldFileName).Data)
432 filePath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
433 //fileComment := t.GetField(fieldFileComment).Data
434 fileNewName := t.GetField(fieldFileNewName).Data
435
436 if fileNewName != nil {
437 path := filePath + "/" + fileName
438 fi, err := os.Stat(path)
439 if err != nil {
440 return res, err
441 }
442 switch mode := fi.Mode(); {
443 case mode.IsDir():
444 if !authorize(cc.Account.Access, accessRenameFolder) {
445 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
446 return res, err
447 }
448 case mode.IsRegular():
449 if !authorize(cc.Account.Access, accessRenameFile) {
450 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
451 return res, err
452 }
453 }
454
455 err = os.Rename(filePath+"/"+fileName, filePath+"/"+string(fileNewName))
456 if os.IsNotExist(err) {
457 res = append(res, cc.NewErrReply(t, "Cannot rename file "+fileName+" because it does not exist or cannot be found."))
458 return res, err
459 }
460 }
461
462 res = append(res, cc.NewReply(t))
463 return res, err
464 }
465
466 // HandleDeleteFile deletes a file or folder
467 // Fields used in the request:
468 // * 201 File name
469 // * 202 File path
470 // Fields used in the reply: none
471 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
472 fileName := string(t.GetField(fieldFileName).Data)
473 filePath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
474
475 path := "./" + filePath + "/" + fileName
476
477 cc.Server.Logger.Debugw("Delete file", "src", filePath+"/"+fileName)
478
479 fi, err := os.Stat(path)
480 if err != nil {
481 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
482 return res, nil
483 }
484 switch mode := fi.Mode(); {
485 case mode.IsDir():
486 if !authorize(cc.Account.Access, accessDeleteFolder) {
487 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
488 return res, err
489 }
490 case mode.IsRegular():
491 if !authorize(cc.Account.Access, accessDeleteFile) {
492 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
493 return res, err
494 }
495 }
496
497 if err := os.RemoveAll(path); err != nil {
498 return res, err
499 }
500
501 res = append(res, cc.NewReply(t))
502 return res, err
503 }
504
505 // HandleMoveFile moves files or folders. Note: seemingly not documented
506 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
507 fileName := string(t.GetField(fieldFileName).Data)
508 filePath := "./" + cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
509 fileNewPath := "./" + cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFileNewPath).Data)
510
511 cc.Server.Logger.Debugw("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
512
513 path := filePath + "/" + fileName
514 fi, err := os.Stat(path)
515 if err != nil {
516 return res, err
517 }
518 switch mode := fi.Mode(); {
519 case mode.IsDir():
520 if !authorize(cc.Account.Access, accessMoveFolder) {
521 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
522 return res, err
523 }
524 case mode.IsRegular():
525 if !authorize(cc.Account.Access, accessMoveFile) {
526 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
527 return res, err
528 }
529 }
530
531 err = os.Rename(filePath+"/"+fileName, fileNewPath+"/"+fileName)
532 if os.IsNotExist(err) {
533 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
534 return res, err
535 }
536 if err != nil {
537 return []Transaction{}, err
538 }
539 // TODO: handle other possible errors; e.g. file delete fails due to file permission issue
540
541 res = append(res, cc.NewReply(t))
542 return res, err
543 }
544
545 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
546 newFolderPath := cc.Server.Config.FileRoot
547
548 // fieldFilePath is only present for nested paths
549 if t.GetField(fieldFilePath).Data != nil {
550 newFp := NewFilePath(t.GetField(fieldFilePath).Data)
551 newFolderPath += newFp.String()
552 }
553 newFolderPath += "/" + string(t.GetField(fieldFileName).Data)
554
555 if err := os.Mkdir(newFolderPath, 0777); err != nil {
556 // TODO: Send error response to client
557 return []Transaction{}, err
558 }
559
560 res = append(res, cc.NewReply(t))
561 return res, err
562 }
563
564 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
565 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
566 userName := string(t.GetField(fieldUserName).Data)
567
568 newAccessLvl := t.GetField(fieldUserAccess).Data
569
570 account := cc.Server.Accounts[login]
571 account.Access = &newAccessLvl
572 account.Name = userName
573
574 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
575 // not include fieldUserPassword
576 if t.GetField(fieldUserPassword).Data == nil {
577 account.Password = hashAndSalt([]byte(""))
578 }
579 if len(t.GetField(fieldUserPassword).Data) > 1 {
580 account.Password = hashAndSalt(t.GetField(fieldUserPassword).Data)
581 }
582
583 file := cc.Server.ConfigDir + "Users/" + login + ".yaml"
584 out, err := yaml.Marshal(&account)
585 if err != nil {
586 return res, err
587 }
588 if err := ioutil.WriteFile(file, out, 0666); err != nil {
589 return res, err
590 }
591
592 // Notify connected clients logged in as the user of the new access level
593 for _, c := range cc.Server.Clients {
594 if c.Account.Login == login {
595 // Note: comment out these two lines to test server-side deny messages
596 newT := NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, newAccessLvl))
597 res = append(res, *newT)
598
599 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
600 if authorize(c.Account.Access, accessDisconUser) {
601 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 1)
602 } else {
603 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 0)
604 }
605 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
606
607 c.Account.Access = account.Access
608
609 cc.sendAll(
610 tranNotifyChangeUser,
611 NewField(fieldUserID, *c.ID),
612 NewField(fieldUserFlags, *c.Flags),
613 NewField(fieldUserName, *c.UserName),
614 NewField(fieldUserIconID, *c.Icon),
615 )
616 }
617 }
618
619 // TODO: If we have just promoted a connected user to admin, notify
620 // connected clients to turn the user red
621
622 res = append(res, cc.NewReply(t))
623 return res, err
624 }
625
626 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
627 userLogin := string(t.GetField(fieldUserLogin).Data)
628 decodedUserLogin := NegatedUserString(t.GetField(fieldUserLogin).Data)
629 account := cc.Server.Accounts[userLogin]
630 if account == nil {
631 errorT := cc.NewErrReply(t, "Account does not exist.")
632 res = append(res, errorT)
633 return res, err
634 }
635
636 res = append(res, cc.NewReply(t,
637 NewField(fieldUserName, []byte(account.Name)),
638 NewField(fieldUserLogin, []byte(decodedUserLogin)),
639 NewField(fieldUserPassword, []byte(account.Password)),
640 NewField(fieldUserAccess, *account.Access),
641 ))
642 return res, err
643 }
644
645 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
646 var userFields []Field
647 // TODO: make order deterministic
648 for _, acc := range cc.Server.Accounts {
649 userField := acc.Payload()
650 userFields = append(userFields, NewField(fieldData, userField))
651 }
652
653 res = append(res, cc.NewReply(t, userFields...))
654 return res, err
655 }
656
657 // HandleNewUser creates a new user account
658 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
659 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
660
661 // If the account already exists, reply with an error
662 // TODO: make order deterministic
663 if _, ok := cc.Server.Accounts[login]; ok {
664 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
665 return res, err
666 }
667
668 if err := cc.Server.NewUser(
669 login,
670 string(t.GetField(fieldUserName).Data),
671 string(t.GetField(fieldUserPassword).Data),
672 t.GetField(fieldUserAccess).Data,
673 ); err != nil {
674 return []Transaction{}, err
675 }
676
677 res = append(res, cc.NewReply(t))
678 return res, err
679 }
680
681 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
682 // TODO: Handle case where account doesn't exist; e.g. delete race condition
683 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
684
685 if err := cc.Server.DeleteUser(login); err != nil {
686 return res, err
687 }
688
689 res = append(res, cc.NewReply(t))
690 return res, err
691 }
692
693 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
694 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
695 cc.sendAll(
696 tranServerMsg,
697 NewField(fieldData, t.GetField(tranGetMsgs).Data),
698 NewField(fieldChatOptions, []byte{0}),
699 )
700
701 res = append(res, cc.NewReply(t))
702 return res, err
703 }
704
705 func byteToInt(bytes []byte) (int, error) {
706 switch len(bytes) {
707 case 2:
708 return int(binary.BigEndian.Uint16(bytes)), nil
709 case 4:
710 return int(binary.BigEndian.Uint32(bytes)), nil
711 }
712
713 return 0, errors.New("unknown byte length")
714 }
715
716 func HandleGetClientConnInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
717 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
718
719 clientConn := cc.Server.Clients[uint16(clientID)]
720 if clientConn == nil {
721 return res, errors.New("invalid client")
722 }
723
724 // TODO: Implement non-hardcoded values
725 template := `Nickname: %s
726 Name: %s
727 Account: %s
728 Address: %s
729
730 -------- File Downloads ---------
731
732 %s
733
734 ------- Folder Downloads --------
735
736 None.
737
738 --------- File Uploads ----------
739
740 None.
741
742 -------- Folder Uploads ---------
743
744 None.
745
746 ------- Waiting Downloads -------
747
748 None.
749
750 `
751
752 activeDownloads := clientConn.Transfers[FileDownload]
753 activeDownloadList := "None."
754 for _, dl := range activeDownloads {
755 activeDownloadList += dl.String() + "\n"
756 }
757
758 template = fmt.Sprintf(
759 template,
760 *clientConn.UserName,
761 clientConn.Account.Name,
762 clientConn.Account.Login,
763 clientConn.Connection.RemoteAddr().String(),
764 activeDownloadList,
765 )
766 template = strings.Replace(template, "\n", "\r", -1)
767
768 res = append(res, cc.NewReply(t,
769 NewField(fieldData, []byte(template)),
770 NewField(fieldUserName, *clientConn.UserName),
771 ))
772 return res, err
773 }
774
775 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
776 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
777
778 return res, err
779 }
780
781 func (cc *ClientConn) notifyNewUserHasJoined() (res []Transaction, err error) {
782 // Notify other ccs that a new user has connected
783 cc.NotifyOthers(
784 *NewTransaction(
785 tranNotifyChangeUser, nil,
786 NewField(fieldUserName, *cc.UserName),
787 NewField(fieldUserID, *cc.ID),
788 NewField(fieldUserIconID, *cc.Icon),
789 NewField(fieldUserFlags, *cc.Flags),
790 ),
791 )
792
793 return res, nil
794 }
795
796 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
797 bs := make([]byte, 2)
798 binary.BigEndian.PutUint16(bs, *cc.Server.NextGuestID)
799
800 *cc.UserName = t.GetField(fieldUserName).Data
801 *cc.ID = bs
802 *cc.Icon = t.GetField(fieldUserIconID).Data
803
804 options := t.GetField(fieldOptions).Data
805 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
806
807 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
808
809 // Check refuse private PM option
810 if optBitmap.Bit(refusePM) == 1 {
811 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
812 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
813 }
814
815 // Check refuse private chat option
816 if optBitmap.Bit(refuseChat) == 1 {
817 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
818 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
819 }
820
821 // Check auto response
822 if optBitmap.Bit(autoResponse) == 1 {
823 *cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
824 } else {
825 *cc.AutoReply = []byte{}
826 }
827
828 _, _ = cc.notifyNewUserHasJoined()
829
830 res = append(res, cc.NewReply(t))
831
832 return res, err
833 }
834
835 const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
836 // "Mon, 02 Jan 2006 15:04:05 MST"
837
838 const defaultNewsTemplate = `From %s (%s):
839
840 %s
841
842 __________________________________________________________`
843
844 // HandleTranOldPostNews updates the flat news
845 // Fields used in this request:
846 // 101 Data
847 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
848 cc.Server.flatNewsMux.Lock()
849 defer cc.Server.flatNewsMux.Unlock()
850
851 newsDateTemplate := defaultNewsDateFormat
852 if cc.Server.Config.NewsDateFormat != "" {
853 newsDateTemplate = cc.Server.Config.NewsDateFormat
854 }
855
856 newsTemplate := defaultNewsTemplate
857 if cc.Server.Config.NewsDelimiter != "" {
858 newsTemplate = cc.Server.Config.NewsDelimiter
859 }
860
861 newsPost := fmt.Sprintf(newsTemplate+"\r", *cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
862 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
863
864 // update news in memory
865 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
866
867 // update news on disk
868 if err := ioutil.WriteFile(cc.Server.ConfigDir+"MessageBoard.txt", cc.Server.FlatNews, 0644); err != nil {
869 return res, err
870 }
871
872 // Notify all clients of updated news
873 cc.sendAll(
874 tranNewMsg,
875 NewField(fieldData, []byte(newsPost)),
876 )
877
878 res = append(res, cc.NewReply(t))
879 return res, err
880 }
881
882 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
883 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
884
885 if authorize(clientConn.Account.Access, accessCannotBeDiscon) {
886 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
887 return res, err
888 }
889
890 if err := clientConn.Connection.Close(); err != nil {
891 return res, err
892 }
893
894 res = append(res, cc.NewReply(t))
895 return res, err
896 }
897
898 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
899 // Fields used in the request:
900 // 325 News path (Optional)
901
902 newsPath := t.GetField(fieldNewsPath).Data
903 cc.Server.Logger.Infow("NewsPath: ", "np", string(newsPath))
904
905 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
906 cats := cc.Server.GetNewsCatByPath(pathStrs)
907
908 // To store the keys in slice in sorted order
909 keys := make([]string, len(cats))
910 i := 0
911 for k := range cats {
912 keys[i] = k
913 i++
914 }
915 sort.Strings(keys)
916
917 var fieldData []Field
918 for _, k := range keys {
919 cat := cats[k]
920 fieldData = append(fieldData, NewField(
921 fieldNewsCatListData15,
922 cat.Payload(),
923 ))
924 }
925
926 res = append(res, cc.NewReply(t, fieldData...))
927 return res, err
928 }
929
930 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
931 name := string(t.GetField(fieldNewsCatName).Data)
932 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
933
934 cats := cc.Server.GetNewsCatByPath(pathStrs)
935 cats[name] = NewsCategoryListData15{
936 Name: name,
937 Type: []byte{0, 3},
938 Articles: map[uint32]*NewsArtData{},
939 SubCats: make(map[string]NewsCategoryListData15),
940 }
941
942 if err := cc.Server.writeThreadedNews(); err != nil {
943 return res, err
944 }
945 res = append(res, cc.NewReply(t))
946 return res, err
947 }
948
949 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
950 // Fields used in the request:
951 // 322 News category name
952 // 325 News path
953 name := string(t.GetField(fieldFileName).Data)
954 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
955
956 cc.Server.Logger.Infof("Creating new news folder %s", name)
957
958 cats := cc.Server.GetNewsCatByPath(pathStrs)
959 cats[name] = NewsCategoryListData15{
960 Name: name,
961 Type: []byte{0, 2},
962 Articles: map[uint32]*NewsArtData{},
963 SubCats: make(map[string]NewsCategoryListData15),
964 }
965 if err := cc.Server.writeThreadedNews(); err != nil {
966 return res, err
967 }
968 res = append(res, cc.NewReply(t))
969 return res, err
970 }
971
972 // Fields used in the request:
973 // 325 News path Optional
974 //
975 // Reply fields:
976 // 321 News article list data Optional
977 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
978 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
979
980 var cat NewsCategoryListData15
981 cats := cc.Server.ThreadedNews.Categories
982
983 for _, path := range pathStrs {
984 cat = cats[path]
985 cats = cats[path].SubCats
986 }
987
988 nald := cat.GetNewsArtListData()
989
990 res = append(res, cc.NewReply(t, NewField(fieldNewsArtListData, nald.Payload())))
991 return res, err
992 }
993
994 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
995 // Request fields
996 // 325 News path
997 // 326 News article ID
998 // 327 News article data flavor
999
1000 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1001
1002 var cat NewsCategoryListData15
1003 cats := cc.Server.ThreadedNews.Categories
1004
1005 for _, path := range pathStrs {
1006 cat = cats[path]
1007 cats = cats[path].SubCats
1008 }
1009 newsArtID := t.GetField(fieldNewsArtID).Data
1010
1011 convertedArtID := binary.BigEndian.Uint16(newsArtID)
1012
1013 art := cat.Articles[uint32(convertedArtID)]
1014 if art == nil {
1015 res = append(res, cc.NewReply(t))
1016 return res, err
1017 }
1018
1019 // Reply fields
1020 // 328 News article title
1021 // 329 News article poster
1022 // 330 News article date
1023 // 331 Previous article ID
1024 // 332 Next article ID
1025 // 335 Parent article ID
1026 // 336 First child article ID
1027 // 327 News article data flavor "Should be “text/plain”
1028 // 333 News article data Optional (if data flavor is “text/plain”)
1029
1030 res = append(res, cc.NewReply(t,
1031 NewField(fieldNewsArtTitle, []byte(art.Title)),
1032 NewField(fieldNewsArtPoster, []byte(art.Poster)),
1033 NewField(fieldNewsArtDate, art.Date),
1034 NewField(fieldNewsArtPrevArt, art.PrevArt),
1035 NewField(fieldNewsArtNextArt, art.NextArt),
1036 NewField(fieldNewsArtParentArt, art.ParentArt),
1037 NewField(fieldNewsArt1stChildArt, art.FirstChildArt),
1038 NewField(fieldNewsArtDataFlav, []byte("text/plain")),
1039 NewField(fieldNewsArtData, []byte(art.Data)),
1040 ))
1041 return res, err
1042 }
1043
1044 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1045 // Access: News Delete Folder (37) or News Delete Category (35)
1046
1047 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1048
1049 // TODO: determine if path is a Folder (Bundle) or Category and check for permission
1050
1051 cc.Server.Logger.Infof("DelNewsItem %v", pathStrs)
1052
1053 cats := cc.Server.ThreadedNews.Categories
1054
1055 delName := pathStrs[len(pathStrs)-1]
1056 if len(pathStrs) > 1 {
1057 for _, path := range pathStrs[0 : len(pathStrs)-1] {
1058 cats = cats[path].SubCats
1059 }
1060 }
1061
1062 delete(cats, delName)
1063
1064 err = cc.Server.writeThreadedNews()
1065 if err != nil {
1066 return res, err
1067 }
1068
1069 // Reply params: none
1070 res = append(res, cc.NewReply(t))
1071
1072 return res, err
1073 }
1074
1075 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1076 // Request Fields
1077 // 325 News path
1078 // 326 News article ID
1079 // 337 News article – recursive delete Delete child articles (1) or not (0)
1080 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1081 ID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1082
1083 // TODO: Delete recursive
1084 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1085
1086 catName := pathStrs[len(pathStrs)-1]
1087 cat := cats[catName]
1088
1089 delete(cat.Articles, uint32(ID))
1090
1091 cats[catName] = cat
1092 if err := cc.Server.writeThreadedNews(); err != nil {
1093 return res, err
1094 }
1095
1096 res = append(res, cc.NewReply(t))
1097 return res, err
1098 }
1099
1100 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1101 // Request fields
1102 // 325 News path
1103 // 326 News article ID ID of the parent article?
1104 // 328 News article title
1105 // 334 News article flags
1106 // 327 News article data flavor Currently “text/plain”
1107 // 333 News article data
1108
1109 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1110 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1111
1112 catName := pathStrs[len(pathStrs)-1]
1113 cat := cats[catName]
1114
1115 newArt := NewsArtData{
1116 Title: string(t.GetField(fieldNewsArtTitle).Data),
1117 Poster: string(*cc.UserName),
1118 Date: NewsDate(),
1119 PrevArt: []byte{0, 0, 0, 0},
1120 NextArt: []byte{0, 0, 0, 0},
1121 ParentArt: append([]byte{0, 0}, t.GetField(fieldNewsArtID).Data...),
1122 FirstChildArt: []byte{0, 0, 0, 0},
1123 DataFlav: []byte("text/plain"),
1124 Data: string(t.GetField(fieldNewsArtData).Data),
1125 }
1126
1127 var keys []int
1128 for k := range cat.Articles {
1129 keys = append(keys, int(k))
1130 }
1131
1132 nextID := uint32(1)
1133 if len(keys) > 0 {
1134 sort.Ints(keys)
1135 prevID := uint32(keys[len(keys)-1])
1136 nextID = prevID + 1
1137
1138 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1139
1140 // Set next article ID
1141 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1142 }
1143
1144 // Update parent article with first child reply
1145 parentID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1146 if parentID != 0 {
1147 parentArt := cat.Articles[uint32(parentID)]
1148
1149 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1150 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1151 }
1152 }
1153
1154 cat.Articles[nextID] = &newArt
1155
1156 cats[catName] = cat
1157 if err := cc.Server.writeThreadedNews(); err != nil {
1158 return res, err
1159 }
1160
1161 res = append(res, cc.NewReply(t))
1162 return res, err
1163 }
1164
1165 // HandleGetMsgs returns the flat news data
1166 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1167 res = append(res, cc.NewReply(t, NewField(fieldData, cc.Server.FlatNews)))
1168
1169 return res, err
1170 }
1171
1172 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1173 fileName := t.GetField(fieldFileName).Data
1174 filePath := ReadFilePath(t.GetField(fieldFilePath).Data)
1175
1176 ffo, err := NewFlattenedFileObject(cc.Server.Config.FileRoot+filePath, string(fileName))
1177 if err != nil {
1178 return res, err
1179 }
1180
1181 transactionRef := cc.Server.NewTransactionRef()
1182 data := binary.BigEndian.Uint32(transactionRef)
1183
1184 cc.Server.Logger.Infow("File download", "path", filePath)
1185
1186 ft := &FileTransfer{
1187 FileName: fileName,
1188 FilePath: []byte(filePath),
1189 ReferenceNumber: transactionRef,
1190 Type: FileDownload,
1191 }
1192
1193 cc.Server.FileTransfers[data] = ft
1194 cc.Transfers[FileDownload] = append(cc.Transfers[FileDownload], ft)
1195
1196 res = append(res, cc.NewReply(t,
1197 NewField(fieldRefNum, transactionRef),
1198 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1199 NewField(fieldTransferSize, ffo.TransferSize()),
1200 NewField(fieldFileSize, ffo.FlatFileDataForkHeader.DataSize),
1201 ))
1202
1203 return res, err
1204 }
1205
1206 // Download all files from the specified folder and sub-folders
1207 // response example
1208 //
1209 // 00
1210 // 01
1211 // 00 00
1212 // 00 00 00 11
1213 // 00 00 00 00
1214 // 00 00 00 18
1215 // 00 00 00 18
1216 //
1217 // 00 03
1218 //
1219 // 00 6c // transfer size
1220 // 00 04 // len
1221 // 00 0f d5 ae
1222 //
1223 // 00 dc // field Folder item count
1224 // 00 02 // len
1225 // 00 02
1226 //
1227 // 00 6b // ref number
1228 // 00 04 // len
1229 // 00 03 64 b1
1230 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1231 transactionRef := cc.Server.NewTransactionRef()
1232 data := binary.BigEndian.Uint32(transactionRef)
1233
1234 fileTransfer := &FileTransfer{
1235 FileName: t.GetField(fieldFileName).Data,
1236 FilePath: t.GetField(fieldFilePath).Data,
1237 ReferenceNumber: transactionRef,
1238 Type: FolderDownload,
1239 }
1240 cc.Server.FileTransfers[data] = fileTransfer
1241 cc.Transfers[FolderDownload] = append(cc.Transfers[FolderDownload], fileTransfer)
1242
1243 fp := NewFilePath(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 }