]> git.r.bdr.sh - rbdr/mobius/blame - hotline/transaction_handlers.go
patch: v0.10.15
[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
993const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
994// "Mon, 02 Jan 2006 15:04:05 MST"
995
996const defaultNewsTemplate = `From %s (%s):
997
998%s
999
1000__________________________________________________________`
1001
1002// HandleTranOldPostNews updates the flat news
1003// Fields used in this request:
1004// 101 Data
1005func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
187d6dc5 1006 if !cc.Authorize(accessNewsPostArt) {
d4c152a4
JH
1007 res = append(res, cc.NewErrReply(t, "You are not allowed to post news."))
1008 return res, err
1009 }
1010
6988a057
JH
1011 cc.Server.flatNewsMux.Lock()
1012 defer cc.Server.flatNewsMux.Unlock()
1013
1014 newsDateTemplate := defaultNewsDateFormat
1015 if cc.Server.Config.NewsDateFormat != "" {
1016 newsDateTemplate = cc.Server.Config.NewsDateFormat
1017 }
1018
1019 newsTemplate := defaultNewsTemplate
1020 if cc.Server.Config.NewsDelimiter != "" {
1021 newsTemplate = cc.Server.Config.NewsDelimiter
1022 }
1023
72dd37f1 1024 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
6988a057
JH
1025 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
1026
4d64a5b9
JH
1027 // update news in memory
1028 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
1029
6988a057 1030 // update news on disk
8a1512f9 1031 if err := cc.Server.FS.WriteFile(filepath.Join(cc.Server.ConfigDir, "MessageBoard.txt"), cc.Server.FlatNews, 0644); err != nil {
6988a057
JH
1032 return res, err
1033 }
1034
1035 // Notify all clients of updated news
1036 cc.sendAll(
1037 tranNewMsg,
1038 NewField(fieldData, []byte(newsPost)),
1039 )
1040
1041 res = append(res, cc.NewReply(t))
1042 return res, err
1043}
1044
1045func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
187d6dc5 1046 if !cc.Authorize(accessDisconUser) {
d4c152a4
JH
1047 res = append(res, cc.NewErrReply(t, "You are not allowed to disconnect users."))
1048 return res, err
1049 }
1050
6988a057
JH
1051 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
1052
187d6dc5 1053 if clientConn.Authorize(accessCannotBeDiscon) {
6988a057
JH
1054 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
1055 return res, err
1056 }
1057
46862572
JH
1058 // If fieldOptions is set, then the client IP is banned in addition to disconnected.
1059 // 00 01 = temporary ban
1060 // 00 02 = permanent ban
1061 if t.GetField(fieldOptions).Data != nil {
1062 switch t.GetField(fieldOptions).Data[1] {
1063 case 1:
1064 // send message: "You are temporarily banned on this server"
1065 cc.logger.Infow("Disconnect & temporarily ban " + string(clientConn.UserName))
1066
1067 res = append(res, *NewTransaction(
1068 tranServerMsg,
1069 clientConn.ID,
1070 NewField(fieldData, []byte("You are temporarily banned on this server")),
1071 NewField(fieldChatOptions, []byte{0, 0}),
1072 ))
1073
1074 banUntil := time.Now().Add(tempBanDuration)
1075 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = &banUntil
1076 cc.Server.writeBanList()
1077 case 2:
1078 // send message: "You are permanently banned on this server"
1079 cc.logger.Infow("Disconnect & ban " + string(clientConn.UserName))
1080
1081 res = append(res, *NewTransaction(
1082 tranServerMsg,
1083 clientConn.ID,
1084 NewField(fieldData, []byte("You are permanently banned on this server")),
1085 NewField(fieldChatOptions, []byte{0, 0}),
1086 ))
1087
1088 cc.Server.banList[strings.Split(clientConn.RemoteAddr, ":")[0]] = nil
1089 cc.Server.writeBanList()
1090 }
6988a057
JH
1091 }
1092
46862572
JH
1093 // TODO: remove this awful hack
1094 go func() {
1095 time.Sleep(1 * time.Second)
1096 clientConn.Disconnect()
1097 }()
1098
1099 return append(res, cc.NewReply(t)), err
6988a057
JH
1100}
1101
d4c152a4
JH
1102// HandleGetNewsCatNameList returns a list of news categories for a path
1103// Fields used in the request:
1104// 325 News path (Optional)
6988a057 1105func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
187d6dc5 1106 if !cc.Authorize(accessNewsReadArt) {
d4c152a4
JH
1107 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1108 return res, err
1109 }
6988a057 1110
6988a057
JH
1111 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1112 cats := cc.Server.GetNewsCatByPath(pathStrs)
1113
1114 // To store the keys in slice in sorted order
1115 keys := make([]string, len(cats))
1116 i := 0
1117 for k := range cats {
1118 keys[i] = k
1119 i++
1120 }
1121 sort.Strings(keys)
1122
1123 var fieldData []Field
1124 for _, k := range keys {
1125 cat := cats[k]
72dd37f1 1126 b, _ := cat.MarshalBinary()
6988a057
JH
1127 fieldData = append(fieldData, NewField(
1128 fieldNewsCatListData15,
72dd37f1 1129 b,
6988a057
JH
1130 ))
1131 }
1132
1133 res = append(res, cc.NewReply(t, fieldData...))
1134 return res, err
1135}
1136
1137func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
187d6dc5 1138 if !cc.Authorize(accessNewsCreateCat) {
d4c152a4
JH
1139 res = append(res, cc.NewErrReply(t, "You are not allowed to create news categories."))
1140 return res, err
1141 }
1142
6988a057
JH
1143 name := string(t.GetField(fieldNewsCatName).Data)
1144 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1145
1146 cats := cc.Server.GetNewsCatByPath(pathStrs)
1147 cats[name] = NewsCategoryListData15{
1148 Name: name,
1149 Type: []byte{0, 3},
1150 Articles: map[uint32]*NewsArtData{},
1151 SubCats: make(map[string]NewsCategoryListData15),
1152 }
1153
1154 if err := cc.Server.writeThreadedNews(); err != nil {
1155 return res, err
1156 }
1157 res = append(res, cc.NewReply(t))
1158 return res, err
1159}
1160
d4c152a4
JH
1161// Fields used in the request:
1162// 322 News category name
1163// 325 News path
6988a057 1164func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
187d6dc5 1165 if !cc.Authorize(accessNewsCreateFldr) {
d4c152a4
JH
1166 res = append(res, cc.NewErrReply(t, "You are not allowed to create news folders."))
1167 return res, err
1168 }
1169
6988a057
JH
1170 name := string(t.GetField(fieldFileName).Data)
1171 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1172
67db911d 1173 cc.logger.Infof("Creating new news folder %s", name)
6988a057
JH
1174
1175 cats := cc.Server.GetNewsCatByPath(pathStrs)
1176 cats[name] = NewsCategoryListData15{
1177 Name: name,
1178 Type: []byte{0, 2},
1179 Articles: map[uint32]*NewsArtData{},
1180 SubCats: make(map[string]NewsCategoryListData15),
1181 }
1182 if err := cc.Server.writeThreadedNews(); err != nil {
1183 return res, err
1184 }
1185 res = append(res, cc.NewReply(t))
1186 return res, err
1187}
1188
33265393
JH
1189// HandleGetNewsArtData gets the list of article names at the specified news path.
1190
6988a057
JH
1191// Fields used in the request:
1192// 325 News path Optional
33265393
JH
1193
1194// Fields used in the reply:
6988a057
JH
1195// 321 News article list data Optional
1196func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
187d6dc5 1197 if !cc.Authorize(accessNewsReadArt) {
d4c152a4
JH
1198 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1199 return res, err
1200 }
6988a057
JH
1201 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1202
1203 var cat NewsCategoryListData15
1204 cats := cc.Server.ThreadedNews.Categories
1205
003a743e
JH
1206 for _, fp := range pathStrs {
1207 cat = cats[fp]
1208 cats = cats[fp].SubCats
6988a057
JH
1209 }
1210
1211 nald := cat.GetNewsArtListData()
1212
1213 res = append(res, cc.NewReply(t, NewField(fieldNewsArtListData, nald.Payload())))
1214 return res, err
1215}
1216
33265393
JH
1217// HandleGetNewsArtData requests information about the specific news article.
1218// Fields used in the request:
1219//
1220// Request fields
1221// 325 News path
1222// 326 News article ID
1223// 327 News article data flavor
1224//
1225// Fields used in the reply:
1226// 328 News article title
1227// 329 News article poster
1228// 330 News article date
1229// 331 Previous article ID
1230// 332 Next article ID
1231// 335 Parent article ID
1232// 336 First child article ID
1233// 327 News article data flavor "Should be “text/plain”
1234// 333 News article data Optional (if data flavor is “text/plain”)
6988a057 1235func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
187d6dc5 1236 if !cc.Authorize(accessNewsReadArt) {
d4c152a4
JH
1237 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1238 return res, err
1239 }
1240
6988a057
JH
1241 var cat NewsCategoryListData15
1242 cats := cc.Server.ThreadedNews.Categories
1243
33265393 1244 for _, fp := range ReadNewsPath(t.GetField(fieldNewsPath).Data) {
003a743e
JH
1245 cat = cats[fp]
1246 cats = cats[fp].SubCats
6988a057 1247 }
6988a057 1248
33265393
JH
1249 // The official Hotline clients will send the article ID as 2 bytes if possible, but
1250 // some third party clients such as Frogblast and Heildrun will always send 4 bytes
1251 convertedID, err := byteToInt(t.GetField(fieldNewsArtID).Data)
1252 if err != nil {
1253 return res, err
1254 }
6988a057 1255
33265393 1256 art := cat.Articles[uint32(convertedID)]
6988a057
JH
1257 if art == nil {
1258 res = append(res, cc.NewReply(t))
1259 return res, err
1260 }
1261
6988a057
JH
1262 res = append(res, cc.NewReply(t,
1263 NewField(fieldNewsArtTitle, []byte(art.Title)),
1264 NewField(fieldNewsArtPoster, []byte(art.Poster)),
1265 NewField(fieldNewsArtDate, art.Date),
1266 NewField(fieldNewsArtPrevArt, art.PrevArt),
1267 NewField(fieldNewsArtNextArt, art.NextArt),
1268 NewField(fieldNewsArtParentArt, art.ParentArt),
1269 NewField(fieldNewsArt1stChildArt, art.FirstChildArt),
1270 NewField(fieldNewsArtDataFlav, []byte("text/plain")),
1271 NewField(fieldNewsArtData, []byte(art.Data)),
1272 ))
1273 return res, err
1274}
1275
8eb43f95
JH
1276// HandleDelNewsItem deletes an existing threaded news folder or category from the server.
1277// Fields used in the request:
1278// 325 News path
1279// Fields used in the reply:
1280// None
6988a057 1281func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
6988a057
JH
1282 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1283
6988a057 1284 cats := cc.Server.ThreadedNews.Categories
6988a057
JH
1285 delName := pathStrs[len(pathStrs)-1]
1286 if len(pathStrs) > 1 {
7e2e07da
JH
1287 for _, fp := range pathStrs[0 : len(pathStrs)-1] {
1288 cats = cats[fp].SubCats
6988a057
JH
1289 }
1290 }
1291
043c00da 1292 if bytes.Equal(cats[delName].Type, []byte{0, 3}) {
8eb43f95
JH
1293 if !cc.Authorize(accessNewsDeleteCat) {
1294 return append(res, cc.NewErrReply(t, "You are not allowed to delete news categories.")), nil
1295 }
1296 } else {
1297 if !cc.Authorize(accessNewsDeleteFldr) {
1298 return append(res, cc.NewErrReply(t, "You are not allowed to delete news folders.")), nil
1299 }
1300 }
1301
6988a057
JH
1302 delete(cats, delName)
1303
8eb43f95 1304 if err := cc.Server.writeThreadedNews(); err != nil {
6988a057
JH
1305 return res, err
1306 }
1307
8eb43f95 1308 return append(res, cc.NewReply(t)), nil
6988a057
JH
1309}
1310
1311func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
187d6dc5 1312 if !cc.Authorize(accessNewsDeleteArt) {
d4c152a4
JH
1313 res = append(res, cc.NewErrReply(t, "You are not allowed to delete news articles."))
1314 return res, err
1315 }
1316
6988a057
JH
1317 // Request Fields
1318 // 325 News path
1319 // 326 News article ID
1320 // 337 News article – recursive delete Delete child articles (1) or not (0)
1321 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
5890e1d2
JH
1322 ID, err := byteToInt(t.GetField(fieldNewsArtID).Data)
1323 if err != nil {
1324 return res, err
1325 }
6988a057
JH
1326
1327 // TODO: Delete recursive
1328 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1329
1330 catName := pathStrs[len(pathStrs)-1]
1331 cat := cats[catName]
1332
1333 delete(cat.Articles, uint32(ID))
1334
1335 cats[catName] = cat
1336 if err := cc.Server.writeThreadedNews(); err != nil {
1337 return res, err
1338 }
1339
1340 res = append(res, cc.NewReply(t))
1341 return res, err
1342}
1343
d4c152a4
JH
1344// Request fields
1345// 325 News path
1346// 326 News article ID ID of the parent article?
1347// 328 News article title
1348// 334 News article flags
1349// 327 News article data flavor Currently “text/plain”
1350// 333 News article data
6988a057 1351func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
187d6dc5 1352 if !cc.Authorize(accessNewsPostArt) {
d4c152a4
JH
1353 res = append(res, cc.NewErrReply(t, "You are not allowed to post news articles."))
1354 return res, err
1355 }
6988a057
JH
1356
1357 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1358 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1359
1360 catName := pathStrs[len(pathStrs)-1]
1361 cat := cats[catName]
1362
5890e1d2
JH
1363 artID, err := byteToInt(t.GetField(fieldNewsArtID).Data)
1364 if err != nil {
1365 return res, err
1366 }
1367 convertedArtID := uint32(artID)
1368 bs := make([]byte, 4)
1369 binary.LittleEndian.PutUint32(bs, convertedArtID)
1370
6988a057
JH
1371 newArt := NewsArtData{
1372 Title: string(t.GetField(fieldNewsArtTitle).Data),
72dd37f1 1373 Poster: string(cc.UserName),
3c9b1dcd 1374 Date: toHotlineTime(time.Now()),
6988a057
JH
1375 PrevArt: []byte{0, 0, 0, 0},
1376 NextArt: []byte{0, 0, 0, 0},
5890e1d2 1377 ParentArt: bs,
6988a057
JH
1378 FirstChildArt: []byte{0, 0, 0, 0},
1379 DataFlav: []byte("text/plain"),
1380 Data: string(t.GetField(fieldNewsArtData).Data),
1381 }
1382
1383 var keys []int
1384 for k := range cat.Articles {
1385 keys = append(keys, int(k))
1386 }
1387
1388 nextID := uint32(1)
1389 if len(keys) > 0 {
1390 sort.Ints(keys)
1391 prevID := uint32(keys[len(keys)-1])
1392 nextID = prevID + 1
1393
1394 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1395
1396 // Set next article ID
1397 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1398 }
1399
1400 // Update parent article with first child reply
5890e1d2 1401 parentID := convertedArtID
6988a057 1402 if parentID != 0 {
5890e1d2 1403 parentArt := cat.Articles[parentID]
6988a057
JH
1404
1405 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1406 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1407 }
1408 }
1409
1410 cat.Articles[nextID] = &newArt
1411
1412 cats[catName] = cat
1413 if err := cc.Server.writeThreadedNews(); err != nil {
1414 return res, err
1415 }
1416
1417 res = append(res, cc.NewReply(t))
1418 return res, err
1419}
1420
1421// HandleGetMsgs returns the flat news data
1422func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
187d6dc5 1423 if !cc.Authorize(accessNewsReadArt) {
481631f6
JH
1424 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1425 return res, err
1426 }
1427
6988a057
JH
1428 res = append(res, cc.NewReply(t, NewField(fieldData, cc.Server.FlatNews)))
1429
1430 return res, err
1431}
1432
1433func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
187d6dc5 1434 if !cc.Authorize(accessDownloadFile) {
481631f6
JH
1435 res = append(res, cc.NewErrReply(t, "You are not allowed to download files."))
1436 return res, err
1437 }
1438
6988a057 1439 fileName := t.GetField(fieldFileName).Data
92a7e455 1440 filePath := t.GetField(fieldFilePath).Data
16a4ad70
JH
1441 resumeData := t.GetField(fieldFileResumeData).Data
1442
1443 var dataOffset int64
1444 var frd FileResumeData
1445 if resumeData != nil {
1446 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1447 return res, err
1448 }
7cd900d6 1449 // TODO: handle rsrc fork offset
16a4ad70
JH
1450 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1451 }
1452
7cd900d6 1453 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
92a7e455
JH
1454 if err != nil {
1455 return res, err
1456 }
1457
7cd900d6 1458 hlFile, err := newFileWrapper(cc.Server.FS, fullFilePath, dataOffset)
6988a057
JH
1459 if err != nil {
1460 return res, err
1461 }
1462
df1ade54 1463 xferSize := hlFile.ffo.TransferSize(0)
6988a057 1464
df1ade54 1465 ft := cc.newFileTransfer(FileDownload, fileName, filePath, xferSize)
6988a057 1466
7cd900d6 1467 // TODO: refactor to remove this
16a4ad70
JH
1468 if resumeData != nil {
1469 var frd FileResumeData
d4c152a4
JH
1470 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1471 return res, err
1472 }
16a4ad70
JH
1473 ft.fileResumeData = &frd
1474 }
1475
d1cd6664
JH
1476 // Optional field for when a HL v1.5+ client requests file preview
1477 // Used only for TEXT, JPEG, GIFF, BMP or PICT files
1478 // The value will always be 2
1479 if t.GetField(fieldFileTransferOptions).Data != nil {
1480 ft.options = t.GetField(fieldFileTransferOptions).Data
7cd900d6 1481 xferSize = hlFile.ffo.FlatFileDataForkHeader.DataSize[:]
d1cd6664
JH
1482 }
1483
6988a057 1484 res = append(res, cc.NewReply(t,
df1ade54 1485 NewField(fieldRefNum, ft.refNum[:]),
6988a057 1486 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
d1cd6664 1487 NewField(fieldTransferSize, xferSize),
7cd900d6 1488 NewField(fieldFileSize, hlFile.ffo.FlatFileDataForkHeader.DataSize[:]),
6988a057
JH
1489 ))
1490
1491 return res, err
1492}
1493
1494// Download all files from the specified folder and sub-folders
6988a057 1495func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
187d6dc5 1496 if !cc.Authorize(accessDownloadFile) {
d4c152a4
JH
1497 res = append(res, cc.NewErrReply(t, "You are not allowed to download folders."))
1498 return res, err
1499 }
1500
92a7e455 1501 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
aebc4d36
JH
1502 if err != nil {
1503 return res, err
1504 }
92a7e455 1505
6988a057
JH
1506 transferSize, err := CalcTotalSize(fullFilePath)
1507 if err != nil {
1508 return res, err
1509 }
1510 itemCount, err := CalcItemCount(fullFilePath)
1511 if err != nil {
1512 return res, err
1513 }
df1ade54
JH
1514
1515 fileTransfer := cc.newFileTransfer(FolderDownload, t.GetField(fieldFileName).Data, t.GetField(fieldFilePath).Data, transferSize)
1516
1517 var fp FilePath
8fc43f8e 1518 _, err = fp.Write(t.GetField(fieldFilePath).Data)
df1ade54
JH
1519 if err != nil {
1520 return res, err
1521 }
1522
6988a057 1523 res = append(res, cc.NewReply(t,
df1ade54 1524 NewField(fieldRefNum, fileTransfer.ReferenceNumber),
6988a057
JH
1525 NewField(fieldTransferSize, transferSize),
1526 NewField(fieldFolderItemCount, itemCount),
1527 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1528 ))
1529 return res, err
1530}
1531
1532// Upload all files from the local folder and its subfolders to the specified path on the server
1533// Fields used in the request
1534// 201 File name
1535// 202 File path
df2735b2 1536// 108 transfer size Total size of all items in the folder
6988a057
JH
1537// 220 Folder item count
1538// 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1539func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
7e2e07da
JH
1540 var fp FilePath
1541 if t.GetField(fieldFilePath).Data != nil {
8fc43f8e 1542 if _, err = fp.Write(t.GetField(fieldFilePath).Data); err != nil {
7e2e07da
JH
1543 return res, err
1544 }
1545 }
1546
1547 // Handle special cases for Upload and Drop Box folders
187d6dc5 1548 if !cc.Authorize(accessUploadAnywhere) {
7e2e07da
JH
1549 if !fp.IsUploadDir() && !fp.IsDropbox() {
1550 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))))
1551 return res, err
1552 }
1553 }
1554
df1ade54
JH
1555 fileTransfer := cc.newFileTransfer(FolderUpload,
1556 t.GetField(fieldFileName).Data,
1557 t.GetField(fieldFilePath).Data,
1558 t.GetField(fieldTransferSize).Data,
1559 )
1560
1561 fileTransfer.FolderItemCount = t.GetField(fieldFolderItemCount).Data
6988a057 1562
df1ade54 1563 res = append(res, cc.NewReply(t, NewField(fieldRefNum, fileTransfer.ReferenceNumber)))
6988a057
JH
1564 return res, err
1565}
1566
7e2e07da 1567// HandleUploadFile
16a4ad70
JH
1568// Fields used in the request:
1569// 201 File name
1570// 202 File path
1571// 204 File transfer options "Optional
1572// Used only to resume download, currently has value 2"
1573// 108 File transfer size "Optional used if download is not resumed"
6988a057 1574func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
187d6dc5 1575 if !cc.Authorize(accessUploadFile) {
a0241c25
JH
1576 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1577 return res, err
1578 }
1579
6988a057
JH
1580 fileName := t.GetField(fieldFileName).Data
1581 filePath := t.GetField(fieldFilePath).Data
16a4ad70 1582 transferOptions := t.GetField(fieldFileTransferOptions).Data
df1ade54 1583 transferSize := t.GetField(fieldTransferSize).Data // not sent for resume
16a4ad70 1584
7e2e07da
JH
1585 var fp FilePath
1586 if filePath != nil {
8fc43f8e 1587 if _, err = fp.Write(filePath); err != nil {
7e2e07da
JH
1588 return res, err
1589 }
1590 }
1591
1592 // Handle special cases for Upload and Drop Box folders
187d6dc5 1593 if !cc.Authorize(accessUploadAnywhere) {
7e2e07da
JH
1594 if !fp.IsUploadDir() && !fp.IsDropbox() {
1595 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))))
1596 return res, err
1597 }
1598 }
df1ade54
JH
1599 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1600 if err != nil {
1601 return res, err
1602 }
7e2e07da 1603
df1ade54
JH
1604 if _, err := cc.Server.FS.Stat(fullFilePath); err == nil {
1605 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))))
1606 return res, err
6988a057
JH
1607 }
1608
df1ade54
JH
1609 ft := cc.newFileTransfer(FileUpload, fileName, filePath, transferSize)
1610
1611 replyT := cc.NewReply(t, NewField(fieldRefNum, ft.ReferenceNumber))
16a4ad70 1612
7cd900d6 1613 // client has requested to resume a partially transferred file
16a4ad70 1614 if transferOptions != nil {
16a4ad70 1615
b196a50a 1616 fileInfo, err := cc.Server.FS.Stat(fullFilePath + incompleteFileSuffix)
16a4ad70
JH
1617 if err != nil {
1618 return res, err
1619 }
1620
1621 offset := make([]byte, 4)
1622 binary.BigEndian.PutUint32(offset, uint32(fileInfo.Size()))
1623
1624 fileResumeData := NewFileResumeData([]ForkInfoList{
1625 *NewForkInfoList(offset),
1626 })
1627
1628 b, _ := fileResumeData.BinaryMarshal()
1629
df1ade54
JH
1630 ft.TransferSize = offset
1631
16a4ad70
JH
1632 replyT.Fields = append(replyT.Fields, NewField(fieldFileResumeData, b))
1633 }
1634
1635 res = append(res, replyT)
6988a057
JH
1636 return res, err
1637}
1638
6988a057 1639func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
6988a057 1640 if len(t.GetField(fieldUserIconID).Data) == 4 {
264b7c27 1641 cc.Icon = t.GetField(fieldUserIconID).Data[2:]
6988a057 1642 } else {
264b7c27
JH
1643 cc.Icon = t.GetField(fieldUserIconID).Data
1644 }
1645 if cc.Authorize(accessAnyName) {
1646 cc.UserName = t.GetField(fieldUserName).Data
6988a057 1647 }
6988a057
JH
1648
1649 // the options field is only passed by the client versions > 1.2.3.
1650 options := t.GetField(fieldOptions).Data
6988a057
JH
1651 if options != nil {
1652 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
a7216f67 1653 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(cc.Flags)))
6988a057 1654
7f12122f 1655 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, optBitmap.Bit(refusePM))
a7216f67 1656 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
6988a057 1657
7f12122f 1658 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, optBitmap.Bit(refuseChat))
a7216f67 1659 binary.BigEndian.PutUint16(cc.Flags, uint16(flagBitmap.Int64()))
6988a057
JH
1660
1661 // Check auto response
1662 if optBitmap.Bit(autoResponse) == 1 {
aebc4d36 1663 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
6988a057 1664 } else {
aebc4d36 1665 cc.AutoReply = []byte{}
6988a057
JH
1666 }
1667 }
1668
264b7c27
JH
1669 for _, c := range sortedClients(cc.Server.Clients) {
1670 res = append(res, *NewTransaction(
1671 tranNotifyChangeUser,
1672 c.ID,
1673 NewField(fieldUserID, *cc.ID),
1674 NewField(fieldUserIconID, cc.Icon),
1675 NewField(fieldUserFlags, cc.Flags),
1676 NewField(fieldUserName, cc.UserName),
1677 ))
1678 }
6988a057
JH
1679
1680 return res, err
1681}
1682
61c272e1
JH
1683// HandleKeepAlive responds to keepalive transactions with an empty reply
1684// * HL 1.9.2 Client sends keepalive msg every 3 minutes
1685// * HL 1.2.3 Client doesn't send keepalives
6988a057
JH
1686func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1687 res = append(res, cc.NewReply(t))
1688
1689 return res, err
1690}
1691
1692func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
92a7e455
JH
1693 fullPath, err := readPath(
1694 cc.Server.Config.FileRoot,
1695 t.GetField(fieldFilePath).Data,
1696 nil,
1697 )
1698 if err != nil {
1699 return res, err
6988a057
JH
1700 }
1701
7e2e07da
JH
1702 var fp FilePath
1703 if t.GetField(fieldFilePath).Data != nil {
8fc43f8e 1704 if _, err = fp.Write(t.GetField(fieldFilePath).Data); err != nil {
7e2e07da
JH
1705 return res, err
1706 }
1707 }
1708
1709 // Handle special case for drop box folders
187d6dc5 1710 if fp.IsDropbox() && !cc.Authorize(accessViewDropBoxes) {
2e08be58 1711 res = append(res, cc.NewErrReply(t, "You are not allowed to view drop boxes."))
7e2e07da
JH
1712 return res, err
1713 }
1714
b8c0a83a 1715 fileNames, err := getFileNameList(fullPath, cc.Server.Config.IgnoreFiles)
6988a057
JH
1716 if err != nil {
1717 return res, err
1718 }
1719
1720 res = append(res, cc.NewReply(t, fileNames...))
1721
1722 return res, err
1723}
1724
1725// =================================
1726// Hotline private chat flow
1727// =================================
1728// 1. ClientA sends tranInviteNewChat to server with user ID to invite
1729// 2. Server creates new ChatID
1730// 3. Server sends tranInviteToChat to invitee
1731// 4. Server replies to ClientA with new Chat ID
1732//
1733// A dialog box pops up in the invitee client with options to accept or decline the invitation.
1734// If Accepted is clicked:
1735// 1. ClientB sends tranJoinChat with fieldChatID
1736
1737// HandleInviteNewChat invites users to new private chat
1738func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
187d6dc5 1739 if !cc.Authorize(accessOpenChat) {
d4c152a4
JH
1740 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1741 return res, err
1742 }
1743
6988a057
JH
1744 // Client to Invite
1745 targetID := t.GetField(fieldUserID).Data
1746 newChatID := cc.Server.NewPrivateChat(cc)
1747
c1c44744
JH
1748 // Check if target user has "Refuse private chat" flag
1749 binary.BigEndian.Uint16(targetID)
1750 targetClient := cc.Server.Clients[binary.BigEndian.Uint16(targetID)]
1751
1752 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(targetClient.Flags)))
1753 if flagBitmap.Bit(userFLagRefusePChat) == 1 {
1754 res = append(res,
1755 *NewTransaction(
1756 tranServerMsg,
1757 cc.ID,
d29edb0a 1758 NewField(fieldData, []byte(string(targetClient.UserName)+" does not accept private chats.")),
c1c44744
JH
1759 NewField(fieldUserName, targetClient.UserName),
1760 NewField(fieldUserID, *targetClient.ID),
1761 NewField(fieldOptions, []byte{0, 2}),
1762 ),
1763 )
1764 } else {
1765 res = append(res,
1766 *NewTransaction(
1767 tranInviteToChat,
1768 &targetID,
1769 NewField(fieldChatID, newChatID),
1770 NewField(fieldUserName, cc.UserName),
1771 NewField(fieldUserID, *cc.ID),
1772 ),
1773 )
1774 }
6988a057
JH
1775
1776 res = append(res,
1777 cc.NewReply(t,
1778 NewField(fieldChatID, newChatID),
72dd37f1 1779 NewField(fieldUserName, cc.UserName),
6988a057 1780 NewField(fieldUserID, *cc.ID),
a7216f67
JH
1781 NewField(fieldUserIconID, cc.Icon),
1782 NewField(fieldUserFlags, cc.Flags),
6988a057
JH
1783 ),
1784 )
1785
1786 return res, err
1787}
1788
1789func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
187d6dc5 1790 if !cc.Authorize(accessOpenChat) {
d4c152a4
JH
1791 res = append(res, cc.NewErrReply(t, "You are not allowed to request private chat."))
1792 return res, err
1793 }
1794
6988a057
JH
1795 // Client to Invite
1796 targetID := t.GetField(fieldUserID).Data
1797 chatID := t.GetField(fieldChatID).Data
1798
1799 res = append(res,
1800 *NewTransaction(
1801 tranInviteToChat,
1802 &targetID,
1803 NewField(fieldChatID, chatID),
72dd37f1 1804 NewField(fieldUserName, cc.UserName),
6988a057
JH
1805 NewField(fieldUserID, *cc.ID),
1806 ),
1807 )
1808 res = append(res,
1809 cc.NewReply(
1810 t,
1811 NewField(fieldChatID, chatID),
72dd37f1 1812 NewField(fieldUserName, cc.UserName),
6988a057 1813 NewField(fieldUserID, *cc.ID),
a7216f67
JH
1814 NewField(fieldUserIconID, cc.Icon),
1815 NewField(fieldUserFlags, cc.Flags),
6988a057
JH
1816 ),
1817 )
1818
1819 return res, err
1820}
1821
1822func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1823 chatID := t.GetField(fieldChatID).Data
1824 chatInt := binary.BigEndian.Uint32(chatID)
1825
1826 privChat := cc.Server.PrivateChats[chatInt]
1827
72dd37f1 1828 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
6988a057
JH
1829
1830 for _, c := range sortedClients(privChat.ClientConn) {
1831 res = append(res,
1832 *NewTransaction(
1833 tranChatMsg,
1834 c.ID,
1835 NewField(fieldChatID, chatID),
1836 NewField(fieldData, resMsg),
1837 ),
1838 )
1839 }
1840
1841 return res, err
1842}
1843
1844// HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1845// Fields used in the reply:
1846// * 115 Chat subject
1847// * 300 User name with info (Optional)
1848// * 300 (more user names with info)
1849func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1850 chatID := t.GetField(fieldChatID).Data
1851 chatInt := binary.BigEndian.Uint32(chatID)
1852
1853 privChat := cc.Server.PrivateChats[chatInt]
1854
1855 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1856 for _, c := range sortedClients(privChat.ClientConn) {
1857 res = append(res,
1858 *NewTransaction(
1859 tranNotifyChatChangeUser,
1860 c.ID,
1861 NewField(fieldChatID, chatID),
72dd37f1 1862 NewField(fieldUserName, cc.UserName),
6988a057 1863 NewField(fieldUserID, *cc.ID),
a7216f67
JH
1864 NewField(fieldUserIconID, cc.Icon),
1865 NewField(fieldUserFlags, cc.Flags),
6988a057
JH
1866 ),
1867 )
1868 }
1869
1870 privChat.ClientConn[cc.uint16ID()] = cc
1871
1872 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1873 for _, c := range sortedClients(privChat.ClientConn) {
1874 user := User{
1875 ID: *c.ID,
a7216f67
JH
1876 Icon: c.Icon,
1877 Flags: c.Flags,
72dd37f1 1878 Name: string(c.UserName),
6988a057
JH
1879 }
1880
1881 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1882 }
1883
1884 res = append(res, cc.NewReply(t, replyFields...))
1885 return res, err
1886}
1887
1888// HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1889// Fields used in the request:
33265393
JH
1890// - 114 fieldChatID
1891//
6988a057
JH
1892// Reply is not expected.
1893func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1894 chatID := t.GetField(fieldChatID).Data
1895 chatInt := binary.BigEndian.Uint32(chatID)
1896
c74c1f28
JH
1897 privChat, ok := cc.Server.PrivateChats[chatInt]
1898 if !ok {
1899 return res, nil
1900 }
6988a057
JH
1901
1902 delete(privChat.ClientConn, cc.uint16ID())
1903
1904 // Notify members of the private chat that the user has left
1905 for _, c := range sortedClients(privChat.ClientConn) {
1906 res = append(res,
1907 *NewTransaction(
1908 tranNotifyChatDeleteUser,
1909 c.ID,
1910 NewField(fieldChatID, chatID),
1911 NewField(fieldUserID, *cc.ID),
1912 ),
1913 )
1914 }
1915
1916 return res, err
1917}
1918
1919// HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1920// Fields used in the request:
1921// * 114 Chat ID
1922// * 115 Chat subject Chat subject string
1923// Reply is not expected.
1924func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1925 chatID := t.GetField(fieldChatID).Data
1926 chatInt := binary.BigEndian.Uint32(chatID)
1927
1928 privChat := cc.Server.PrivateChats[chatInt]
1929 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1930
1931 for _, c := range sortedClients(privChat.ClientConn) {
1932 res = append(res,
1933 *NewTransaction(
1934 tranNotifyChatSubject,
1935 c.ID,
1936 NewField(fieldChatID, chatID),
1937 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),
1938 ),
1939 )
1940 }
1941
1942 return res, err
1943}
decc2fbf 1944
7cd900d6 1945// HandleMakeAlias makes a filer alias using the specified path.
decc2fbf
JH
1946// Fields used in the request:
1947// 201 File name
1948// 202 File path
1949// 212 File new path Destination path
1950//
1951// Fields used in the reply:
1952// None
1953func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
187d6dc5 1954 if !cc.Authorize(accessMakeAlias) {
decc2fbf
JH
1955 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
1956 return res, err
1957 }
1958 fileName := t.GetField(fieldFileName).Data
1959 filePath := t.GetField(fieldFilePath).Data
1960 fileNewPath := t.GetField(fieldFileNewPath).Data
1961
1962 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1963 if err != nil {
1964 return res, err
1965 }
1966
1967 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
1968 if err != nil {
1969 return res, err
1970 }
1971
67db911d 1972 cc.logger.Debugw("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
decc2fbf 1973
b196a50a 1974 if err := cc.Server.FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
decc2fbf
JH
1975 res = append(res, cc.NewErrReply(t, "Error creating alias"))
1976 return res, nil
1977 }
1978
1979 res = append(res, cc.NewReply(t))
1980 return res, err
1981}
9067f234 1982
969e6481
JH
1983// HandleDownloadBanner handles requests for a new banner from the server
1984// Fields used in the request:
1985// None
1986// Fields used in the reply:
1987// 107 fieldRefNum Used later for transfer
1988// 108 fieldTransferSize Size of data to be downloaded
9067f234 1989func HandleDownloadBanner(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
9067f234
JH
1990 fi, err := cc.Server.FS.Stat(filepath.Join(cc.Server.ConfigDir, cc.Server.Config.BannerFile))
1991 if err != nil {
1992 return res, err
1993 }
1994
df1ade54 1995 ft := cc.newFileTransfer(bannerDownload, []byte{}, []byte{}, make([]byte, 4))
9067f234 1996
df1ade54 1997 binary.BigEndian.PutUint32(ft.TransferSize, uint32(fi.Size()))
9067f234
JH
1998
1999 res = append(res, cc.NewReply(t,
df1ade54
JH
2000 NewField(fieldRefNum, ft.refNum[:]),
2001 NewField(fieldTransferSize, ft.TransferSize),
9067f234
JH
2002 ))
2003
9067f234
JH
2004 return res, err
2005}