-
Notifications
You must be signed in to change notification settings - Fork 601
/
Copy pathuseragent.go
91 lines (80 loc) · 2.55 KB
/
useragent.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
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2016-2020 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package snapdenv
import (
"fmt"
"strings"
"github.com/snapcore/snapd/arch"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/release"
)
// UserAgent to send
var userAgent = "unset"
// SetUserAgentFromVersion sets up a user-agent string.
func SetUserAgentFromVersion(version string, probeForceDevMode func() bool, extraProds ...string) (restore func()) {
extras := make([]string, 1, 3)
extras[0] = "series " + release.Series
if release.OnClassic {
extras = append(extras, "classic")
}
if probeForceDevMode != nil && probeForceDevMode() {
extras = append(extras, "devmode")
}
if release.OnWSL {
extras = append(extras, "wsl")
}
if Testing() {
extras = append(extras, "testing")
}
extraProdStr := ""
if len(extraProds) != 0 {
extraProdStr = " " + strings.Join(extraProds, " ")
}
origUserAgent := userAgent
// xxx this assumes ReleaseInfo's ID and VersionID don't have weird characters
// (see rfc 7231 for values of weird)
// assumption checks out in practice, q.v. https://github.com/zyga/os-release-zoo
userAgent = fmt.Sprintf("snapd/%v (%s)%s %s/%s (%s) linux/%s", version,
strings.Join(extras, "; "), extraProdStr, release.ReleaseInfo.ID,
release.ReleaseInfo.VersionID, string(arch.DpkgArchitecture()),
sanitizeKernelVersion(osutil.KernelVersion()))
return func() {
userAgent = origUserAgent
}
}
func sanitizeKernelVersion(in string) string {
out := stripUnsafeRunes(in)
// Arbitrary choice, limit kernel version to 25 characters
if len(out) > 25 {
out = out[:25]
}
return out
}
func safeRuneMapper(r rune) rune {
if r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-' || r == '_' || r == '.' {
return r
}
return -1
}
func stripUnsafeRunes(in string) string {
return strings.Map(safeRuneMapper, in)
}
// UserAgent returns the user-agent string setup through SetUserAgentFromVersion.
func UserAgent() string {
return userAgent
}