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