]> git.r.bdr.sh - rbdr/mobius/blob - hotline/transaction_handlers.go
2a817687f531ca774fac3c33641550542826699e
[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.v3"
9 "io/ioutil"
10 "math/big"
11 "os"
12 "path"
13 "path/filepath"
14 "sort"
15 "strings"
16 "time"
17 )
18
19 type TransactionType struct {
20 Handler func(*ClientConn, *Transaction) ([]Transaction, error) // function for handling the transaction type
21 Name string // Name of transaction as it will appear in logging
22 RequiredFields []requiredField
23 }
24
25 var TransactionHandlers = map[uint16]TransactionType{
26 // Server initiated
27 tranChatMsg: {
28 Name: "tranChatMsg",
29 },
30 // Server initiated
31 tranNotifyChangeUser: {
32 Name: "tranNotifyChangeUser",
33 },
34 tranError: {
35 Name: "tranError",
36 },
37 tranShowAgreement: {
38 Name: "tranShowAgreement",
39 },
40 tranUserAccess: {
41 Name: "tranUserAccess",
42 },
43 tranNotifyDeleteUser: {
44 Name: "tranNotifyDeleteUser",
45 },
46 tranAgreed: {
47 Name: "tranAgreed",
48 Handler: HandleTranAgreed,
49 },
50 tranChatSend: {
51 Name: "tranChatSend",
52 Handler: HandleChatSend,
53 RequiredFields: []requiredField{
54 {
55 ID: fieldData,
56 minLen: 0,
57 },
58 },
59 },
60 tranDelNewsArt: {
61 Name: "tranDelNewsArt",
62 Handler: HandleDelNewsArt,
63 },
64 tranDelNewsItem: {
65 Name: "tranDelNewsItem",
66 Handler: HandleDelNewsItem,
67 },
68 tranDeleteFile: {
69 Name: "tranDeleteFile",
70 Handler: HandleDeleteFile,
71 },
72 tranDeleteUser: {
73 Name: "tranDeleteUser",
74 Handler: HandleDeleteUser,
75 },
76 tranDisconnectUser: {
77 Name: "tranDisconnectUser",
78 Handler: HandleDisconnectUser,
79 },
80 tranDownloadFile: {
81 Name: "tranDownloadFile",
82 Handler: HandleDownloadFile,
83 },
84 tranDownloadFldr: {
85 Name: "tranDownloadFldr",
86 Handler: HandleDownloadFolder,
87 },
88 tranGetClientInfoText: {
89 Name: "tranGetClientInfoText",
90 Handler: HandleGetClientInfoText,
91 },
92 tranGetFileInfo: {
93 Name: "tranGetFileInfo",
94 Handler: HandleGetFileInfo,
95 },
96 tranGetFileNameList: {
97 Name: "tranGetFileNameList",
98 Handler: HandleGetFileNameList,
99 },
100 tranGetMsgs: {
101 Name: "tranGetMsgs",
102 Handler: HandleGetMsgs,
103 },
104 tranGetNewsArtData: {
105 Name: "tranGetNewsArtData",
106 Handler: HandleGetNewsArtData,
107 },
108 tranGetNewsArtNameList: {
109 Name: "tranGetNewsArtNameList",
110 Handler: HandleGetNewsArtNameList,
111 },
112 tranGetNewsCatNameList: {
113 Name: "tranGetNewsCatNameList",
114 Handler: HandleGetNewsCatNameList,
115 },
116 tranGetUser: {
117 Name: "tranGetUser",
118 Handler: HandleGetUser,
119 },
120 tranGetUserNameList: {
121 Name: "tranHandleGetUserNameList",
122 Handler: HandleGetUserNameList,
123 },
124 tranInviteNewChat: {
125 Name: "tranInviteNewChat",
126 Handler: HandleInviteNewChat,
127 },
128 tranInviteToChat: {
129 Name: "tranInviteToChat",
130 Handler: HandleInviteToChat,
131 },
132 tranJoinChat: {
133 Name: "tranJoinChat",
134 Handler: HandleJoinChat,
135 },
136 tranKeepAlive: {
137 Name: "tranKeepAlive",
138 Handler: HandleKeepAlive,
139 },
140 tranLeaveChat: {
141 Name: "tranJoinChat",
142 Handler: HandleLeaveChat,
143 },
144 tranListUsers: {
145 Name: "tranListUsers",
146 Handler: HandleListUsers,
147 },
148 tranMoveFile: {
149 Name: "tranMoveFile",
150 Handler: HandleMoveFile,
151 },
152 tranNewFolder: {
153 Name: "tranNewFolder",
154 Handler: HandleNewFolder,
155 },
156 tranNewNewsCat: {
157 Name: "tranNewNewsCat",
158 Handler: HandleNewNewsCat,
159 },
160 tranNewNewsFldr: {
161 Name: "tranNewNewsFldr",
162 Handler: HandleNewNewsFldr,
163 },
164 tranNewUser: {
165 Name: "tranNewUser",
166 Handler: HandleNewUser,
167 },
168 tranUpdateUser: {
169 Name: "tranUpdateUser",
170 Handler: HandleUpdateUser,
171 },
172 tranOldPostNews: {
173 Name: "tranOldPostNews",
174 Handler: HandleTranOldPostNews,
175 },
176 tranPostNewsArt: {
177 Name: "tranPostNewsArt",
178 Handler: HandlePostNewsArt,
179 },
180 tranRejectChatInvite: {
181 Name: "tranRejectChatInvite",
182 Handler: HandleRejectChatInvite,
183 },
184 tranSendInstantMsg: {
185 Name: "tranSendInstantMsg",
186 Handler: HandleSendInstantMsg,
187 RequiredFields: []requiredField{
188 {
189 ID: fieldData,
190 minLen: 0,
191 },
192 {
193 ID: fieldUserID,
194 },
195 },
196 },
197 tranSetChatSubject: {
198 Name: "tranSetChatSubject",
199 Handler: HandleSetChatSubject,
200 },
201 tranMakeFileAlias: {
202 Name: "tranMakeFileAlias",
203 Handler: HandleMakeAlias,
204 RequiredFields: []requiredField{
205 {ID: fieldFileName, minLen: 1},
206 {ID: fieldFilePath, minLen: 1},
207 {ID: fieldFileNewPath, minLen: 1},
208 },
209 },
210 tranSetClientUserInfo: {
211 Name: "tranSetClientUserInfo",
212 Handler: HandleSetClientUserInfo,
213 },
214 tranSetFileInfo: {
215 Name: "tranSetFileInfo",
216 Handler: HandleSetFileInfo,
217 },
218 tranSetUser: {
219 Name: "tranSetUser",
220 Handler: HandleSetUser,
221 },
222 tranUploadFile: {
223 Name: "tranUploadFile",
224 Handler: HandleUploadFile,
225 },
226 tranUploadFldr: {
227 Name: "tranUploadFldr",
228 Handler: HandleUploadFolder,
229 },
230 tranUserBroadcast: {
231 Name: "tranUserBroadcast",
232 Handler: HandleUserBroadcast,
233 },
234 tranDownloadBanner: {
235 Name: "tranDownloadBanner",
236 Handler: HandleDownloadBanner,
237 },
238 }
239
240 func HandleChatSend(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
241 if !authorize(cc.Account.Access, accessSendChat) {
242 res = append(res, cc.NewErrReply(t, "You are not allowed to participate in chat."))
243 return res, err
244 }
245
246 // Truncate long usernames
247 trunc := fmt.Sprintf("%13s", cc.UserName)
248 formattedMsg := fmt.Sprintf("\r%.14s: %s", trunc, t.GetField(fieldData).Data)
249
250 // By holding the option key, Hotline chat allows users to send /me formatted messages like:
251 // *** Halcyon does stuff
252 // This is indicated by the presence of the optional field fieldChatOptions in the transaction payload
253 if t.GetField(fieldChatOptions).Data != nil {
254 formattedMsg = fmt.Sprintf("\r*** %s %s", cc.UserName, t.GetField(fieldData).Data)
255 }
256
257 chatID := t.GetField(fieldChatID).Data
258 // a non-nil chatID indicates the message belongs to a private chat
259 if chatID != nil {
260 chatInt := binary.BigEndian.Uint32(chatID)
261 privChat := cc.Server.PrivateChats[chatInt]
262
263 clients := sortedClients(privChat.ClientConn)
264
265 // send the message to all connected clients of the private chat
266 for _, c := range clients {
267 res = append(res, *NewTransaction(
268 tranChatMsg,
269 c.ID,
270 NewField(fieldChatID, chatID),
271 NewField(fieldData, []byte(formattedMsg)),
272 ))
273 }
274 return res, err
275 }
276
277 for _, c := range sortedClients(cc.Server.Clients) {
278 // Filter out clients that do not have the read chat permission
279 if authorize(c.Account.Access, accessReadChat) {
280 res = append(res, *NewTransaction(tranChatMsg, c.ID, NewField(fieldData, []byte(formattedMsg))))
281 }
282 }
283
284 return res, err
285 }
286
287 // HandleSendInstantMsg sends instant message to the user on the current server.
288 // Fields used in the request:
289 // 103 User ID
290 // 113 Options
291 // One of the following values:
292 // - User message (myOpt_UserMessage = 1)
293 // - Refuse message (myOpt_RefuseMessage = 2)
294 // - Refuse chat (myOpt_RefuseChat = 3)
295 // - Automatic response (myOpt_AutomaticResponse = 4)"
296 // 101 Data Optional
297 // 214 Quoting message Optional
298 //
299 // Fields used in the reply:
300 // None
301 func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
302 msg := t.GetField(fieldData)
303 ID := t.GetField(fieldUserID)
304
305 reply := NewTransaction(
306 tranServerMsg,
307 &ID.Data,
308 NewField(fieldData, msg.Data),
309 NewField(fieldUserName, cc.UserName),
310 NewField(fieldUserID, *cc.ID),
311 NewField(fieldOptions, []byte{0, 1}),
312 )
313
314 // Later versions of Hotline include the original message in the fieldQuotingMsg field so
315 // the receiving client can display both the received message and what it is in reply to
316 if t.GetField(fieldQuotingMsg).Data != nil {
317 reply.Fields = append(reply.Fields, NewField(fieldQuotingMsg, t.GetField(fieldQuotingMsg).Data))
318 }
319
320 res = append(res, *reply)
321
322 id, _ := byteToInt(ID.Data)
323 otherClient, ok := cc.Server.Clients[uint16(id)]
324 if !ok {
325 return res, errors.New("invalid client ID")
326 }
327
328 // Respond with auto reply if other client has it enabled
329 if len(otherClient.AutoReply) > 0 {
330 res = append(res,
331 *NewTransaction(
332 tranServerMsg,
333 cc.ID,
334 NewField(fieldData, otherClient.AutoReply),
335 NewField(fieldUserName, otherClient.UserName),
336 NewField(fieldUserID, *otherClient.ID),
337 NewField(fieldOptions, []byte{0, 1}),
338 ),
339 )
340 }
341
342 res = append(res, cc.NewReply(t))
343
344 return res, err
345 }
346
347 func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
348 fileName := t.GetField(fieldFileName).Data
349 filePath := t.GetField(fieldFilePath).Data
350
351 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
352 if err != nil {
353 return res, err
354 }
355
356 fw, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
357 if err != nil {
358 return res, err
359 }
360
361 res = append(res, cc.NewReply(t,
362 NewField(fieldFileName, []byte(fw.name)),
363 NewField(fieldFileTypeString, fw.ffo.FlatFileInformationFork.friendlyType()),
364 NewField(fieldFileCreatorString, fw.ffo.FlatFileInformationFork.friendlyCreator()),
365 NewField(fieldFileComment, fw.ffo.FlatFileInformationFork.Comment),
366 NewField(fieldFileType, fw.ffo.FlatFileInformationFork.TypeSignature),
367 NewField(fieldFileCreateDate, fw.ffo.FlatFileInformationFork.CreateDate),
368 NewField(fieldFileModifyDate, fw.ffo.FlatFileInformationFork.ModifyDate),
369 NewField(fieldFileSize, fw.totalSize()),
370 ))
371 return res, err
372 }
373
374 // HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
375 // Fields used in the request:
376 // * 201 File name
377 // * 202 File path Optional
378 // * 211 File new name Optional
379 // * 210 File comment Optional
380 // Fields used in the reply: None
381 func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
382 fileName := t.GetField(fieldFileName).Data
383 filePath := t.GetField(fieldFilePath).Data
384
385 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
386 if err != nil {
387 return res, err
388 }
389
390 fi, err := cc.Server.FS.Stat(fullFilePath)
391 if err != nil {
392 return res, err
393 }
394
395 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
396 if err != nil {
397 return res, err
398 }
399 if t.GetField(fieldFileComment).Data != nil {
400 switch mode := fi.Mode(); {
401 case mode.IsDir():
402 if !authorize(cc.Account.Access, accessSetFolderComment) {
403 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for folders."))
404 return res, err
405 }
406 case mode.IsRegular():
407 if !authorize(cc.Account.Access, accessSetFileComment) {
408 res = append(res, cc.NewErrReply(t, "You are not allowed to set comments for files."))
409 return res, err
410 }
411 }
412
413 if err := hlFile.ffo.FlatFileInformationFork.setComment(t.GetField(fieldFileComment).Data); err != nil {
414 return res, err
415 }
416 w, err := hlFile.infoForkWriter()
417 if err != nil {
418 return res, err
419 }
420 _, err = w.Write(hlFile.ffo.FlatFileInformationFork.MarshalBinary())
421 if err != nil {
422 return res, err
423 }
424 }
425
426 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, t.GetField(fieldFileNewName).Data)
427 if err != nil {
428 return nil, err
429 }
430
431 fileNewName := t.GetField(fieldFileNewName).Data
432
433 if fileNewName != nil {
434 switch mode := fi.Mode(); {
435 case mode.IsDir():
436 if !authorize(cc.Account.Access, accessRenameFolder) {
437 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
438 return res, err
439 }
440 err = os.Rename(fullFilePath, fullNewFilePath)
441 if os.IsNotExist(err) {
442 res = append(res, cc.NewErrReply(t, "Cannot rename folder "+string(fileName)+" because it does not exist or cannot be found."))
443 return res, err
444 }
445 case mode.IsRegular():
446 if !authorize(cc.Account.Access, accessRenameFile) {
447 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
448 return res, err
449 }
450 fileDir, err := readPath(cc.Server.Config.FileRoot, filePath, []byte{})
451 if err != nil {
452 return nil, err
453 }
454 hlFile.name = string(fileNewName)
455 err = hlFile.move(fileDir)
456 if os.IsNotExist(err) {
457 res = append(res, cc.NewErrReply(t, "Cannot rename file "+string(fileName)+" because it does not exist or cannot be found."))
458 return res, err
459 }
460 if err != nil {
461 panic(err)
462 }
463 }
464 }
465
466 res = append(res, cc.NewReply(t))
467 return res, err
468 }
469
470 // HandleDeleteFile deletes a file or folder
471 // Fields used in the request:
472 // * 201 File name
473 // * 202 File path
474 // Fields used in the reply: none
475 func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
476 fileName := t.GetField(fieldFileName).Data
477 filePath := t.GetField(fieldFilePath).Data
478
479 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
480 if err != nil {
481 return res, err
482 }
483
484 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, 0)
485 if err != nil {
486 return res, err
487 }
488
489 fi, err := hlFile.dataFile()
490 if err != nil {
491 res = append(res, cc.NewErrReply(t, "Cannot delete file "+string(fileName)+" because it does not exist or cannot be found."))
492 return res, nil
493 }
494
495 switch mode := fi.Mode(); {
496 case mode.IsDir():
497 if !authorize(cc.Account.Access, accessDeleteFolder) {
498 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
499 return res, err
500 }
501 case mode.IsRegular():
502 if !authorize(cc.Account.Access, accessDeleteFile) {
503 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
504 return res, err
505 }
506 }
507
508 if err := hlFile.delete(); err != nil {
509 return res, err
510 }
511
512 res = append(res, cc.NewReply(t))
513 return res, err
514 }
515
516 // HandleMoveFile moves files or folders. Note: seemingly not documented
517 func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
518 fileName := string(t.GetField(fieldFileName).Data)
519
520 filePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
521 if err != nil {
522 return res, err
523 }
524
525 fileNewPath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFileNewPath).Data, nil)
526 if err != nil {
527 return res, err
528 }
529
530 cc.logger.Infow("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
531
532 hlFile, err := newFileWrapper(cc.Server.FS, filePath, 0)
533 if err != nil {
534 return res, err
535 }
536
537 fi, err := hlFile.dataFile()
538 if err != nil {
539 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
540 return res, err
541 }
542 if err != nil {
543 return res, err
544 }
545 switch mode := fi.Mode(); {
546 case mode.IsDir():
547 if !authorize(cc.Account.Access, accessMoveFolder) {
548 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
549 return res, err
550 }
551 case mode.IsRegular():
552 if !authorize(cc.Account.Access, accessMoveFile) {
553 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
554 return res, err
555 }
556 }
557 if err := hlFile.move(fileNewPath); err != nil {
558 return res, err
559 }
560 // TODO: handle other possible errors; e.g. fileWrapper delete fails due to fileWrapper permission issue
561
562 res = append(res, cc.NewReply(t))
563 return res, err
564 }
565
566 func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
567 if !authorize(cc.Account.Access, accessCreateFolder) {
568 res = append(res, cc.NewErrReply(t, "You are not allowed to create folders."))
569 return res, err
570 }
571 folderName := string(t.GetField(fieldFileName).Data)
572
573 folderName = path.Join("/", folderName)
574
575 var subPath string
576
577 // fieldFilePath is only present for nested paths
578 if t.GetField(fieldFilePath).Data != nil {
579 var newFp FilePath
580 err := newFp.UnmarshalBinary(t.GetField(fieldFilePath).Data)
581 if err != nil {
582 return nil, err
583 }
584
585 for _, pathItem := range newFp.Items {
586 subPath = filepath.Join("/", subPath, string(pathItem.Name))
587 }
588 }
589 newFolderPath := path.Join(cc.Server.Config.FileRoot, subPath, folderName)
590
591 // TODO: check path and folder name lengths
592
593 if _, err := cc.Server.FS.Stat(newFolderPath); !os.IsNotExist(err) {
594 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that name.", folderName)
595 return []Transaction{cc.NewErrReply(t, msg)}, nil
596 }
597
598 // TODO: check for disallowed characters to maintain compatibility for original client
599
600 if err := cc.Server.FS.Mkdir(newFolderPath, 0777); err != nil {
601 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
602 return []Transaction{cc.NewErrReply(t, msg)}, nil
603 }
604
605 res = append(res, cc.NewReply(t))
606 return res, err
607 }
608
609 func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
610 if !authorize(cc.Account.Access, accessModifyUser) {
611 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
612 return res, err
613 }
614
615 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
616 userName := string(t.GetField(fieldUserName).Data)
617
618 newAccessLvl := t.GetField(fieldUserAccess).Data
619
620 account := cc.Server.Accounts[login]
621 account.Access = &newAccessLvl
622 account.Name = userName
623
624 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
625 // not include fieldUserPassword
626 if t.GetField(fieldUserPassword).Data == nil {
627 account.Password = hashAndSalt([]byte(""))
628 }
629 if len(t.GetField(fieldUserPassword).Data) > 1 {
630 account.Password = hashAndSalt(t.GetField(fieldUserPassword).Data)
631 }
632
633 out, err := yaml.Marshal(&account)
634 if err != nil {
635 return res, err
636 }
637 if err := os.WriteFile(filepath.Join(cc.Server.ConfigDir, "Users", login+".yaml"), out, 0666); err != nil {
638 return res, err
639 }
640
641 // Notify connected clients logged in as the user of the new access level
642 for _, c := range cc.Server.Clients {
643 if c.Account.Login == login {
644 // Note: comment out these two lines to test server-side deny messages
645 newT := NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, newAccessLvl))
646 res = append(res, *newT)
647
648 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(c.Flags)))
649 if authorize(c.Account.Access, accessDisconUser) {
650 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 1)
651 } else {
652 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 0)
653 }
654 binary.BigEndian.PutUint16(c.Flags, uint16(flagBitmap.Int64()))
655
656 c.Account.Access = account.Access
657
658 cc.sendAll(
659 tranNotifyChangeUser,
660 NewField(fieldUserID, *c.ID),
661 NewField(fieldUserFlags, c.Flags),
662 NewField(fieldUserName, c.UserName),
663 NewField(fieldUserIconID, c.Icon),
664 )
665 }
666 }
667
668 res = append(res, cc.NewReply(t))
669 return res, err
670 }
671
672 func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
673 if !authorize(cc.Account.Access, accessOpenUser) {
674 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
675 return res, err
676 }
677
678 account := cc.Server.Accounts[string(t.GetField(fieldUserLogin).Data)]
679 if account == nil {
680 res = append(res, cc.NewErrReply(t, "Account does not exist."))
681 return res, err
682 }
683
684 res = append(res, cc.NewReply(t,
685 NewField(fieldUserName, []byte(account.Name)),
686 NewField(fieldUserLogin, negateString(t.GetField(fieldUserLogin).Data)),
687 NewField(fieldUserPassword, []byte(account.Password)),
688 NewField(fieldUserAccess, *account.Access),
689 ))
690 return res, err
691 }
692
693 func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
694 if !authorize(cc.Account.Access, accessOpenUser) {
695 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
696 return res, err
697 }
698
699 var userFields []Field
700 for _, acc := range cc.Server.Accounts {
701 b := make([]byte, 0, 100)
702 n, err := acc.Read(b)
703 if err != nil {
704 return res, err
705 }
706
707 userFields = append(userFields, NewField(fieldData, b[:n]))
708 }
709
710 res = append(res, cc.NewReply(t, userFields...))
711 return res, err
712 }
713
714 // HandleUpdateUser is used by the v1.5+ multi-user editor to perform account editing for multiple users at a time.
715 // An update can be a mix of these actions:
716 // * Create user
717 // * Delete user
718 // * Modify user (including renaming the account login)
719 //
720 // The Transaction sent by the client includes one data field per user that was modified. This data field in turn
721 // contains another data field encoded in its payload with a varying number of sub fields depending on which action is
722 // performed. This seems to be the only place in the Hotline protocol where a data field contains another data field.
723 func HandleUpdateUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
724 for _, field := range t.Fields {
725 subFields, err := ReadFields(field.Data[0:2], field.Data[2:])
726 if err != nil {
727 return res, err
728 }
729
730 if len(subFields) == 1 {
731 login := DecodeUserString(getField(fieldData, &subFields).Data)
732 cc.logger.Infow("DeleteUser", "login", login)
733
734 if !authorize(cc.Account.Access, accessDeleteUser) {
735 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
736 return res, err
737 }
738
739 if err := cc.Server.DeleteUser(login); err != nil {
740 return res, err
741 }
742 continue
743 }
744
745 login := DecodeUserString(getField(fieldUserLogin, &subFields).Data)
746
747 // check if the login dataFile; if so, we know we are updating an existing user
748 if acc, ok := cc.Server.Accounts[login]; ok {
749 cc.logger.Infow("UpdateUser", "login", login)
750
751 // account dataFile, so this is an update action
752 if !authorize(cc.Account.Access, accessModifyUser) {
753 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
754 return res, err
755 }
756
757 if getField(fieldUserPassword, &subFields) != nil {
758 newPass := getField(fieldUserPassword, &subFields).Data
759 acc.Password = hashAndSalt(newPass)
760 } else {
761 acc.Password = hashAndSalt([]byte(""))
762 }
763
764 if getField(fieldUserAccess, &subFields) != nil {
765 acc.Access = &getField(fieldUserAccess, &subFields).Data
766 }
767
768 err = cc.Server.UpdateUser(
769 DecodeUserString(getField(fieldData, &subFields).Data),
770 DecodeUserString(getField(fieldUserLogin, &subFields).Data),
771 string(getField(fieldUserName, &subFields).Data),
772 acc.Password,
773 *acc.Access,
774 )
775 if err != nil {
776 return res, err
777 }
778 } else {
779 cc.logger.Infow("CreateUser", "login", login)
780
781 if !authorize(cc.Account.Access, accessCreateUser) {
782 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
783 return res, err
784 }
785
786 err := cc.Server.NewUser(
787 login,
788 string(getField(fieldUserName, &subFields).Data),
789 string(getField(fieldUserPassword, &subFields).Data),
790 getField(fieldUserAccess, &subFields).Data,
791 )
792 if err != nil {
793 return []Transaction{}, err
794 }
795 }
796 }
797
798 res = append(res, cc.NewReply(t))
799 return res, err
800 }
801
802 // HandleNewUser creates a new user account
803 func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
804 if !authorize(cc.Account.Access, accessCreateUser) {
805 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
806 return res, err
807 }
808
809 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
810
811 // If the account already dataFile, reply with an error
812 if _, ok := cc.Server.Accounts[login]; ok {
813 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
814 return res, err
815 }
816
817 if err := cc.Server.NewUser(
818 login,
819 string(t.GetField(fieldUserName).Data),
820 string(t.GetField(fieldUserPassword).Data),
821 t.GetField(fieldUserAccess).Data,
822 ); err != nil {
823 return []Transaction{}, err
824 }
825
826 res = append(res, cc.NewReply(t))
827 return res, err
828 }
829
830 func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
831 if !authorize(cc.Account.Access, accessDeleteUser) {
832 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
833 return res, err
834 }
835
836 // TODO: Handle case where account doesn't exist; e.g. delete race condition
837 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
838
839 if err := cc.Server.DeleteUser(login); err != nil {
840 return res, err
841 }
842
843 res = append(res, cc.NewReply(t))
844 return res, err
845 }
846
847 // HandleUserBroadcast sends an Administrator Message to all connected clients of the server
848 func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
849 if !authorize(cc.Account.Access, accessBroadcast) {
850 res = append(res, cc.NewErrReply(t, "You are not allowed to send broadcast messages."))
851 return res, err
852 }
853
854 cc.sendAll(
855 tranServerMsg,
856 NewField(fieldData, t.GetField(tranGetMsgs).Data),
857 NewField(fieldChatOptions, []byte{0}),
858 )
859
860 res = append(res, cc.NewReply(t))
861 return res, err
862 }
863
864 func byteToInt(bytes []byte) (int, error) {
865 switch len(bytes) {
866 case 2:
867 return int(binary.BigEndian.Uint16(bytes)), nil
868 case 4:
869 return int(binary.BigEndian.Uint32(bytes)), nil
870 }
871
872 return 0, errors.New("unknown byte length")
873 }
874
875 // HandleGetClientInfoText returns user information for the specific user.
876 //
877 // Fields used in the request:
878 // 103 User ID
879 //
880 // Fields used in the reply:
881 // 102 User name
882 // 101 Data User info text string
883 func HandleGetClientInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
884 if !authorize(cc.Account.Access, accessGetClientInfo) {
885 res = append(res, cc.NewErrReply(t, "You are not allowed to get client info."))
886 return res, err
887 }
888
889 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
890
891 clientConn := cc.Server.Clients[uint16(clientID)]
892 if clientConn == nil {
893 return append(res, cc.NewErrReply(t, "User not found.")), err
894 }
895
896 res = append(res, cc.NewReply(t,
897 NewField(fieldData, []byte(clientConn.String())),
898 NewField(fieldUserName, clientConn.UserName),
899 ))
900 return res, err
901 }
902
903 func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
904 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
905
906 return res, err
907 }
908
909 func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
910 cc.Agreed = true
911
912 if t.GetField(fieldUserName).Data != nil {
913 if cc.Authorize(accessAnyName) {
914 cc.UserName = t.GetField(fieldUserName).Data
915 } else {
916 cc.UserName = []byte(cc.Account.Name)
917 }
918 }
919
920 cc.Icon = t.GetField(fieldUserIconID).Data
921
922 cc.logger = cc.logger.With("name", string(cc.UserName))
923 cc.logger.Infow("Login successful", "clientVersion", fmt.Sprintf("%x", cc.Version))
924
925 options := t.GetField(fieldOptions).Data
926 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
927
928 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
929
930 // Check refuse private PM option
931 if optBitmap.Bit(refusePM) == 1 {
932 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
933 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
934 }
935
936 // Check refuse private chat option
937 if optBitmap.Bit(refuseChat) == 1 {
938 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
939 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
940 }
941
942 // Check auto response
943 if optBitmap.Bit(autoResponse) == 1 {
944 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
945 } else {
946 cc.AutoReply = []byte{}
947 }
948
949 trans := cc.notifyOthers(
950 *NewTransaction(
951 tranNotifyChangeUser, nil,
952 NewField(fieldUserName, cc.UserName),
953 NewField(fieldUserID, *cc.ID),
954 NewField(fieldUserIconID, cc.Icon),
955 NewField(fieldUserFlags, cc.Flags),
956 ),
957 )
958 res = append(res, trans...)
959
960 if cc.Server.Config.BannerFile != "" {
961 res = append(res, *NewTransaction(tranServerBanner, cc.ID, NewField(fieldBannerType, []byte("JPEG"))))
962 }
963
964 res = append(res, cc.NewReply(t))
965
966 return res, err
967 }
968
969 const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
970 // "Mon, 02 Jan 2006 15:04:05 MST"
971
972 const defaultNewsTemplate = `From %s (%s):
973
974 %s
975
976 __________________________________________________________`
977
978 // HandleTranOldPostNews updates the flat news
979 // Fields used in this request:
980 // 101 Data
981 func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
982 if !authorize(cc.Account.Access, accessNewsPostArt) {
983 res = append(res, cc.NewErrReply(t, "You are not allowed to post news."))
984 return res, err
985 }
986
987 cc.Server.flatNewsMux.Lock()
988 defer cc.Server.flatNewsMux.Unlock()
989
990 newsDateTemplate := defaultNewsDateFormat
991 if cc.Server.Config.NewsDateFormat != "" {
992 newsDateTemplate = cc.Server.Config.NewsDateFormat
993 }
994
995 newsTemplate := defaultNewsTemplate
996 if cc.Server.Config.NewsDelimiter != "" {
997 newsTemplate = cc.Server.Config.NewsDelimiter
998 }
999
1000 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
1001 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
1002
1003 // update news in memory
1004 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
1005
1006 // update news on disk
1007 if err := ioutil.WriteFile(cc.Server.ConfigDir+"MessageBoard.txt", cc.Server.FlatNews, 0644); err != nil {
1008 return res, err
1009 }
1010
1011 // Notify all clients of updated news
1012 cc.sendAll(
1013 tranNewMsg,
1014 NewField(fieldData, []byte(newsPost)),
1015 )
1016
1017 res = append(res, cc.NewReply(t))
1018 return res, err
1019 }
1020
1021 func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1022 if !authorize(cc.Account.Access, accessDisconUser) {
1023 res = append(res, cc.NewErrReply(t, "You are not allowed to disconnect users."))
1024 return res, err
1025 }
1026
1027 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
1028
1029 if authorize(clientConn.Account.Access, accessCannotBeDiscon) {
1030 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
1031 return res, err
1032 }
1033
1034 // If fieldOptions is set, then the client IP is banned in addition to disconnected.
1035 // 00 01 = temporary ban
1036 // 00 02 = permanent ban
1037 if t.GetField(fieldOptions).Data != nil {
1038 switch t.GetField(fieldOptions).Data[1] {
1039 case 1:
1040 // send message: "You are temporarily banned on this server"
1041 cc.logger.Infow("Disconnect & temporarily ban " + string(clientConn.UserName))
1042
1043 res = append(res, *NewTransaction(
1044 tranServerMsg,
1045 clientConn.ID,
1046 NewField(fieldData, []byte("You are temporarily banned on this server")),
1047 NewField(fieldChatOptions, []byte{0, 0}),
1048 ))
1049
1050 banUntil := time.Now().Add(tempBanDuration)
1051 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = &banUntil
1052 cc.Server.writeBanList()
1053 case 2:
1054 // send message: "You are permanently banned on this server"
1055 cc.logger.Infow("Disconnect & ban " + string(clientConn.UserName))
1056
1057 res = append(res, *NewTransaction(
1058 tranServerMsg,
1059 clientConn.ID,
1060 NewField(fieldData, []byte("You are permanently banned on this server")),
1061 NewField(fieldChatOptions, []byte{0, 0}),
1062 ))
1063
1064 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = nil
1065 cc.Server.writeBanList()
1066 }
1067 }
1068
1069 // TODO: remove this awful hack
1070 go func() {
1071 time.Sleep(1 * time.Second)
1072 clientConn.Disconnect()
1073 }()
1074
1075 return append(res, cc.NewReply(t)), err
1076 }
1077
1078 // HandleGetNewsCatNameList returns a list of news categories for a path
1079 // Fields used in the request:
1080 // 325 News path (Optional)
1081 func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1082 if !authorize(cc.Account.Access, accessNewsReadArt) {
1083 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1084 return res, err
1085 }
1086
1087 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1088 cats := cc.Server.GetNewsCatByPath(pathStrs)
1089
1090 // To store the keys in slice in sorted order
1091 keys := make([]string, len(cats))
1092 i := 0
1093 for k := range cats {
1094 keys[i] = k
1095 i++
1096 }
1097 sort.Strings(keys)
1098
1099 var fieldData []Field
1100 for _, k := range keys {
1101 cat := cats[k]
1102 b, _ := cat.MarshalBinary()
1103 fieldData = append(fieldData, NewField(
1104 fieldNewsCatListData15,
1105 b,
1106 ))
1107 }
1108
1109 res = append(res, cc.NewReply(t, fieldData...))
1110 return res, err
1111 }
1112
1113 func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1114 if !authorize(cc.Account.Access, accessNewsCreateCat) {
1115 res = append(res, cc.NewErrReply(t, "You are not allowed to create news categories."))
1116 return res, err
1117 }
1118
1119 name := string(t.GetField(fieldNewsCatName).Data)
1120 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1121
1122 cats := cc.Server.GetNewsCatByPath(pathStrs)
1123 cats[name] = NewsCategoryListData15{
1124 Name: name,
1125 Type: []byte{0, 3},
1126 Articles: map[uint32]*NewsArtData{},
1127 SubCats: make(map[string]NewsCategoryListData15),
1128 }
1129
1130 if err := cc.Server.writeThreadedNews(); err != nil {
1131 return res, err
1132 }
1133 res = append(res, cc.NewReply(t))
1134 return res, err
1135 }
1136
1137 // Fields used in the request:
1138 // 322 News category name
1139 // 325 News path
1140 func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1141 if !authorize(cc.Account.Access, accessNewsCreateFldr) {
1142 res = append(res, cc.NewErrReply(t, "You are not allowed to create news folders."))
1143 return res, err
1144 }
1145
1146 name := string(t.GetField(fieldFileName).Data)
1147 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1148
1149 cc.logger.Infof("Creating new news folder %s", name)
1150
1151 cats := cc.Server.GetNewsCatByPath(pathStrs)
1152 cats[name] = NewsCategoryListData15{
1153 Name: name,
1154 Type: []byte{0, 2},
1155 Articles: map[uint32]*NewsArtData{},
1156 SubCats: make(map[string]NewsCategoryListData15),
1157 }
1158 if err := cc.Server.writeThreadedNews(); err != nil {
1159 return res, err
1160 }
1161 res = append(res, cc.NewReply(t))
1162 return res, err
1163 }
1164
1165 // Fields used in the request:
1166 // 325 News path Optional
1167 //
1168 // Reply fields:
1169 // 321 News article list data Optional
1170 func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1171 if !authorize(cc.Account.Access, accessNewsReadArt) {
1172 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1173 return res, err
1174 }
1175 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1176
1177 var cat NewsCategoryListData15
1178 cats := cc.Server.ThreadedNews.Categories
1179
1180 for _, fp := range pathStrs {
1181 cat = cats[fp]
1182 cats = cats[fp].SubCats
1183 }
1184
1185 nald := cat.GetNewsArtListData()
1186
1187 res = append(res, cc.NewReply(t, NewField(fieldNewsArtListData, nald.Payload())))
1188 return res, err
1189 }
1190
1191 func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1192 if !authorize(cc.Account.Access, accessNewsReadArt) {
1193 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1194 return res, err
1195 }
1196
1197 // Request fields
1198 // 325 News fp
1199 // 326 News article ID
1200 // 327 News article data flavor
1201
1202 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1203
1204 var cat NewsCategoryListData15
1205 cats := cc.Server.ThreadedNews.Categories
1206
1207 for _, fp := range pathStrs {
1208 cat = cats[fp]
1209 cats = cats[fp].SubCats
1210 }
1211 newsArtID := t.GetField(fieldNewsArtID).Data
1212
1213 convertedArtID := binary.BigEndian.Uint16(newsArtID)
1214
1215 art := cat.Articles[uint32(convertedArtID)]
1216 if art == nil {
1217 res = append(res, cc.NewReply(t))
1218 return res, err
1219 }
1220
1221 // Reply fields
1222 // 328 News article title
1223 // 329 News article poster
1224 // 330 News article date
1225 // 331 Previous article ID
1226 // 332 Next article ID
1227 // 335 Parent article ID
1228 // 336 First child article ID
1229 // 327 News article data flavor "Should be “text/plain”
1230 // 333 News article data Optional (if data flavor is “text/plain”)
1231
1232 res = append(res, cc.NewReply(t,
1233 NewField(fieldNewsArtTitle, []byte(art.Title)),
1234 NewField(fieldNewsArtPoster, []byte(art.Poster)),
1235 NewField(fieldNewsArtDate, art.Date),
1236 NewField(fieldNewsArtPrevArt, art.PrevArt),
1237 NewField(fieldNewsArtNextArt, art.NextArt),
1238 NewField(fieldNewsArtParentArt, art.ParentArt),
1239 NewField(fieldNewsArt1stChildArt, art.FirstChildArt),
1240 NewField(fieldNewsArtDataFlav, []byte("text/plain")),
1241 NewField(fieldNewsArtData, []byte(art.Data)),
1242 ))
1243 return res, err
1244 }
1245
1246 func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1247 // Has multiple access flags: News Delete Folder (37) or News Delete Category (35)
1248 // TODO: Implement
1249
1250 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1251
1252 // TODO: determine if path is a Folder (Bundle) or Category and check for permission
1253
1254 cc.logger.Infof("DelNewsItem %v", pathStrs)
1255
1256 cats := cc.Server.ThreadedNews.Categories
1257
1258 delName := pathStrs[len(pathStrs)-1]
1259 if len(pathStrs) > 1 {
1260 for _, fp := range pathStrs[0 : len(pathStrs)-1] {
1261 cats = cats[fp].SubCats
1262 }
1263 }
1264
1265 delete(cats, delName)
1266
1267 err = cc.Server.writeThreadedNews()
1268 if err != nil {
1269 return res, err
1270 }
1271
1272 // Reply params: none
1273 res = append(res, cc.NewReply(t))
1274
1275 return res, err
1276 }
1277
1278 func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1279 if !authorize(cc.Account.Access, accessNewsDeleteArt) {
1280 res = append(res, cc.NewErrReply(t, "You are not allowed to delete news articles."))
1281 return res, err
1282 }
1283
1284 // Request Fields
1285 // 325 News path
1286 // 326 News article ID
1287 // 337 News article – recursive delete Delete child articles (1) or not (0)
1288 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1289 ID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1290
1291 // TODO: Delete recursive
1292 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1293
1294 catName := pathStrs[len(pathStrs)-1]
1295 cat := cats[catName]
1296
1297 delete(cat.Articles, uint32(ID))
1298
1299 cats[catName] = cat
1300 if err := cc.Server.writeThreadedNews(); err != nil {
1301 return res, err
1302 }
1303
1304 res = append(res, cc.NewReply(t))
1305 return res, err
1306 }
1307
1308 // Request fields
1309 // 325 News path
1310 // 326 News article ID ID of the parent article?
1311 // 328 News article title
1312 // 334 News article flags
1313 // 327 News article data flavor Currently “text/plain”
1314 // 333 News article data
1315 func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1316 if !authorize(cc.Account.Access, accessNewsPostArt) {
1317 res = append(res, cc.NewErrReply(t, "You are not allowed to post news articles."))
1318 return res, err
1319 }
1320
1321 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1322 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1323
1324 catName := pathStrs[len(pathStrs)-1]
1325 cat := cats[catName]
1326
1327 newArt := NewsArtData{
1328 Title: string(t.GetField(fieldNewsArtTitle).Data),
1329 Poster: string(cc.UserName),
1330 Date: toHotlineTime(time.Now()),
1331 PrevArt: []byte{0, 0, 0, 0},
1332 NextArt: []byte{0, 0, 0, 0},
1333 ParentArt: append([]byte{0, 0}, t.GetField(fieldNewsArtID).Data...),
1334 FirstChildArt: []byte{0, 0, 0, 0},
1335 DataFlav: []byte("text/plain"),
1336 Data: string(t.GetField(fieldNewsArtData).Data),
1337 }
1338
1339 var keys []int
1340 for k := range cat.Articles {
1341 keys = append(keys, int(k))
1342 }
1343
1344 nextID := uint32(1)
1345 if len(keys) > 0 {
1346 sort.Ints(keys)
1347 prevID := uint32(keys[len(keys)-1])
1348 nextID = prevID + 1
1349
1350 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1351
1352 // Set next article ID
1353 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1354 }
1355
1356 // Update parent article with first child reply
1357 parentID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1358 if parentID != 0 {
1359 parentArt := cat.Articles[uint32(parentID)]
1360
1361 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1362 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1363 }
1364 }
1365
1366 cat.Articles[nextID] = &newArt
1367
1368 cats[catName] = cat
1369 if err := cc.Server.writeThreadedNews(); err != nil {
1370 return res, err
1371 }
1372
1373 res = append(res, cc.NewReply(t))
1374 return res, err
1375 }
1376
1377 // HandleGetMsgs returns the flat news data
1378 func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1379 if !authorize(cc.Account.Access, accessNewsReadArt) {
1380 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1381 return res, err
1382 }
1383
1384 res = append(res, cc.NewReply(t, NewField(fieldData, cc.Server.FlatNews)))
1385
1386 return res, err
1387 }
1388
1389 func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1390 if !authorize(cc.Account.Access, accessDownloadFile) {
1391 res = append(res, cc.NewErrReply(t, "You are not allowed to download files."))
1392 return res, err
1393 }
1394
1395 fileName := t.GetField(fieldFileName).Data
1396 filePath := t.GetField(fieldFilePath).Data
1397 resumeData := t.GetField(fieldFileResumeData).Data
1398
1399 var dataOffset int64
1400 var frd FileResumeData
1401 if resumeData != nil {
1402 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1403 return res, err
1404 }
1405 // TODO: handle rsrc fork offset
1406 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1407 }
1408
1409 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1410 if err != nil {
1411 return res, err
1412 }
1413
1414 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, dataOffset)
1415 if err != nil {
1416 return res, err
1417 }
1418
1419 xferSize := hlFile.ffo.TransferSize(0)
1420
1421 ft := cc.newFileTransfer(FileDownload, fileName, filePath, xferSize)
1422
1423 // TODO: refactor to remove this
1424 if resumeData != nil {
1425 var frd FileResumeData
1426 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1427 return res, err
1428 }
1429 ft.fileResumeData = &frd
1430 }
1431
1432 // Optional field for when a HL v1.5+ client requests file preview
1433 // Used only for TEXT, JPEG, GIFF, BMP or PICT files
1434 // The value will always be 2
1435 if t.GetField(fieldFileTransferOptions).Data != nil {
1436 ft.options = t.GetField(fieldFileTransferOptions).Data
1437 xferSize = hlFile.ffo.FlatFileDataForkHeader.DataSize[:]
1438 }
1439
1440 res = append(res, cc.NewReply(t,
1441 NewField(fieldRefNum, ft.refNum[:]),
1442 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1443 NewField(fieldTransferSize, xferSize),
1444 NewField(fieldFileSize, hlFile.ffo.FlatFileDataForkHeader.DataSize[:]),
1445 ))
1446
1447 return res, err
1448 }
1449
1450 // Download all files from the specified folder and sub-folders
1451 func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1452 if !authorize(cc.Account.Access, accessDownloadFile) {
1453 res = append(res, cc.NewErrReply(t, "You are not allowed to download folders."))
1454 return res, err
1455 }
1456
1457 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
1458 if err != nil {
1459 return res, err
1460 }
1461
1462 transferSize, err := CalcTotalSize(fullFilePath)
1463 if err != nil {
1464 return res, err
1465 }
1466 itemCount, err := CalcItemCount(fullFilePath)
1467 if err != nil {
1468 return res, err
1469 }
1470
1471 fileTransfer := cc.newFileTransfer(FolderDownload, t.GetField(fieldFileName).Data, t.GetField(fieldFilePath).Data, transferSize)
1472
1473 var fp FilePath
1474 err = fp.UnmarshalBinary(t.GetField(fieldFilePath).Data)
1475 if err != nil {
1476 return res, err
1477 }
1478
1479 res = append(res, cc.NewReply(t,
1480 NewField(fieldRefNum, fileTransfer.ReferenceNumber),
1481 NewField(fieldTransferSize, transferSize),
1482 NewField(fieldFolderItemCount, itemCount),
1483 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1484 ))
1485 return res, err
1486 }
1487
1488 // Upload all files from the local folder and its subfolders to the specified path on the server
1489 // Fields used in the request
1490 // 201 File name
1491 // 202 File path
1492 // 108 transfer size Total size of all items in the folder
1493 // 220 Folder item count
1494 // 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1495 func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1496 var fp FilePath
1497 if t.GetField(fieldFilePath).Data != nil {
1498 if err = fp.UnmarshalBinary(t.GetField(fieldFilePath).Data); err != nil {
1499 return res, err
1500 }
1501 }
1502
1503 // Handle special cases for Upload and Drop Box folders
1504 if !authorize(cc.Account.Access, accessUploadAnywhere) {
1505 if !fp.IsUploadDir() && !fp.IsDropbox() {
1506 res = append(res, cc.NewErrReply(t, fmt.Sprintf("Cannot accept upload of the folder \"%v\" because you are only allowed to upload to the \"Uploads\" folder.", string(t.GetField(fieldFileName).Data))))
1507 return res, err
1508 }
1509 }
1510
1511 fileTransfer := cc.newFileTransfer(FolderUpload,
1512 t.GetField(fieldFileName).Data,
1513 t.GetField(fieldFilePath).Data,
1514 t.GetField(fieldTransferSize).Data,
1515 )
1516
1517 fileTransfer.FolderItemCount = t.GetField(fieldFolderItemCount).Data
1518
1519 res = append(res, cc.NewReply(t, NewField(fieldRefNum, fileTransfer.ReferenceNumber)))
1520 return res, err
1521 }
1522
1523 // HandleUploadFile
1524 // Fields used in the request:
1525 // 201 File name
1526 // 202 File path
1527 // 204 File transfer options "Optional
1528 // Used only to resume download, currently has value 2"
1529 // 108 File transfer size "Optional used if download is not resumed"
1530 func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1531 if !authorize(cc.Account.Access, accessUploadFile) {
1532 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1533 return res, err
1534 }
1535
1536 fileName := t.GetField(fieldFileName).Data
1537 filePath := t.GetField(fieldFilePath).Data
1538 transferOptions := t.GetField(fieldFileTransferOptions).Data
1539 transferSize := t.GetField(fieldTransferSize).Data // not sent for resume
1540
1541 var fp FilePath
1542 if filePath != nil {
1543 if err = fp.UnmarshalBinary(filePath); err != nil {
1544 return res, err
1545 }
1546 }
1547
1548 // Handle special cases for Upload and Drop Box folders
1549 if !authorize(cc.Account.Access, accessUploadAnywhere) {
1550 if !fp.IsUploadDir() && !fp.IsDropbox() {
1551 res = append(res, cc.NewErrReply(t, fmt.Sprintf("Cannot accept upload of the file \"%v\" because you are only allowed to upload to the \"Uploads\" folder.", string(fileName))))
1552 return res, err
1553 }
1554 }
1555 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1556 if err != nil {
1557 return res, err
1558 }
1559
1560 if _, err := cc.Server.FS.Stat(fullFilePath); err == nil {
1561 res = append(res, cc.NewErrReply(t, fmt.Sprintf("Cannot accept upload because there is already a file named \"%v\". Try choosing a different name.", string(fileName))))
1562 return res, err
1563 }
1564
1565 ft := cc.newFileTransfer(FileUpload, fileName, filePath, transferSize)
1566
1567 replyT := cc.NewReply(t, NewField(fieldRefNum, ft.ReferenceNumber))
1568
1569 // client has requested to resume a partially transferred file
1570 if transferOptions != nil {
1571
1572 fileInfo, err := cc.Server.FS.Stat(fullFilePath + incompleteFileSuffix)
1573 if err != nil {
1574 return res, err
1575 }
1576
1577 offset := make([]byte, 4)
1578 binary.BigEndian.PutUint32(offset, uint32(fileInfo.Size()))
1579
1580 fileResumeData := NewFileResumeData([]ForkInfoList{
1581 *NewForkInfoList(offset),
1582 })
1583
1584 b, _ := fileResumeData.BinaryMarshal()
1585
1586 ft.TransferSize = offset
1587
1588 replyT.Fields = append(replyT.Fields, NewField(fieldFileResumeData, b))
1589 }
1590
1591 res = append(res, replyT)
1592 return res, err
1593 }
1594
1595 func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1596 if len(t.GetField(fieldUserIconID).Data) == 4 {
1597 cc.Icon = t.GetField(fieldUserIconID).Data[2:]
1598 } else {
1599 cc.Icon = t.GetField(fieldUserIconID).Data
1600 }
1601 if cc.Authorize(accessAnyName) {
1602 cc.UserName = t.GetField(fieldUserName).Data
1603 }
1604
1605 // the options field is only passed by the client versions > 1.2.3.
1606 options := t.GetField(fieldOptions).Data
1607 if options != nil {
1608 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1609 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
1610
1611 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, optBitmap.Bit(refusePM))
1612 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1613
1614 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, optBitmap.Bit(refuseChat))
1615 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
1616
1617 // Check auto response
1618 if optBitmap.Bit(autoResponse) == 1 {
1619 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
1620 } else {
1621 cc.AutoReply = []byte{}
1622 }
1623 }
1624
1625 for _, c := range sortedClients(cc.Server.Clients) {
1626 res = append(res, *NewTransaction(
1627 tranNotifyChangeUser,
1628 c.ID,
1629 NewField(fieldUserID, *cc.ID),
1630 NewField(fieldUserIconID, cc.Icon),
1631 NewField(fieldUserFlags, cc.Flags),
1632 NewField(fieldUserName, cc.UserName),
1633 ))
1634 }
1635
1636 return res, err
1637 }
1638
1639 // HandleKeepAlive responds to keepalive transactions with an empty reply
1640 // * HL 1.9.2 Client sends keepalive msg every 3 minutes
1641 // * HL 1.2.3 Client doesn't send keepalives
1642 func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1643 res = append(res, cc.NewReply(t))
1644
1645 return res, err
1646 }
1647
1648 func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1649 fullPath, err := readPath(
1650 cc.Server.Config.FileRoot,
1651 t.GetField(fieldFilePath).Data,
1652 nil,
1653 )
1654 if err != nil {
1655 return res, err
1656 }
1657
1658 var fp FilePath
1659 if t.GetField(fieldFilePath).Data != nil {
1660 if err = fp.UnmarshalBinary(t.GetField(fieldFilePath).Data); err != nil {
1661 return res, err
1662 }
1663 }
1664
1665 // Handle special case for drop box folders
1666 if fp.IsDropbox() && !authorize(cc.Account.Access, accessViewDropBoxes) {
1667 res = append(res, cc.NewErrReply(t, "You are not allowed to view drop boxes."))
1668 return res, err
1669 }
1670
1671 fileNames, err := getFileNameList(fullPath)
1672 if err != nil {
1673 return res, err
1674 }
1675
1676 res = append(res, cc.NewReply(t, fileNames...))
1677
1678 return res, err
1679 }
1680
1681 // =================================
1682 // Hotline private chat flow
1683 // =================================
1684 // 1. ClientA sends tranInviteNewChat to server with user ID to invite
1685 // 2. Server creates new ChatID
1686 // 3. Server sends tranInviteToChat to invitee
1687 // 4. Server replies to ClientA with new Chat ID
1688 //
1689 // A dialog box pops up in the invitee client with options to accept or decline the invitation.
1690 // If Accepted is clicked:
1691 // 1. ClientB sends tranJoinChat with fieldChatID
1692
1693 // HandleInviteNewChat invites users to new private chat
1694 func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1695 if !authorize(cc.Account.Access, accessOpenChat) {
1696 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1697 return res, err
1698 }
1699
1700 // Client to Invite
1701 targetID := t.GetField(fieldUserID).Data
1702 newChatID := cc.Server.NewPrivateChat(cc)
1703
1704 res = append(res,
1705 *NewTransaction(
1706 tranInviteToChat,
1707 &targetID,
1708 NewField(fieldChatID, newChatID),
1709 NewField(fieldUserName, cc.UserName),
1710 NewField(fieldUserID, *cc.ID),
1711 ),
1712 )
1713
1714 res = append(res,
1715 cc.NewReply(t,
1716 NewField(fieldChatID, newChatID),
1717 NewField(fieldUserName, cc.UserName),
1718 NewField(fieldUserID, *cc.ID),
1719 NewField(fieldUserIconID, cc.Icon),
1720 NewField(fieldUserFlags, cc.Flags),
1721 ),
1722 )
1723
1724 return res, err
1725 }
1726
1727 func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1728 if !authorize(cc.Account.Access, accessOpenChat) {
1729 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1730 return res, err
1731 }
1732
1733 // Client to Invite
1734 targetID := t.GetField(fieldUserID).Data
1735 chatID := t.GetField(fieldChatID).Data
1736
1737 res = append(res,
1738 *NewTransaction(
1739 tranInviteToChat,
1740 &targetID,
1741 NewField(fieldChatID, chatID),
1742 NewField(fieldUserName, cc.UserName),
1743 NewField(fieldUserID, *cc.ID),
1744 ),
1745 )
1746 res = append(res,
1747 cc.NewReply(
1748 t,
1749 NewField(fieldChatID, chatID),
1750 NewField(fieldUserName, cc.UserName),
1751 NewField(fieldUserID, *cc.ID),
1752 NewField(fieldUserIconID, cc.Icon),
1753 NewField(fieldUserFlags, cc.Flags),
1754 ),
1755 )
1756
1757 return res, err
1758 }
1759
1760 func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1761 chatID := t.GetField(fieldChatID).Data
1762 chatInt := binary.BigEndian.Uint32(chatID)
1763
1764 privChat := cc.Server.PrivateChats[chatInt]
1765
1766 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
1767
1768 for _, c := range sortedClients(privChat.ClientConn) {
1769 res = append(res,
1770 *NewTransaction(
1771 tranChatMsg,
1772 c.ID,
1773 NewField(fieldChatID, chatID),
1774 NewField(fieldData, resMsg),
1775 ),
1776 )
1777 }
1778
1779 return res, err
1780 }
1781
1782 // HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1783 // Fields used in the reply:
1784 // * 115 Chat subject
1785 // * 300 User name with info (Optional)
1786 // * 300 (more user names with info)
1787 func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1788 chatID := t.GetField(fieldChatID).Data
1789 chatInt := binary.BigEndian.Uint32(chatID)
1790
1791 privChat := cc.Server.PrivateChats[chatInt]
1792
1793 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1794 for _, c := range sortedClients(privChat.ClientConn) {
1795 res = append(res,
1796 *NewTransaction(
1797 tranNotifyChatChangeUser,
1798 c.ID,
1799 NewField(fieldChatID, chatID),
1800 NewField(fieldUserName, cc.UserName),
1801 NewField(fieldUserID, *cc.ID),
1802 NewField(fieldUserIconID, cc.Icon),
1803 NewField(fieldUserFlags, cc.Flags),
1804 ),
1805 )
1806 }
1807
1808 privChat.ClientConn[cc.uint16ID()] = cc
1809
1810 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1811 for _, c := range sortedClients(privChat.ClientConn) {
1812 user := User{
1813 ID: *c.ID,
1814 Icon: c.Icon,
1815 Flags: c.Flags,
1816 Name: string(c.UserName),
1817 }
1818
1819 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1820 }
1821
1822 res = append(res, cc.NewReply(t, replyFields...))
1823 return res, err
1824 }
1825
1826 // HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1827 // Fields used in the request:
1828 // * 114 fieldChatID
1829 // Reply is not expected.
1830 func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1831 chatID := t.GetField(fieldChatID).Data
1832 chatInt := binary.BigEndian.Uint32(chatID)
1833
1834 privChat, ok := cc.Server.PrivateChats[chatInt]
1835 if !ok {
1836 return res, nil
1837 }
1838
1839 delete(privChat.ClientConn, cc.uint16ID())
1840
1841 // Notify members of the private chat that the user has left
1842 for _, c := range sortedClients(privChat.ClientConn) {
1843 res = append(res,
1844 *NewTransaction(
1845 tranNotifyChatDeleteUser,
1846 c.ID,
1847 NewField(fieldChatID, chatID),
1848 NewField(fieldUserID, *cc.ID),
1849 ),
1850 )
1851 }
1852
1853 return res, err
1854 }
1855
1856 // HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1857 // Fields used in the request:
1858 // * 114 Chat ID
1859 // * 115 Chat subject Chat subject string
1860 // Reply is not expected.
1861 func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1862 chatID := t.GetField(fieldChatID).Data
1863 chatInt := binary.BigEndian.Uint32(chatID)
1864
1865 privChat := cc.Server.PrivateChats[chatInt]
1866 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1867
1868 for _, c := range sortedClients(privChat.ClientConn) {
1869 res = append(res,
1870 *NewTransaction(
1871 tranNotifyChatSubject,
1872 c.ID,
1873 NewField(fieldChatID, chatID),
1874 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),
1875 ),
1876 )
1877 }
1878
1879 return res, err
1880 }
1881
1882 // HandleMakeAlias makes a filer alias using the specified path.
1883 // Fields used in the request:
1884 // 201 File name
1885 // 202 File path
1886 // 212 File new path Destination path
1887 //
1888 // Fields used in the reply:
1889 // None
1890 func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1891 if !authorize(cc.Account.Access, accessMakeAlias) {
1892 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
1893 return res, err
1894 }
1895 fileName := t.GetField(fieldFileName).Data
1896 filePath := t.GetField(fieldFilePath).Data
1897 fileNewPath := t.GetField(fieldFileNewPath).Data
1898
1899 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1900 if err != nil {
1901 return res, err
1902 }
1903
1904 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
1905 if err != nil {
1906 return res, err
1907 }
1908
1909 cc.logger.Debugw("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
1910
1911 if err := cc.Server.FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
1912 res = append(res, cc.NewErrReply(t, "Error creating alias"))
1913 return res, nil
1914 }
1915
1916 res = append(res, cc.NewReply(t))
1917 return res, err
1918 }
1919
1920 func HandleDownloadBanner(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1921 fi, err := cc.Server.FS.Stat(filepath.Join(cc.Server.ConfigDir, cc.Server.Config.BannerFile))
1922 if err != nil {
1923 return res, err
1924 }
1925
1926 ft := cc.newFileTransfer(bannerDownload, []byte{}, []byte{}, make([]byte, 4))
1927
1928 binary.BigEndian.PutUint32(ft.TransferSize, uint32(fi.Size()))
1929
1930 res = append(res, cc.NewReply(t,
1931 NewField(fieldRefNum, ft.refNum[:]),
1932 NewField(fieldTransferSize, ft.TransferSize),
1933 ))
1934
1935 return res, err
1936 }