-
Notifications
You must be signed in to change notification settings - Fork 106
/
parser.go
394 lines (356 loc) · 8.97 KB
/
parser.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
package uaparser
import (
"fmt"
"io/ioutil"
"regexp"
"sort"
"sync"
"sync/atomic"
"time"
"gopkg.in/yaml.v2"
)
type RegexesDefinitions struct {
UA []*uaParser `yaml:"user_agent_parsers"`
OS []*osParser `yaml:"os_parsers"`
Device []*deviceParser `yaml:"device_parsers"`
_ [4]byte // padding for alignment
sync.RWMutex
}
type UserAgentSorter []*uaParser
func (a UserAgentSorter) Len() int { return len(a) }
func (a UserAgentSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a UserAgentSorter) Less(i, j int) bool {
return atomic.LoadUint64(&a[i].MatchesCount) > atomic.LoadUint64(&a[j].MatchesCount)
}
type uaParser struct {
Reg *regexp.Regexp
Expr string `yaml:"regex"`
Flags string `yaml:"regex_flag"`
FamilyReplacement string `yaml:"family_replacement"`
V1Replacement string `yaml:"v1_replacement"`
V2Replacement string `yaml:"v2_replacement"`
V3Replacement string `yaml:"v3_replacement"`
_ [4]byte // padding for alignment
MatchesCount uint64
}
func (ua *uaParser) setDefaults() {
if ua.FamilyReplacement == "" {
ua.FamilyReplacement = "$1"
}
if ua.V1Replacement == "" {
ua.V1Replacement = "$2"
}
if ua.V2Replacement == "" {
ua.V2Replacement = "$3"
}
if ua.V3Replacement == "" {
ua.V3Replacement = "$4"
}
}
type OsSorter []*osParser
func (a OsSorter) Len() int { return len(a) }
func (a OsSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a OsSorter) Less(i, j int) bool {
return atomic.LoadUint64(&a[i].MatchesCount) > atomic.LoadUint64(&a[j].MatchesCount)
}
type osParser struct {
Reg *regexp.Regexp
Expr string `yaml:"regex"`
Flags string `yaml:"regex_flag"`
OSReplacement string `yaml:"os_replacement"`
V1Replacement string `yaml:"os_v1_replacement"`
V2Replacement string `yaml:"os_v2_replacement"`
V3Replacement string `yaml:"os_v3_replacement"`
V4Replacement string `yaml:"os_v4_replacement"`
_ [4]byte // padding for alignment
MatchesCount uint64
}
func (os *osParser) setDefaults() {
if os.OSReplacement == "" {
os.OSReplacement = "$1"
}
if os.V1Replacement == "" {
os.V1Replacement = "$2"
}
if os.V2Replacement == "" {
os.V2Replacement = "$3"
}
if os.V3Replacement == "" {
os.V3Replacement = "$4"
}
if os.V4Replacement == "" {
os.V4Replacement = "$5"
}
}
type DeviceSorter []*deviceParser
func (a DeviceSorter) Len() int { return len(a) }
func (a DeviceSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a DeviceSorter) Less(i, j int) bool {
return atomic.LoadUint64(&a[i].MatchesCount) > atomic.LoadUint64(&a[j].MatchesCount)
}
type deviceParser struct {
Reg *regexp.Regexp
Expr string `yaml:"regex"`
Flags string `yaml:"regex_flag"`
DeviceReplacement string `yaml:"device_replacement"`
BrandReplacement string `yaml:"brand_replacement"`
ModelReplacement string `yaml:"model_replacement"`
_ [4]byte // padding for alignment
MatchesCount uint64
}
func (device *deviceParser) setDefaults() {
if device.DeviceReplacement == "" {
device.DeviceReplacement = "$1"
}
if device.ModelReplacement == "" {
device.ModelReplacement = "$1"
}
}
type Client struct {
UserAgent *UserAgent
Os *Os
Device *Device
}
type Parser struct {
/* atomic operation are done on the following unit64.
* These must be 64bit aligned. On 32bit architectures
* this is only guaranteed to be on the beginning of a struct */
UserAgentMisses uint64
OsMisses uint64
DeviceMisses uint64
cache *cache
RegexesDefinitions
Mode int
UseSort bool
debugMode bool
}
const (
EOsLookUpMode = 1 /* 00000001 */
EUserAgentLookUpMode = 2 /* 00000010 */
EDeviceLookUpMode = 4 /* 00000100 */
cMinMissesTreshold = 100000
cDefaultMissesTreshold = 500000
cDefaultMatchIdxNotOk = 20
cDefaultSortOption = false
)
var (
missesTreshold = uint64(500000)
matchIdxNotOk = 20
)
func (parser *Parser) mustCompile() { // until we can use yaml.UnmarshalYAML with embedded pointer struct
for _, p := range parser.UA {
p.Reg = compileRegex(p.Flags, p.Expr)
p.setDefaults()
}
for _, p := range parser.OS {
p.Reg = compileRegex(p.Flags, p.Expr)
p.setDefaults()
}
for _, p := range parser.Device {
p.Reg = compileRegex(p.Flags, p.Expr)
p.setDefaults()
}
}
func NewWithOptions(regexFile string, mode, treshold, topCnt int, useSort, debugMode bool) (*Parser, error) {
data, err := ioutil.ReadFile(regexFile)
if nil != err {
return nil, err
}
if topCnt >= 0 {
matchIdxNotOk = topCnt
}
if treshold > cMinMissesTreshold {
missesTreshold = uint64(treshold)
}
parser, err := NewFromBytes(data)
if err != nil {
return nil, err
}
parser.Mode = mode
parser.UseSort = useSort
parser.debugMode = debugMode
return parser, nil
}
func New(regexFile string) (*Parser, error) {
data, err := ioutil.ReadFile(regexFile)
if nil != err {
return nil, err
}
matchIdxNotOk = cDefaultMatchIdxNotOk
missesTreshold = cDefaultMissesTreshold
parser, err := NewFromBytes(data)
if err != nil {
return nil, err
}
return parser, nil
}
func NewFromSaved() *Parser {
parser, err := NewFromBytes(DefinitionYaml)
if err != nil {
// if the YAML is malformed, it's a programmatic error inside what
// we've statically-compiled in our binary. Panic!
panic(err.Error())
}
return parser
}
func NewFromBytes(data []byte) (*Parser, error) {
parser := &Parser{
Mode: EOsLookUpMode | EUserAgentLookUpMode | EDeviceLookUpMode,
cache: newCache(),
}
if err := yaml.Unmarshal(data, &parser.RegexesDefinitions); err != nil {
return nil, err
}
parser.mustCompile()
return parser, nil
}
func (parser *Parser) Parse(line string) *Client {
cli := new(Client)
var wg sync.WaitGroup
if EUserAgentLookUpMode&parser.Mode == EUserAgentLookUpMode {
wg.Add(1)
go func() {
defer wg.Done()
parser.RLock()
cli.UserAgent = parser.ParseUserAgent(line)
parser.RUnlock()
}()
}
if EOsLookUpMode&parser.Mode == EOsLookUpMode {
wg.Add(1)
go func() {
defer wg.Done()
parser.RLock()
cli.Os = parser.ParseOs(line)
parser.RUnlock()
}()
}
if EDeviceLookUpMode&parser.Mode == EDeviceLookUpMode {
wg.Add(1)
go func() {
defer wg.Done()
parser.RLock()
cli.Device = parser.ParseDevice(line)
parser.RUnlock()
}()
}
wg.Wait()
if parser.UseSort == true {
checkAndSort(parser)
}
return cli
}
func (parser *Parser) ParseUserAgent(line string) *UserAgent {
cachedUA, ok := parser.cache.userAgent.Get(line)
if ok {
return cachedUA.(*UserAgent)
}
ua := new(UserAgent)
foundIdx := -1
found := false
for i, uaPattern := range parser.UA {
uaPattern.Match(line, ua)
if len(ua.Family) > 0 {
found = true
foundIdx = i
atomic.AddUint64(&uaPattern.MatchesCount, 1)
break
}
}
if !found {
ua.Family = "Other"
}
if foundIdx > matchIdxNotOk {
atomic.AddUint64(&parser.UserAgentMisses, 1)
}
parser.cache.userAgent.Add(line, ua)
return ua
}
func (parser *Parser) ParseOs(line string) *Os {
cachedOS, ok := parser.cache.os.Get(line)
if ok {
return cachedOS.(*Os)
}
os := new(Os)
foundIdx := -1
found := false
for i, osPattern := range parser.OS {
osPattern.Match(line, os)
if len(os.Family) > 0 {
found = true
foundIdx = i
atomic.AddUint64(&osPattern.MatchesCount, 1)
break
}
}
if !found {
os.Family = "Other"
}
if foundIdx > matchIdxNotOk {
atomic.AddUint64(&parser.OsMisses, 1)
}
parser.cache.os.Add(line, os)
return os
}
func (parser *Parser) ParseDevice(line string) *Device {
cachedDevice, ok := parser.cache.device.Get(line)
if ok {
return cachedDevice.(*Device)
}
dvc := new(Device)
foundIdx := -1
found := false
for i, dvcPattern := range parser.Device {
dvcPattern.Match(line, dvc)
if len(dvc.Family) > 0 {
found = true
foundIdx = i
atomic.AddUint64(&dvcPattern.MatchesCount, 1)
break
}
}
if !found {
dvc.Family = "Other"
}
if foundIdx > matchIdxNotOk {
atomic.AddUint64(&parser.DeviceMisses, 1)
}
parser.cache.device.Add(line, dvc)
return dvc
}
func checkAndSort(parser *Parser) {
parser.Lock()
if atomic.LoadUint64(&parser.UserAgentMisses) >= missesTreshold {
if parser.debugMode {
fmt.Printf("%s\tSorting UserAgents slice\n", time.Now())
}
parser.UserAgentMisses = 0
sort.Sort(UserAgentSorter(parser.UA))
}
parser.Unlock()
parser.Lock()
if atomic.LoadUint64(&parser.OsMisses) >= missesTreshold {
if parser.debugMode {
fmt.Printf("%s\tSorting OS slice\n", time.Now())
}
parser.OsMisses = 0
sort.Sort(OsSorter(parser.OS))
}
parser.Unlock()
parser.Lock()
if atomic.LoadUint64(&parser.DeviceMisses) >= missesTreshold {
if parser.debugMode {
fmt.Printf("%s\tSorting Device slice\n", time.Now())
}
parser.DeviceMisses = 0
sort.Sort(DeviceSorter(parser.Device))
}
parser.Unlock()
}
func compileRegex(flags, expr string) *regexp.Regexp {
if flags == "" {
return regexp.MustCompile(expr)
} else {
return regexp.MustCompile(fmt.Sprintf("(?%s)%s", flags, expr))
}
}