]> git.r.bdr.sh - rbdr/mobius/blob - hotline/transaction.go
Fix panic on empty news path
[rbdr/mobius] / hotline / transaction.go
1 package hotline
2
3 import (
4 "bufio"
5 "bytes"
6 "encoding/binary"
7 "errors"
8 "fmt"
9 "io"
10 "math/rand"
11 "slices"
12 )
13
14 type TranType [2]byte
15
16 var (
17 TranError = TranType{0x00, 0x00} // 0
18 TranGetMsgs = TranType{0x00, 0x65} // 101
19 TranNewMsg = TranType{0x00, 0x66} // 102
20 TranOldPostNews = TranType{0x00, 0x67} // 103
21 TranServerMsg = TranType{0x00, 0x68} // 104
22 TranChatSend = TranType{0x00, 0x69} // 105
23 TranChatMsg = TranType{0x00, 0x6A} // 106
24 TranLogin = TranType{0x00, 0x6B} // 107
25 TranSendInstantMsg = TranType{0x00, 0x6C} // 108
26 TranShowAgreement = TranType{0x00, 0x6D} // 109
27 TranDisconnectUser = TranType{0x00, 0x6E} // 110
28 TranDisconnectMsg = TranType{0x00, 0x6F} // 111
29 TranInviteNewChat = TranType{0x00, 0x70} // 112
30 TranInviteToChat = TranType{0x00, 0x71} // 113
31 TranRejectChatInvite = TranType{0x00, 0x72} // 114
32 TranJoinChat = TranType{0x00, 0x73} // 115
33 TranLeaveChat = TranType{0x00, 0x74} // 116
34 TranNotifyChatChangeUser = TranType{0x00, 0x75} // 117
35 TranNotifyChatDeleteUser = TranType{0x00, 0x76} // 118
36 TranNotifyChatSubject = TranType{0x00, 0x77} // 119
37 TranSetChatSubject = TranType{0x00, 0x78} // 120
38 TranAgreed = TranType{0x00, 0x79} // 121
39 TranServerBanner = TranType{0x00, 0x7A} // 122
40 TranGetFileNameList = TranType{0x00, 0xC8} // 200
41 TranDownloadFile = TranType{0x00, 0xCA} // 202
42 TranUploadFile = TranType{0x00, 0xCB} // 203
43 TranNewFolder = TranType{0x00, 0xCD} // 205
44 TranDeleteFile = TranType{0x00, 0xCC} // 204
45 TranGetFileInfo = TranType{0x00, 0xCE} // 206
46 TranSetFileInfo = TranType{0x00, 0xCF} // 207
47 TranMoveFile = TranType{0x00, 0xD0} // 208
48 TranMakeFileAlias = TranType{0x00, 0xD1} // 209
49 TranDownloadFldr = TranType{0x00, 0xD2} // 210
50 TranDownloadInfo = TranType{0x00, 0xD3} // 211
51 TranDownloadBanner = TranType{0x00, 0xD4} // 212
52 TranUploadFldr = TranType{0x00, 0xD5} // 213
53 TranGetUserNameList = TranType{0x01, 0x2C} // 300
54 TranNotifyChangeUser = TranType{0x01, 0x2D} // 301
55 TranNotifyDeleteUser = TranType{0x01, 0x2E} // 302
56 TranGetClientInfoText = TranType{0x01, 0x2F} // 303
57 TranSetClientUserInfo = TranType{0x01, 0x30} // 304
58 TranListUsers = TranType{0x01, 0x5C} // 348
59 TranUpdateUser = TranType{0x01, 0x5D} // 349
60 TranNewUser = TranType{0x01, 0x5E} // 350
61 TranDeleteUser = TranType{0x01, 0x5F} // 351
62 TranGetUser = TranType{0x01, 0x60} // 352
63 TranSetUser = TranType{0x01, 0x61} // 353
64 TranUserAccess = TranType{0x01, 0x62} // 354
65 TranUserBroadcast = TranType{0x01, 0x63} // 355
66 TranGetNewsCatNameList = TranType{0x01, 0x72} // 370
67 TranGetNewsArtNameList = TranType{0x01, 0x73} // 371
68 TranDelNewsItem = TranType{0x01, 0x7C} // 380
69 TranNewNewsFldr = TranType{0x01, 0x7D} // 381
70 TranNewNewsCat = TranType{0x01, 0x7E} // 382
71 TranGetNewsArtData = TranType{0x01, 0x90} // 400
72 TranPostNewsArt = TranType{0x01, 0x9A} // 410
73 TranDelNewsArt = TranType{0x01, 0x9B} // 411
74 TranKeepAlive = TranType{0x01, 0xF4} // 500
75 )
76
77 type Transaction struct {
78 Flags byte // Reserved (should be 0)
79 IsReply byte // Request (0) or reply (1)
80 Type TranType // Requested operation (user defined)
81 ID [4]byte // Unique transaction ID (must be != 0)
82 ErrorCode [4]byte // Used in the reply (user defined, 0 = no error)
83 TotalSize [4]byte // Total data size for the fields in this transaction.
84 DataSize [4]byte // Size of data in this transaction part. This allows splitting large transactions into smaller parts.
85 ParamCount [2]byte // Number of the parameters for this transaction
86 Fields []Field
87
88 ClientID ClientID // Internal identifier for target client
89 readOffset int // Internal offset to track read progress
90 }
91
92 var tranTypeNames = map[TranType]string{
93 TranChatMsg: "Receive chat",
94 TranNotifyChangeUser: "User change",
95 TranError: "Error",
96 TranShowAgreement: "Show agreement",
97 TranUserAccess: "User access",
98 TranNotifyDeleteUser: "User left",
99 TranAgreed: "Accept agreement",
100 TranChatSend: "Send chat",
101 TranDelNewsArt: "Delete news article",
102 TranDelNewsItem: "Delete news item",
103 TranDeleteFile: "Delete file",
104 TranDeleteUser: "Delete user",
105 TranDisconnectUser: "Disconnect user",
106 TranDownloadFile: "Download file",
107 TranDownloadFldr: "Download folder",
108 TranGetClientInfoText: "Get client info",
109 TranGetFileInfo: "Get file info",
110 TranGetFileNameList: "Get file list",
111 TranGetMsgs: "Get messages",
112 TranGetNewsArtData: "Get news article",
113 TranGetNewsArtNameList: "Get news article list",
114 TranGetNewsCatNameList: "Get news categories",
115 TranGetUser: "Get user",
116 TranGetUserNameList: "Get user list",
117 TranInviteNewChat: "Invite to new chat",
118 TranInviteToChat: "Invite to chat",
119 TranJoinChat: "Join chat",
120 TranKeepAlive: "Keepalive",
121 TranLeaveChat: "Leave chat",
122 TranListUsers: "List user accounts",
123 TranMoveFile: "Move file",
124 TranNewFolder: "Create folder",
125 TranNewNewsCat: "Create news category",
126 TranNewNewsFldr: "Create news bundle",
127 TranNewUser: "Create user account",
128 TranUpdateUser: "Update user account",
129 TranOldPostNews: "Post to message board",
130 TranPostNewsArt: "Create news article",
131 TranRejectChatInvite: "Decline chat invite",
132 TranSendInstantMsg: "Send message",
133 TranSetChatSubject: "Set chat subject",
134 TranMakeFileAlias: "Make file alias",
135 TranSetClientUserInfo: "Set client user info",
136 TranSetFileInfo: "Set file info",
137 TranSetUser: "Set user",
138 TranUploadFile: "Upload file",
139 TranUploadFldr: "Upload folder",
140 TranUserBroadcast: "Send broadcast",
141 TranDownloadBanner: "Download banner",
142 }
143
144 // NewTransaction creates a new Transaction with the specified type, client, and optional fields.
145 func NewTransaction(t TranType, clientID ClientID, fields ...Field) Transaction {
146 transaction := Transaction{
147 Type: t,
148 ClientID: clientID,
149 Fields: fields,
150 }
151
152 // Give the transaction a random ID.
153 binary.BigEndian.PutUint32(transaction.ID[:], rand.Uint32())
154
155 return transaction
156 }
157
158 // Write implements io.Writer interface for Transaction.
159 // Transactions read from the network are read as complete tokens with a bufio.Scanner, so
160 // the arg p is guaranteed to have the full byte payload of a complete transaction.
161 func (t *Transaction) Write(p []byte) (n int, err error) {
162 // Make sure we have the minimum number of bytes for a transaction.
163 if len(p) < 22 {
164 return 0, errors.New("buffer too small")
165 }
166
167 // Read the total size field.
168 totalSize := binary.BigEndian.Uint32(p[12:16])
169 tranLen := int(20 + totalSize)
170
171 paramCount := binary.BigEndian.Uint16(p[20:22])
172
173 t.Flags = p[0]
174 t.IsReply = p[1]
175 copy(t.Type[:], p[2:4])
176 copy(t.ID[:], p[4:8])
177 copy(t.ErrorCode[:], p[8:12])
178 copy(t.TotalSize[:], p[12:16])
179 copy(t.DataSize[:], p[16:20])
180 copy(t.ParamCount[:], p[20:22])
181
182 scanner := bufio.NewScanner(bytes.NewReader(p[22:tranLen]))
183 scanner.Split(FieldScanner)
184
185 for i := 0; i < int(paramCount); i++ {
186 if !scanner.Scan() {
187 return 0, fmt.Errorf("error scanning field: %w", scanner.Err())
188 }
189
190 var field Field
191 if _, err := field.Write(scanner.Bytes()); err != nil {
192 return 0, fmt.Errorf("error reading field: %w", err)
193 }
194 t.Fields = append(t.Fields, field)
195 }
196
197 if err := scanner.Err(); err != nil {
198 return 0, fmt.Errorf("scanner error: %w", err)
199 }
200
201 return len(p), nil
202 }
203
204 const tranHeaderLen = 20 // fixed length of transaction fields before the variable length fields
205
206 // transactionScanner implements bufio.SplitFunc for parsing incoming byte slices into complete tokens
207 func transactionScanner(data []byte, _ bool) (advance int, token []byte, err error) {
208 // The bytes that contain the size of a transaction are from 12:16, so we need at least 16 bytes
209 if len(data) < 16 {
210 return 0, nil, nil
211 }
212
213 totalSize := binary.BigEndian.Uint32(data[12:16])
214
215 // tranLen represents the length of bytes that are part of the transaction
216 tranLen := int(tranHeaderLen + totalSize)
217 if tranLen > len(data) {
218 return 0, nil, nil
219 }
220
221 return tranLen, data[0:tranLen], nil
222 }
223
224 const minFieldLen = 4
225
226 // Read implements the io.Reader interface for Transaction
227 func (t *Transaction) Read(p []byte) (int, error) {
228 payloadSize := t.Size()
229
230 fieldCount := make([]byte, 2)
231 binary.BigEndian.PutUint16(fieldCount, uint16(len(t.Fields)))
232
233 bbuf := new(bytes.Buffer)
234
235 for _, field := range t.Fields {
236 f := field
237 _, err := bbuf.ReadFrom(&f)
238 if err != nil {
239 return 0, fmt.Errorf("error reading field: %w", err)
240 }
241 }
242
243 buf := slices.Concat(
244 []byte{t.Flags, t.IsReply},
245 t.Type[:],
246 t.ID[:],
247 t.ErrorCode[:],
248 payloadSize,
249 payloadSize, // this is the dataSize field, but seeming the same as totalSize
250 fieldCount,
251 bbuf.Bytes(),
252 )
253
254 if t.readOffset >= len(buf) {
255 return 0, io.EOF // All bytes have been read
256 }
257
258 n := copy(p, buf[t.readOffset:])
259 t.readOffset += n
260
261 return n, nil
262 }
263
264 // Size returns the total size of the transaction payload
265 func (t *Transaction) Size() []byte {
266 bs := make([]byte, 4)
267
268 fieldSize := 0
269 for _, field := range t.Fields {
270 fieldSize += len(field.Data) + 4
271 }
272
273 binary.BigEndian.PutUint32(bs, uint32(fieldSize+2))
274
275 return bs
276 }
277
278 func (t *Transaction) GetField(id [2]byte) *Field {
279 for _, field := range t.Fields {
280 if id == field.Type {
281 return &field
282 }
283 }
284
285 return &Field{}
286 }