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