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