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