github.com/nicocha30/gvisor-ligolo@v0.0.0-20230726075806-989fa2c0a413/pkg/hostos/hostos.go (about) 1 // Copyright 2022 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Package hostos contains utility functions for getting information about the host OS. 16 package hostos 17 18 import ( 19 "fmt" 20 "regexp" 21 "strings" 22 "sync" 23 24 "golang.org/x/mod/semver" 25 "golang.org/x/sys/unix" 26 ) 27 28 // Version represents a semantic version of the form "%d.%d[.%d]". 29 type Version struct { 30 version string 31 } 32 33 // AtLeast returns whether vr is at least version major.minor. 34 func (vr Version) AtLeast(major, minor int) bool { 35 return semver.Compare(vr.version, fmt.Sprintf("v%d.%d", major, minor)) >= 0 36 } 37 38 // LessThan returns whether vr is less than version major.minor. 39 func (vr Version) LessThan(major, minor int) bool { 40 return !vr.AtLeast(major, minor) 41 } 42 43 // String implements fmt.Stringer. 44 func (vr Version) String() string { 45 if vr.version == "" { 46 return "unknown" 47 } 48 // Omit the "v" prefix required by semver. 49 return vr.version[1:] 50 } 51 52 // These values are effectively local to KernelVersion, but kept here so as to 53 // work with sync.Once. 54 var ( 55 semVersion Version 56 unameErr error 57 once sync.Once 58 ) 59 60 // KernelVersion returns the version of the kernel using uname(). 61 func KernelVersion() (Version, error) { 62 once.Do(func() { 63 var utsname unix.Utsname 64 if err := unix.Uname(&utsname); err != nil { 65 unameErr = err 66 return 67 } 68 69 var sb strings.Builder 70 for _, b := range utsname.Release { 71 if b == 0 { 72 break 73 } 74 sb.WriteByte(byte(b)) 75 } 76 77 versionRegexp := regexp.MustCompile(`[0-9]+\.[0-9]+(\.[0-9]+)?`) 78 version := "v" + string(versionRegexp.Find([]byte(sb.String()))) 79 if !semver.IsValid(version) { 80 unameErr = fmt.Errorf("invalid version found in release %q", sb.String()) 81 return 82 } 83 semVersion.version = version 84 }) 85 86 return semVersion, unameErr 87 }