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