]> git.r.bdr.sh - rbdr/mobius/blame - hotline/transaction_handlers.go
Handle zero length comment and file paths for Nostalgia compatibility
[rbdr/mobius] / hotline / transaction_handlers.go
CommitLineData
6988a057
JH
1package hotline
2
3import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7 "fmt"
0197c3f5 8 "gopkg.in/yaml.v3"
6988a057
JH
9 "io/ioutil"
10 "math/big"
11 "os"
00d1ef67 12 "path"
6988a057
JH
13 "sort"
14 "strings"
15 "time"
16)
17
18type TransactionType struct {
19 Access int // Specifies access privilege required to perform the transaction
20 DenyMsg string // The error reply message when user does not have access
21 Handler func(*ClientConn, *Transaction) ([]Transaction, error) // function for handling the transaction type
22 Name string // Name of transaction as it will appear in logging
23 RequiredFields []requiredField
24}
25
26var TransactionHandlers = map[uint16]TransactionType{
27 // Server initiated
28 tranChatMsg: {
29 Name: "tranChatMsg",
30 },
31 // Server initiated
32 tranNotifyChangeUser: {
33 Name: "tranNotifyChangeUser",
34 },
35 tranError: {
36 Name: "tranError",
37 },
38 tranShowAgreement: {
39 Name: "tranShowAgreement",
40 },
41 tranUserAccess: {
42 Name: "tranUserAccess",
43 },
5454019c
JH
44 tranNotifyDeleteUser: {
45 Name: "tranNotifyDeleteUser",
46 },
6988a057 47 tranAgreed: {
fe71da2b 48 Access: accessAlwaysAllow,
6988a057
JH
49 Name: "tranAgreed",
50 Handler: HandleTranAgreed,
51 },
52 tranChatSend: {
481631f6 53 Access: accessAlwaysAllow,
6988a057
JH
54 Handler: HandleChatSend,
55 Name: "tranChatSend",
56 RequiredFields: []requiredField{
57 {
58 ID: fieldData,
59 minLen: 0,
60 },
61 },
62 },
63 tranDelNewsArt: {
64 Access: accessNewsDeleteArt,
65 DenyMsg: "You are not allowed to delete news articles.",
66 Name: "tranDelNewsArt",
67 Handler: HandleDelNewsArt,
68 },
69 tranDelNewsItem: {
fe71da2b 70 Access: accessAlwaysAllow, // Granular access enforced inside the handler
6988a057
JH
71 // Has multiple access flags: News Delete Folder (37) or News Delete Category (35)
72 // TODO: Implement inside the handler
73 Name: "tranDelNewsItem",
74 Handler: HandleDelNewsItem,
75 },
76 tranDeleteFile: {
fe71da2b 77 Access: accessAlwaysAllow, // Granular access enforced inside the handler
6988a057
JH
78 Name: "tranDeleteFile",
79 Handler: HandleDeleteFile,
80 },
81 tranDeleteUser: {
481631f6 82 Access: accessAlwaysAllow,
6988a057
JH
83 Name: "tranDeleteUser",
84 Handler: HandleDeleteUser,
85 },
86 tranDisconnectUser: {
87 Access: accessDisconUser,
88 DenyMsg: "You are not allowed to disconnect users.",
89 Name: "tranDisconnectUser",
90 Handler: HandleDisconnectUser,
91 },
92 tranDownloadFile: {
481631f6 93 Access: accessAlwaysAllow,
6988a057
JH
94 Name: "tranDownloadFile",
95 Handler: HandleDownloadFile,
96 },
97 tranDownloadFldr: {
98 Access: accessDownloadFile, // There is no specific access flag for folder vs file download
99 DenyMsg: "You are not allowed to download files.",
100 Name: "tranDownloadFldr",
101 Handler: HandleDownloadFolder,
102 },
103 tranGetClientInfoText: {
104 Access: accessGetClientInfo,
105 DenyMsg: "You are not allowed to get client info",
106 Name: "tranGetClientInfoText",
107 Handler: HandleGetClientConnInfoText,
108 },
109 tranGetFileInfo: {
fe71da2b 110 Access: accessAlwaysAllow,
6988a057
JH
111 Name: "tranGetFileInfo",
112 Handler: HandleGetFileInfo,
113 },
114 tranGetFileNameList: {
fe71da2b 115 Access: accessAlwaysAllow,
6988a057
JH
116 Name: "tranGetFileNameList",
117 Handler: HandleGetFileNameList,
118 },
119 tranGetMsgs: {
481631f6 120 Access: accessAlwaysAllow,
6988a057
JH
121 Name: "tranGetMsgs",
122 Handler: HandleGetMsgs,
123 },
124 tranGetNewsArtData: {
5454019c
JH
125 Access: accessNewsReadArt,
126 DenyMsg: "You are not allowed to read news.",
6988a057
JH
127 Name: "tranGetNewsArtData",
128 Handler: HandleGetNewsArtData,
129 },
130 tranGetNewsArtNameList: {
5454019c
JH
131 Access: accessNewsReadArt,
132 DenyMsg: "You are not allowed to read news.",
6988a057
JH
133 Name: "tranGetNewsArtNameList",
134 Handler: HandleGetNewsArtNameList,
135 },
136 tranGetNewsCatNameList: {
5454019c
JH
137 Access: accessNewsReadArt,
138 DenyMsg: "You are not allowed to read news.",
6988a057
JH
139 Name: "tranGetNewsCatNameList",
140 Handler: HandleGetNewsCatNameList,
141 },
142 tranGetUser: {
481631f6 143 Access: accessAlwaysAllow,
6988a057
JH
144 Name: "tranGetUser",
145 Handler: HandleGetUser,
146 },
147 tranGetUserNameList: {
fe71da2b 148 Access: accessAlwaysAllow,
6988a057
JH
149 Name: "tranHandleGetUserNameList",
150 Handler: HandleGetUserNameList,
151 },
152 tranInviteNewChat: {
153 Access: accessOpenChat,
154 DenyMsg: "You are not allowed to request private chat.",
155 Name: "tranInviteNewChat",
156 Handler: HandleInviteNewChat,
157 },
158 tranInviteToChat: {
5454019c
JH
159 Access: accessOpenChat,
160 DenyMsg: "You are not allowed to request private chat.",
6988a057
JH
161 Name: "tranInviteToChat",
162 Handler: HandleInviteToChat,
163 },
164 tranJoinChat: {
fe71da2b 165 Access: accessAlwaysAllow,
6988a057
JH
166 Name: "tranJoinChat",
167 Handler: HandleJoinChat,
168 },
169 tranKeepAlive: {
fe71da2b 170 Access: accessAlwaysAllow,
6988a057
JH
171 Name: "tranKeepAlive",
172 Handler: HandleKeepAlive,
173 },
174 tranLeaveChat: {
fe71da2b 175 Access: accessAlwaysAllow,
6988a057
JH
176 Name: "tranJoinChat",
177 Handler: HandleLeaveChat,
178 },
6988a057 179 tranListUsers: {
481631f6 180 Access: accessAlwaysAllow,
6988a057
JH
181 Name: "tranListUsers",
182 Handler: HandleListUsers,
183 },
184 tranMoveFile: {
185 Access: accessMoveFile,
186 DenyMsg: "You are not allowed to move files.",
187 Name: "tranMoveFile",
188 Handler: HandleMoveFile,
189 },
190 tranNewFolder: {
5454019c
JH
191 Access: accessCreateFolder,
192 DenyMsg: "You are not allow to create folders.",
6988a057
JH
193 Name: "tranNewFolder",
194 Handler: HandleNewFolder,
195 },
196 tranNewNewsCat: {
5454019c
JH
197 Access: accessNewsCreateCat,
198 DenyMsg: "You are not allowed to create news categories.",
6988a057
JH
199 Name: "tranNewNewsCat",
200 Handler: HandleNewNewsCat,
201 },
202 tranNewNewsFldr: {
5454019c
JH
203 Access: accessNewsCreateFldr,
204 DenyMsg: "You are not allowed to create news folders.",
6988a057
JH
205 Name: "tranNewNewsFldr",
206 Handler: HandleNewNewsFldr,
207 },
208 tranNewUser: {
481631f6 209 Access: accessAlwaysAllow,
6988a057
JH
210 Name: "tranNewUser",
211 Handler: HandleNewUser,
212 },
d2810ae9
JH
213 tranUpdateUser: {
214 Access: accessAlwaysAllow,
215 Name: "tranUpdateUser",
216 Handler: HandleUpdateUser,
217 },
6988a057 218 tranOldPostNews: {
5454019c
JH
219 Access: accessNewsPostArt,
220 DenyMsg: "You are not allowed to post news.",
6988a057
JH
221 Name: "tranOldPostNews",
222 Handler: HandleTranOldPostNews,
223 },
224 tranPostNewsArt: {
225 Access: accessNewsPostArt,
226 DenyMsg: "You are not allowed to post news articles.",
227 Name: "tranPostNewsArt",
228 Handler: HandlePostNewsArt,
229 },
230 tranRejectChatInvite: {
fe71da2b 231 Access: accessAlwaysAllow,
6988a057
JH
232 Name: "tranRejectChatInvite",
233 Handler: HandleRejectChatInvite,
234 },
235 tranSendInstantMsg: {
5454019c 236 Access: accessAlwaysAllow,
aebc4d36
JH
237 // Access: accessSendPrivMsg,
238 // DenyMsg: "You are not allowed to send private messages",
6988a057
JH
239 Name: "tranSendInstantMsg",
240 Handler: HandleSendInstantMsg,
241 RequiredFields: []requiredField{
242 {
243 ID: fieldData,
244 minLen: 0,
245 },
246 {
247 ID: fieldUserID,
248 },
249 },
250 },
251 tranSetChatSubject: {
fe71da2b 252 Access: accessAlwaysAllow,
6988a057
JH
253 Name: "tranSetChatSubject",
254 Handler: HandleSetChatSubject,
255 },
decc2fbf 256 tranMakeFileAlias: {
fe71da2b 257 Access: accessAlwaysAllow,
decc2fbf
JH
258 Name: "tranMakeFileAlias",
259 Handler: HandleMakeAlias,
260 RequiredFields: []requiredField{
261 {ID: fieldFileName, minLen: 1},
262 {ID: fieldFilePath, minLen: 1},
263 {ID: fieldFileNewPath, minLen: 1},
264 },
265 },
6988a057 266 tranSetClientUserInfo: {
fe71da2b 267 Access: accessAlwaysAllow,
6988a057
JH
268 Name: "tranSetClientUserInfo",
269 Handler: HandleSetClientUserInfo,
270 },
271 tranSetFileInfo: {
fe71da2b 272 Access: accessAlwaysAllow,
6988a057
JH
273 Name: "tranSetFileInfo",
274 Handler: HandleSetFileInfo,
275 },
276 tranSetUser: {
277 Access: accessModifyUser,
278 DenyMsg: "You are not allowed to modify accounts.",
279 Name: "tranSetUser",
280 Handler: HandleSetUser,
281 },
282 tranUploadFile: {
fe71da2b 283 Access: accessAlwaysAllow,
6988a057
JH
284 Name: "tranUploadFile",
285 Handler: HandleUploadFile,
286 },
287 tranUploadFldr: {
fe71da2b 288 Access: accessAlwaysAllow,
6988a057
JH
289 Name: "tranUploadFldr",
290 Handler: HandleUploadFolder,
291 },
292 tranUserBroadcast: {
293 Access: accessBroadcast,
294 DenyMsg: "You are not allowed to send broadcast messages.",
295 Name: "tranUserBroadcast",
296 Handler: HandleUserBroadcast,
297 },
298}
299
300func HandleChatSend(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
003a743e
JH
301 if !authorize(cc.Account.Access, accessSendChat) {
302 res = append(res, cc.NewErrReply(t, "You are not allowed to participate in chat."))
303 return res, err
304 }
305
6988a057 306 // Truncate long usernames
72dd37f1 307 trunc := fmt.Sprintf("%13s", cc.UserName)
6988a057
JH
308 formattedMsg := fmt.Sprintf("\r%.14s: %s", trunc, t.GetField(fieldData).Data)
309
310 // By holding the option key, Hotline chat allows users to send /me formatted messages like:
311 // *** Halcyon does stuff
312 // This is indicated by the presence of the optional field fieldChatOptions in the transaction payload
313 if t.GetField(fieldChatOptions).Data != nil {
72dd37f1 314 formattedMsg = fmt.Sprintf("\r*** %s %s", cc.UserName, t.GetField(fieldData).Data)
6988a057
JH
315 }
316
317 if bytes.Equal(t.GetField(fieldData).Data, []byte("/stats")) {
318 formattedMsg = strings.Replace(cc.Server.Stats.String(), "\n", "\r", -1)
319 }
320
321 chatID := t.GetField(fieldChatID).Data
322 // a non-nil chatID indicates the message belongs to a private chat
323 if chatID != nil {
324 chatInt := binary.BigEndian.Uint32(chatID)
325 privChat := cc.Server.PrivateChats[chatInt]
326
481631f6
JH
327 clients := sortedClients(privChat.ClientConn)
328
6988a057 329 // send the message to all connected clients of the private chat
481631f6 330 for _, c := range clients {
6988a057
JH
331 res = append(res, *NewTransaction(
332 tranChatMsg,
333 c.ID,
334 NewField(fieldChatID, chatID),
335 NewField(fieldData, []byte(formattedMsg)),
336 ))
337 }
338 return res, err
339 }
340
341 for _, c := range sortedClients(cc.Server.Clients) {
342 // Filter out clients that do not have the read chat permission
343 if authorize(c.Account.Access, accessReadChat) {
344 res = append(res, *NewTransaction(tranChatMsg, c.ID, NewField(fieldData, []byte(formattedMsg))))
345 }
346 }
347
348 return res, err
349}
350
351// HandleSendInstantMsg sends instant message to the user on the current server.
352// Fields used in the request:
353// 103 User ID
354// 113 Options
355// One of the following values:
356// - User message (myOpt_UserMessage = 1)
357// - Refuse message (myOpt_RefuseMessage = 2)
358// - Refuse chat (myOpt_RefuseChat = 3)
359// - Automatic response (myOpt_AutomaticResponse = 4)"
360// 101 Data Optional
361// 214 Quoting message Optional
362//
aebc4d36 363// Fields used in the reply:
6988a057
JH
364// None
365func HandleSendInstantMsg(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
366 msg := t.GetField(fieldData)
367 ID := t.GetField(fieldUserID)
6988a057 368
5ae50876
JH
369 reply := *NewTransaction(
370 tranServerMsg,
371 &ID.Data,
372 NewField(fieldData, msg.Data),
373 NewField(fieldUserName, cc.UserName),
374 NewField(fieldUserID, *cc.ID),
375 NewField(fieldOptions, []byte{0, 1}),
6988a057 376 )
6988a057 377
5ae50876
JH
378 // Later versions of Hotline include the original message in the fieldQuotingMsg field so
379 // the receiving client can display both the received message and what it is in reply to
380 if t.GetField(fieldQuotingMsg).Data != nil {
381 reply.Fields = append(reply.Fields, NewField(fieldQuotingMsg, t.GetField(fieldQuotingMsg).Data))
382 }
383
384 res = append(res, reply)
385
386 id, _ := byteToInt(ID.Data)
6988a057
JH
387 otherClient := cc.Server.Clients[uint16(id)]
388 if otherClient == nil {
389 return res, errors.New("ohno")
390 }
391
392 // Respond with auto reply if other client has it enabled
aebc4d36 393 if len(otherClient.AutoReply) > 0 {
6988a057
JH
394 res = append(res,
395 *NewTransaction(
396 tranServerMsg,
397 cc.ID,
aebc4d36 398 NewField(fieldData, otherClient.AutoReply),
72dd37f1 399 NewField(fieldUserName, otherClient.UserName),
6988a057
JH
400 NewField(fieldUserID, *otherClient.ID),
401 NewField(fieldOptions, []byte{0, 1}),
402 ),
403 )
404 }
405
406 res = append(res, cc.NewReply(t))
407
408 return res, err
409}
410
411func HandleGetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
92a7e455
JH
412 fileName := t.GetField(fieldFileName).Data
413 filePath := t.GetField(fieldFilePath).Data
6988a057 414
16a4ad70 415 ffo, err := NewFlattenedFileObject(cc.Server.Config.FileRoot, filePath, fileName, 0)
6988a057
JH
416 if err != nil {
417 return res, err
418 }
419
420 res = append(res, cc.NewReply(t,
92a7e455 421 NewField(fieldFileName, fileName),
6988a057
JH
422 NewField(fieldFileTypeString, ffo.FlatFileInformationFork.TypeSignature),
423 NewField(fieldFileCreatorString, ffo.FlatFileInformationFork.CreatorSignature),
424 NewField(fieldFileComment, ffo.FlatFileInformationFork.Comment),
425 NewField(fieldFileType, ffo.FlatFileInformationFork.TypeSignature),
426 NewField(fieldFileCreateDate, ffo.FlatFileInformationFork.CreateDate),
427 NewField(fieldFileModifyDate, ffo.FlatFileInformationFork.ModifyDate),
85767504 428 NewField(fieldFileSize, ffo.FlatFileDataForkHeader.DataSize[:]),
6988a057
JH
429 ))
430 return res, err
431}
432
433// HandleSetFileInfo updates a file or folder name and/or comment from the Get Info window
434// TODO: Implement support for comments
435// Fields used in the request:
436// * 201 File name
437// * 202 File path Optional
438// * 211 File new name Optional
439// * 210 File comment Optional
440// Fields used in the reply: None
441func HandleSetFileInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
92a7e455
JH
442 fileName := t.GetField(fieldFileName).Data
443 filePath := t.GetField(fieldFilePath).Data
444
445 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
446 if err != nil {
447 return res, err
448 }
449
450 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, t.GetField(fieldFileNewName).Data)
451 if err != nil {
452 return nil, err
453 }
454
aebc4d36 455 // fileComment := t.GetField(fieldFileComment).Data
6988a057
JH
456 fileNewName := t.GetField(fieldFileNewName).Data
457
458 if fileNewName != nil {
92a7e455 459 fi, err := FS.Stat(fullFilePath)
6988a057
JH
460 if err != nil {
461 return res, err
462 }
463 switch mode := fi.Mode(); {
464 case mode.IsDir():
465 if !authorize(cc.Account.Access, accessRenameFolder) {
466 res = append(res, cc.NewErrReply(t, "You are not allowed to rename folders."))
467 return res, err
468 }
469 case mode.IsRegular():
470 if !authorize(cc.Account.Access, accessRenameFile) {
471 res = append(res, cc.NewErrReply(t, "You are not allowed to rename files."))
472 return res, err
473 }
474 }
475
92a7e455 476 err = os.Rename(fullFilePath, fullNewFilePath)
6988a057 477 if os.IsNotExist(err) {
92a7e455 478 res = append(res, cc.NewErrReply(t, "Cannot rename file "+string(fileName)+" because it does not exist or cannot be found."))
6988a057
JH
479 return res, err
480 }
481 }
482
483 res = append(res, cc.NewReply(t))
484 return res, err
485}
486
487// HandleDeleteFile deletes a file or folder
488// Fields used in the request:
489// * 201 File name
490// * 202 File path
491// Fields used in the reply: none
492func HandleDeleteFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
92a7e455
JH
493 fileName := t.GetField(fieldFileName).Data
494 filePath := t.GetField(fieldFilePath).Data
6988a057 495
92a7e455
JH
496 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
497 if err != nil {
498 return res, err
499 }
6988a057 500
92a7e455 501 cc.Server.Logger.Debugw("Delete file", "src", fullFilePath)
6988a057 502
92a7e455 503 fi, err := os.Stat(fullFilePath)
6988a057 504 if err != nil {
92a7e455 505 res = append(res, cc.NewErrReply(t, "Cannot delete file "+string(fileName)+" because it does not exist or cannot be found."))
6988a057
JH
506 return res, nil
507 }
508 switch mode := fi.Mode(); {
509 case mode.IsDir():
510 if !authorize(cc.Account.Access, accessDeleteFolder) {
511 res = append(res, cc.NewErrReply(t, "You are not allowed to delete folders."))
512 return res, err
513 }
514 case mode.IsRegular():
515 if !authorize(cc.Account.Access, accessDeleteFile) {
516 res = append(res, cc.NewErrReply(t, "You are not allowed to delete files."))
517 return res, err
518 }
519 }
520
92a7e455 521 if err := os.RemoveAll(fullFilePath); err != nil {
6988a057
JH
522 return res, err
523 }
524
525 res = append(res, cc.NewReply(t))
526 return res, err
527}
528
529// HandleMoveFile moves files or folders. Note: seemingly not documented
530func HandleMoveFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
531 fileName := string(t.GetField(fieldFileName).Data)
00d1ef67
JH
532 filePath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFilePath).Data)
533 fileNewPath := cc.Server.Config.FileRoot + ReadFilePath(t.GetField(fieldFileNewPath).Data)
6988a057
JH
534
535 cc.Server.Logger.Debugw("Move file", "src", filePath+"/"+fileName, "dst", fileNewPath+"/"+fileName)
536
003a743e
JH
537 fp := filePath + "/" + fileName
538 fi, err := os.Stat(fp)
6988a057
JH
539 if err != nil {
540 return res, err
541 }
542 switch mode := fi.Mode(); {
543 case mode.IsDir():
544 if !authorize(cc.Account.Access, accessMoveFolder) {
545 res = append(res, cc.NewErrReply(t, "You are not allowed to move folders."))
546 return res, err
547 }
548 case mode.IsRegular():
549 if !authorize(cc.Account.Access, accessMoveFile) {
550 res = append(res, cc.NewErrReply(t, "You are not allowed to move files."))
551 return res, err
552 }
553 }
554
555 err = os.Rename(filePath+"/"+fileName, fileNewPath+"/"+fileName)
556 if os.IsNotExist(err) {
557 res = append(res, cc.NewErrReply(t, "Cannot delete file "+fileName+" because it does not exist or cannot be found."))
558 return res, err
559 }
560 if err != nil {
561 return []Transaction{}, err
562 }
563 // TODO: handle other possible errors; e.g. file delete fails due to file permission issue
564
565 res = append(res, cc.NewReply(t))
566 return res, err
567}
568
569func HandleNewFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
570 newFolderPath := cc.Server.Config.FileRoot
00d1ef67
JH
571 folderName := string(t.GetField(fieldFileName).Data)
572
573 folderName = path.Join("/", folderName)
6988a057
JH
574
575 // fieldFilePath is only present for nested paths
576 if t.GetField(fieldFilePath).Data != nil {
72dd37f1 577 var newFp FilePath
00d1ef67
JH
578 err := newFp.UnmarshalBinary(t.GetField(fieldFilePath).Data)
579 if err != nil {
580 return nil, err
581 }
6988a057
JH
582 newFolderPath += newFp.String()
583 }
00d1ef67 584 newFolderPath = path.Join(newFolderPath, folderName)
6988a057 585
00d1ef67
JH
586 // TODO: check path and folder name lengths
587
588 if _, err := FS.Stat(newFolderPath); !os.IsNotExist(err) {
589 msg := fmt.Sprintf("Cannot create folder \"%s\" because there is already a file or folder with that name.", folderName)
590 return []Transaction{cc.NewErrReply(t, msg)}, nil
591 }
592
593 // TODO: check for disallowed characters to maintain compatibility for original client
594
595 if err := FS.Mkdir(newFolderPath, 0777); err != nil {
596 msg := fmt.Sprintf("Cannot create folder \"%s\" because an error occurred.", folderName)
597 return []Transaction{cc.NewErrReply(t, msg)}, nil
6988a057
JH
598 }
599
600 res = append(res, cc.NewReply(t))
601 return res, err
602}
603
604func HandleSetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
605 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
606 userName := string(t.GetField(fieldUserName).Data)
607
608 newAccessLvl := t.GetField(fieldUserAccess).Data
609
610 account := cc.Server.Accounts[login]
611 account.Access = &newAccessLvl
612 account.Name = userName
613
614 // If the password field is cleared in the Hotline edit user UI, the SetUser transaction does
615 // not include fieldUserPassword
616 if t.GetField(fieldUserPassword).Data == nil {
617 account.Password = hashAndSalt([]byte(""))
618 }
619 if len(t.GetField(fieldUserPassword).Data) > 1 {
620 account.Password = hashAndSalt(t.GetField(fieldUserPassword).Data)
621 }
622
6988a057
JH
623 out, err := yaml.Marshal(&account)
624 if err != nil {
625 return res, err
626 }
d2810ae9 627 if err := os.WriteFile(cc.Server.ConfigDir+"Users/"+login+".yaml", out, 0666); err != nil {
6988a057
JH
628 return res, err
629 }
630
631 // Notify connected clients logged in as the user of the new access level
632 for _, c := range cc.Server.Clients {
633 if c.Account.Login == login {
634 // Note: comment out these two lines to test server-side deny messages
635 newT := NewTransaction(tranUserAccess, c.ID, NewField(fieldUserAccess, newAccessLvl))
636 res = append(res, *newT)
637
638 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*c.Flags)))
639 if authorize(c.Account.Access, accessDisconUser) {
640 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 1)
641 } else {
642 flagBitmap.SetBit(flagBitmap, userFlagAdmin, 0)
643 }
644 binary.BigEndian.PutUint16(*c.Flags, uint16(flagBitmap.Int64()))
645
646 c.Account.Access = account.Access
647
648 cc.sendAll(
649 tranNotifyChangeUser,
650 NewField(fieldUserID, *c.ID),
651 NewField(fieldUserFlags, *c.Flags),
72dd37f1 652 NewField(fieldUserName, c.UserName),
6988a057
JH
653 NewField(fieldUserIconID, *c.Icon),
654 )
655 }
656 }
657
6988a057
JH
658 res = append(res, cc.NewReply(t))
659 return res, err
660}
661
662func HandleGetUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
003a743e
JH
663 if !authorize(cc.Account.Access, accessOpenUser) {
664 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
665 return res, err
666 }
667
aebc4d36 668 account := cc.Server.Accounts[string(t.GetField(fieldUserLogin).Data)]
6988a057 669 if account == nil {
481631f6 670 res = append(res, cc.NewErrReply(t, "Account does not exist."))
6988a057
JH
671 return res, err
672 }
673
674 res = append(res, cc.NewReply(t,
675 NewField(fieldUserName, []byte(account.Name)),
b25c4a19 676 NewField(fieldUserLogin, negateString(t.GetField(fieldUserLogin).Data)),
6988a057
JH
677 NewField(fieldUserPassword, []byte(account.Password)),
678 NewField(fieldUserAccess, *account.Access),
679 ))
680 return res, err
681}
682
683func HandleListUsers(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
481631f6
JH
684 if !authorize(cc.Account.Access, accessOpenUser) {
685 res = append(res, cc.NewErrReply(t, "You are not allowed to view accounts."))
686 return res, err
687 }
688
6988a057 689 var userFields []Field
6988a057 690 for _, acc := range cc.Server.Accounts {
c5d9af5a 691 userField := acc.MarshalBinary()
6988a057
JH
692 userFields = append(userFields, NewField(fieldData, userField))
693 }
694
695 res = append(res, cc.NewReply(t, userFields...))
696 return res, err
697}
698
d2810ae9
JH
699// HandleUpdateUser is used by the v1.5+ multi-user editor to perform account editing for multiple users at a time.
700// An update can be a mix of these actions:
701// * Create user
702// * Delete user
703// * Modify user (including renaming the account login)
704//
705// The Transaction sent by the client includes one data field per user that was modified. This data field in turn
706// contains another data field encoded in its payload with a varying number of sub fields depending on which action is
707// performed. This seems to be the only place in the Hotline protocol where a data field contains another data field.
708func HandleUpdateUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
709 for _, field := range t.Fields {
710 subFields, err := ReadFields(field.Data[0:2], field.Data[2:])
711 if err != nil {
712 return res, err
713 }
714
715 if len(subFields) == 1 {
716 login := DecodeUserString(getField(fieldData, &subFields).Data)
717 cc.Server.Logger.Infow("DeleteUser", "login", login)
718
719 if !authorize(cc.Account.Access, accessDeleteUser) {
720 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
721 return res, err
722 }
723
724 if err := cc.Server.DeleteUser(login); err != nil {
725 return res, err
726 }
727 continue
728 }
729
730 login := DecodeUserString(getField(fieldUserLogin, &subFields).Data)
731
732 // check if the login exists; if so, we know we are updating an existing user
733 if acc, ok := cc.Server.Accounts[login]; ok {
734 cc.Server.Logger.Infow("UpdateUser", "login", login)
735
736 // account exists, so this is an update action
737 if !authorize(cc.Account.Access, accessModifyUser) {
738 res = append(res, cc.NewErrReply(t, "You are not allowed to modify accounts."))
739 return res, err
740 }
741
742 if getField(fieldUserPassword, &subFields) != nil {
743 newPass := getField(fieldUserPassword, &subFields).Data
744 acc.Password = hashAndSalt(newPass)
745 } else {
746 acc.Password = hashAndSalt([]byte(""))
747 }
748
749 if getField(fieldUserAccess, &subFields) != nil {
750 acc.Access = &getField(fieldUserAccess, &subFields).Data
751 }
752
753 err = cc.Server.UpdateUser(
754 DecodeUserString(getField(fieldData, &subFields).Data),
755 DecodeUserString(getField(fieldUserLogin, &subFields).Data),
756 string(getField(fieldUserName, &subFields).Data),
757 acc.Password,
758 *acc.Access,
759 )
760 if err != nil {
761 return res, err
762 }
763 } else {
764 cc.Server.Logger.Infow("CreateUser", "login", login)
765
766 if !authorize(cc.Account.Access, accessCreateUser) {
767 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
768 return res, err
769 }
770
771 err := cc.Server.NewUser(
772 login,
773 string(getField(fieldUserName, &subFields).Data),
774 string(getField(fieldUserPassword, &subFields).Data),
775 getField(fieldUserAccess, &subFields).Data,
776 )
777 if err != nil {
778 return []Transaction{}, err
779 }
780 }
781 }
782
783 res = append(res, cc.NewReply(t))
784 return res, err
785}
786
6988a057
JH
787// HandleNewUser creates a new user account
788func HandleNewUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
481631f6
JH
789 if !authorize(cc.Account.Access, accessCreateUser) {
790 res = append(res, cc.NewErrReply(t, "You are not allowed to create new accounts."))
791 return res, err
792 }
793
6988a057
JH
794 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
795
796 // If the account already exists, reply with an error
6988a057
JH
797 if _, ok := cc.Server.Accounts[login]; ok {
798 res = append(res, cc.NewErrReply(t, "Cannot create account "+login+" because there is already an account with that login."))
799 return res, err
800 }
801
802 if err := cc.Server.NewUser(
803 login,
804 string(t.GetField(fieldUserName).Data),
805 string(t.GetField(fieldUserPassword).Data),
806 t.GetField(fieldUserAccess).Data,
807 ); err != nil {
808 return []Transaction{}, err
809 }
810
811 res = append(res, cc.NewReply(t))
812 return res, err
813}
814
815func HandleDeleteUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
003a743e
JH
816 if !authorize(cc.Account.Access, accessDeleteUser) {
817 res = append(res, cc.NewErrReply(t, "You are not allowed to delete accounts."))
818 return res, err
819 }
820
6988a057
JH
821 // TODO: Handle case where account doesn't exist; e.g. delete race condition
822 login := DecodeUserString(t.GetField(fieldUserLogin).Data)
823
824 if err := cc.Server.DeleteUser(login); err != nil {
825 return res, err
826 }
827
828 res = append(res, cc.NewReply(t))
829 return res, err
830}
831
832// HandleUserBroadcast sends an Administrator Message to all connected clients of the server
833func HandleUserBroadcast(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
834 cc.sendAll(
835 tranServerMsg,
836 NewField(fieldData, t.GetField(tranGetMsgs).Data),
837 NewField(fieldChatOptions, []byte{0}),
838 )
839
840 res = append(res, cc.NewReply(t))
841 return res, err
842}
843
844func byteToInt(bytes []byte) (int, error) {
845 switch len(bytes) {
846 case 2:
847 return int(binary.BigEndian.Uint16(bytes)), nil
848 case 4:
849 return int(binary.BigEndian.Uint32(bytes)), nil
850 }
851
852 return 0, errors.New("unknown byte length")
853}
854
855func HandleGetClientConnInfoText(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
856 clientID, _ := byteToInt(t.GetField(fieldUserID).Data)
857
858 clientConn := cc.Server.Clients[uint16(clientID)]
859 if clientConn == nil {
860 return res, errors.New("invalid client")
861 }
862
863 // TODO: Implement non-hardcoded values
864 template := `Nickname: %s
865Name: %s
866Account: %s
867Address: %s
868
869-------- File Downloads ---------
870
871%s
872
873------- Folder Downloads --------
874
875None.
876
877--------- File Uploads ----------
878
879None.
880
881-------- Folder Uploads ---------
882
883None.
884
885------- Waiting Downloads -------
886
887None.
888
889 `
890
891 activeDownloads := clientConn.Transfers[FileDownload]
892 activeDownloadList := "None."
893 for _, dl := range activeDownloads {
894 activeDownloadList += dl.String() + "\n"
895 }
896
897 template = fmt.Sprintf(
898 template,
72dd37f1 899 clientConn.UserName,
6988a057
JH
900 clientConn.Account.Name,
901 clientConn.Account.Login,
902 clientConn.Connection.RemoteAddr().String(),
903 activeDownloadList,
904 )
905 template = strings.Replace(template, "\n", "\r", -1)
906
907 res = append(res, cc.NewReply(t,
908 NewField(fieldData, []byte(template)),
72dd37f1 909 NewField(fieldUserName, clientConn.UserName),
6988a057
JH
910 ))
911 return res, err
912}
913
914func HandleGetUserNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
915 res = append(res, cc.NewReply(t, cc.Server.connectedUsers()...))
916
917 return res, err
918}
919
6988a057 920func HandleTranAgreed(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
bd1ce113 921 cc.Agreed = true
72dd37f1 922 cc.UserName = t.GetField(fieldUserName).Data
6988a057
JH
923 *cc.Icon = t.GetField(fieldUserIconID).Data
924
925 options := t.GetField(fieldOptions).Data
926 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
927
928 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
929
930 // Check refuse private PM option
931 if optBitmap.Bit(refusePM) == 1 {
932 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, 1)
933 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
934 }
935
936 // Check refuse private chat option
937 if optBitmap.Bit(refuseChat) == 1 {
938 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, 1)
939 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
940 }
941
942 // Check auto response
943 if optBitmap.Bit(autoResponse) == 1 {
aebc4d36 944 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
6988a057 945 } else {
aebc4d36 946 cc.AutoReply = []byte{}
6988a057
JH
947 }
948
003a743e
JH
949 cc.notifyOthers(
950 *NewTransaction(
951 tranNotifyChangeUser, nil,
952 NewField(fieldUserName, cc.UserName),
953 NewField(fieldUserID, *cc.ID),
954 NewField(fieldUserIconID, *cc.Icon),
955 NewField(fieldUserFlags, *cc.Flags),
956 ),
957 )
6988a057
JH
958
959 res = append(res, cc.NewReply(t))
960
961 return res, err
962}
963
964const defaultNewsDateFormat = "Jan02 15:04" // Jun23 20:49
965// "Mon, 02 Jan 2006 15:04:05 MST"
966
967const defaultNewsTemplate = `From %s (%s):
968
969%s
970
971__________________________________________________________`
972
973// HandleTranOldPostNews updates the flat news
974// Fields used in this request:
975// 101 Data
976func HandleTranOldPostNews(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
977 cc.Server.flatNewsMux.Lock()
978 defer cc.Server.flatNewsMux.Unlock()
979
980 newsDateTemplate := defaultNewsDateFormat
981 if cc.Server.Config.NewsDateFormat != "" {
982 newsDateTemplate = cc.Server.Config.NewsDateFormat
983 }
984
985 newsTemplate := defaultNewsTemplate
986 if cc.Server.Config.NewsDelimiter != "" {
987 newsTemplate = cc.Server.Config.NewsDelimiter
988 }
989
72dd37f1 990 newsPost := fmt.Sprintf(newsTemplate+"\r", cc.UserName, time.Now().Format(newsDateTemplate), t.GetField(fieldData).Data)
6988a057
JH
991 newsPost = strings.Replace(newsPost, "\n", "\r", -1)
992
993 // update news in memory
994 cc.Server.FlatNews = append([]byte(newsPost), cc.Server.FlatNews...)
995
996 // update news on disk
997 if err := ioutil.WriteFile(cc.Server.ConfigDir+"MessageBoard.txt", cc.Server.FlatNews, 0644); err != nil {
998 return res, err
999 }
1000
1001 // Notify all clients of updated news
1002 cc.sendAll(
1003 tranNewMsg,
1004 NewField(fieldData, []byte(newsPost)),
1005 )
1006
1007 res = append(res, cc.NewReply(t))
1008 return res, err
1009}
1010
1011func HandleDisconnectUser(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1012 clientConn := cc.Server.Clients[binary.BigEndian.Uint16(t.GetField(fieldUserID).Data)]
1013
1014 if authorize(clientConn.Account.Access, accessCannotBeDiscon) {
1015 res = append(res, cc.NewErrReply(t, clientConn.Account.Login+" is not allowed to be disconnected."))
1016 return res, err
1017 }
1018
1019 if err := clientConn.Connection.Close(); err != nil {
1020 return res, err
1021 }
1022
1023 res = append(res, cc.NewReply(t))
1024 return res, err
1025}
1026
1027func HandleGetNewsCatNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1028 // Fields used in the request:
1029 // 325 News path (Optional)
1030
1031 newsPath := t.GetField(fieldNewsPath).Data
1032 cc.Server.Logger.Infow("NewsPath: ", "np", string(newsPath))
1033
1034 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1035 cats := cc.Server.GetNewsCatByPath(pathStrs)
1036
1037 // To store the keys in slice in sorted order
1038 keys := make([]string, len(cats))
1039 i := 0
1040 for k := range cats {
1041 keys[i] = k
1042 i++
1043 }
1044 sort.Strings(keys)
1045
1046 var fieldData []Field
1047 for _, k := range keys {
1048 cat := cats[k]
72dd37f1 1049 b, _ := cat.MarshalBinary()
6988a057
JH
1050 fieldData = append(fieldData, NewField(
1051 fieldNewsCatListData15,
72dd37f1 1052 b,
6988a057
JH
1053 ))
1054 }
1055
1056 res = append(res, cc.NewReply(t, fieldData...))
1057 return res, err
1058}
1059
1060func HandleNewNewsCat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1061 name := string(t.GetField(fieldNewsCatName).Data)
1062 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1063
1064 cats := cc.Server.GetNewsCatByPath(pathStrs)
1065 cats[name] = NewsCategoryListData15{
1066 Name: name,
1067 Type: []byte{0, 3},
1068 Articles: map[uint32]*NewsArtData{},
1069 SubCats: make(map[string]NewsCategoryListData15),
1070 }
1071
1072 if err := cc.Server.writeThreadedNews(); err != nil {
1073 return res, err
1074 }
1075 res = append(res, cc.NewReply(t))
1076 return res, err
1077}
1078
1079func HandleNewNewsFldr(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1080 // Fields used in the request:
1081 // 322 News category name
1082 // 325 News path
1083 name := string(t.GetField(fieldFileName).Data)
1084 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1085
1086 cc.Server.Logger.Infof("Creating new news folder %s", name)
1087
1088 cats := cc.Server.GetNewsCatByPath(pathStrs)
1089 cats[name] = NewsCategoryListData15{
1090 Name: name,
1091 Type: []byte{0, 2},
1092 Articles: map[uint32]*NewsArtData{},
1093 SubCats: make(map[string]NewsCategoryListData15),
1094 }
1095 if err := cc.Server.writeThreadedNews(); err != nil {
1096 return res, err
1097 }
1098 res = append(res, cc.NewReply(t))
1099 return res, err
1100}
1101
1102// Fields used in the request:
1103// 325 News path Optional
1104//
1105// Reply fields:
1106// 321 News article list data Optional
1107func HandleGetNewsArtNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1108 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1109
1110 var cat NewsCategoryListData15
1111 cats := cc.Server.ThreadedNews.Categories
1112
003a743e
JH
1113 for _, fp := range pathStrs {
1114 cat = cats[fp]
1115 cats = cats[fp].SubCats
6988a057
JH
1116 }
1117
1118 nald := cat.GetNewsArtListData()
1119
1120 res = append(res, cc.NewReply(t, NewField(fieldNewsArtListData, nald.Payload())))
1121 return res, err
1122}
1123
1124func HandleGetNewsArtData(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1125 // Request fields
003a743e 1126 // 325 News fp
6988a057
JH
1127 // 326 News article ID
1128 // 327 News article data flavor
1129
1130 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1131
1132 var cat NewsCategoryListData15
1133 cats := cc.Server.ThreadedNews.Categories
1134
003a743e
JH
1135 for _, fp := range pathStrs {
1136 cat = cats[fp]
1137 cats = cats[fp].SubCats
6988a057
JH
1138 }
1139 newsArtID := t.GetField(fieldNewsArtID).Data
1140
1141 convertedArtID := binary.BigEndian.Uint16(newsArtID)
1142
1143 art := cat.Articles[uint32(convertedArtID)]
1144 if art == nil {
1145 res = append(res, cc.NewReply(t))
1146 return res, err
1147 }
1148
1149 // Reply fields
1150 // 328 News article title
1151 // 329 News article poster
1152 // 330 News article date
1153 // 331 Previous article ID
1154 // 332 Next article ID
1155 // 335 Parent article ID
1156 // 336 First child article ID
1157 // 327 News article data flavor "Should be “text/plain”
1158 // 333 News article data Optional (if data flavor is “text/plain”)
1159
1160 res = append(res, cc.NewReply(t,
1161 NewField(fieldNewsArtTitle, []byte(art.Title)),
1162 NewField(fieldNewsArtPoster, []byte(art.Poster)),
1163 NewField(fieldNewsArtDate, art.Date),
1164 NewField(fieldNewsArtPrevArt, art.PrevArt),
1165 NewField(fieldNewsArtNextArt, art.NextArt),
1166 NewField(fieldNewsArtParentArt, art.ParentArt),
1167 NewField(fieldNewsArt1stChildArt, art.FirstChildArt),
1168 NewField(fieldNewsArtDataFlav, []byte("text/plain")),
1169 NewField(fieldNewsArtData, []byte(art.Data)),
1170 ))
1171 return res, err
1172}
1173
1174func HandleDelNewsItem(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1175 // Access: News Delete Folder (37) or News Delete Category (35)
1176
1177 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1178
1179 // TODO: determine if path is a Folder (Bundle) or Category and check for permission
1180
1181 cc.Server.Logger.Infof("DelNewsItem %v", pathStrs)
1182
1183 cats := cc.Server.ThreadedNews.Categories
1184
1185 delName := pathStrs[len(pathStrs)-1]
1186 if len(pathStrs) > 1 {
7e2e07da
JH
1187 for _, fp := range pathStrs[0 : len(pathStrs)-1] {
1188 cats = cats[fp].SubCats
6988a057
JH
1189 }
1190 }
1191
1192 delete(cats, delName)
1193
1194 err = cc.Server.writeThreadedNews()
1195 if err != nil {
1196 return res, err
1197 }
1198
1199 // Reply params: none
1200 res = append(res, cc.NewReply(t))
1201
1202 return res, err
1203}
1204
1205func HandleDelNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1206 // Request Fields
1207 // 325 News path
1208 // 326 News article ID
1209 // 337 News article – recursive delete Delete child articles (1) or not (0)
1210 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1211 ID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1212
1213 // TODO: Delete recursive
1214 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1215
1216 catName := pathStrs[len(pathStrs)-1]
1217 cat := cats[catName]
1218
1219 delete(cat.Articles, uint32(ID))
1220
1221 cats[catName] = cat
1222 if err := cc.Server.writeThreadedNews(); err != nil {
1223 return res, err
1224 }
1225
1226 res = append(res, cc.NewReply(t))
1227 return res, err
1228}
1229
1230func HandlePostNewsArt(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1231 // Request fields
1232 // 325 News path
1233 // 326 News article ID ID of the parent article?
1234 // 328 News article title
1235 // 334 News article flags
1236 // 327 News article data flavor Currently “text/plain”
1237 // 333 News article data
1238
1239 pathStrs := ReadNewsPath(t.GetField(fieldNewsPath).Data)
1240 cats := cc.Server.GetNewsCatByPath(pathStrs[:len(pathStrs)-1])
1241
1242 catName := pathStrs[len(pathStrs)-1]
1243 cat := cats[catName]
1244
1245 newArt := NewsArtData{
1246 Title: string(t.GetField(fieldNewsArtTitle).Data),
72dd37f1 1247 Poster: string(cc.UserName),
3c9b1dcd 1248 Date: toHotlineTime(time.Now()),
6988a057
JH
1249 PrevArt: []byte{0, 0, 0, 0},
1250 NextArt: []byte{0, 0, 0, 0},
1251 ParentArt: append([]byte{0, 0}, t.GetField(fieldNewsArtID).Data...),
1252 FirstChildArt: []byte{0, 0, 0, 0},
1253 DataFlav: []byte("text/plain"),
1254 Data: string(t.GetField(fieldNewsArtData).Data),
1255 }
1256
1257 var keys []int
1258 for k := range cat.Articles {
1259 keys = append(keys, int(k))
1260 }
1261
1262 nextID := uint32(1)
1263 if len(keys) > 0 {
1264 sort.Ints(keys)
1265 prevID := uint32(keys[len(keys)-1])
1266 nextID = prevID + 1
1267
1268 binary.BigEndian.PutUint32(newArt.PrevArt, prevID)
1269
1270 // Set next article ID
1271 binary.BigEndian.PutUint32(cat.Articles[prevID].NextArt, nextID)
1272 }
1273
1274 // Update parent article with first child reply
1275 parentID := binary.BigEndian.Uint16(t.GetField(fieldNewsArtID).Data)
1276 if parentID != 0 {
1277 parentArt := cat.Articles[uint32(parentID)]
1278
1279 if bytes.Equal(parentArt.FirstChildArt, []byte{0, 0, 0, 0}) {
1280 binary.BigEndian.PutUint32(parentArt.FirstChildArt, nextID)
1281 }
1282 }
1283
1284 cat.Articles[nextID] = &newArt
1285
1286 cats[catName] = cat
1287 if err := cc.Server.writeThreadedNews(); err != nil {
1288 return res, err
1289 }
1290
1291 res = append(res, cc.NewReply(t))
1292 return res, err
1293}
1294
1295// HandleGetMsgs returns the flat news data
1296func HandleGetMsgs(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
481631f6
JH
1297 if !authorize(cc.Account.Access, accessNewsReadArt) {
1298 res = append(res, cc.NewErrReply(t, "You are not allowed to read news."))
1299 return res, err
1300 }
1301
6988a057
JH
1302 res = append(res, cc.NewReply(t, NewField(fieldData, cc.Server.FlatNews)))
1303
1304 return res, err
1305}
1306
1307func HandleDownloadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
481631f6
JH
1308 if !authorize(cc.Account.Access, accessDownloadFile) {
1309 res = append(res, cc.NewErrReply(t, "You are not allowed to download files."))
1310 return res, err
1311 }
1312
6988a057 1313 fileName := t.GetField(fieldFileName).Data
92a7e455 1314 filePath := t.GetField(fieldFilePath).Data
6988a057 1315
16a4ad70
JH
1316 // 2 bytes
1317 // transferOptions := t.GetField(fieldFileTransferOptions).Data
1318 resumeData := t.GetField(fieldFileResumeData).Data
1319
1320 var dataOffset int64
1321 var frd FileResumeData
1322 if resumeData != nil {
1323 if err := frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data); err != nil {
1324 return res, err
1325 }
1326 dataOffset = int64(binary.BigEndian.Uint32(frd.ForkInfoList[0].DataSize[:]))
1327 }
1328
92a7e455
JH
1329 var fp FilePath
1330 err = fp.UnmarshalBinary(filePath)
1331 if err != nil {
1332 return res, err
1333 }
1334
16a4ad70 1335 ffo, err := NewFlattenedFileObject(cc.Server.Config.FileRoot, filePath, fileName, dataOffset)
6988a057
JH
1336 if err != nil {
1337 return res, err
1338 }
1339
1340 transactionRef := cc.Server.NewTransactionRef()
1341 data := binary.BigEndian.Uint32(transactionRef)
1342
6988a057
JH
1343 ft := &FileTransfer{
1344 FileName: fileName,
92a7e455 1345 FilePath: filePath,
6988a057
JH
1346 ReferenceNumber: transactionRef,
1347 Type: FileDownload,
1348 }
1349
16a4ad70
JH
1350 if resumeData != nil {
1351 var frd FileResumeData
1352 frd.UnmarshalBinary(t.GetField(fieldFileResumeData).Data)
1353 ft.fileResumeData = &frd
1354 }
1355
6988a057
JH
1356 cc.Server.FileTransfers[data] = ft
1357 cc.Transfers[FileDownload] = append(cc.Transfers[FileDownload], ft)
1358
1359 res = append(res, cc.NewReply(t,
1360 NewField(fieldRefNum, transactionRef),
1361 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1362 NewField(fieldTransferSize, ffo.TransferSize()),
85767504 1363 NewField(fieldFileSize, ffo.FlatFileDataForkHeader.DataSize[:]),
6988a057
JH
1364 ))
1365
1366 return res, err
1367}
1368
1369// Download all files from the specified folder and sub-folders
1370// response example
1371//
1372// 00
1373// 01
1374// 00 00
1375// 00 00 00 11
1376// 00 00 00 00
1377// 00 00 00 18
1378// 00 00 00 18
1379//
1380// 00 03
1381//
1382// 00 6c // transfer size
1383// 00 04 // len
1384// 00 0f d5 ae
1385//
1386// 00 dc // field Folder item count
1387// 00 02 // len
1388// 00 02
1389//
1390// 00 6b // ref number
1391// 00 04 // len
1392// 00 03 64 b1
1393func HandleDownloadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1394 transactionRef := cc.Server.NewTransactionRef()
1395 data := binary.BigEndian.Uint32(transactionRef)
1396
1397 fileTransfer := &FileTransfer{
1398 FileName: t.GetField(fieldFileName).Data,
1399 FilePath: t.GetField(fieldFilePath).Data,
1400 ReferenceNumber: transactionRef,
1401 Type: FolderDownload,
1402 }
1403 cc.Server.FileTransfers[data] = fileTransfer
1404 cc.Transfers[FolderDownload] = append(cc.Transfers[FolderDownload], fileTransfer)
1405
72dd37f1 1406 var fp FilePath
c5d9af5a
JH
1407 err = fp.UnmarshalBinary(t.GetField(fieldFilePath).Data)
1408 if err != nil {
1409 return res, err
1410 }
6988a057 1411
92a7e455 1412 fullFilePath, err := readPath(cc.Server.Config.FileRoot, t.GetField(fieldFilePath).Data, t.GetField(fieldFileName).Data)
aebc4d36
JH
1413 if err != nil {
1414 return res, err
1415 }
92a7e455 1416
6988a057
JH
1417 transferSize, err := CalcTotalSize(fullFilePath)
1418 if err != nil {
1419 return res, err
1420 }
1421 itemCount, err := CalcItemCount(fullFilePath)
1422 if err != nil {
1423 return res, err
1424 }
1425 res = append(res, cc.NewReply(t,
1426 NewField(fieldRefNum, transactionRef),
1427 NewField(fieldTransferSize, transferSize),
1428 NewField(fieldFolderItemCount, itemCount),
1429 NewField(fieldWaitingCount, []byte{0x00, 0x00}), // TODO: Implement waiting count
1430 ))
1431 return res, err
1432}
1433
1434// Upload all files from the local folder and its subfolders to the specified path on the server
1435// Fields used in the request
1436// 201 File name
1437// 202 File path
df2735b2 1438// 108 transfer size Total size of all items in the folder
6988a057
JH
1439// 220 Folder item count
1440// 204 File transfer options "Optional Currently set to 1" (TODO: ??)
1441func HandleUploadFolder(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1442 transactionRef := cc.Server.NewTransactionRef()
1443 data := binary.BigEndian.Uint32(transactionRef)
1444
7e2e07da
JH
1445 var fp FilePath
1446 if t.GetField(fieldFilePath).Data != nil {
1447 if err = fp.UnmarshalBinary(t.GetField(fieldFilePath).Data); err != nil {
1448 return res, err
1449 }
1450 }
1451
1452 // Handle special cases for Upload and Drop Box folders
1453 if !authorize(cc.Account.Access, accessUploadAnywhere) {
1454 if !fp.IsUploadDir() && !fp.IsDropbox() {
1455 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))))
1456 return res, err
1457 }
1458 }
1459
6988a057
JH
1460 fileTransfer := &FileTransfer{
1461 FileName: t.GetField(fieldFileName).Data,
1462 FilePath: t.GetField(fieldFilePath).Data,
1463 ReferenceNumber: transactionRef,
1464 Type: FolderUpload,
1465 FolderItemCount: t.GetField(fieldFolderItemCount).Data,
1466 TransferSize: t.GetField(fieldTransferSize).Data,
1467 }
1468 cc.Server.FileTransfers[data] = fileTransfer
1469
1470 res = append(res, cc.NewReply(t, NewField(fieldRefNum, transactionRef)))
1471 return res, err
1472}
1473
7e2e07da 1474// HandleUploadFile
16a4ad70
JH
1475// Fields used in the request:
1476// 201 File name
1477// 202 File path
1478// 204 File transfer options "Optional
1479// Used only to resume download, currently has value 2"
1480// 108 File transfer size "Optional used if download is not resumed"
6988a057 1481func HandleUploadFile(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
a0241c25
JH
1482 if !authorize(cc.Account.Access, accessUploadFile) {
1483 res = append(res, cc.NewErrReply(t, "You are not allowed to upload files."))
1484 return res, err
1485 }
1486
6988a057
JH
1487 fileName := t.GetField(fieldFileName).Data
1488 filePath := t.GetField(fieldFilePath).Data
1489
16a4ad70
JH
1490 transferOptions := t.GetField(fieldFileTransferOptions).Data
1491
1492 // TODO: is this field useful for anything?
1493 // transferSize := t.GetField(fieldTransferSize).Data
1494
7e2e07da
JH
1495 var fp FilePath
1496 if filePath != nil {
1497 if err = fp.UnmarshalBinary(filePath); err != nil {
1498 return res, err
1499 }
1500 }
1501
1502 // Handle special cases for Upload and Drop Box folders
1503 if !authorize(cc.Account.Access, accessUploadAnywhere) {
1504 if !fp.IsUploadDir() && !fp.IsDropbox() {
1505 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))))
1506 return res, err
1507 }
1508 }
1509
6988a057
JH
1510 transactionRef := cc.Server.NewTransactionRef()
1511 data := binary.BigEndian.Uint32(transactionRef)
1512
a0241c25 1513 cc.Server.FileTransfers[data] = &FileTransfer{
6988a057
JH
1514 FileName: fileName,
1515 FilePath: filePath,
1516 ReferenceNumber: transactionRef,
1517 Type: FileUpload,
1518 }
1519
16a4ad70
JH
1520 replyT := cc.NewReply(t, NewField(fieldRefNum, transactionRef))
1521
1522 // client has requested to resume a partially transfered file
1523 if transferOptions != nil {
1524 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1525 if err != nil {
1526 return res, err
1527 }
1528
1529 fileInfo, err := FS.Stat(fullFilePath + incompleteFileSuffix)
1530 if err != nil {
1531 return res, err
1532 }
1533
1534 offset := make([]byte, 4)
1535 binary.BigEndian.PutUint32(offset, uint32(fileInfo.Size()))
1536
1537 fileResumeData := NewFileResumeData([]ForkInfoList{
1538 *NewForkInfoList(offset),
1539 })
1540
1541 b, _ := fileResumeData.BinaryMarshal()
1542
1543 replyT.Fields = append(replyT.Fields, NewField(fieldFileResumeData, b))
1544 }
1545
1546 res = append(res, replyT)
6988a057
JH
1547 return res, err
1548}
1549
6988a057
JH
1550func HandleSetClientUserInfo(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1551 var icon []byte
1552 if len(t.GetField(fieldUserIconID).Data) == 4 {
1553 icon = t.GetField(fieldUserIconID).Data[2:]
1554 } else {
1555 icon = t.GetField(fieldUserIconID).Data
1556 }
1557 *cc.Icon = icon
72dd37f1 1558 cc.UserName = t.GetField(fieldUserName).Data
6988a057
JH
1559
1560 // the options field is only passed by the client versions > 1.2.3.
1561 options := t.GetField(fieldOptions).Data
1562
1563 if options != nil {
1564 optBitmap := big.NewInt(int64(binary.BigEndian.Uint16(options)))
1565 flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(*cc.Flags)))
1566
7f12122f
JH
1567 flagBitmap.SetBit(flagBitmap, userFlagRefusePM, optBitmap.Bit(refusePM))
1568 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
6988a057 1569
7f12122f
JH
1570 flagBitmap.SetBit(flagBitmap, userFLagRefusePChat, optBitmap.Bit(refuseChat))
1571 binary.BigEndian.PutUint16(*cc.Flags, uint16(flagBitmap.Int64()))
6988a057
JH
1572
1573 // Check auto response
1574 if optBitmap.Bit(autoResponse) == 1 {
aebc4d36 1575 cc.AutoReply = t.GetField(fieldAutomaticResponse).Data
6988a057 1576 } else {
aebc4d36 1577 cc.AutoReply = []byte{}
6988a057
JH
1578 }
1579 }
1580
1581 // Notify all clients of updated user info
1582 cc.sendAll(
1583 tranNotifyChangeUser,
1584 NewField(fieldUserID, *cc.ID),
1585 NewField(fieldUserIconID, *cc.Icon),
1586 NewField(fieldUserFlags, *cc.Flags),
72dd37f1 1587 NewField(fieldUserName, cc.UserName),
6988a057
JH
1588 )
1589
1590 return res, err
1591}
1592
61c272e1
JH
1593// HandleKeepAlive responds to keepalive transactions with an empty reply
1594// * HL 1.9.2 Client sends keepalive msg every 3 minutes
1595// * HL 1.2.3 Client doesn't send keepalives
6988a057
JH
1596func HandleKeepAlive(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1597 res = append(res, cc.NewReply(t))
1598
1599 return res, err
1600}
1601
1602func HandleGetFileNameList(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
92a7e455
JH
1603 fullPath, err := readPath(
1604 cc.Server.Config.FileRoot,
1605 t.GetField(fieldFilePath).Data,
1606 nil,
1607 )
1608 if err != nil {
1609 return res, err
6988a057
JH
1610 }
1611
7e2e07da
JH
1612 var fp FilePath
1613 if t.GetField(fieldFilePath).Data != nil {
1614 if err = fp.UnmarshalBinary(t.GetField(fieldFilePath).Data); err != nil {
1615 return res, err
1616 }
1617 }
1618
1619 // Handle special case for drop box folders
1620 if fp.IsDropbox() && !authorize(cc.Account.Access, accessViewDropBoxes) {
1621 res = append(res, cc.NewReply(t))
1622 return res, err
1623 }
1624
92a7e455 1625 fileNames, err := getFileNameList(fullPath)
6988a057
JH
1626 if err != nil {
1627 return res, err
1628 }
1629
1630 res = append(res, cc.NewReply(t, fileNames...))
1631
1632 return res, err
1633}
1634
1635// =================================
1636// Hotline private chat flow
1637// =================================
1638// 1. ClientA sends tranInviteNewChat to server with user ID to invite
1639// 2. Server creates new ChatID
1640// 3. Server sends tranInviteToChat to invitee
1641// 4. Server replies to ClientA with new Chat ID
1642//
1643// A dialog box pops up in the invitee client with options to accept or decline the invitation.
1644// If Accepted is clicked:
1645// 1. ClientB sends tranJoinChat with fieldChatID
1646
1647// HandleInviteNewChat invites users to new private chat
1648func HandleInviteNewChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1649 // Client to Invite
1650 targetID := t.GetField(fieldUserID).Data
1651 newChatID := cc.Server.NewPrivateChat(cc)
1652
1653 res = append(res,
1654 *NewTransaction(
1655 tranInviteToChat,
1656 &targetID,
1657 NewField(fieldChatID, newChatID),
72dd37f1 1658 NewField(fieldUserName, cc.UserName),
6988a057
JH
1659 NewField(fieldUserID, *cc.ID),
1660 ),
1661 )
1662
1663 res = append(res,
1664 cc.NewReply(t,
1665 NewField(fieldChatID, newChatID),
72dd37f1 1666 NewField(fieldUserName, cc.UserName),
6988a057
JH
1667 NewField(fieldUserID, *cc.ID),
1668 NewField(fieldUserIconID, *cc.Icon),
1669 NewField(fieldUserFlags, *cc.Flags),
1670 ),
1671 )
1672
1673 return res, err
1674}
1675
1676func HandleInviteToChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1677 // Client to Invite
1678 targetID := t.GetField(fieldUserID).Data
1679 chatID := t.GetField(fieldChatID).Data
1680
1681 res = append(res,
1682 *NewTransaction(
1683 tranInviteToChat,
1684 &targetID,
1685 NewField(fieldChatID, chatID),
72dd37f1 1686 NewField(fieldUserName, cc.UserName),
6988a057
JH
1687 NewField(fieldUserID, *cc.ID),
1688 ),
1689 )
1690 res = append(res,
1691 cc.NewReply(
1692 t,
1693 NewField(fieldChatID, chatID),
72dd37f1 1694 NewField(fieldUserName, cc.UserName),
6988a057
JH
1695 NewField(fieldUserID, *cc.ID),
1696 NewField(fieldUserIconID, *cc.Icon),
1697 NewField(fieldUserFlags, *cc.Flags),
1698 ),
1699 )
1700
1701 return res, err
1702}
1703
1704func HandleRejectChatInvite(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1705 chatID := t.GetField(fieldChatID).Data
1706 chatInt := binary.BigEndian.Uint32(chatID)
1707
1708 privChat := cc.Server.PrivateChats[chatInt]
1709
72dd37f1 1710 resMsg := append(cc.UserName, []byte(" declined invitation to chat")...)
6988a057
JH
1711
1712 for _, c := range sortedClients(privChat.ClientConn) {
1713 res = append(res,
1714 *NewTransaction(
1715 tranChatMsg,
1716 c.ID,
1717 NewField(fieldChatID, chatID),
1718 NewField(fieldData, resMsg),
1719 ),
1720 )
1721 }
1722
1723 return res, err
1724}
1725
1726// HandleJoinChat is sent from a v1.8+ Hotline client when the joins a private chat
1727// Fields used in the reply:
1728// * 115 Chat subject
1729// * 300 User name with info (Optional)
1730// * 300 (more user names with info)
1731func HandleJoinChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1732 chatID := t.GetField(fieldChatID).Data
1733 chatInt := binary.BigEndian.Uint32(chatID)
1734
1735 privChat := cc.Server.PrivateChats[chatInt]
1736
1737 // Send tranNotifyChatChangeUser to current members of the chat to inform of new user
1738 for _, c := range sortedClients(privChat.ClientConn) {
1739 res = append(res,
1740 *NewTransaction(
1741 tranNotifyChatChangeUser,
1742 c.ID,
1743 NewField(fieldChatID, chatID),
72dd37f1 1744 NewField(fieldUserName, cc.UserName),
6988a057
JH
1745 NewField(fieldUserID, *cc.ID),
1746 NewField(fieldUserIconID, *cc.Icon),
1747 NewField(fieldUserFlags, *cc.Flags),
1748 ),
1749 )
1750 }
1751
1752 privChat.ClientConn[cc.uint16ID()] = cc
1753
1754 replyFields := []Field{NewField(fieldChatSubject, []byte(privChat.Subject))}
1755 for _, c := range sortedClients(privChat.ClientConn) {
1756 user := User{
1757 ID: *c.ID,
1758 Icon: *c.Icon,
1759 Flags: *c.Flags,
72dd37f1 1760 Name: string(c.UserName),
6988a057
JH
1761 }
1762
1763 replyFields = append(replyFields, NewField(fieldUsernameWithInfo, user.Payload()))
1764 }
1765
1766 res = append(res, cc.NewReply(t, replyFields...))
1767 return res, err
1768}
1769
1770// HandleLeaveChat is sent from a v1.8+ Hotline client when the user exits a private chat
1771// Fields used in the request:
1772// * 114 fieldChatID
1773// Reply is not expected.
1774func HandleLeaveChat(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1775 chatID := t.GetField(fieldChatID).Data
1776 chatInt := binary.BigEndian.Uint32(chatID)
1777
1778 privChat := cc.Server.PrivateChats[chatInt]
1779
1780 delete(privChat.ClientConn, cc.uint16ID())
1781
1782 // Notify members of the private chat that the user has left
1783 for _, c := range sortedClients(privChat.ClientConn) {
1784 res = append(res,
1785 *NewTransaction(
1786 tranNotifyChatDeleteUser,
1787 c.ID,
1788 NewField(fieldChatID, chatID),
1789 NewField(fieldUserID, *cc.ID),
1790 ),
1791 )
1792 }
1793
1794 return res, err
1795}
1796
1797// HandleSetChatSubject is sent from a v1.8+ Hotline client when the user sets a private chat subject
1798// Fields used in the request:
1799// * 114 Chat ID
1800// * 115 Chat subject Chat subject string
1801// Reply is not expected.
1802func HandleSetChatSubject(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1803 chatID := t.GetField(fieldChatID).Data
1804 chatInt := binary.BigEndian.Uint32(chatID)
1805
1806 privChat := cc.Server.PrivateChats[chatInt]
1807 privChat.Subject = string(t.GetField(fieldChatSubject).Data)
1808
1809 for _, c := range sortedClients(privChat.ClientConn) {
1810 res = append(res,
1811 *NewTransaction(
1812 tranNotifyChatSubject,
1813 c.ID,
1814 NewField(fieldChatID, chatID),
1815 NewField(fieldChatSubject, t.GetField(fieldChatSubject).Data),
1816 ),
1817 )
1818 }
1819
1820 return res, err
1821}
decc2fbf
JH
1822
1823// HandleMakeAlias makes a file alias using the specified path.
1824// Fields used in the request:
1825// 201 File name
1826// 202 File path
1827// 212 File new path Destination path
1828//
1829// Fields used in the reply:
1830// None
1831func HandleMakeAlias(cc *ClientConn, t *Transaction) (res []Transaction, err error) {
1832 if !authorize(cc.Account.Access, accessMakeAlias) {
1833 res = append(res, cc.NewErrReply(t, "You are not allowed to make aliases."))
1834 return res, err
1835 }
1836 fileName := t.GetField(fieldFileName).Data
1837 filePath := t.GetField(fieldFilePath).Data
1838 fileNewPath := t.GetField(fieldFileNewPath).Data
1839
1840 fullFilePath, err := readPath(cc.Server.Config.FileRoot, filePath, fileName)
1841 if err != nil {
1842 return res, err
1843 }
1844
1845 fullNewFilePath, err := readPath(cc.Server.Config.FileRoot, fileNewPath, fileName)
1846 if err != nil {
1847 return res, err
1848 }
1849
1850 cc.Server.Logger.Debugw("Make alias", "src", fullFilePath, "dst", fullNewFilePath)
1851
1852 if err := FS.Symlink(fullFilePath, fullNewFilePath); err != nil {
1853 res = append(res, cc.NewErrReply(t, "Error creating alias"))
1854 return res, nil
1855 }
1856
1857 res = append(res, cc.NewReply(t))
1858 return res, err
1859}