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