-
Notifications
You must be signed in to change notification settings - Fork 68
/
ua.go
691 lines (593 loc) · 16.1 KB
/
ua.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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
package useragent
import (
"bytes"
"regexp"
"strings"
)
// UserAgent struct containing all data extracted from parsed user-agent string
type UserAgent struct {
VersionNo VersionNo
OSVersionNo VersionNo
URL string
String string
Name string
Version string
OS string
OSVersion string
Device string
Mobile bool
Tablet bool
Desktop bool
Bot bool
}
// Constants for browsers and operating systems for easier comparison
const (
Windows = "Windows"
WindowsPhone = "Windows Phone"
WindowsNT = "Windows NT"
WindowsPhoneOS = "Windows Phone OS"
Android = "Android"
MacOS = "macOS"
IOS = "iOS"
Linux = "Linux"
FreeBSD = "FreeBSD"
ChromeOS = "ChromeOS"
BlackBerry = "BlackBerry"
CrOS = "CrOS"
Harmony = "Harmony"
Opera = "Opera"
OperaMini = "Opera Mini"
OperaTouch = "Opera Touch"
Chrome = "Chrome"
HeadlessChrome = "Headless Chrome"
Firefox = "Firefox"
InternetExplorer = "Internet Explorer"
Safari = "Safari"
Edge = "Edge"
Vivaldi = "Vivaldi"
MobileSafari = "Mobile Safari"
NetFront = "NetFront"
Mozilla = "Mozilla"
Msie = "MSIE"
SamsungBrowser = "Samsung Browser"
GoogleAdsBot = "Google Ads Bot"
Googlebot = "Googlebot"
Twitterbot = "Twitterbot"
FacebookExternalHit = "facebookexternalhit"
Applebot = "Applebot"
Bingbot = "Bingbot"
YandexBot = "YandexBot"
YandexAdNet = "YandexAdNet"
FacebookApp = "Facebook App"
InstagramApp = "Instagram App"
TiktokApp = "TikTok App"
Version = "Version"
Mobile = "Mobile"
Tablet = "Tablet"
tablet = "tablet"
)
// Parse user agent string returning UserAgent struct
func Parse(userAgent string) UserAgent {
ua := UserAgent{
String: userAgent,
}
tokens := parse([]byte(userAgent))
ua.URL = tokens.url
// OS lookup
switch {
case tokens.exists(Android):
ua.OS = Android
var osIndex int
osIndex, ua.OSVersion = tokens.getIndexValue(Android)
ua.Tablet = strings.Contains(strings.ToLower(ua.String), tablet)
ua.Device = tokens.findAndroidDevice(osIndex)
case tokens.exists("iPhone"):
ua.OS = IOS
ua.OSVersion = tokens.findMacOSVersion()
ua.Device = "iPhone"
ua.Mobile = true
case tokens.exists("iPad"):
ua.OS = IOS
ua.OSVersion = tokens.findMacOSVersion()
ua.Device = "iPad"
ua.Tablet = true
case tokens.exists(WindowsNT):
ua.OS = Windows
ua.OSVersion = tokens.get(WindowsNT)
ua.Desktop = true
case tokens.exists(WindowsPhoneOS):
ua.OS = WindowsPhone
ua.OSVersion = tokens.get(WindowsPhoneOS)
ua.Mobile = true
case tokens.exists("Macintosh"):
ua.OS = MacOS
ua.OSVersion = tokens.findMacOSVersion()
ua.Desktop = true
case tokens.exists(Linux):
ua.OS = Linux
ua.OSVersion = tokens.get(Linux)
ua.Desktop = true
case tokens.exists(FreeBSD):
ua.OS = FreeBSD
ua.OSVersion = tokens.get(FreeBSD)
ua.Desktop = true
case tokens.exists(CrOS):
ua.OS = ChromeOS
ua.OSVersion = tokens.get(CrOS)
ua.Desktop = true
case tokens.exists(BlackBerry):
ua.OS = BlackBerry
ua.OSVersion = tokens.get(BlackBerry)
ua.Mobile = true
case tokens.exists("OpenHarmony"):
ua.OS = Harmony
ua.OSVersion = tokens.get("OpenHarmony")
ua.Mobile = true
}
switch {
case tokens.exists(Googlebot):
ua.Name = Googlebot
ua.Version = tokens.get(Googlebot)
ua.Bot = true
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
case tokens.existsAny("GoogleProber", "GoogleProducer"):
if name := tokens.findBestMatch(false); name != "" {
ua.Name = name
}
ua.Bot = true
case tokens.exists("Bytespider"):
ua.Name = "Bytespider"
ua.Mobile = tokens.exists("Mobile Safari")
ua.Bot = true
case tokens.exists(Applebot):
ua.Name = Applebot
ua.Version = tokens.get(Applebot)
ua.Bot = true
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
ua.OS = ""
case tokens.get(OperaMini) != "":
ua.Name = OperaMini
ua.Version = tokens.get(OperaMini)
ua.Mobile = true
case tokens.get("OPR") != "":
ua.Name = Opera
ua.Version = tokens.get("OPR")
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
case tokens.get("OPT") != "":
ua.Name = OperaTouch
ua.Version = tokens.get("OPT")
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
// Opera on iOS
case tokens.get("OPiOS") != "":
ua.Name = Opera
ua.Version = tokens.get("OPiOS")
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
// Chrome on iOS
case tokens.get("CriOS") != "":
ua.Name = Chrome
ua.Version = tokens.get("CriOS")
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
// Firefox on iOS
case tokens.get("FxiOS") != "":
ua.Name = Firefox
ua.Version = tokens.get("FxiOS")
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
case tokens.get(Firefox) != "":
ua.Name = Firefox
ua.Version = tokens.get(Firefox)
ua.Mobile = tokens.exists(Mobile)
ua.Tablet = tokens.exists(Tablet)
case tokens.get(Vivaldi) != "":
ua.Name = Vivaldi
ua.Version = tokens.get(Vivaldi)
case tokens.exists(Msie):
ua.Name = InternetExplorer
ua.Version = tokens.get(Msie)
case tokens.get("EdgiOS") != "":
ua.Name = Edge
ua.Version = tokens.get("EdgiOS")
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
case tokens.get(Edge) != "":
ua.Name = Edge
ua.Version = tokens.get(Edge)
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
case tokens.get("Edg") != "":
ua.Name = Edge
ua.Version = tokens.get("Edg")
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
case tokens.get("EdgA") != "":
ua.Name = Edge
ua.Version = tokens.get("EdgA")
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
case tokens.get("bingbot") != "":
ua.Name = Bingbot
ua.Version = tokens.get("bingbot")
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
case tokens.get(YandexBot) != "":
ua.Name = YandexBot
ua.Version = tokens.get(YandexBot)
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
ua.Bot = true
case tokens.get(YandexAdNet) != "":
ua.Name = YandexAdNet
ua.Version = tokens.get(YandexAdNet)
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
ua.Bot = true
case tokens.get("SamsungBrowser") != "":
ua.Name = SamsungBrowser
ua.Version = tokens.get("SamsungBrowser")
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
ua.OS = Android
case tokens.get("HeadlessChrome") != "":
ua.Name = HeadlessChrome
ua.Version = tokens.get("HeadlessChrome")
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
ua.Bot = true
case tokens.existsAny("AdsBot-Google-Mobile", "Mediapartners-Google", "AdsBot-Google"):
ua.Name = GoogleAdsBot
ua.Bot = true
ua.Mobile = ua.IsAndroid() || ua.IsIOS()
case tokens.exists("Yahoo Ad monitoring"):
ua.Name = "Yahoo Ad monitoring"
ua.Bot = true
ua.Mobile = ua.IsAndroid() || ua.IsIOS()
case tokens.exists("XiaoMi"):
miui := tokens.get("XiaoMi")
if strings.HasPrefix(miui, "MiuiBrowser") {
ua.Name = "Miui Browser"
ua.Version = strings.TrimPrefix(miui, "MiuiBrowser/")
ua.Mobile = true
}
case tokens.exists("FBAN"):
ua.Name = FacebookApp
ua.Version = tokens.get("FBAN")
case tokens.exists("FB_IAB"):
ua.Name = FacebookApp
ua.Version = tokens.get("FBAV")
case tokens.startsWith("Instagram"):
ua.Name = InstagramApp
ua.Version = tokens.findInstagramVersion()
case tokens.exists("BytedanceWebview"):
ua.Name = TiktokApp
ua.Version = tokens.get("app_version")
case tokens.get("HuaweiBrowser") != "":
ua.Name = "Huawei Browser"
ua.Version = tokens.get("HuaweiBrowser")
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
case tokens.exists(BlackBerry):
ua.Name = BlackBerry
ua.Version = tokens.get(Version)
case tokens.exists(NetFront):
ua.Name = NetFront
ua.Version = tokens.get(NetFront)
ua.Mobile = true
// if Chrome and Safari defined, find any other token sent descr
case tokens.exists(Chrome) && tokens.exists(Safari):
name := tokens.findBestMatch(true)
if name != "" {
ua.Name = name
ua.Version = tokens.get(name)
break
}
fallthrough
case tokens.exists(Chrome):
ua.Name = Chrome
ua.Version = tokens.get(Chrome)
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
case tokens.exists("Brave Chrome"):
ua.Name = Chrome
ua.Version = tokens.get("Brave Chrome")
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
case tokens.exists(Safari):
ua.Name = Safari
v := tokens.get(Version)
if v != "" {
ua.Version = v
} else {
ua.Version = tokens.get(Safari)
}
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
default:
if ua.IsAndroid() && tokens.get(Version) != "" {
ua.Name = "Android browser"
ua.Version = tokens.get(Version)
ua.Mobile = true
} else {
if name := tokens.findBestMatch(false); name != "" {
ua.Name = name
ua.Version = tokens.get(name)
} else {
ua.Name = ua.String
}
ua.Bot = strings.Contains(strings.ToLower(ua.Name), "bot")
// If mobile flag has already been set, don't override it.
if !ua.Mobile {
ua.Mobile = tokens.existsAny(Mobile, MobileSafari)
}
}
}
if ua.IsAndroid() {
ua.Mobile = true
}
// if tablet, switch mobile to off
if ua.Tablet {
ua.Mobile = false
}
// if not already bot, check some popular bots and whether URL is set
if !ua.Bot {
switch ua.Name {
case Twitterbot, FacebookExternalHit, "facebookcatalog":
ua.Bot = true
default:
ua.Bot = ua.URL != ""
}
}
ua.VersionNo = parseVersion(ua.Version)
ua.OSVersionNo = parseVersion(ua.OSVersion)
return ua
}
// var buffPool = sync.Pool{New: func() interface{} {
// return bytes.NewBuffer(make([]byte, 0, 30))
// }}
func parse(userAgent []byte) properties {
clients := properties{
list: make([]property, 0, 8),
}
slash := false
isURL := false
// buff := buffPool.Get().(*bytes.Buffer)
// val := buffPool.Get().(*bytes.Buffer)
// buff.Reset()
// val.Reset()
buff := bytes.NewBuffer(make([]byte, 0, 30))
val := bytes.NewBuffer(make([]byte, 0, 30))
addToken := func() {
if buff.Len() != 0 {
s := string(bytes.TrimSpace(buff.Bytes()))
if !ignore(s) {
if isURL {
clients.url = strings.TrimPrefix(s, "+")
return
}
if val.Len() == 0 {
// if value don't exists, try to get version from the token
clients.list = append(clients.list, checkVer(s))
} else {
clients.list = append(clients.list, property{Key: s, Value: string(bytes.TrimSpace(val.Bytes()))})
}
}
}
buff.Reset()
val.Reset()
slash = false
isURL = false
}
parOpen := false
braOpen := false
for i, c := range userAgent {
switch {
case c == 41: // )
addToken()
parOpen = false
case (parOpen || braOpen) && c == 59: // ;
addToken()
case c == 59: // ;
addToken()
case c == 40: // (
addToken()
parOpen = true
case c == 91: // [
addToken()
braOpen = true
case c == 93: // ]
addToken()
braOpen = false
case c == 58: // :
if bytes.HasSuffix(buff.Bytes(), []byte("http")) || bytes.HasSuffix(buff.Bytes(), []byte("https")) {
// If we are part of a URL just write the character.
buff.WriteByte(c)
} else if i != len(userAgent)-1 && userAgent[i+1] != ' ' {
// If the following character is not a space, change to a space.
buff.WriteByte(' ')
}
// Otherwise don't write as it's probably a badly formatted key value separator.
case slash && c == 32:
addToken()
case slash:
val.WriteByte(c)
case c == 47 && !isURL: // /
if i != len(userAgent)-1 && userAgent[i+1] == 47 && (bytes.HasSuffix(buff.Bytes(), []byte("http:")) || bytes.HasSuffix(buff.Bytes(), []byte("https:"))) {
buff.WriteByte(c)
isURL = true
} else {
if ignore(buff.String()) {
buff.Reset()
} else {
slash = true
}
}
default:
buff.WriteByte(c)
}
}
addToken()
// buffPool.Put(buff)
// buffPool.Put(val)
return clients
}
func checkVer(s string) property {
i := strings.LastIndex(s, " ")
if i == -1 {
return property{Key: s, Value: ""}
}
switch s[:i] {
case Linux, WindowsNT, WindowsPhoneOS, Msie, Android, "OpenHarmony":
return property{Key: s[:i], Value: s[i+1:]}
case "CrOS x86_64", "CrOS aarch64", "CrOS armv7l":
j := strings.LastIndex(s[:i], " ")
return property{Key: s[:j], Value: s[j+1 : i]}
default:
return property{Key: s, Value: ""}
}
}
// ignore returns true if token should be ignored
func ignore(s string) bool {
switch s {
case "KHTML, like Gecko", "U", "compatible", Mozilla, "WOW64", "en", "en-us", "en-gb", "ru-ru", "Browser":
return true
default:
return false
}
}
type property struct {
Key string
Value string
}
type properties struct {
list []property
url string
}
func (p properties) get(key string) string {
for _, prop := range p.list {
if prop.Key == key {
return prop.Value
}
}
return ""
}
func (p properties) getIndexValue(key string) (int, string) {
for i, prop := range p.list {
if prop.Key == key {
return i, prop.Value
}
}
return -1, ""
}
func (p properties) exists(key string) bool {
for _, prop := range p.list {
if prop.Key == key {
return true
}
}
return false
}
// func (p properties) existsIgnoreCase(key string) bool {
// for _, prop := range p.list {
// if strings.EqualFold(prop.Key, key) {
// return true
// }
// }
// return false
// }
func (p properties) existsAny(keys ...string) bool {
for _, k := range keys {
for _, prop := range p.list {
if prop.Key == k {
return true
}
}
}
return false
}
func (p properties) getAny(keys ...string) (key, value string) {
for _, k := range keys {
for _, prop := range p.list {
if prop.Key == k {
return prop.Key, prop.Value
}
}
}
return "", ""
}
func (p properties) findMacOSVersion() string {
for _, token := range p.list {
if strings.Contains(token.Key, "OS") {
if ver := findVersion(token.Value); ver != "" {
return ver
} else if ver = findVersion(token.Key); ver != "" {
return ver
}
}
}
return ""
}
func (p properties) startsWith(value string) bool {
for _, prop := range p.list {
if strings.HasPrefix(prop.Key, value) {
return true
}
}
return false
}
func (p properties) findInstagramVersion() string {
for _, token := range p.list {
if strings.HasPrefix(token.Key, "Instagram") {
if ver := findVersion(token.Value); ver != "" {
return ver
} else if ver = findVersion(token.Key); ver != "" {
return ver
}
}
}
return ""
}
// findBestMatch from the rest of the bunch
// in first cycle only return key with version value
// if withVerValue is false, do another cycle and return any token
func (p properties) findBestMatch(withVerOnly bool) string {
n := 2
if withVerOnly {
n = 1
}
for i := 0; i < n; i++ {
for _, prop := range p.list {
switch prop.Key {
case Chrome, Firefox, Safari, Version, Mobile, MobileSafari, Mozilla, "AppleWebKit", WindowsNT, WindowsPhoneOS, Android, "Macintosh", Linux, "GSA", CrOS, Tablet, "OpenHarmony":
default:
// don't pick if starts with number
if len(prop.Key) != 0 && prop.Key[0] >= 48 && prop.Key[0] <= 57 {
break
}
if i == 0 {
if prop.Value != "" { // in first check, only return keys with value
return prop.Key
}
} else {
return prop.Key
}
}
}
}
return ""
}
var rxMacOSVer = regexp.MustCompile(`[_\d\.]+`)
func findVersion(s string) string {
if ver := rxMacOSVer.FindString(s); ver != "" {
return strings.Replace(ver, "_", ".", -1)
}
return ""
}
// findAndroidDevice in tokens
func (p *properties) findAndroidDevice(startIndex int) string {
for i := startIndex; i < startIndex+1; i++ {
if len(p.list) > i+1 {
dev := p.list[i+1].Key
if len(dev) == 2 || (len(dev) == 5 && dev[2] == '-') {
// probably language tag (en-us etc..), ignore and continue loop
continue
}
switch dev {
case Chrome, Firefox, Safari, OperaMini, "Presto", Version, Mobile, MobileSafari, Mozilla, "AppleWebKit", WindowsNT, WindowsPhoneOS, Android, "Macintosh", Linux, CrOS:
// ignore these tokens, not device names
default:
if strings.Contains(strings.ToLower(dev), tablet) {
p.list[i+1].Key = Tablet // leave Tablet tag for later table detection
} else {
p.list = append(p.list[:i+1], p.list[i+2:]...)
}
return strings.TrimSpace(strings.TrimSuffix(dev, "Build"))
}
}
}
return ""
}