]> git.r.bdr.sh - rbdr/mobius/blob - hotline/transaction_handlers.go
Tests and minor fixes
[rbdr/mobius] / hotline / transaction_handlers.go
1 package hotline
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7 "fmt"
8 "gopkg.in/yaml.v2"
9 "io/ioutil"
10 "math/big"
11 "os"
12 "path"
13 "sort"
14 "strings"
15 "time"
16 )
17
18 type TransactionType struct {
19 Access int // Specifies access privilege required to perform the transaction
20 DenyMsg string // The error reply message when user does not have access
21 Handler func(*ClientConn, *Transaction) ([]Transaction, error) // function for handling the transaction type
22 Name string // Name of transaction as it will appear in logging
23 RequiredFields []requiredField
24 }
25
26 var TransactionHandlers = map[uint16]TransactionType{
27 // Server initiated
28 tranChatMsg: {
29 Name: "tranChatMsg",
30 },
31 // Server initiated
32 tranNotifyChangeUser: {
33 Name: "tranNotifyChangeUser",
34 },
35 tranError: {
36 Name: "tranError",
37 },
38 tranShowAgreement: {
39 Name: "tranShowAgreement",
40 },
41 tranUserAccess: {
42 Name: "tranUserAccess",
43 },
44 tranNotifyDeleteUser: {
45 Name: "tranNotifyDeleteUser",
46 },
47 tranAgreed: {
48 Access: accessAlwaysAllow,
49 Name: "tranAgreed",
50 Handler: HandleTranAgreed,
51 },
52 tranChatSend: {
53 Access: 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("\r*** %s %s", 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
403 ffo, err := NewFlattenedFileObject(filePath, fileName)
404 if err != nil {
405 return res, err
406 }
407
408 res = append(res, cc.NewReply(t,
409 NewField(fieldFileName, []byte(fileName)),
410 NewField(fieldFileTypeString, ffo.FlatFileInformationFork.TypeSignature),
411 NewField(fieldFileCreatorString, ffo.FlatFileInformationFork.CreatorSignature),
412 NewField(fieldFileComment, ffo.FlatFileInformationFork.Comment),
413 NewField(fieldFileType, ffo.FlatFileInformationFork.TypeSignature),
414 NewField(fieldFileCreateDate, ffo.FlatFileInformationFork.CreateDate),
415 NewField(fieldFileModifyDate, ffo.FlatFileInformationFork.ModifyDate),
416 NewField(fieldFileSize, ffo.FlatFileDataForkHeader.DataSize),
417 ))
418 return res, err
419 }
420
421 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
422 // TODO: Implement support for comments
423 // Fields used in the request:
424 // * 201 File name
425 // * 202 File path Optional
426 // * 211 File new name Optional
427 // * 210 File comment Optional
428 // Fields used in the reply: None
429 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
430 fileName := string(t.GetField(fieldFileName).Data)
431 filePath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
432 //fileComment := t.GetField(fieldFileComment).Data
433 fileNewName := t.GetField(fieldFileNewName).Data
434
435 if fileNewName != nil {
436 path := filePath + "/" + fileName
437 fi, err := os.Stat(path)
438 if err != nil {
439 return res, err
440 }
441 switch mode := fi.Mode(); {
442 case mode.IsDir():
443 if !authorize(cc.Account.Access, accessRenameFolder) {
444 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
445 return res, err
446 }
447 case mode.IsRegular():
448 if !authorize(cc.Account.Access, accessRenameFile) {
449 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
450 return res, err
451 }
452 }
453
454 err = os.Rename(filePath+"/"+fileName, filePath+"/"+string(fileNewName))
455 if os.IsNotExist(err) {
456 res = append(res, cc.NewErrReply(t, "Cannot rename file "+fileName+" because it does not exist or cannot be found."))
457 return res, err
458 }
459 }
460
461 res = append(res, cc.NewReply(t))
462 return res, err
463 }
464
465 // HandleDeleteFile deletes a file or folder
466 // Fields used in the request:
467 // * 201 File name
468 // * 202 File path
469 // Fields used in the reply: none
470 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
471 fileName := string(t.GetField(fieldFileName).Data)
472 filePath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
473
474 path := filePath + fileName
475
476 cc.Server.Logger.Debugw("Delete file", "src", path)
477
478 fi, err := os.Stat(path)
479 if err != nil {
480 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
481 return res, nil
482 }
483 switch mode := fi.Mode(); {
484 case mode.IsDir():
485 if !authorize(cc.Account.Access, accessDeleteFolder) {
486 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
487 return res, err
488 }
489 case mode.IsRegular():
490 if !authorize(cc.Account.Access, accessDeleteFile) {
491 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
492 return res, err
493 }
494 }
495
496 if err := os.RemoveAll(path); err != nil {
497 return res, err
498 }
499
500 res = append(res, cc.NewReply(t))
501 return res, err
502 }
503
504 // HandleMoveFile moves files or folders. Note: seemingly not documented
505 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
506 fileName := string(t.GetField(fieldFileName).Data)
507 filePath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
508 fileNewPath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFileNewPath).Data)
509
510 cc.Server.Logger.Debugw("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
511
512 path := filePath + "/" + fileName
513 fi, err := os.Stat(path)
514 if err != nil {
515 return res, err
516 }
517 switch mode := fi.Mode(); {
518 case mode.IsDir():
519 if !authorize(cc.Account.Access, accessMoveFolder) {
520 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
521 return res, err
522 }
523 case mode.IsRegular():
524 if !authorize(cc.Account.Access, accessMoveFile) {
525 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
526 return res, err
527 }
528 }
529
530 err = os.Rename(filePath+"/"+fileName, fileNewPath+"/"+fileName)
531 if os.IsNotExist(err) {
532 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
533 return res, err
534 }
535 if err != nil {
536 return []Transaction{}, err
537 }
538 // TODO: handle other possible errors; e.g. file delete fails due to file permission issue
539
540 res = append(res, cc.NewReply(t))
541 return res, err
542 }
543
544 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
545 newFolderPath := cc.Server.Config.FileRoot
546 folderName := string(t.GetField(fieldFileName).Data)
547
548 folderName = path.Join("/", folderName)
549
550 // fieldFilePath is only present for nested paths
551 if t.GetField(fieldFilePath).Data != nil {
552 var newFp FilePath
553 err := newFp.UnmarshalBinary(t.GetField(fieldFilePath).Data)
554 if err != nil {
555 return nil, err
556 }
557 newFolderPath += newFp.String()
558 }
559 newFolderPath = path.Join(newFolderPath, folderName)
560
561 // TODO: check path and folder name lengths
562
563 if _, err := FS.Stat(newFolderPath); !os.IsNotExist(err) {
564 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that name.", folderName)
565 return []Transaction{cc.NewErrReply(t, msg)}, nil
566 }
567
568 // TODO: check for disallowed characters to maintain compatibility for original client
569
570 if err := FS.Mkdir(newFolderPath, 0777); err != nil {
571 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
572 return []Transaction{cc.NewErrReply(t, msg)}, nil
573 }
574
575 res = append(res, cc.NewReply(t))
576 return res, err
577 }
578
579 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
580 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
581 userName := string(t.GetField(fieldUserName).Data)
582
583 newAccessLvl := t.GetField(fieldUserAccess).Data
584
585 account := cc.Server.Accounts[login]
586 account.Access = &newAccessLvl
587 account.Name = userName
588
589 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
590 // not include fieldUserPassword
591 if t.GetField(fieldUserPassword).Data == nil {
592 account.Password = hashAndSalt([]byte(""))
593 }
594 if len(t.GetField(fieldUserPassword).Data) > 1 {
595 account.Password = hashAndSalt(t.GetField(fieldUserPassword).Data)
596 }
597
598 file := cc.Server.ConfigDir + "Users/" + login + ".yaml"
599 out, err := yaml.Marshal(&account)
600 if err != nil {
601 return res, err
602 }
603 if err := ioutil.WriteFile(file, out, 0666); err != nil {
604 return res, err
605 }
606
607 // Notify connected clients logged in as the user of the new access level
608 for _, c := range cc.Server.Clients {
609 if c.Account.Login == login {
610 // Note: comment out these two lines to test server-side deny messages
611 newT := NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, newAccessLvl))
612 res = append(res, *newT)
613
614 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
615 if authorize(c.Account.Access, accessDisconUser) {
616 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 1)
617 } else {
618 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 0)
619 }
620 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
621
622 c.Account.Access = account.Access
623
624 cc.sendAll(
625 tranNotifyChangeUser,
626 NewField(fieldUserID, *c.ID),
627 NewField(fieldUserFlags, *c.Flags),
628 NewField(fieldUserName, c.UserName),
629 NewField(fieldUserIconID, *c.Icon),
630 )
631 }
632 }
633
634 // TODO: If we have just promoted a connected user to admin, notify
635 // connected clients to turn the user red
636
637 res = append(res, cc.NewReply(t))
638 return res, err
639 }
640
641 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
642 userLogin := string(t.GetField(fieldUserLogin).Data)
643 account := cc.Server.Accounts[userLogin]
644 if account == nil {
645 errorT := cc.NewErrReply(t, "Account does not exist.")
646 res = append(res, errorT)
647 return res, err
648 }
649
650 res = append(res, cc.NewReply(t,
651 NewField(fieldUserName, []byte(account.Name)),
652 NewField(fieldUserLogin, negateString(t.GetField(fieldUserLogin).Data)),
653 NewField(fieldUserPassword, []byte(account.Password)),
654 NewField(fieldUserAccess, *account.Access),
655 ))
656 return res, err
657 }
658
659 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
660 var userFields []Field
661 // TODO: make order deterministic
662 for _, acc := range cc.Server.Accounts {
663 userField := acc.MarshalBinary()
664 userFields = append(userFields, NewField(fieldData, userField))
665 }
666
667 res = append(res, cc.NewReply(t, userFields...))
668 return res, err
669 }
670
671 // HandleNewUser creates a new user account
672 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
673 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
674
675 // If the account already exists, reply with an error
676 // TODO: make order deterministic
677 if _, ok := cc.Server.Accounts[login]; ok {
678 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
679 return res, err
680 }
681
682 if err := cc.Server.NewUser(
683 login,
684 string(t.GetField(fieldUserName).Data),
685 string(t.GetField(fieldUserPassword).Data),
686 t.GetField(fieldUserAccess).Data,
687 ); err != nil {
688 return []Transaction{}, err
689 }
690
691 res = append(res, cc.NewReply(t))
692 return res, err
693 }
694
695 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
696 // TODO: Handle case where account doesn't exist; e.g. delete race condition
697 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
698
699 if err := cc.Server.DeleteUser(login); err != nil {
700 return res, err
701 }
702
703 res = append(res, cc.NewReply(t))
704 return res, err
705 }
706
707 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
708 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
709 cc.sendAll(
710 tranServerMsg,
711 NewField(fieldData, t.GetField(tranGetMsgs).Data),
712 NewField(fieldChatOptions, []byte{0}),
713 )
714
715 res = append(res, cc.NewReply(t))
716 return res, err
717 }
718
719 func byteToInt(bytes []byte) (int, error) {
720 switch len(bytes) {
721 case 2:
722 return int(binary.BigEndian.Uint16(bytes)), nil
723 case 4:
724 return int(binary.BigEndian.Uint32(bytes)), nil
725 }
726
727 return 0, errors.New("unknown byte length")
728 }
729
730 func HandleGetClientConnInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
731 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
732
733 clientConn := cc.Server.Clients[uint16(clientID)]
734 if clientConn == nil {
735 return res, errors.New("invalid client")
736 }
737
738 // TODO: Implement non-hardcoded values
739 template := `Nickname: %s
740 Name: %s
741 Account: %s
742 Address: %s
743
744 -------- File Downloads ---------
745
746 %s
747
748 ------- Folder Downloads --------
749
750 None.
751
752 --------- File Uploads ----------
753
754 None.
755
756 -------- Folder Uploads ---------
757
758 None.
759
760 ------- Waiting Downloads -------
761
762 None.
763
764 `
765
766 activeDownloads := clientConn.Transfers[FileDownload]
767 activeDownloadList := "None."
768 for _, dl := range activeDownloads {
769 activeDownloadList += dl.String() + "\n"
770 }
771
772 template = fmt.Sprintf(
773 template,
774 clientConn.UserName,
775 clientConn.Account.Name,
776 clientConn.Account.Login,
777 clientConn.Connection.RemoteAddr().String(),
778 activeDownloadList,
779 )
780 template = strings.Replace(template, "\n", "\r", -1)
781
782 res = append(res, cc.NewReply(t,
783 NewField(fieldData, []byte(template)),
784 NewField(fieldUserName, clientConn.UserName),
785 ))
786 return res, err
787 }
788
789 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
790 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
791
792 return res, err
793 }
794
795 func (cc *ClientConn) notifyNewUserHasJoined() (res []Transaction, err error) {
796 // Notify other ccs that a new user has connected
797 cc.NotifyOthers(
798 *NewTransaction(
799 tranNotifyChangeUser, nil,
800 NewField(fieldUserName, cc.UserName),
801 NewField(fieldUserID, *cc.ID),
802 NewField(fieldUserIconID, *cc.Icon),
803 NewField(fieldUserFlags, *cc.Flags),
804 ),
805 )
806
807 return res, nil
808 }
809
810 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
811 bs := make([]byte, 2)
812 binary.BigEndian.PutUint16(bs, *cc.Server.NextGuestID)
813
814 cc.UserName = t.GetField(fieldUserName).Data
815 *cc.ID = bs
816 *cc.Icon = t.GetField(fieldUserIconID).Data
817
818 options := t.GetField(fieldOptions).Data
819 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
820
821 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
822
823 // Check refuse private PM option
824 if optBitmap.Bit(refusePM) == 1 {
825 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
826 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
827 }
828
829 // Check refuse private chat option
830 if optBitmap.Bit(refuseChat) == 1 {
831 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
832 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
833 }
834
835 // Check auto response
836 if optBitmap.Bit(autoResponse) == 1 {
837 *cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
838 } else {
839 *cc.AutoReply = []byte{}
840 }
841
842 _, _ = cc.notifyNewUserHasJoined()
843
844 res = append(res, cc.NewReply(t))
845
846 return res, err
847 }
848
849 const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
850 // "Mon, 02 Jan 2006 15:04:05 MST"
851
852 const defaultNewsTemplate = `From %s (%s):
853
854 %s
855
856 __________________________________________________________`
857
858 // HandleTranOldPostNews updates the flat news
859 // Fields used in this request:
860 // 101 Data
861 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
862 cc.Server.flatNewsMux.Lock()
863 defer cc.Server.flatNewsMux.Unlock()
864
865 newsDateTemplate := defaultNewsDateFormat
866 if cc.Server.Config.NewsDateFormat != "" {
867 newsDateTemplate = cc.Server.Config.NewsDateFormat
868 }
869
870 newsTemplate := defaultNewsTemplate
871 if cc.Server.Config.NewsDelimiter != "" {
872 newsTemplate = cc.Server.Config.NewsDelimiter
873 }
874
875 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
876 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
877
878 // update news in memory
879 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
880
881 // update news on disk
882 if err := ioutil.WriteFile(cc.Server.ConfigDir+"MessageBoard.txt", cc.Server.FlatNews, 0644); err != nil {
883 return res, err
884 }
885
886 // Notify all clients of updated news
887 cc.sendAll(
888 tranNewMsg,
889 NewField(fieldData, []byte(newsPost)),
890 )
891
892 res = append(res, cc.NewReply(t))
893 return res, err
894 }
895
896 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
897 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
898
899 if authorize(clientConn.Account.Access, accessCannotBeDiscon) {
900 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
901 return res, err
902 }
903
904 if err := clientConn.Connection.Close(); err != nil {
905 return res, err
906 }
907
908 res = append(res, cc.NewReply(t))
909 return res, err
910 }
911
912 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
913 // Fields used in the request:
914 // 325 News path (Optional)
915
916 newsPath := t.GetField(fieldNewsPath).Data
917 cc.Server.Logger.Infow("NewsPath: ", "np", string(newsPath))
918
919 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
920 cats := cc.Server.GetNewsCatByPath(pathStrs)
921
922 // To store the keys in slice in sorted order
923 keys := make([]string, len(cats))
924 i := 0
925 for k := range cats {
926 keys[i] = k
927 i++
928 }
929 sort.Strings(keys)
930
931 var fieldData []Field
932 for _, k := range keys {
933 cat := cats[k]
934 b, _ := cat.MarshalBinary()
935 fieldData = append(fieldData, NewField(
936 fieldNewsCatListData15,
937 b,
938 ))
939 }
940
941 res = append(res, cc.NewReply(t, fieldData...))
942 return res, err
943 }
944
945 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
946 name := string(t.GetField(fieldNewsCatName).Data)
947 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
948
949 cats := cc.Server.GetNewsCatByPath(pathStrs)
950 cats[name] = NewsCategoryListData15{
951 Name: name,
952 Type: []byte{0, 3},
953 Articles: map[uint32]*NewsArtData{},
954 SubCats: make(map[string]NewsCategoryListData15),
955 }
956
957 if err := cc.Server.writeThreadedNews(); err != nil {
958 return res, err
959 }
960 res = append(res, cc.NewReply(t))
961 return res, err
962 }
963
964 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
965 // Fields used in the request:
966 // 322 News category name
967 // 325 News path
968 name := string(t.GetField(fieldFileName).Data)
969 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
970
971 cc.Server.Logger.Infof("Creating new news folder %s", name)
972
973 cats := cc.Server.GetNewsCatByPath(pathStrs)
974 cats[name] = NewsCategoryListData15{
975 Name: name,
976 Type: []byte{0, 2},
977 Articles: map[uint32]*NewsArtData{},
978 SubCats: make(map[string]NewsCategoryListData15),
979 }
980 if err := cc.Server.writeThreadedNews(); err != nil {
981 return res, err
982 }
983 res = append(res, cc.NewReply(t))
984 return res, err
985 }
986
987 // Fields used in the request:
988 // 325 News path Optional
989 //
990 // Reply fields:
991 // 321 News article list data Optional
992 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
993 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
994
995 var cat NewsCategoryListData15
996 cats := cc.Server.ThreadedNews.Categories
997
998 for _, path := range pathStrs {
999 cat = cats[path]
1000 cats = cats[path].SubCats
1001 }
1002
1003 nald := cat.GetNewsArtListData()
1004
1005 res = append(res, cc.NewReply(t, NewField(fieldNewsArtListData, nald.Payload())))
1006 return res, err
1007 }
1008
1009 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1010 // Request fields
1011 // 325 News path
1012 // 326 News article ID
1013 // 327 News article data flavor
1014
1015 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1016
1017 var cat NewsCategoryListData15
1018 cats := cc.Server.ThreadedNews.Categories
1019
1020 for _, path := range pathStrs {
1021 cat = cats[path]
1022 cats = cats[path].SubCats
1023 }
1024 newsArtID := t.GetField(fieldNewsArtID).Data
1025
1026 convertedArtID := binary.BigEndian.Uint16(newsArtID)
1027
1028 art := cat.Articles[uint32(convertedArtID)]
1029 if art == nil {
1030 res = append(res, cc.NewReply(t))
1031 return res, err
1032 }
1033
1034 // Reply fields
1035 // 328 News article title
1036 // 329 News article poster
1037 // 330 News article date
1038 // 331 Previous article ID
1039 // 332 Next article ID
1040 // 335 Parent article ID
1041 // 336 First child article ID
1042 // 327 News article data flavor "Should be “text/plain”
1043 // 333 News article data Optional (if data flavor is “text/plain”)
1044
1045 res = append(res, cc.NewReply(t,
1046 NewField(fieldNewsArtTitle, []byte(art.Title)),
1047 NewField(fieldNewsArtPoster, []byte(art.Poster)),
1048 NewField(fieldNewsArtDate, art.Date),
1049 NewField(fieldNewsArtPrevArt, art.PrevArt),
1050 NewField(fieldNewsArtNextArt, art.NextArt),
1051 NewField(fieldNewsArtParentArt, art.ParentArt),
1052 NewField(fieldNewsArt1stChildArt, art.FirstChildArt),
1053 NewField(fieldNewsArtDataFlav, []byte("text/plain")),
1054 NewField(fieldNewsArtData, []byte(art.Data)),
1055 ))
1056 return res, err
1057 }
1058
1059 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1060 // Access: News Delete Folder (37) or News Delete Category (35)
1061
1062 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1063
1064 // TODO: determine if path is a Folder (Bundle) or Category and check for permission
1065
1066 cc.Server.Logger.Infof("DelNewsItem %v", pathStrs)
1067
1068 cats := cc.Server.ThreadedNews.Categories
1069
1070 delName := pathStrs[len(pathStrs)-1]
1071 if len(pathStrs) > 1 {
1072 for _, path := range pathStrs[0 : len(pathStrs)-1] {
1073 cats = cats[path].SubCats
1074 }
1075 }
1076
1077 delete(cats, delName)
1078
1079 err = cc.Server.writeThreadedNews()
1080 if err != nil {
1081 return res, err
1082 }
1083
1084 // Reply params: none
1085 res = append(res, cc.NewReply(t))
1086
1087 return res, err
1088 }
1089
1090 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1091 // Request Fields
1092 // 325 News path
1093 // 326 News article ID
1094 // 337 News article – recursive delete Delete child articles (1) or not (0)
1095 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1096 ID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1097
1098 // TODO: Delete recursive
1099 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1100
1101 catName := pathStrs[len(pathStrs)-1]
1102 cat := cats[catName]
1103
1104 delete(cat.Articles, uint32(ID))
1105
1106 cats[catName] = cat
1107 if err := cc.Server.writeThreadedNews(); err != nil {
1108 return res, err
1109 }
1110
1111 res = append(res, cc.NewReply(t))
1112 return res, err
1113 }
1114
1115 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1116 // Request fields
1117 // 325 News path
1118 // 326 News article ID ID of the parent article?
1119 // 328 News article title
1120 // 334 News article flags
1121 // 327 News article data flavor Currently “text/plain”
1122 // 333 News article data
1123
1124 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1125 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1126
1127 catName := pathStrs[len(pathStrs)-1]
1128 cat := cats[catName]
1129
1130 newArt := NewsArtData{
1131 Title: string(t.GetField(fieldNewsArtTitle).Data),
1132 Poster: string(cc.UserName),
1133 Date: NewsDate(),
1134 PrevArt: []byte{0, 0, 0, 0},
1135 NextArt: []byte{0, 0, 0, 0},
1136 ParentArt: append([]byte{0, 0}, t.GetField(fieldNewsArtID).Data...),
1137 FirstChildArt: []byte{0, 0, 0, 0},
1138 DataFlav: []byte("text/plain"),
1139 Data: string(t.GetField(fieldNewsArtData).Data),
1140 }
1141
1142 var keys []int
1143 for k := range cat.Articles {
1144 keys = append(keys, int(k))
1145 }
1146
1147 nextID := uint32(1)
1148 if len(keys) > 0 {
1149 sort.Ints(keys)
1150 prevID := uint32(keys[len(keys)-1])
1151 nextID = prevID + 1
1152
1153 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1154
1155 // Set next article ID
1156 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1157 }
1158
1159 // Update parent article with first child reply
1160 parentID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1161 if parentID != 0 {
1162 parentArt := cat.Articles[uint32(parentID)]
1163
1164 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1165 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1166 }
1167 }
1168
1169 cat.Articles[nextID] = &newArt
1170
1171 cats[catName] = cat
1172 if err := cc.Server.writeThreadedNews(); err != nil {
1173 return res, err
1174 }
1175
1176 res = append(res, cc.NewReply(t))
1177 return res, err
1178 }
1179
1180 // HandleGetMsgs returns the flat news data
1181 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1182 res = append(res, cc.NewReply(t, NewField(fieldData, cc.Server.FlatNews)))
1183
1184 return res, err
1185 }
1186
1187 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1188 fileName := t.GetField(fieldFileName).Data
1189 filePath := ReadFilePath(t.GetField(fieldFilePath).Data)
1190
1191 ffo, err := NewFlattenedFileObject(cc.Server.Config.FileRoot+filePath, string(fileName))
1192 if err != nil {
1193 return res, err
1194 }
1195
1196 transactionRef := cc.Server.NewTransactionRef()
1197 data := binary.BigEndian.Uint32(transactionRef)
1198
1199 cc.Server.Logger.Infow("File download", "path", filePath)
1200
1201 ft := &FileTransfer{
1202 FileName: fileName,
1203 FilePath: []byte(filePath),
1204 ReferenceNumber: transactionRef,
1205 Type: FileDownload,
1206 }
1207
1208 cc.Server.FileTransfers[data] = ft
1209 cc.Transfers[FileDownload] = append(cc.Transfers[FileDownload], ft)
1210
1211 res = append(res, cc.NewReply(t,
1212 NewField(fieldRefNum, transactionRef),
1213 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1214 NewField(fieldTransferSize, ffo.TransferSize()),
1215 NewField(fieldFileSize, ffo.FlatFileDataForkHeader.DataSize),
1216 ))
1217
1218 return res, err
1219 }
1220
1221 // Download all files from the specified folder and sub-folders
1222 // response example
1223 //
1224 // 00
1225 // 01
1226 // 00 00
1227 // 00 00 00 11
1228 // 00 00 00 00
1229 // 00 00 00 18
1230 // 00 00 00 18
1231 //
1232 // 00 03
1233 //
1234 // 00 6c // transfer size
1235 // 00 04 // len
1236 // 00 0f d5 ae
1237 //
1238 // 00 dc // field Folder item count
1239 // 00 02 // len
1240 // 00 02
1241 //
1242 // 00 6b // ref number
1243 // 00 04 // len
1244 // 00 03 64 b1
1245 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1246 transactionRef := cc.Server.NewTransactionRef()
1247 data := binary.BigEndian.Uint32(transactionRef)
1248
1249 fileTransfer := &FileTransfer{
1250 FileName: t.GetField(fieldFileName).Data,
1251 FilePath: t.GetField(fieldFilePath).Data,
1252 ReferenceNumber: transactionRef,
1253 Type: FolderDownload,
1254 }
1255 cc.Server.FileTransfers[data] = fileTransfer
1256 cc.Transfers[FolderDownload] = append(cc.Transfers[FolderDownload], fileTransfer)
1257
1258 var fp FilePath
1259 err = fp.UnmarshalBinary(t.GetField(fieldFilePath).Data)
1260 if err != nil {
1261 return res, err
1262 }
1263
1264 fullFilePath := fmt.Sprintf("%v%v", cc.Server.Config.FileRoot+fp.String(), string(fileTransfer.FileName))
1265 transferSize, err := CalcTotalSize(fullFilePath)
1266 if err != nil {
1267 return res, err
1268 }
1269 itemCount, err := CalcItemCount(fullFilePath)
1270 if err != nil {
1271 return res, err
1272 }
1273 res = append(res, cc.NewReply(t,
1274 NewField(fieldRefNum, transactionRef),
1275 NewField(fieldTransferSize, transferSize),
1276 NewField(fieldFolderItemCount, itemCount),
1277 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1278 ))
1279 return res, err
1280 }
1281
1282 // Upload all files from the local folder and its subfolders to the specified path on the server
1283 // Fields used in the request
1284 // 201 File name
1285 // 202 File path
1286 // 108 transfer size Total size of all items in the folder
1287 // 220 Folder item count
1288 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1289 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1290 transactionRef := cc.Server.NewTransactionRef()
1291 data := binary.BigEndian.Uint32(transactionRef)
1292
1293 fileTransfer := &FileTransfer{
1294 FileName: t.GetField(fieldFileName).Data,
1295 FilePath: t.GetField(fieldFilePath).Data,
1296 ReferenceNumber: transactionRef,
1297 Type: FolderUpload,
1298 FolderItemCount: t.GetField(fieldFolderItemCount).Data,
1299 TransferSize: t.GetField(fieldTransferSize).Data,
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 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1308 fileName := t.GetField(fieldFileName).Data
1309 filePath := t.GetField(fieldFilePath).Data
1310
1311 transactionRef := cc.Server.NewTransactionRef()
1312 data := binary.BigEndian.Uint32(transactionRef)
1313
1314 fileTransfer := &FileTransfer{
1315 FileName: fileName,
1316 FilePath: filePath,
1317 ReferenceNumber: transactionRef,
1318 Type: FileUpload,
1319 }
1320
1321 cc.Server.FileTransfers[data] = fileTransfer
1322
1323 res = append(res, cc.NewReply(t, NewField(fieldRefNum, transactionRef)))
1324 return res, err
1325 }
1326
1327 // User options
1328 const (
1329 refusePM = 0
1330 refuseChat = 1
1331 autoResponse = 2
1332 )
1333
1334 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1335 var icon []byte
1336 if len(t.GetField(fieldUserIconID).Data) == 4 {
1337 icon = t.GetField(fieldUserIconID).Data[2:]
1338 } else {
1339 icon = t.GetField(fieldUserIconID).Data
1340 }
1341 *cc.Icon = icon
1342 cc.UserName = t.GetField(fieldUserName).Data
1343
1344 // the options field is only passed by the client versions > 1.2.3.
1345 options := t.GetField(fieldOptions).Data
1346
1347 if options != nil {
1348 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1349 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
1350
1351 // Check refuse private PM option
1352 if optBitmap.Bit(refusePM) == 1 {
1353 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
1354 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
1355 }
1356
1357 // Check refuse private chat option
1358 if optBitmap.Bit(refuseChat) == 1 {
1359 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
1360 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
1361 }
1362
1363 // Check auto response
1364 if optBitmap.Bit(autoResponse) == 1 {
1365 *cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
1366 } else {
1367 *cc.AutoReply = []byte{}
1368 }
1369 }
1370
1371 // Notify all clients of updated user info
1372 cc.sendAll(
1373 tranNotifyChangeUser,
1374 NewField(fieldUserID, *cc.ID),
1375 NewField(fieldUserIconID, *cc.Icon),
1376 NewField(fieldUserFlags, *cc.Flags),
1377 NewField(fieldUserName, cc.UserName),
1378 )
1379
1380 return res, err
1381 }
1382
1383 // HandleKeepAlive response to keepalive transactions with an empty reply
1384 // HL 1.9.2 Client sends keepalive msg every 3 minutes
1385 // HL 1.2.3 Client doesn't send keepalives
1386 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1387 res = append(res, cc.NewReply(t))
1388
1389 return res, err
1390 }
1391
1392 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1393 filePath := cc.Server.Config.FileRoot
1394
1395 path := t.GetField(fieldFilePath).Data
1396 if len(path) > 0 {
1397 filePath = cc.Server.Config.FileRoot + ReadFilePath(path)
1398 }
1399
1400 fileNames, err := getFileNameList(filePath)
1401 if err != nil {
1402 return res, err
1403 }
1404
1405 res = append(res, cc.NewReply(t, fileNames...))
1406
1407 return res, err
1408 }
1409
1410 // =================================
1411 // Hotline private chat flow
1412 // =================================
1413 // 1. ClientA sends tranInviteNewChat to server with user ID to invite
1414 // 2. Server creates new ChatID
1415 // 3. Server sends tranInviteToChat to invitee
1416 // 4. Server replies to ClientA with new Chat ID
1417 //
1418 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1419 // If Accepted is clicked:
1420 // 1. ClientB sends tranJoinChat with fieldChatID
1421
1422 // HandleInviteNewChat invites users to new private chat
1423 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1424 // Client to Invite
1425 targetID := t.GetField(fieldUserID).Data
1426 newChatID := cc.Server.NewPrivateChat(cc)
1427
1428 res = append(res,
1429 *NewTransaction(
1430 tranInviteToChat,
1431 &targetID,
1432 NewField(fieldChatID, newChatID),
1433 NewField(fieldUserName, cc.UserName),
1434 NewField(fieldUserID, *cc.ID),
1435 ),
1436 )
1437
1438 res = append(res,
1439 cc.NewReply(t,
1440 NewField(fieldChatID, newChatID),
1441 NewField(fieldUserName, cc.UserName),
1442 NewField(fieldUserID, *cc.ID),
1443 NewField(fieldUserIconID, *cc.Icon),
1444 NewField(fieldUserFlags, *cc.Flags),
1445 ),
1446 )
1447
1448 return res, err
1449 }
1450
1451 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1452 // Client to Invite
1453 targetID := t.GetField(fieldUserID).Data
1454 chatID := t.GetField(fieldChatID).Data
1455
1456 res = append(res,
1457 *NewTransaction(
1458 tranInviteToChat,
1459 &targetID,
1460 NewField(fieldChatID, chatID),
1461 NewField(fieldUserName, cc.UserName),
1462 NewField(fieldUserID, *cc.ID),
1463 ),
1464 )
1465 res = append(res,
1466 cc.NewReply(
1467 t,
1468 NewField(fieldChatID, chatID),
1469 NewField(fieldUserName, cc.UserName),
1470 NewField(fieldUserID, *cc.ID),
1471 NewField(fieldUserIconID, *cc.Icon),
1472 NewField(fieldUserFlags, *cc.Flags),
1473 ),
1474 )
1475
1476 return res, err
1477 }
1478
1479 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1480 chatID := t.GetField(fieldChatID).Data
1481 chatInt := binary.BigEndian.Uint32(chatID)
1482
1483 privChat := cc.Server.PrivateChats[chatInt]
1484
1485 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1486
1487 for _, c := range sortedClients(privChat.ClientConn) {
1488 res = append(res,
1489 *NewTransaction(
1490 tranChatMsg,
1491 c.ID,
1492 NewField(fieldChatID, chatID),
1493 NewField(fieldData, resMsg),
1494 ),
1495 )
1496 }
1497
1498 return res, err
1499 }
1500
1501 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1502 // Fields used in the reply:
1503 // * 115 Chat subject
1504 // * 300 User name with info (Optional)
1505 // * 300 (more user names with info)
1506 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1507 chatID := t.GetField(fieldChatID).Data
1508 chatInt := binary.BigEndian.Uint32(chatID)
1509
1510 privChat := cc.Server.PrivateChats[chatInt]
1511
1512 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1513 for _, c := range sortedClients(privChat.ClientConn) {
1514 res = append(res,
1515 *NewTransaction(
1516 tranNotifyChatChangeUser,
1517 c.ID,
1518 NewField(fieldChatID, chatID),
1519 NewField(fieldUserName, cc.UserName),
1520 NewField(fieldUserID, *cc.ID),
1521 NewField(fieldUserIconID, *cc.Icon),
1522 NewField(fieldUserFlags, *cc.Flags),
1523 ),
1524 )
1525 }
1526
1527 privChat.ClientConn[cc.uint16ID()] = cc
1528
1529 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1530 for _, c := range sortedClients(privChat.ClientConn) {
1531 user := User{
1532 ID: *c.ID,
1533 Icon: *c.Icon,
1534 Flags: *c.Flags,
1535 Name: string(c.UserName),
1536 }
1537
1538 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1539 }
1540
1541 res = append(res, cc.NewReply(t, replyFields...))
1542 return res, err
1543 }
1544
1545 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1546 // Fields used in the request:
1547 // * 114 fieldChatID
1548 // Reply is not expected.
1549 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1550 chatID := t.GetField(fieldChatID).Data
1551 chatInt := binary.BigEndian.Uint32(chatID)
1552
1553 privChat := cc.Server.PrivateChats[chatInt]
1554
1555 delete(privChat.ClientConn, cc.uint16ID())
1556
1557 // Notify members of the private chat that the user has left
1558 for _, c := range sortedClients(privChat.ClientConn) {
1559 res = append(res,
1560 *NewTransaction(
1561 tranNotifyChatDeleteUser,
1562 c.ID,
1563 NewField(fieldChatID, chatID),
1564 NewField(fieldUserID, *cc.ID),
1565 ),
1566 )
1567 }
1568
1569 return res, err
1570 }
1571
1572 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1573 // Fields used in the request:
1574 // * 114 Chat ID
1575 // * 115 Chat subject Chat subject string
1576 // Reply is not expected.
1577 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1578 chatID := t.GetField(fieldChatID).Data
1579 chatInt := binary.BigEndian.Uint32(chatID)
1580
1581 privChat := cc.Server.PrivateChats[chatInt]
1582 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1583
1584 for _, c := range sortedClients(privChat.ClientConn) {
1585 res = append(res,
1586 *NewTransaction(
1587 tranNotifyChatSubject,
1588 c.ID,
1589 NewField(fieldChatID, chatID),
1590 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),
1591 ),
1592 )
1593 }
1594
1595 return res, err
1596 }