-
Notifications
You must be signed in to change notification settings - Fork 15
/
quirks.go
499 lines (423 loc) · 12.1 KB
/
quirks.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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
/* ipp-usb - HTTP reverse proxy, backed by IPP-over-USB connection to device
*
* Copyright (C) 2020 and up by Alexander Pevzner ([email protected])
* See LICENSE for license terms and conditions
*
* Device-specific quirks
*/
package main
import (
"fmt"
"io"
"io/ioutil"
"math"
"net/http"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
)
// Quirk represents a single quirk
type Quirk struct {
Origin string // file:line of definition
Match string // Match pattern
Name string // Quirk name
RawValue string // Quirk raw (not parsed) value
Parsed interface{} // Parsed Value
LoadOrder int // Incremented in order of loading
}
// Quirk names. Use these constants instead of literal strings,
// so compiler will catch a mistake:
const (
QuirkNmBlacklist = "blacklist"
QuirkNmBuggyIppResponses = "buggy-ipp-responses"
QuirkNmDisableFax = "disable-fax"
QuirkNmIgnoreIppStatus = "ignore-ipp-status"
QuirkNmInitDelay = "init-delay"
QuirkNmInitReset = "init-reset"
QuirkNmInitTimeout = "init-timeout"
QuirkNmRequestDelay = "request-delay"
QuirkNmUsbMaxInterfaces = "usb-max-interfaces"
)
// quirkParse maps quirk names into appropriate parsing methods,
// which defines value syntax and resulting type.
var quirkParse = map[string]func(*Quirk) error{
QuirkNmBlacklist: (*Quirk).parseBool,
QuirkNmBuggyIppResponses: (*Quirk).parseQuirkBuggyIppRsp,
QuirkNmDisableFax: (*Quirk).parseBool,
QuirkNmIgnoreIppStatus: (*Quirk).parseBool,
QuirkNmInitDelay: (*Quirk).parseDuration,
QuirkNmInitReset: (*Quirk).parseQuirkResetMethod,
QuirkNmInitTimeout: (*Quirk).parseDuration,
QuirkNmRequestDelay: (*Quirk).parseDuration,
QuirkNmUsbMaxInterfaces: (*Quirk).parseUint,
}
// quirkDefaultStrings contains default values for quirks, in
// a string form.
var quirkDefaultStrings = map[string]string{
QuirkNmBlacklist: "false",
QuirkNmBuggyIppResponses: "reject",
QuirkNmDisableFax: "false",
QuirkNmIgnoreIppStatus: "false",
QuirkNmInitDelay: "0",
QuirkNmInitReset: "none",
QuirkNmInitTimeout: DevInitTimeout.String(),
QuirkNmRequestDelay: "0",
QuirkNmUsbMaxInterfaces: "0",
}
// quirkDefault contains default values for quirks, precompiled.
var quirkDefault = make(map[string]*Quirk)
// init populates quirkDefault using quirk values from quirkDefaultStrings.
func init() {
for name, value := range quirkDefaultStrings {
println(name, "=", value)
q := &Quirk{
Origin: "default",
Match: "*",
Name: name,
RawValue: value,
LoadOrder: math.MaxInt32,
}
parse := quirkParse[name]
err := parse(q)
if err != nil {
panic(err)
}
quirkDefault[name] = q
}
}
// parseBool parses and saves [Quirk.RawValue] as bool.
func (q *Quirk) parseBool() error {
switch q.RawValue {
case "true":
q.Parsed = true
case "false":
q.Parsed = false
default:
return fmt.Errorf("%q: must be true or false", q.RawValue)
}
return nil
}
// parseUind parses [Quirk.RawValue] as bool.
func (q *Quirk) parseUint() error {
v, err := strconv.ParseUint(q.RawValue, 10, 32)
if err != nil {
return fmt.Errorf("%q: invalid unsigned integer", q.RawValue)
}
q.Parsed = uint(v)
return nil
}
// parseDuration parses [Quirk.RawValue] as time.Duration.
func (q *Quirk) parseDuration() error {
// Try to parse as uint. If OK, interpret it
// as a millisecond time.
ms, err := strconv.ParseUint(q.RawValue, 10, 32)
if err == nil {
q.Parsed = time.Millisecond * time.Duration(ms)
return nil
}
// Try to use time.ParseDuration.
//
if strings.HasPrefix(q.RawValue, "+") ||
strings.HasPrefix(q.RawValue, "-") {
// Note, time.ParseDuration allows signed duration,
// but we don't.
return fmt.Errorf("%q: invalid duration", q.RawValue)
}
v, err := time.ParseDuration(q.RawValue)
if err == nil && v >= 0 {
q.Parsed = v
return nil
}
return fmt.Errorf("%q: invalid duration", q.RawValue)
}
// parseQuirkBuggyIppRsp parses [Quirk.RawValue] as QuirkBuggyIppRsp.
func (q *Quirk) parseQuirkBuggyIppRsp() error {
switch q.RawValue {
case "allow":
q.Parsed = QuirkBuggyIppRspAllow
case "reject":
q.Parsed = QuirkBuggyIppRspReject
case "sanitize":
q.Parsed = QuirkBuggyIppRspSanitize
default:
s := q.RawValue
return fmt.Errorf("%q: must be allow, reject or sanitize", s)
}
return nil
}
// parseQuirkResetMethod parses [Quirk.RawValue] as QuirkResetMethod.
func (q *Quirk) parseQuirkResetMethod() error {
switch q.RawValue {
case "none":
q.Parsed = QuirkResetNone
case "soft":
q.Parsed = QuirkResetSoft
case "hard":
q.Parsed = QuirkResetHard
default:
return fmt.Errorf("%q: must be none, soft or hard", q.RawValue)
}
return nil
}
// prioritize returns more prioritized Quirk, choosing between q and q2.
func (q *Quirk) prioritize(q2 *Quirk, model string) *Quirk {
matchlen := GlobMatch(model, q.Match)
matchlen2 := GlobMatch(model, q2.Match)
switch {
// Choose by match length (more specific match wins)
case matchlen > matchlen2:
return q
case matchlen < matchlen2:
return q2
// Choose by load order (first loaded wins)
case q.LoadOrder > q2.LoadOrder:
return q
}
return q
}
// QuirkResetMethod represents how to reset a device
// during initialization
type QuirkResetMethod int
// QuirkResetUnset - reset method not specified
// QuirkResetNone - don't reset device at all
// QuirkResetSoft - use class-specific soft reset
// QuirkResetHard - use USB hard reset
const (
QuirkResetNone QuirkResetMethod = iota
QuirkResetSoft
QuirkResetHard
)
// String returns textual representation of QuirkResetMethod
func (m QuirkResetMethod) String() string {
switch m {
case QuirkResetNone:
return "none"
case QuirkResetSoft:
return "soft"
case QuirkResetHard:
return "hard"
}
return fmt.Sprintf("unknown (%d)", int(m))
}
// QuirkBuggyIppRsp defines, how to handle buggy IPP responses
type QuirkBuggyIppRsp int
// QuirkBuggyIppRspReject - ipp-usb will reject bad IPP responses
// QuirkBuggyIppRspAllow - ipp-usb will allow bad IPP responses
// QuirkBuggyIppRspSanitize - bad ipp responses will be sanitized (fixed)
const (
QuirkBuggyIppRspReject QuirkBuggyIppRsp = iota
QuirkBuggyIppRspAllow
QuirkBuggyIppRspSanitize
)
// String returns textual representation of QuirkBuggyIppRsp
func (m QuirkBuggyIppRsp) String() string {
switch m {
case QuirkBuggyIppRspReject:
return "reject"
case QuirkBuggyIppRspAllow:
return "allow"
case QuirkBuggyIppRspSanitize:
return "sanitize"
}
return fmt.Sprintf("unknown (%d)", int(m))
}
// Quirks is the collection of Quirk-s.
type Quirks struct {
byName map[string]*Quirk // Quirks by name
HTTPHeaders map[string]string // HTTP header override
}
// Get returns quirk by name.
func (quirks Quirks) Get(name string) *Quirk {
q := quirks.byName[name]
if q == nil {
q = quirkDefault[name]
}
return q
}
// All returns all quirks in the collection. This method is
// intended mostly for diagnostic purposes (logging, dumping,
// testing and so on).
func (quirks Quirks) All() []*Quirk {
qq := make([]*Quirk, 0, len(quirks.byName))
for _, q := range quirks.byName {
qq = append(qq, q)
}
sort.Slice(qq, func(i, j int) bool {
return qq[i].Name < qq[j].Name
})
return qq
}
// GetBlacklist returns effective "blacklist" parameter,
// taking the whole set into consideration.
func (quirks Quirks) GetBlacklist() bool {
return quirks.Get(QuirkNmBlacklist).Parsed.(bool)
}
// GetBuggyIppRsp returns effective "buggy-ipp-responses" parameter
// taking the whole set into consideration.
func (quirks Quirks) GetBuggyIppRsp() QuirkBuggyIppRsp {
return quirks.Get(QuirkNmBuggyIppResponses).Parsed.(QuirkBuggyIppRsp)
}
// GetDisableFax returns effective "disable-fax" parameter,
// taking the whole set into consideration.
func (quirks Quirks) GetDisableFax() bool {
return quirks.Get(QuirkNmDisableFax).Parsed.(bool)
}
// GetIgnoreIppStatus returns effective "ignore-ipp-status" parameter,
// taking the whole set into consideration.
func (quirks Quirks) GetIgnoreIppStatus() bool {
return quirks.Get(QuirkNmIgnoreIppStatus).Parsed.(bool)
}
// GetInitDelay returns effective "init-delay" parameter
// taking the whole set into consideration.
func (quirks Quirks) GetInitDelay() time.Duration {
return quirks.Get(QuirkNmInitDelay).Parsed.(time.Duration)
}
// GetInitReset returns effective "init-reset" parameter
// taking the whole set into consideration.
func (quirks Quirks) GetInitReset() QuirkResetMethod {
return quirks.Get(QuirkNmInitReset).Parsed.(QuirkResetMethod)
}
// GetInitTimeout returns effective "init-timeout" parameter
// taking the whole set into consideration.
func (quirks Quirks) GetInitTimeout() time.Duration {
return quirks.Get(QuirkNmInitTimeout).Parsed.(time.Duration)
}
// GetRequestDelay returns effective "request-delay" parameter
// taking the whole set into consideration.
func (quirks Quirks) GetRequestDelay() time.Duration {
return quirks.Get(QuirkNmRequestDelay).Parsed.(time.Duration)
}
// GetUsbMaxInterfaces returns effective "usb-max-interfaces" parameter,
// taking the whole set into consideration.
func (quirks Quirks) GetUsbMaxInterfaces() uint {
return quirks.Get(QuirkNmUsbMaxInterfaces).Parsed.(uint)
}
// QuirksSet represents collection of quirks
type QuirksSet []*Quirks
// LoadQuirksSet creates new QuirksSet and loads its content from a directory
func LoadQuirksSet(paths ...string) (QuirksSet, error) {
qset := QuirksSet{}
for _, path := range paths {
err := qset.readDir(path)
if err != nil {
return nil, err
}
}
return qset, nil
}
// readDir loads all Quirks from a directory
func (qset *QuirksSet) readDir(path string) error {
files, err := ioutil.ReadDir(path)
if err != nil {
if os.IsNotExist(err) {
err = nil
}
return err
}
for _, file := range files {
if file.Mode().IsRegular() &&
strings.HasSuffix(file.Name(), ".conf") {
err = qset.readFile(filepath.Join(path, file.Name()))
if err != nil {
return err
}
}
}
return nil
}
// readFile reads all Quirks from a file
func (qset *QuirksSet) readFile(file string) error {
// Open quirks file
ini, err := OpenIniFileWithRecType(file)
if err != nil {
return err
}
defer ini.Close()
// Load all quirks
var quirks *Quirks
var loadOrder int
for err == nil {
var rec *IniRecord
rec, err = ini.Next()
if err != nil {
break
}
origin := fmt.Sprintf("%s:%d", rec.File, rec.Line)
// Get Quirks structure
if rec.Type == IniRecordSection {
quirks = &Quirks{
byName: make(map[string]*Quirk),
HTTPHeaders: make(map[string]string),
}
qset.Add(quirks)
continue
} else if quirks == nil {
err = fmt.Errorf("%s: %q = %q out of any section",
origin, rec.Key, rec.Value)
break
}
if found := quirks.byName[rec.Key]; found != nil {
err = fmt.Errorf("%s: %q already defined at %s",
origin, rec.Key, found.Origin)
return err
}
q := &Quirk{
Origin: origin,
Match: rec.Section,
Name: rec.Key,
RawValue: rec.Value,
LoadOrder: loadOrder,
}
loadOrder++
if strings.HasPrefix(rec.Key, "http-") {
// Canonicalize HTTP header name
q.Name = strings.ToLower(q.Name)
q.Parsed = q.RawValue
hdr := http.CanonicalHeaderKey(rec.Key[5:])
quirks.HTTPHeaders[hdr] = q.RawValue
} else {
parse := quirkParse[rec.Key]
if parse == nil {
// Ignore unknown keys, it may be due to
// downgrade of the ipp-usb
continue
}
err := parse(q)
if err != nil {
err = fmt.Errorf("%s: %s", origin, err)
return err
}
}
quirks.byName[rec.Key] = q
}
if err == io.EOF {
err = nil
}
return err
}
// Add appends Quirks to QuirksSet
func (qset *QuirksSet) Add(q *Quirks) {
*qset = append(*qset, q)
}
// MatchByModelName returns collection of quirks, applicable for
// specific device, matched by model name.
func (qset QuirksSet) MatchByModelName(model string) Quirks {
ret := Quirks{
byName: make(map[string]*Quirk),
}
for _, quirks := range qset {
for name, q := range quirks.byName {
if GlobMatch(model, q.Match) >= 0 {
q2 := ret.byName[name]
if q2 != nil {
q = q.prioritize(q2, model)
}
ret.byName[name] = q
}
}
}
return ret
}