]> git.r.bdr.sh - rbdr/mobius/blob - hotline/transaction_handlers.go
Fix string negation bug
[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 account := cc.Server.Accounts[userLogin]
629 if account == nil {
630 errorT := cc.NewErrReply(t, "Account does not exist.")
631 res = append(res, errorT)
632 return res, err
633 }
634
635 res = append(res, cc.NewReply(t,
636 NewField(fieldUserName, []byte(account.Name)),
637 NewField(fieldUserLogin, negateString(t.GetField(fieldUserLogin).Data)),
638 NewField(fieldUserPassword, []byte(account.Password)),
639 NewField(fieldUserAccess, *account.Access),
640 ))
641 return res, err
642 }
643
644 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
645 var userFields []Field
646 // TODO: make order deterministic
647 for _, acc := range cc.Server.Accounts {
648 userField := acc.Payload()
649 userFields = append(userFields, NewField(fieldData, userField))
650 }
651
652 res = append(res, cc.NewReply(t, userFields...))
653 return res, err
654 }
655
656 // HandleNewUser creates a new user account
657 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
658 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
659
660 // If the account already exists, reply with an error
661 // TODO: make order deterministic
662 if _, ok := cc.Server.Accounts[login]; ok {
663 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
664 return res, err
665 }
666
667 if err := cc.Server.NewUser(
668 login,
669 string(t.GetField(fieldUserName).Data),
670 string(t.GetField(fieldUserPassword).Data),
671 t.GetField(fieldUserAccess).Data,
672 ); err != nil {
673 return []Transaction{}, err
674 }
675
676 res = append(res, cc.NewReply(t))
677 return res, err
678 }
679
680 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
681 // TODO: Handle case where account doesn't exist; e.g. delete race condition
682 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
683
684 if err := cc.Server.DeleteUser(login); err != nil {
685 return res, err
686 }
687
688 res = append(res, cc.NewReply(t))
689 return res, err
690 }
691
692 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
693 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
694 cc.sendAll(
695 tranServerMsg,
696 NewField(fieldData, t.GetField(tranGetMsgs).Data),
697 NewField(fieldChatOptions, []byte{0}),
698 )
699
700 res = append(res, cc.NewReply(t))
701 return res, err
702 }
703
704 func byteToInt(bytes []byte) (int, error) {
705 switch len(bytes) {
706 case 2:
707 return int(binary.BigEndian.Uint16(bytes)), nil
708 case 4:
709 return int(binary.BigEndian.Uint32(bytes)), nil
710 }
711
712 return 0, errors.New("unknown byte length")
713 }
714
715 func HandleGetClientConnInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
716 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
717
718 clientConn := cc.Server.Clients[uint16(clientID)]
719 if clientConn == nil {
720 return res, errors.New("invalid client")
721 }
722
723 // TODO: Implement non-hardcoded values
724 template := `Nickname: %s
725 Name: %s
726 Account: %s
727 Address: %s
728
729 -------- File Downloads ---------
730
731 %s
732
733 ------- Folder Downloads --------
734
735 None.
736
737 --------- File Uploads ----------
738
739 None.
740
741 -------- Folder Uploads ---------
742
743 None.
744
745 ------- Waiting Downloads -------
746
747 None.
748
749 `
750
751 activeDownloads := clientConn.Transfers[FileDownload]
752 activeDownloadList := "None."
753 for _, dl := range activeDownloads {
754 activeDownloadList += dl.String() + "\n"
755 }
756
757 template = fmt.Sprintf(
758 template,
759 *clientConn.UserName,
760 clientConn.Account.Name,
761 clientConn.Account.Login,
762 clientConn.Connection.RemoteAddr().String(),
763 activeDownloadList,
764 )
765 template = strings.Replace(template, "\n", "\r", -1)
766
767 res = append(res, cc.NewReply(t,
768 NewField(fieldData, []byte(template)),
769 NewField(fieldUserName, *clientConn.UserName),
770 ))
771 return res, err
772 }
773
774 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
775 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
776
777 return res, err
778 }
779
780 func (cc *ClientConn) notifyNewUserHasJoined() (res []Transaction, err error) {
781 // Notify other ccs that a new user has connected
782 cc.NotifyOthers(
783 *NewTransaction(
784 tranNotifyChangeUser, nil,
785 NewField(fieldUserName, *cc.UserName),
786 NewField(fieldUserID, *cc.ID),
787 NewField(fieldUserIconID, *cc.Icon),
788 NewField(fieldUserFlags, *cc.Flags),
789 ),
790 )
791
792 return res, nil
793 }
794
795 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
796 bs := make([]byte, 2)
797 binary.BigEndian.PutUint16(bs, *cc.Server.NextGuestID)
798
799 *cc.UserName = t.GetField(fieldUserName).Data
800 *cc.ID = bs
801 *cc.Icon = t.GetField(fieldUserIconID).Data
802
803 options := t.GetField(fieldOptions).Data
804 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
805
806 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
807
808 // Check refuse private PM option
809 if optBitmap.Bit(refusePM) == 1 {
810 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
811 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
812 }
813
814 // Check refuse private chat option
815 if optBitmap.Bit(refuseChat) == 1 {
816 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
817 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
818 }
819
820 // Check auto response
821 if optBitmap.Bit(autoResponse) == 1 {
822 *cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
823 } else {
824 *cc.AutoReply = []byte{}
825 }
826
827 _, _ = cc.notifyNewUserHasJoined()
828
829 res = append(res, cc.NewReply(t))
830
831 return res, err
832 }
833
834 const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
835 // "Mon, 02 Jan 2006 15:04:05 MST"
836
837 const defaultNewsTemplate = `From %s (%s):
838
839 %s
840
841 __________________________________________________________`
842
843 // HandleTranOldPostNews updates the flat news
844 // Fields used in this request:
845 // 101 Data
846 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
847 cc.Server.flatNewsMux.Lock()
848 defer cc.Server.flatNewsMux.Unlock()
849
850 newsDateTemplate := defaultNewsDateFormat
851 if cc.Server.Config.NewsDateFormat != "" {
852 newsDateTemplate = cc.Server.Config.NewsDateFormat
853 }
854
855 newsTemplate := defaultNewsTemplate
856 if cc.Server.Config.NewsDelimiter != "" {
857 newsTemplate = cc.Server.Config.NewsDelimiter
858 }
859
860 newsPost := fmt.Sprintf(newsTemplate+"\r", *cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
861 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
862
863 // update news in memory
864 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
865
866 // update news on disk
867 if err := ioutil.WriteFile(cc.Server.ConfigDir+"MessageBoard.txt", cc.Server.FlatNews, 0644); err != nil {
868 return res, err
869 }
870
871 // Notify all clients of updated news
872 cc.sendAll(
873 tranNewMsg,
874 NewField(fieldData, []byte(newsPost)),
875 )
876
877 res = append(res, cc.NewReply(t))
878 return res, err
879 }
880
881 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
882 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
883
884 if authorize(clientConn.Account.Access, accessCannotBeDiscon) {
885 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
886 return res, err
887 }
888
889 if err := clientConn.Connection.Close(); err != nil {
890 return res, err
891 }
892
893 res = append(res, cc.NewReply(t))
894 return res, err
895 }
896
897 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
898 // Fields used in the request:
899 // 325 News path (Optional)
900
901 newsPath := t.GetField(fieldNewsPath).Data
902 cc.Server.Logger.Infow("NewsPath: ", "np", string(newsPath))
903
904 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
905 cats := cc.Server.GetNewsCatByPath(pathStrs)
906
907 // To store the keys in slice in sorted order
908 keys := make([]string, len(cats))
909 i := 0
910 for k := range cats {
911 keys[i] = k
912 i++
913 }
914 sort.Strings(keys)
915
916 var fieldData []Field
917 for _, k := range keys {
918 cat := cats[k]
919 fieldData = append(fieldData, NewField(
920 fieldNewsCatListData15,
921 cat.Payload(),
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 fp := NewFilePath(t.GetField(fieldFilePath).Data)
1243
1244 fullFilePath := fmt.Sprintf("./%v/%v", cc.Server.Config.FileRoot+fp.String(), string(fileTransfer.FileName))
1245 transferSize, err := CalcTotalSize(fullFilePath)
1246 if err != nil {
1247 return res, err
1248 }
1249 itemCount, err := CalcItemCount(fullFilePath)
1250 if err != nil {
1251 return res, err
1252 }
1253 res = append(res, cc.NewReply(t,
1254 NewField(fieldRefNum, transactionRef),
1255 NewField(fieldTransferSize, transferSize),
1256 NewField(fieldFolderItemCount, itemCount),
1257 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1258 ))
1259 return res, err
1260 }
1261
1262 // Upload all files from the local folder and its subfolders to the specified path on the server
1263 // Fields used in the request
1264 // 201 File name
1265 // 202 File path
1266 // 108 Transfer size Total size of all items in the folder
1267 // 220 Folder item count
1268 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1269 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1270 transactionRef := cc.Server.NewTransactionRef()
1271 data := binary.BigEndian.Uint32(transactionRef)
1272
1273 fileTransfer := &FileTransfer{
1274 FileName: t.GetField(fieldFileName).Data,
1275 FilePath: t.GetField(fieldFilePath).Data,
1276 ReferenceNumber: transactionRef,
1277 Type: FolderUpload,
1278 FolderItemCount: t.GetField(fieldFolderItemCount).Data,
1279 TransferSize: t.GetField(fieldTransferSize).Data,
1280 }
1281 cc.Server.FileTransfers[data] = fileTransfer
1282
1283 res = append(res, cc.NewReply(t, NewField(fieldRefNum, transactionRef)))
1284 return res, err
1285 }
1286
1287 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1288 fileName := t.GetField(fieldFileName).Data
1289 filePath := t.GetField(fieldFilePath).Data
1290
1291 transactionRef := cc.Server.NewTransactionRef()
1292 data := binary.BigEndian.Uint32(transactionRef)
1293
1294 fileTransfer := &FileTransfer{
1295 FileName: fileName,
1296 FilePath: filePath,
1297 ReferenceNumber: transactionRef,
1298 Type: FileUpload,
1299 }
1300
1301 cc.Server.FileTransfers[data] = fileTransfer
1302
1303 res = append(res, cc.NewReply(t, NewField(fieldRefNum, transactionRef)))
1304 return res, err
1305 }
1306
1307 // User options
1308 const (
1309 refusePM = 0
1310 refuseChat = 1
1311 autoResponse = 2
1312 )
1313
1314 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1315 var icon []byte
1316 if len(t.GetField(fieldUserIconID).Data) == 4 {
1317 icon = t.GetField(fieldUserIconID).Data[2:]
1318 } else {
1319 icon = t.GetField(fieldUserIconID).Data
1320 }
1321 *cc.Icon = icon
1322 *cc.UserName = t.GetField(fieldUserName).Data
1323
1324 // the options field is only passed by the client versions > 1.2.3.
1325 options := t.GetField(fieldOptions).Data
1326
1327 if options != nil {
1328 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1329 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
1330
1331 // Check refuse private PM option
1332 if optBitmap.Bit(refusePM) == 1 {
1333 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
1334 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
1335 }
1336
1337 // Check refuse private chat option
1338 if optBitmap.Bit(refuseChat) == 1 {
1339 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
1340 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
1341 }
1342
1343 // Check auto response
1344 if optBitmap.Bit(autoResponse) == 1 {
1345 *cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
1346 } else {
1347 *cc.AutoReply = []byte{}
1348 }
1349 }
1350
1351 // Notify all clients of updated user info
1352 cc.sendAll(
1353 tranNotifyChangeUser,
1354 NewField(fieldUserID, *cc.ID),
1355 NewField(fieldUserIconID, *cc.Icon),
1356 NewField(fieldUserFlags, *cc.Flags),
1357 NewField(fieldUserName, *cc.UserName),
1358 )
1359
1360 return res, err
1361 }
1362
1363 // HandleKeepAlive response to keepalive transactions with an empty reply
1364 // HL 1.9.2 Client sends keepalive msg every 3 minutes
1365 // HL 1.2.3 Client doesn't send keepalives
1366 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1367 res = append(res, cc.NewReply(t))
1368
1369 return res, err
1370 }
1371
1372 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1373 filePath := cc.Server.Config.FileRoot
1374
1375 path := t.GetField(fieldFilePath).Data
1376 if len(path) > 0 {
1377 filePath = cc.Server.Config.FileRoot + ReadFilePath(path)
1378 }
1379
1380 fileNames, err := getFileNameList(filePath)
1381 if err != nil {
1382 return res, err
1383 }
1384
1385 res = append(res, cc.NewReply(t, fileNames...))
1386
1387 return res, err
1388 }
1389
1390 // =================================
1391 // Hotline private chat flow
1392 // =================================
1393 // 1. ClientA sends tranInviteNewChat to server with user ID to invite
1394 // 2. Server creates new ChatID
1395 // 3. Server sends tranInviteToChat to invitee
1396 // 4. Server replies to ClientA with new Chat ID
1397 //
1398 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1399 // If Accepted is clicked:
1400 // 1. ClientB sends tranJoinChat with fieldChatID
1401
1402 // HandleInviteNewChat invites users to new private chat
1403 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1404 // Client to Invite
1405 targetID := t.GetField(fieldUserID).Data
1406 newChatID := cc.Server.NewPrivateChat(cc)
1407
1408 res = append(res,
1409 *NewTransaction(
1410 tranInviteToChat,
1411 &targetID,
1412 NewField(fieldChatID, newChatID),
1413 NewField(fieldUserName, *cc.UserName),
1414 NewField(fieldUserID, *cc.ID),
1415 ),
1416 )
1417
1418 res = append(res,
1419 cc.NewReply(t,
1420 NewField(fieldChatID, newChatID),
1421 NewField(fieldUserName, *cc.UserName),
1422 NewField(fieldUserID, *cc.ID),
1423 NewField(fieldUserIconID, *cc.Icon),
1424 NewField(fieldUserFlags, *cc.Flags),
1425 ),
1426 )
1427
1428 return res, err
1429 }
1430
1431 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1432 // Client to Invite
1433 targetID := t.GetField(fieldUserID).Data
1434 chatID := t.GetField(fieldChatID).Data
1435
1436 res = append(res,
1437 *NewTransaction(
1438 tranInviteToChat,
1439 &targetID,
1440 NewField(fieldChatID, chatID),
1441 NewField(fieldUserName, *cc.UserName),
1442 NewField(fieldUserID, *cc.ID),
1443 ),
1444 )
1445 res = append(res,
1446 cc.NewReply(
1447 t,
1448 NewField(fieldChatID, chatID),
1449 NewField(fieldUserName, *cc.UserName),
1450 NewField(fieldUserID, *cc.ID),
1451 NewField(fieldUserIconID, *cc.Icon),
1452 NewField(fieldUserFlags, *cc.Flags),
1453 ),
1454 )
1455
1456 return res, err
1457 }
1458
1459 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1460 chatID := t.GetField(fieldChatID).Data
1461 chatInt := binary.BigEndian.Uint32(chatID)
1462
1463 privChat := cc.Server.PrivateChats[chatInt]
1464
1465 resMsg := append(*cc.UserName, []byte(" declined invitation to chat")...)
1466
1467 for _, c := range sortedClients(privChat.ClientConn) {
1468 res = append(res,
1469 *NewTransaction(
1470 tranChatMsg,
1471 c.ID,
1472 NewField(fieldChatID, chatID),
1473 NewField(fieldData, resMsg),
1474 ),
1475 )
1476 }
1477
1478 return res, err
1479 }
1480
1481 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1482 // Fields used in the reply:
1483 // * 115 Chat subject
1484 // * 300 User name with info (Optional)
1485 // * 300 (more user names with info)
1486 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1487 chatID := t.GetField(fieldChatID).Data
1488 chatInt := binary.BigEndian.Uint32(chatID)
1489
1490 privChat := cc.Server.PrivateChats[chatInt]
1491
1492 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1493 for _, c := range sortedClients(privChat.ClientConn) {
1494 res = append(res,
1495 *NewTransaction(
1496 tranNotifyChatChangeUser,
1497 c.ID,
1498 NewField(fieldChatID, chatID),
1499 NewField(fieldUserName, *cc.UserName),
1500 NewField(fieldUserID, *cc.ID),
1501 NewField(fieldUserIconID, *cc.Icon),
1502 NewField(fieldUserFlags, *cc.Flags),
1503 ),
1504 )
1505 }
1506
1507 privChat.ClientConn[cc.uint16ID()] = cc
1508
1509 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1510 for _, c := range sortedClients(privChat.ClientConn) {
1511 user := User{
1512 ID: *c.ID,
1513 Icon: *c.Icon,
1514 Flags: *c.Flags,
1515 Name: string(*c.UserName),
1516 }
1517
1518 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1519 }
1520
1521 res = append(res, cc.NewReply(t, replyFields...))
1522 return res, err
1523 }
1524
1525 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1526 // Fields used in the request:
1527 // * 114 fieldChatID
1528 // Reply is not expected.
1529 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1530 chatID := t.GetField(fieldChatID).Data
1531 chatInt := binary.BigEndian.Uint32(chatID)
1532
1533 privChat := cc.Server.PrivateChats[chatInt]
1534
1535 delete(privChat.ClientConn, cc.uint16ID())
1536
1537 // Notify members of the private chat that the user has left
1538 for _, c := range sortedClients(privChat.ClientConn) {
1539 res = append(res,
1540 *NewTransaction(
1541 tranNotifyChatDeleteUser,
1542 c.ID,
1543 NewField(fieldChatID, chatID),
1544 NewField(fieldUserID, *cc.ID),
1545 ),
1546 )
1547 }
1548
1549 return res, err
1550 }
1551
1552 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1553 // Fields used in the request:
1554 // * 114 Chat ID
1555 // * 115 Chat subject Chat subject string
1556 // Reply is not expected.
1557 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1558 chatID := t.GetField(fieldChatID).Data
1559 chatInt := binary.BigEndian.Uint32(chatID)
1560
1561 privChat := cc.Server.PrivateChats[chatInt]
1562 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1563
1564 for _, c := range sortedClients(privChat.ClientConn) {
1565 res = append(res,
1566 *NewTransaction(
1567 tranNotifyChatSubject,
1568 c.ID,
1569 NewField(fieldChatID, chatID),
1570 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),
1571 ),
1572 )
1573 }
1574
1575 return res, err
1576 }