-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsfutil.go
474 lines (400 loc) · 10.4 KB
/
csfutil.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
package csfutil
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"os"
"strings"
)
// A CSFUtil provides some basic methods for accessing a CSF file.
// The zero value of CSFUtil cannot be used and may cause nil pointer panic,
// always use Open() to open a file.
type CSFUtil struct {
dword []byte // buffer for read uint values
// file holds a temporary reference to the underlying CSF file while
// reading contents.
file *os.File
// name of currently opening file
filename string
Version uint // CSF file Version section
NumLabels uint // CSF file NumLabels section
NumStrings uint // CSF file NumStrings section
Unused uint // CSF file (unused) section
Language uint // CSF file Language section
// Values holds all CSF LabelValue pair, uses capitalized CSF Label name
// as map key
Values map[string]LabelValue
// Categories holds CSF Label categories -> CSF Label Name map, uses
// capitalized category name as map key
Categories map[string][]string
// Order stores original CSF Label order according to the CSF file, in
// capitalized form.
Order []string
}
// pos returns current reading position.
func (r *CSFUtil) pos() uint {
offset, err := r.file.Seek(0, io.SeekCurrent)
if err != nil {
panic(err)
}
return uint(offset)
}
// read reads next size bytes and return them.
func (r *CSFUtil) read(size uint) ([]byte, error) {
b := make([]byte, size)
n, err := r.file.Read(b)
if err != nil {
return nil, err
}
if uint(n) != size {
return b, fmt.Errorf("not enough data, want [%d]byte, got [%d]byte", size, n)
}
return b, nil
}
// readDWORD reads the next 4 bytes and return them.
func (r *CSFUtil) readDWORD() ([]byte, error) {
n, err := r.file.Read(r.dword)
if err != nil {
return nil, err
}
if n != 4 {
return nil, fmt.Errorf("not a dword value")
}
return r.dword, nil
}
// readUInt reads the next DWORD and return them.
func (r *CSFUtil) readUInt() (uint, error) {
_, err := r.readDWORD()
if err != nil {
return 0, err
}
return uint(binary.LittleEndian.Uint32(r.dword)), nil
}
// checkIdentifier checks if the following 4 bytes is presented in the given
// identifier array.
func (r *CSFUtil) checkIdentifier(ids ...string) error {
_, err := r.readDWORD()
if err != nil {
return err
}
for _, id := range ids {
if bytes.Equal(r.dword, []byte(id)) {
return nil
}
}
return fmt.Errorf("not a valid identifier, want %v, got `%s`", ids, string(r.dword))
}
// readHeader reads and parse CSF file header for later use.
func (r *CSFUtil) readHeader() error {
var i uint
var err error
// file header
if err := r.checkIdentifier(CSFFileIdentifier); err != nil {
return fmt.Errorf("not a valid CSF file, reason: %w at %x", err, r.pos())
}
// file version
i, err = r.readUInt()
if err != nil {
return err
}
r.Version = i
// num labels
i, err = r.readUInt()
if err != nil {
return err
}
r.NumLabels = i
// num strings
i, err = r.readUInt()
if err != nil {
return err
}
r.NumStrings = i
// unused
i, err = r.readUInt()
if err != nil {
return err
}
r.Unused = i
// language
i, err = r.readUInt()
if err != nil {
return err
}
r.Language = i
return nil
}
// readLabel reads the following CSF Label and returns.
func (r *CSFUtil) readLabel() (Label, error) {
offset := r.pos()
if err := r.checkIdentifier(LabelIdentifier); err != nil {
return Label{}, fmt.Errorf("not a valid label start, reason: %w at %x", err, offset)
}
pairs, err := r.readUInt()
if err != nil {
return Label{}, err
}
length, err := r.readUInt()
if err != nil {
return Label{}, err
}
value, err := r.read(length)
if err != nil {
return Label{}, err
}
lbl := Label{
Offset: offset,
StringPairs: pairs,
Value: value,
}
return lbl, nil
}
// readValue reads the following CSF Value and returns.
func (r *CSFUtil) readValue() (Value, error) {
offset := r.pos()
if err := r.checkIdentifier(ValueIdentifier, ValueWithExtraIdentifier); err != nil {
return Value{}, fmt.Errorf("not a valid value start, reason: %w, at %x", err, offset)
}
hasExtra := bytes.Equal(r.dword, []byte("WRTS"))
length, err := r.readUInt()
if err != nil {
return Value{}, err
}
value, err := r.read(length * 2)
if err != nil {
return Value{}, err
}
var extraVal []byte
if hasExtra {
extraLength, err := r.readUInt()
extraVal, err = r.read(extraLength)
if err != nil {
return Value{}, err
}
}
val := Value{
Offset: offset,
HaveExtra: hasExtra,
Value: value,
ExtraValue: extraVal,
}
return val, nil
}
// readContent reads the CSF file till end and store all parsed
// CSF LabelValue pairs into Values map.
func (r *CSFUtil) readContent() error {
mapLabelValue := map[string]LabelValue{}
mapCate := map[string][]string{}
listOrder := []string{}
counter := 0
for {
label, err := r.readLabel()
if err != nil {
if errors.Is(err, io.EOF) {
break
} else {
return err
}
}
value, err := r.readValue()
if err != nil {
if errors.Is(err, io.EOF) {
break
} else {
return err
}
}
labelName := label.ValueString()
upperLabelName := strings.ToUpper(labelName)
// make sure entries in Categories and Order are unique
if _, ok := mapLabelValue[upperLabelName]; !ok {
// ignore Labels that don't have a category
if strings.Contains(upperLabelName, ":") {
categoryName := upperLabelName[0:strings.Index(upperLabelName, ":")]
if list, ok := mapCate[categoryName]; ok {
mapCate[categoryName] = append(list, labelName)
} else {
mapCate[categoryName] = []string{}
}
} else {
if list, ok := mapCate[""]; ok {
mapCate[""] = append(list, labelName)
} else {
mapCate[""] = []string{}
}
}
listOrder = append(listOrder, upperLabelName)
}
lv := LabelValue{Label: label, Value: value}
mapLabelValue[upperLabelName] = lv
counter++
if counter > 20000 {
return fmt.Errorf("too many strings")
}
}
r.Values = mapLabelValue
r.Categories = mapCate
r.Order = listOrder
return nil
}
// openAndParse open and parses the named file.
// Must be called before using CSFUtil.
func (r *CSFUtil) openAndParse(name string) error {
f, err := os.OpenFile(name, os.O_RDONLY, 0)
if err != nil {
return err
}
defer f.Close()
// initialization
r.file = f
r.dword = make([]byte, 4)
// read file as ModEnc suggests
if err := r.readHeader(); err != nil {
return err
}
if err := r.readContent(); err != nil {
return err
}
return nil
}
// LanguageName returns language name of current CSF file, if not in the list,
// "Unknown" is returned.
func (r *CSFUtil) LanguageName() string {
if r.Language > 9 {
return Languages[10]
} else {
return Languages[r.Language]
}
}
// PrintAll prints all LabelValue pairs stored in Values in
// "LABELNAME (upper case) => LabelName -> Value , ExtraValue" format.
// Mainly for debug purpose.
func (r *CSFUtil) PrintAll() {
for label, labelValue := range r.Values {
fmt.Println(label, "=>", labelValue)
}
}
// WriteLabelValue do the same as WriteLabelValueAfter() does, but will
// always write at file end if no old CSF Label presents.
func (r *CSFUtil) WriteLabelValue(lv LabelValue, overwriteLabel bool) {
r.WriteLabelValueBefore(lv, overwriteLabel, "")
}
// WriteLabelValueBefore writes given CSF LabelValue pair into the file, will
// overwrite and preserve order if old CSF Label presents, otherwise will write
// before given label. If the given label is not found, then it will write at
// file end.
func (r *CSFUtil) WriteLabelValueBefore(lv LabelValue, overwriteLabel bool, successor string) {
successorUpper := strings.ToUpper(successor)
labelNameUpper := strings.ToUpper(lv.Label.ValueString())
if _, ok := r.Values[labelNameUpper]; ok {
// overwrite exist, preserve original order
if !overwriteLabel {
lv.Label.Write(r.Values[labelNameUpper].Label.ValueString())
}
} else if _, ok := r.Values[successorUpper]; ok {
// new in the middle
pos := len(r.Order)
l := pos
for i, s := range r.Order {
if s == successorUpper {
pos = i
}
}
r.Order = append(append(r.Order[0:pos], labelNameUpper), r.Order[pos:l]...)
} else {
// new at the end
r.Order = append(r.Order, labelNameUpper)
}
r.Values[labelNameUpper] = lv
r.NumLabels = uint(len(r.Values))
r.NumStrings = uint(len(r.Values))
}
// RemoveLabelValue is used to eliminate the given CSF LabelValue
func (r *CSFUtil) RemoveLabelValue(name string) {
if len(r.Order) == 0 {
return
} else {
upperName := strings.ToUpper(name)
delete(r.Values, upperName)
for i, s := range r.Order {
if s == upperName {
if len(r.Order) > 1 {
r.Order = append(r.Order[:i], r.Order[i+1:]...)
} else {
r.Order = []string{}
}
break
}
}
r.NumLabels = uint(len(r.Values))
r.NumStrings = uint(len(r.Values))
}
}
// Save saves the changes to the CSF file. Intermediate backup file will be
// created as $tmp_filename.csf.
func (r *CSFUtil) Save() error {
f, err := os.OpenFile("$tmp_"+r.filename, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return err
}
b := []byte{}
buf := bytes.NewBuffer(b)
dword := make([]byte, 4)
// write file header
buf.WriteString(CSFFileIdentifier)
binary.LittleEndian.PutUint32(dword, uint32(r.Version))
buf.Write(dword)
binary.LittleEndian.PutUint32(dword, uint32(r.NumLabels))
buf.Write(dword)
binary.LittleEndian.PutUint32(dword, uint32(r.NumStrings))
buf.Write(dword)
binary.LittleEndian.PutUint32(dword, uint32(r.Unused))
buf.Write(dword)
binary.LittleEndian.PutUint32(dword, uint32(r.Language))
buf.Write(dword)
for _, s := range r.Order {
buf.Write(r.Values[s].Bytes())
}
_, err = f.Write(buf.Bytes())
if err != nil {
return err
}
err = f.Sync()
if err != nil {
return err
}
f.Close()
if err := os.Rename("$tmp_"+r.filename, r.filename); err != nil {
return err
}
return nil
}
// Open opens the given file and parse it, returning pointer to CSFUtil.
// Remember to call Close() on the returning CSFUtil.
func Open(name string) (*CSFUtil, error) {
reader := &CSFUtil{filename: name}
return reader, reader.openAndParse(name)
}
// MustOpen do the same thing as Open, but panics if error occurs.
func MustOpen(name string) *CSFUtil {
u, err := Open(name)
if err != nil {
panic(err)
}
return u
}
func New(name string, version, unused, language uint) *CSFUtil {
return &CSFUtil{
filename: name,
Version: version,
NumLabels: 0,
NumStrings: 0,
Unused: unused,
Language: language,
Values: map[string]LabelValue{},
Categories: map[string][]string{},
Order: []string{},
}
}