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