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