repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/plan9/zsyscall_plan9_amd64.go | vendor/golang.org/x/sys/plan9/zsyscall_plan9_amd64.go | // go run mksyscall.go -l32 -plan9 -tags plan9,amd64 syscall_plan9.go
// Code generated by the command above; see README.md. DO NOT EDIT.
//go:build plan9 && amd64
package plan9
import "unsafe"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func fd2path(fd int, buf []byte) (err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_FD2PATH, uintptr(fd), uintptr(_p0), uintptr(len(buf)))
if int32(r0) == -1 {
err = e1
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func pipe(p *[2]int32) (err error) {
r0, _, e1 := Syscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0)
if int32(r0) == -1 {
err = e1
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func await(s []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(s) > 0 {
_p0 = unsafe.Pointer(&s[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_AWAIT, uintptr(_p0), uintptr(len(s)), 0)
n = int(r0)
if int32(r0) == -1 {
err = e1
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func open(path string, mode int) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
fd = int(r0)
if int32(r0) == -1 {
err = e1
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func create(path string, mode int, perm uint32) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_CREATE, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
fd = int(r0)
if int32(r0) == -1 {
err = e1
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func remove(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_REMOVE, uintptr(unsafe.Pointer(_p0)), 0, 0)
if int32(r0) == -1 {
err = e1
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func stat(path string, edir []byte) (n int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 unsafe.Pointer
if len(edir) > 0 {
_p1 = unsafe.Pointer(&edir[0])
} else {
_p1 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(edir)))
n = int(r0)
if int32(r0) == -1 {
err = e1
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func bind(name string, old string, flag int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(old)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_BIND, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flag))
if int32(r0) == -1 {
err = e1
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func mount(fd int, afd int, old string, flag int, aname string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(old)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(aname)
if err != nil {
return
}
r0, _, e1 := Syscall6(SYS_MOUNT, uintptr(fd), uintptr(afd), uintptr(unsafe.Pointer(_p0)), uintptr(flag), uintptr(unsafe.Pointer(_p1)), 0)
if int32(r0) == -1 {
err = e1
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func wstat(path string, edir []byte) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 unsafe.Pointer
if len(edir) > 0 {
_p1 = unsafe.Pointer(&edir[0])
} else {
_p1 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_WSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(edir)))
if int32(r0) == -1 {
err = e1
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func chdir(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
if int32(r0) == -1 {
err = e1
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Dup(oldfd int, newfd int) (fd int, err error) {
r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), uintptr(newfd), 0)
fd = int(r0)
if int32(r0) == -1 {
err = e1
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pread(fd int, p []byte, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0)
n = int(r0)
if int32(r0) == -1 {
err = e1
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pwrite(fd int, p []byte, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), uintptr(offset>>32), 0)
n = int(r0)
if int32(r0) == -1 {
err = e1
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Close(fd int) (err error) {
r0, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0)
if int32(r0) == -1 {
err = e1
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstat(fd int, edir []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(edir) > 0 {
_p0 = unsafe.Pointer(&edir[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(_p0), uintptr(len(edir)))
n = int(r0)
if int32(r0) == -1 {
err = e1
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fwstat(fd int, edir []byte) (err error) {
var _p0 unsafe.Pointer
if len(edir) > 0 {
_p0 = unsafe.Pointer(&edir[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_FWSTAT, uintptr(fd), uintptr(_p0), uintptr(len(edir)))
if int32(r0) == -1 {
err = e1
}
return
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/plan9/race.go | vendor/golang.org/x/sys/plan9/race.go | // Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build plan9 && race
package plan9
import (
"runtime"
"unsafe"
)
const raceenabled = true
func raceAcquire(addr unsafe.Pointer) {
runtime.RaceAcquire(addr)
}
func raceReleaseMerge(addr unsafe.Pointer) {
runtime.RaceReleaseMerge(addr)
}
func raceReadRange(addr unsafe.Pointer, len int) {
runtime.RaceReadRange(addr, len)
}
func raceWriteRange(addr unsafe.Pointer, len int) {
runtime.RaceWriteRange(addr, len)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/plan9/str.go | vendor/golang.org/x/sys/plan9/str.go | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build plan9
package plan9
func itoa(val int) string { // do it here rather than with fmt to avoid dependency
if val < 0 {
return "-" + itoa(-val)
}
var buf [32]byte // big enough for int64
i := len(buf) - 1
for val >= 10 {
buf[i] = byte(val%10 + '0')
i--
val /= 10
}
buf[i] = byte(val + '0')
return string(buf[i:])
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/execabs/execabs_go118.go | vendor/golang.org/x/sys/execabs/execabs_go118.go | // Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !go1.19
package execabs
import "os/exec"
func isGo119ErrDot(err error) bool {
return false
}
func isGo119ErrFieldSet(cmd *exec.Cmd) bool {
return false
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/execabs/execabs_go119.go | vendor/golang.org/x/sys/execabs/execabs_go119.go | // Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build go1.19
package execabs
import (
"errors"
"os/exec"
)
func isGo119ErrDot(err error) bool {
return errors.Is(err, exec.ErrDot)
}
func isGo119ErrFieldSet(cmd *exec.Cmd) bool {
return cmd.Err != nil
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/execabs/execabs.go | vendor/golang.org/x/sys/execabs/execabs.go | // Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package execabs is a drop-in replacement for os/exec
// that requires PATH lookups to find absolute paths.
// That is, execabs.Command("cmd") runs the same PATH lookup
// as exec.Command("cmd"), but if the result is a path
// which is relative, the Run and Start methods will report
// an error instead of running the executable.
//
// See https://blog.golang.org/path-security for more information
// about when it may be necessary or appropriate to use this package.
package execabs
import (
"context"
"fmt"
"os/exec"
"path/filepath"
"reflect"
"unsafe"
)
// ErrNotFound is the error resulting if a path search failed to find an executable file.
// It is an alias for exec.ErrNotFound.
var ErrNotFound = exec.ErrNotFound
// Cmd represents an external command being prepared or run.
// It is an alias for exec.Cmd.
type Cmd = exec.Cmd
// Error is returned by LookPath when it fails to classify a file as an executable.
// It is an alias for exec.Error.
type Error = exec.Error
// An ExitError reports an unsuccessful exit by a command.
// It is an alias for exec.ExitError.
type ExitError = exec.ExitError
func relError(file, path string) error {
return fmt.Errorf("%s resolves to executable in current directory (.%c%s)", file, filepath.Separator, path)
}
// LookPath searches for an executable named file in the directories
// named by the PATH environment variable. If file contains a slash,
// it is tried directly and the PATH is not consulted. The result will be
// an absolute path.
//
// LookPath differs from exec.LookPath in its handling of PATH lookups,
// which are used for file names without slashes. If exec.LookPath's
// PATH lookup would have returned an executable from the current directory,
// LookPath instead returns an error.
func LookPath(file string) (string, error) {
path, err := exec.LookPath(file)
if err != nil && !isGo119ErrDot(err) {
return "", err
}
if filepath.Base(file) == file && !filepath.IsAbs(path) {
return "", relError(file, path)
}
return path, nil
}
func fixCmd(name string, cmd *exec.Cmd) {
if filepath.Base(name) == name && !filepath.IsAbs(cmd.Path) && !isGo119ErrFieldSet(cmd) {
// exec.Command was called with a bare binary name and
// exec.LookPath returned a path which is not absolute.
// Set cmd.lookPathErr and clear cmd.Path so that it
// cannot be run.
lookPathErr := (*error)(unsafe.Pointer(reflect.ValueOf(cmd).Elem().FieldByName("lookPathErr").Addr().Pointer()))
if *lookPathErr == nil {
*lookPathErr = relError(name, cmd.Path)
}
cmd.Path = ""
}
}
// CommandContext is like Command but includes a context.
//
// The provided context is used to kill the process (by calling os.Process.Kill)
// if the context becomes done before the command completes on its own.
func CommandContext(ctx context.Context, name string, arg ...string) *exec.Cmd {
cmd := exec.CommandContext(ctx, name, arg...)
fixCmd(name, cmd)
return cmd
}
// Command returns the Cmd struct to execute the named program with the given arguments.
// See exec.Command for most details.
//
// Command differs from exec.Command in its handling of PATH lookups,
// which are used when the program name contains no slashes.
// If exec.Command would have returned an exec.Cmd configured to run an
// executable from the current directory, Command instead
// returns an exec.Cmd that will return an error from Start or Run.
func Command(name string, arg ...string) *exec.Cmd {
cmd := exec.Command(name, arg...)
fixCmd(name, cmd)
return cmd
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/types_windows_arm64.go | vendor/golang.org/x/sys/windows/types_windows_arm64.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package windows
type WSAData struct {
Version uint16
HighVersion uint16
MaxSockets uint16
MaxUdpDg uint16
VendorInfo *byte
Description [WSADESCRIPTION_LEN + 1]byte
SystemStatus [WSASYS_STATUS_LEN + 1]byte
}
type Servent struct {
Name *byte
Aliases **byte
Proto *byte
Port uint16
}
type JOBOBJECT_BASIC_LIMIT_INFORMATION struct {
PerProcessUserTimeLimit int64
PerJobUserTimeLimit int64
LimitFlags uint32
MinimumWorkingSetSize uintptr
MaximumWorkingSetSize uintptr
ActiveProcessLimit uint32
Affinity uintptr
PriorityClass uint32
SchedulingClass uint32
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/zsyscall_windows.go | vendor/golang.org/x/sys/windows/zsyscall_windows.go | // Code generated by 'go generate'; DO NOT EDIT.
package windows
import (
"syscall"
"unsafe"
)
var _ unsafe.Pointer
// Do the interface allocations only once for common
// Errno values.
const (
errnoERROR_IO_PENDING = 997
)
var (
errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING)
errERROR_EINVAL error = syscall.EINVAL
)
// errnoErr returns common boxed Errno values, to prevent
// allocations at runtime.
func errnoErr(e syscall.Errno) error {
switch e {
case 0:
return errERROR_EINVAL
case errnoERROR_IO_PENDING:
return errERROR_IO_PENDING
}
// TODO: add more here, after collecting data on the common
// error values see on Windows. (perhaps when running
// all.bat?)
return e
}
var (
modCfgMgr32 = NewLazySystemDLL("CfgMgr32.dll")
modadvapi32 = NewLazySystemDLL("advapi32.dll")
modcrypt32 = NewLazySystemDLL("crypt32.dll")
moddnsapi = NewLazySystemDLL("dnsapi.dll")
moddwmapi = NewLazySystemDLL("dwmapi.dll")
modiphlpapi = NewLazySystemDLL("iphlpapi.dll")
modkernel32 = NewLazySystemDLL("kernel32.dll")
modmswsock = NewLazySystemDLL("mswsock.dll")
modnetapi32 = NewLazySystemDLL("netapi32.dll")
modntdll = NewLazySystemDLL("ntdll.dll")
modole32 = NewLazySystemDLL("ole32.dll")
modpsapi = NewLazySystemDLL("psapi.dll")
modsechost = NewLazySystemDLL("sechost.dll")
modsecur32 = NewLazySystemDLL("secur32.dll")
modsetupapi = NewLazySystemDLL("setupapi.dll")
modshell32 = NewLazySystemDLL("shell32.dll")
moduser32 = NewLazySystemDLL("user32.dll")
moduserenv = NewLazySystemDLL("userenv.dll")
modversion = NewLazySystemDLL("version.dll")
modwinmm = NewLazySystemDLL("winmm.dll")
modwintrust = NewLazySystemDLL("wintrust.dll")
modws2_32 = NewLazySystemDLL("ws2_32.dll")
modwtsapi32 = NewLazySystemDLL("wtsapi32.dll")
procCM_Get_DevNode_Status = modCfgMgr32.NewProc("CM_Get_DevNode_Status")
procCM_Get_Device_Interface_ListW = modCfgMgr32.NewProc("CM_Get_Device_Interface_ListW")
procCM_Get_Device_Interface_List_SizeW = modCfgMgr32.NewProc("CM_Get_Device_Interface_List_SizeW")
procCM_MapCrToWin32Err = modCfgMgr32.NewProc("CM_MapCrToWin32Err")
procAdjustTokenGroups = modadvapi32.NewProc("AdjustTokenGroups")
procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges")
procAllocateAndInitializeSid = modadvapi32.NewProc("AllocateAndInitializeSid")
procBuildSecurityDescriptorW = modadvapi32.NewProc("BuildSecurityDescriptorW")
procChangeServiceConfig2W = modadvapi32.NewProc("ChangeServiceConfig2W")
procChangeServiceConfigW = modadvapi32.NewProc("ChangeServiceConfigW")
procCheckTokenMembership = modadvapi32.NewProc("CheckTokenMembership")
procCloseServiceHandle = modadvapi32.NewProc("CloseServiceHandle")
procControlService = modadvapi32.NewProc("ControlService")
procConvertSecurityDescriptorToStringSecurityDescriptorW = modadvapi32.NewProc("ConvertSecurityDescriptorToStringSecurityDescriptorW")
procConvertSidToStringSidW = modadvapi32.NewProc("ConvertSidToStringSidW")
procConvertStringSecurityDescriptorToSecurityDescriptorW = modadvapi32.NewProc("ConvertStringSecurityDescriptorToSecurityDescriptorW")
procConvertStringSidToSidW = modadvapi32.NewProc("ConvertStringSidToSidW")
procCopySid = modadvapi32.NewProc("CopySid")
procCreateProcessAsUserW = modadvapi32.NewProc("CreateProcessAsUserW")
procCreateServiceW = modadvapi32.NewProc("CreateServiceW")
procCreateWellKnownSid = modadvapi32.NewProc("CreateWellKnownSid")
procCryptAcquireContextW = modadvapi32.NewProc("CryptAcquireContextW")
procCryptGenRandom = modadvapi32.NewProc("CryptGenRandom")
procCryptReleaseContext = modadvapi32.NewProc("CryptReleaseContext")
procDeleteService = modadvapi32.NewProc("DeleteService")
procDeregisterEventSource = modadvapi32.NewProc("DeregisterEventSource")
procDuplicateTokenEx = modadvapi32.NewProc("DuplicateTokenEx")
procEnumDependentServicesW = modadvapi32.NewProc("EnumDependentServicesW")
procEnumServicesStatusExW = modadvapi32.NewProc("EnumServicesStatusExW")
procEqualSid = modadvapi32.NewProc("EqualSid")
procFreeSid = modadvapi32.NewProc("FreeSid")
procGetAce = modadvapi32.NewProc("GetAce")
procGetLengthSid = modadvapi32.NewProc("GetLengthSid")
procGetNamedSecurityInfoW = modadvapi32.NewProc("GetNamedSecurityInfoW")
procGetSecurityDescriptorControl = modadvapi32.NewProc("GetSecurityDescriptorControl")
procGetSecurityDescriptorDacl = modadvapi32.NewProc("GetSecurityDescriptorDacl")
procGetSecurityDescriptorGroup = modadvapi32.NewProc("GetSecurityDescriptorGroup")
procGetSecurityDescriptorLength = modadvapi32.NewProc("GetSecurityDescriptorLength")
procGetSecurityDescriptorOwner = modadvapi32.NewProc("GetSecurityDescriptorOwner")
procGetSecurityDescriptorRMControl = modadvapi32.NewProc("GetSecurityDescriptorRMControl")
procGetSecurityDescriptorSacl = modadvapi32.NewProc("GetSecurityDescriptorSacl")
procGetSecurityInfo = modadvapi32.NewProc("GetSecurityInfo")
procGetSidIdentifierAuthority = modadvapi32.NewProc("GetSidIdentifierAuthority")
procGetSidSubAuthority = modadvapi32.NewProc("GetSidSubAuthority")
procGetSidSubAuthorityCount = modadvapi32.NewProc("GetSidSubAuthorityCount")
procGetTokenInformation = modadvapi32.NewProc("GetTokenInformation")
procImpersonateSelf = modadvapi32.NewProc("ImpersonateSelf")
procInitializeSecurityDescriptor = modadvapi32.NewProc("InitializeSecurityDescriptor")
procInitiateSystemShutdownExW = modadvapi32.NewProc("InitiateSystemShutdownExW")
procIsTokenRestricted = modadvapi32.NewProc("IsTokenRestricted")
procIsValidSecurityDescriptor = modadvapi32.NewProc("IsValidSecurityDescriptor")
procIsValidSid = modadvapi32.NewProc("IsValidSid")
procIsWellKnownSid = modadvapi32.NewProc("IsWellKnownSid")
procLookupAccountNameW = modadvapi32.NewProc("LookupAccountNameW")
procLookupAccountSidW = modadvapi32.NewProc("LookupAccountSidW")
procLookupPrivilegeValueW = modadvapi32.NewProc("LookupPrivilegeValueW")
procMakeAbsoluteSD = modadvapi32.NewProc("MakeAbsoluteSD")
procMakeSelfRelativeSD = modadvapi32.NewProc("MakeSelfRelativeSD")
procNotifyServiceStatusChangeW = modadvapi32.NewProc("NotifyServiceStatusChangeW")
procOpenProcessToken = modadvapi32.NewProc("OpenProcessToken")
procOpenSCManagerW = modadvapi32.NewProc("OpenSCManagerW")
procOpenServiceW = modadvapi32.NewProc("OpenServiceW")
procOpenThreadToken = modadvapi32.NewProc("OpenThreadToken")
procQueryServiceConfig2W = modadvapi32.NewProc("QueryServiceConfig2W")
procQueryServiceConfigW = modadvapi32.NewProc("QueryServiceConfigW")
procQueryServiceDynamicInformation = modadvapi32.NewProc("QueryServiceDynamicInformation")
procQueryServiceLockStatusW = modadvapi32.NewProc("QueryServiceLockStatusW")
procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus")
procQueryServiceStatusEx = modadvapi32.NewProc("QueryServiceStatusEx")
procRegCloseKey = modadvapi32.NewProc("RegCloseKey")
procRegEnumKeyExW = modadvapi32.NewProc("RegEnumKeyExW")
procRegNotifyChangeKeyValue = modadvapi32.NewProc("RegNotifyChangeKeyValue")
procRegOpenKeyExW = modadvapi32.NewProc("RegOpenKeyExW")
procRegQueryInfoKeyW = modadvapi32.NewProc("RegQueryInfoKeyW")
procRegQueryValueExW = modadvapi32.NewProc("RegQueryValueExW")
procRegisterEventSourceW = modadvapi32.NewProc("RegisterEventSourceW")
procRegisterServiceCtrlHandlerExW = modadvapi32.NewProc("RegisterServiceCtrlHandlerExW")
procReportEventW = modadvapi32.NewProc("ReportEventW")
procRevertToSelf = modadvapi32.NewProc("RevertToSelf")
procSetEntriesInAclW = modadvapi32.NewProc("SetEntriesInAclW")
procSetKernelObjectSecurity = modadvapi32.NewProc("SetKernelObjectSecurity")
procSetNamedSecurityInfoW = modadvapi32.NewProc("SetNamedSecurityInfoW")
procSetSecurityDescriptorControl = modadvapi32.NewProc("SetSecurityDescriptorControl")
procSetSecurityDescriptorDacl = modadvapi32.NewProc("SetSecurityDescriptorDacl")
procSetSecurityDescriptorGroup = modadvapi32.NewProc("SetSecurityDescriptorGroup")
procSetSecurityDescriptorOwner = modadvapi32.NewProc("SetSecurityDescriptorOwner")
procSetSecurityDescriptorRMControl = modadvapi32.NewProc("SetSecurityDescriptorRMControl")
procSetSecurityDescriptorSacl = modadvapi32.NewProc("SetSecurityDescriptorSacl")
procSetSecurityInfo = modadvapi32.NewProc("SetSecurityInfo")
procSetServiceStatus = modadvapi32.NewProc("SetServiceStatus")
procSetThreadToken = modadvapi32.NewProc("SetThreadToken")
procSetTokenInformation = modadvapi32.NewProc("SetTokenInformation")
procStartServiceCtrlDispatcherW = modadvapi32.NewProc("StartServiceCtrlDispatcherW")
procStartServiceW = modadvapi32.NewProc("StartServiceW")
procCertAddCertificateContextToStore = modcrypt32.NewProc("CertAddCertificateContextToStore")
procCertCloseStore = modcrypt32.NewProc("CertCloseStore")
procCertCreateCertificateContext = modcrypt32.NewProc("CertCreateCertificateContext")
procCertDeleteCertificateFromStore = modcrypt32.NewProc("CertDeleteCertificateFromStore")
procCertDuplicateCertificateContext = modcrypt32.NewProc("CertDuplicateCertificateContext")
procCertEnumCertificatesInStore = modcrypt32.NewProc("CertEnumCertificatesInStore")
procCertFindCertificateInStore = modcrypt32.NewProc("CertFindCertificateInStore")
procCertFindChainInStore = modcrypt32.NewProc("CertFindChainInStore")
procCertFindExtension = modcrypt32.NewProc("CertFindExtension")
procCertFreeCertificateChain = modcrypt32.NewProc("CertFreeCertificateChain")
procCertFreeCertificateContext = modcrypt32.NewProc("CertFreeCertificateContext")
procCertGetCertificateChain = modcrypt32.NewProc("CertGetCertificateChain")
procCertGetNameStringW = modcrypt32.NewProc("CertGetNameStringW")
procCertOpenStore = modcrypt32.NewProc("CertOpenStore")
procCertOpenSystemStoreW = modcrypt32.NewProc("CertOpenSystemStoreW")
procCertVerifyCertificateChainPolicy = modcrypt32.NewProc("CertVerifyCertificateChainPolicy")
procCryptAcquireCertificatePrivateKey = modcrypt32.NewProc("CryptAcquireCertificatePrivateKey")
procCryptDecodeObject = modcrypt32.NewProc("CryptDecodeObject")
procCryptProtectData = modcrypt32.NewProc("CryptProtectData")
procCryptQueryObject = modcrypt32.NewProc("CryptQueryObject")
procCryptUnprotectData = modcrypt32.NewProc("CryptUnprotectData")
procPFXImportCertStore = modcrypt32.NewProc("PFXImportCertStore")
procDnsNameCompare_W = moddnsapi.NewProc("DnsNameCompare_W")
procDnsQuery_W = moddnsapi.NewProc("DnsQuery_W")
procDnsRecordListFree = moddnsapi.NewProc("DnsRecordListFree")
procDwmGetWindowAttribute = moddwmapi.NewProc("DwmGetWindowAttribute")
procDwmSetWindowAttribute = moddwmapi.NewProc("DwmSetWindowAttribute")
procCancelMibChangeNotify2 = modiphlpapi.NewProc("CancelMibChangeNotify2")
procFreeMibTable = modiphlpapi.NewProc("FreeMibTable")
procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses")
procGetAdaptersInfo = modiphlpapi.NewProc("GetAdaptersInfo")
procGetBestInterfaceEx = modiphlpapi.NewProc("GetBestInterfaceEx")
procGetIfEntry = modiphlpapi.NewProc("GetIfEntry")
procGetIfEntry2Ex = modiphlpapi.NewProc("GetIfEntry2Ex")
procGetIpForwardEntry2 = modiphlpapi.NewProc("GetIpForwardEntry2")
procGetIpForwardTable2 = modiphlpapi.NewProc("GetIpForwardTable2")
procGetUnicastIpAddressEntry = modiphlpapi.NewProc("GetUnicastIpAddressEntry")
procNotifyIpInterfaceChange = modiphlpapi.NewProc("NotifyIpInterfaceChange")
procNotifyRouteChange2 = modiphlpapi.NewProc("NotifyRouteChange2")
procNotifyUnicastIpAddressChange = modiphlpapi.NewProc("NotifyUnicastIpAddressChange")
procAddDllDirectory = modkernel32.NewProc("AddDllDirectory")
procAssignProcessToJobObject = modkernel32.NewProc("AssignProcessToJobObject")
procCancelIo = modkernel32.NewProc("CancelIo")
procCancelIoEx = modkernel32.NewProc("CancelIoEx")
procClearCommBreak = modkernel32.NewProc("ClearCommBreak")
procClearCommError = modkernel32.NewProc("ClearCommError")
procCloseHandle = modkernel32.NewProc("CloseHandle")
procClosePseudoConsole = modkernel32.NewProc("ClosePseudoConsole")
procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe")
procCreateDirectoryW = modkernel32.NewProc("CreateDirectoryW")
procCreateEventExW = modkernel32.NewProc("CreateEventExW")
procCreateEventW = modkernel32.NewProc("CreateEventW")
procCreateFileMappingW = modkernel32.NewProc("CreateFileMappingW")
procCreateFileW = modkernel32.NewProc("CreateFileW")
procCreateHardLinkW = modkernel32.NewProc("CreateHardLinkW")
procCreateIoCompletionPort = modkernel32.NewProc("CreateIoCompletionPort")
procCreateJobObjectW = modkernel32.NewProc("CreateJobObjectW")
procCreateMutexExW = modkernel32.NewProc("CreateMutexExW")
procCreateMutexW = modkernel32.NewProc("CreateMutexW")
procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW")
procCreatePipe = modkernel32.NewProc("CreatePipe")
procCreateProcessW = modkernel32.NewProc("CreateProcessW")
procCreatePseudoConsole = modkernel32.NewProc("CreatePseudoConsole")
procCreateSymbolicLinkW = modkernel32.NewProc("CreateSymbolicLinkW")
procCreateToolhelp32Snapshot = modkernel32.NewProc("CreateToolhelp32Snapshot")
procDefineDosDeviceW = modkernel32.NewProc("DefineDosDeviceW")
procDeleteFileW = modkernel32.NewProc("DeleteFileW")
procDeleteProcThreadAttributeList = modkernel32.NewProc("DeleteProcThreadAttributeList")
procDeleteVolumeMountPointW = modkernel32.NewProc("DeleteVolumeMountPointW")
procDeviceIoControl = modkernel32.NewProc("DeviceIoControl")
procDisconnectNamedPipe = modkernel32.NewProc("DisconnectNamedPipe")
procDuplicateHandle = modkernel32.NewProc("DuplicateHandle")
procEscapeCommFunction = modkernel32.NewProc("EscapeCommFunction")
procExitProcess = modkernel32.NewProc("ExitProcess")
procExpandEnvironmentStringsW = modkernel32.NewProc("ExpandEnvironmentStringsW")
procFindClose = modkernel32.NewProc("FindClose")
procFindCloseChangeNotification = modkernel32.NewProc("FindCloseChangeNotification")
procFindFirstChangeNotificationW = modkernel32.NewProc("FindFirstChangeNotificationW")
procFindFirstFileW = modkernel32.NewProc("FindFirstFileW")
procFindFirstVolumeMountPointW = modkernel32.NewProc("FindFirstVolumeMountPointW")
procFindFirstVolumeW = modkernel32.NewProc("FindFirstVolumeW")
procFindNextChangeNotification = modkernel32.NewProc("FindNextChangeNotification")
procFindNextFileW = modkernel32.NewProc("FindNextFileW")
procFindNextVolumeMountPointW = modkernel32.NewProc("FindNextVolumeMountPointW")
procFindNextVolumeW = modkernel32.NewProc("FindNextVolumeW")
procFindResourceW = modkernel32.NewProc("FindResourceW")
procFindVolumeClose = modkernel32.NewProc("FindVolumeClose")
procFindVolumeMountPointClose = modkernel32.NewProc("FindVolumeMountPointClose")
procFlushConsoleInputBuffer = modkernel32.NewProc("FlushConsoleInputBuffer")
procFlushFileBuffers = modkernel32.NewProc("FlushFileBuffers")
procFlushViewOfFile = modkernel32.NewProc("FlushViewOfFile")
procFormatMessageW = modkernel32.NewProc("FormatMessageW")
procFreeEnvironmentStringsW = modkernel32.NewProc("FreeEnvironmentStringsW")
procFreeLibrary = modkernel32.NewProc("FreeLibrary")
procGenerateConsoleCtrlEvent = modkernel32.NewProc("GenerateConsoleCtrlEvent")
procGetACP = modkernel32.NewProc("GetACP")
procGetActiveProcessorCount = modkernel32.NewProc("GetActiveProcessorCount")
procGetCommModemStatus = modkernel32.NewProc("GetCommModemStatus")
procGetCommState = modkernel32.NewProc("GetCommState")
procGetCommTimeouts = modkernel32.NewProc("GetCommTimeouts")
procGetCommandLineW = modkernel32.NewProc("GetCommandLineW")
procGetComputerNameExW = modkernel32.NewProc("GetComputerNameExW")
procGetComputerNameW = modkernel32.NewProc("GetComputerNameW")
procGetConsoleCP = modkernel32.NewProc("GetConsoleCP")
procGetConsoleMode = modkernel32.NewProc("GetConsoleMode")
procGetConsoleOutputCP = modkernel32.NewProc("GetConsoleOutputCP")
procGetConsoleScreenBufferInfo = modkernel32.NewProc("GetConsoleScreenBufferInfo")
procGetCurrentDirectoryW = modkernel32.NewProc("GetCurrentDirectoryW")
procGetCurrentProcessId = modkernel32.NewProc("GetCurrentProcessId")
procGetCurrentThreadId = modkernel32.NewProc("GetCurrentThreadId")
procGetDiskFreeSpaceExW = modkernel32.NewProc("GetDiskFreeSpaceExW")
procGetDriveTypeW = modkernel32.NewProc("GetDriveTypeW")
procGetEnvironmentStringsW = modkernel32.NewProc("GetEnvironmentStringsW")
procGetEnvironmentVariableW = modkernel32.NewProc("GetEnvironmentVariableW")
procGetExitCodeProcess = modkernel32.NewProc("GetExitCodeProcess")
procGetFileAttributesExW = modkernel32.NewProc("GetFileAttributesExW")
procGetFileAttributesW = modkernel32.NewProc("GetFileAttributesW")
procGetFileInformationByHandle = modkernel32.NewProc("GetFileInformationByHandle")
procGetFileInformationByHandleEx = modkernel32.NewProc("GetFileInformationByHandleEx")
procGetFileTime = modkernel32.NewProc("GetFileTime")
procGetFileType = modkernel32.NewProc("GetFileType")
procGetFinalPathNameByHandleW = modkernel32.NewProc("GetFinalPathNameByHandleW")
procGetFullPathNameW = modkernel32.NewProc("GetFullPathNameW")
procGetLargePageMinimum = modkernel32.NewProc("GetLargePageMinimum")
procGetLastError = modkernel32.NewProc("GetLastError")
procGetLogicalDriveStringsW = modkernel32.NewProc("GetLogicalDriveStringsW")
procGetLogicalDrives = modkernel32.NewProc("GetLogicalDrives")
procGetLongPathNameW = modkernel32.NewProc("GetLongPathNameW")
procGetMaximumProcessorCount = modkernel32.NewProc("GetMaximumProcessorCount")
procGetModuleFileNameW = modkernel32.NewProc("GetModuleFileNameW")
procGetModuleHandleExW = modkernel32.NewProc("GetModuleHandleExW")
procGetNamedPipeClientProcessId = modkernel32.NewProc("GetNamedPipeClientProcessId")
procGetNamedPipeHandleStateW = modkernel32.NewProc("GetNamedPipeHandleStateW")
procGetNamedPipeInfo = modkernel32.NewProc("GetNamedPipeInfo")
procGetNamedPipeServerProcessId = modkernel32.NewProc("GetNamedPipeServerProcessId")
procGetNumberOfConsoleInputEvents = modkernel32.NewProc("GetNumberOfConsoleInputEvents")
procGetOverlappedResult = modkernel32.NewProc("GetOverlappedResult")
procGetPriorityClass = modkernel32.NewProc("GetPriorityClass")
procGetProcAddress = modkernel32.NewProc("GetProcAddress")
procGetProcessId = modkernel32.NewProc("GetProcessId")
procGetProcessPreferredUILanguages = modkernel32.NewProc("GetProcessPreferredUILanguages")
procGetProcessShutdownParameters = modkernel32.NewProc("GetProcessShutdownParameters")
procGetProcessTimes = modkernel32.NewProc("GetProcessTimes")
procGetProcessWorkingSetSizeEx = modkernel32.NewProc("GetProcessWorkingSetSizeEx")
procGetQueuedCompletionStatus = modkernel32.NewProc("GetQueuedCompletionStatus")
procGetShortPathNameW = modkernel32.NewProc("GetShortPathNameW")
procGetStartupInfoW = modkernel32.NewProc("GetStartupInfoW")
procGetStdHandle = modkernel32.NewProc("GetStdHandle")
procGetSystemDirectoryW = modkernel32.NewProc("GetSystemDirectoryW")
procGetSystemPreferredUILanguages = modkernel32.NewProc("GetSystemPreferredUILanguages")
procGetSystemTimeAsFileTime = modkernel32.NewProc("GetSystemTimeAsFileTime")
procGetSystemTimePreciseAsFileTime = modkernel32.NewProc("GetSystemTimePreciseAsFileTime")
procGetSystemWindowsDirectoryW = modkernel32.NewProc("GetSystemWindowsDirectoryW")
procGetTempPathW = modkernel32.NewProc("GetTempPathW")
procGetThreadPreferredUILanguages = modkernel32.NewProc("GetThreadPreferredUILanguages")
procGetTickCount64 = modkernel32.NewProc("GetTickCount64")
procGetTimeZoneInformation = modkernel32.NewProc("GetTimeZoneInformation")
procGetUserPreferredUILanguages = modkernel32.NewProc("GetUserPreferredUILanguages")
procGetVersion = modkernel32.NewProc("GetVersion")
procGetVolumeInformationByHandleW = modkernel32.NewProc("GetVolumeInformationByHandleW")
procGetVolumeInformationW = modkernel32.NewProc("GetVolumeInformationW")
procGetVolumeNameForVolumeMountPointW = modkernel32.NewProc("GetVolumeNameForVolumeMountPointW")
procGetVolumePathNameW = modkernel32.NewProc("GetVolumePathNameW")
procGetVolumePathNamesForVolumeNameW = modkernel32.NewProc("GetVolumePathNamesForVolumeNameW")
procGetWindowsDirectoryW = modkernel32.NewProc("GetWindowsDirectoryW")
procInitializeProcThreadAttributeList = modkernel32.NewProc("InitializeProcThreadAttributeList")
procIsWow64Process = modkernel32.NewProc("IsWow64Process")
procIsWow64Process2 = modkernel32.NewProc("IsWow64Process2")
procLoadLibraryExW = modkernel32.NewProc("LoadLibraryExW")
procLoadLibraryW = modkernel32.NewProc("LoadLibraryW")
procLoadResource = modkernel32.NewProc("LoadResource")
procLocalAlloc = modkernel32.NewProc("LocalAlloc")
procLocalFree = modkernel32.NewProc("LocalFree")
procLockFileEx = modkernel32.NewProc("LockFileEx")
procLockResource = modkernel32.NewProc("LockResource")
procMapViewOfFile = modkernel32.NewProc("MapViewOfFile")
procModule32FirstW = modkernel32.NewProc("Module32FirstW")
procModule32NextW = modkernel32.NewProc("Module32NextW")
procMoveFileExW = modkernel32.NewProc("MoveFileExW")
procMoveFileW = modkernel32.NewProc("MoveFileW")
procMultiByteToWideChar = modkernel32.NewProc("MultiByteToWideChar")
procOpenEventW = modkernel32.NewProc("OpenEventW")
procOpenMutexW = modkernel32.NewProc("OpenMutexW")
procOpenProcess = modkernel32.NewProc("OpenProcess")
procOpenThread = modkernel32.NewProc("OpenThread")
procPostQueuedCompletionStatus = modkernel32.NewProc("PostQueuedCompletionStatus")
procProcess32FirstW = modkernel32.NewProc("Process32FirstW")
procProcess32NextW = modkernel32.NewProc("Process32NextW")
procProcessIdToSessionId = modkernel32.NewProc("ProcessIdToSessionId")
procPulseEvent = modkernel32.NewProc("PulseEvent")
procPurgeComm = modkernel32.NewProc("PurgeComm")
procQueryDosDeviceW = modkernel32.NewProc("QueryDosDeviceW")
procQueryFullProcessImageNameW = modkernel32.NewProc("QueryFullProcessImageNameW")
procQueryInformationJobObject = modkernel32.NewProc("QueryInformationJobObject")
procReadConsoleW = modkernel32.NewProc("ReadConsoleW")
procReadDirectoryChangesW = modkernel32.NewProc("ReadDirectoryChangesW")
procReadFile = modkernel32.NewProc("ReadFile")
procReadProcessMemory = modkernel32.NewProc("ReadProcessMemory")
procReleaseMutex = modkernel32.NewProc("ReleaseMutex")
procRemoveDirectoryW = modkernel32.NewProc("RemoveDirectoryW")
procRemoveDllDirectory = modkernel32.NewProc("RemoveDllDirectory")
procResetEvent = modkernel32.NewProc("ResetEvent")
procResizePseudoConsole = modkernel32.NewProc("ResizePseudoConsole")
procResumeThread = modkernel32.NewProc("ResumeThread")
procSetCommBreak = modkernel32.NewProc("SetCommBreak")
procSetCommMask = modkernel32.NewProc("SetCommMask")
procSetCommState = modkernel32.NewProc("SetCommState")
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | true |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/race0.go | vendor/golang.org/x/sys/windows/race0.go | // Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build windows && !race
package windows
import (
"unsafe"
)
const raceenabled = false
func raceAcquire(addr unsafe.Pointer) {
}
func raceReleaseMerge(addr unsafe.Pointer) {
}
func raceReadRange(addr unsafe.Pointer, len int) {
}
func raceWriteRange(addr unsafe.Pointer, len int) {
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/security_windows.go | vendor/golang.org/x/sys/windows/security_windows.go | // Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package windows
import (
"syscall"
"unsafe"
)
const (
NameUnknown = 0
NameFullyQualifiedDN = 1
NameSamCompatible = 2
NameDisplay = 3
NameUniqueId = 6
NameCanonical = 7
NameUserPrincipal = 8
NameCanonicalEx = 9
NameServicePrincipal = 10
NameDnsDomain = 12
)
// This function returns 1 byte BOOLEAN rather than the 4 byte BOOL.
// http://blogs.msdn.com/b/drnick/archive/2007/12/19/windows-and-upn-format-credentials.aspx
//sys TranslateName(accName *uint16, accNameFormat uint32, desiredNameFormat uint32, translatedName *uint16, nSize *uint32) (err error) [failretval&0xff==0] = secur32.TranslateNameW
//sys GetUserNameEx(nameFormat uint32, nameBuffre *uint16, nSize *uint32) (err error) [failretval&0xff==0] = secur32.GetUserNameExW
// TranslateAccountName converts a directory service
// object name from one format to another.
func TranslateAccountName(username string, from, to uint32, initSize int) (string, error) {
u, e := UTF16PtrFromString(username)
if e != nil {
return "", e
}
n := uint32(50)
for {
b := make([]uint16, n)
e = TranslateName(u, from, to, &b[0], &n)
if e == nil {
return UTF16ToString(b[:n]), nil
}
if e != ERROR_INSUFFICIENT_BUFFER {
return "", e
}
if n <= uint32(len(b)) {
return "", e
}
}
}
const (
// do not reorder
NetSetupUnknownStatus = iota
NetSetupUnjoined
NetSetupWorkgroupName
NetSetupDomainName
)
type UserInfo10 struct {
Name *uint16
Comment *uint16
UsrComment *uint16
FullName *uint16
}
//sys NetUserGetInfo(serverName *uint16, userName *uint16, level uint32, buf **byte) (neterr error) = netapi32.NetUserGetInfo
//sys NetGetJoinInformation(server *uint16, name **uint16, bufType *uint32) (neterr error) = netapi32.NetGetJoinInformation
//sys NetApiBufferFree(buf *byte) (neterr error) = netapi32.NetApiBufferFree
//sys NetUserEnum(serverName *uint16, level uint32, filter uint32, buf **byte, prefMaxLen uint32, entriesRead *uint32, totalEntries *uint32, resumeHandle *uint32) (neterr error) = netapi32.NetUserEnum
const (
// do not reorder
SidTypeUser = 1 + iota
SidTypeGroup
SidTypeDomain
SidTypeAlias
SidTypeWellKnownGroup
SidTypeDeletedAccount
SidTypeInvalid
SidTypeUnknown
SidTypeComputer
SidTypeLabel
)
type SidIdentifierAuthority struct {
Value [6]byte
}
var (
SECURITY_NULL_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 0}}
SECURITY_WORLD_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 1}}
SECURITY_LOCAL_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 2}}
SECURITY_CREATOR_SID_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 3}}
SECURITY_NON_UNIQUE_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 4}}
SECURITY_NT_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 5}}
SECURITY_MANDATORY_LABEL_AUTHORITY = SidIdentifierAuthority{[6]byte{0, 0, 0, 0, 0, 16}}
)
const (
SECURITY_NULL_RID = 0
SECURITY_WORLD_RID = 0
SECURITY_LOCAL_RID = 0
SECURITY_CREATOR_OWNER_RID = 0
SECURITY_CREATOR_GROUP_RID = 1
SECURITY_DIALUP_RID = 1
SECURITY_NETWORK_RID = 2
SECURITY_BATCH_RID = 3
SECURITY_INTERACTIVE_RID = 4
SECURITY_LOGON_IDS_RID = 5
SECURITY_SERVICE_RID = 6
SECURITY_LOCAL_SYSTEM_RID = 18
SECURITY_BUILTIN_DOMAIN_RID = 32
SECURITY_PRINCIPAL_SELF_RID = 10
SECURITY_CREATOR_OWNER_SERVER_RID = 0x2
SECURITY_CREATOR_GROUP_SERVER_RID = 0x3
SECURITY_LOGON_IDS_RID_COUNT = 0x3
SECURITY_ANONYMOUS_LOGON_RID = 0x7
SECURITY_PROXY_RID = 0x8
SECURITY_ENTERPRISE_CONTROLLERS_RID = 0x9
SECURITY_SERVER_LOGON_RID = SECURITY_ENTERPRISE_CONTROLLERS_RID
SECURITY_AUTHENTICATED_USER_RID = 0xb
SECURITY_RESTRICTED_CODE_RID = 0xc
SECURITY_NT_NON_UNIQUE_RID = 0x15
)
// Predefined domain-relative RIDs for local groups.
// See https://msdn.microsoft.com/en-us/library/windows/desktop/aa379649(v=vs.85).aspx
const (
DOMAIN_ALIAS_RID_ADMINS = 0x220
DOMAIN_ALIAS_RID_USERS = 0x221
DOMAIN_ALIAS_RID_GUESTS = 0x222
DOMAIN_ALIAS_RID_POWER_USERS = 0x223
DOMAIN_ALIAS_RID_ACCOUNT_OPS = 0x224
DOMAIN_ALIAS_RID_SYSTEM_OPS = 0x225
DOMAIN_ALIAS_RID_PRINT_OPS = 0x226
DOMAIN_ALIAS_RID_BACKUP_OPS = 0x227
DOMAIN_ALIAS_RID_REPLICATOR = 0x228
DOMAIN_ALIAS_RID_RAS_SERVERS = 0x229
DOMAIN_ALIAS_RID_PREW2KCOMPACCESS = 0x22a
DOMAIN_ALIAS_RID_REMOTE_DESKTOP_USERS = 0x22b
DOMAIN_ALIAS_RID_NETWORK_CONFIGURATION_OPS = 0x22c
DOMAIN_ALIAS_RID_INCOMING_FOREST_TRUST_BUILDERS = 0x22d
DOMAIN_ALIAS_RID_MONITORING_USERS = 0x22e
DOMAIN_ALIAS_RID_LOGGING_USERS = 0x22f
DOMAIN_ALIAS_RID_AUTHORIZATIONACCESS = 0x230
DOMAIN_ALIAS_RID_TS_LICENSE_SERVERS = 0x231
DOMAIN_ALIAS_RID_DCOM_USERS = 0x232
DOMAIN_ALIAS_RID_IUSERS = 0x238
DOMAIN_ALIAS_RID_CRYPTO_OPERATORS = 0x239
DOMAIN_ALIAS_RID_CACHEABLE_PRINCIPALS_GROUP = 0x23b
DOMAIN_ALIAS_RID_NON_CACHEABLE_PRINCIPALS_GROUP = 0x23c
DOMAIN_ALIAS_RID_EVENT_LOG_READERS_GROUP = 0x23d
DOMAIN_ALIAS_RID_CERTSVC_DCOM_ACCESS_GROUP = 0x23e
)
//sys LookupAccountSid(systemName *uint16, sid *SID, name *uint16, nameLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) = advapi32.LookupAccountSidW
//sys LookupAccountName(systemName *uint16, accountName *uint16, sid *SID, sidLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) = advapi32.LookupAccountNameW
//sys ConvertSidToStringSid(sid *SID, stringSid **uint16) (err error) = advapi32.ConvertSidToStringSidW
//sys ConvertStringSidToSid(stringSid *uint16, sid **SID) (err error) = advapi32.ConvertStringSidToSidW
//sys GetLengthSid(sid *SID) (len uint32) = advapi32.GetLengthSid
//sys CopySid(destSidLen uint32, destSid *SID, srcSid *SID) (err error) = advapi32.CopySid
//sys AllocateAndInitializeSid(identAuth *SidIdentifierAuthority, subAuth byte, subAuth0 uint32, subAuth1 uint32, subAuth2 uint32, subAuth3 uint32, subAuth4 uint32, subAuth5 uint32, subAuth6 uint32, subAuth7 uint32, sid **SID) (err error) = advapi32.AllocateAndInitializeSid
//sys createWellKnownSid(sidType WELL_KNOWN_SID_TYPE, domainSid *SID, sid *SID, sizeSid *uint32) (err error) = advapi32.CreateWellKnownSid
//sys isWellKnownSid(sid *SID, sidType WELL_KNOWN_SID_TYPE) (isWellKnown bool) = advapi32.IsWellKnownSid
//sys FreeSid(sid *SID) (err error) [failretval!=0] = advapi32.FreeSid
//sys EqualSid(sid1 *SID, sid2 *SID) (isEqual bool) = advapi32.EqualSid
//sys getSidIdentifierAuthority(sid *SID) (authority *SidIdentifierAuthority) = advapi32.GetSidIdentifierAuthority
//sys getSidSubAuthorityCount(sid *SID) (count *uint8) = advapi32.GetSidSubAuthorityCount
//sys getSidSubAuthority(sid *SID, index uint32) (subAuthority *uint32) = advapi32.GetSidSubAuthority
//sys isValidSid(sid *SID) (isValid bool) = advapi32.IsValidSid
// The security identifier (SID) structure is a variable-length
// structure used to uniquely identify users or groups.
type SID struct{}
// StringToSid converts a string-format security identifier
// SID into a valid, functional SID.
func StringToSid(s string) (*SID, error) {
var sid *SID
p, e := UTF16PtrFromString(s)
if e != nil {
return nil, e
}
e = ConvertStringSidToSid(p, &sid)
if e != nil {
return nil, e
}
defer LocalFree((Handle)(unsafe.Pointer(sid)))
return sid.Copy()
}
// LookupSID retrieves a security identifier SID for the account
// and the name of the domain on which the account was found.
// System specify target computer to search.
func LookupSID(system, account string) (sid *SID, domain string, accType uint32, err error) {
if len(account) == 0 {
return nil, "", 0, syscall.EINVAL
}
acc, e := UTF16PtrFromString(account)
if e != nil {
return nil, "", 0, e
}
var sys *uint16
if len(system) > 0 {
sys, e = UTF16PtrFromString(system)
if e != nil {
return nil, "", 0, e
}
}
n := uint32(50)
dn := uint32(50)
for {
b := make([]byte, n)
db := make([]uint16, dn)
sid = (*SID)(unsafe.Pointer(&b[0]))
e = LookupAccountName(sys, acc, sid, &n, &db[0], &dn, &accType)
if e == nil {
return sid, UTF16ToString(db), accType, nil
}
if e != ERROR_INSUFFICIENT_BUFFER {
return nil, "", 0, e
}
if n <= uint32(len(b)) {
return nil, "", 0, e
}
}
}
// String converts SID to a string format suitable for display, storage, or transmission.
func (sid *SID) String() string {
var s *uint16
e := ConvertSidToStringSid(sid, &s)
if e != nil {
return ""
}
defer LocalFree((Handle)(unsafe.Pointer(s)))
return UTF16ToString((*[256]uint16)(unsafe.Pointer(s))[:])
}
// Len returns the length, in bytes, of a valid security identifier SID.
func (sid *SID) Len() int {
return int(GetLengthSid(sid))
}
// Copy creates a duplicate of security identifier SID.
func (sid *SID) Copy() (*SID, error) {
b := make([]byte, sid.Len())
sid2 := (*SID)(unsafe.Pointer(&b[0]))
e := CopySid(uint32(len(b)), sid2, sid)
if e != nil {
return nil, e
}
return sid2, nil
}
// IdentifierAuthority returns the identifier authority of the SID.
func (sid *SID) IdentifierAuthority() SidIdentifierAuthority {
return *getSidIdentifierAuthority(sid)
}
// SubAuthorityCount returns the number of sub-authorities in the SID.
func (sid *SID) SubAuthorityCount() uint8 {
return *getSidSubAuthorityCount(sid)
}
// SubAuthority returns the sub-authority of the SID as specified by
// the index, which must be less than sid.SubAuthorityCount().
func (sid *SID) SubAuthority(idx uint32) uint32 {
if idx >= uint32(sid.SubAuthorityCount()) {
panic("sub-authority index out of range")
}
return *getSidSubAuthority(sid, idx)
}
// IsValid returns whether the SID has a valid revision and length.
func (sid *SID) IsValid() bool {
return isValidSid(sid)
}
// Equals compares two SIDs for equality.
func (sid *SID) Equals(sid2 *SID) bool {
return EqualSid(sid, sid2)
}
// IsWellKnown determines whether the SID matches the well-known sidType.
func (sid *SID) IsWellKnown(sidType WELL_KNOWN_SID_TYPE) bool {
return isWellKnownSid(sid, sidType)
}
// LookupAccount retrieves the name of the account for this SID
// and the name of the first domain on which this SID is found.
// System specify target computer to search for.
func (sid *SID) LookupAccount(system string) (account, domain string, accType uint32, err error) {
var sys *uint16
if len(system) > 0 {
sys, err = UTF16PtrFromString(system)
if err != nil {
return "", "", 0, err
}
}
n := uint32(50)
dn := uint32(50)
for {
b := make([]uint16, n)
db := make([]uint16, dn)
e := LookupAccountSid(sys, sid, &b[0], &n, &db[0], &dn, &accType)
if e == nil {
return UTF16ToString(b), UTF16ToString(db), accType, nil
}
if e != ERROR_INSUFFICIENT_BUFFER {
return "", "", 0, e
}
if n <= uint32(len(b)) {
return "", "", 0, e
}
}
}
// Various types of pre-specified SIDs that can be synthesized and compared at runtime.
type WELL_KNOWN_SID_TYPE uint32
const (
WinNullSid = 0
WinWorldSid = 1
WinLocalSid = 2
WinCreatorOwnerSid = 3
WinCreatorGroupSid = 4
WinCreatorOwnerServerSid = 5
WinCreatorGroupServerSid = 6
WinNtAuthoritySid = 7
WinDialupSid = 8
WinNetworkSid = 9
WinBatchSid = 10
WinInteractiveSid = 11
WinServiceSid = 12
WinAnonymousSid = 13
WinProxySid = 14
WinEnterpriseControllersSid = 15
WinSelfSid = 16
WinAuthenticatedUserSid = 17
WinRestrictedCodeSid = 18
WinTerminalServerSid = 19
WinRemoteLogonIdSid = 20
WinLogonIdsSid = 21
WinLocalSystemSid = 22
WinLocalServiceSid = 23
WinNetworkServiceSid = 24
WinBuiltinDomainSid = 25
WinBuiltinAdministratorsSid = 26
WinBuiltinUsersSid = 27
WinBuiltinGuestsSid = 28
WinBuiltinPowerUsersSid = 29
WinBuiltinAccountOperatorsSid = 30
WinBuiltinSystemOperatorsSid = 31
WinBuiltinPrintOperatorsSid = 32
WinBuiltinBackupOperatorsSid = 33
WinBuiltinReplicatorSid = 34
WinBuiltinPreWindows2000CompatibleAccessSid = 35
WinBuiltinRemoteDesktopUsersSid = 36
WinBuiltinNetworkConfigurationOperatorsSid = 37
WinAccountAdministratorSid = 38
WinAccountGuestSid = 39
WinAccountKrbtgtSid = 40
WinAccountDomainAdminsSid = 41
WinAccountDomainUsersSid = 42
WinAccountDomainGuestsSid = 43
WinAccountComputersSid = 44
WinAccountControllersSid = 45
WinAccountCertAdminsSid = 46
WinAccountSchemaAdminsSid = 47
WinAccountEnterpriseAdminsSid = 48
WinAccountPolicyAdminsSid = 49
WinAccountRasAndIasServersSid = 50
WinNTLMAuthenticationSid = 51
WinDigestAuthenticationSid = 52
WinSChannelAuthenticationSid = 53
WinThisOrganizationSid = 54
WinOtherOrganizationSid = 55
WinBuiltinIncomingForestTrustBuildersSid = 56
WinBuiltinPerfMonitoringUsersSid = 57
WinBuiltinPerfLoggingUsersSid = 58
WinBuiltinAuthorizationAccessSid = 59
WinBuiltinTerminalServerLicenseServersSid = 60
WinBuiltinDCOMUsersSid = 61
WinBuiltinIUsersSid = 62
WinIUserSid = 63
WinBuiltinCryptoOperatorsSid = 64
WinUntrustedLabelSid = 65
WinLowLabelSid = 66
WinMediumLabelSid = 67
WinHighLabelSid = 68
WinSystemLabelSid = 69
WinWriteRestrictedCodeSid = 70
WinCreatorOwnerRightsSid = 71
WinCacheablePrincipalsGroupSid = 72
WinNonCacheablePrincipalsGroupSid = 73
WinEnterpriseReadonlyControllersSid = 74
WinAccountReadonlyControllersSid = 75
WinBuiltinEventLogReadersGroup = 76
WinNewEnterpriseReadonlyControllersSid = 77
WinBuiltinCertSvcDComAccessGroup = 78
WinMediumPlusLabelSid = 79
WinLocalLogonSid = 80
WinConsoleLogonSid = 81
WinThisOrganizationCertificateSid = 82
WinApplicationPackageAuthoritySid = 83
WinBuiltinAnyPackageSid = 84
WinCapabilityInternetClientSid = 85
WinCapabilityInternetClientServerSid = 86
WinCapabilityPrivateNetworkClientServerSid = 87
WinCapabilityPicturesLibrarySid = 88
WinCapabilityVideosLibrarySid = 89
WinCapabilityMusicLibrarySid = 90
WinCapabilityDocumentsLibrarySid = 91
WinCapabilitySharedUserCertificatesSid = 92
WinCapabilityEnterpriseAuthenticationSid = 93
WinCapabilityRemovableStorageSid = 94
WinBuiltinRDSRemoteAccessServersSid = 95
WinBuiltinRDSEndpointServersSid = 96
WinBuiltinRDSManagementServersSid = 97
WinUserModeDriversSid = 98
WinBuiltinHyperVAdminsSid = 99
WinAccountCloneableControllersSid = 100
WinBuiltinAccessControlAssistanceOperatorsSid = 101
WinBuiltinRemoteManagementUsersSid = 102
WinAuthenticationAuthorityAssertedSid = 103
WinAuthenticationServiceAssertedSid = 104
WinLocalAccountSid = 105
WinLocalAccountAndAdministratorSid = 106
WinAccountProtectedUsersSid = 107
WinCapabilityAppointmentsSid = 108
WinCapabilityContactsSid = 109
WinAccountDefaultSystemManagedSid = 110
WinBuiltinDefaultSystemManagedGroupSid = 111
WinBuiltinStorageReplicaAdminsSid = 112
WinAccountKeyAdminsSid = 113
WinAccountEnterpriseKeyAdminsSid = 114
WinAuthenticationKeyTrustSid = 115
WinAuthenticationKeyPropertyMFASid = 116
WinAuthenticationKeyPropertyAttestationSid = 117
WinAuthenticationFreshKeyAuthSid = 118
WinBuiltinDeviceOwnersSid = 119
)
// Creates a SID for a well-known predefined alias, generally using the constants of the form
// Win*Sid, for the local machine.
func CreateWellKnownSid(sidType WELL_KNOWN_SID_TYPE) (*SID, error) {
return CreateWellKnownDomainSid(sidType, nil)
}
// Creates a SID for a well-known predefined alias, generally using the constants of the form
// Win*Sid, for the domain specified by the domainSid parameter.
func CreateWellKnownDomainSid(sidType WELL_KNOWN_SID_TYPE, domainSid *SID) (*SID, error) {
n := uint32(50)
for {
b := make([]byte, n)
sid := (*SID)(unsafe.Pointer(&b[0]))
err := createWellKnownSid(sidType, domainSid, sid, &n)
if err == nil {
return sid, nil
}
if err != ERROR_INSUFFICIENT_BUFFER {
return nil, err
}
if n <= uint32(len(b)) {
return nil, err
}
}
}
const (
// do not reorder
TOKEN_ASSIGN_PRIMARY = 1 << iota
TOKEN_DUPLICATE
TOKEN_IMPERSONATE
TOKEN_QUERY
TOKEN_QUERY_SOURCE
TOKEN_ADJUST_PRIVILEGES
TOKEN_ADJUST_GROUPS
TOKEN_ADJUST_DEFAULT
TOKEN_ADJUST_SESSIONID
TOKEN_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED |
TOKEN_ASSIGN_PRIMARY |
TOKEN_DUPLICATE |
TOKEN_IMPERSONATE |
TOKEN_QUERY |
TOKEN_QUERY_SOURCE |
TOKEN_ADJUST_PRIVILEGES |
TOKEN_ADJUST_GROUPS |
TOKEN_ADJUST_DEFAULT |
TOKEN_ADJUST_SESSIONID
TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY
TOKEN_WRITE = STANDARD_RIGHTS_WRITE |
TOKEN_ADJUST_PRIVILEGES |
TOKEN_ADJUST_GROUPS |
TOKEN_ADJUST_DEFAULT
TOKEN_EXECUTE = STANDARD_RIGHTS_EXECUTE
)
const (
// do not reorder
TokenUser = 1 + iota
TokenGroups
TokenPrivileges
TokenOwner
TokenPrimaryGroup
TokenDefaultDacl
TokenSource
TokenType
TokenImpersonationLevel
TokenStatistics
TokenRestrictedSids
TokenSessionId
TokenGroupsAndPrivileges
TokenSessionReference
TokenSandBoxInert
TokenAuditPolicy
TokenOrigin
TokenElevationType
TokenLinkedToken
TokenElevation
TokenHasRestrictions
TokenAccessInformation
TokenVirtualizationAllowed
TokenVirtualizationEnabled
TokenIntegrityLevel
TokenUIAccess
TokenMandatoryPolicy
TokenLogonSid
MaxTokenInfoClass
)
// Group attributes inside of Tokengroups.Groups[i].Attributes
const (
SE_GROUP_MANDATORY = 0x00000001
SE_GROUP_ENABLED_BY_DEFAULT = 0x00000002
SE_GROUP_ENABLED = 0x00000004
SE_GROUP_OWNER = 0x00000008
SE_GROUP_USE_FOR_DENY_ONLY = 0x00000010
SE_GROUP_INTEGRITY = 0x00000020
SE_GROUP_INTEGRITY_ENABLED = 0x00000040
SE_GROUP_LOGON_ID = 0xC0000000
SE_GROUP_RESOURCE = 0x20000000
SE_GROUP_VALID_ATTRIBUTES = SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED | SE_GROUP_OWNER | SE_GROUP_USE_FOR_DENY_ONLY | SE_GROUP_LOGON_ID | SE_GROUP_RESOURCE | SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED
)
// Privilege attributes
const (
SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001
SE_PRIVILEGE_ENABLED = 0x00000002
SE_PRIVILEGE_REMOVED = 0x00000004
SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000
SE_PRIVILEGE_VALID_ATTRIBUTES = SE_PRIVILEGE_ENABLED_BY_DEFAULT | SE_PRIVILEGE_ENABLED | SE_PRIVILEGE_REMOVED | SE_PRIVILEGE_USED_FOR_ACCESS
)
// Token types
const (
TokenPrimary = 1
TokenImpersonation = 2
)
// Impersonation levels
const (
SecurityAnonymous = 0
SecurityIdentification = 1
SecurityImpersonation = 2
SecurityDelegation = 3
)
type LUID struct {
LowPart uint32
HighPart int32
}
type LUIDAndAttributes struct {
Luid LUID
Attributes uint32
}
type SIDAndAttributes struct {
Sid *SID
Attributes uint32
}
type Tokenuser struct {
User SIDAndAttributes
}
type Tokenprimarygroup struct {
PrimaryGroup *SID
}
type Tokengroups struct {
GroupCount uint32
Groups [1]SIDAndAttributes // Use AllGroups() for iterating.
}
// AllGroups returns a slice that can be used to iterate over the groups in g.
func (g *Tokengroups) AllGroups() []SIDAndAttributes {
return (*[(1 << 28) - 1]SIDAndAttributes)(unsafe.Pointer(&g.Groups[0]))[:g.GroupCount:g.GroupCount]
}
type Tokenprivileges struct {
PrivilegeCount uint32
Privileges [1]LUIDAndAttributes // Use AllPrivileges() for iterating.
}
// AllPrivileges returns a slice that can be used to iterate over the privileges in p.
func (p *Tokenprivileges) AllPrivileges() []LUIDAndAttributes {
return (*[(1 << 27) - 1]LUIDAndAttributes)(unsafe.Pointer(&p.Privileges[0]))[:p.PrivilegeCount:p.PrivilegeCount]
}
type Tokenmandatorylabel struct {
Label SIDAndAttributes
}
func (tml *Tokenmandatorylabel) Size() uint32 {
return uint32(unsafe.Sizeof(Tokenmandatorylabel{})) + GetLengthSid(tml.Label.Sid)
}
// Authorization Functions
//sys checkTokenMembership(tokenHandle Token, sidToCheck *SID, isMember *int32) (err error) = advapi32.CheckTokenMembership
//sys isTokenRestricted(tokenHandle Token) (ret bool, err error) [!failretval] = advapi32.IsTokenRestricted
//sys OpenProcessToken(process Handle, access uint32, token *Token) (err error) = advapi32.OpenProcessToken
//sys OpenThreadToken(thread Handle, access uint32, openAsSelf bool, token *Token) (err error) = advapi32.OpenThreadToken
//sys ImpersonateSelf(impersonationlevel uint32) (err error) = advapi32.ImpersonateSelf
//sys RevertToSelf() (err error) = advapi32.RevertToSelf
//sys SetThreadToken(thread *Handle, token Token) (err error) = advapi32.SetThreadToken
//sys LookupPrivilegeValue(systemname *uint16, name *uint16, luid *LUID) (err error) = advapi32.LookupPrivilegeValueW
//sys AdjustTokenPrivileges(token Token, disableAllPrivileges bool, newstate *Tokenprivileges, buflen uint32, prevstate *Tokenprivileges, returnlen *uint32) (err error) = advapi32.AdjustTokenPrivileges
//sys AdjustTokenGroups(token Token, resetToDefault bool, newstate *Tokengroups, buflen uint32, prevstate *Tokengroups, returnlen *uint32) (err error) = advapi32.AdjustTokenGroups
//sys GetTokenInformation(token Token, infoClass uint32, info *byte, infoLen uint32, returnedLen *uint32) (err error) = advapi32.GetTokenInformation
//sys SetTokenInformation(token Token, infoClass uint32, info *byte, infoLen uint32) (err error) = advapi32.SetTokenInformation
//sys DuplicateTokenEx(existingToken Token, desiredAccess uint32, tokenAttributes *SecurityAttributes, impersonationLevel uint32, tokenType uint32, newToken *Token) (err error) = advapi32.DuplicateTokenEx
//sys GetUserProfileDirectory(t Token, dir *uint16, dirLen *uint32) (err error) = userenv.GetUserProfileDirectoryW
//sys getSystemDirectory(dir *uint16, dirLen uint32) (len uint32, err error) = kernel32.GetSystemDirectoryW
//sys getWindowsDirectory(dir *uint16, dirLen uint32) (len uint32, err error) = kernel32.GetWindowsDirectoryW
//sys getSystemWindowsDirectory(dir *uint16, dirLen uint32) (len uint32, err error) = kernel32.GetSystemWindowsDirectoryW
// An access token contains the security information for a logon session.
// The system creates an access token when a user logs on, and every
// process executed on behalf of the user has a copy of the token.
// The token identifies the user, the user's groups, and the user's
// privileges. The system uses the token to control access to securable
// objects and to control the ability of the user to perform various
// system-related operations on the local computer.
type Token Handle
// OpenCurrentProcessToken opens an access token associated with current
// process with TOKEN_QUERY access. It is a real token that needs to be closed.
//
// Deprecated: Explicitly call OpenProcessToken(CurrentProcess(), ...)
// with the desired access instead, or use GetCurrentProcessToken for a
// TOKEN_QUERY token.
func OpenCurrentProcessToken() (Token, error) {
var token Token
err := OpenProcessToken(CurrentProcess(), TOKEN_QUERY, &token)
return token, err
}
// GetCurrentProcessToken returns the access token associated with
// the current process. It is a pseudo token that does not need
// to be closed.
func GetCurrentProcessToken() Token {
return Token(^uintptr(4 - 1))
}
// GetCurrentThreadToken return the access token associated with
// the current thread. It is a pseudo token that does not need
// to be closed.
func GetCurrentThreadToken() Token {
return Token(^uintptr(5 - 1))
}
// GetCurrentThreadEffectiveToken returns the effective access token
// associated with the current thread. It is a pseudo token that does
// not need to be closed.
func GetCurrentThreadEffectiveToken() Token {
return Token(^uintptr(6 - 1))
}
// Close releases access to access token.
func (t Token) Close() error {
return CloseHandle(Handle(t))
}
// getInfo retrieves a specified type of information about an access token.
func (t Token) getInfo(class uint32, initSize int) (unsafe.Pointer, error) {
n := uint32(initSize)
for {
b := make([]byte, n)
e := GetTokenInformation(t, class, &b[0], uint32(len(b)), &n)
if e == nil {
return unsafe.Pointer(&b[0]), nil
}
if e != ERROR_INSUFFICIENT_BUFFER {
return nil, e
}
if n <= uint32(len(b)) {
return nil, e
}
}
}
// GetTokenUser retrieves access token t user account information.
func (t Token) GetTokenUser() (*Tokenuser, error) {
i, e := t.getInfo(TokenUser, 50)
if e != nil {
return nil, e
}
return (*Tokenuser)(i), nil
}
// GetTokenGroups retrieves group accounts associated with access token t.
func (t Token) GetTokenGroups() (*Tokengroups, error) {
i, e := t.getInfo(TokenGroups, 50)
if e != nil {
return nil, e
}
return (*Tokengroups)(i), nil
}
// GetTokenPrimaryGroup retrieves access token t primary group information.
// A pointer to a SID structure representing a group that will become
// the primary group of any objects created by a process using this access token.
func (t Token) GetTokenPrimaryGroup() (*Tokenprimarygroup, error) {
i, e := t.getInfo(TokenPrimaryGroup, 50)
if e != nil {
return nil, e
}
return (*Tokenprimarygroup)(i), nil
}
// GetUserProfileDirectory retrieves path to the
// root directory of the access token t user's profile.
func (t Token) GetUserProfileDirectory() (string, error) {
n := uint32(100)
for {
b := make([]uint16, n)
e := GetUserProfileDirectory(t, &b[0], &n)
if e == nil {
return UTF16ToString(b), nil
}
if e != ERROR_INSUFFICIENT_BUFFER {
return "", e
}
if n <= uint32(len(b)) {
return "", e
}
}
}
// IsElevated returns whether the current token is elevated from a UAC perspective.
func (token Token) IsElevated() bool {
var isElevated uint32
var outLen uint32
err := GetTokenInformation(token, TokenElevation, (*byte)(unsafe.Pointer(&isElevated)), uint32(unsafe.Sizeof(isElevated)), &outLen)
if err != nil {
return false
}
return outLen == uint32(unsafe.Sizeof(isElevated)) && isElevated != 0
}
// GetLinkedToken returns the linked token, which may be an elevated UAC token.
func (token Token) GetLinkedToken() (Token, error) {
var linkedToken Token
var outLen uint32
err := GetTokenInformation(token, TokenLinkedToken, (*byte)(unsafe.Pointer(&linkedToken)), uint32(unsafe.Sizeof(linkedToken)), &outLen)
if err != nil {
return Token(0), err
}
return linkedToken, nil
}
// GetSystemDirectory retrieves the path to current location of the system
// directory, which is typically, though not always, `C:\Windows\System32`.
func GetSystemDirectory() (string, error) {
n := uint32(MAX_PATH)
for {
b := make([]uint16, n)
l, e := getSystemDirectory(&b[0], n)
if e != nil {
return "", e
}
if l <= n {
return UTF16ToString(b[:l]), nil
}
n = l
}
}
// GetWindowsDirectory retrieves the path to current location of the Windows
// directory, which is typically, though not always, `C:\Windows`. This may
// be a private user directory in the case that the application is running
// under a terminal server.
func GetWindowsDirectory() (string, error) {
n := uint32(MAX_PATH)
for {
b := make([]uint16, n)
l, e := getWindowsDirectory(&b[0], n)
if e != nil {
return "", e
}
if l <= n {
return UTF16ToString(b[:l]), nil
}
n = l
}
}
// GetSystemWindowsDirectory retrieves the path to current location of the
// Windows directory, which is typically, though not always, `C:\Windows`.
func GetSystemWindowsDirectory() (string, error) {
n := uint32(MAX_PATH)
for {
b := make([]uint16, n)
l, e := getSystemWindowsDirectory(&b[0], n)
if e != nil {
return "", e
}
if l <= n {
return UTF16ToString(b[:l]), nil
}
n = l
}
}
// IsMember reports whether the access token t is a member of the provided SID.
func (t Token) IsMember(sid *SID) (bool, error) {
var b int32
if e := checkTokenMembership(t, sid, &b); e != nil {
return false, e
}
return b != 0, nil
}
// IsRestricted reports whether the access token t is a restricted token.
func (t Token) IsRestricted() (isRestricted bool, err error) {
isRestricted, err = isTokenRestricted(t)
if !isRestricted && err == syscall.EINVAL {
// If err is EINVAL, this returned ERROR_SUCCESS indicating a non-restricted token.
err = nil
}
return
}
const (
WTS_CONSOLE_CONNECT = 0x1
WTS_CONSOLE_DISCONNECT = 0x2
WTS_REMOTE_CONNECT = 0x3
WTS_REMOTE_DISCONNECT = 0x4
WTS_SESSION_LOGON = 0x5
WTS_SESSION_LOGOFF = 0x6
WTS_SESSION_LOCK = 0x7
WTS_SESSION_UNLOCK = 0x8
WTS_SESSION_REMOTE_CONTROL = 0x9
WTS_SESSION_CREATE = 0xa
WTS_SESSION_TERMINATE = 0xb
)
const (
WTSActive = 0
WTSConnected = 1
WTSConnectQuery = 2
WTSShadow = 3
WTSDisconnected = 4
WTSIdle = 5
WTSListen = 6
WTSReset = 7
WTSDown = 8
WTSInit = 9
)
type WTSSESSION_NOTIFICATION struct {
Size uint32
SessionID uint32
}
type WTS_SESSION_INFO struct {
SessionID uint32
WindowStationName *uint16
State uint32
}
//sys WTSQueryUserToken(session uint32, token *Token) (err error) = wtsapi32.WTSQueryUserToken
//sys WTSEnumerateSessions(handle Handle, reserved uint32, version uint32, sessions **WTS_SESSION_INFO, count *uint32) (err error) = wtsapi32.WTSEnumerateSessionsW
//sys WTSFreeMemory(ptr uintptr) = wtsapi32.WTSFreeMemory
//sys WTSGetActiveConsoleSessionId() (sessionID uint32)
type ACL struct {
aclRevision byte
sbz1 byte
aclSize uint16
AceCount uint16
sbz2 uint16
}
type SECURITY_DESCRIPTOR struct {
revision byte
sbz1 byte
control SECURITY_DESCRIPTOR_CONTROL
owner *SID
group *SID
sacl *ACL
dacl *ACL
}
type SECURITY_QUALITY_OF_SERVICE struct {
Length uint32
ImpersonationLevel uint32
ContextTrackingMode byte
EffectiveOnly byte
}
// Constants for the ContextTrackingMode field of SECURITY_QUALITY_OF_SERVICE.
const (
SECURITY_STATIC_TRACKING = 0
SECURITY_DYNAMIC_TRACKING = 1
)
type SecurityAttributes struct {
Length uint32
SecurityDescriptor *SECURITY_DESCRIPTOR
InheritHandle uint32
}
type SE_OBJECT_TYPE uint32
// Constants for type SE_OBJECT_TYPE
const (
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | true |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/dll_windows.go | vendor/golang.org/x/sys/windows/dll_windows.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package windows
import (
"sync"
"sync/atomic"
"syscall"
"unsafe"
)
// We need to use LoadLibrary and GetProcAddress from the Go runtime, because
// the these symbols are loaded by the system linker and are required to
// dynamically load additional symbols. Note that in the Go runtime, these
// return syscall.Handle and syscall.Errno, but these are the same, in fact,
// as windows.Handle and windows.Errno, and we intend to keep these the same.
//go:linkname syscall_loadlibrary syscall.loadlibrary
func syscall_loadlibrary(filename *uint16) (handle Handle, err Errno)
//go:linkname syscall_getprocaddress syscall.getprocaddress
func syscall_getprocaddress(handle Handle, procname *uint8) (proc uintptr, err Errno)
// DLLError describes reasons for DLL load failures.
type DLLError struct {
Err error
ObjName string
Msg string
}
func (e *DLLError) Error() string { return e.Msg }
func (e *DLLError) Unwrap() error { return e.Err }
// A DLL implements access to a single DLL.
type DLL struct {
Name string
Handle Handle
}
// LoadDLL loads DLL file into memory.
//
// Warning: using LoadDLL without an absolute path name is subject to
// DLL preloading attacks. To safely load a system DLL, use [NewLazySystemDLL],
// or use [LoadLibraryEx] directly.
func LoadDLL(name string) (dll *DLL, err error) {
namep, err := UTF16PtrFromString(name)
if err != nil {
return nil, err
}
h, e := syscall_loadlibrary(namep)
if e != 0 {
return nil, &DLLError{
Err: e,
ObjName: name,
Msg: "Failed to load " + name + ": " + e.Error(),
}
}
d := &DLL{
Name: name,
Handle: h,
}
return d, nil
}
// MustLoadDLL is like LoadDLL but panics if load operation fails.
func MustLoadDLL(name string) *DLL {
d, e := LoadDLL(name)
if e != nil {
panic(e)
}
return d
}
// FindProc searches DLL d for procedure named name and returns *Proc
// if found. It returns an error if search fails.
func (d *DLL) FindProc(name string) (proc *Proc, err error) {
namep, err := BytePtrFromString(name)
if err != nil {
return nil, err
}
a, e := syscall_getprocaddress(d.Handle, namep)
if e != 0 {
return nil, &DLLError{
Err: e,
ObjName: name,
Msg: "Failed to find " + name + " procedure in " + d.Name + ": " + e.Error(),
}
}
p := &Proc{
Dll: d,
Name: name,
addr: a,
}
return p, nil
}
// MustFindProc is like FindProc but panics if search fails.
func (d *DLL) MustFindProc(name string) *Proc {
p, e := d.FindProc(name)
if e != nil {
panic(e)
}
return p
}
// FindProcByOrdinal searches DLL d for procedure by ordinal and returns *Proc
// if found. It returns an error if search fails.
func (d *DLL) FindProcByOrdinal(ordinal uintptr) (proc *Proc, err error) {
a, e := GetProcAddressByOrdinal(d.Handle, ordinal)
name := "#" + itoa(int(ordinal))
if e != nil {
return nil, &DLLError{
Err: e,
ObjName: name,
Msg: "Failed to find " + name + " procedure in " + d.Name + ": " + e.Error(),
}
}
p := &Proc{
Dll: d,
Name: name,
addr: a,
}
return p, nil
}
// MustFindProcByOrdinal is like FindProcByOrdinal but panics if search fails.
func (d *DLL) MustFindProcByOrdinal(ordinal uintptr) *Proc {
p, e := d.FindProcByOrdinal(ordinal)
if e != nil {
panic(e)
}
return p
}
// Release unloads DLL d from memory.
func (d *DLL) Release() (err error) {
return FreeLibrary(d.Handle)
}
// A Proc implements access to a procedure inside a DLL.
type Proc struct {
Dll *DLL
Name string
addr uintptr
}
// Addr returns the address of the procedure represented by p.
// The return value can be passed to Syscall to run the procedure.
func (p *Proc) Addr() uintptr {
return p.addr
}
//go:uintptrescapes
// Call executes procedure p with arguments a. It will panic, if more than 15 arguments
// are supplied.
//
// The returned error is always non-nil, constructed from the result of GetLastError.
// Callers must inspect the primary return value to decide whether an error occurred
// (according to the semantics of the specific function being called) before consulting
// the error. The error will be guaranteed to contain windows.Errno.
func (p *Proc) Call(a ...uintptr) (r1, r2 uintptr, lastErr error) {
switch len(a) {
case 0:
return syscall.Syscall(p.Addr(), uintptr(len(a)), 0, 0, 0)
case 1:
return syscall.Syscall(p.Addr(), uintptr(len(a)), a[0], 0, 0)
case 2:
return syscall.Syscall(p.Addr(), uintptr(len(a)), a[0], a[1], 0)
case 3:
return syscall.Syscall(p.Addr(), uintptr(len(a)), a[0], a[1], a[2])
case 4:
return syscall.Syscall6(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], 0, 0)
case 5:
return syscall.Syscall6(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], 0)
case 6:
return syscall.Syscall6(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5])
case 7:
return syscall.Syscall9(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], 0, 0)
case 8:
return syscall.Syscall9(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], 0)
case 9:
return syscall.Syscall9(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8])
case 10:
return syscall.Syscall12(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], 0, 0)
case 11:
return syscall.Syscall12(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], 0)
case 12:
return syscall.Syscall12(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11])
case 13:
return syscall.Syscall15(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], 0, 0)
case 14:
return syscall.Syscall15(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], 0)
case 15:
return syscall.Syscall15(p.Addr(), uintptr(len(a)), a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14])
default:
panic("Call " + p.Name + " with too many arguments " + itoa(len(a)) + ".")
}
}
// A LazyDLL implements access to a single DLL.
// It will delay the load of the DLL until the first
// call to its Handle method or to one of its
// LazyProc's Addr method.
type LazyDLL struct {
Name string
// System determines whether the DLL must be loaded from the
// Windows System directory, bypassing the normal DLL search
// path.
System bool
mu sync.Mutex
dll *DLL // non nil once DLL is loaded
}
// Load loads DLL file d.Name into memory. It returns an error if fails.
// Load will not try to load DLL, if it is already loaded into memory.
func (d *LazyDLL) Load() error {
// Non-racy version of:
// if d.dll != nil {
if atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&d.dll))) != nil {
return nil
}
d.mu.Lock()
defer d.mu.Unlock()
if d.dll != nil {
return nil
}
// kernel32.dll is special, since it's where LoadLibraryEx comes from.
// The kernel already special-cases its name, so it's always
// loaded from system32.
var dll *DLL
var err error
if d.Name == "kernel32.dll" {
dll, err = LoadDLL(d.Name)
} else {
dll, err = loadLibraryEx(d.Name, d.System)
}
if err != nil {
return err
}
// Non-racy version of:
// d.dll = dll
atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&d.dll)), unsafe.Pointer(dll))
return nil
}
// mustLoad is like Load but panics if search fails.
func (d *LazyDLL) mustLoad() {
e := d.Load()
if e != nil {
panic(e)
}
}
// Handle returns d's module handle.
func (d *LazyDLL) Handle() uintptr {
d.mustLoad()
return uintptr(d.dll.Handle)
}
// NewProc returns a LazyProc for accessing the named procedure in the DLL d.
func (d *LazyDLL) NewProc(name string) *LazyProc {
return &LazyProc{l: d, Name: name}
}
// NewLazyDLL creates new LazyDLL associated with DLL file.
//
// Warning: using NewLazyDLL without an absolute path name is subject to
// DLL preloading attacks. To safely load a system DLL, use [NewLazySystemDLL].
func NewLazyDLL(name string) *LazyDLL {
return &LazyDLL{Name: name}
}
// NewLazySystemDLL is like NewLazyDLL, but will only
// search Windows System directory for the DLL if name is
// a base name (like "advapi32.dll").
func NewLazySystemDLL(name string) *LazyDLL {
return &LazyDLL{Name: name, System: true}
}
// A LazyProc implements access to a procedure inside a LazyDLL.
// It delays the lookup until the Addr method is called.
type LazyProc struct {
Name string
mu sync.Mutex
l *LazyDLL
proc *Proc
}
// Find searches DLL for procedure named p.Name. It returns
// an error if search fails. Find will not search procedure,
// if it is already found and loaded into memory.
func (p *LazyProc) Find() error {
// Non-racy version of:
// if p.proc == nil {
if atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&p.proc))) == nil {
p.mu.Lock()
defer p.mu.Unlock()
if p.proc == nil {
e := p.l.Load()
if e != nil {
return e
}
proc, e := p.l.dll.FindProc(p.Name)
if e != nil {
return e
}
// Non-racy version of:
// p.proc = proc
atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&p.proc)), unsafe.Pointer(proc))
}
}
return nil
}
// mustFind is like Find but panics if search fails.
func (p *LazyProc) mustFind() {
e := p.Find()
if e != nil {
panic(e)
}
}
// Addr returns the address of the procedure represented by p.
// The return value can be passed to Syscall to run the procedure.
// It will panic if the procedure cannot be found.
func (p *LazyProc) Addr() uintptr {
p.mustFind()
return p.proc.Addr()
}
//go:uintptrescapes
// Call executes procedure p with arguments a. It will panic, if more than 15 arguments
// are supplied. It will also panic if the procedure cannot be found.
//
// The returned error is always non-nil, constructed from the result of GetLastError.
// Callers must inspect the primary return value to decide whether an error occurred
// (according to the semantics of the specific function being called) before consulting
// the error. The error will be guaranteed to contain windows.Errno.
func (p *LazyProc) Call(a ...uintptr) (r1, r2 uintptr, lastErr error) {
p.mustFind()
return p.proc.Call(a...)
}
var canDoSearchSystem32Once struct {
sync.Once
v bool
}
func initCanDoSearchSystem32() {
// https://msdn.microsoft.com/en-us/library/ms684179(v=vs.85).aspx says:
// "Windows 7, Windows Server 2008 R2, Windows Vista, and Windows
// Server 2008: The LOAD_LIBRARY_SEARCH_* flags are available on
// systems that have KB2533623 installed. To determine whether the
// flags are available, use GetProcAddress to get the address of the
// AddDllDirectory, RemoveDllDirectory, or SetDefaultDllDirectories
// function. If GetProcAddress succeeds, the LOAD_LIBRARY_SEARCH_*
// flags can be used with LoadLibraryEx."
canDoSearchSystem32Once.v = (modkernel32.NewProc("AddDllDirectory").Find() == nil)
}
func canDoSearchSystem32() bool {
canDoSearchSystem32Once.Do(initCanDoSearchSystem32)
return canDoSearchSystem32Once.v
}
func isBaseName(name string) bool {
for _, c := range name {
if c == ':' || c == '/' || c == '\\' {
return false
}
}
return true
}
// loadLibraryEx wraps the Windows LoadLibraryEx function.
//
// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms684179(v=vs.85).aspx
//
// If name is not an absolute path, LoadLibraryEx searches for the DLL
// in a variety of automatic locations unless constrained by flags.
// See: https://msdn.microsoft.com/en-us/library/ff919712%28VS.85%29.aspx
func loadLibraryEx(name string, system bool) (*DLL, error) {
loadDLL := name
var flags uintptr
if system {
if canDoSearchSystem32() {
flags = LOAD_LIBRARY_SEARCH_SYSTEM32
} else if isBaseName(name) {
// WindowsXP or unpatched Windows machine
// trying to load "foo.dll" out of the system
// folder, but LoadLibraryEx doesn't support
// that yet on their system, so emulate it.
systemdir, err := GetSystemDirectory()
if err != nil {
return nil, err
}
loadDLL = systemdir + "\\" + name
}
}
h, err := LoadLibraryEx(loadDLL, 0, flags)
if err != nil {
return nil, err
}
return &DLL{Name: name, Handle: h}, nil
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/service.go | vendor/golang.org/x/sys/windows/service.go | // Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build windows
package windows
const (
SC_MANAGER_CONNECT = 1
SC_MANAGER_CREATE_SERVICE = 2
SC_MANAGER_ENUMERATE_SERVICE = 4
SC_MANAGER_LOCK = 8
SC_MANAGER_QUERY_LOCK_STATUS = 16
SC_MANAGER_MODIFY_BOOT_CONFIG = 32
SC_MANAGER_ALL_ACCESS = 0xf003f
)
const (
SERVICE_KERNEL_DRIVER = 1
SERVICE_FILE_SYSTEM_DRIVER = 2
SERVICE_ADAPTER = 4
SERVICE_RECOGNIZER_DRIVER = 8
SERVICE_WIN32_OWN_PROCESS = 16
SERVICE_WIN32_SHARE_PROCESS = 32
SERVICE_WIN32 = SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS
SERVICE_INTERACTIVE_PROCESS = 256
SERVICE_DRIVER = SERVICE_KERNEL_DRIVER | SERVICE_FILE_SYSTEM_DRIVER | SERVICE_RECOGNIZER_DRIVER
SERVICE_TYPE_ALL = SERVICE_WIN32 | SERVICE_ADAPTER | SERVICE_DRIVER | SERVICE_INTERACTIVE_PROCESS
SERVICE_BOOT_START = 0
SERVICE_SYSTEM_START = 1
SERVICE_AUTO_START = 2
SERVICE_DEMAND_START = 3
SERVICE_DISABLED = 4
SERVICE_ERROR_IGNORE = 0
SERVICE_ERROR_NORMAL = 1
SERVICE_ERROR_SEVERE = 2
SERVICE_ERROR_CRITICAL = 3
SC_STATUS_PROCESS_INFO = 0
SC_ACTION_NONE = 0
SC_ACTION_RESTART = 1
SC_ACTION_REBOOT = 2
SC_ACTION_RUN_COMMAND = 3
SERVICE_STOPPED = 1
SERVICE_START_PENDING = 2
SERVICE_STOP_PENDING = 3
SERVICE_RUNNING = 4
SERVICE_CONTINUE_PENDING = 5
SERVICE_PAUSE_PENDING = 6
SERVICE_PAUSED = 7
SERVICE_NO_CHANGE = 0xffffffff
SERVICE_ACCEPT_STOP = 1
SERVICE_ACCEPT_PAUSE_CONTINUE = 2
SERVICE_ACCEPT_SHUTDOWN = 4
SERVICE_ACCEPT_PARAMCHANGE = 8
SERVICE_ACCEPT_NETBINDCHANGE = 16
SERVICE_ACCEPT_HARDWAREPROFILECHANGE = 32
SERVICE_ACCEPT_POWEREVENT = 64
SERVICE_ACCEPT_SESSIONCHANGE = 128
SERVICE_ACCEPT_PRESHUTDOWN = 256
SERVICE_CONTROL_STOP = 1
SERVICE_CONTROL_PAUSE = 2
SERVICE_CONTROL_CONTINUE = 3
SERVICE_CONTROL_INTERROGATE = 4
SERVICE_CONTROL_SHUTDOWN = 5
SERVICE_CONTROL_PARAMCHANGE = 6
SERVICE_CONTROL_NETBINDADD = 7
SERVICE_CONTROL_NETBINDREMOVE = 8
SERVICE_CONTROL_NETBINDENABLE = 9
SERVICE_CONTROL_NETBINDDISABLE = 10
SERVICE_CONTROL_DEVICEEVENT = 11
SERVICE_CONTROL_HARDWAREPROFILECHANGE = 12
SERVICE_CONTROL_POWEREVENT = 13
SERVICE_CONTROL_SESSIONCHANGE = 14
SERVICE_CONTROL_PRESHUTDOWN = 15
SERVICE_ACTIVE = 1
SERVICE_INACTIVE = 2
SERVICE_STATE_ALL = 3
SERVICE_QUERY_CONFIG = 1
SERVICE_CHANGE_CONFIG = 2
SERVICE_QUERY_STATUS = 4
SERVICE_ENUMERATE_DEPENDENTS = 8
SERVICE_START = 16
SERVICE_STOP = 32
SERVICE_PAUSE_CONTINUE = 64
SERVICE_INTERROGATE = 128
SERVICE_USER_DEFINED_CONTROL = 256
SERVICE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_START | SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_INTERROGATE | SERVICE_USER_DEFINED_CONTROL
SERVICE_RUNS_IN_SYSTEM_PROCESS = 1
SERVICE_CONFIG_DESCRIPTION = 1
SERVICE_CONFIG_FAILURE_ACTIONS = 2
SERVICE_CONFIG_DELAYED_AUTO_START_INFO = 3
SERVICE_CONFIG_FAILURE_ACTIONS_FLAG = 4
SERVICE_CONFIG_SERVICE_SID_INFO = 5
SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO = 6
SERVICE_CONFIG_PRESHUTDOWN_INFO = 7
SERVICE_CONFIG_TRIGGER_INFO = 8
SERVICE_CONFIG_PREFERRED_NODE = 9
SERVICE_CONFIG_LAUNCH_PROTECTED = 12
SERVICE_SID_TYPE_NONE = 0
SERVICE_SID_TYPE_UNRESTRICTED = 1
SERVICE_SID_TYPE_RESTRICTED = 2 | SERVICE_SID_TYPE_UNRESTRICTED
SC_ENUM_PROCESS_INFO = 0
SERVICE_NOTIFY_STATUS_CHANGE = 2
SERVICE_NOTIFY_STOPPED = 0x00000001
SERVICE_NOTIFY_START_PENDING = 0x00000002
SERVICE_NOTIFY_STOP_PENDING = 0x00000004
SERVICE_NOTIFY_RUNNING = 0x00000008
SERVICE_NOTIFY_CONTINUE_PENDING = 0x00000010
SERVICE_NOTIFY_PAUSE_PENDING = 0x00000020
SERVICE_NOTIFY_PAUSED = 0x00000040
SERVICE_NOTIFY_CREATED = 0x00000080
SERVICE_NOTIFY_DELETED = 0x00000100
SERVICE_NOTIFY_DELETE_PENDING = 0x00000200
SC_EVENT_DATABASE_CHANGE = 0
SC_EVENT_PROPERTY_CHANGE = 1
SC_EVENT_STATUS_CHANGE = 2
SERVICE_START_REASON_DEMAND = 0x00000001
SERVICE_START_REASON_AUTO = 0x00000002
SERVICE_START_REASON_TRIGGER = 0x00000004
SERVICE_START_REASON_RESTART_ON_FAILURE = 0x00000008
SERVICE_START_REASON_DELAYEDAUTO = 0x00000010
SERVICE_DYNAMIC_INFORMATION_LEVEL_START_REASON = 1
)
type ENUM_SERVICE_STATUS struct {
ServiceName *uint16
DisplayName *uint16
ServiceStatus SERVICE_STATUS
}
type SERVICE_STATUS struct {
ServiceType uint32
CurrentState uint32
ControlsAccepted uint32
Win32ExitCode uint32
ServiceSpecificExitCode uint32
CheckPoint uint32
WaitHint uint32
}
type SERVICE_TABLE_ENTRY struct {
ServiceName *uint16
ServiceProc uintptr
}
type QUERY_SERVICE_CONFIG struct {
ServiceType uint32
StartType uint32
ErrorControl uint32
BinaryPathName *uint16
LoadOrderGroup *uint16
TagId uint32
Dependencies *uint16
ServiceStartName *uint16
DisplayName *uint16
}
type SERVICE_DESCRIPTION struct {
Description *uint16
}
type SERVICE_DELAYED_AUTO_START_INFO struct {
IsDelayedAutoStartUp uint32
}
type SERVICE_STATUS_PROCESS struct {
ServiceType uint32
CurrentState uint32
ControlsAccepted uint32
Win32ExitCode uint32
ServiceSpecificExitCode uint32
CheckPoint uint32
WaitHint uint32
ProcessId uint32
ServiceFlags uint32
}
type ENUM_SERVICE_STATUS_PROCESS struct {
ServiceName *uint16
DisplayName *uint16
ServiceStatusProcess SERVICE_STATUS_PROCESS
}
type SERVICE_NOTIFY struct {
Version uint32
NotifyCallback uintptr
Context uintptr
NotificationStatus uint32
ServiceStatus SERVICE_STATUS_PROCESS
NotificationTriggered uint32
ServiceNames *uint16
}
type SERVICE_FAILURE_ACTIONS struct {
ResetPeriod uint32
RebootMsg *uint16
Command *uint16
ActionsCount uint32
Actions *SC_ACTION
}
type SERVICE_FAILURE_ACTIONS_FLAG struct {
FailureActionsOnNonCrashFailures int32
}
type SC_ACTION struct {
Type uint32
Delay uint32
}
type QUERY_SERVICE_LOCK_STATUS struct {
IsLocked uint32
LockOwner *uint16
LockDuration uint32
}
//sys OpenSCManager(machineName *uint16, databaseName *uint16, access uint32) (handle Handle, err error) [failretval==0] = advapi32.OpenSCManagerW
//sys CloseServiceHandle(handle Handle) (err error) = advapi32.CloseServiceHandle
//sys CreateService(mgr Handle, serviceName *uint16, displayName *uint16, access uint32, srvType uint32, startType uint32, errCtl uint32, pathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16) (handle Handle, err error) [failretval==0] = advapi32.CreateServiceW
//sys OpenService(mgr Handle, serviceName *uint16, access uint32) (handle Handle, err error) [failretval==0] = advapi32.OpenServiceW
//sys DeleteService(service Handle) (err error) = advapi32.DeleteService
//sys StartService(service Handle, numArgs uint32, argVectors **uint16) (err error) = advapi32.StartServiceW
//sys QueryServiceStatus(service Handle, status *SERVICE_STATUS) (err error) = advapi32.QueryServiceStatus
//sys QueryServiceLockStatus(mgr Handle, lockStatus *QUERY_SERVICE_LOCK_STATUS, bufSize uint32, bytesNeeded *uint32) (err error) = advapi32.QueryServiceLockStatusW
//sys ControlService(service Handle, control uint32, status *SERVICE_STATUS) (err error) = advapi32.ControlService
//sys StartServiceCtrlDispatcher(serviceTable *SERVICE_TABLE_ENTRY) (err error) = advapi32.StartServiceCtrlDispatcherW
//sys SetServiceStatus(service Handle, serviceStatus *SERVICE_STATUS) (err error) = advapi32.SetServiceStatus
//sys ChangeServiceConfig(service Handle, serviceType uint32, startType uint32, errorControl uint32, binaryPathName *uint16, loadOrderGroup *uint16, tagId *uint32, dependencies *uint16, serviceStartName *uint16, password *uint16, displayName *uint16) (err error) = advapi32.ChangeServiceConfigW
//sys QueryServiceConfig(service Handle, serviceConfig *QUERY_SERVICE_CONFIG, bufSize uint32, bytesNeeded *uint32) (err error) = advapi32.QueryServiceConfigW
//sys ChangeServiceConfig2(service Handle, infoLevel uint32, info *byte) (err error) = advapi32.ChangeServiceConfig2W
//sys QueryServiceConfig2(service Handle, infoLevel uint32, buff *byte, buffSize uint32, bytesNeeded *uint32) (err error) = advapi32.QueryServiceConfig2W
//sys EnumServicesStatusEx(mgr Handle, infoLevel uint32, serviceType uint32, serviceState uint32, services *byte, bufSize uint32, bytesNeeded *uint32, servicesReturned *uint32, resumeHandle *uint32, groupName *uint16) (err error) = advapi32.EnumServicesStatusExW
//sys QueryServiceStatusEx(service Handle, infoLevel uint32, buff *byte, buffSize uint32, bytesNeeded *uint32) (err error) = advapi32.QueryServiceStatusEx
//sys NotifyServiceStatusChange(service Handle, notifyMask uint32, notifier *SERVICE_NOTIFY) (ret error) = advapi32.NotifyServiceStatusChangeW
//sys SubscribeServiceChangeNotifications(service Handle, eventType uint32, callback uintptr, callbackCtx uintptr, subscription *uintptr) (ret error) = sechost.SubscribeServiceChangeNotifications?
//sys UnsubscribeServiceChangeNotifications(subscription uintptr) = sechost.UnsubscribeServiceChangeNotifications?
//sys RegisterServiceCtrlHandlerEx(serviceName *uint16, handlerProc uintptr, context uintptr) (handle Handle, err error) = advapi32.RegisterServiceCtrlHandlerExW
//sys QueryServiceDynamicInformation(service Handle, infoLevel uint32, dynamicInfo unsafe.Pointer) (err error) = advapi32.QueryServiceDynamicInformation?
//sys EnumDependentServices(service Handle, activityState uint32, services *ENUM_SERVICE_STATUS, buffSize uint32, bytesNeeded *uint32, servicesReturned *uint32) (err error) = advapi32.EnumDependentServicesW
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/eventlog.go | vendor/golang.org/x/sys/windows/eventlog.go | // Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build windows
package windows
const (
EVENTLOG_SUCCESS = 0
EVENTLOG_ERROR_TYPE = 1
EVENTLOG_WARNING_TYPE = 2
EVENTLOG_INFORMATION_TYPE = 4
EVENTLOG_AUDIT_SUCCESS = 8
EVENTLOG_AUDIT_FAILURE = 16
)
//sys RegisterEventSource(uncServerName *uint16, sourceName *uint16) (handle Handle, err error) [failretval==0] = advapi32.RegisterEventSourceW
//sys DeregisterEventSource(handle Handle) (err error) = advapi32.DeregisterEventSource
//sys ReportEvent(log Handle, etype uint16, category uint16, eventId uint32, usrSId uintptr, numStrings uint16, dataSize uint32, strings **uint16, rawData *byte) (err error) = advapi32.ReportEventW
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/mksyscall.go | vendor/golang.org/x/sys/windows/mksyscall.go | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build generate
package windows
//go:generate go run golang.org/x/sys/windows/mkwinsyscall -output zsyscall_windows.go eventlog.go service.go syscall_windows.go security_windows.go setupapi_windows.go
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/zerrors_windows.go | vendor/golang.org/x/sys/windows/zerrors_windows.go | // Code generated by 'mkerrors.bash'; DO NOT EDIT.
package windows
import "syscall"
const (
FACILITY_NULL = 0
FACILITY_RPC = 1
FACILITY_DISPATCH = 2
FACILITY_STORAGE = 3
FACILITY_ITF = 4
FACILITY_WIN32 = 7
FACILITY_WINDOWS = 8
FACILITY_SSPI = 9
FACILITY_SECURITY = 9
FACILITY_CONTROL = 10
FACILITY_CERT = 11
FACILITY_INTERNET = 12
FACILITY_MEDIASERVER = 13
FACILITY_MSMQ = 14
FACILITY_SETUPAPI = 15
FACILITY_SCARD = 16
FACILITY_COMPLUS = 17
FACILITY_AAF = 18
FACILITY_URT = 19
FACILITY_ACS = 20
FACILITY_DPLAY = 21
FACILITY_UMI = 22
FACILITY_SXS = 23
FACILITY_WINDOWS_CE = 24
FACILITY_HTTP = 25
FACILITY_USERMODE_COMMONLOG = 26
FACILITY_WER = 27
FACILITY_USERMODE_FILTER_MANAGER = 31
FACILITY_BACKGROUNDCOPY = 32
FACILITY_CONFIGURATION = 33
FACILITY_WIA = 33
FACILITY_STATE_MANAGEMENT = 34
FACILITY_METADIRECTORY = 35
FACILITY_WINDOWSUPDATE = 36
FACILITY_DIRECTORYSERVICE = 37
FACILITY_GRAPHICS = 38
FACILITY_SHELL = 39
FACILITY_NAP = 39
FACILITY_TPM_SERVICES = 40
FACILITY_TPM_SOFTWARE = 41
FACILITY_UI = 42
FACILITY_XAML = 43
FACILITY_ACTION_QUEUE = 44
FACILITY_PLA = 48
FACILITY_WINDOWS_SETUP = 48
FACILITY_FVE = 49
FACILITY_FWP = 50
FACILITY_WINRM = 51
FACILITY_NDIS = 52
FACILITY_USERMODE_HYPERVISOR = 53
FACILITY_CMI = 54
FACILITY_USERMODE_VIRTUALIZATION = 55
FACILITY_USERMODE_VOLMGR = 56
FACILITY_BCD = 57
FACILITY_USERMODE_VHD = 58
FACILITY_USERMODE_HNS = 59
FACILITY_SDIAG = 60
FACILITY_WEBSERVICES = 61
FACILITY_WINPE = 61
FACILITY_WPN = 62
FACILITY_WINDOWS_STORE = 63
FACILITY_INPUT = 64
FACILITY_EAP = 66
FACILITY_WINDOWS_DEFENDER = 80
FACILITY_OPC = 81
FACILITY_XPS = 82
FACILITY_MBN = 84
FACILITY_POWERSHELL = 84
FACILITY_RAS = 83
FACILITY_P2P_INT = 98
FACILITY_P2P = 99
FACILITY_DAF = 100
FACILITY_BLUETOOTH_ATT = 101
FACILITY_AUDIO = 102
FACILITY_STATEREPOSITORY = 103
FACILITY_VISUALCPP = 109
FACILITY_SCRIPT = 112
FACILITY_PARSE = 113
FACILITY_BLB = 120
FACILITY_BLB_CLI = 121
FACILITY_WSBAPP = 122
FACILITY_BLBUI = 128
FACILITY_USN = 129
FACILITY_USERMODE_VOLSNAP = 130
FACILITY_TIERING = 131
FACILITY_WSB_ONLINE = 133
FACILITY_ONLINE_ID = 134
FACILITY_DEVICE_UPDATE_AGENT = 135
FACILITY_DRVSERVICING = 136
FACILITY_DLS = 153
FACILITY_DELIVERY_OPTIMIZATION = 208
FACILITY_USERMODE_SPACES = 231
FACILITY_USER_MODE_SECURITY_CORE = 232
FACILITY_USERMODE_LICENSING = 234
FACILITY_SOS = 160
FACILITY_DEBUGGERS = 176
FACILITY_SPP = 256
FACILITY_RESTORE = 256
FACILITY_DMSERVER = 256
FACILITY_DEPLOYMENT_SERVICES_SERVER = 257
FACILITY_DEPLOYMENT_SERVICES_IMAGING = 258
FACILITY_DEPLOYMENT_SERVICES_MANAGEMENT = 259
FACILITY_DEPLOYMENT_SERVICES_UTIL = 260
FACILITY_DEPLOYMENT_SERVICES_BINLSVC = 261
FACILITY_DEPLOYMENT_SERVICES_PXE = 263
FACILITY_DEPLOYMENT_SERVICES_TFTP = 264
FACILITY_DEPLOYMENT_SERVICES_TRANSPORT_MANAGEMENT = 272
FACILITY_DEPLOYMENT_SERVICES_DRIVER_PROVISIONING = 278
FACILITY_DEPLOYMENT_SERVICES_MULTICAST_SERVER = 289
FACILITY_DEPLOYMENT_SERVICES_MULTICAST_CLIENT = 290
FACILITY_DEPLOYMENT_SERVICES_CONTENT_PROVIDER = 293
FACILITY_LINGUISTIC_SERVICES = 305
FACILITY_AUDIOSTREAMING = 1094
FACILITY_ACCELERATOR = 1536
FACILITY_WMAAECMA = 1996
FACILITY_DIRECTMUSIC = 2168
FACILITY_DIRECT3D10 = 2169
FACILITY_DXGI = 2170
FACILITY_DXGI_DDI = 2171
FACILITY_DIRECT3D11 = 2172
FACILITY_DIRECT3D11_DEBUG = 2173
FACILITY_DIRECT3D12 = 2174
FACILITY_DIRECT3D12_DEBUG = 2175
FACILITY_LEAP = 2184
FACILITY_AUDCLNT = 2185
FACILITY_WINCODEC_DWRITE_DWM = 2200
FACILITY_WINML = 2192
FACILITY_DIRECT2D = 2201
FACILITY_DEFRAG = 2304
FACILITY_USERMODE_SDBUS = 2305
FACILITY_JSCRIPT = 2306
FACILITY_PIDGENX = 2561
FACILITY_EAS = 85
FACILITY_WEB = 885
FACILITY_WEB_SOCKET = 886
FACILITY_MOBILE = 1793
FACILITY_SQLITE = 1967
FACILITY_UTC = 1989
FACILITY_WEP = 2049
FACILITY_SYNCENGINE = 2050
FACILITY_XBOX = 2339
FACILITY_GAME = 2340
FACILITY_PIX = 2748
ERROR_SUCCESS syscall.Errno = 0
NO_ERROR = 0
SEC_E_OK Handle = 0x00000000
ERROR_INVALID_FUNCTION syscall.Errno = 1
ERROR_FILE_NOT_FOUND syscall.Errno = 2
ERROR_PATH_NOT_FOUND syscall.Errno = 3
ERROR_TOO_MANY_OPEN_FILES syscall.Errno = 4
ERROR_ACCESS_DENIED syscall.Errno = 5
ERROR_INVALID_HANDLE syscall.Errno = 6
ERROR_ARENA_TRASHED syscall.Errno = 7
ERROR_NOT_ENOUGH_MEMORY syscall.Errno = 8
ERROR_INVALID_BLOCK syscall.Errno = 9
ERROR_BAD_ENVIRONMENT syscall.Errno = 10
ERROR_BAD_FORMAT syscall.Errno = 11
ERROR_INVALID_ACCESS syscall.Errno = 12
ERROR_INVALID_DATA syscall.Errno = 13
ERROR_OUTOFMEMORY syscall.Errno = 14
ERROR_INVALID_DRIVE syscall.Errno = 15
ERROR_CURRENT_DIRECTORY syscall.Errno = 16
ERROR_NOT_SAME_DEVICE syscall.Errno = 17
ERROR_NO_MORE_FILES syscall.Errno = 18
ERROR_WRITE_PROTECT syscall.Errno = 19
ERROR_BAD_UNIT syscall.Errno = 20
ERROR_NOT_READY syscall.Errno = 21
ERROR_BAD_COMMAND syscall.Errno = 22
ERROR_CRC syscall.Errno = 23
ERROR_BAD_LENGTH syscall.Errno = 24
ERROR_SEEK syscall.Errno = 25
ERROR_NOT_DOS_DISK syscall.Errno = 26
ERROR_SECTOR_NOT_FOUND syscall.Errno = 27
ERROR_OUT_OF_PAPER syscall.Errno = 28
ERROR_WRITE_FAULT syscall.Errno = 29
ERROR_READ_FAULT syscall.Errno = 30
ERROR_GEN_FAILURE syscall.Errno = 31
ERROR_SHARING_VIOLATION syscall.Errno = 32
ERROR_LOCK_VIOLATION syscall.Errno = 33
ERROR_WRONG_DISK syscall.Errno = 34
ERROR_SHARING_BUFFER_EXCEEDED syscall.Errno = 36
ERROR_HANDLE_EOF syscall.Errno = 38
ERROR_HANDLE_DISK_FULL syscall.Errno = 39
ERROR_NOT_SUPPORTED syscall.Errno = 50
ERROR_REM_NOT_LIST syscall.Errno = 51
ERROR_DUP_NAME syscall.Errno = 52
ERROR_BAD_NETPATH syscall.Errno = 53
ERROR_NETWORK_BUSY syscall.Errno = 54
ERROR_DEV_NOT_EXIST syscall.Errno = 55
ERROR_TOO_MANY_CMDS syscall.Errno = 56
ERROR_ADAP_HDW_ERR syscall.Errno = 57
ERROR_BAD_NET_RESP syscall.Errno = 58
ERROR_UNEXP_NET_ERR syscall.Errno = 59
ERROR_BAD_REM_ADAP syscall.Errno = 60
ERROR_PRINTQ_FULL syscall.Errno = 61
ERROR_NO_SPOOL_SPACE syscall.Errno = 62
ERROR_PRINT_CANCELLED syscall.Errno = 63
ERROR_NETNAME_DELETED syscall.Errno = 64
ERROR_NETWORK_ACCESS_DENIED syscall.Errno = 65
ERROR_BAD_DEV_TYPE syscall.Errno = 66
ERROR_BAD_NET_NAME syscall.Errno = 67
ERROR_TOO_MANY_NAMES syscall.Errno = 68
ERROR_TOO_MANY_SESS syscall.Errno = 69
ERROR_SHARING_PAUSED syscall.Errno = 70
ERROR_REQ_NOT_ACCEP syscall.Errno = 71
ERROR_REDIR_PAUSED syscall.Errno = 72
ERROR_FILE_EXISTS syscall.Errno = 80
ERROR_CANNOT_MAKE syscall.Errno = 82
ERROR_FAIL_I24 syscall.Errno = 83
ERROR_OUT_OF_STRUCTURES syscall.Errno = 84
ERROR_ALREADY_ASSIGNED syscall.Errno = 85
ERROR_INVALID_PASSWORD syscall.Errno = 86
ERROR_INVALID_PARAMETER syscall.Errno = 87
ERROR_NET_WRITE_FAULT syscall.Errno = 88
ERROR_NO_PROC_SLOTS syscall.Errno = 89
ERROR_TOO_MANY_SEMAPHORES syscall.Errno = 100
ERROR_EXCL_SEM_ALREADY_OWNED syscall.Errno = 101
ERROR_SEM_IS_SET syscall.Errno = 102
ERROR_TOO_MANY_SEM_REQUESTS syscall.Errno = 103
ERROR_INVALID_AT_INTERRUPT_TIME syscall.Errno = 104
ERROR_SEM_OWNER_DIED syscall.Errno = 105
ERROR_SEM_USER_LIMIT syscall.Errno = 106
ERROR_DISK_CHANGE syscall.Errno = 107
ERROR_DRIVE_LOCKED syscall.Errno = 108
ERROR_BROKEN_PIPE syscall.Errno = 109
ERROR_OPEN_FAILED syscall.Errno = 110
ERROR_BUFFER_OVERFLOW syscall.Errno = 111
ERROR_DISK_FULL syscall.Errno = 112
ERROR_NO_MORE_SEARCH_HANDLES syscall.Errno = 113
ERROR_INVALID_TARGET_HANDLE syscall.Errno = 114
ERROR_INVALID_CATEGORY syscall.Errno = 117
ERROR_INVALID_VERIFY_SWITCH syscall.Errno = 118
ERROR_BAD_DRIVER_LEVEL syscall.Errno = 119
ERROR_CALL_NOT_IMPLEMENTED syscall.Errno = 120
ERROR_SEM_TIMEOUT syscall.Errno = 121
ERROR_INSUFFICIENT_BUFFER syscall.Errno = 122
ERROR_INVALID_NAME syscall.Errno = 123
ERROR_INVALID_LEVEL syscall.Errno = 124
ERROR_NO_VOLUME_LABEL syscall.Errno = 125
ERROR_MOD_NOT_FOUND syscall.Errno = 126
ERROR_PROC_NOT_FOUND syscall.Errno = 127
ERROR_WAIT_NO_CHILDREN syscall.Errno = 128
ERROR_CHILD_NOT_COMPLETE syscall.Errno = 129
ERROR_DIRECT_ACCESS_HANDLE syscall.Errno = 130
ERROR_NEGATIVE_SEEK syscall.Errno = 131
ERROR_SEEK_ON_DEVICE syscall.Errno = 132
ERROR_IS_JOIN_TARGET syscall.Errno = 133
ERROR_IS_JOINED syscall.Errno = 134
ERROR_IS_SUBSTED syscall.Errno = 135
ERROR_NOT_JOINED syscall.Errno = 136
ERROR_NOT_SUBSTED syscall.Errno = 137
ERROR_JOIN_TO_JOIN syscall.Errno = 138
ERROR_SUBST_TO_SUBST syscall.Errno = 139
ERROR_JOIN_TO_SUBST syscall.Errno = 140
ERROR_SUBST_TO_JOIN syscall.Errno = 141
ERROR_BUSY_DRIVE syscall.Errno = 142
ERROR_SAME_DRIVE syscall.Errno = 143
ERROR_DIR_NOT_ROOT syscall.Errno = 144
ERROR_DIR_NOT_EMPTY syscall.Errno = 145
ERROR_IS_SUBST_PATH syscall.Errno = 146
ERROR_IS_JOIN_PATH syscall.Errno = 147
ERROR_PATH_BUSY syscall.Errno = 148
ERROR_IS_SUBST_TARGET syscall.Errno = 149
ERROR_SYSTEM_TRACE syscall.Errno = 150
ERROR_INVALID_EVENT_COUNT syscall.Errno = 151
ERROR_TOO_MANY_MUXWAITERS syscall.Errno = 152
ERROR_INVALID_LIST_FORMAT syscall.Errno = 153
ERROR_LABEL_TOO_LONG syscall.Errno = 154
ERROR_TOO_MANY_TCBS syscall.Errno = 155
ERROR_SIGNAL_REFUSED syscall.Errno = 156
ERROR_DISCARDED syscall.Errno = 157
ERROR_NOT_LOCKED syscall.Errno = 158
ERROR_BAD_THREADID_ADDR syscall.Errno = 159
ERROR_BAD_ARGUMENTS syscall.Errno = 160
ERROR_BAD_PATHNAME syscall.Errno = 161
ERROR_SIGNAL_PENDING syscall.Errno = 162
ERROR_MAX_THRDS_REACHED syscall.Errno = 164
ERROR_LOCK_FAILED syscall.Errno = 167
ERROR_BUSY syscall.Errno = 170
ERROR_DEVICE_SUPPORT_IN_PROGRESS syscall.Errno = 171
ERROR_CANCEL_VIOLATION syscall.Errno = 173
ERROR_ATOMIC_LOCKS_NOT_SUPPORTED syscall.Errno = 174
ERROR_INVALID_SEGMENT_NUMBER syscall.Errno = 180
ERROR_INVALID_ORDINAL syscall.Errno = 182
ERROR_ALREADY_EXISTS syscall.Errno = 183
ERROR_INVALID_FLAG_NUMBER syscall.Errno = 186
ERROR_SEM_NOT_FOUND syscall.Errno = 187
ERROR_INVALID_STARTING_CODESEG syscall.Errno = 188
ERROR_INVALID_STACKSEG syscall.Errno = 189
ERROR_INVALID_MODULETYPE syscall.Errno = 190
ERROR_INVALID_EXE_SIGNATURE syscall.Errno = 191
ERROR_EXE_MARKED_INVALID syscall.Errno = 192
ERROR_BAD_EXE_FORMAT syscall.Errno = 193
ERROR_ITERATED_DATA_EXCEEDS_64k syscall.Errno = 194
ERROR_INVALID_MINALLOCSIZE syscall.Errno = 195
ERROR_DYNLINK_FROM_INVALID_RING syscall.Errno = 196
ERROR_IOPL_NOT_ENABLED syscall.Errno = 197
ERROR_INVALID_SEGDPL syscall.Errno = 198
ERROR_AUTODATASEG_EXCEEDS_64k syscall.Errno = 199
ERROR_RING2SEG_MUST_BE_MOVABLE syscall.Errno = 200
ERROR_RELOC_CHAIN_XEEDS_SEGLIM syscall.Errno = 201
ERROR_INFLOOP_IN_RELOC_CHAIN syscall.Errno = 202
ERROR_ENVVAR_NOT_FOUND syscall.Errno = 203
ERROR_NO_SIGNAL_SENT syscall.Errno = 205
ERROR_FILENAME_EXCED_RANGE syscall.Errno = 206
ERROR_RING2_STACK_IN_USE syscall.Errno = 207
ERROR_META_EXPANSION_TOO_LONG syscall.Errno = 208
ERROR_INVALID_SIGNAL_NUMBER syscall.Errno = 209
ERROR_THREAD_1_INACTIVE syscall.Errno = 210
ERROR_LOCKED syscall.Errno = 212
ERROR_TOO_MANY_MODULES syscall.Errno = 214
ERROR_NESTING_NOT_ALLOWED syscall.Errno = 215
ERROR_EXE_MACHINE_TYPE_MISMATCH syscall.Errno = 216
ERROR_EXE_CANNOT_MODIFY_SIGNED_BINARY syscall.Errno = 217
ERROR_EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY syscall.Errno = 218
ERROR_FILE_CHECKED_OUT syscall.Errno = 220
ERROR_CHECKOUT_REQUIRED syscall.Errno = 221
ERROR_BAD_FILE_TYPE syscall.Errno = 222
ERROR_FILE_TOO_LARGE syscall.Errno = 223
ERROR_FORMS_AUTH_REQUIRED syscall.Errno = 224
ERROR_VIRUS_INFECTED syscall.Errno = 225
ERROR_VIRUS_DELETED syscall.Errno = 226
ERROR_PIPE_LOCAL syscall.Errno = 229
ERROR_BAD_PIPE syscall.Errno = 230
ERROR_PIPE_BUSY syscall.Errno = 231
ERROR_NO_DATA syscall.Errno = 232
ERROR_PIPE_NOT_CONNECTED syscall.Errno = 233
ERROR_MORE_DATA syscall.Errno = 234
ERROR_NO_WORK_DONE syscall.Errno = 235
ERROR_VC_DISCONNECTED syscall.Errno = 240
ERROR_INVALID_EA_NAME syscall.Errno = 254
ERROR_EA_LIST_INCONSISTENT syscall.Errno = 255
WAIT_TIMEOUT syscall.Errno = 258
ERROR_NO_MORE_ITEMS syscall.Errno = 259
ERROR_CANNOT_COPY syscall.Errno = 266
ERROR_DIRECTORY syscall.Errno = 267
ERROR_EAS_DIDNT_FIT syscall.Errno = 275
ERROR_EA_FILE_CORRUPT syscall.Errno = 276
ERROR_EA_TABLE_FULL syscall.Errno = 277
ERROR_INVALID_EA_HANDLE syscall.Errno = 278
ERROR_EAS_NOT_SUPPORTED syscall.Errno = 282
ERROR_NOT_OWNER syscall.Errno = 288
ERROR_TOO_MANY_POSTS syscall.Errno = 298
ERROR_PARTIAL_COPY syscall.Errno = 299
ERROR_OPLOCK_NOT_GRANTED syscall.Errno = 300
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | true |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/types_windows_386.go | vendor/golang.org/x/sys/windows/types_windows_386.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package windows
type WSAData struct {
Version uint16
HighVersion uint16
Description [WSADESCRIPTION_LEN + 1]byte
SystemStatus [WSASYS_STATUS_LEN + 1]byte
MaxSockets uint16
MaxUdpDg uint16
VendorInfo *byte
}
type Servent struct {
Name *byte
Aliases **byte
Port uint16
Proto *byte
}
type JOBOBJECT_BASIC_LIMIT_INFORMATION struct {
PerProcessUserTimeLimit int64
PerJobUserTimeLimit int64
LimitFlags uint32
MinimumWorkingSetSize uintptr
MaximumWorkingSetSize uintptr
ActiveProcessLimit uint32
Affinity uintptr
PriorityClass uint32
SchedulingClass uint32
_ uint32 // pad to 8 byte boundary
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/exec_windows.go | vendor/golang.org/x/sys/windows/exec_windows.go | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Fork, exec, wait, etc.
package windows
import (
errorspkg "errors"
"unsafe"
)
// EscapeArg rewrites command line argument s as prescribed
// in http://msdn.microsoft.com/en-us/library/ms880421.
// This function returns "" (2 double quotes) if s is empty.
// Alternatively, these transformations are done:
// - every back slash (\) is doubled, but only if immediately
// followed by double quote (");
// - every double quote (") is escaped by back slash (\);
// - finally, s is wrapped with double quotes (arg -> "arg"),
// but only if there is space or tab inside s.
func EscapeArg(s string) string {
if len(s) == 0 {
return `""`
}
n := len(s)
hasSpace := false
for i := 0; i < len(s); i++ {
switch s[i] {
case '"', '\\':
n++
case ' ', '\t':
hasSpace = true
}
}
if hasSpace {
n += 2 // Reserve space for quotes.
}
if n == len(s) {
return s
}
qs := make([]byte, n)
j := 0
if hasSpace {
qs[j] = '"'
j++
}
slashes := 0
for i := 0; i < len(s); i++ {
switch s[i] {
default:
slashes = 0
qs[j] = s[i]
case '\\':
slashes++
qs[j] = s[i]
case '"':
for ; slashes > 0; slashes-- {
qs[j] = '\\'
j++
}
qs[j] = '\\'
j++
qs[j] = s[i]
}
j++
}
if hasSpace {
for ; slashes > 0; slashes-- {
qs[j] = '\\'
j++
}
qs[j] = '"'
j++
}
return string(qs[:j])
}
// ComposeCommandLine escapes and joins the given arguments suitable for use as a Windows command line,
// in CreateProcess's CommandLine argument, CreateService/ChangeServiceConfig's BinaryPathName argument,
// or any program that uses CommandLineToArgv.
func ComposeCommandLine(args []string) string {
if len(args) == 0 {
return ""
}
// Per https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-commandlinetoargvw:
// “This function accepts command lines that contain a program name; the
// program name can be enclosed in quotation marks or not.”
//
// Unfortunately, it provides no means of escaping interior quotation marks
// within that program name, and we have no way to report them here.
prog := args[0]
mustQuote := len(prog) == 0
for i := 0; i < len(prog); i++ {
c := prog[i]
if c <= ' ' || (c == '"' && i == 0) {
// Force quotes for not only the ASCII space and tab as described in the
// MSDN article, but also ASCII control characters.
// The documentation for CommandLineToArgvW doesn't say what happens when
// the first argument is not a valid program name, but it empirically
// seems to drop unquoted control characters.
mustQuote = true
break
}
}
var commandLine []byte
if mustQuote {
commandLine = make([]byte, 0, len(prog)+2)
commandLine = append(commandLine, '"')
for i := 0; i < len(prog); i++ {
c := prog[i]
if c == '"' {
// This quote would interfere with our surrounding quotes.
// We have no way to report an error, so just strip out
// the offending character instead.
continue
}
commandLine = append(commandLine, c)
}
commandLine = append(commandLine, '"')
} else {
if len(args) == 1 {
// args[0] is a valid command line representing itself.
// No need to allocate a new slice or string for it.
return prog
}
commandLine = []byte(prog)
}
for _, arg := range args[1:] {
commandLine = append(commandLine, ' ')
// TODO(bcmills): since we're already appending to a slice, it would be nice
// to avoid the intermediate allocations of EscapeArg.
// Perhaps we can factor out an appendEscapedArg function.
commandLine = append(commandLine, EscapeArg(arg)...)
}
return string(commandLine)
}
// DecomposeCommandLine breaks apart its argument command line into unescaped parts using CommandLineToArgv,
// as gathered from GetCommandLine, QUERY_SERVICE_CONFIG's BinaryPathName argument, or elsewhere that
// command lines are passed around.
// DecomposeCommandLine returns an error if commandLine contains NUL.
func DecomposeCommandLine(commandLine string) ([]string, error) {
if len(commandLine) == 0 {
return []string{}, nil
}
utf16CommandLine, err := UTF16FromString(commandLine)
if err != nil {
return nil, errorspkg.New("string with NUL passed to DecomposeCommandLine")
}
var argc int32
argv, err := commandLineToArgv(&utf16CommandLine[0], &argc)
if err != nil {
return nil, err
}
defer LocalFree(Handle(unsafe.Pointer(argv)))
var args []string
for _, p := range unsafe.Slice(argv, argc) {
args = append(args, UTF16PtrToString(p))
}
return args, nil
}
// CommandLineToArgv parses a Unicode command line string and sets
// argc to the number of parsed arguments.
//
// The returned memory should be freed using a single call to LocalFree.
//
// Note that although the return type of CommandLineToArgv indicates 8192
// entries of up to 8192 characters each, the actual count of parsed arguments
// may exceed 8192, and the documentation for CommandLineToArgvW does not mention
// any bound on the lengths of the individual argument strings.
// (See https://go.dev/issue/63236.)
func CommandLineToArgv(cmd *uint16, argc *int32) (argv *[8192]*[8192]uint16, err error) {
argp, err := commandLineToArgv(cmd, argc)
argv = (*[8192]*[8192]uint16)(unsafe.Pointer(argp))
return argv, err
}
func CloseOnExec(fd Handle) {
SetHandleInformation(Handle(fd), HANDLE_FLAG_INHERIT, 0)
}
// FullPath retrieves the full path of the specified file.
func FullPath(name string) (path string, err error) {
p, err := UTF16PtrFromString(name)
if err != nil {
return "", err
}
n := uint32(100)
for {
buf := make([]uint16, n)
n, err = GetFullPathName(p, uint32(len(buf)), &buf[0], nil)
if err != nil {
return "", err
}
if n <= uint32(len(buf)) {
return UTF16ToString(buf[:n]), nil
}
}
}
// NewProcThreadAttributeList allocates a new ProcThreadAttributeListContainer, with the requested maximum number of attributes.
func NewProcThreadAttributeList(maxAttrCount uint32) (*ProcThreadAttributeListContainer, error) {
var size uintptr
err := initializeProcThreadAttributeList(nil, maxAttrCount, 0, &size)
if err != ERROR_INSUFFICIENT_BUFFER {
if err == nil {
return nil, errorspkg.New("unable to query buffer size from InitializeProcThreadAttributeList")
}
return nil, err
}
alloc, err := LocalAlloc(LMEM_FIXED, uint32(size))
if err != nil {
return nil, err
}
// size is guaranteed to be ≥1 by InitializeProcThreadAttributeList.
al := &ProcThreadAttributeListContainer{data: (*ProcThreadAttributeList)(unsafe.Pointer(alloc))}
err = initializeProcThreadAttributeList(al.data, maxAttrCount, 0, &size)
if err != nil {
return nil, err
}
return al, err
}
// Update modifies the ProcThreadAttributeList using UpdateProcThreadAttribute.
func (al *ProcThreadAttributeListContainer) Update(attribute uintptr, value unsafe.Pointer, size uintptr) error {
al.pointers = append(al.pointers, value)
return updateProcThreadAttribute(al.data, 0, attribute, value, size, nil, nil)
}
// Delete frees ProcThreadAttributeList's resources.
func (al *ProcThreadAttributeListContainer) Delete() {
deleteProcThreadAttributeList(al.data)
LocalFree(Handle(unsafe.Pointer(al.data)))
al.data = nil
al.pointers = nil
}
// List returns the actual ProcThreadAttributeList to be passed to StartupInfoEx.
func (al *ProcThreadAttributeListContainer) List() *ProcThreadAttributeList {
return al.data
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/aliases.go | vendor/golang.org/x/sys/windows/aliases.go | // Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build windows
package windows
import "syscall"
type Errno = syscall.Errno
type SysProcAttr = syscall.SysProcAttr
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/syscall.go | vendor/golang.org/x/sys/windows/syscall.go | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build windows
// Package windows contains an interface to the low-level operating system
// primitives. OS details vary depending on the underlying system, and
// by default, godoc will display the OS-specific documentation for the current
// system. If you want godoc to display syscall documentation for another
// system, set $GOOS and $GOARCH to the desired system. For example, if
// you want to view documentation for freebsd/arm on linux/amd64, set $GOOS
// to freebsd and $GOARCH to arm.
//
// The primary use of this package is inside other packages that provide a more
// portable interface to the system, such as "os", "time" and "net". Use
// those packages rather than this one if you can.
//
// For details of the functions and data types in this package consult
// the manuals for the appropriate operating system.
//
// These calls return err == nil to indicate success; otherwise
// err represents an operating system error describing the failure and
// holds a value of type syscall.Errno.
package windows // import "golang.org/x/sys/windows"
import (
"bytes"
"strings"
"syscall"
"unsafe"
)
// ByteSliceFromString returns a NUL-terminated slice of bytes
// containing the text of s. If s contains a NUL byte at any
// location, it returns (nil, syscall.EINVAL).
func ByteSliceFromString(s string) ([]byte, error) {
if strings.IndexByte(s, 0) != -1 {
return nil, syscall.EINVAL
}
a := make([]byte, len(s)+1)
copy(a, s)
return a, nil
}
// BytePtrFromString returns a pointer to a NUL-terminated array of
// bytes containing the text of s. If s contains a NUL byte at any
// location, it returns (nil, syscall.EINVAL).
func BytePtrFromString(s string) (*byte, error) {
a, err := ByteSliceFromString(s)
if err != nil {
return nil, err
}
return &a[0], nil
}
// ByteSliceToString returns a string form of the text represented by the slice s, with a terminating NUL and any
// bytes after the NUL removed.
func ByteSliceToString(s []byte) string {
if i := bytes.IndexByte(s, 0); i != -1 {
s = s[:i]
}
return string(s)
}
// BytePtrToString takes a pointer to a sequence of text and returns the corresponding string.
// If the pointer is nil, it returns the empty string. It assumes that the text sequence is terminated
// at a zero byte; if the zero byte is not present, the program may crash.
func BytePtrToString(p *byte) string {
if p == nil {
return ""
}
if *p == 0 {
return ""
}
// Find NUL terminator.
n := 0
for ptr := unsafe.Pointer(p); *(*byte)(ptr) != 0; n++ {
ptr = unsafe.Pointer(uintptr(ptr) + 1)
}
return string(unsafe.Slice(p, n))
}
// Single-word zero for use when we need a valid pointer to 0 bytes.
// See mksyscall.pl.
var _zero uintptr
func (ts *Timespec) Unix() (sec int64, nsec int64) {
return int64(ts.Sec), int64(ts.Nsec)
}
func (tv *Timeval) Unix() (sec int64, nsec int64) {
return int64(tv.Sec), int64(tv.Usec) * 1000
}
func (ts *Timespec) Nano() int64 {
return int64(ts.Sec)*1e9 + int64(ts.Nsec)
}
func (tv *Timeval) Nano() int64 {
return int64(tv.Sec)*1e9 + int64(tv.Usec)*1000
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/syscall_windows.go | vendor/golang.org/x/sys/windows/syscall_windows.go | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Windows system calls.
package windows
import (
errorspkg "errors"
"fmt"
"runtime"
"sync"
"syscall"
"time"
"unicode/utf16"
"unsafe"
)
type (
Handle uintptr
HWND uintptr
)
const (
InvalidHandle = ^Handle(0)
InvalidHWND = ^HWND(0)
// Flags for DefineDosDevice.
DDD_EXACT_MATCH_ON_REMOVE = 0x00000004
DDD_NO_BROADCAST_SYSTEM = 0x00000008
DDD_RAW_TARGET_PATH = 0x00000001
DDD_REMOVE_DEFINITION = 0x00000002
// Return values for GetDriveType.
DRIVE_UNKNOWN = 0
DRIVE_NO_ROOT_DIR = 1
DRIVE_REMOVABLE = 2
DRIVE_FIXED = 3
DRIVE_REMOTE = 4
DRIVE_CDROM = 5
DRIVE_RAMDISK = 6
// File system flags from GetVolumeInformation and GetVolumeInformationByHandle.
FILE_CASE_SENSITIVE_SEARCH = 0x00000001
FILE_CASE_PRESERVED_NAMES = 0x00000002
FILE_FILE_COMPRESSION = 0x00000010
FILE_DAX_VOLUME = 0x20000000
FILE_NAMED_STREAMS = 0x00040000
FILE_PERSISTENT_ACLS = 0x00000008
FILE_READ_ONLY_VOLUME = 0x00080000
FILE_SEQUENTIAL_WRITE_ONCE = 0x00100000
FILE_SUPPORTS_ENCRYPTION = 0x00020000
FILE_SUPPORTS_EXTENDED_ATTRIBUTES = 0x00800000
FILE_SUPPORTS_HARD_LINKS = 0x00400000
FILE_SUPPORTS_OBJECT_IDS = 0x00010000
FILE_SUPPORTS_OPEN_BY_FILE_ID = 0x01000000
FILE_SUPPORTS_REPARSE_POINTS = 0x00000080
FILE_SUPPORTS_SPARSE_FILES = 0x00000040
FILE_SUPPORTS_TRANSACTIONS = 0x00200000
FILE_SUPPORTS_USN_JOURNAL = 0x02000000
FILE_UNICODE_ON_DISK = 0x00000004
FILE_VOLUME_IS_COMPRESSED = 0x00008000
FILE_VOLUME_QUOTAS = 0x00000020
// Flags for LockFileEx.
LOCKFILE_FAIL_IMMEDIATELY = 0x00000001
LOCKFILE_EXCLUSIVE_LOCK = 0x00000002
// Return value of SleepEx and other APC functions
WAIT_IO_COMPLETION = 0x000000C0
)
// StringToUTF16 is deprecated. Use UTF16FromString instead.
// If s contains a NUL byte this function panics instead of
// returning an error.
func StringToUTF16(s string) []uint16 {
a, err := UTF16FromString(s)
if err != nil {
panic("windows: string with NUL passed to StringToUTF16")
}
return a
}
// UTF16FromString returns the UTF-16 encoding of the UTF-8 string
// s, with a terminating NUL added. If s contains a NUL byte at any
// location, it returns (nil, syscall.EINVAL).
func UTF16FromString(s string) ([]uint16, error) {
return syscall.UTF16FromString(s)
}
// UTF16ToString returns the UTF-8 encoding of the UTF-16 sequence s,
// with a terminating NUL and any bytes after the NUL removed.
func UTF16ToString(s []uint16) string {
return syscall.UTF16ToString(s)
}
// StringToUTF16Ptr is deprecated. Use UTF16PtrFromString instead.
// If s contains a NUL byte this function panics instead of
// returning an error.
func StringToUTF16Ptr(s string) *uint16 { return &StringToUTF16(s)[0] }
// UTF16PtrFromString returns pointer to the UTF-16 encoding of
// the UTF-8 string s, with a terminating NUL added. If s
// contains a NUL byte at any location, it returns (nil, syscall.EINVAL).
func UTF16PtrFromString(s string) (*uint16, error) {
a, err := UTF16FromString(s)
if err != nil {
return nil, err
}
return &a[0], nil
}
// UTF16PtrToString takes a pointer to a UTF-16 sequence and returns the corresponding UTF-8 encoded string.
// If the pointer is nil, it returns the empty string. It assumes that the UTF-16 sequence is terminated
// at a zero word; if the zero word is not present, the program may crash.
func UTF16PtrToString(p *uint16) string {
if p == nil {
return ""
}
if *p == 0 {
return ""
}
// Find NUL terminator.
n := 0
for ptr := unsafe.Pointer(p); *(*uint16)(ptr) != 0; n++ {
ptr = unsafe.Pointer(uintptr(ptr) + unsafe.Sizeof(*p))
}
return UTF16ToString(unsafe.Slice(p, n))
}
func Getpagesize() int { return 4096 }
// NewCallback converts a Go function to a function pointer conforming to the stdcall calling convention.
// This is useful when interoperating with Windows code requiring callbacks.
// The argument is expected to be a function with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr.
func NewCallback(fn interface{}) uintptr {
return syscall.NewCallback(fn)
}
// NewCallbackCDecl converts a Go function to a function pointer conforming to the cdecl calling convention.
// This is useful when interoperating with Windows code requiring callbacks.
// The argument is expected to be a function with one uintptr-sized result. The function must not have arguments with size larger than the size of uintptr.
func NewCallbackCDecl(fn interface{}) uintptr {
return syscall.NewCallbackCDecl(fn)
}
// windows api calls
//sys GetLastError() (lasterr error)
//sys LoadLibrary(libname string) (handle Handle, err error) = LoadLibraryW
//sys LoadLibraryEx(libname string, zero Handle, flags uintptr) (handle Handle, err error) = LoadLibraryExW
//sys FreeLibrary(handle Handle) (err error)
//sys GetProcAddress(module Handle, procname string) (proc uintptr, err error)
//sys GetModuleFileName(module Handle, filename *uint16, size uint32) (n uint32, err error) = kernel32.GetModuleFileNameW
//sys GetModuleHandleEx(flags uint32, moduleName *uint16, module *Handle) (err error) = kernel32.GetModuleHandleExW
//sys SetDefaultDllDirectories(directoryFlags uint32) (err error)
//sys AddDllDirectory(path *uint16) (cookie uintptr, err error) = kernel32.AddDllDirectory
//sys RemoveDllDirectory(cookie uintptr) (err error) = kernel32.RemoveDllDirectory
//sys SetDllDirectory(path string) (err error) = kernel32.SetDllDirectoryW
//sys GetVersion() (ver uint32, err error)
//sys FormatMessage(flags uint32, msgsrc uintptr, msgid uint32, langid uint32, buf []uint16, args *byte) (n uint32, err error) = FormatMessageW
//sys ExitProcess(exitcode uint32)
//sys IsWow64Process(handle Handle, isWow64 *bool) (err error) = IsWow64Process
//sys IsWow64Process2(handle Handle, processMachine *uint16, nativeMachine *uint16) (err error) = IsWow64Process2?
//sys CreateFile(name *uint16, access uint32, mode uint32, sa *SecurityAttributes, createmode uint32, attrs uint32, templatefile Handle) (handle Handle, err error) [failretval==InvalidHandle] = CreateFileW
//sys CreateNamedPipe(name *uint16, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *SecurityAttributes) (handle Handle, err error) [failretval==InvalidHandle] = CreateNamedPipeW
//sys ConnectNamedPipe(pipe Handle, overlapped *Overlapped) (err error)
//sys DisconnectNamedPipe(pipe Handle) (err error)
//sys GetNamedPipeClientProcessId(pipe Handle, clientProcessID *uint32) (err error)
//sys GetNamedPipeServerProcessId(pipe Handle, serverProcessID *uint32) (err error)
//sys GetNamedPipeInfo(pipe Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error)
//sys GetNamedPipeHandleState(pipe Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) = GetNamedPipeHandleStateW
//sys SetNamedPipeHandleState(pipe Handle, state *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32) (err error) = SetNamedPipeHandleState
//sys readFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) = ReadFile
//sys writeFile(handle Handle, buf []byte, done *uint32, overlapped *Overlapped) (err error) = WriteFile
//sys GetOverlappedResult(handle Handle, overlapped *Overlapped, done *uint32, wait bool) (err error)
//sys SetFilePointer(handle Handle, lowoffset int32, highoffsetptr *int32, whence uint32) (newlowoffset uint32, err error) [failretval==0xffffffff]
//sys CloseHandle(handle Handle) (err error)
//sys GetStdHandle(stdhandle uint32) (handle Handle, err error) [failretval==InvalidHandle]
//sys SetStdHandle(stdhandle uint32, handle Handle) (err error)
//sys findFirstFile1(name *uint16, data *win32finddata1) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstFileW
//sys findNextFile1(handle Handle, data *win32finddata1) (err error) = FindNextFileW
//sys FindClose(handle Handle) (err error)
//sys GetFileInformationByHandle(handle Handle, data *ByHandleFileInformation) (err error)
//sys GetFileInformationByHandleEx(handle Handle, class uint32, outBuffer *byte, outBufferLen uint32) (err error)
//sys SetFileInformationByHandle(handle Handle, class uint32, inBuffer *byte, inBufferLen uint32) (err error)
//sys GetCurrentDirectory(buflen uint32, buf *uint16) (n uint32, err error) = GetCurrentDirectoryW
//sys SetCurrentDirectory(path *uint16) (err error) = SetCurrentDirectoryW
//sys CreateDirectory(path *uint16, sa *SecurityAttributes) (err error) = CreateDirectoryW
//sys RemoveDirectory(path *uint16) (err error) = RemoveDirectoryW
//sys DeleteFile(path *uint16) (err error) = DeleteFileW
//sys MoveFile(from *uint16, to *uint16) (err error) = MoveFileW
//sys MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) = MoveFileExW
//sys LockFileEx(file Handle, flags uint32, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error)
//sys UnlockFileEx(file Handle, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *Overlapped) (err error)
//sys GetComputerName(buf *uint16, n *uint32) (err error) = GetComputerNameW
//sys GetComputerNameEx(nametype uint32, buf *uint16, n *uint32) (err error) = GetComputerNameExW
//sys SetEndOfFile(handle Handle) (err error)
//sys SetFileValidData(handle Handle, validDataLength int64) (err error)
//sys GetSystemTimeAsFileTime(time *Filetime)
//sys GetSystemTimePreciseAsFileTime(time *Filetime)
//sys GetTimeZoneInformation(tzi *Timezoneinformation) (rc uint32, err error) [failretval==0xffffffff]
//sys CreateIoCompletionPort(filehandle Handle, cphandle Handle, key uintptr, threadcnt uint32) (handle Handle, err error)
//sys GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uintptr, overlapped **Overlapped, timeout uint32) (err error)
//sys PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uintptr, overlapped *Overlapped) (err error)
//sys CancelIo(s Handle) (err error)
//sys CancelIoEx(s Handle, o *Overlapped) (err error)
//sys CreateProcess(appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) = CreateProcessW
//sys CreateProcessAsUser(token Token, appName *uint16, commandLine *uint16, procSecurity *SecurityAttributes, threadSecurity *SecurityAttributes, inheritHandles bool, creationFlags uint32, env *uint16, currentDir *uint16, startupInfo *StartupInfo, outProcInfo *ProcessInformation) (err error) = advapi32.CreateProcessAsUserW
//sys initializeProcThreadAttributeList(attrlist *ProcThreadAttributeList, attrcount uint32, flags uint32, size *uintptr) (err error) = InitializeProcThreadAttributeList
//sys deleteProcThreadAttributeList(attrlist *ProcThreadAttributeList) = DeleteProcThreadAttributeList
//sys updateProcThreadAttribute(attrlist *ProcThreadAttributeList, flags uint32, attr uintptr, value unsafe.Pointer, size uintptr, prevvalue unsafe.Pointer, returnedsize *uintptr) (err error) = UpdateProcThreadAttribute
//sys OpenProcess(desiredAccess uint32, inheritHandle bool, processId uint32) (handle Handle, err error)
//sys ShellExecute(hwnd Handle, verb *uint16, file *uint16, args *uint16, cwd *uint16, showCmd int32) (err error) [failretval<=32] = shell32.ShellExecuteW
//sys GetWindowThreadProcessId(hwnd HWND, pid *uint32) (tid uint32, err error) = user32.GetWindowThreadProcessId
//sys LoadKeyboardLayout(name *uint16, flags uint32) (hkl Handle, err error) [failretval==0] = user32.LoadKeyboardLayoutW
//sys UnloadKeyboardLayout(hkl Handle) (err error) = user32.UnloadKeyboardLayout
//sys GetKeyboardLayout(tid uint32) (hkl Handle) = user32.GetKeyboardLayout
//sys ToUnicodeEx(vkey uint32, scancode uint32, keystate *byte, pwszBuff *uint16, cchBuff int32, flags uint32, hkl Handle) (ret int32) = user32.ToUnicodeEx
//sys GetShellWindow() (shellWindow HWND) = user32.GetShellWindow
//sys MessageBox(hwnd HWND, text *uint16, caption *uint16, boxtype uint32) (ret int32, err error) [failretval==0] = user32.MessageBoxW
//sys ExitWindowsEx(flags uint32, reason uint32) (err error) = user32.ExitWindowsEx
//sys shGetKnownFolderPath(id *KNOWNFOLDERID, flags uint32, token Token, path **uint16) (ret error) = shell32.SHGetKnownFolderPath
//sys TerminateProcess(handle Handle, exitcode uint32) (err error)
//sys GetExitCodeProcess(handle Handle, exitcode *uint32) (err error)
//sys getStartupInfo(startupInfo *StartupInfo) = GetStartupInfoW
//sys GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error)
//sys DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error)
//sys WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff]
//sys waitForMultipleObjects(count uint32, handles uintptr, waitAll bool, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff] = WaitForMultipleObjects
//sys GetTempPath(buflen uint32, buf *uint16) (n uint32, err error) = GetTempPathW
//sys CreatePipe(readhandle *Handle, writehandle *Handle, sa *SecurityAttributes, size uint32) (err error)
//sys GetFileType(filehandle Handle) (n uint32, err error)
//sys CryptAcquireContext(provhandle *Handle, container *uint16, provider *uint16, provtype uint32, flags uint32) (err error) = advapi32.CryptAcquireContextW
//sys CryptReleaseContext(provhandle Handle, flags uint32) (err error) = advapi32.CryptReleaseContext
//sys CryptGenRandom(provhandle Handle, buflen uint32, buf *byte) (err error) = advapi32.CryptGenRandom
//sys GetEnvironmentStrings() (envs *uint16, err error) [failretval==nil] = kernel32.GetEnvironmentStringsW
//sys FreeEnvironmentStrings(envs *uint16) (err error) = kernel32.FreeEnvironmentStringsW
//sys GetEnvironmentVariable(name *uint16, buffer *uint16, size uint32) (n uint32, err error) = kernel32.GetEnvironmentVariableW
//sys SetEnvironmentVariable(name *uint16, value *uint16) (err error) = kernel32.SetEnvironmentVariableW
//sys ExpandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) = kernel32.ExpandEnvironmentStringsW
//sys CreateEnvironmentBlock(block **uint16, token Token, inheritExisting bool) (err error) = userenv.CreateEnvironmentBlock
//sys DestroyEnvironmentBlock(block *uint16) (err error) = userenv.DestroyEnvironmentBlock
//sys getTickCount64() (ms uint64) = kernel32.GetTickCount64
//sys GetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error)
//sys SetFileTime(handle Handle, ctime *Filetime, atime *Filetime, wtime *Filetime) (err error)
//sys GetFileAttributes(name *uint16) (attrs uint32, err error) [failretval==INVALID_FILE_ATTRIBUTES] = kernel32.GetFileAttributesW
//sys SetFileAttributes(name *uint16, attrs uint32) (err error) = kernel32.SetFileAttributesW
//sys GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error) = kernel32.GetFileAttributesExW
//sys GetCommandLine() (cmd *uint16) = kernel32.GetCommandLineW
//sys commandLineToArgv(cmd *uint16, argc *int32) (argv **uint16, err error) [failretval==nil] = shell32.CommandLineToArgvW
//sys LocalFree(hmem Handle) (handle Handle, err error) [failretval!=0]
//sys LocalAlloc(flags uint32, length uint32) (ptr uintptr, err error)
//sys SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error)
//sys FlushFileBuffers(handle Handle) (err error)
//sys GetFullPathName(path *uint16, buflen uint32, buf *uint16, fname **uint16) (n uint32, err error) = kernel32.GetFullPathNameW
//sys GetLongPathName(path *uint16, buf *uint16, buflen uint32) (n uint32, err error) = kernel32.GetLongPathNameW
//sys GetShortPathName(longpath *uint16, shortpath *uint16, buflen uint32) (n uint32, err error) = kernel32.GetShortPathNameW
//sys GetFinalPathNameByHandle(file Handle, filePath *uint16, filePathSize uint32, flags uint32) (n uint32, err error) = kernel32.GetFinalPathNameByHandleW
//sys CreateFileMapping(fhandle Handle, sa *SecurityAttributes, prot uint32, maxSizeHigh uint32, maxSizeLow uint32, name *uint16) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateFileMappingW
//sys MapViewOfFile(handle Handle, access uint32, offsetHigh uint32, offsetLow uint32, length uintptr) (addr uintptr, err error)
//sys UnmapViewOfFile(addr uintptr) (err error)
//sys FlushViewOfFile(addr uintptr, length uintptr) (err error)
//sys VirtualLock(addr uintptr, length uintptr) (err error)
//sys VirtualUnlock(addr uintptr, length uintptr) (err error)
//sys VirtualAlloc(address uintptr, size uintptr, alloctype uint32, protect uint32) (value uintptr, err error) = kernel32.VirtualAlloc
//sys VirtualFree(address uintptr, size uintptr, freetype uint32) (err error) = kernel32.VirtualFree
//sys VirtualProtect(address uintptr, size uintptr, newprotect uint32, oldprotect *uint32) (err error) = kernel32.VirtualProtect
//sys VirtualProtectEx(process Handle, address uintptr, size uintptr, newProtect uint32, oldProtect *uint32) (err error) = kernel32.VirtualProtectEx
//sys VirtualQuery(address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error) = kernel32.VirtualQuery
//sys VirtualQueryEx(process Handle, address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error) = kernel32.VirtualQueryEx
//sys ReadProcessMemory(process Handle, baseAddress uintptr, buffer *byte, size uintptr, numberOfBytesRead *uintptr) (err error) = kernel32.ReadProcessMemory
//sys WriteProcessMemory(process Handle, baseAddress uintptr, buffer *byte, size uintptr, numberOfBytesWritten *uintptr) (err error) = kernel32.WriteProcessMemory
//sys TransmitFile(s Handle, handle Handle, bytesToWrite uint32, bytsPerSend uint32, overlapped *Overlapped, transmitFileBuf *TransmitFileBuffers, flags uint32) (err error) = mswsock.TransmitFile
//sys ReadDirectoryChanges(handle Handle, buf *byte, buflen uint32, watchSubTree bool, mask uint32, retlen *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) = kernel32.ReadDirectoryChangesW
//sys FindFirstChangeNotification(path string, watchSubtree bool, notifyFilter uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.FindFirstChangeNotificationW
//sys FindNextChangeNotification(handle Handle) (err error)
//sys FindCloseChangeNotification(handle Handle) (err error)
//sys CertOpenSystemStore(hprov Handle, name *uint16) (store Handle, err error) = crypt32.CertOpenSystemStoreW
//sys CertOpenStore(storeProvider uintptr, msgAndCertEncodingType uint32, cryptProv uintptr, flags uint32, para uintptr) (handle Handle, err error) = crypt32.CertOpenStore
//sys CertEnumCertificatesInStore(store Handle, prevContext *CertContext) (context *CertContext, err error) [failretval==nil] = crypt32.CertEnumCertificatesInStore
//sys CertAddCertificateContextToStore(store Handle, certContext *CertContext, addDisposition uint32, storeContext **CertContext) (err error) = crypt32.CertAddCertificateContextToStore
//sys CertCloseStore(store Handle, flags uint32) (err error) = crypt32.CertCloseStore
//sys CertDeleteCertificateFromStore(certContext *CertContext) (err error) = crypt32.CertDeleteCertificateFromStore
//sys CertDuplicateCertificateContext(certContext *CertContext) (dupContext *CertContext) = crypt32.CertDuplicateCertificateContext
//sys PFXImportCertStore(pfx *CryptDataBlob, password *uint16, flags uint32) (store Handle, err error) = crypt32.PFXImportCertStore
//sys CertGetCertificateChain(engine Handle, leaf *CertContext, time *Filetime, additionalStore Handle, para *CertChainPara, flags uint32, reserved uintptr, chainCtx **CertChainContext) (err error) = crypt32.CertGetCertificateChain
//sys CertFreeCertificateChain(ctx *CertChainContext) = crypt32.CertFreeCertificateChain
//sys CertCreateCertificateContext(certEncodingType uint32, certEncoded *byte, encodedLen uint32) (context *CertContext, err error) [failretval==nil] = crypt32.CertCreateCertificateContext
//sys CertFreeCertificateContext(ctx *CertContext) (err error) = crypt32.CertFreeCertificateContext
//sys CertVerifyCertificateChainPolicy(policyOID uintptr, chain *CertChainContext, para *CertChainPolicyPara, status *CertChainPolicyStatus) (err error) = crypt32.CertVerifyCertificateChainPolicy
//sys CertGetNameString(certContext *CertContext, nameType uint32, flags uint32, typePara unsafe.Pointer, name *uint16, size uint32) (chars uint32) = crypt32.CertGetNameStringW
//sys CertFindExtension(objId *byte, countExtensions uint32, extensions *CertExtension) (ret *CertExtension) = crypt32.CertFindExtension
//sys CertFindCertificateInStore(store Handle, certEncodingType uint32, findFlags uint32, findType uint32, findPara unsafe.Pointer, prevCertContext *CertContext) (cert *CertContext, err error) [failretval==nil] = crypt32.CertFindCertificateInStore
//sys CertFindChainInStore(store Handle, certEncodingType uint32, findFlags uint32, findType uint32, findPara unsafe.Pointer, prevChainContext *CertChainContext) (certchain *CertChainContext, err error) [failretval==nil] = crypt32.CertFindChainInStore
//sys CryptAcquireCertificatePrivateKey(cert *CertContext, flags uint32, parameters unsafe.Pointer, cryptProvOrNCryptKey *Handle, keySpec *uint32, callerFreeProvOrNCryptKey *bool) (err error) = crypt32.CryptAcquireCertificatePrivateKey
//sys CryptQueryObject(objectType uint32, object unsafe.Pointer, expectedContentTypeFlags uint32, expectedFormatTypeFlags uint32, flags uint32, msgAndCertEncodingType *uint32, contentType *uint32, formatType *uint32, certStore *Handle, msg *Handle, context *unsafe.Pointer) (err error) = crypt32.CryptQueryObject
//sys CryptDecodeObject(encodingType uint32, structType *byte, encodedBytes *byte, lenEncodedBytes uint32, flags uint32, decoded unsafe.Pointer, decodedLen *uint32) (err error) = crypt32.CryptDecodeObject
//sys CryptProtectData(dataIn *DataBlob, name *uint16, optionalEntropy *DataBlob, reserved uintptr, promptStruct *CryptProtectPromptStruct, flags uint32, dataOut *DataBlob) (err error) = crypt32.CryptProtectData
//sys CryptUnprotectData(dataIn *DataBlob, name **uint16, optionalEntropy *DataBlob, reserved uintptr, promptStruct *CryptProtectPromptStruct, flags uint32, dataOut *DataBlob) (err error) = crypt32.CryptUnprotectData
//sys WinVerifyTrustEx(hwnd HWND, actionId *GUID, data *WinTrustData) (ret error) = wintrust.WinVerifyTrustEx
//sys RegOpenKeyEx(key Handle, subkey *uint16, options uint32, desiredAccess uint32, result *Handle) (regerrno error) = advapi32.RegOpenKeyExW
//sys RegCloseKey(key Handle) (regerrno error) = advapi32.RegCloseKey
//sys RegQueryInfoKey(key Handle, class *uint16, classLen *uint32, reserved *uint32, subkeysLen *uint32, maxSubkeyLen *uint32, maxClassLen *uint32, valuesLen *uint32, maxValueNameLen *uint32, maxValueLen *uint32, saLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegQueryInfoKeyW
//sys RegEnumKeyEx(key Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, class *uint16, classLen *uint32, lastWriteTime *Filetime) (regerrno error) = advapi32.RegEnumKeyExW
//sys RegQueryValueEx(key Handle, name *uint16, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegQueryValueExW
//sys RegNotifyChangeKeyValue(key Handle, watchSubtree bool, notifyFilter uint32, event Handle, asynchronous bool) (regerrno error) = advapi32.RegNotifyChangeKeyValue
//sys GetCurrentProcessId() (pid uint32) = kernel32.GetCurrentProcessId
//sys ProcessIdToSessionId(pid uint32, sessionid *uint32) (err error) = kernel32.ProcessIdToSessionId
//sys ClosePseudoConsole(console Handle) = kernel32.ClosePseudoConsole
//sys createPseudoConsole(size uint32, in Handle, out Handle, flags uint32, pconsole *Handle) (hr error) = kernel32.CreatePseudoConsole
//sys GetConsoleMode(console Handle, mode *uint32) (err error) = kernel32.GetConsoleMode
//sys SetConsoleMode(console Handle, mode uint32) (err error) = kernel32.SetConsoleMode
//sys GetConsoleScreenBufferInfo(console Handle, info *ConsoleScreenBufferInfo) (err error) = kernel32.GetConsoleScreenBufferInfo
//sys setConsoleCursorPosition(console Handle, position uint32) (err error) = kernel32.SetConsoleCursorPosition
//sys GetConsoleCP() (cp uint32, err error) = kernel32.GetConsoleCP
//sys GetConsoleOutputCP() (cp uint32, err error) = kernel32.GetConsoleOutputCP
//sys SetConsoleCP(cp uint32) (err error) = kernel32.SetConsoleCP
//sys SetConsoleOutputCP(cp uint32) (err error) = kernel32.SetConsoleOutputCP
//sys WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) = kernel32.WriteConsoleW
//sys ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) = kernel32.ReadConsoleW
//sys GetNumberOfConsoleInputEvents(console Handle, numevents *uint32) (err error) = kernel32.GetNumberOfConsoleInputEvents
//sys FlushConsoleInputBuffer(console Handle) (err error) = kernel32.FlushConsoleInputBuffer
//sys resizePseudoConsole(pconsole Handle, size uint32) (hr error) = kernel32.ResizePseudoConsole
//sys CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.CreateToolhelp32Snapshot
//sys Module32First(snapshot Handle, moduleEntry *ModuleEntry32) (err error) = kernel32.Module32FirstW
//sys Module32Next(snapshot Handle, moduleEntry *ModuleEntry32) (err error) = kernel32.Module32NextW
//sys Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32FirstW
//sys Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) = kernel32.Process32NextW
//sys Thread32First(snapshot Handle, threadEntry *ThreadEntry32) (err error)
//sys Thread32Next(snapshot Handle, threadEntry *ThreadEntry32) (err error)
//sys DeviceIoControl(handle Handle, ioControlCode uint32, inBuffer *byte, inBufferSize uint32, outBuffer *byte, outBufferSize uint32, bytesReturned *uint32, overlapped *Overlapped) (err error)
// This function returns 1 byte BOOLEAN rather than the 4 byte BOOL.
//sys CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error) [failretval&0xff==0] = CreateSymbolicLinkW
//sys CreateHardLink(filename *uint16, existingfilename *uint16, reserved uintptr) (err error) [failretval&0xff==0] = CreateHardLinkW
//sys GetCurrentThreadId() (id uint32)
//sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateEventW
//sys CreateEventEx(eventAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateEventExW
//sys OpenEvent(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) = kernel32.OpenEventW
//sys SetEvent(event Handle) (err error) = kernel32.SetEvent
//sys ResetEvent(event Handle) (err error) = kernel32.ResetEvent
//sys PulseEvent(event Handle) (err error) = kernel32.PulseEvent
//sys CreateMutex(mutexAttrs *SecurityAttributes, initialOwner bool, name *uint16) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateMutexW
//sys CreateMutexEx(mutexAttrs *SecurityAttributes, name *uint16, flags uint32, desiredAccess uint32) (handle Handle, err error) [failretval == 0 || e1 == ERROR_ALREADY_EXISTS] = kernel32.CreateMutexExW
//sys OpenMutex(desiredAccess uint32, inheritHandle bool, name *uint16) (handle Handle, err error) = kernel32.OpenMutexW
//sys ReleaseMutex(mutex Handle) (err error) = kernel32.ReleaseMutex
//sys SleepEx(milliseconds uint32, alertable bool) (ret uint32) = kernel32.SleepEx
//sys CreateJobObject(jobAttr *SecurityAttributes, name *uint16) (handle Handle, err error) = kernel32.CreateJobObjectW
//sys AssignProcessToJobObject(job Handle, process Handle) (err error) = kernel32.AssignProcessToJobObject
//sys TerminateJobObject(job Handle, exitCode uint32) (err error) = kernel32.TerminateJobObject
//sys SetErrorMode(mode uint32) (ret uint32) = kernel32.SetErrorMode
//sys ResumeThread(thread Handle) (ret uint32, err error) [failretval==0xffffffff] = kernel32.ResumeThread
//sys SetPriorityClass(process Handle, priorityClass uint32) (err error) = kernel32.SetPriorityClass
//sys GetPriorityClass(process Handle) (ret uint32, err error) = kernel32.GetPriorityClass
//sys QueryInformationJobObject(job Handle, JobObjectInformationClass int32, JobObjectInformation uintptr, JobObjectInformationLength uint32, retlen *uint32) (err error) = kernel32.QueryInformationJobObject
//sys SetInformationJobObject(job Handle, JobObjectInformationClass uint32, JobObjectInformation uintptr, JobObjectInformationLength uint32) (ret int, err error)
//sys GenerateConsoleCtrlEvent(ctrlEvent uint32, processGroupID uint32) (err error)
//sys GetProcessId(process Handle) (id uint32, err error)
//sys QueryFullProcessImageName(proc Handle, flags uint32, exeName *uint16, size *uint32) (err error) = kernel32.QueryFullProcessImageNameW
//sys OpenThread(desiredAccess uint32, inheritHandle bool, threadId uint32) (handle Handle, err error)
//sys SetProcessPriorityBoost(process Handle, disable bool) (err error) = kernel32.SetProcessPriorityBoost
//sys GetProcessWorkingSetSizeEx(hProcess Handle, lpMinimumWorkingSetSize *uintptr, lpMaximumWorkingSetSize *uintptr, flags *uint32)
//sys SetProcessWorkingSetSizeEx(hProcess Handle, dwMinimumWorkingSetSize uintptr, dwMaximumWorkingSetSize uintptr, flags uint32) (err error)
//sys ClearCommBreak(handle Handle) (err error)
//sys ClearCommError(handle Handle, lpErrors *uint32, lpStat *ComStat) (err error)
//sys EscapeCommFunction(handle Handle, dwFunc uint32) (err error)
//sys GetCommState(handle Handle, lpDCB *DCB) (err error)
//sys GetCommModemStatus(handle Handle, lpModemStat *uint32) (err error)
//sys GetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error)
//sys PurgeComm(handle Handle, dwFlags uint32) (err error)
//sys SetCommBreak(handle Handle) (err error)
//sys SetCommMask(handle Handle, dwEvtMask uint32) (err error)
//sys SetCommState(handle Handle, lpDCB *DCB) (err error)
//sys SetCommTimeouts(handle Handle, timeouts *CommTimeouts) (err error)
//sys SetupComm(handle Handle, dwInQueue uint32, dwOutQueue uint32) (err error)
//sys WaitCommEvent(handle Handle, lpEvtMask *uint32, lpOverlapped *Overlapped) (err error)
//sys GetActiveProcessorCount(groupNumber uint16) (ret uint32)
//sys GetMaximumProcessorCount(groupNumber uint16) (ret uint32)
//sys EnumWindows(enumFunc uintptr, param unsafe.Pointer) (err error) = user32.EnumWindows
//sys EnumChildWindows(hwnd HWND, enumFunc uintptr, param unsafe.Pointer) = user32.EnumChildWindows
//sys GetClassName(hwnd HWND, className *uint16, maxCount int32) (copied int32, err error) = user32.GetClassNameW
//sys GetDesktopWindow() (hwnd HWND) = user32.GetDesktopWindow
//sys GetForegroundWindow() (hwnd HWND) = user32.GetForegroundWindow
//sys IsWindow(hwnd HWND) (isWindow bool) = user32.IsWindow
//sys IsWindowUnicode(hwnd HWND) (isUnicode bool) = user32.IsWindowUnicode
//sys IsWindowVisible(hwnd HWND) (isVisible bool) = user32.IsWindowVisible
//sys GetGUIThreadInfo(thread uint32, info *GUIThreadInfo) (err error) = user32.GetGUIThreadInfo
//sys GetLargePageMinimum() (size uintptr)
// Volume Management Functions
//sys DefineDosDevice(flags uint32, deviceName *uint16, targetPath *uint16) (err error) = DefineDosDeviceW
//sys DeleteVolumeMountPoint(volumeMountPoint *uint16) (err error) = DeleteVolumeMountPointW
//sys FindFirstVolume(volumeName *uint16, bufferLength uint32) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstVolumeW
//sys FindFirstVolumeMountPoint(rootPathName *uint16, volumeMountPoint *uint16, bufferLength uint32) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstVolumeMountPointW
//sys FindNextVolume(findVolume Handle, volumeName *uint16, bufferLength uint32) (err error) = FindNextVolumeW
//sys FindNextVolumeMountPoint(findVolumeMountPoint Handle, volumeMountPoint *uint16, bufferLength uint32) (err error) = FindNextVolumeMountPointW
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | true |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/memory_windows.go | vendor/golang.org/x/sys/windows/memory_windows.go | // Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package windows
const (
MEM_COMMIT = 0x00001000
MEM_RESERVE = 0x00002000
MEM_DECOMMIT = 0x00004000
MEM_RELEASE = 0x00008000
MEM_RESET = 0x00080000
MEM_TOP_DOWN = 0x00100000
MEM_WRITE_WATCH = 0x00200000
MEM_PHYSICAL = 0x00400000
MEM_RESET_UNDO = 0x01000000
MEM_LARGE_PAGES = 0x20000000
PAGE_NOACCESS = 0x00000001
PAGE_READONLY = 0x00000002
PAGE_READWRITE = 0x00000004
PAGE_WRITECOPY = 0x00000008
PAGE_EXECUTE = 0x00000010
PAGE_EXECUTE_READ = 0x00000020
PAGE_EXECUTE_READWRITE = 0x00000040
PAGE_EXECUTE_WRITECOPY = 0x00000080
PAGE_GUARD = 0x00000100
PAGE_NOCACHE = 0x00000200
PAGE_WRITECOMBINE = 0x00000400
PAGE_TARGETS_INVALID = 0x40000000
PAGE_TARGETS_NO_UPDATE = 0x40000000
QUOTA_LIMITS_HARDWS_MIN_DISABLE = 0x00000002
QUOTA_LIMITS_HARDWS_MIN_ENABLE = 0x00000001
QUOTA_LIMITS_HARDWS_MAX_DISABLE = 0x00000008
QUOTA_LIMITS_HARDWS_MAX_ENABLE = 0x00000004
)
type MemoryBasicInformation struct {
BaseAddress uintptr
AllocationBase uintptr
AllocationProtect uint32
PartitionId uint16
RegionSize uintptr
State uint32
Protect uint32
Type uint32
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/setupapi_windows.go | vendor/golang.org/x/sys/windows/setupapi_windows.go | // Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package windows
import (
"encoding/binary"
"errors"
"fmt"
"runtime"
"strings"
"syscall"
"unsafe"
)
// This file contains functions that wrap SetupAPI.dll and CfgMgr32.dll,
// core system functions for managing hardware devices, drivers, and the PnP tree.
// Information about these APIs can be found at:
// https://docs.microsoft.com/en-us/windows-hardware/drivers/install/setupapi
// https://docs.microsoft.com/en-us/windows/win32/devinst/cfgmgr32-
const (
ERROR_EXPECTED_SECTION_NAME Errno = 0x20000000 | 0xC0000000 | 0
ERROR_BAD_SECTION_NAME_LINE Errno = 0x20000000 | 0xC0000000 | 1
ERROR_SECTION_NAME_TOO_LONG Errno = 0x20000000 | 0xC0000000 | 2
ERROR_GENERAL_SYNTAX Errno = 0x20000000 | 0xC0000000 | 3
ERROR_WRONG_INF_STYLE Errno = 0x20000000 | 0xC0000000 | 0x100
ERROR_SECTION_NOT_FOUND Errno = 0x20000000 | 0xC0000000 | 0x101
ERROR_LINE_NOT_FOUND Errno = 0x20000000 | 0xC0000000 | 0x102
ERROR_NO_BACKUP Errno = 0x20000000 | 0xC0000000 | 0x103
ERROR_NO_ASSOCIATED_CLASS Errno = 0x20000000 | 0xC0000000 | 0x200
ERROR_CLASS_MISMATCH Errno = 0x20000000 | 0xC0000000 | 0x201
ERROR_DUPLICATE_FOUND Errno = 0x20000000 | 0xC0000000 | 0x202
ERROR_NO_DRIVER_SELECTED Errno = 0x20000000 | 0xC0000000 | 0x203
ERROR_KEY_DOES_NOT_EXIST Errno = 0x20000000 | 0xC0000000 | 0x204
ERROR_INVALID_DEVINST_NAME Errno = 0x20000000 | 0xC0000000 | 0x205
ERROR_INVALID_CLASS Errno = 0x20000000 | 0xC0000000 | 0x206
ERROR_DEVINST_ALREADY_EXISTS Errno = 0x20000000 | 0xC0000000 | 0x207
ERROR_DEVINFO_NOT_REGISTERED Errno = 0x20000000 | 0xC0000000 | 0x208
ERROR_INVALID_REG_PROPERTY Errno = 0x20000000 | 0xC0000000 | 0x209
ERROR_NO_INF Errno = 0x20000000 | 0xC0000000 | 0x20A
ERROR_NO_SUCH_DEVINST Errno = 0x20000000 | 0xC0000000 | 0x20B
ERROR_CANT_LOAD_CLASS_ICON Errno = 0x20000000 | 0xC0000000 | 0x20C
ERROR_INVALID_CLASS_INSTALLER Errno = 0x20000000 | 0xC0000000 | 0x20D
ERROR_DI_DO_DEFAULT Errno = 0x20000000 | 0xC0000000 | 0x20E
ERROR_DI_NOFILECOPY Errno = 0x20000000 | 0xC0000000 | 0x20F
ERROR_INVALID_HWPROFILE Errno = 0x20000000 | 0xC0000000 | 0x210
ERROR_NO_DEVICE_SELECTED Errno = 0x20000000 | 0xC0000000 | 0x211
ERROR_DEVINFO_LIST_LOCKED Errno = 0x20000000 | 0xC0000000 | 0x212
ERROR_DEVINFO_DATA_LOCKED Errno = 0x20000000 | 0xC0000000 | 0x213
ERROR_DI_BAD_PATH Errno = 0x20000000 | 0xC0000000 | 0x214
ERROR_NO_CLASSINSTALL_PARAMS Errno = 0x20000000 | 0xC0000000 | 0x215
ERROR_FILEQUEUE_LOCKED Errno = 0x20000000 | 0xC0000000 | 0x216
ERROR_BAD_SERVICE_INSTALLSECT Errno = 0x20000000 | 0xC0000000 | 0x217
ERROR_NO_CLASS_DRIVER_LIST Errno = 0x20000000 | 0xC0000000 | 0x218
ERROR_NO_ASSOCIATED_SERVICE Errno = 0x20000000 | 0xC0000000 | 0x219
ERROR_NO_DEFAULT_DEVICE_INTERFACE Errno = 0x20000000 | 0xC0000000 | 0x21A
ERROR_DEVICE_INTERFACE_ACTIVE Errno = 0x20000000 | 0xC0000000 | 0x21B
ERROR_DEVICE_INTERFACE_REMOVED Errno = 0x20000000 | 0xC0000000 | 0x21C
ERROR_BAD_INTERFACE_INSTALLSECT Errno = 0x20000000 | 0xC0000000 | 0x21D
ERROR_NO_SUCH_INTERFACE_CLASS Errno = 0x20000000 | 0xC0000000 | 0x21E
ERROR_INVALID_REFERENCE_STRING Errno = 0x20000000 | 0xC0000000 | 0x21F
ERROR_INVALID_MACHINENAME Errno = 0x20000000 | 0xC0000000 | 0x220
ERROR_REMOTE_COMM_FAILURE Errno = 0x20000000 | 0xC0000000 | 0x221
ERROR_MACHINE_UNAVAILABLE Errno = 0x20000000 | 0xC0000000 | 0x222
ERROR_NO_CONFIGMGR_SERVICES Errno = 0x20000000 | 0xC0000000 | 0x223
ERROR_INVALID_PROPPAGE_PROVIDER Errno = 0x20000000 | 0xC0000000 | 0x224
ERROR_NO_SUCH_DEVICE_INTERFACE Errno = 0x20000000 | 0xC0000000 | 0x225
ERROR_DI_POSTPROCESSING_REQUIRED Errno = 0x20000000 | 0xC0000000 | 0x226
ERROR_INVALID_COINSTALLER Errno = 0x20000000 | 0xC0000000 | 0x227
ERROR_NO_COMPAT_DRIVERS Errno = 0x20000000 | 0xC0000000 | 0x228
ERROR_NO_DEVICE_ICON Errno = 0x20000000 | 0xC0000000 | 0x229
ERROR_INVALID_INF_LOGCONFIG Errno = 0x20000000 | 0xC0000000 | 0x22A
ERROR_DI_DONT_INSTALL Errno = 0x20000000 | 0xC0000000 | 0x22B
ERROR_INVALID_FILTER_DRIVER Errno = 0x20000000 | 0xC0000000 | 0x22C
ERROR_NON_WINDOWS_NT_DRIVER Errno = 0x20000000 | 0xC0000000 | 0x22D
ERROR_NON_WINDOWS_DRIVER Errno = 0x20000000 | 0xC0000000 | 0x22E
ERROR_NO_CATALOG_FOR_OEM_INF Errno = 0x20000000 | 0xC0000000 | 0x22F
ERROR_DEVINSTALL_QUEUE_NONNATIVE Errno = 0x20000000 | 0xC0000000 | 0x230
ERROR_NOT_DISABLEABLE Errno = 0x20000000 | 0xC0000000 | 0x231
ERROR_CANT_REMOVE_DEVINST Errno = 0x20000000 | 0xC0000000 | 0x232
ERROR_INVALID_TARGET Errno = 0x20000000 | 0xC0000000 | 0x233
ERROR_DRIVER_NONNATIVE Errno = 0x20000000 | 0xC0000000 | 0x234
ERROR_IN_WOW64 Errno = 0x20000000 | 0xC0000000 | 0x235
ERROR_SET_SYSTEM_RESTORE_POINT Errno = 0x20000000 | 0xC0000000 | 0x236
ERROR_SCE_DISABLED Errno = 0x20000000 | 0xC0000000 | 0x238
ERROR_UNKNOWN_EXCEPTION Errno = 0x20000000 | 0xC0000000 | 0x239
ERROR_PNP_REGISTRY_ERROR Errno = 0x20000000 | 0xC0000000 | 0x23A
ERROR_REMOTE_REQUEST_UNSUPPORTED Errno = 0x20000000 | 0xC0000000 | 0x23B
ERROR_NOT_AN_INSTALLED_OEM_INF Errno = 0x20000000 | 0xC0000000 | 0x23C
ERROR_INF_IN_USE_BY_DEVICES Errno = 0x20000000 | 0xC0000000 | 0x23D
ERROR_DI_FUNCTION_OBSOLETE Errno = 0x20000000 | 0xC0000000 | 0x23E
ERROR_NO_AUTHENTICODE_CATALOG Errno = 0x20000000 | 0xC0000000 | 0x23F
ERROR_AUTHENTICODE_DISALLOWED Errno = 0x20000000 | 0xC0000000 | 0x240
ERROR_AUTHENTICODE_TRUSTED_PUBLISHER Errno = 0x20000000 | 0xC0000000 | 0x241
ERROR_AUTHENTICODE_TRUST_NOT_ESTABLISHED Errno = 0x20000000 | 0xC0000000 | 0x242
ERROR_AUTHENTICODE_PUBLISHER_NOT_TRUSTED Errno = 0x20000000 | 0xC0000000 | 0x243
ERROR_SIGNATURE_OSATTRIBUTE_MISMATCH Errno = 0x20000000 | 0xC0000000 | 0x244
ERROR_ONLY_VALIDATE_VIA_AUTHENTICODE Errno = 0x20000000 | 0xC0000000 | 0x245
ERROR_DEVICE_INSTALLER_NOT_READY Errno = 0x20000000 | 0xC0000000 | 0x246
ERROR_DRIVER_STORE_ADD_FAILED Errno = 0x20000000 | 0xC0000000 | 0x247
ERROR_DEVICE_INSTALL_BLOCKED Errno = 0x20000000 | 0xC0000000 | 0x248
ERROR_DRIVER_INSTALL_BLOCKED Errno = 0x20000000 | 0xC0000000 | 0x249
ERROR_WRONG_INF_TYPE Errno = 0x20000000 | 0xC0000000 | 0x24A
ERROR_FILE_HASH_NOT_IN_CATALOG Errno = 0x20000000 | 0xC0000000 | 0x24B
ERROR_DRIVER_STORE_DELETE_FAILED Errno = 0x20000000 | 0xC0000000 | 0x24C
ERROR_UNRECOVERABLE_STACK_OVERFLOW Errno = 0x20000000 | 0xC0000000 | 0x300
EXCEPTION_SPAPI_UNRECOVERABLE_STACK_OVERFLOW Errno = ERROR_UNRECOVERABLE_STACK_OVERFLOW
ERROR_NO_DEFAULT_INTERFACE_DEVICE Errno = ERROR_NO_DEFAULT_DEVICE_INTERFACE
ERROR_INTERFACE_DEVICE_ACTIVE Errno = ERROR_DEVICE_INTERFACE_ACTIVE
ERROR_INTERFACE_DEVICE_REMOVED Errno = ERROR_DEVICE_INTERFACE_REMOVED
ERROR_NO_SUCH_INTERFACE_DEVICE Errno = ERROR_NO_SUCH_DEVICE_INTERFACE
)
const (
MAX_DEVICE_ID_LEN = 200
MAX_DEVNODE_ID_LEN = MAX_DEVICE_ID_LEN
MAX_GUID_STRING_LEN = 39 // 38 chars + terminator null
MAX_CLASS_NAME_LEN = 32
MAX_PROFILE_LEN = 80
MAX_CONFIG_VALUE = 9999
MAX_INSTANCE_VALUE = 9999
CONFIGMG_VERSION = 0x0400
)
// Maximum string length constants
const (
LINE_LEN = 256 // Windows 9x-compatible maximum for displayable strings coming from a device INF.
MAX_INF_STRING_LENGTH = 4096 // Actual maximum size of an INF string (including string substitutions).
MAX_INF_SECTION_NAME_LENGTH = 255 // For Windows 9x compatibility, INF section names should be constrained to 32 characters.
MAX_TITLE_LEN = 60
MAX_INSTRUCTION_LEN = 256
MAX_LABEL_LEN = 30
MAX_SERVICE_NAME_LEN = 256
MAX_SUBTITLE_LEN = 256
)
const (
// SP_MAX_MACHINENAME_LENGTH defines maximum length of a machine name in the format expected by ConfigMgr32 CM_Connect_Machine (i.e., "\\\\MachineName\0").
SP_MAX_MACHINENAME_LENGTH = MAX_PATH + 3
)
// HSPFILEQ is type for setup file queue
type HSPFILEQ uintptr
// DevInfo holds reference to device information set
type DevInfo Handle
// DEVINST is a handle usually recognized by cfgmgr32 APIs
type DEVINST uint32
// DevInfoData is a device information structure (references a device instance that is a member of a device information set)
type DevInfoData struct {
size uint32
ClassGUID GUID
DevInst DEVINST
_ uintptr
}
// DevInfoListDetailData is a structure for detailed information on a device information set (used for SetupDiGetDeviceInfoListDetail which supersedes the functionality of SetupDiGetDeviceInfoListClass).
type DevInfoListDetailData struct {
size uint32 // Use unsafeSizeOf method
ClassGUID GUID
RemoteMachineHandle Handle
remoteMachineName [SP_MAX_MACHINENAME_LENGTH]uint16
}
func (*DevInfoListDetailData) unsafeSizeOf() uint32 {
if unsafe.Sizeof(uintptr(0)) == 4 {
// Windows declares this with pshpack1.h
return uint32(unsafe.Offsetof(DevInfoListDetailData{}.remoteMachineName) + unsafe.Sizeof(DevInfoListDetailData{}.remoteMachineName))
}
return uint32(unsafe.Sizeof(DevInfoListDetailData{}))
}
func (data *DevInfoListDetailData) RemoteMachineName() string {
return UTF16ToString(data.remoteMachineName[:])
}
func (data *DevInfoListDetailData) SetRemoteMachineName(remoteMachineName string) error {
str, err := UTF16FromString(remoteMachineName)
if err != nil {
return err
}
copy(data.remoteMachineName[:], str)
return nil
}
// DI_FUNCTION is function type for device installer
type DI_FUNCTION uint32
const (
DIF_SELECTDEVICE DI_FUNCTION = 0x00000001
DIF_INSTALLDEVICE DI_FUNCTION = 0x00000002
DIF_ASSIGNRESOURCES DI_FUNCTION = 0x00000003
DIF_PROPERTIES DI_FUNCTION = 0x00000004
DIF_REMOVE DI_FUNCTION = 0x00000005
DIF_FIRSTTIMESETUP DI_FUNCTION = 0x00000006
DIF_FOUNDDEVICE DI_FUNCTION = 0x00000007
DIF_SELECTCLASSDRIVERS DI_FUNCTION = 0x00000008
DIF_VALIDATECLASSDRIVERS DI_FUNCTION = 0x00000009
DIF_INSTALLCLASSDRIVERS DI_FUNCTION = 0x0000000A
DIF_CALCDISKSPACE DI_FUNCTION = 0x0000000B
DIF_DESTROYPRIVATEDATA DI_FUNCTION = 0x0000000C
DIF_VALIDATEDRIVER DI_FUNCTION = 0x0000000D
DIF_DETECT DI_FUNCTION = 0x0000000F
DIF_INSTALLWIZARD DI_FUNCTION = 0x00000010
DIF_DESTROYWIZARDDATA DI_FUNCTION = 0x00000011
DIF_PROPERTYCHANGE DI_FUNCTION = 0x00000012
DIF_ENABLECLASS DI_FUNCTION = 0x00000013
DIF_DETECTVERIFY DI_FUNCTION = 0x00000014
DIF_INSTALLDEVICEFILES DI_FUNCTION = 0x00000015
DIF_UNREMOVE DI_FUNCTION = 0x00000016
DIF_SELECTBESTCOMPATDRV DI_FUNCTION = 0x00000017
DIF_ALLOW_INSTALL DI_FUNCTION = 0x00000018
DIF_REGISTERDEVICE DI_FUNCTION = 0x00000019
DIF_NEWDEVICEWIZARD_PRESELECT DI_FUNCTION = 0x0000001A
DIF_NEWDEVICEWIZARD_SELECT DI_FUNCTION = 0x0000001B
DIF_NEWDEVICEWIZARD_PREANALYZE DI_FUNCTION = 0x0000001C
DIF_NEWDEVICEWIZARD_POSTANALYZE DI_FUNCTION = 0x0000001D
DIF_NEWDEVICEWIZARD_FINISHINSTALL DI_FUNCTION = 0x0000001E
DIF_INSTALLINTERFACES DI_FUNCTION = 0x00000020
DIF_DETECTCANCEL DI_FUNCTION = 0x00000021
DIF_REGISTER_COINSTALLERS DI_FUNCTION = 0x00000022
DIF_ADDPROPERTYPAGE_ADVANCED DI_FUNCTION = 0x00000023
DIF_ADDPROPERTYPAGE_BASIC DI_FUNCTION = 0x00000024
DIF_TROUBLESHOOTER DI_FUNCTION = 0x00000026
DIF_POWERMESSAGEWAKE DI_FUNCTION = 0x00000027
DIF_ADDREMOTEPROPERTYPAGE_ADVANCED DI_FUNCTION = 0x00000028
DIF_UPDATEDRIVER_UI DI_FUNCTION = 0x00000029
DIF_FINISHINSTALL_ACTION DI_FUNCTION = 0x0000002A
)
// DevInstallParams is device installation parameters structure (associated with a particular device information element, or globally with a device information set)
type DevInstallParams struct {
size uint32
Flags DI_FLAGS
FlagsEx DI_FLAGSEX
hwndParent uintptr
InstallMsgHandler uintptr
InstallMsgHandlerContext uintptr
FileQueue HSPFILEQ
_ uintptr
_ uint32
driverPath [MAX_PATH]uint16
}
func (params *DevInstallParams) DriverPath() string {
return UTF16ToString(params.driverPath[:])
}
func (params *DevInstallParams) SetDriverPath(driverPath string) error {
str, err := UTF16FromString(driverPath)
if err != nil {
return err
}
copy(params.driverPath[:], str)
return nil
}
// DI_FLAGS is SP_DEVINSTALL_PARAMS.Flags values
type DI_FLAGS uint32
const (
// Flags for choosing a device
DI_SHOWOEM DI_FLAGS = 0x00000001 // support Other... button
DI_SHOWCOMPAT DI_FLAGS = 0x00000002 // show compatibility list
DI_SHOWCLASS DI_FLAGS = 0x00000004 // show class list
DI_SHOWALL DI_FLAGS = 0x00000007 // both class & compat list shown
DI_NOVCP DI_FLAGS = 0x00000008 // don't create a new copy queue--use caller-supplied FileQueue
DI_DIDCOMPAT DI_FLAGS = 0x00000010 // Searched for compatible devices
DI_DIDCLASS DI_FLAGS = 0x00000020 // Searched for class devices
DI_AUTOASSIGNRES DI_FLAGS = 0x00000040 // No UI for resources if possible
// Flags returned by DiInstallDevice to indicate need to reboot/restart
DI_NEEDRESTART DI_FLAGS = 0x00000080 // Reboot required to take effect
DI_NEEDREBOOT DI_FLAGS = 0x00000100 // ""
// Flags for device installation
DI_NOBROWSE DI_FLAGS = 0x00000200 // no Browse... in InsertDisk
// Flags set by DiBuildDriverInfoList
DI_MULTMFGS DI_FLAGS = 0x00000400 // Set if multiple manufacturers in class driver list
// Flag indicates that device is disabled
DI_DISABLED DI_FLAGS = 0x00000800 // Set if device disabled
// Flags for Device/Class Properties
DI_GENERALPAGE_ADDED DI_FLAGS = 0x00001000
DI_RESOURCEPAGE_ADDED DI_FLAGS = 0x00002000
// Flag to indicate the setting properties for this Device (or class) caused a change so the Dev Mgr UI probably needs to be updated.
DI_PROPERTIES_CHANGE DI_FLAGS = 0x00004000
// Flag to indicate that the sorting from the INF file should be used.
DI_INF_IS_SORTED DI_FLAGS = 0x00008000
// Flag to indicate that only the INF specified by SP_DEVINSTALL_PARAMS.DriverPath should be searched.
DI_ENUMSINGLEINF DI_FLAGS = 0x00010000
// Flag that prevents ConfigMgr from removing/re-enumerating devices during device
// registration, installation, and deletion.
DI_DONOTCALLCONFIGMG DI_FLAGS = 0x00020000
// The following flag can be used to install a device disabled
DI_INSTALLDISABLED DI_FLAGS = 0x00040000
// Flag that causes SetupDiBuildDriverInfoList to build a device's compatible driver
// list from its existing class driver list, instead of the normal INF search.
DI_COMPAT_FROM_CLASS DI_FLAGS = 0x00080000
// This flag is set if the Class Install params should be used.
DI_CLASSINSTALLPARAMS DI_FLAGS = 0x00100000
// This flag is set if the caller of DiCallClassInstaller does NOT want the internal default action performed if the Class installer returns ERROR_DI_DO_DEFAULT.
DI_NODI_DEFAULTACTION DI_FLAGS = 0x00200000
// Flags for device installation
DI_QUIETINSTALL DI_FLAGS = 0x00800000 // don't confuse the user with questions or excess info
DI_NOFILECOPY DI_FLAGS = 0x01000000 // No file Copy necessary
DI_FORCECOPY DI_FLAGS = 0x02000000 // Force files to be copied from install path
DI_DRIVERPAGE_ADDED DI_FLAGS = 0x04000000 // Prop provider added Driver page.
DI_USECI_SELECTSTRINGS DI_FLAGS = 0x08000000 // Use Class Installer Provided strings in the Select Device Dlg
DI_OVERRIDE_INFFLAGS DI_FLAGS = 0x10000000 // Override INF flags
DI_PROPS_NOCHANGEUSAGE DI_FLAGS = 0x20000000 // No Enable/Disable in General Props
DI_NOSELECTICONS DI_FLAGS = 0x40000000 // No small icons in select device dialogs
DI_NOWRITE_IDS DI_FLAGS = 0x80000000 // Don't write HW & Compat IDs on install
)
// DI_FLAGSEX is SP_DEVINSTALL_PARAMS.FlagsEx values
type DI_FLAGSEX uint32
const (
DI_FLAGSEX_CI_FAILED DI_FLAGSEX = 0x00000004 // Failed to Load/Call class installer
DI_FLAGSEX_FINISHINSTALL_ACTION DI_FLAGSEX = 0x00000008 // Class/co-installer wants to get a DIF_FINISH_INSTALL action in client context.
DI_FLAGSEX_DIDINFOLIST DI_FLAGSEX = 0x00000010 // Did the Class Info List
DI_FLAGSEX_DIDCOMPATINFO DI_FLAGSEX = 0x00000020 // Did the Compat Info List
DI_FLAGSEX_FILTERCLASSES DI_FLAGSEX = 0x00000040
DI_FLAGSEX_SETFAILEDINSTALL DI_FLAGSEX = 0x00000080
DI_FLAGSEX_DEVICECHANGE DI_FLAGSEX = 0x00000100
DI_FLAGSEX_ALWAYSWRITEIDS DI_FLAGSEX = 0x00000200
DI_FLAGSEX_PROPCHANGE_PENDING DI_FLAGSEX = 0x00000400 // One or more device property sheets have had changes made to them, and need to have a DIF_PROPERTYCHANGE occur.
DI_FLAGSEX_ALLOWEXCLUDEDDRVS DI_FLAGSEX = 0x00000800
DI_FLAGSEX_NOUIONQUERYREMOVE DI_FLAGSEX = 0x00001000
DI_FLAGSEX_USECLASSFORCOMPAT DI_FLAGSEX = 0x00002000 // Use the device's class when building compat drv list. (Ignored if DI_COMPAT_FROM_CLASS flag is specified.)
DI_FLAGSEX_NO_DRVREG_MODIFY DI_FLAGSEX = 0x00008000 // Don't run AddReg and DelReg for device's software (driver) key.
DI_FLAGSEX_IN_SYSTEM_SETUP DI_FLAGSEX = 0x00010000 // Installation is occurring during initial system setup.
DI_FLAGSEX_INET_DRIVER DI_FLAGSEX = 0x00020000 // Driver came from Windows Update
DI_FLAGSEX_APPENDDRIVERLIST DI_FLAGSEX = 0x00040000 // Cause SetupDiBuildDriverInfoList to append a new driver list to an existing list.
DI_FLAGSEX_PREINSTALLBACKUP DI_FLAGSEX = 0x00080000 // not used
DI_FLAGSEX_BACKUPONREPLACE DI_FLAGSEX = 0x00100000 // not used
DI_FLAGSEX_DRIVERLIST_FROM_URL DI_FLAGSEX = 0x00200000 // build driver list from INF(s) retrieved from URL specified in SP_DEVINSTALL_PARAMS.DriverPath (empty string means Windows Update website)
DI_FLAGSEX_EXCLUDE_OLD_INET_DRIVERS DI_FLAGSEX = 0x00800000 // Don't include old Internet drivers when building a driver list. Ignored on Windows Vista and later.
DI_FLAGSEX_POWERPAGE_ADDED DI_FLAGSEX = 0x01000000 // class installer added their own power page
DI_FLAGSEX_FILTERSIMILARDRIVERS DI_FLAGSEX = 0x02000000 // only include similar drivers in class list
DI_FLAGSEX_INSTALLEDDRIVER DI_FLAGSEX = 0x04000000 // only add the installed driver to the class or compat driver list. Used in calls to SetupDiBuildDriverInfoList
DI_FLAGSEX_NO_CLASSLIST_NODE_MERGE DI_FLAGSEX = 0x08000000 // Don't remove identical driver nodes from the class list
DI_FLAGSEX_ALTPLATFORM_DRVSEARCH DI_FLAGSEX = 0x10000000 // Build driver list based on alternate platform information specified in associated file queue
DI_FLAGSEX_RESTART_DEVICE_ONLY DI_FLAGSEX = 0x20000000 // only restart the device drivers are being installed on as opposed to restarting all devices using those drivers.
DI_FLAGSEX_RECURSIVESEARCH DI_FLAGSEX = 0x40000000 // Tell SetupDiBuildDriverInfoList to do a recursive search
DI_FLAGSEX_SEARCH_PUBLISHED_INFS DI_FLAGSEX = 0x80000000 // Tell SetupDiBuildDriverInfoList to do a "published INF" search
)
// ClassInstallHeader is the first member of any class install parameters structure. It contains the device installation request code that defines the format of the rest of the install parameters structure.
type ClassInstallHeader struct {
size uint32
InstallFunction DI_FUNCTION
}
func MakeClassInstallHeader(installFunction DI_FUNCTION) *ClassInstallHeader {
hdr := &ClassInstallHeader{InstallFunction: installFunction}
hdr.size = uint32(unsafe.Sizeof(*hdr))
return hdr
}
// DICS_STATE specifies values indicating a change in a device's state
type DICS_STATE uint32
const (
DICS_ENABLE DICS_STATE = 0x00000001 // The device is being enabled.
DICS_DISABLE DICS_STATE = 0x00000002 // The device is being disabled.
DICS_PROPCHANGE DICS_STATE = 0x00000003 // The properties of the device have changed.
DICS_START DICS_STATE = 0x00000004 // The device is being started (if the request is for the currently active hardware profile).
DICS_STOP DICS_STATE = 0x00000005 // The device is being stopped. The driver stack will be unloaded and the CSCONFIGFLAG_DO_NOT_START flag will be set for the device.
)
// DICS_FLAG specifies the scope of a device property change
type DICS_FLAG uint32
const (
DICS_FLAG_GLOBAL DICS_FLAG = 0x00000001 // make change in all hardware profiles
DICS_FLAG_CONFIGSPECIFIC DICS_FLAG = 0x00000002 // make change in specified profile only
DICS_FLAG_CONFIGGENERAL DICS_FLAG = 0x00000004 // 1 or more hardware profile-specific changes to follow (obsolete)
)
// PropChangeParams is a structure corresponding to a DIF_PROPERTYCHANGE install function.
type PropChangeParams struct {
ClassInstallHeader ClassInstallHeader
StateChange DICS_STATE
Scope DICS_FLAG
HwProfile uint32
}
// DI_REMOVEDEVICE specifies the scope of the device removal
type DI_REMOVEDEVICE uint32
const (
DI_REMOVEDEVICE_GLOBAL DI_REMOVEDEVICE = 0x00000001 // Make this change in all hardware profiles. Remove information about the device from the registry.
DI_REMOVEDEVICE_CONFIGSPECIFIC DI_REMOVEDEVICE = 0x00000002 // Make this change to only the hardware profile specified by HwProfile. this flag only applies to root-enumerated devices. When Windows removes the device from the last hardware profile in which it was configured, Windows performs a global removal.
)
// RemoveDeviceParams is a structure corresponding to a DIF_REMOVE install function.
type RemoveDeviceParams struct {
ClassInstallHeader ClassInstallHeader
Scope DI_REMOVEDEVICE
HwProfile uint32
}
// DrvInfoData is driver information structure (member of a driver info list that may be associated with a particular device instance, or (globally) with a device information set)
type DrvInfoData struct {
size uint32
DriverType uint32
_ uintptr
description [LINE_LEN]uint16
mfgName [LINE_LEN]uint16
providerName [LINE_LEN]uint16
DriverDate Filetime
DriverVersion uint64
}
func (data *DrvInfoData) Description() string {
return UTF16ToString(data.description[:])
}
func (data *DrvInfoData) SetDescription(description string) error {
str, err := UTF16FromString(description)
if err != nil {
return err
}
copy(data.description[:], str)
return nil
}
func (data *DrvInfoData) MfgName() string {
return UTF16ToString(data.mfgName[:])
}
func (data *DrvInfoData) SetMfgName(mfgName string) error {
str, err := UTF16FromString(mfgName)
if err != nil {
return err
}
copy(data.mfgName[:], str)
return nil
}
func (data *DrvInfoData) ProviderName() string {
return UTF16ToString(data.providerName[:])
}
func (data *DrvInfoData) SetProviderName(providerName string) error {
str, err := UTF16FromString(providerName)
if err != nil {
return err
}
copy(data.providerName[:], str)
return nil
}
// IsNewer method returns true if DrvInfoData date and version is newer than supplied parameters.
func (data *DrvInfoData) IsNewer(driverDate Filetime, driverVersion uint64) bool {
if data.DriverDate.HighDateTime > driverDate.HighDateTime {
return true
}
if data.DriverDate.HighDateTime < driverDate.HighDateTime {
return false
}
if data.DriverDate.LowDateTime > driverDate.LowDateTime {
return true
}
if data.DriverDate.LowDateTime < driverDate.LowDateTime {
return false
}
if data.DriverVersion > driverVersion {
return true
}
if data.DriverVersion < driverVersion {
return false
}
return false
}
// DrvInfoDetailData is driver information details structure (provides detailed information about a particular driver information structure)
type DrvInfoDetailData struct {
size uint32 // Use unsafeSizeOf method
InfDate Filetime
compatIDsOffset uint32
compatIDsLength uint32
_ uintptr
sectionName [LINE_LEN]uint16
infFileName [MAX_PATH]uint16
drvDescription [LINE_LEN]uint16
hardwareID [1]uint16
}
func (*DrvInfoDetailData) unsafeSizeOf() uint32 {
if unsafe.Sizeof(uintptr(0)) == 4 {
// Windows declares this with pshpack1.h
return uint32(unsafe.Offsetof(DrvInfoDetailData{}.hardwareID) + unsafe.Sizeof(DrvInfoDetailData{}.hardwareID))
}
return uint32(unsafe.Sizeof(DrvInfoDetailData{}))
}
func (data *DrvInfoDetailData) SectionName() string {
return UTF16ToString(data.sectionName[:])
}
func (data *DrvInfoDetailData) InfFileName() string {
return UTF16ToString(data.infFileName[:])
}
func (data *DrvInfoDetailData) DrvDescription() string {
return UTF16ToString(data.drvDescription[:])
}
func (data *DrvInfoDetailData) HardwareID() string {
if data.compatIDsOffset > 1 {
bufW := data.getBuf()
return UTF16ToString(bufW[:wcslen(bufW)])
}
return ""
}
func (data *DrvInfoDetailData) CompatIDs() []string {
a := make([]string, 0)
if data.compatIDsLength > 0 {
bufW := data.getBuf()
bufW = bufW[data.compatIDsOffset : data.compatIDsOffset+data.compatIDsLength]
for i := 0; i < len(bufW); {
j := i + wcslen(bufW[i:])
if i < j {
a = append(a, UTF16ToString(bufW[i:j]))
}
i = j + 1
}
}
return a
}
func (data *DrvInfoDetailData) getBuf() []uint16 {
len := (data.size - uint32(unsafe.Offsetof(data.hardwareID))) / 2
sl := struct {
addr *uint16
len int
cap int
}{&data.hardwareID[0], int(len), int(len)}
return *(*[]uint16)(unsafe.Pointer(&sl))
}
// IsCompatible method tests if given hardware ID matches the driver or is listed on the compatible ID list.
func (data *DrvInfoDetailData) IsCompatible(hwid string) bool {
hwidLC := strings.ToLower(hwid)
if strings.ToLower(data.HardwareID()) == hwidLC {
return true
}
a := data.CompatIDs()
for i := range a {
if strings.ToLower(a[i]) == hwidLC {
return true
}
}
return false
}
// DICD flags control SetupDiCreateDeviceInfo
type DICD uint32
const (
DICD_GENERATE_ID DICD = 0x00000001
DICD_INHERIT_CLASSDRVS DICD = 0x00000002
)
// SUOI flags control SetupUninstallOEMInf
type SUOI uint32
const (
SUOI_FORCEDELETE SUOI = 0x0001
)
// SPDIT flags to distinguish between class drivers and
// device drivers. (Passed in 'DriverType' parameter of
// driver information list APIs)
type SPDIT uint32
const (
SPDIT_NODRIVER SPDIT = 0x00000000
SPDIT_CLASSDRIVER SPDIT = 0x00000001
SPDIT_COMPATDRIVER SPDIT = 0x00000002
)
// DIGCF flags control what is included in the device information set built by SetupDiGetClassDevs
type DIGCF uint32
const (
DIGCF_DEFAULT DIGCF = 0x00000001 // only valid with DIGCF_DEVICEINTERFACE
DIGCF_PRESENT DIGCF = 0x00000002
DIGCF_ALLCLASSES DIGCF = 0x00000004
DIGCF_PROFILE DIGCF = 0x00000008
DIGCF_DEVICEINTERFACE DIGCF = 0x00000010
)
// DIREG specifies values for SetupDiCreateDevRegKey, SetupDiOpenDevRegKey, and SetupDiDeleteDevRegKey.
type DIREG uint32
const (
DIREG_DEV DIREG = 0x00000001 // Open/Create/Delete device key
DIREG_DRV DIREG = 0x00000002 // Open/Create/Delete driver key
DIREG_BOTH DIREG = 0x00000004 // Delete both driver and Device key
)
// SPDRP specifies device registry property codes
// (Codes marked as read-only (R) may only be used for
// SetupDiGetDeviceRegistryProperty)
//
// These values should cover the same set of registry properties
// as defined by the CM_DRP codes in cfgmgr32.h.
//
// Note that SPDRP codes are zero based while CM_DRP codes are one based!
type SPDRP uint32
const (
SPDRP_DEVICEDESC SPDRP = 0x00000000 // DeviceDesc (R/W)
SPDRP_HARDWAREID SPDRP = 0x00000001 // HardwareID (R/W)
SPDRP_COMPATIBLEIDS SPDRP = 0x00000002 // CompatibleIDs (R/W)
SPDRP_SERVICE SPDRP = 0x00000004 // Service (R/W)
SPDRP_CLASS SPDRP = 0x00000007 // Class (R--tied to ClassGUID)
SPDRP_CLASSGUID SPDRP = 0x00000008 // ClassGUID (R/W)
SPDRP_DRIVER SPDRP = 0x00000009 // Driver (R/W)
SPDRP_CONFIGFLAGS SPDRP = 0x0000000A // ConfigFlags (R/W)
SPDRP_MFG SPDRP = 0x0000000B // Mfg (R/W)
SPDRP_FRIENDLYNAME SPDRP = 0x0000000C // FriendlyName (R/W)
SPDRP_LOCATION_INFORMATION SPDRP = 0x0000000D // LocationInformation (R/W)
SPDRP_PHYSICAL_DEVICE_OBJECT_NAME SPDRP = 0x0000000E // PhysicalDeviceObjectName (R)
SPDRP_CAPABILITIES SPDRP = 0x0000000F // Capabilities (R)
SPDRP_UI_NUMBER SPDRP = 0x00000010 // UiNumber (R)
SPDRP_UPPERFILTERS SPDRP = 0x00000011 // UpperFilters (R/W)
SPDRP_LOWERFILTERS SPDRP = 0x00000012 // LowerFilters (R/W)
SPDRP_BUSTYPEGUID SPDRP = 0x00000013 // BusTypeGUID (R)
SPDRP_LEGACYBUSTYPE SPDRP = 0x00000014 // LegacyBusType (R)
SPDRP_BUSNUMBER SPDRP = 0x00000015 // BusNumber (R)
SPDRP_ENUMERATOR_NAME SPDRP = 0x00000016 // Enumerator Name (R)
SPDRP_SECURITY SPDRP = 0x00000017 // Security (R/W, binary form)
SPDRP_SECURITY_SDS SPDRP = 0x00000018 // Security (W, SDS form)
SPDRP_DEVTYPE SPDRP = 0x00000019 // Device Type (R/W)
SPDRP_EXCLUSIVE SPDRP = 0x0000001A // Device is exclusive-access (R/W)
SPDRP_CHARACTERISTICS SPDRP = 0x0000001B // Device Characteristics (R/W)
SPDRP_ADDRESS SPDRP = 0x0000001C // Device Address (R)
SPDRP_UI_NUMBER_DESC_FORMAT SPDRP = 0x0000001D // UiNumberDescFormat (R/W)
SPDRP_DEVICE_POWER_DATA SPDRP = 0x0000001E // Device Power Data (R)
SPDRP_REMOVAL_POLICY SPDRP = 0x0000001F // Removal Policy (R)
SPDRP_REMOVAL_POLICY_HW_DEFAULT SPDRP = 0x00000020 // Hardware Removal Policy (R)
SPDRP_REMOVAL_POLICY_OVERRIDE SPDRP = 0x00000021 // Removal Policy Override (RW)
SPDRP_INSTALL_STATE SPDRP = 0x00000022 // Device Install State (R)
SPDRP_LOCATION_PATHS SPDRP = 0x00000023 // Device Location Paths (R)
SPDRP_BASE_CONTAINERID SPDRP = 0x00000024 // Base ContainerID (R)
SPDRP_MAXIMUM_PROPERTY SPDRP = 0x00000025 // Upper bound on ordinals
)
// DEVPROPTYPE represents the property-data-type identifier that specifies the
// data type of a device property value in the unified device property model.
type DEVPROPTYPE uint32
const (
DEVPROP_TYPEMOD_ARRAY DEVPROPTYPE = 0x00001000
DEVPROP_TYPEMOD_LIST DEVPROPTYPE = 0x00002000
DEVPROP_TYPE_EMPTY DEVPROPTYPE = 0x00000000
DEVPROP_TYPE_NULL DEVPROPTYPE = 0x00000001
DEVPROP_TYPE_SBYTE DEVPROPTYPE = 0x00000002
DEVPROP_TYPE_BYTE DEVPROPTYPE = 0x00000003
DEVPROP_TYPE_INT16 DEVPROPTYPE = 0x00000004
DEVPROP_TYPE_UINT16 DEVPROPTYPE = 0x00000005
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | true |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/zknownfolderids_windows.go | vendor/golang.org/x/sys/windows/zknownfolderids_windows.go | // Code generated by 'mkknownfolderids.bash'; DO NOT EDIT.
package windows
type KNOWNFOLDERID GUID
var (
FOLDERID_NetworkFolder = &KNOWNFOLDERID{0xd20beec4, 0x5ca8, 0x4905, [8]byte{0xae, 0x3b, 0xbf, 0x25, 0x1e, 0xa0, 0x9b, 0x53}}
FOLDERID_ComputerFolder = &KNOWNFOLDERID{0x0ac0837c, 0xbbf8, 0x452a, [8]byte{0x85, 0x0d, 0x79, 0xd0, 0x8e, 0x66, 0x7c, 0xa7}}
FOLDERID_InternetFolder = &KNOWNFOLDERID{0x4d9f7874, 0x4e0c, 0x4904, [8]byte{0x96, 0x7b, 0x40, 0xb0, 0xd2, 0x0c, 0x3e, 0x4b}}
FOLDERID_ControlPanelFolder = &KNOWNFOLDERID{0x82a74aeb, 0xaeb4, 0x465c, [8]byte{0xa0, 0x14, 0xd0, 0x97, 0xee, 0x34, 0x6d, 0x63}}
FOLDERID_PrintersFolder = &KNOWNFOLDERID{0x76fc4e2d, 0xd6ad, 0x4519, [8]byte{0xa6, 0x63, 0x37, 0xbd, 0x56, 0x06, 0x81, 0x85}}
FOLDERID_SyncManagerFolder = &KNOWNFOLDERID{0x43668bf8, 0xc14e, 0x49b2, [8]byte{0x97, 0xc9, 0x74, 0x77, 0x84, 0xd7, 0x84, 0xb7}}
FOLDERID_SyncSetupFolder = &KNOWNFOLDERID{0x0f214138, 0xb1d3, 0x4a90, [8]byte{0xbb, 0xa9, 0x27, 0xcb, 0xc0, 0xc5, 0x38, 0x9a}}
FOLDERID_ConflictFolder = &KNOWNFOLDERID{0x4bfefb45, 0x347d, 0x4006, [8]byte{0xa5, 0xbe, 0xac, 0x0c, 0xb0, 0x56, 0x71, 0x92}}
FOLDERID_SyncResultsFolder = &KNOWNFOLDERID{0x289a9a43, 0xbe44, 0x4057, [8]byte{0xa4, 0x1b, 0x58, 0x7a, 0x76, 0xd7, 0xe7, 0xf9}}
FOLDERID_RecycleBinFolder = &KNOWNFOLDERID{0xb7534046, 0x3ecb, 0x4c18, [8]byte{0xbe, 0x4e, 0x64, 0xcd, 0x4c, 0xb7, 0xd6, 0xac}}
FOLDERID_ConnectionsFolder = &KNOWNFOLDERID{0x6f0cd92b, 0x2e97, 0x45d1, [8]byte{0x88, 0xff, 0xb0, 0xd1, 0x86, 0xb8, 0xde, 0xdd}}
FOLDERID_Fonts = &KNOWNFOLDERID{0xfd228cb7, 0xae11, 0x4ae3, [8]byte{0x86, 0x4c, 0x16, 0xf3, 0x91, 0x0a, 0xb8, 0xfe}}
FOLDERID_Desktop = &KNOWNFOLDERID{0xb4bfcc3a, 0xdb2c, 0x424c, [8]byte{0xb0, 0x29, 0x7f, 0xe9, 0x9a, 0x87, 0xc6, 0x41}}
FOLDERID_Startup = &KNOWNFOLDERID{0xb97d20bb, 0xf46a, 0x4c97, [8]byte{0xba, 0x10, 0x5e, 0x36, 0x08, 0x43, 0x08, 0x54}}
FOLDERID_Programs = &KNOWNFOLDERID{0xa77f5d77, 0x2e2b, 0x44c3, [8]byte{0xa6, 0xa2, 0xab, 0xa6, 0x01, 0x05, 0x4a, 0x51}}
FOLDERID_StartMenu = &KNOWNFOLDERID{0x625b53c3, 0xab48, 0x4ec1, [8]byte{0xba, 0x1f, 0xa1, 0xef, 0x41, 0x46, 0xfc, 0x19}}
FOLDERID_Recent = &KNOWNFOLDERID{0xae50c081, 0xebd2, 0x438a, [8]byte{0x86, 0x55, 0x8a, 0x09, 0x2e, 0x34, 0x98, 0x7a}}
FOLDERID_SendTo = &KNOWNFOLDERID{0x8983036c, 0x27c0, 0x404b, [8]byte{0x8f, 0x08, 0x10, 0x2d, 0x10, 0xdc, 0xfd, 0x74}}
FOLDERID_Documents = &KNOWNFOLDERID{0xfdd39ad0, 0x238f, 0x46af, [8]byte{0xad, 0xb4, 0x6c, 0x85, 0x48, 0x03, 0x69, 0xc7}}
FOLDERID_Favorites = &KNOWNFOLDERID{0x1777f761, 0x68ad, 0x4d8a, [8]byte{0x87, 0xbd, 0x30, 0xb7, 0x59, 0xfa, 0x33, 0xdd}}
FOLDERID_NetHood = &KNOWNFOLDERID{0xc5abbf53, 0xe17f, 0x4121, [8]byte{0x89, 0x00, 0x86, 0x62, 0x6f, 0xc2, 0xc9, 0x73}}
FOLDERID_PrintHood = &KNOWNFOLDERID{0x9274bd8d, 0xcfd1, 0x41c3, [8]byte{0xb3, 0x5e, 0xb1, 0x3f, 0x55, 0xa7, 0x58, 0xf4}}
FOLDERID_Templates = &KNOWNFOLDERID{0xa63293e8, 0x664e, 0x48db, [8]byte{0xa0, 0x79, 0xdf, 0x75, 0x9e, 0x05, 0x09, 0xf7}}
FOLDERID_CommonStartup = &KNOWNFOLDERID{0x82a5ea35, 0xd9cd, 0x47c5, [8]byte{0x96, 0x29, 0xe1, 0x5d, 0x2f, 0x71, 0x4e, 0x6e}}
FOLDERID_CommonPrograms = &KNOWNFOLDERID{0x0139d44e, 0x6afe, 0x49f2, [8]byte{0x86, 0x90, 0x3d, 0xaf, 0xca, 0xe6, 0xff, 0xb8}}
FOLDERID_CommonStartMenu = &KNOWNFOLDERID{0xa4115719, 0xd62e, 0x491d, [8]byte{0xaa, 0x7c, 0xe7, 0x4b, 0x8b, 0xe3, 0xb0, 0x67}}
FOLDERID_PublicDesktop = &KNOWNFOLDERID{0xc4aa340d, 0xf20f, 0x4863, [8]byte{0xaf, 0xef, 0xf8, 0x7e, 0xf2, 0xe6, 0xba, 0x25}}
FOLDERID_ProgramData = &KNOWNFOLDERID{0x62ab5d82, 0xfdc1, 0x4dc3, [8]byte{0xa9, 0xdd, 0x07, 0x0d, 0x1d, 0x49, 0x5d, 0x97}}
FOLDERID_CommonTemplates = &KNOWNFOLDERID{0xb94237e7, 0x57ac, 0x4347, [8]byte{0x91, 0x51, 0xb0, 0x8c, 0x6c, 0x32, 0xd1, 0xf7}}
FOLDERID_PublicDocuments = &KNOWNFOLDERID{0xed4824af, 0xdce4, 0x45a8, [8]byte{0x81, 0xe2, 0xfc, 0x79, 0x65, 0x08, 0x36, 0x34}}
FOLDERID_RoamingAppData = &KNOWNFOLDERID{0x3eb685db, 0x65f9, 0x4cf6, [8]byte{0xa0, 0x3a, 0xe3, 0xef, 0x65, 0x72, 0x9f, 0x3d}}
FOLDERID_LocalAppData = &KNOWNFOLDERID{0xf1b32785, 0x6fba, 0x4fcf, [8]byte{0x9d, 0x55, 0x7b, 0x8e, 0x7f, 0x15, 0x70, 0x91}}
FOLDERID_LocalAppDataLow = &KNOWNFOLDERID{0xa520a1a4, 0x1780, 0x4ff6, [8]byte{0xbd, 0x18, 0x16, 0x73, 0x43, 0xc5, 0xaf, 0x16}}
FOLDERID_InternetCache = &KNOWNFOLDERID{0x352481e8, 0x33be, 0x4251, [8]byte{0xba, 0x85, 0x60, 0x07, 0xca, 0xed, 0xcf, 0x9d}}
FOLDERID_Cookies = &KNOWNFOLDERID{0x2b0f765d, 0xc0e9, 0x4171, [8]byte{0x90, 0x8e, 0x08, 0xa6, 0x11, 0xb8, 0x4f, 0xf6}}
FOLDERID_History = &KNOWNFOLDERID{0xd9dc8a3b, 0xb784, 0x432e, [8]byte{0xa7, 0x81, 0x5a, 0x11, 0x30, 0xa7, 0x59, 0x63}}
FOLDERID_System = &KNOWNFOLDERID{0x1ac14e77, 0x02e7, 0x4e5d, [8]byte{0xb7, 0x44, 0x2e, 0xb1, 0xae, 0x51, 0x98, 0xb7}}
FOLDERID_SystemX86 = &KNOWNFOLDERID{0xd65231b0, 0xb2f1, 0x4857, [8]byte{0xa4, 0xce, 0xa8, 0xe7, 0xc6, 0xea, 0x7d, 0x27}}
FOLDERID_Windows = &KNOWNFOLDERID{0xf38bf404, 0x1d43, 0x42f2, [8]byte{0x93, 0x05, 0x67, 0xde, 0x0b, 0x28, 0xfc, 0x23}}
FOLDERID_Profile = &KNOWNFOLDERID{0x5e6c858f, 0x0e22, 0x4760, [8]byte{0x9a, 0xfe, 0xea, 0x33, 0x17, 0xb6, 0x71, 0x73}}
FOLDERID_Pictures = &KNOWNFOLDERID{0x33e28130, 0x4e1e, 0x4676, [8]byte{0x83, 0x5a, 0x98, 0x39, 0x5c, 0x3b, 0xc3, 0xbb}}
FOLDERID_ProgramFilesX86 = &KNOWNFOLDERID{0x7c5a40ef, 0xa0fb, 0x4bfc, [8]byte{0x87, 0x4a, 0xc0, 0xf2, 0xe0, 0xb9, 0xfa, 0x8e}}
FOLDERID_ProgramFilesCommonX86 = &KNOWNFOLDERID{0xde974d24, 0xd9c6, 0x4d3e, [8]byte{0xbf, 0x91, 0xf4, 0x45, 0x51, 0x20, 0xb9, 0x17}}
FOLDERID_ProgramFilesX64 = &KNOWNFOLDERID{0x6d809377, 0x6af0, 0x444b, [8]byte{0x89, 0x57, 0xa3, 0x77, 0x3f, 0x02, 0x20, 0x0e}}
FOLDERID_ProgramFilesCommonX64 = &KNOWNFOLDERID{0x6365d5a7, 0x0f0d, 0x45e5, [8]byte{0x87, 0xf6, 0x0d, 0xa5, 0x6b, 0x6a, 0x4f, 0x7d}}
FOLDERID_ProgramFiles = &KNOWNFOLDERID{0x905e63b6, 0xc1bf, 0x494e, [8]byte{0xb2, 0x9c, 0x65, 0xb7, 0x32, 0xd3, 0xd2, 0x1a}}
FOLDERID_ProgramFilesCommon = &KNOWNFOLDERID{0xf7f1ed05, 0x9f6d, 0x47a2, [8]byte{0xaa, 0xae, 0x29, 0xd3, 0x17, 0xc6, 0xf0, 0x66}}
FOLDERID_UserProgramFiles = &KNOWNFOLDERID{0x5cd7aee2, 0x2219, 0x4a67, [8]byte{0xb8, 0x5d, 0x6c, 0x9c, 0xe1, 0x56, 0x60, 0xcb}}
FOLDERID_UserProgramFilesCommon = &KNOWNFOLDERID{0xbcbd3057, 0xca5c, 0x4622, [8]byte{0xb4, 0x2d, 0xbc, 0x56, 0xdb, 0x0a, 0xe5, 0x16}}
FOLDERID_AdminTools = &KNOWNFOLDERID{0x724ef170, 0xa42d, 0x4fef, [8]byte{0x9f, 0x26, 0xb6, 0x0e, 0x84, 0x6f, 0xba, 0x4f}}
FOLDERID_CommonAdminTools = &KNOWNFOLDERID{0xd0384e7d, 0xbac3, 0x4797, [8]byte{0x8f, 0x14, 0xcb, 0xa2, 0x29, 0xb3, 0x92, 0xb5}}
FOLDERID_Music = &KNOWNFOLDERID{0x4bd8d571, 0x6d19, 0x48d3, [8]byte{0xbe, 0x97, 0x42, 0x22, 0x20, 0x08, 0x0e, 0x43}}
FOLDERID_Videos = &KNOWNFOLDERID{0x18989b1d, 0x99b5, 0x455b, [8]byte{0x84, 0x1c, 0xab, 0x7c, 0x74, 0xe4, 0xdd, 0xfc}}
FOLDERID_Ringtones = &KNOWNFOLDERID{0xc870044b, 0xf49e, 0x4126, [8]byte{0xa9, 0xc3, 0xb5, 0x2a, 0x1f, 0xf4, 0x11, 0xe8}}
FOLDERID_PublicPictures = &KNOWNFOLDERID{0xb6ebfb86, 0x6907, 0x413c, [8]byte{0x9a, 0xf7, 0x4f, 0xc2, 0xab, 0xf0, 0x7c, 0xc5}}
FOLDERID_PublicMusic = &KNOWNFOLDERID{0x3214fab5, 0x9757, 0x4298, [8]byte{0xbb, 0x61, 0x92, 0xa9, 0xde, 0xaa, 0x44, 0xff}}
FOLDERID_PublicVideos = &KNOWNFOLDERID{0x2400183a, 0x6185, 0x49fb, [8]byte{0xa2, 0xd8, 0x4a, 0x39, 0x2a, 0x60, 0x2b, 0xa3}}
FOLDERID_PublicRingtones = &KNOWNFOLDERID{0xe555ab60, 0x153b, 0x4d17, [8]byte{0x9f, 0x04, 0xa5, 0xfe, 0x99, 0xfc, 0x15, 0xec}}
FOLDERID_ResourceDir = &KNOWNFOLDERID{0x8ad10c31, 0x2adb, 0x4296, [8]byte{0xa8, 0xf7, 0xe4, 0x70, 0x12, 0x32, 0xc9, 0x72}}
FOLDERID_LocalizedResourcesDir = &KNOWNFOLDERID{0x2a00375e, 0x224c, 0x49de, [8]byte{0xb8, 0xd1, 0x44, 0x0d, 0xf7, 0xef, 0x3d, 0xdc}}
FOLDERID_CommonOEMLinks = &KNOWNFOLDERID{0xc1bae2d0, 0x10df, 0x4334, [8]byte{0xbe, 0xdd, 0x7a, 0xa2, 0x0b, 0x22, 0x7a, 0x9d}}
FOLDERID_CDBurning = &KNOWNFOLDERID{0x9e52ab10, 0xf80d, 0x49df, [8]byte{0xac, 0xb8, 0x43, 0x30, 0xf5, 0x68, 0x78, 0x55}}
FOLDERID_UserProfiles = &KNOWNFOLDERID{0x0762d272, 0xc50a, 0x4bb0, [8]byte{0xa3, 0x82, 0x69, 0x7d, 0xcd, 0x72, 0x9b, 0x80}}
FOLDERID_Playlists = &KNOWNFOLDERID{0xde92c1c7, 0x837f, 0x4f69, [8]byte{0xa3, 0xbb, 0x86, 0xe6, 0x31, 0x20, 0x4a, 0x23}}
FOLDERID_SamplePlaylists = &KNOWNFOLDERID{0x15ca69b3, 0x30ee, 0x49c1, [8]byte{0xac, 0xe1, 0x6b, 0x5e, 0xc3, 0x72, 0xaf, 0xb5}}
FOLDERID_SampleMusic = &KNOWNFOLDERID{0xb250c668, 0xf57d, 0x4ee1, [8]byte{0xa6, 0x3c, 0x29, 0x0e, 0xe7, 0xd1, 0xaa, 0x1f}}
FOLDERID_SamplePictures = &KNOWNFOLDERID{0xc4900540, 0x2379, 0x4c75, [8]byte{0x84, 0x4b, 0x64, 0xe6, 0xfa, 0xf8, 0x71, 0x6b}}
FOLDERID_SampleVideos = &KNOWNFOLDERID{0x859ead94, 0x2e85, 0x48ad, [8]byte{0xa7, 0x1a, 0x09, 0x69, 0xcb, 0x56, 0xa6, 0xcd}}
FOLDERID_PhotoAlbums = &KNOWNFOLDERID{0x69d2cf90, 0xfc33, 0x4fb7, [8]byte{0x9a, 0x0c, 0xeb, 0xb0, 0xf0, 0xfc, 0xb4, 0x3c}}
FOLDERID_Public = &KNOWNFOLDERID{0xdfdf76a2, 0xc82a, 0x4d63, [8]byte{0x90, 0x6a, 0x56, 0x44, 0xac, 0x45, 0x73, 0x85}}
FOLDERID_ChangeRemovePrograms = &KNOWNFOLDERID{0xdf7266ac, 0x9274, 0x4867, [8]byte{0x8d, 0x55, 0x3b, 0xd6, 0x61, 0xde, 0x87, 0x2d}}
FOLDERID_AppUpdates = &KNOWNFOLDERID{0xa305ce99, 0xf527, 0x492b, [8]byte{0x8b, 0x1a, 0x7e, 0x76, 0xfa, 0x98, 0xd6, 0xe4}}
FOLDERID_AddNewPrograms = &KNOWNFOLDERID{0xde61d971, 0x5ebc, 0x4f02, [8]byte{0xa3, 0xa9, 0x6c, 0x82, 0x89, 0x5e, 0x5c, 0x04}}
FOLDERID_Downloads = &KNOWNFOLDERID{0x374de290, 0x123f, 0x4565, [8]byte{0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b}}
FOLDERID_PublicDownloads = &KNOWNFOLDERID{0x3d644c9b, 0x1fb8, 0x4f30, [8]byte{0x9b, 0x45, 0xf6, 0x70, 0x23, 0x5f, 0x79, 0xc0}}
FOLDERID_SavedSearches = &KNOWNFOLDERID{0x7d1d3a04, 0xdebb, 0x4115, [8]byte{0x95, 0xcf, 0x2f, 0x29, 0xda, 0x29, 0x20, 0xda}}
FOLDERID_QuickLaunch = &KNOWNFOLDERID{0x52a4f021, 0x7b75, 0x48a9, [8]byte{0x9f, 0x6b, 0x4b, 0x87, 0xa2, 0x10, 0xbc, 0x8f}}
FOLDERID_Contacts = &KNOWNFOLDERID{0x56784854, 0xc6cb, 0x462b, [8]byte{0x81, 0x69, 0x88, 0xe3, 0x50, 0xac, 0xb8, 0x82}}
FOLDERID_SidebarParts = &KNOWNFOLDERID{0xa75d362e, 0x50fc, 0x4fb7, [8]byte{0xac, 0x2c, 0xa8, 0xbe, 0xaa, 0x31, 0x44, 0x93}}
FOLDERID_SidebarDefaultParts = &KNOWNFOLDERID{0x7b396e54, 0x9ec5, 0x4300, [8]byte{0xbe, 0x0a, 0x24, 0x82, 0xeb, 0xae, 0x1a, 0x26}}
FOLDERID_PublicGameTasks = &KNOWNFOLDERID{0xdebf2536, 0xe1a8, 0x4c59, [8]byte{0xb6, 0xa2, 0x41, 0x45, 0x86, 0x47, 0x6a, 0xea}}
FOLDERID_GameTasks = &KNOWNFOLDERID{0x054fae61, 0x4dd8, 0x4787, [8]byte{0x80, 0xb6, 0x09, 0x02, 0x20, 0xc4, 0xb7, 0x00}}
FOLDERID_SavedGames = &KNOWNFOLDERID{0x4c5c32ff, 0xbb9d, 0x43b0, [8]byte{0xb5, 0xb4, 0x2d, 0x72, 0xe5, 0x4e, 0xaa, 0xa4}}
FOLDERID_Games = &KNOWNFOLDERID{0xcac52c1a, 0xb53d, 0x4edc, [8]byte{0x92, 0xd7, 0x6b, 0x2e, 0x8a, 0xc1, 0x94, 0x34}}
FOLDERID_SEARCH_MAPI = &KNOWNFOLDERID{0x98ec0e18, 0x2098, 0x4d44, [8]byte{0x86, 0x44, 0x66, 0x97, 0x93, 0x15, 0xa2, 0x81}}
FOLDERID_SEARCH_CSC = &KNOWNFOLDERID{0xee32e446, 0x31ca, 0x4aba, [8]byte{0x81, 0x4f, 0xa5, 0xeb, 0xd2, 0xfd, 0x6d, 0x5e}}
FOLDERID_Links = &KNOWNFOLDERID{0xbfb9d5e0, 0xc6a9, 0x404c, [8]byte{0xb2, 0xb2, 0xae, 0x6d, 0xb6, 0xaf, 0x49, 0x68}}
FOLDERID_UsersFiles = &KNOWNFOLDERID{0xf3ce0f7c, 0x4901, 0x4acc, [8]byte{0x86, 0x48, 0xd5, 0xd4, 0x4b, 0x04, 0xef, 0x8f}}
FOLDERID_UsersLibraries = &KNOWNFOLDERID{0xa302545d, 0xdeff, 0x464b, [8]byte{0xab, 0xe8, 0x61, 0xc8, 0x64, 0x8d, 0x93, 0x9b}}
FOLDERID_SearchHome = &KNOWNFOLDERID{0x190337d1, 0xb8ca, 0x4121, [8]byte{0xa6, 0x39, 0x6d, 0x47, 0x2d, 0x16, 0x97, 0x2a}}
FOLDERID_OriginalImages = &KNOWNFOLDERID{0x2c36c0aa, 0x5812, 0x4b87, [8]byte{0xbf, 0xd0, 0x4c, 0xd0, 0xdf, 0xb1, 0x9b, 0x39}}
FOLDERID_DocumentsLibrary = &KNOWNFOLDERID{0x7b0db17d, 0x9cd2, 0x4a93, [8]byte{0x97, 0x33, 0x46, 0xcc, 0x89, 0x02, 0x2e, 0x7c}}
FOLDERID_MusicLibrary = &KNOWNFOLDERID{0x2112ab0a, 0xc86a, 0x4ffe, [8]byte{0xa3, 0x68, 0x0d, 0xe9, 0x6e, 0x47, 0x01, 0x2e}}
FOLDERID_PicturesLibrary = &KNOWNFOLDERID{0xa990ae9f, 0xa03b, 0x4e80, [8]byte{0x94, 0xbc, 0x99, 0x12, 0xd7, 0x50, 0x41, 0x04}}
FOLDERID_VideosLibrary = &KNOWNFOLDERID{0x491e922f, 0x5643, 0x4af4, [8]byte{0xa7, 0xeb, 0x4e, 0x7a, 0x13, 0x8d, 0x81, 0x74}}
FOLDERID_RecordedTVLibrary = &KNOWNFOLDERID{0x1a6fdba2, 0xf42d, 0x4358, [8]byte{0xa7, 0x98, 0xb7, 0x4d, 0x74, 0x59, 0x26, 0xc5}}
FOLDERID_HomeGroup = &KNOWNFOLDERID{0x52528a6b, 0xb9e3, 0x4add, [8]byte{0xb6, 0x0d, 0x58, 0x8c, 0x2d, 0xba, 0x84, 0x2d}}
FOLDERID_HomeGroupCurrentUser = &KNOWNFOLDERID{0x9b74b6a3, 0x0dfd, 0x4f11, [8]byte{0x9e, 0x78, 0x5f, 0x78, 0x00, 0xf2, 0xe7, 0x72}}
FOLDERID_DeviceMetadataStore = &KNOWNFOLDERID{0x5ce4a5e9, 0xe4eb, 0x479d, [8]byte{0xb8, 0x9f, 0x13, 0x0c, 0x02, 0x88, 0x61, 0x55}}
FOLDERID_Libraries = &KNOWNFOLDERID{0x1b3ea5dc, 0xb587, 0x4786, [8]byte{0xb4, 0xef, 0xbd, 0x1d, 0xc3, 0x32, 0xae, 0xae}}
FOLDERID_PublicLibraries = &KNOWNFOLDERID{0x48daf80b, 0xe6cf, 0x4f4e, [8]byte{0xb8, 0x00, 0x0e, 0x69, 0xd8, 0x4e, 0xe3, 0x84}}
FOLDERID_UserPinned = &KNOWNFOLDERID{0x9e3995ab, 0x1f9c, 0x4f13, [8]byte{0xb8, 0x27, 0x48, 0xb2, 0x4b, 0x6c, 0x71, 0x74}}
FOLDERID_ImplicitAppShortcuts = &KNOWNFOLDERID{0xbcb5256f, 0x79f6, 0x4cee, [8]byte{0xb7, 0x25, 0xdc, 0x34, 0xe4, 0x02, 0xfd, 0x46}}
FOLDERID_AccountPictures = &KNOWNFOLDERID{0x008ca0b1, 0x55b4, 0x4c56, [8]byte{0xb8, 0xa8, 0x4d, 0xe4, 0xb2, 0x99, 0xd3, 0xbe}}
FOLDERID_PublicUserTiles = &KNOWNFOLDERID{0x0482af6c, 0x08f1, 0x4c34, [8]byte{0x8c, 0x90, 0xe1, 0x7e, 0xc9, 0x8b, 0x1e, 0x17}}
FOLDERID_AppsFolder = &KNOWNFOLDERID{0x1e87508d, 0x89c2, 0x42f0, [8]byte{0x8a, 0x7e, 0x64, 0x5a, 0x0f, 0x50, 0xca, 0x58}}
FOLDERID_StartMenuAllPrograms = &KNOWNFOLDERID{0xf26305ef, 0x6948, 0x40b9, [8]byte{0xb2, 0x55, 0x81, 0x45, 0x3d, 0x09, 0xc7, 0x85}}
FOLDERID_CommonStartMenuPlaces = &KNOWNFOLDERID{0xa440879f, 0x87a0, 0x4f7d, [8]byte{0xb7, 0x00, 0x02, 0x07, 0xb9, 0x66, 0x19, 0x4a}}
FOLDERID_ApplicationShortcuts = &KNOWNFOLDERID{0xa3918781, 0xe5f2, 0x4890, [8]byte{0xb3, 0xd9, 0xa7, 0xe5, 0x43, 0x32, 0x32, 0x8c}}
FOLDERID_RoamingTiles = &KNOWNFOLDERID{0x00bcfc5a, 0xed94, 0x4e48, [8]byte{0x96, 0xa1, 0x3f, 0x62, 0x17, 0xf2, 0x19, 0x90}}
FOLDERID_RoamedTileImages = &KNOWNFOLDERID{0xaaa8d5a5, 0xf1d6, 0x4259, [8]byte{0xba, 0xa8, 0x78, 0xe7, 0xef, 0x60, 0x83, 0x5e}}
FOLDERID_Screenshots = &KNOWNFOLDERID{0xb7bede81, 0xdf94, 0x4682, [8]byte{0xa7, 0xd8, 0x57, 0xa5, 0x26, 0x20, 0xb8, 0x6f}}
FOLDERID_CameraRoll = &KNOWNFOLDERID{0xab5fb87b, 0x7ce2, 0x4f83, [8]byte{0x91, 0x5d, 0x55, 0x08, 0x46, 0xc9, 0x53, 0x7b}}
FOLDERID_SkyDrive = &KNOWNFOLDERID{0xa52bba46, 0xe9e1, 0x435f, [8]byte{0xb3, 0xd9, 0x28, 0xda, 0xa6, 0x48, 0xc0, 0xf6}}
FOLDERID_OneDrive = &KNOWNFOLDERID{0xa52bba46, 0xe9e1, 0x435f, [8]byte{0xb3, 0xd9, 0x28, 0xda, 0xa6, 0x48, 0xc0, 0xf6}}
FOLDERID_SkyDriveDocuments = &KNOWNFOLDERID{0x24d89e24, 0x2f19, 0x4534, [8]byte{0x9d, 0xde, 0x6a, 0x66, 0x71, 0xfb, 0xb8, 0xfe}}
FOLDERID_SkyDrivePictures = &KNOWNFOLDERID{0x339719b5, 0x8c47, 0x4894, [8]byte{0x94, 0xc2, 0xd8, 0xf7, 0x7a, 0xdd, 0x44, 0xa6}}
FOLDERID_SkyDriveMusic = &KNOWNFOLDERID{0xc3f2459e, 0x80d6, 0x45dc, [8]byte{0xbf, 0xef, 0x1f, 0x76, 0x9f, 0x2b, 0xe7, 0x30}}
FOLDERID_SkyDriveCameraRoll = &KNOWNFOLDERID{0x767e6811, 0x49cb, 0x4273, [8]byte{0x87, 0xc2, 0x20, 0xf3, 0x55, 0xe1, 0x08, 0x5b}}
FOLDERID_SearchHistory = &KNOWNFOLDERID{0x0d4c3db6, 0x03a3, 0x462f, [8]byte{0xa0, 0xe6, 0x08, 0x92, 0x4c, 0x41, 0xb5, 0xd4}}
FOLDERID_SearchTemplates = &KNOWNFOLDERID{0x7e636bfe, 0xdfa9, 0x4d5e, [8]byte{0xb4, 0x56, 0xd7, 0xb3, 0x98, 0x51, 0xd8, 0xa9}}
FOLDERID_CameraRollLibrary = &KNOWNFOLDERID{0x2b20df75, 0x1eda, 0x4039, [8]byte{0x80, 0x97, 0x38, 0x79, 0x82, 0x27, 0xd5, 0xb7}}
FOLDERID_SavedPictures = &KNOWNFOLDERID{0x3b193882, 0xd3ad, 0x4eab, [8]byte{0x96, 0x5a, 0x69, 0x82, 0x9d, 0x1f, 0xb5, 0x9f}}
FOLDERID_SavedPicturesLibrary = &KNOWNFOLDERID{0xe25b5812, 0xbe88, 0x4bd9, [8]byte{0x94, 0xb0, 0x29, 0x23, 0x34, 0x77, 0xb6, 0xc3}}
FOLDERID_RetailDemo = &KNOWNFOLDERID{0x12d4c69e, 0x24ad, 0x4923, [8]byte{0xbe, 0x19, 0x31, 0x32, 0x1c, 0x43, 0xa7, 0x67}}
FOLDERID_Device = &KNOWNFOLDERID{0x1c2ac1dc, 0x4358, 0x4b6c, [8]byte{0x97, 0x33, 0xaf, 0x21, 0x15, 0x65, 0x76, 0xf0}}
FOLDERID_DevelopmentFiles = &KNOWNFOLDERID{0xdbe8e08e, 0x3053, 0x4bbc, [8]byte{0xb1, 0x83, 0x2a, 0x7b, 0x2b, 0x19, 0x1e, 0x59}}
FOLDERID_Objects3D = &KNOWNFOLDERID{0x31c0dd25, 0x9439, 0x4f12, [8]byte{0xbf, 0x41, 0x7f, 0xf4, 0xed, 0xa3, 0x87, 0x22}}
FOLDERID_AppCaptures = &KNOWNFOLDERID{0xedc0fe71, 0x98d8, 0x4f4a, [8]byte{0xb9, 0x20, 0xc8, 0xdc, 0x13, 0x3c, 0xb1, 0x65}}
FOLDERID_LocalDocuments = &KNOWNFOLDERID{0xf42ee2d3, 0x909f, 0x4907, [8]byte{0x88, 0x71, 0x4c, 0x22, 0xfc, 0x0b, 0xf7, 0x56}}
FOLDERID_LocalPictures = &KNOWNFOLDERID{0x0ddd015d, 0xb06c, 0x45d5, [8]byte{0x8c, 0x4c, 0xf5, 0x97, 0x13, 0x85, 0x46, 0x39}}
FOLDERID_LocalVideos = &KNOWNFOLDERID{0x35286a68, 0x3c57, 0x41a1, [8]byte{0xbb, 0xb1, 0x0e, 0xae, 0x73, 0xd7, 0x6c, 0x95}}
FOLDERID_LocalMusic = &KNOWNFOLDERID{0xa0c69a99, 0x21c8, 0x4671, [8]byte{0x87, 0x03, 0x79, 0x34, 0x16, 0x2f, 0xcf, 0x1d}}
FOLDERID_LocalDownloads = &KNOWNFOLDERID{0x7d83ee9b, 0x2244, 0x4e70, [8]byte{0xb1, 0xf5, 0x53, 0x93, 0x04, 0x2a, 0xf1, 0xe4}}
FOLDERID_RecordedCalls = &KNOWNFOLDERID{0x2f8b40c2, 0x83ed, 0x48ee, [8]byte{0xb3, 0x83, 0xa1, 0xf1, 0x57, 0xec, 0x6f, 0x9a}}
FOLDERID_AllAppMods = &KNOWNFOLDERID{0x7ad67899, 0x66af, 0x43ba, [8]byte{0x91, 0x56, 0x6a, 0xad, 0x42, 0xe6, 0xc5, 0x96}}
FOLDERID_CurrentAppMods = &KNOWNFOLDERID{0x3db40b20, 0x2a30, 0x4dbe, [8]byte{0x91, 0x7e, 0x77, 0x1d, 0xd2, 0x1d, 0xd0, 0x99}}
FOLDERID_AppDataDesktop = &KNOWNFOLDERID{0xb2c5e279, 0x7add, 0x439f, [8]byte{0xb2, 0x8c, 0xc4, 0x1f, 0xe1, 0xbb, 0xf6, 0x72}}
FOLDERID_AppDataDocuments = &KNOWNFOLDERID{0x7be16610, 0x1f7f, 0x44ac, [8]byte{0xbf, 0xf0, 0x83, 0xe1, 0x5f, 0x2f, 0xfc, 0xa1}}
FOLDERID_AppDataFavorites = &KNOWNFOLDERID{0x7cfbefbc, 0xde1f, 0x45aa, [8]byte{0xb8, 0x43, 0xa5, 0x42, 0xac, 0x53, 0x6c, 0xc9}}
FOLDERID_AppDataProgramData = &KNOWNFOLDERID{0x559d40a3, 0xa036, 0x40fa, [8]byte{0xaf, 0x61, 0x84, 0xcb, 0x43, 0x0a, 0x4d, 0x34}}
)
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/types_windows.go | vendor/golang.org/x/sys/windows/types_windows.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package windows
import (
"net"
"syscall"
"unsafe"
)
// NTStatus corresponds with NTSTATUS, error values returned by ntdll.dll and
// other native functions.
type NTStatus uint32
const (
// Invented values to support what package os expects.
O_RDONLY = 0x00000
O_WRONLY = 0x00001
O_RDWR = 0x00002
O_CREAT = 0x00040
O_EXCL = 0x00080
O_NOCTTY = 0x00100
O_TRUNC = 0x00200
O_NONBLOCK = 0x00800
O_APPEND = 0x00400
O_SYNC = 0x01000
O_ASYNC = 0x02000
O_CLOEXEC = 0x80000
)
const (
// More invented values for signals
SIGHUP = Signal(0x1)
SIGINT = Signal(0x2)
SIGQUIT = Signal(0x3)
SIGILL = Signal(0x4)
SIGTRAP = Signal(0x5)
SIGABRT = Signal(0x6)
SIGBUS = Signal(0x7)
SIGFPE = Signal(0x8)
SIGKILL = Signal(0x9)
SIGSEGV = Signal(0xb)
SIGPIPE = Signal(0xd)
SIGALRM = Signal(0xe)
SIGTERM = Signal(0xf)
)
var signals = [...]string{
1: "hangup",
2: "interrupt",
3: "quit",
4: "illegal instruction",
5: "trace/breakpoint trap",
6: "aborted",
7: "bus error",
8: "floating point exception",
9: "killed",
10: "user defined signal 1",
11: "segmentation fault",
12: "user defined signal 2",
13: "broken pipe",
14: "alarm clock",
15: "terminated",
}
// File flags for [os.OpenFile]. The O_ prefix is used to indicate
// that these flags are specific to the OpenFile function.
const (
O_FILE_FLAG_OPEN_NO_RECALL = FILE_FLAG_OPEN_NO_RECALL
O_FILE_FLAG_OPEN_REPARSE_POINT = FILE_FLAG_OPEN_REPARSE_POINT
O_FILE_FLAG_SESSION_AWARE = FILE_FLAG_SESSION_AWARE
O_FILE_FLAG_POSIX_SEMANTICS = FILE_FLAG_POSIX_SEMANTICS
O_FILE_FLAG_BACKUP_SEMANTICS = FILE_FLAG_BACKUP_SEMANTICS
O_FILE_FLAG_DELETE_ON_CLOSE = FILE_FLAG_DELETE_ON_CLOSE
O_FILE_FLAG_SEQUENTIAL_SCAN = FILE_FLAG_SEQUENTIAL_SCAN
O_FILE_FLAG_RANDOM_ACCESS = FILE_FLAG_RANDOM_ACCESS
O_FILE_FLAG_NO_BUFFERING = FILE_FLAG_NO_BUFFERING
O_FILE_FLAG_OVERLAPPED = FILE_FLAG_OVERLAPPED
O_FILE_FLAG_WRITE_THROUGH = FILE_FLAG_WRITE_THROUGH
)
const (
FILE_READ_DATA = 0x00000001
FILE_READ_ATTRIBUTES = 0x00000080
FILE_READ_EA = 0x00000008
FILE_WRITE_DATA = 0x00000002
FILE_WRITE_ATTRIBUTES = 0x00000100
FILE_WRITE_EA = 0x00000010
FILE_APPEND_DATA = 0x00000004
FILE_EXECUTE = 0x00000020
FILE_GENERIC_READ = STANDARD_RIGHTS_READ | FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA | SYNCHRONIZE
FILE_GENERIC_WRITE = STANDARD_RIGHTS_WRITE | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA | FILE_APPEND_DATA | SYNCHRONIZE
FILE_GENERIC_EXECUTE = STANDARD_RIGHTS_EXECUTE | FILE_READ_ATTRIBUTES | FILE_EXECUTE | SYNCHRONIZE
FILE_LIST_DIRECTORY = 0x00000001
FILE_TRAVERSE = 0x00000020
FILE_SHARE_READ = 0x00000001
FILE_SHARE_WRITE = 0x00000002
FILE_SHARE_DELETE = 0x00000004
FILE_ATTRIBUTE_READONLY = 0x00000001
FILE_ATTRIBUTE_HIDDEN = 0x00000002
FILE_ATTRIBUTE_SYSTEM = 0x00000004
FILE_ATTRIBUTE_DIRECTORY = 0x00000010
FILE_ATTRIBUTE_ARCHIVE = 0x00000020
FILE_ATTRIBUTE_DEVICE = 0x00000040
FILE_ATTRIBUTE_NORMAL = 0x00000080
FILE_ATTRIBUTE_TEMPORARY = 0x00000100
FILE_ATTRIBUTE_SPARSE_FILE = 0x00000200
FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400
FILE_ATTRIBUTE_COMPRESSED = 0x00000800
FILE_ATTRIBUTE_OFFLINE = 0x00001000
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 0x00002000
FILE_ATTRIBUTE_ENCRYPTED = 0x00004000
FILE_ATTRIBUTE_INTEGRITY_STREAM = 0x00008000
FILE_ATTRIBUTE_VIRTUAL = 0x00010000
FILE_ATTRIBUTE_NO_SCRUB_DATA = 0x00020000
FILE_ATTRIBUTE_RECALL_ON_OPEN = 0x00040000
FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS = 0x00400000
INVALID_FILE_ATTRIBUTES = 0xffffffff
CREATE_NEW = 1
CREATE_ALWAYS = 2
OPEN_EXISTING = 3
OPEN_ALWAYS = 4
TRUNCATE_EXISTING = 5
FILE_FLAG_OPEN_REQUIRING_OPLOCK = 0x00040000
FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000
FILE_FLAG_OPEN_NO_RECALL = 0x00100000
FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000
FILE_FLAG_SESSION_AWARE = 0x00800000
FILE_FLAG_POSIX_SEMANTICS = 0x01000000
FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
FILE_FLAG_DELETE_ON_CLOSE = 0x04000000
FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000
FILE_FLAG_RANDOM_ACCESS = 0x10000000
FILE_FLAG_NO_BUFFERING = 0x20000000
FILE_FLAG_OVERLAPPED = 0x40000000
FILE_FLAG_WRITE_THROUGH = 0x80000000
HANDLE_FLAG_INHERIT = 0x00000001
STARTF_USESTDHANDLES = 0x00000100
STARTF_USESHOWWINDOW = 0x00000001
DUPLICATE_CLOSE_SOURCE = 0x00000001
DUPLICATE_SAME_ACCESS = 0x00000002
STD_INPUT_HANDLE = -10 & (1<<32 - 1)
STD_OUTPUT_HANDLE = -11 & (1<<32 - 1)
STD_ERROR_HANDLE = -12 & (1<<32 - 1)
FILE_BEGIN = 0
FILE_CURRENT = 1
FILE_END = 2
LANG_ENGLISH = 0x09
SUBLANG_ENGLISH_US = 0x01
FORMAT_MESSAGE_ALLOCATE_BUFFER = 256
FORMAT_MESSAGE_IGNORE_INSERTS = 512
FORMAT_MESSAGE_FROM_STRING = 1024
FORMAT_MESSAGE_FROM_HMODULE = 2048
FORMAT_MESSAGE_FROM_SYSTEM = 4096
FORMAT_MESSAGE_ARGUMENT_ARRAY = 8192
FORMAT_MESSAGE_MAX_WIDTH_MASK = 255
MAX_PATH = 260
MAX_LONG_PATH = 32768
MAX_MODULE_NAME32 = 255
MAX_COMPUTERNAME_LENGTH = 15
MAX_DHCPV6_DUID_LENGTH = 130
MAX_DNS_SUFFIX_STRING_LENGTH = 256
TIME_ZONE_ID_UNKNOWN = 0
TIME_ZONE_ID_STANDARD = 1
TIME_ZONE_ID_DAYLIGHT = 2
IGNORE = 0
INFINITE = 0xffffffff
WAIT_ABANDONED = 0x00000080
WAIT_OBJECT_0 = 0x00000000
WAIT_FAILED = 0xFFFFFFFF
// Access rights for process.
PROCESS_ALL_ACCESS = 0xFFFF
PROCESS_CREATE_PROCESS = 0x0080
PROCESS_CREATE_THREAD = 0x0002
PROCESS_DUP_HANDLE = 0x0040
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
PROCESS_SET_INFORMATION = 0x0200
PROCESS_SET_QUOTA = 0x0100
PROCESS_SUSPEND_RESUME = 0x0800
PROCESS_TERMINATE = 0x0001
PROCESS_VM_OPERATION = 0x0008
PROCESS_VM_READ = 0x0010
PROCESS_VM_WRITE = 0x0020
// Access rights for thread.
THREAD_DIRECT_IMPERSONATION = 0x0200
THREAD_GET_CONTEXT = 0x0008
THREAD_IMPERSONATE = 0x0100
THREAD_QUERY_INFORMATION = 0x0040
THREAD_QUERY_LIMITED_INFORMATION = 0x0800
THREAD_SET_CONTEXT = 0x0010
THREAD_SET_INFORMATION = 0x0020
THREAD_SET_LIMITED_INFORMATION = 0x0400
THREAD_SET_THREAD_TOKEN = 0x0080
THREAD_SUSPEND_RESUME = 0x0002
THREAD_TERMINATE = 0x0001
FILE_MAP_COPY = 0x01
FILE_MAP_WRITE = 0x02
FILE_MAP_READ = 0x04
FILE_MAP_EXECUTE = 0x20
CTRL_C_EVENT = 0
CTRL_BREAK_EVENT = 1
CTRL_CLOSE_EVENT = 2
CTRL_LOGOFF_EVENT = 5
CTRL_SHUTDOWN_EVENT = 6
// Windows reserves errors >= 1<<29 for application use.
APPLICATION_ERROR = 1 << 29
)
const (
// Process creation flags.
CREATE_BREAKAWAY_FROM_JOB = 0x01000000
CREATE_DEFAULT_ERROR_MODE = 0x04000000
CREATE_NEW_CONSOLE = 0x00000010
CREATE_NEW_PROCESS_GROUP = 0x00000200
CREATE_NO_WINDOW = 0x08000000
CREATE_PROTECTED_PROCESS = 0x00040000
CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000
CREATE_SEPARATE_WOW_VDM = 0x00000800
CREATE_SHARED_WOW_VDM = 0x00001000
CREATE_SUSPENDED = 0x00000004
CREATE_UNICODE_ENVIRONMENT = 0x00000400
DEBUG_ONLY_THIS_PROCESS = 0x00000002
DEBUG_PROCESS = 0x00000001
DETACHED_PROCESS = 0x00000008
EXTENDED_STARTUPINFO_PRESENT = 0x00080000
INHERIT_PARENT_AFFINITY = 0x00010000
)
const (
// attributes for ProcThreadAttributeList
PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = 0x00020000
PROC_THREAD_ATTRIBUTE_HANDLE_LIST = 0x00020002
PROC_THREAD_ATTRIBUTE_GROUP_AFFINITY = 0x00030003
PROC_THREAD_ATTRIBUTE_PREFERRED_NODE = 0x00020004
PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR = 0x00030005
PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY = 0x00020007
PROC_THREAD_ATTRIBUTE_UMS_THREAD = 0x00030006
PROC_THREAD_ATTRIBUTE_PROTECTION_LEVEL = 0x0002000b
PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE = 0x00020016
)
const (
// flags for CreateToolhelp32Snapshot
TH32CS_SNAPHEAPLIST = 0x01
TH32CS_SNAPPROCESS = 0x02
TH32CS_SNAPTHREAD = 0x04
TH32CS_SNAPMODULE = 0x08
TH32CS_SNAPMODULE32 = 0x10
TH32CS_SNAPALL = TH32CS_SNAPHEAPLIST | TH32CS_SNAPMODULE | TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD
TH32CS_INHERIT = 0x80000000
)
const (
// flags for EnumProcessModulesEx
LIST_MODULES_32BIT = 0x01
LIST_MODULES_64BIT = 0x02
LIST_MODULES_ALL = 0x03
LIST_MODULES_DEFAULT = 0x00
)
const (
// filters for ReadDirectoryChangesW and FindFirstChangeNotificationW
FILE_NOTIFY_CHANGE_FILE_NAME = 0x001
FILE_NOTIFY_CHANGE_DIR_NAME = 0x002
FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x004
FILE_NOTIFY_CHANGE_SIZE = 0x008
FILE_NOTIFY_CHANGE_LAST_WRITE = 0x010
FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x020
FILE_NOTIFY_CHANGE_CREATION = 0x040
FILE_NOTIFY_CHANGE_SECURITY = 0x100
)
const (
// do not reorder
FILE_ACTION_ADDED = iota + 1
FILE_ACTION_REMOVED
FILE_ACTION_MODIFIED
FILE_ACTION_RENAMED_OLD_NAME
FILE_ACTION_RENAMED_NEW_NAME
)
const (
// wincrypt.h
/* certenrolld_begin -- PROV_RSA_*/
PROV_RSA_FULL = 1
PROV_RSA_SIG = 2
PROV_DSS = 3
PROV_FORTEZZA = 4
PROV_MS_EXCHANGE = 5
PROV_SSL = 6
PROV_RSA_SCHANNEL = 12
PROV_DSS_DH = 13
PROV_EC_ECDSA_SIG = 14
PROV_EC_ECNRA_SIG = 15
PROV_EC_ECDSA_FULL = 16
PROV_EC_ECNRA_FULL = 17
PROV_DH_SCHANNEL = 18
PROV_SPYRUS_LYNKS = 20
PROV_RNG = 21
PROV_INTEL_SEC = 22
PROV_REPLACE_OWF = 23
PROV_RSA_AES = 24
/* dwFlags definitions for CryptAcquireContext */
CRYPT_VERIFYCONTEXT = 0xF0000000
CRYPT_NEWKEYSET = 0x00000008
CRYPT_DELETEKEYSET = 0x00000010
CRYPT_MACHINE_KEYSET = 0x00000020
CRYPT_SILENT = 0x00000040
CRYPT_DEFAULT_CONTAINER_OPTIONAL = 0x00000080
/* Flags for PFXImportCertStore */
CRYPT_EXPORTABLE = 0x00000001
CRYPT_USER_PROTECTED = 0x00000002
CRYPT_USER_KEYSET = 0x00001000
PKCS12_PREFER_CNG_KSP = 0x00000100
PKCS12_ALWAYS_CNG_KSP = 0x00000200
PKCS12_ALLOW_OVERWRITE_KEY = 0x00004000
PKCS12_NO_PERSIST_KEY = 0x00008000
PKCS12_INCLUDE_EXTENDED_PROPERTIES = 0x00000010
/* Flags for CryptAcquireCertificatePrivateKey */
CRYPT_ACQUIRE_CACHE_FLAG = 0x00000001
CRYPT_ACQUIRE_USE_PROV_INFO_FLAG = 0x00000002
CRYPT_ACQUIRE_COMPARE_KEY_FLAG = 0x00000004
CRYPT_ACQUIRE_NO_HEALING = 0x00000008
CRYPT_ACQUIRE_SILENT_FLAG = 0x00000040
CRYPT_ACQUIRE_WINDOW_HANDLE_FLAG = 0x00000080
CRYPT_ACQUIRE_NCRYPT_KEY_FLAGS_MASK = 0x00070000
CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG = 0x00010000
CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG = 0x00020000
CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG = 0x00040000
/* pdwKeySpec for CryptAcquireCertificatePrivateKey */
AT_KEYEXCHANGE = 1
AT_SIGNATURE = 2
CERT_NCRYPT_KEY_SPEC = 0xFFFFFFFF
/* Default usage match type is AND with value zero */
USAGE_MATCH_TYPE_AND = 0
USAGE_MATCH_TYPE_OR = 1
/* msgAndCertEncodingType values for CertOpenStore function */
X509_ASN_ENCODING = 0x00000001
PKCS_7_ASN_ENCODING = 0x00010000
/* storeProvider values for CertOpenStore function */
CERT_STORE_PROV_MSG = 1
CERT_STORE_PROV_MEMORY = 2
CERT_STORE_PROV_FILE = 3
CERT_STORE_PROV_REG = 4
CERT_STORE_PROV_PKCS7 = 5
CERT_STORE_PROV_SERIALIZED = 6
CERT_STORE_PROV_FILENAME_A = 7
CERT_STORE_PROV_FILENAME_W = 8
CERT_STORE_PROV_FILENAME = CERT_STORE_PROV_FILENAME_W
CERT_STORE_PROV_SYSTEM_A = 9
CERT_STORE_PROV_SYSTEM_W = 10
CERT_STORE_PROV_SYSTEM = CERT_STORE_PROV_SYSTEM_W
CERT_STORE_PROV_COLLECTION = 11
CERT_STORE_PROV_SYSTEM_REGISTRY_A = 12
CERT_STORE_PROV_SYSTEM_REGISTRY_W = 13
CERT_STORE_PROV_SYSTEM_REGISTRY = CERT_STORE_PROV_SYSTEM_REGISTRY_W
CERT_STORE_PROV_PHYSICAL_W = 14
CERT_STORE_PROV_PHYSICAL = CERT_STORE_PROV_PHYSICAL_W
CERT_STORE_PROV_SMART_CARD_W = 15
CERT_STORE_PROV_SMART_CARD = CERT_STORE_PROV_SMART_CARD_W
CERT_STORE_PROV_LDAP_W = 16
CERT_STORE_PROV_LDAP = CERT_STORE_PROV_LDAP_W
CERT_STORE_PROV_PKCS12 = 17
/* store characteristics (low WORD of flag) for CertOpenStore function */
CERT_STORE_NO_CRYPT_RELEASE_FLAG = 0x00000001
CERT_STORE_SET_LOCALIZED_NAME_FLAG = 0x00000002
CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG = 0x00000004
CERT_STORE_DELETE_FLAG = 0x00000010
CERT_STORE_UNSAFE_PHYSICAL_FLAG = 0x00000020
CERT_STORE_SHARE_STORE_FLAG = 0x00000040
CERT_STORE_SHARE_CONTEXT_FLAG = 0x00000080
CERT_STORE_MANIFOLD_FLAG = 0x00000100
CERT_STORE_ENUM_ARCHIVED_FLAG = 0x00000200
CERT_STORE_UPDATE_KEYID_FLAG = 0x00000400
CERT_STORE_BACKUP_RESTORE_FLAG = 0x00000800
CERT_STORE_MAXIMUM_ALLOWED_FLAG = 0x00001000
CERT_STORE_CREATE_NEW_FLAG = 0x00002000
CERT_STORE_OPEN_EXISTING_FLAG = 0x00004000
CERT_STORE_READONLY_FLAG = 0x00008000
/* store locations (high WORD of flag) for CertOpenStore function */
CERT_SYSTEM_STORE_CURRENT_USER = 0x00010000
CERT_SYSTEM_STORE_LOCAL_MACHINE = 0x00020000
CERT_SYSTEM_STORE_CURRENT_SERVICE = 0x00040000
CERT_SYSTEM_STORE_SERVICES = 0x00050000
CERT_SYSTEM_STORE_USERS = 0x00060000
CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY = 0x00070000
CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY = 0x00080000
CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE = 0x00090000
CERT_SYSTEM_STORE_UNPROTECTED_FLAG = 0x40000000
CERT_SYSTEM_STORE_RELOCATE_FLAG = 0x80000000
/* Miscellaneous high-WORD flags for CertOpenStore function */
CERT_REGISTRY_STORE_REMOTE_FLAG = 0x00010000
CERT_REGISTRY_STORE_SERIALIZED_FLAG = 0x00020000
CERT_REGISTRY_STORE_ROAMING_FLAG = 0x00040000
CERT_REGISTRY_STORE_MY_IE_DIRTY_FLAG = 0x00080000
CERT_REGISTRY_STORE_LM_GPT_FLAG = 0x01000000
CERT_REGISTRY_STORE_CLIENT_GPT_FLAG = 0x80000000
CERT_FILE_STORE_COMMIT_ENABLE_FLAG = 0x00010000
CERT_LDAP_STORE_SIGN_FLAG = 0x00010000
CERT_LDAP_STORE_AREC_EXCLUSIVE_FLAG = 0x00020000
CERT_LDAP_STORE_OPENED_FLAG = 0x00040000
CERT_LDAP_STORE_UNBIND_FLAG = 0x00080000
/* addDisposition values for CertAddCertificateContextToStore function */
CERT_STORE_ADD_NEW = 1
CERT_STORE_ADD_USE_EXISTING = 2
CERT_STORE_ADD_REPLACE_EXISTING = 3
CERT_STORE_ADD_ALWAYS = 4
CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES = 5
CERT_STORE_ADD_NEWER = 6
CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES = 7
/* ErrorStatus values for CertTrustStatus struct */
CERT_TRUST_NO_ERROR = 0x00000000
CERT_TRUST_IS_NOT_TIME_VALID = 0x00000001
CERT_TRUST_IS_REVOKED = 0x00000004
CERT_TRUST_IS_NOT_SIGNATURE_VALID = 0x00000008
CERT_TRUST_IS_NOT_VALID_FOR_USAGE = 0x00000010
CERT_TRUST_IS_UNTRUSTED_ROOT = 0x00000020
CERT_TRUST_REVOCATION_STATUS_UNKNOWN = 0x00000040
CERT_TRUST_IS_CYCLIC = 0x00000080
CERT_TRUST_INVALID_EXTENSION = 0x00000100
CERT_TRUST_INVALID_POLICY_CONSTRAINTS = 0x00000200
CERT_TRUST_INVALID_BASIC_CONSTRAINTS = 0x00000400
CERT_TRUST_INVALID_NAME_CONSTRAINTS = 0x00000800
CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT = 0x00001000
CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT = 0x00002000
CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT = 0x00004000
CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT = 0x00008000
CERT_TRUST_IS_PARTIAL_CHAIN = 0x00010000
CERT_TRUST_CTL_IS_NOT_TIME_VALID = 0x00020000
CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID = 0x00040000
CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE = 0x00080000
CERT_TRUST_HAS_WEAK_SIGNATURE = 0x00100000
CERT_TRUST_IS_OFFLINE_REVOCATION = 0x01000000
CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY = 0x02000000
CERT_TRUST_IS_EXPLICIT_DISTRUST = 0x04000000
CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT = 0x08000000
/* InfoStatus values for CertTrustStatus struct */
CERT_TRUST_HAS_EXACT_MATCH_ISSUER = 0x00000001
CERT_TRUST_HAS_KEY_MATCH_ISSUER = 0x00000002
CERT_TRUST_HAS_NAME_MATCH_ISSUER = 0x00000004
CERT_TRUST_IS_SELF_SIGNED = 0x00000008
CERT_TRUST_HAS_PREFERRED_ISSUER = 0x00000100
CERT_TRUST_HAS_ISSUANCE_CHAIN_POLICY = 0x00000400
CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS = 0x00000400
CERT_TRUST_IS_PEER_TRUSTED = 0x00000800
CERT_TRUST_HAS_CRL_VALIDITY_EXTENDED = 0x00001000
CERT_TRUST_IS_FROM_EXCLUSIVE_TRUST_STORE = 0x00002000
CERT_TRUST_IS_CA_TRUSTED = 0x00004000
CERT_TRUST_IS_COMPLEX_CHAIN = 0x00010000
/* Certificate Information Flags */
CERT_INFO_VERSION_FLAG = 1
CERT_INFO_SERIAL_NUMBER_FLAG = 2
CERT_INFO_SIGNATURE_ALGORITHM_FLAG = 3
CERT_INFO_ISSUER_FLAG = 4
CERT_INFO_NOT_BEFORE_FLAG = 5
CERT_INFO_NOT_AFTER_FLAG = 6
CERT_INFO_SUBJECT_FLAG = 7
CERT_INFO_SUBJECT_PUBLIC_KEY_INFO_FLAG = 8
CERT_INFO_ISSUER_UNIQUE_ID_FLAG = 9
CERT_INFO_SUBJECT_UNIQUE_ID_FLAG = 10
CERT_INFO_EXTENSION_FLAG = 11
/* dwFindType for CertFindCertificateInStore */
CERT_COMPARE_MASK = 0xFFFF
CERT_COMPARE_SHIFT = 16
CERT_COMPARE_ANY = 0
CERT_COMPARE_SHA1_HASH = 1
CERT_COMPARE_NAME = 2
CERT_COMPARE_ATTR = 3
CERT_COMPARE_MD5_HASH = 4
CERT_COMPARE_PROPERTY = 5
CERT_COMPARE_PUBLIC_KEY = 6
CERT_COMPARE_HASH = CERT_COMPARE_SHA1_HASH
CERT_COMPARE_NAME_STR_A = 7
CERT_COMPARE_NAME_STR_W = 8
CERT_COMPARE_KEY_SPEC = 9
CERT_COMPARE_ENHKEY_USAGE = 10
CERT_COMPARE_CTL_USAGE = CERT_COMPARE_ENHKEY_USAGE
CERT_COMPARE_SUBJECT_CERT = 11
CERT_COMPARE_ISSUER_OF = 12
CERT_COMPARE_EXISTING = 13
CERT_COMPARE_SIGNATURE_HASH = 14
CERT_COMPARE_KEY_IDENTIFIER = 15
CERT_COMPARE_CERT_ID = 16
CERT_COMPARE_CROSS_CERT_DIST_POINTS = 17
CERT_COMPARE_PUBKEY_MD5_HASH = 18
CERT_COMPARE_SUBJECT_INFO_ACCESS = 19
CERT_COMPARE_HASH_STR = 20
CERT_COMPARE_HAS_PRIVATE_KEY = 21
CERT_FIND_ANY = (CERT_COMPARE_ANY << CERT_COMPARE_SHIFT)
CERT_FIND_SHA1_HASH = (CERT_COMPARE_SHA1_HASH << CERT_COMPARE_SHIFT)
CERT_FIND_MD5_HASH = (CERT_COMPARE_MD5_HASH << CERT_COMPARE_SHIFT)
CERT_FIND_SIGNATURE_HASH = (CERT_COMPARE_SIGNATURE_HASH << CERT_COMPARE_SHIFT)
CERT_FIND_KEY_IDENTIFIER = (CERT_COMPARE_KEY_IDENTIFIER << CERT_COMPARE_SHIFT)
CERT_FIND_HASH = CERT_FIND_SHA1_HASH
CERT_FIND_PROPERTY = (CERT_COMPARE_PROPERTY << CERT_COMPARE_SHIFT)
CERT_FIND_PUBLIC_KEY = (CERT_COMPARE_PUBLIC_KEY << CERT_COMPARE_SHIFT)
CERT_FIND_SUBJECT_NAME = (CERT_COMPARE_NAME<<CERT_COMPARE_SHIFT | CERT_INFO_SUBJECT_FLAG)
CERT_FIND_SUBJECT_ATTR = (CERT_COMPARE_ATTR<<CERT_COMPARE_SHIFT | CERT_INFO_SUBJECT_FLAG)
CERT_FIND_ISSUER_NAME = (CERT_COMPARE_NAME<<CERT_COMPARE_SHIFT | CERT_INFO_ISSUER_FLAG)
CERT_FIND_ISSUER_ATTR = (CERT_COMPARE_ATTR<<CERT_COMPARE_SHIFT | CERT_INFO_ISSUER_FLAG)
CERT_FIND_SUBJECT_STR_A = (CERT_COMPARE_NAME_STR_A<<CERT_COMPARE_SHIFT | CERT_INFO_SUBJECT_FLAG)
CERT_FIND_SUBJECT_STR_W = (CERT_COMPARE_NAME_STR_W<<CERT_COMPARE_SHIFT | CERT_INFO_SUBJECT_FLAG)
CERT_FIND_SUBJECT_STR = CERT_FIND_SUBJECT_STR_W
CERT_FIND_ISSUER_STR_A = (CERT_COMPARE_NAME_STR_A<<CERT_COMPARE_SHIFT | CERT_INFO_ISSUER_FLAG)
CERT_FIND_ISSUER_STR_W = (CERT_COMPARE_NAME_STR_W<<CERT_COMPARE_SHIFT | CERT_INFO_ISSUER_FLAG)
CERT_FIND_ISSUER_STR = CERT_FIND_ISSUER_STR_W
CERT_FIND_KEY_SPEC = (CERT_COMPARE_KEY_SPEC << CERT_COMPARE_SHIFT)
CERT_FIND_ENHKEY_USAGE = (CERT_COMPARE_ENHKEY_USAGE << CERT_COMPARE_SHIFT)
CERT_FIND_CTL_USAGE = CERT_FIND_ENHKEY_USAGE
CERT_FIND_SUBJECT_CERT = (CERT_COMPARE_SUBJECT_CERT << CERT_COMPARE_SHIFT)
CERT_FIND_ISSUER_OF = (CERT_COMPARE_ISSUER_OF << CERT_COMPARE_SHIFT)
CERT_FIND_EXISTING = (CERT_COMPARE_EXISTING << CERT_COMPARE_SHIFT)
CERT_FIND_CERT_ID = (CERT_COMPARE_CERT_ID << CERT_COMPARE_SHIFT)
CERT_FIND_CROSS_CERT_DIST_POINTS = (CERT_COMPARE_CROSS_CERT_DIST_POINTS << CERT_COMPARE_SHIFT)
CERT_FIND_PUBKEY_MD5_HASH = (CERT_COMPARE_PUBKEY_MD5_HASH << CERT_COMPARE_SHIFT)
CERT_FIND_SUBJECT_INFO_ACCESS = (CERT_COMPARE_SUBJECT_INFO_ACCESS << CERT_COMPARE_SHIFT)
CERT_FIND_HASH_STR = (CERT_COMPARE_HASH_STR << CERT_COMPARE_SHIFT)
CERT_FIND_HAS_PRIVATE_KEY = (CERT_COMPARE_HAS_PRIVATE_KEY << CERT_COMPARE_SHIFT)
CERT_FIND_OPTIONAL_ENHKEY_USAGE_FLAG = 0x1
CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG = 0x2
CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG = 0x4
CERT_FIND_NO_ENHKEY_USAGE_FLAG = 0x8
CERT_FIND_OR_ENHKEY_USAGE_FLAG = 0x10
CERT_FIND_VALID_ENHKEY_USAGE_FLAG = 0x20
CERT_FIND_OPTIONAL_CTL_USAGE_FLAG = CERT_FIND_OPTIONAL_ENHKEY_USAGE_FLAG
CERT_FIND_EXT_ONLY_CTL_USAGE_FLAG = CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG
CERT_FIND_PROP_ONLY_CTL_USAGE_FLAG = CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG
CERT_FIND_NO_CTL_USAGE_FLAG = CERT_FIND_NO_ENHKEY_USAGE_FLAG
CERT_FIND_OR_CTL_USAGE_FLAG = CERT_FIND_OR_ENHKEY_USAGE_FLAG
CERT_FIND_VALID_CTL_USAGE_FLAG = CERT_FIND_VALID_ENHKEY_USAGE_FLAG
/* policyOID values for CertVerifyCertificateChainPolicy function */
CERT_CHAIN_POLICY_BASE = 1
CERT_CHAIN_POLICY_AUTHENTICODE = 2
CERT_CHAIN_POLICY_AUTHENTICODE_TS = 3
CERT_CHAIN_POLICY_SSL = 4
CERT_CHAIN_POLICY_BASIC_CONSTRAINTS = 5
CERT_CHAIN_POLICY_NT_AUTH = 6
CERT_CHAIN_POLICY_MICROSOFT_ROOT = 7
CERT_CHAIN_POLICY_EV = 8
CERT_CHAIN_POLICY_SSL_F12 = 9
/* flag for dwFindType CertFindChainInStore */
CERT_CHAIN_FIND_BY_ISSUER = 1
/* dwFindFlags for CertFindChainInStore when dwFindType == CERT_CHAIN_FIND_BY_ISSUER */
CERT_CHAIN_FIND_BY_ISSUER_COMPARE_KEY_FLAG = 0x0001
CERT_CHAIN_FIND_BY_ISSUER_COMPLEX_CHAIN_FLAG = 0x0002
CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_URL_FLAG = 0x0004
CERT_CHAIN_FIND_BY_ISSUER_LOCAL_MACHINE_FLAG = 0x0008
CERT_CHAIN_FIND_BY_ISSUER_NO_KEY_FLAG = 0x4000
CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_FLAG = 0x8000
/* Certificate Store close flags */
CERT_CLOSE_STORE_FORCE_FLAG = 0x00000001
CERT_CLOSE_STORE_CHECK_FLAG = 0x00000002
/* CryptQueryObject object type */
CERT_QUERY_OBJECT_FILE = 1
CERT_QUERY_OBJECT_BLOB = 2
/* CryptQueryObject content type flags */
CERT_QUERY_CONTENT_CERT = 1
CERT_QUERY_CONTENT_CTL = 2
CERT_QUERY_CONTENT_CRL = 3
CERT_QUERY_CONTENT_SERIALIZED_STORE = 4
CERT_QUERY_CONTENT_SERIALIZED_CERT = 5
CERT_QUERY_CONTENT_SERIALIZED_CTL = 6
CERT_QUERY_CONTENT_SERIALIZED_CRL = 7
CERT_QUERY_CONTENT_PKCS7_SIGNED = 8
CERT_QUERY_CONTENT_PKCS7_UNSIGNED = 9
CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED = 10
CERT_QUERY_CONTENT_PKCS10 = 11
CERT_QUERY_CONTENT_PFX = 12
CERT_QUERY_CONTENT_CERT_PAIR = 13
CERT_QUERY_CONTENT_PFX_AND_LOAD = 14
CERT_QUERY_CONTENT_FLAG_CERT = (1 << CERT_QUERY_CONTENT_CERT)
CERT_QUERY_CONTENT_FLAG_CTL = (1 << CERT_QUERY_CONTENT_CTL)
CERT_QUERY_CONTENT_FLAG_CRL = (1 << CERT_QUERY_CONTENT_CRL)
CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE = (1 << CERT_QUERY_CONTENT_SERIALIZED_STORE)
CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT = (1 << CERT_QUERY_CONTENT_SERIALIZED_CERT)
CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL = (1 << CERT_QUERY_CONTENT_SERIALIZED_CTL)
CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL = (1 << CERT_QUERY_CONTENT_SERIALIZED_CRL)
CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED = (1 << CERT_QUERY_CONTENT_PKCS7_SIGNED)
CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED = (1 << CERT_QUERY_CONTENT_PKCS7_UNSIGNED)
CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED = (1 << CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED)
CERT_QUERY_CONTENT_FLAG_PKCS10 = (1 << CERT_QUERY_CONTENT_PKCS10)
CERT_QUERY_CONTENT_FLAG_PFX = (1 << CERT_QUERY_CONTENT_PFX)
CERT_QUERY_CONTENT_FLAG_CERT_PAIR = (1 << CERT_QUERY_CONTENT_CERT_PAIR)
CERT_QUERY_CONTENT_FLAG_PFX_AND_LOAD = (1 << CERT_QUERY_CONTENT_PFX_AND_LOAD)
CERT_QUERY_CONTENT_FLAG_ALL = (CERT_QUERY_CONTENT_FLAG_CERT | CERT_QUERY_CONTENT_FLAG_CTL | CERT_QUERY_CONTENT_FLAG_CRL | CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE | CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT | CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL | CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL | CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED | CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED | CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED | CERT_QUERY_CONTENT_FLAG_PKCS10 | CERT_QUERY_CONTENT_FLAG_PFX | CERT_QUERY_CONTENT_FLAG_CERT_PAIR)
CERT_QUERY_CONTENT_FLAG_ALL_ISSUER_CERT = (CERT_QUERY_CONTENT_FLAG_CERT | CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE | CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT | CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED | CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED)
/* CryptQueryObject format type flags */
CERT_QUERY_FORMAT_BINARY = 1
CERT_QUERY_FORMAT_BASE64_ENCODED = 2
CERT_QUERY_FORMAT_ASN_ASCII_HEX_ENCODED = 3
CERT_QUERY_FORMAT_FLAG_BINARY = (1 << CERT_QUERY_FORMAT_BINARY)
CERT_QUERY_FORMAT_FLAG_BASE64_ENCODED = (1 << CERT_QUERY_FORMAT_BASE64_ENCODED)
CERT_QUERY_FORMAT_FLAG_ASN_ASCII_HEX_ENCODED = (1 << CERT_QUERY_FORMAT_ASN_ASCII_HEX_ENCODED)
CERT_QUERY_FORMAT_FLAG_ALL = (CERT_QUERY_FORMAT_FLAG_BINARY | CERT_QUERY_FORMAT_FLAG_BASE64_ENCODED | CERT_QUERY_FORMAT_FLAG_ASN_ASCII_HEX_ENCODED)
/* CertGetNameString name types */
CERT_NAME_EMAIL_TYPE = 1
CERT_NAME_RDN_TYPE = 2
CERT_NAME_ATTR_TYPE = 3
CERT_NAME_SIMPLE_DISPLAY_TYPE = 4
CERT_NAME_FRIENDLY_DISPLAY_TYPE = 5
CERT_NAME_DNS_TYPE = 6
CERT_NAME_URL_TYPE = 7
CERT_NAME_UPN_TYPE = 8
/* CertGetNameString flags */
CERT_NAME_ISSUER_FLAG = 0x1
CERT_NAME_DISABLE_IE4_UTF8_FLAG = 0x10000
CERT_NAME_SEARCH_ALL_NAMES_FLAG = 0x2
CERT_NAME_STR_ENABLE_PUNYCODE_FLAG = 0x00200000
/* AuthType values for SSLExtraCertChainPolicyPara struct */
AUTHTYPE_CLIENT = 1
AUTHTYPE_SERVER = 2
/* Checks values for SSLExtraCertChainPolicyPara struct */
SECURITY_FLAG_IGNORE_REVOCATION = 0x00000080
SECURITY_FLAG_IGNORE_UNKNOWN_CA = 0x00000100
SECURITY_FLAG_IGNORE_WRONG_USAGE = 0x00000200
SECURITY_FLAG_IGNORE_CERT_CN_INVALID = 0x00001000
SECURITY_FLAG_IGNORE_CERT_DATE_INVALID = 0x00002000
/* Flags for Crypt[Un]ProtectData */
CRYPTPROTECT_UI_FORBIDDEN = 0x1
CRYPTPROTECT_LOCAL_MACHINE = 0x4
CRYPTPROTECT_CRED_SYNC = 0x8
CRYPTPROTECT_AUDIT = 0x10
CRYPTPROTECT_NO_RECOVERY = 0x20
CRYPTPROTECT_VERIFY_PROTECTION = 0x40
CRYPTPROTECT_CRED_REGENERATE = 0x80
/* Flags for CryptProtectPromptStruct */
CRYPTPROTECT_PROMPT_ON_UNPROTECT = 1
CRYPTPROTECT_PROMPT_ON_PROTECT = 2
CRYPTPROTECT_PROMPT_RESERVED = 4
CRYPTPROTECT_PROMPT_STRONG = 8
CRYPTPROTECT_PROMPT_REQUIRE_STRONG = 16
)
const (
// flags for SetErrorMode
SEM_FAILCRITICALERRORS = 0x0001
SEM_NOALIGNMENTFAULTEXCEPT = 0x0004
SEM_NOGPFAULTERRORBOX = 0x0002
SEM_NOOPENFILEERRORBOX = 0x8000
)
const (
// Priority class.
ABOVE_NORMAL_PRIORITY_CLASS = 0x00008000
BELOW_NORMAL_PRIORITY_CLASS = 0x00004000
HIGH_PRIORITY_CLASS = 0x00000080
IDLE_PRIORITY_CLASS = 0x00000040
NORMAL_PRIORITY_CLASS = 0x00000020
PROCESS_MODE_BACKGROUND_BEGIN = 0x00100000
PROCESS_MODE_BACKGROUND_END = 0x00200000
REALTIME_PRIORITY_CLASS = 0x00000100
)
/* wintrust.h constants for WinVerifyTrustEx */
const (
WTD_UI_ALL = 1
WTD_UI_NONE = 2
WTD_UI_NOBAD = 3
WTD_UI_NOGOOD = 4
WTD_REVOKE_NONE = 0
WTD_REVOKE_WHOLECHAIN = 1
WTD_CHOICE_FILE = 1
WTD_CHOICE_CATALOG = 2
WTD_CHOICE_BLOB = 3
WTD_CHOICE_SIGNER = 4
WTD_CHOICE_CERT = 5
WTD_STATEACTION_IGNORE = 0x00000000
WTD_STATEACTION_VERIFY = 0x00000001
WTD_STATEACTION_CLOSE = 0x00000002
WTD_STATEACTION_AUTO_CACHE = 0x00000003
WTD_STATEACTION_AUTO_CACHE_FLUSH = 0x00000004
WTD_USE_IE4_TRUST_FLAG = 0x1
WTD_NO_IE4_CHAIN_FLAG = 0x2
WTD_NO_POLICY_USAGE_FLAG = 0x4
WTD_REVOCATION_CHECK_NONE = 0x10
WTD_REVOCATION_CHECK_END_CERT = 0x20
WTD_REVOCATION_CHECK_CHAIN = 0x40
WTD_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT = 0x80
WTD_SAFER_FLAG = 0x100
WTD_HASH_ONLY_FLAG = 0x200
WTD_USE_DEFAULT_OSVER_CHECK = 0x400
WTD_LIFETIME_SIGNING_FLAG = 0x800
WTD_CACHE_ONLY_URL_RETRIEVAL = 0x1000
WTD_DISABLE_MD2_MD4 = 0x2000
WTD_MOTW = 0x4000
WTD_UICONTEXT_EXECUTE = 0
WTD_UICONTEXT_INSTALL = 1
)
var (
OID_PKIX_KP_SERVER_AUTH = []byte("1.3.6.1.5.5.7.3.1\x00")
OID_SERVER_GATED_CRYPTO = []byte("1.3.6.1.4.1.311.10.3.3\x00")
OID_SGC_NETSCAPE = []byte("2.16.840.1.113730.4.1\x00")
WINTRUST_ACTION_GENERIC_VERIFY_V2 = GUID{
Data1: 0xaac56b,
Data2: 0xcd44,
Data3: 0x11d0,
Data4: [8]byte{0x8c, 0xc2, 0x0, 0xc0, 0x4f, 0xc2, 0x95, 0xee},
}
)
// Pointer represents a pointer to an arbitrary Windows type.
//
// Pointer-typed fields may point to one of many different types. It's
// up to the caller to provide a pointer to the appropriate type, cast
// to Pointer. The caller must obey the unsafe.Pointer rules while
// doing so.
type Pointer *struct{}
// Invented values to support what package os expects.
type Timeval struct {
Sec int32
Usec int32
}
func (tv *Timeval) Nanoseconds() int64 {
return (int64(tv.Sec)*1e6 + int64(tv.Usec)) * 1e3
}
func NsecToTimeval(nsec int64) (tv Timeval) {
tv.Sec = int32(nsec / 1e9)
tv.Usec = int32(nsec % 1e9 / 1e3)
return
}
type Overlapped struct {
Internal uintptr
InternalHigh uintptr
Offset uint32
OffsetHigh uint32
HEvent Handle
}
type FileNotifyInformation struct {
NextEntryOffset uint32
Action uint32
FileNameLength uint32
FileName uint16
}
type Filetime struct {
LowDateTime uint32
HighDateTime uint32
}
// Nanoseconds returns Filetime ft in nanoseconds
// since Epoch (00:00:00 UTC, January 1, 1970).
func (ft *Filetime) Nanoseconds() int64 {
// 100-nanosecond intervals since January 1, 1601
nsec := int64(ft.HighDateTime)<<32 + int64(ft.LowDateTime)
// change starting time to the Epoch (00:00:00 UTC, January 1, 1970)
nsec -= 116444736000000000
// convert into nanoseconds
nsec *= 100
return nsec
}
func NsecToFiletime(nsec int64) (ft Filetime) {
// convert into 100-nanosecond
nsec /= 100
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | true |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/env_windows.go | vendor/golang.org/x/sys/windows/env_windows.go | // Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Windows environment variables.
package windows
import (
"syscall"
"unsafe"
)
func Getenv(key string) (value string, found bool) {
return syscall.Getenv(key)
}
func Setenv(key, value string) error {
return syscall.Setenv(key, value)
}
func Clearenv() {
syscall.Clearenv()
}
func Environ() []string {
return syscall.Environ()
}
// Returns a default environment associated with the token, rather than the current
// process. If inheritExisting is true, then this environment also inherits the
// environment of the current process.
func (token Token) Environ(inheritExisting bool) (env []string, err error) {
var block *uint16
err = CreateEnvironmentBlock(&block, token, inheritExisting)
if err != nil {
return nil, err
}
defer DestroyEnvironmentBlock(block)
size := unsafe.Sizeof(*block)
for *block != 0 {
// find NUL terminator
end := unsafe.Pointer(block)
for *(*uint16)(end) != 0 {
end = unsafe.Add(end, size)
}
entry := unsafe.Slice(block, (uintptr(end)-uintptr(unsafe.Pointer(block)))/size)
env = append(env, UTF16ToString(entry))
block = (*uint16)(unsafe.Add(end, size))
}
return env, nil
}
func Unsetenv(key string) error {
return syscall.Unsetenv(key)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/types_windows_amd64.go | vendor/golang.org/x/sys/windows/types_windows_amd64.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package windows
type WSAData struct {
Version uint16
HighVersion uint16
MaxSockets uint16
MaxUdpDg uint16
VendorInfo *byte
Description [WSADESCRIPTION_LEN + 1]byte
SystemStatus [WSASYS_STATUS_LEN + 1]byte
}
type Servent struct {
Name *byte
Aliases **byte
Proto *byte
Port uint16
}
type JOBOBJECT_BASIC_LIMIT_INFORMATION struct {
PerProcessUserTimeLimit int64
PerJobUserTimeLimit int64
LimitFlags uint32
MinimumWorkingSetSize uintptr
MaximumWorkingSetSize uintptr
ActiveProcessLimit uint32
Affinity uintptr
PriorityClass uint32
SchedulingClass uint32
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/race.go | vendor/golang.org/x/sys/windows/race.go | // Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build windows && race
package windows
import (
"runtime"
"unsafe"
)
const raceenabled = true
func raceAcquire(addr unsafe.Pointer) {
runtime.RaceAcquire(addr)
}
func raceReleaseMerge(addr unsafe.Pointer) {
runtime.RaceReleaseMerge(addr)
}
func raceReadRange(addr unsafe.Pointer, len int) {
runtime.RaceReadRange(addr, len)
}
func raceWriteRange(addr unsafe.Pointer, len int) {
runtime.RaceWriteRange(addr, len)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/str.go | vendor/golang.org/x/sys/windows/str.go | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build windows
package windows
func itoa(val int) string { // do it here rather than with fmt to avoid dependency
if val < 0 {
return "-" + itoa(-val)
}
var buf [32]byte // big enough for int64
i := len(buf) - 1
for val >= 10 {
buf[i] = byte(val%10 + '0')
i--
val /= 10
}
buf[i] = byte(val + '0')
return string(buf[i:])
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sys/windows/types_windows_arm.go | vendor/golang.org/x/sys/windows/types_windows_arm.go | // Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package windows
type WSAData struct {
Version uint16
HighVersion uint16
Description [WSADESCRIPTION_LEN + 1]byte
SystemStatus [WSASYS_STATUS_LEN + 1]byte
MaxSockets uint16
MaxUdpDg uint16
VendorInfo *byte
}
type Servent struct {
Name *byte
Aliases **byte
Port uint16
Proto *byte
}
type JOBOBJECT_BASIC_LIMIT_INFORMATION struct {
PerProcessUserTimeLimit int64
PerJobUserTimeLimit int64
LimitFlags uint32
MinimumWorkingSetSize uintptr
MaximumWorkingSetSize uintptr
ActiveProcessLimit uint32
Affinity uintptr
PriorityClass uint32
SchedulingClass uint32
_ uint32 // pad to 8 byte boundary
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/golang.org/x/sync/errgroup/errgroup.go | vendor/golang.org/x/sync/errgroup/errgroup.go | // Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package errgroup provides synchronization, error propagation, and Context
// cancellation for groups of goroutines working on subtasks of a common task.
//
// [errgroup.Group] is related to [sync.WaitGroup] but adds handling of tasks
// returning errors.
package errgroup
import (
"context"
"fmt"
"sync"
)
type token struct{}
// A Group is a collection of goroutines working on subtasks that are part of
// the same overall task. A Group should not be reused for different tasks.
//
// A zero Group is valid, has no limit on the number of active goroutines,
// and does not cancel on error.
type Group struct {
cancel func(error)
wg sync.WaitGroup
sem chan token
errOnce sync.Once
err error
}
func (g *Group) done() {
if g.sem != nil {
<-g.sem
}
g.wg.Done()
}
// WithContext returns a new Group and an associated Context derived from ctx.
//
// The derived Context is canceled the first time a function passed to Go
// returns a non-nil error or the first time Wait returns, whichever occurs
// first.
func WithContext(ctx context.Context) (*Group, context.Context) {
ctx, cancel := context.WithCancelCause(ctx)
return &Group{cancel: cancel}, ctx
}
// Wait blocks until all function calls from the Go method have returned, then
// returns the first non-nil error (if any) from them.
func (g *Group) Wait() error {
g.wg.Wait()
if g.cancel != nil {
g.cancel(g.err)
}
return g.err
}
// Go calls the given function in a new goroutine.
//
// The first call to Go must happen before a Wait.
// It blocks until the new goroutine can be added without the number of
// goroutines in the group exceeding the configured limit.
//
// The first goroutine in the group that returns a non-nil error will
// cancel the associated Context, if any. The error will be returned
// by Wait.
func (g *Group) Go(f func() error) {
if g.sem != nil {
g.sem <- token{}
}
g.wg.Add(1)
go func() {
defer g.done()
// It is tempting to propagate panics from f()
// up to the goroutine that calls Wait, but
// it creates more problems than it solves:
// - it delays panics arbitrarily,
// making bugs harder to detect;
// - it turns f's panic stack into a mere value,
// hiding it from crash-monitoring tools;
// - it risks deadlocks that hide the panic entirely,
// if f's panic leaves the program in a state
// that prevents the Wait call from being reached.
// See #53757, #74275, #74304, #74306.
if err := f(); err != nil {
g.errOnce.Do(func() {
g.err = err
if g.cancel != nil {
g.cancel(g.err)
}
})
}
}()
}
// TryGo calls the given function in a new goroutine only if the number of
// active goroutines in the group is currently below the configured limit.
//
// The return value reports whether the goroutine was started.
func (g *Group) TryGo(f func() error) bool {
if g.sem != nil {
select {
case g.sem <- token{}:
// Note: this allows barging iff channels in general allow barging.
default:
return false
}
}
g.wg.Add(1)
go func() {
defer g.done()
if err := f(); err != nil {
g.errOnce.Do(func() {
g.err = err
if g.cancel != nil {
g.cancel(g.err)
}
})
}
}()
return true
}
// SetLimit limits the number of active goroutines in this group to at most n.
// A negative value indicates no limit.
// A limit of zero will prevent any new goroutines from being added.
//
// Any subsequent call to the Go method will block until it can add an active
// goroutine without exceeding the configured limit.
//
// The limit must not be modified while any goroutines in the group are active.
func (g *Group) SetLimit(n int) {
if n < 0 {
g.sem = nil
return
}
if active := len(g.sem); active != 0 {
panic(fmt.Errorf("errgroup: modify limit while %v goroutines in the group are still active", active))
}
g.sem = make(chan token, n)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/dario.cat/mergo/merge.go | vendor/dario.cat/mergo/merge.go | // Copyright 2013 Dario Castañé. All rights reserved.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on src/pkg/reflect/deepequal.go from official
// golang's stdlib.
package mergo
import (
"fmt"
"reflect"
)
func hasMergeableFields(dst reflect.Value) (exported bool) {
for i, n := 0, dst.NumField(); i < n; i++ {
field := dst.Type().Field(i)
if field.Anonymous && dst.Field(i).Kind() == reflect.Struct {
exported = exported || hasMergeableFields(dst.Field(i))
} else if isExportedComponent(&field) {
exported = exported || len(field.PkgPath) == 0
}
}
return
}
func isExportedComponent(field *reflect.StructField) bool {
pkgPath := field.PkgPath
if len(pkgPath) > 0 {
return false
}
c := field.Name[0]
if 'a' <= c && c <= 'z' || c == '_' {
return false
}
return true
}
type Config struct {
Transformers Transformers
Overwrite bool
ShouldNotDereference bool
AppendSlice bool
TypeCheck bool
overwriteWithEmptyValue bool
overwriteSliceWithEmptyValue bool
sliceDeepCopy bool
debug bool
}
type Transformers interface {
Transformer(reflect.Type) func(dst, src reflect.Value) error
}
// Traverses recursively both values, assigning src's fields values to dst.
// The map argument tracks comparisons that have already been seen, which allows
// short circuiting on recursive types.
func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (err error) {
overwrite := config.Overwrite
typeCheck := config.TypeCheck
overwriteWithEmptySrc := config.overwriteWithEmptyValue
overwriteSliceWithEmptySrc := config.overwriteSliceWithEmptyValue
sliceDeepCopy := config.sliceDeepCopy
if !src.IsValid() {
return
}
if dst.CanAddr() {
addr := dst.UnsafeAddr()
h := 17 * addr
seen := visited[h]
typ := dst.Type()
for p := seen; p != nil; p = p.next {
if p.ptr == addr && p.typ == typ {
return nil
}
}
// Remember, remember...
visited[h] = &visit{typ, seen, addr}
}
if config.Transformers != nil && !isReflectNil(dst) && dst.IsValid() {
if fn := config.Transformers.Transformer(dst.Type()); fn != nil {
err = fn(dst, src)
return
}
}
switch dst.Kind() {
case reflect.Struct:
if hasMergeableFields(dst) {
for i, n := 0, dst.NumField(); i < n; i++ {
if err = deepMerge(dst.Field(i), src.Field(i), visited, depth+1, config); err != nil {
return
}
}
} else {
if dst.CanSet() && (isReflectNil(dst) || overwrite) && (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc) {
dst.Set(src)
}
}
case reflect.Map:
if dst.IsNil() && !src.IsNil() {
if dst.CanSet() {
dst.Set(reflect.MakeMap(dst.Type()))
} else {
dst = src
return
}
}
if src.Kind() != reflect.Map {
if overwrite && dst.CanSet() {
dst.Set(src)
}
return
}
for _, key := range src.MapKeys() {
srcElement := src.MapIndex(key)
if !srcElement.IsValid() {
continue
}
dstElement := dst.MapIndex(key)
switch srcElement.Kind() {
case reflect.Chan, reflect.Func, reflect.Map, reflect.Interface, reflect.Slice:
if srcElement.IsNil() {
if overwrite {
dst.SetMapIndex(key, srcElement)
}
continue
}
fallthrough
default:
if !srcElement.CanInterface() {
continue
}
switch reflect.TypeOf(srcElement.Interface()).Kind() {
case reflect.Struct:
fallthrough
case reflect.Ptr:
fallthrough
case reflect.Map:
srcMapElm := srcElement
dstMapElm := dstElement
if srcMapElm.CanInterface() {
srcMapElm = reflect.ValueOf(srcMapElm.Interface())
if dstMapElm.IsValid() {
dstMapElm = reflect.ValueOf(dstMapElm.Interface())
}
}
if err = deepMerge(dstMapElm, srcMapElm, visited, depth+1, config); err != nil {
return
}
case reflect.Slice:
srcSlice := reflect.ValueOf(srcElement.Interface())
var dstSlice reflect.Value
if !dstElement.IsValid() || dstElement.IsNil() {
dstSlice = reflect.MakeSlice(srcSlice.Type(), 0, srcSlice.Len())
} else {
dstSlice = reflect.ValueOf(dstElement.Interface())
}
if (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) && !config.AppendSlice && !sliceDeepCopy {
if typeCheck && srcSlice.Type() != dstSlice.Type() {
return fmt.Errorf("cannot override two slices with different type (%s, %s)", srcSlice.Type(), dstSlice.Type())
}
dstSlice = srcSlice
} else if config.AppendSlice {
if srcSlice.Type() != dstSlice.Type() {
return fmt.Errorf("cannot append two slices with different type (%s, %s)", srcSlice.Type(), dstSlice.Type())
}
dstSlice = reflect.AppendSlice(dstSlice, srcSlice)
} else if sliceDeepCopy {
i := 0
for ; i < srcSlice.Len() && i < dstSlice.Len(); i++ {
srcElement := srcSlice.Index(i)
dstElement := dstSlice.Index(i)
if srcElement.CanInterface() {
srcElement = reflect.ValueOf(srcElement.Interface())
}
if dstElement.CanInterface() {
dstElement = reflect.ValueOf(dstElement.Interface())
}
if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil {
return
}
}
}
dst.SetMapIndex(key, dstSlice)
}
}
if dstElement.IsValid() && !isEmptyValue(dstElement, !config.ShouldNotDereference) {
if reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Slice {
continue
}
if reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Map && reflect.TypeOf(dstElement.Interface()).Kind() == reflect.Map {
continue
}
}
if srcElement.IsValid() && ((srcElement.Kind() != reflect.Ptr && overwrite) || !dstElement.IsValid() || isEmptyValue(dstElement, !config.ShouldNotDereference)) {
if dst.IsNil() {
dst.Set(reflect.MakeMap(dst.Type()))
}
dst.SetMapIndex(key, srcElement)
}
}
// Ensure that all keys in dst are deleted if they are not in src.
if overwriteWithEmptySrc {
for _, key := range dst.MapKeys() {
srcElement := src.MapIndex(key)
if !srcElement.IsValid() {
dst.SetMapIndex(key, reflect.Value{})
}
}
}
case reflect.Slice:
if !dst.CanSet() {
break
}
if (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) && !config.AppendSlice && !sliceDeepCopy {
dst.Set(src)
} else if config.AppendSlice {
if src.Type() != dst.Type() {
return fmt.Errorf("cannot append two slice with different type (%s, %s)", src.Type(), dst.Type())
}
dst.Set(reflect.AppendSlice(dst, src))
} else if sliceDeepCopy {
for i := 0; i < src.Len() && i < dst.Len(); i++ {
srcElement := src.Index(i)
dstElement := dst.Index(i)
if srcElement.CanInterface() {
srcElement = reflect.ValueOf(srcElement.Interface())
}
if dstElement.CanInterface() {
dstElement = reflect.ValueOf(dstElement.Interface())
}
if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil {
return
}
}
}
case reflect.Ptr:
fallthrough
case reflect.Interface:
if isReflectNil(src) {
if overwriteWithEmptySrc && dst.CanSet() && src.Type().AssignableTo(dst.Type()) {
dst.Set(src)
}
break
}
if src.Kind() != reflect.Interface {
if dst.IsNil() || (src.Kind() != reflect.Ptr && overwrite) {
if dst.CanSet() && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) {
dst.Set(src)
}
} else if src.Kind() == reflect.Ptr {
if !config.ShouldNotDereference {
if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil {
return
}
} else if src.Elem().Kind() != reflect.Struct {
if overwriteWithEmptySrc || (overwrite && !src.IsNil()) || dst.IsNil() {
dst.Set(src)
}
}
} else if dst.Elem().Type() == src.Type() {
if err = deepMerge(dst.Elem(), src, visited, depth+1, config); err != nil {
return
}
} else {
return ErrDifferentArgumentsTypes
}
break
}
if dst.IsNil() || overwrite {
if dst.CanSet() && (overwrite || isEmptyValue(dst, !config.ShouldNotDereference)) {
dst.Set(src)
}
break
}
if dst.Elem().Kind() == src.Elem().Kind() {
if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil {
return
}
break
}
default:
mustSet := (isEmptyValue(dst, !config.ShouldNotDereference) || overwrite) && (!isEmptyValue(src, !config.ShouldNotDereference) || overwriteWithEmptySrc)
if mustSet {
if dst.CanSet() {
dst.Set(src)
} else {
dst = src
}
}
}
return
}
// Merge will fill any empty for value type attributes on the dst struct using corresponding
// src attributes if they themselves are not empty. dst and src must be valid same-type structs
// and dst must be a pointer to struct.
// It won't merge unexported (private) fields and will do recursively any exported field.
func Merge(dst, src interface{}, opts ...func(*Config)) error {
return merge(dst, src, opts...)
}
// MergeWithOverwrite will do the same as Merge except that non-empty dst attributes will be overridden by
// non-empty src attribute values.
// Deprecated: use Merge(…) with WithOverride
func MergeWithOverwrite(dst, src interface{}, opts ...func(*Config)) error {
return merge(dst, src, append(opts, WithOverride)...)
}
// WithTransformers adds transformers to merge, allowing to customize the merging of some types.
func WithTransformers(transformers Transformers) func(*Config) {
return func(config *Config) {
config.Transformers = transformers
}
}
// WithOverride will make merge override non-empty dst attributes with non-empty src attributes values.
func WithOverride(config *Config) {
config.Overwrite = true
}
// WithOverwriteWithEmptyValue will make merge override non empty dst attributes with empty src attributes values.
func WithOverwriteWithEmptyValue(config *Config) {
config.Overwrite = true
config.overwriteWithEmptyValue = true
}
// WithOverrideEmptySlice will make merge override empty dst slice with empty src slice.
func WithOverrideEmptySlice(config *Config) {
config.overwriteSliceWithEmptyValue = true
}
// WithoutDereference prevents dereferencing pointers when evaluating whether they are empty
// (i.e. a non-nil pointer is never considered empty).
func WithoutDereference(config *Config) {
config.ShouldNotDereference = true
}
// WithAppendSlice will make merge append slices instead of overwriting it.
func WithAppendSlice(config *Config) {
config.AppendSlice = true
}
// WithTypeCheck will make merge check types while overwriting it (must be used with WithOverride).
func WithTypeCheck(config *Config) {
config.TypeCheck = true
}
// WithSliceDeepCopy will merge slice element one by one with Overwrite flag.
func WithSliceDeepCopy(config *Config) {
config.sliceDeepCopy = true
config.Overwrite = true
}
func merge(dst, src interface{}, opts ...func(*Config)) error {
if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr {
return ErrNonPointerArgument
}
var (
vDst, vSrc reflect.Value
err error
)
config := &Config{}
for _, opt := range opts {
opt(config)
}
if vDst, vSrc, err = resolveValues(dst, src); err != nil {
return err
}
if vDst.Type() != vSrc.Type() {
return ErrDifferentArgumentsTypes
}
return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config)
}
// IsReflectNil is the reflect value provided nil
func isReflectNil(v reflect.Value) bool {
k := v.Kind()
switch k {
case reflect.Interface, reflect.Slice, reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr:
// Both interface and slice are nil if first word is 0.
// Both are always bigger than a word; assume flagIndir.
return v.IsNil()
default:
return false
}
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/dario.cat/mergo/map.go | vendor/dario.cat/mergo/map.go | // Copyright 2014 Dario Castañé. All rights reserved.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on src/pkg/reflect/deepequal.go from official
// golang's stdlib.
package mergo
import (
"fmt"
"reflect"
"unicode"
"unicode/utf8"
)
func changeInitialCase(s string, mapper func(rune) rune) string {
if s == "" {
return s
}
r, n := utf8.DecodeRuneInString(s)
return string(mapper(r)) + s[n:]
}
func isExported(field reflect.StructField) bool {
r, _ := utf8.DecodeRuneInString(field.Name)
return r >= 'A' && r <= 'Z'
}
// Traverses recursively both values, assigning src's fields values to dst.
// The map argument tracks comparisons that have already been seen, which allows
// short circuiting on recursive types.
func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (err error) {
overwrite := config.Overwrite
if dst.CanAddr() {
addr := dst.UnsafeAddr()
h := 17 * addr
seen := visited[h]
typ := dst.Type()
for p := seen; p != nil; p = p.next {
if p.ptr == addr && p.typ == typ {
return nil
}
}
// Remember, remember...
visited[h] = &visit{typ, seen, addr}
}
zeroValue := reflect.Value{}
switch dst.Kind() {
case reflect.Map:
dstMap := dst.Interface().(map[string]interface{})
for i, n := 0, src.NumField(); i < n; i++ {
srcType := src.Type()
field := srcType.Field(i)
if !isExported(field) {
continue
}
fieldName := field.Name
fieldName = changeInitialCase(fieldName, unicode.ToLower)
if _, ok := dstMap[fieldName]; !ok || (!isEmptyValue(reflect.ValueOf(src.Field(i).Interface()), !config.ShouldNotDereference) && overwrite) || config.overwriteWithEmptyValue {
dstMap[fieldName] = src.Field(i).Interface()
}
}
case reflect.Ptr:
if dst.IsNil() {
v := reflect.New(dst.Type().Elem())
dst.Set(v)
}
dst = dst.Elem()
fallthrough
case reflect.Struct:
srcMap := src.Interface().(map[string]interface{})
for key := range srcMap {
config.overwriteWithEmptyValue = true
srcValue := srcMap[key]
fieldName := changeInitialCase(key, unicode.ToUpper)
dstElement := dst.FieldByName(fieldName)
if dstElement == zeroValue {
// We discard it because the field doesn't exist.
continue
}
srcElement := reflect.ValueOf(srcValue)
dstKind := dstElement.Kind()
srcKind := srcElement.Kind()
if srcKind == reflect.Ptr && dstKind != reflect.Ptr {
srcElement = srcElement.Elem()
srcKind = reflect.TypeOf(srcElement.Interface()).Kind()
} else if dstKind == reflect.Ptr {
// Can this work? I guess it can't.
if srcKind != reflect.Ptr && srcElement.CanAddr() {
srcPtr := srcElement.Addr()
srcElement = reflect.ValueOf(srcPtr)
srcKind = reflect.Ptr
}
}
if !srcElement.IsValid() {
continue
}
if srcKind == dstKind {
if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil {
return
}
} else if dstKind == reflect.Interface && dstElement.Kind() == reflect.Interface {
if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil {
return
}
} else if srcKind == reflect.Map {
if err = deepMap(dstElement, srcElement, visited, depth+1, config); err != nil {
return
}
} else {
return fmt.Errorf("type mismatch on %s field: found %v, expected %v", fieldName, srcKind, dstKind)
}
}
}
return
}
// Map sets fields' values in dst from src.
// src can be a map with string keys or a struct. dst must be the opposite:
// if src is a map, dst must be a valid pointer to struct. If src is a struct,
// dst must be map[string]interface{}.
// It won't merge unexported (private) fields and will do recursively
// any exported field.
// If dst is a map, keys will be src fields' names in lower camel case.
// Missing key in src that doesn't match a field in dst will be skipped. This
// doesn't apply if dst is a map.
// This is separated method from Merge because it is cleaner and it keeps sane
// semantics: merging equal types, mapping different (restricted) types.
func Map(dst, src interface{}, opts ...func(*Config)) error {
return _map(dst, src, opts...)
}
// MapWithOverwrite will do the same as Map except that non-empty dst attributes will be overridden by
// non-empty src attribute values.
// Deprecated: Use Map(…) with WithOverride
func MapWithOverwrite(dst, src interface{}, opts ...func(*Config)) error {
return _map(dst, src, append(opts, WithOverride)...)
}
func _map(dst, src interface{}, opts ...func(*Config)) error {
if dst != nil && reflect.ValueOf(dst).Kind() != reflect.Ptr {
return ErrNonPointerArgument
}
var (
vDst, vSrc reflect.Value
err error
)
config := &Config{}
for _, opt := range opts {
opt(config)
}
if vDst, vSrc, err = resolveValues(dst, src); err != nil {
return err
}
// To be friction-less, we redirect equal-type arguments
// to deepMerge. Only because arguments can be anything.
if vSrc.Kind() == vDst.Kind() {
return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config)
}
switch vSrc.Kind() {
case reflect.Struct:
if vDst.Kind() != reflect.Map {
return ErrExpectedMapAsDestination
}
case reflect.Map:
if vDst.Kind() != reflect.Struct {
return ErrExpectedStructAsDestination
}
default:
return ErrNotSupported
}
return deepMap(vDst, vSrc, make(map[uintptr]*visit), 0, config)
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/dario.cat/mergo/mergo.go | vendor/dario.cat/mergo/mergo.go | // Copyright 2013 Dario Castañé. All rights reserved.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Based on src/pkg/reflect/deepequal.go from official
// golang's stdlib.
package mergo
import (
"errors"
"reflect"
)
// Errors reported by Mergo when it finds invalid arguments.
var (
ErrNilArguments = errors.New("src and dst must not be nil")
ErrDifferentArgumentsTypes = errors.New("src and dst must be of same type")
ErrNotSupported = errors.New("only structs, maps, and slices are supported")
ErrExpectedMapAsDestination = errors.New("dst was expected to be a map")
ErrExpectedStructAsDestination = errors.New("dst was expected to be a struct")
ErrNonPointerArgument = errors.New("dst must be a pointer")
)
// During deepMerge, must keep track of checks that are
// in progress. The comparison algorithm assumes that all
// checks in progress are true when it reencounters them.
// Visited are stored in a map indexed by 17 * a1 + a2;
type visit struct {
typ reflect.Type
next *visit
ptr uintptr
}
// From src/pkg/encoding/json/encode.go.
func isEmptyValue(v reflect.Value, shouldDereference bool) bool {
switch v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Interface, reflect.Ptr:
if v.IsNil() {
return true
}
if shouldDereference {
return isEmptyValue(v.Elem(), shouldDereference)
}
return false
case reflect.Func:
return v.IsNil()
case reflect.Invalid:
return true
}
return false
}
func resolveValues(dst, src interface{}) (vDst, vSrc reflect.Value, err error) {
if dst == nil || src == nil {
err = ErrNilArguments
return
}
vDst = reflect.ValueOf(dst).Elem()
if vDst.Kind() != reflect.Struct && vDst.Kind() != reflect.Map && vDst.Kind() != reflect.Slice {
err = ErrNotSupported
return
}
vSrc = reflect.ValueOf(src)
// We check if vSrc is a pointer to dereference it.
if vSrc.Kind() == reflect.Ptr {
vSrc = vSrc.Elem()
}
return
}
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
jesseduffield/lazygit | https://github.com/jesseduffield/lazygit/blob/80dd695d7a8d32714603f5a6307f26f589802b1d/vendor/dario.cat/mergo/doc.go | vendor/dario.cat/mergo/doc.go | // Copyright 2013 Dario Castañé. All rights reserved.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements.
Mergo merges same-type structs and maps by setting default values in zero-value fields. Mergo won't merge unexported (private) fields. It will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection).
# Status
It is ready for production use. It is used in several projects by Docker, Google, The Linux Foundation, VMWare, Shopify, etc.
# Important notes
1.0.0
In 1.0.0 Mergo moves to a vanity URL `dario.cat/mergo`.
0.3.9
Please keep in mind that a problematic PR broke 0.3.9. We reverted it in 0.3.10. We consider 0.3.10 as stable but not bug-free. . Also, this version adds suppot for go modules.
Keep in mind that in 0.3.2, Mergo changed Merge() and Map() signatures to support transformers. We added an optional/variadic argument so that it won't break the existing code.
If you were using Mergo before April 6th, 2015, please check your project works as intended after updating your local copy with go get -u dario.cat/mergo. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause in existing projects after the change (release 0.2.0).
# Install
Do your usual installation procedure:
go get dario.cat/mergo
// use in your .go code
import (
"dario.cat/mergo"
)
# Usage
You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. It won't merge empty structs value as they are zero values too. Also, maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection).
if err := mergo.Merge(&dst, src); err != nil {
// ...
}
Also, you can merge overwriting values using the transformer WithOverride.
if err := mergo.Merge(&dst, src, mergo.WithOverride); err != nil {
// ...
}
Additionally, you can map a map[string]interface{} to a struct (and otherwise, from struct to map), following the same restrictions as in Merge(). Keys are capitalized to find each corresponding exported field.
if err := mergo.Map(&dst, srcMap); err != nil {
// ...
}
Warning: if you map a struct to map, it won't do it recursively. Don't expect Mergo to map struct members of your struct as map[string]interface{}. They will be just assigned as values.
Here is a nice example:
package main
import (
"fmt"
"dario.cat/mergo"
)
type Foo struct {
A string
B int64
}
func main() {
src := Foo{
A: "one",
B: 2,
}
dest := Foo{
A: "two",
}
mergo.Merge(&dest, src)
fmt.Println(dest)
// Will print
// {two 2}
}
# Transformers
Transformers allow to merge specific types differently than in the default behavior. In other words, now you can customize how some types are merged. For example, time.Time is a struct; it doesn't have zero value but IsZero can return true because it has fields with zero value. How can we merge a non-zero time.Time?
package main
import (
"fmt"
"dario.cat/mergo"
"reflect"
"time"
)
type timeTransformer struct {
}
func (t timeTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error {
if typ == reflect.TypeOf(time.Time{}) {
return func(dst, src reflect.Value) error {
if dst.CanSet() {
isZero := dst.MethodByName("IsZero")
result := isZero.Call([]reflect.Value{})
if result[0].Bool() {
dst.Set(src)
}
}
return nil
}
}
return nil
}
type Snapshot struct {
Time time.Time
// ...
}
func main() {
src := Snapshot{time.Now()}
dest := Snapshot{}
mergo.Merge(&dest, src, mergo.WithTransformers(timeTransformer{}))
fmt.Println(dest)
// Will print
// { 2018-01-12 01:15:00 +0000 UTC m=+0.000000001 }
}
# Contact me
If I can help you, you have an idea or you are using Mergo in your projects, don't hesitate to drop me a line (or a pull request): https://twitter.com/im_dario
# About
Written by Dario Castañé: https://da.rio.hn
# License
BSD 3-Clause license, as Go language.
*/
package mergo
| go | MIT | 80dd695d7a8d32714603f5a6307f26f589802b1d | 2026-01-07T08:35:43.445894Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/mocks.go | mocks.go | package core
//go:generate env GOBIN=$PWD go install -v github.com/golang/mock/mockgen@latest
//go:generate ./mockgen -package mocks -destination testing/mocks/io.go -mock_names Reader=Reader,Writer=Writer io Reader,Writer
//go:generate ./mockgen -package mocks -destination testing/mocks/log.go -mock_names Handler=LogHandler github.com/v2fly/v2ray-core/v5/common/log Handler
//go:generate ./mockgen -package mocks -destination testing/mocks/mux.go -mock_names ClientWorkerFactory=MuxClientWorkerFactory github.com/v2fly/v2ray-core/v5/common/mux ClientWorkerFactory
//go:generate ./mockgen -package mocks -destination testing/mocks/dns.go -mock_names Client=DNSClient github.com/v2fly/v2ray-core/v5/features/dns Client
//go:generate ./mockgen -package mocks -destination testing/mocks/outbound.go -mock_names Manager=OutboundManager,HandlerSelector=OutboundHandlerSelector github.com/v2fly/v2ray-core/v5/features/outbound Manager,HandlerSelector
//go:generate ./mockgen -package mocks -destination testing/mocks/proxy.go -mock_names Inbound=ProxyInbound,Outbound=ProxyOutbound github.com/v2fly/v2ray-core/v5/proxy Inbound,Outbound
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/errors.generated.go | errors.generated.go | package core
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/annotations.go | annotations.go | package core
// Annotation is a concept in V2Ray. This struct is only for documentation. It is not used anywhere.
// Annotations begin with "v2ray:" in comment, as metadata of functions or types.
type Annotation struct {
// API is for types or functions that can be used in other libs. Possible values are:
//
// * v2ray:api:beta for types or functions that are ready for use, but maybe changed in the future.
// * v2ray:api:stable for types or functions with guarantee of backward compatibility.
// * v2ray:api:deprecated for types or functions that should not be used anymore.
//
// Types or functions without api annotation should not be used externally.
API string
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/proto.go | proto.go | package core
//go:generate go install -v google.golang.org/protobuf/cmd/protoc-gen-go@latest
//go:generate go install -v google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
//go:generate go run ./infra/vprotogen/
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/context_test.go | context_test.go | package core_test
import (
"context"
"testing"
_ "unsafe"
. "github.com/v2fly/v2ray-core/v5"
)
func TestFromContextPanic(t *testing.T) {
defer func() {
r := recover()
if r == nil {
t.Error("expect panic, but nil")
}
}()
MustFromContext(context.Background())
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/config.go | config.go | package core
import (
"fmt"
"io"
"log"
"os"
"path/filepath"
"reflect"
"strings"
"google.golang.org/protobuf/proto"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/cmdarg"
)
const (
// FormatAuto represents all available formats by auto selecting
FormatAuto = "auto"
// FormatJSON represents json format
FormatJSON = "json"
// FormatTOML represents toml format
FormatTOML = "toml"
// FormatYAML represents yaml format
FormatYAML = "yaml"
// FormatProtobuf represents protobuf format
FormatProtobuf = "protobuf"
// FormatProtobufShort is the short of FormatProtobuf
FormatProtobufShort = "pb"
)
// ConfigFormat is a configurable format of V2Ray config file.
type ConfigFormat struct {
Name []string
Extension []string
Loader ConfigLoader
}
// ConfigLoader is a utility to load V2Ray config from external source.
type ConfigLoader func(input interface{}) (*Config, error)
var (
configLoaders = make([]*ConfigFormat, 0)
configLoaderByName = make(map[string]*ConfigFormat)
configLoaderByExt = make(map[string]*ConfigFormat)
)
// RegisterConfigLoader add a new ConfigLoader.
func RegisterConfigLoader(format *ConfigFormat) error {
for _, name := range format.Name {
if _, found := configLoaderByName[name]; found {
return newError(name, " already registered.")
}
configLoaderByName[name] = format
}
for _, ext := range format.Extension {
lext := strings.ToLower(ext)
if f, found := configLoaderByExt[lext]; found {
return newError(ext, " already registered to ", f.Name)
}
configLoaderByExt[lext] = format
}
configLoaders = append(configLoaders, format)
return nil
}
func getExtension(filename string) string {
ext := filepath.Ext(filename)
return strings.ToLower(ext)
}
// GetLoaderExtensions get config loader extensions.
func GetLoaderExtensions(formatName string) ([]string, error) {
if formatName == FormatAuto {
return GetAllExtensions(), nil
}
if f, found := configLoaderByName[formatName]; found {
return f.Extension, nil
}
return nil, newError("config loader not found: ", formatName).AtWarning()
}
// GetAllExtensions get all extensions supported
func GetAllExtensions() []string {
extensions := make([]string, 0)
for _, f := range configLoaderByName {
extensions = append(extensions, f.Extension...)
}
return extensions
}
// LoadConfig loads multiple config with given format from given source.
// input accepts:
// * string of a single filename/url(s) to open to read
// * []string slice of multiple filename/url(s) to open to read
// * io.Reader that reads a config content (the original way)
func LoadConfig(formatName string, input interface{}) (*Config, error) {
cnt := getInputCount(input)
if cnt == 0 {
log.Println("Using config from STDIN")
input = os.Stdin
cnt = 1
}
if formatName == FormatAuto && cnt == 1 {
// This ensures only to call auto loader for multiple files,
// so that it can only care about merging scenarios
return loadSingleConfigAutoFormat(input)
}
// if input is a slice with single element, extract it
// so that unmergeable loaders don't need to deal with
// slices
s := reflect.Indirect(reflect.ValueOf(input))
k := s.Kind()
if (k == reflect.Slice || k == reflect.Array) && s.Len() == 1 {
value := reflect.Indirect(s.Index(0))
if value.Kind() == reflect.String {
// string type alias
input = fmt.Sprint(value.Interface())
} else {
input = value.Interface()
}
}
f, found := configLoaderByName[formatName]
if !found {
return nil, newError("config loader not found: ", formatName).AtWarning()
}
return f.Loader(input)
}
// loadSingleConfigAutoFormat loads a single config with from given source.
// input accepts:
// * string of a single filename/url(s) to open to read
// * io.Reader that reads a config content (the original way)
func loadSingleConfigAutoFormat(input interface{}) (*Config, error) {
switch v := input.(type) {
case cmdarg.Arg:
return loadSingleConfigAutoFormatFromFile(v.String())
case string:
return loadSingleConfigByTryingAllLoaders(v)
case io.Reader:
data, err := buf.ReadAllToBytes(v)
if err != nil {
return nil, err
}
return loadSingleConfigByTryingAllLoaders(data)
default:
return loadSingleConfigByTryingAllLoaders(v)
}
}
func loadSingleConfigAutoFormatFromFile(file string) (*Config, error) {
extension := getExtension(file)
if extension != "" {
lowerName := strings.ToLower(extension)
if f, found := configLoaderByExt[lowerName]; found {
return f.Loader(file)
}
return nil, newError("config loader not found for: ", extension).AtWarning()
}
return loadSingleConfigByTryingAllLoaders(file)
}
func loadSingleConfigByTryingAllLoaders(input interface{}) (*Config, error) {
var errorReasons strings.Builder
for _, f := range configLoaders {
if f.Name[0] == FormatAuto {
continue
}
c, err := f.Loader(input)
if err == nil {
return c, nil
}
errorReasons.WriteString(fmt.Sprintf("unable to parse as %v:%v;", f.Name[0], err.Error()))
}
return nil, newError("tried all loaders but failed when attempting to parse: ", input, ";", errorReasons.String()).AtWarning()
}
func getInputCount(input interface{}) int {
s := reflect.Indirect(reflect.ValueOf(input))
k := s.Kind()
if k == reflect.Slice || k == reflect.Array {
return s.Len()
}
return 1
}
func loadProtobufConfig(data []byte) (*Config, error) {
config := new(Config)
if err := proto.Unmarshal(data, config); err != nil {
return nil, err
}
return config, nil
}
func init() {
common.Must(RegisterConfigLoader(&ConfigFormat{
Name: []string{FormatProtobuf, FormatProtobufShort},
Extension: []string{".pb"},
Loader: func(input interface{}) (*Config, error) {
switch v := input.(type) {
case string:
r, err := cmdarg.LoadArg(v)
if err != nil {
return nil, err
}
data, err := buf.ReadAllToBytes(r)
if err != nil {
return nil, err
}
return loadProtobufConfig(data)
case io.Reader:
data, err := buf.ReadAllToBytes(v)
if err != nil {
return nil, err
}
return loadProtobufConfig(data)
default:
return nil, newError("unknown type")
}
},
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/v2ray.go | v2ray.go | package core
import (
"context"
"reflect"
sync "sync"
"github.com/v2fly/v2ray-core/v5/common/environment/deferredpersistentstorage"
"github.com/v2fly/v2ray-core/v5/common/environment/filesystemimpl"
"github.com/v2fly/v2ray-core/v5/features/extension/storage"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/environment"
"github.com/v2fly/v2ray-core/v5/common/environment/systemnetworkimpl"
"github.com/v2fly/v2ray-core/v5/common/environment/transientstorageimpl"
"github.com/v2fly/v2ray-core/v5/common/serial"
"github.com/v2fly/v2ray-core/v5/features"
"github.com/v2fly/v2ray-core/v5/features/dns"
"github.com/v2fly/v2ray-core/v5/features/dns/localdns"
"github.com/v2fly/v2ray-core/v5/features/inbound"
"github.com/v2fly/v2ray-core/v5/features/outbound"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/features/routing"
"github.com/v2fly/v2ray-core/v5/features/stats"
)
// Server is an instance of V2Ray. At any time, there must be at most one Server instance running.
type Server interface {
common.Runnable
}
// ServerType returns the type of the server.
func ServerType() interface{} {
return (*Instance)(nil)
}
type resolution struct {
deps []reflect.Type
callback interface{}
}
func getFeature(allFeatures []features.Feature, t reflect.Type) features.Feature {
for _, f := range allFeatures {
if reflect.TypeOf(f.Type()) == t {
return f
}
}
return nil
}
func (r *resolution) resolve(allFeatures []features.Feature) (bool, error) {
var fs []features.Feature
for _, d := range r.deps {
f := getFeature(allFeatures, d)
if f == nil {
return false, nil
}
fs = append(fs, f)
}
callback := reflect.ValueOf(r.callback)
var input []reflect.Value
callbackType := callback.Type()
for i := 0; i < callbackType.NumIn(); i++ {
pt := callbackType.In(i)
for _, f := range fs {
if reflect.TypeOf(f).AssignableTo(pt) {
input = append(input, reflect.ValueOf(f))
break
}
}
}
if len(input) != callbackType.NumIn() {
panic("Can't get all input parameters")
}
var err error
ret := callback.Call(input)
errInterface := reflect.TypeOf((*error)(nil)).Elem()
for i := len(ret) - 1; i >= 0; i-- {
if ret[i].Type() == errInterface {
v := ret[i].Interface()
if v != nil {
err = v.(error)
}
break
}
}
return true, err
}
// Instance combines all functionalities in V2Ray.
type Instance struct {
access sync.Mutex
features []features.Feature
featureResolutions []resolution
running bool
env environment.RootEnvironment
ctx context.Context
}
func AddInboundHandler(server *Instance, config *InboundHandlerConfig) error {
inboundManager := server.GetFeature(inbound.ManagerType()).(inbound.Manager)
proxyEnv := server.env.ProxyEnvironment("i" + config.Tag)
rawHandler, err := CreateObjectWithEnvironment(server, config, proxyEnv)
if err != nil {
return err
}
handler, ok := rawHandler.(inbound.Handler)
if !ok {
return newError("not an InboundHandler")
}
if err := inboundManager.AddHandler(server.ctx, handler); err != nil {
return err
}
return nil
}
func addInboundHandlers(server *Instance, configs []*InboundHandlerConfig) error {
for _, inboundConfig := range configs {
if err := AddInboundHandler(server, inboundConfig); err != nil {
return err
}
}
return nil
}
func AddOutboundHandler(server *Instance, config *OutboundHandlerConfig) error {
outboundManager := server.GetFeature(outbound.ManagerType()).(outbound.Manager)
proxyEnv := server.env.ProxyEnvironment("o" + config.Tag)
rawHandler, err := CreateObjectWithEnvironment(server, config, proxyEnv)
if err != nil {
return err
}
handler, ok := rawHandler.(outbound.Handler)
if !ok {
return newError("not an OutboundHandler")
}
if err := outboundManager.AddHandler(server.ctx, handler); err != nil {
return err
}
return nil
}
func RemoveOutboundHandler(server *Instance, tag string) error {
outboundManager := server.GetFeature(outbound.ManagerType()).(outbound.Manager)
if err := outboundManager.RemoveHandler(server.ctx, tag); err != nil {
return err
}
if err := server.env.DropProxyEnvironment("o" + tag); err != nil {
return err
}
return nil
}
func addOutboundHandlers(server *Instance, configs []*OutboundHandlerConfig) error {
for _, outboundConfig := range configs {
if err := AddOutboundHandler(server, outboundConfig); err != nil {
return err
}
}
return nil
}
// RequireFeatures is a helper function to require features from Instance in context.
// See Instance.RequireFeatures for more information.
func RequireFeatures(ctx context.Context, callback interface{}) error {
v := MustFromContext(ctx)
return v.RequireFeatures(callback)
}
// New returns a new V2Ray instance based on given configuration.
// The instance is not started at this point.
// To ensure V2Ray instance works properly, the config must contain one Dispatcher, one InboundHandlerManager and one OutboundHandlerManager. Other features are optional.
func New(config *Config) (*Instance, error) {
server := &Instance{ctx: context.Background()}
done, err := initInstanceWithConfig(config, server)
if done {
return nil, err
}
return server, nil
}
func NewWithContext(ctx context.Context, config *Config) (*Instance, error) {
server := &Instance{ctx: ctx}
done, err := initInstanceWithConfig(config, server)
if done {
return nil, err
}
return server, nil
}
func initInstanceWithConfig(config *Config, server *Instance) (bool, error) {
if config.Transport != nil {
features.PrintDeprecatedFeatureWarning("global transport settings")
}
if err := config.Transport.Apply(); err != nil {
return true, err
}
defaultNetworkImpl := systemnetworkimpl.NewSystemNetworkDefault()
defaultFilesystemImpl := filesystemimpl.NewDefaultFileSystemDefaultImpl()
deferredPersistentStorageImpl := deferredpersistentstorage.NewDeferredPersistentStorage(server.ctx)
server.env = environment.NewRootEnvImpl(server.ctx,
transientstorageimpl.NewScopedTransientStorageImpl(),
defaultNetworkImpl.Dialer(),
defaultNetworkImpl.Listener(),
defaultFilesystemImpl,
deferredPersistentStorageImpl)
for _, appSettings := range config.App {
settings, err := serial.GetInstanceOf(appSettings)
if err != nil {
return true, err
}
key := appSettings.TypeUrl
appEnv := server.env.AppEnvironment(key)
obj, err := CreateObjectWithEnvironment(server, settings, appEnv)
if err != nil {
return true, err
}
if feature, ok := obj.(features.Feature); ok {
if err := server.AddFeature(feature); err != nil {
return true, err
}
}
}
essentialFeatures := []struct {
Type interface{}
Instance features.Feature
}{
{dns.ClientType(), localdns.New()},
{policy.ManagerType(), policy.DefaultManager{}},
{routing.RouterType(), routing.DefaultRouter{}},
{stats.ManagerType(), stats.NoopManager{}},
}
for _, f := range essentialFeatures {
if server.GetFeature(f.Type) == nil {
if err := server.AddFeature(f.Instance); err != nil {
return true, err
}
}
}
if server.featureResolutions != nil {
return true, newError("not all dependency are resolved.")
}
if persistentStorageService := server.GetFeature(storage.ScopedPersistentStorageServiceType); persistentStorageService != nil {
deferredPersistentStorageImpl.ProvideInner(server.ctx, persistentStorageService.(storage.ScopedPersistentStorage))
} else {
deferredPersistentStorageImpl.ProvideInner(server.ctx, nil)
}
if err := addInboundHandlers(server, config.Inbound); err != nil {
return true, err
}
if err := addOutboundHandlers(server, config.Outbound); err != nil {
return true, err
}
return false, nil
}
// Type implements common.HasType.
func (s *Instance) Type() interface{} {
return ServerType()
}
// Close shutdown the V2Ray instance.
func (s *Instance) Close() error {
s.access.Lock()
defer s.access.Unlock()
s.running = false
var errors []interface{}
for _, f := range s.features {
if err := f.Close(); err != nil {
errors = append(errors, err)
}
}
if len(errors) > 0 {
return newError("failed to close all features").Base(newError(serial.Concat(errors...)))
}
return nil
}
// RequireFeatures registers a callback, which will be called when all dependent features are registered.
// The callback must be a func(). All its parameters must be features.Feature.
func (s *Instance) RequireFeatures(callback interface{}) error {
callbackType := reflect.TypeOf(callback)
if callbackType.Kind() != reflect.Func {
panic("not a function")
}
var featureTypes []reflect.Type
for i := 0; i < callbackType.NumIn(); i++ {
featureTypes = append(featureTypes, reflect.PtrTo(callbackType.In(i)))
}
r := resolution{
deps: featureTypes,
callback: callback,
}
if finished, err := r.resolve(s.features); finished {
return err
}
s.featureResolutions = append(s.featureResolutions, r)
return nil
}
// AddFeature registers a feature into current Instance.
func (s *Instance) AddFeature(feature features.Feature) error {
s.features = append(s.features, feature)
if s.running {
if err := feature.Start(); err != nil {
newError("failed to start feature").Base(err).WriteToLog()
}
return nil
}
if s.featureResolutions == nil {
return nil
}
var pendingResolutions []resolution
for _, r := range s.featureResolutions {
finished, err := r.resolve(s.features)
if finished && err != nil {
return err
}
if !finished {
pendingResolutions = append(pendingResolutions, r)
}
}
if len(pendingResolutions) == 0 {
s.featureResolutions = nil
} else if len(pendingResolutions) < len(s.featureResolutions) {
s.featureResolutions = pendingResolutions
}
return nil
}
// GetFeature returns a feature of the given type, or nil if such feature is not registered.
func (s *Instance) GetFeature(featureType interface{}) features.Feature {
return getFeature(s.features, reflect.TypeOf(featureType))
}
// Start starts the V2Ray instance, including all registered features. When Start returns error, the state of the instance is unknown.
// A V2Ray instance can be started only once. Upon closing, the instance is not guaranteed to start again.
//
// v2ray:api:stable
func (s *Instance) Start() error {
s.access.Lock()
defer s.access.Unlock()
s.running = true
for _, f := range s.features {
if err := f.Start(); err != nil {
return err
}
}
newError("V2Ray ", Version(), " started").AtWarning().WriteToLog()
return nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/format.go | format.go | package core
//go:generate go install -v github.com/daixiang0/gci@latest
//go:generate go run ./infra/vformat/
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/v2ray_test.go | v2ray_test.go | package core_test
import (
"testing"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/anypb"
. "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/dispatcher"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/serial"
"github.com/v2fly/v2ray-core/v5/common/uuid"
"github.com/v2fly/v2ray-core/v5/features/dns"
"github.com/v2fly/v2ray-core/v5/features/dns/localdns"
_ "github.com/v2fly/v2ray-core/v5/main/distro/all"
"github.com/v2fly/v2ray-core/v5/proxy/dokodemo"
"github.com/v2fly/v2ray-core/v5/proxy/vmess"
"github.com/v2fly/v2ray-core/v5/proxy/vmess/outbound"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
)
func TestV2RayDependency(t *testing.T) {
instance := new(Instance)
wait := make(chan bool, 1)
instance.RequireFeatures(func(d dns.Client) {
if d == nil {
t.Error("expected dns client fulfilled, but actually nil")
}
wait <- true
})
instance.AddFeature(localdns.New())
<-wait
}
func TestV2RayClose(t *testing.T) {
port := tcp.PickPort()
userID := uuid.New()
config := &Config{
App: []*anypb.Any{
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.InboundConfig{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
},
Inbound: []*InboundHandlerConfig{
{
ReceiverSettings: serial.ToTypedMessage(&proxyman.ReceiverConfig{
PortRange: net.SinglePortRange(port),
Listen: net.NewIPOrDomain(net.LocalHostIP),
}),
ProxySettings: serial.ToTypedMessage(&dokodemo.Config{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(0),
NetworkList: &net.NetworkList{
Network: []net.Network{net.Network_TCP, net.Network_UDP},
},
}),
},
},
Outbound: []*OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&outbound.Config{
Receiver: []*protocol.ServerEndpoint{
{
Address: net.NewIPOrDomain(net.LocalHostIP),
Port: uint32(0),
User: []*protocol.User{
{
Account: serial.ToTypedMessage(&vmess.Account{
Id: userID.String(),
}),
},
},
},
},
}),
},
},
}
cfgBytes, err := proto.Marshal(config)
common.Must(err)
server, err := StartInstance(FormatProtobuf, cfgBytes)
common.Must(err)
server.Close()
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/context.go | context.go | package core
import (
"context"
)
// V2rayKey is the key type of Instance in Context, exported for test.
type v2rayKeyType int
const v2rayKey v2rayKeyType = 1
// FromContext returns an Instance from the given context, or nil if the context doesn't contain one.
func FromContext(ctx context.Context) *Instance {
if s, ok := ctx.Value(v2rayKey).(*Instance); ok {
return s
}
return nil
}
// MustFromContext returns an Instance from the given context, or panics if not present.
func MustFromContext(ctx context.Context) *Instance {
v := FromContext(ctx)
if v == nil {
panic("V is not in context.")
}
return v
}
/*
toContext returns ctx from the given context, or creates an Instance if the context doesn't find that.
It is unsupported to use this function to create a context that is suitable to invoke V2Ray's internal component
in third party code, you shouldn't use //go:linkname to alias of this function into your own package and
use this function in your third party code.
For third party code, usage enabled by creating a context to interact with V2Ray's internal component is unsupported,
and may break at any time.
*/
func toContext(ctx context.Context, v *Instance) context.Context {
if FromContext(ctx) != v {
ctx = context.WithValue(ctx, v2rayKey, v)
}
return ctx
}
/*
ToBackgroundDetachedContext create a detached context from another context
Internal API
*/
func ToBackgroundDetachedContext(ctx context.Context) context.Context {
return &temporaryValueDelegationFix{context.Background(), ctx}
}
type temporaryValueDelegationFix struct {
context.Context
value context.Context
}
func (t *temporaryValueDelegationFix) Value(key interface{}) interface{} {
return t.value.Value(key)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/config.pb.go | config.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.10
// protoc v5.28.1
// source: config.proto
package core
import (
transport "github.com/v2fly/v2ray-core/v5/transport"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
anypb "google.golang.org/protobuf/types/known/anypb"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// Config is the master config of V2Ray. V2Ray takes this config as input and
// functions accordingly.
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Inbound handler configurations. Must have at least one item.
Inbound []*InboundHandlerConfig `protobuf:"bytes,1,rep,name=inbound,proto3" json:"inbound,omitempty"`
// Outbound handler configurations. Must have at least one item. The first
// item is used as default for routing.
Outbound []*OutboundHandlerConfig `protobuf:"bytes,2,rep,name=outbound,proto3" json:"outbound,omitempty"`
// App is for configurations of all features in V2Ray. A feature must
// implement the Feature interface, and its config type must be registered
// through common.RegisterConfig.
App []*anypb.Any `protobuf:"bytes,4,rep,name=app,proto3" json:"app,omitempty"`
// Transport settings.
// Deprecated. Each inbound and outbound should choose their own transport
// config. Date to remove: 2020-01-13
//
// Deprecated: Marked as deprecated in config.proto.
Transport *transport.Config `protobuf:"bytes,5,opt,name=transport,proto3" json:"transport,omitempty"`
// Configuration for extensions. The config may not work if corresponding
// extension is not loaded into V2Ray. V2Ray will ignore such config during
// initialization.
Extension []*anypb.Any `protobuf:"bytes,6,rep,name=extension,proto3" json:"extension,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_config_proto_rawDescGZIP(), []int{0}
}
func (x *Config) GetInbound() []*InboundHandlerConfig {
if x != nil {
return x.Inbound
}
return nil
}
func (x *Config) GetOutbound() []*OutboundHandlerConfig {
if x != nil {
return x.Outbound
}
return nil
}
func (x *Config) GetApp() []*anypb.Any {
if x != nil {
return x.App
}
return nil
}
// Deprecated: Marked as deprecated in config.proto.
func (x *Config) GetTransport() *transport.Config {
if x != nil {
return x.Transport
}
return nil
}
func (x *Config) GetExtension() []*anypb.Any {
if x != nil {
return x.Extension
}
return nil
}
// InboundHandlerConfig is the configuration for inbound handler.
type InboundHandlerConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Tag of the inbound handler. The tag must be unique among all inbound
// handlers
Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"`
// Settings for how this inbound proxy is handled.
ReceiverSettings *anypb.Any `protobuf:"bytes,2,opt,name=receiver_settings,json=receiverSettings,proto3" json:"receiver_settings,omitempty"`
// Settings for inbound proxy. Must be one of the inbound proxies.
ProxySettings *anypb.Any `protobuf:"bytes,3,opt,name=proxy_settings,json=proxySettings,proto3" json:"proxy_settings,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *InboundHandlerConfig) Reset() {
*x = InboundHandlerConfig{}
mi := &file_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *InboundHandlerConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*InboundHandlerConfig) ProtoMessage() {}
func (x *InboundHandlerConfig) ProtoReflect() protoreflect.Message {
mi := &file_config_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use InboundHandlerConfig.ProtoReflect.Descriptor instead.
func (*InboundHandlerConfig) Descriptor() ([]byte, []int) {
return file_config_proto_rawDescGZIP(), []int{1}
}
func (x *InboundHandlerConfig) GetTag() string {
if x != nil {
return x.Tag
}
return ""
}
func (x *InboundHandlerConfig) GetReceiverSettings() *anypb.Any {
if x != nil {
return x.ReceiverSettings
}
return nil
}
func (x *InboundHandlerConfig) GetProxySettings() *anypb.Any {
if x != nil {
return x.ProxySettings
}
return nil
}
// OutboundHandlerConfig is the configuration for outbound handler.
type OutboundHandlerConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Tag of this outbound handler.
Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"`
// Settings for how to dial connection for this outbound handler.
SenderSettings *anypb.Any `protobuf:"bytes,2,opt,name=sender_settings,json=senderSettings,proto3" json:"sender_settings,omitempty"`
// Settings for this outbound proxy. Must be one of the outbound proxies.
ProxySettings *anypb.Any `protobuf:"bytes,3,opt,name=proxy_settings,json=proxySettings,proto3" json:"proxy_settings,omitempty"`
// If not zero, this outbound will be expired in seconds. Not used for now.
Expire int64 `protobuf:"varint,4,opt,name=expire,proto3" json:"expire,omitempty"`
// Comment of this outbound handler. Not used for now.
Comment string `protobuf:"bytes,5,opt,name=comment,proto3" json:"comment,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *OutboundHandlerConfig) Reset() {
*x = OutboundHandlerConfig{}
mi := &file_config_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *OutboundHandlerConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*OutboundHandlerConfig) ProtoMessage() {}
func (x *OutboundHandlerConfig) ProtoReflect() protoreflect.Message {
mi := &file_config_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use OutboundHandlerConfig.ProtoReflect.Descriptor instead.
func (*OutboundHandlerConfig) Descriptor() ([]byte, []int) {
return file_config_proto_rawDescGZIP(), []int{2}
}
func (x *OutboundHandlerConfig) GetTag() string {
if x != nil {
return x.Tag
}
return ""
}
func (x *OutboundHandlerConfig) GetSenderSettings() *anypb.Any {
if x != nil {
return x.SenderSettings
}
return nil
}
func (x *OutboundHandlerConfig) GetProxySettings() *anypb.Any {
if x != nil {
return x.ProxySettings
}
return nil
}
func (x *OutboundHandlerConfig) GetExpire() int64 {
if x != nil {
return x.Expire
}
return 0
}
func (x *OutboundHandlerConfig) GetComment() string {
if x != nil {
return x.Comment
}
return ""
}
var File_config_proto protoreflect.FileDescriptor
const file_config_proto_rawDesc = "" +
"\n" +
"\fconfig.proto\x12\n" +
"v2ray.core\x1a\x19google/protobuf/any.proto\x1a\x16transport/config.proto\"\xa5\x02\n" +
"\x06Config\x12:\n" +
"\ainbound\x18\x01 \x03(\v2 .v2ray.core.InboundHandlerConfigR\ainbound\x12=\n" +
"\boutbound\x18\x02 \x03(\v2!.v2ray.core.OutboundHandlerConfigR\boutbound\x12&\n" +
"\x03app\x18\x04 \x03(\v2\x14.google.protobuf.AnyR\x03app\x12>\n" +
"\ttransport\x18\x05 \x01(\v2\x1c.v2ray.core.transport.ConfigB\x02\x18\x01R\ttransport\x122\n" +
"\textension\x18\x06 \x03(\v2\x14.google.protobuf.AnyR\textensionJ\x04\b\x03\x10\x04\"\xa8\x01\n" +
"\x14InboundHandlerConfig\x12\x10\n" +
"\x03tag\x18\x01 \x01(\tR\x03tag\x12A\n" +
"\x11receiver_settings\x18\x02 \x01(\v2\x14.google.protobuf.AnyR\x10receiverSettings\x12;\n" +
"\x0eproxy_settings\x18\x03 \x01(\v2\x14.google.protobuf.AnyR\rproxySettings\"\xd7\x01\n" +
"\x15OutboundHandlerConfig\x12\x10\n" +
"\x03tag\x18\x01 \x01(\tR\x03tag\x12=\n" +
"\x0fsender_settings\x18\x02 \x01(\v2\x14.google.protobuf.AnyR\x0esenderSettings\x12;\n" +
"\x0eproxy_settings\x18\x03 \x01(\v2\x14.google.protobuf.AnyR\rproxySettings\x12\x16\n" +
"\x06expire\x18\x04 \x01(\x03R\x06expire\x12\x18\n" +
"\acomment\x18\x05 \x01(\tR\acommentBD\n" +
"\x0ecom.v2ray.coreP\x01Z#github.com/v2fly/v2ray-core/v5;core\xaa\x02\n" +
"V2Ray.Coreb\x06proto3"
var (
file_config_proto_rawDescOnce sync.Once
file_config_proto_rawDescData []byte
)
func file_config_proto_rawDescGZIP() []byte {
file_config_proto_rawDescOnce.Do(func() {
file_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_config_proto_rawDesc), len(file_config_proto_rawDesc)))
})
return file_config_proto_rawDescData
}
var file_config_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
var file_config_proto_goTypes = []any{
(*Config)(nil), // 0: v2ray.core.Config
(*InboundHandlerConfig)(nil), // 1: v2ray.core.InboundHandlerConfig
(*OutboundHandlerConfig)(nil), // 2: v2ray.core.OutboundHandlerConfig
(*anypb.Any)(nil), // 3: google.protobuf.Any
(*transport.Config)(nil), // 4: v2ray.core.transport.Config
}
var file_config_proto_depIdxs = []int32{
1, // 0: v2ray.core.Config.inbound:type_name -> v2ray.core.InboundHandlerConfig
2, // 1: v2ray.core.Config.outbound:type_name -> v2ray.core.OutboundHandlerConfig
3, // 2: v2ray.core.Config.app:type_name -> google.protobuf.Any
4, // 3: v2ray.core.Config.transport:type_name -> v2ray.core.transport.Config
3, // 4: v2ray.core.Config.extension:type_name -> google.protobuf.Any
3, // 5: v2ray.core.InboundHandlerConfig.receiver_settings:type_name -> google.protobuf.Any
3, // 6: v2ray.core.InboundHandlerConfig.proxy_settings:type_name -> google.protobuf.Any
3, // 7: v2ray.core.OutboundHandlerConfig.sender_settings:type_name -> google.protobuf.Any
3, // 8: v2ray.core.OutboundHandlerConfig.proxy_settings:type_name -> google.protobuf.Any
9, // [9:9] is the sub-list for method output_type
9, // [9:9] is the sub-list for method input_type
9, // [9:9] is the sub-list for extension type_name
9, // [9:9] is the sub-list for extension extendee
0, // [0:9] is the sub-list for field type_name
}
func init() { file_config_proto_init() }
func file_config_proto_init() {
if File_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_config_proto_rawDesc), len(file_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 3,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_config_proto_goTypes,
DependencyIndexes: file_config_proto_depIdxs,
MessageInfos: file_config_proto_msgTypes,
}.Build()
File_config_proto = out.File
file_config_proto_goTypes = nil
file_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/functions.go | functions.go | package core
import (
"bytes"
"context"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/environment/envctx"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/features/routing"
"github.com/v2fly/v2ray-core/v5/transport/internet/udp"
)
// CreateObject creates a new object based on the given V2Ray instance and config. The V2Ray instance may be nil.
func CreateObject(v *Instance, config interface{}) (interface{}, error) {
return CreateObjectWithEnvironment(v, config, nil)
}
func CreateObjectWithEnvironment(v *Instance, config, environment interface{}) (interface{}, error) {
var ctx context.Context
if v != nil {
ctx = toContext(v.ctx, v)
}
ctx = envctx.ContextWithEnvironment(ctx, environment)
return common.CreateObject(ctx, config)
}
// StartInstance starts a new V2Ray instance with given serialized config.
// By default V2Ray only support config in protobuf format, i.e., configFormat = "protobuf". Caller need to load other packages to add JSON support.
//
// v2ray:api:stable
func StartInstance(configFormat string, configBytes []byte) (*Instance, error) {
config, err := LoadConfig(configFormat, bytes.NewReader(configBytes))
if err != nil {
return nil, err
}
instance, err := New(config)
if err != nil {
return nil, err
}
if err := instance.Start(); err != nil {
return nil, err
}
return instance, nil
}
// Dial provides an easy way for upstream caller to create net.Conn through V2Ray.
// It dispatches the request to the given destination by the given V2Ray instance.
// Since it is under a proxy context, the LocalAddr() and RemoteAddr() in returned net.Conn
// will not show real addresses being used for communication.
//
// v2ray:api:stable
func Dial(ctx context.Context, v *Instance, dest net.Destination) (net.Conn, error) {
ctx = toContext(ctx, v)
dispatcher := v.GetFeature(routing.DispatcherType())
if dispatcher == nil {
return nil, newError("routing.Dispatcher is not registered in V2Ray core")
}
r, err := dispatcher.(routing.Dispatcher).Dispatch(ctx, dest)
if err != nil {
return nil, err
}
var readerOpt net.ConnectionOption
if dest.Network == net.Network_TCP {
readerOpt = net.ConnectionOutputMulti(r.Reader)
} else {
readerOpt = net.ConnectionOutputMultiUDP(r.Reader)
}
return net.NewConnection(net.ConnectionInputMulti(r.Writer), readerOpt), nil
}
// DialUDP provides a way to exchange UDP packets through V2Ray instance to remote servers.
// Since it is under a proxy context, the LocalAddr() in returned PacketConn will not show the real address.
//
// TODO: SetDeadline() / SetReadDeadline() / SetWriteDeadline() are not implemented.
//
// v2ray:api:beta
func DialUDP(ctx context.Context, v *Instance) (net.PacketConn, error) {
ctx = toContext(ctx, v)
dispatcher := v.GetFeature(routing.DispatcherType())
if dispatcher == nil {
return nil, newError("routing.Dispatcher is not registered in V2Ray core")
}
return udp.DialDispatcher(ctx, dispatcher.(routing.Dispatcher))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/core.go | core.go | // Package core provides an entry point to use V2Ray core functionalities.
//
// V2Ray makes it possible to accept incoming network connections with certain
// protocol, process the data, and send them through another connection with
// the same or a difference protocol on demand.
//
// It may be configured to work with multiple protocols at the same time, and
// uses the internal router to tunnel through different inbound and outbound
// connections.
package core
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
import (
"runtime"
"github.com/v2fly/v2ray-core/v5/common/serial"
)
var (
version = "5.43.0"
build = "Custom"
codename = "V2Fly, a community-driven edition of V2Ray."
intro = "A unified platform for anti-censorship."
)
// Version returns V2Ray's version as a string, in the form of "x.y.z" where x, y and z are numbers.
// ".z" part may be omitted in regular releases.
func Version() string {
return version
}
// VersionStatement returns a list of strings representing the full version info.
func VersionStatement() []string {
return []string{
serial.Concat("V2Ray ", Version(), " (", codename, ") ", build, " (", runtime.Version(), " ", runtime.GOOS, "/", runtime.GOARCH, ")"),
intro,
}
}
/*
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::c:::::::::::::::::::::::ccc:::cccc::::::c:::::cccc::::cc::::::::::::::::::::::::ccccccc::cccccccccc::cc:::;:::::::::::::::::::::::::::ccc:::cccc:ccc::::::c:::::::::::::::::::::::::::cccc:cccccccccccccccccccccc:;;::::::::::::::::::c::::ccc::::::ccc:::ccc::cccccc::::cc:cc:::ccccccccccccccccccccccccccccccccccccccc
:::;::::::::::::::::::::::::::::::::::::::::::::::cc:::::::::::::::::::::::::::::::::::::ccc::cc:::::c:::::::::::ccc::ccc:::::ccc::::::cc:::::cccc:::::::::::::::::::::cccccccccccccccccccccccccc:::::::::::::::::::::::::cc::ccc::::::::::::::c::c::::::::::::c::::::::c::::::cccccccccccccccccccccccccc:;:::::::::::::::ccc::cccccccc::c:cccc::cc:::cccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::cc::::::::cc::::::::::::ccccc:::::ccccccccc::cccc::ccccccc:::c::::::::c:c:::::cccccccccccccccccccccccccc::::::::::::::::::::::::cc:::::ccc:::c::::::::::::::::c::::::::::::::::::::::ccccccccccccccccccccccccccc:::::::::::::::::::::cccccc:ccccc::ccccccccc:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
::;;::::::::::::::::::::::::::::::::::::::::::::::::::::::::c:::::::::::::::::::::cc::::::::::::::::c:::cc::::c::::::::cccccc::::cccccccccc::ccccccc::c::::::::c::::::::ccccccccccccccccccccccccc:::::::::::::::::::::::::c::::cccc:::cc:::cc:::::::::::::::::::::::::::c::::::ccccccccccccccccccccccccccc::::::::::::::::::::cccc::cccccc:ccc:cccccccccccccccc:cccccccccccccccccccccccccccccccccccccccccccccccc
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::cc:::::::::::::::ccc:::::c:::cc::::::::::::::::::::::cc:::c::cccc::::::::::cccccccccccc:ccc::c:::::::ccc:::::::cccccccccccccccccccccccccc:::::::::::::::::::cccccccccccccc::::::::ccc::c::cc:::cc::::::::::::::cc:::::cccccccccccccccccccccccccccc::::::::::::::::::::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
::::::::::::::::::::::::::::::::::::::::::::::::::::::c::::::::::::::::::::c::::::::::::::::::::ccccc::::::::::::ccc::cc:::::cccc::::cccccccccccc::::cccccc:::ccccc:::::cccccccccccccccccccccccccc::::::::::::::::::::c:cc:::cc::::::::::::cc::cc:::::::cccc::::::c:::::cc::::::ccccccccccccccccccccccccccc:::::::::ccc::::::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::cc:::::::::::::::ccccccc:::::ccccc::ccc::ccccccccccccccccccccccccccccccc:cccc::::cccccc::::cccccccccccccccccccccccccc::::::::::::::::c:::::cc::::::::cc:::cccc::::cc::::ccc:ccc::c:::::::::cccc::::ccccccccccccccccccccccccccc::::::::::cc::::::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
::::::::::::::::::::::::::::::::::::::::::::::::::::c::::::::cc::::::::::::::cc:::::::ccccc:::c:::::ccc::cccc:::cccccc:ccccccccccccccccccccccccccccccccccc::::ccccccc:::cccccccccccccccccccccccccc:::::::::cc:::::::::::::cc:::cc::cccccccc::cccccc::ccccccccc:c::::::::ccc:::::cccccccccccccccccccccccccccc:::::::::ccc:::::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
::::::::::::::::::::::::::::::::::::::::::::cc:::::::::ccc:::::c::::::cc:::cccc:::c:::ccccc::::ccc::cccccccccc::cccccc::ccccccccccccccccccccccccccccccccccc:ccccccccc::ccccccccccccccccccccccccccc:::::::::::::::::::::::::cc:cccc::cccccccccccc:ccc::cccccc:ccc::::::::cccc:::::ccccccccccccccccccccccccccc:::::::::ccc:::::c:ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
:::::::::::::::::::::::::::::::::::c:::::::c:::::c:::::cc::::::::::::cccccc::::ccccccccc:::::::ccccccccccccccccccccccc:cccccccccccccccccccccccllccccccccccccccccccccc::cccccccccccccccccccccccccccc:::::::::c:::::::::::ccccccccccccccccccccccc::cc:::::cccccccc:::cc:::ccccc::::ccccccccccccccccccccccccccc:::::::::cccc::::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
:::::::::::::::::::::::::::::cc::cc:::::::c:::::::::::::c:::cc:::::::cccccc::::cccccccc:cc:::ccccccccccccccccccccccccccccccccccccccccccccccoxk00Okxddoolllllloodxkkxdoloolccccccccccccccccccccccccc:::::::::c:::::::::cccccccc::cc::ccccc:::cccccc:ccc:ccccccccc:ccccc:::cc:cc:::ccccccccccccccccccccccccccc:::::::::ccccc:::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
::::::::::::::::::c::::::::ccc:::cc:::::::c::::cc::c::::c:::ccc:::ccc::::::ccc:::ccccccccccccccccccccccccccccccccccccccccccccloxxkOO0OkkkkOKXK00000000KKK0KKXXNNWWWWNXKKK0kdoolclloooddollccccccccc:::::::::cc:::::cccccccccccc:ccccccccc::cccccccccccccc:cccccc:ccccc:::cc:cc:::cccccccccccccccccccccccccccc:::::::cccccc:::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
:::::::::::::::::::::::::::::::::::::::c::ccc:::cc::cc::ccc:::::cc:::cc::::ccc::cccc:cccccccccccccccccccccccccccccccccccccccdkO0KKK0000OOkkOKXXXXXXXXXNNXKXNNNNNNNNNNNXXXXXKKKOO0KKKKKKK0Oxxoolllcc:::::::::cc::::ccc::cccc:cccccccc:ccccccccccccccccccccccccccccccc:cc:::cc:::::ccccccccccccccccccccccccccccc::::::::c::c:::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
:::::::::::::::::::::ccc::::c:::c:ccc::c::ccccc:ccc::::ccccccccc:cc:cccccccccccccc:ccccccccccccccccccccccccccccccccccccccclxOOOO00KKKKKKK00KKXXNNNNXNNNNXXXXXNNNNNNNNNXXKKXXXXXXXXXXXKKXXNXXK00KOdl::::::::ccc:::::cccccccccccc:cccc::ccccccccccccccccccccccccccccc::cc:::ccc:cc::ccccccccccccccccccccccccccccc:::::::cccc::::cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
::::::::::::::::::ccccccccc:cc::cccc::ccc:ccccc:ccc:::ccccccccccccccccccccccccc:ccccccccccccccccccccccccccccccccccclok000O0XNNNNNXK00KKXK0K0xxk000KXXXXXNNNNNNNXNNNNNNXXXXXNNXXXXXKX0dodxxxxddxOOxl::::::::cccc::::ccccccccccccccccccccc::cccccccccccccccccccccccccccccc::cccccc:::cccccccccccccccccccccccccccc::::::::ccccc::cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
:::::::::::::c::::cccc:::c::ccccccccc::cc:ccccc:ccc::cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclx0XNNNXNXXXNNNXKKKKXXX0OOxooddoodkKXKKKKXNXXNXXXXKKKKXX00KXKKXXNNXK0kko:;;::cccccc::::::::ccc::::ccccccccccccccccccccccccccccccccccccccccccccccccccccc::cccccc:::cccccccccccccccccccccccccccc::::::::cccccc:::cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
::::::::::::::cc:ccc::ccccc:cccccccccc::cccccccccccccccccccccccccccccc:cccccccccccccccccccccccccccccccccccccccclxKNNNNXOO0KOkO0KXXNXXXXK0kololllol:lO0kkxkOKXXXXK0kkxddxO000OOkOO0KKXNNNXOxl:::coolc::::::::ccc:::ccccccccccccccccccccccccccccccccccccccccccccccccccccc:::cccccc:::ccccccccccccccccccccccccccccc::::ccccccccc::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
:ccc::::::::::cc:c:::cccccccccccccccccccccccccccc:ccccccccccccccccccccccccccccccccccccccccc:ccccccccccccccccccoOXNWWNN0dcllldO0KKXXXXXXXXKxllldkkkxxdlc;;lOK00OOOd:;;;:cdk0OxkxoodxxkOOOOO0Okl,cO0kl::::::::ccc:::ccccccccccccccccccccccccccccccccccccccccccccccccccccccc::cccccc::ccccccccccccccccccccccccccccc:::cc:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
::cc:::::::::c::::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccldO00KNNNXKOddk0KXXXXXXXXXXKK0OOOOO0KKxc;,,.;oxxddxkOx:;,;loddxxolddlc::ccccc:;cooox0KKkl:::::ccccc:::cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc::ccccccccccccccccccccccccccccc:::::cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
c:cc:::c::cccccc::ccccccccccc:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccldkkxdxkKK000kxkkOO0000OOOOOkdloOKKO0K0dc,...;ccc:lxO0dccclllccloolllc:;;;:cc:;.,:cok0Okkkl::::cccccc:::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc::ccccccccccccccccccccccccccccc:::::cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
ccc::::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclx0KK0OxdxOOOxl::codxxdoooolccoxO0K00kdoodl;''',;;;:lxOOdollccc::cc:;;;;,'',;;;;'','';:coxxl::::cccccc:::cccccccccccccccccccccccccccccccccccccccccccccccccccccccc:cccccc::cccccccccccccccccccccccccccccc::c::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccllccccccccccccccccccccc
cc:::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccldxOKXNXKOxxdl:;;,,,,,,,ckOx;:k00Okkxolc;;;:;,''',,'',:ok0kocc::,.',,;;;;,''',;,;,...',;:ccc::::::ccccc:::cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc::ccccclcccclcccccccccccccccccc::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccllcc
ccc::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccooloOKKKK0Oo:;,''..'.. ;xO0OxxOkxdddddoll:;,..,,,,;'.'',:ll:,,,,'..'''',,;;,,,,;;;,',,;;::cc:cccc:ccccc::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc::ccccllccccccclcclllcccccccclcc::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclllccccccccccccc
cccc:ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclollxOOOO0Oxl:;'''',;;;cdxodxdoolllldk00Od:,'..,;,;;;,,'.....'',,,,,'''.''''.....,,,''',::ccc:cccc::ccccc:ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc:::cccclcccllcclcccllcccccccclcc:::ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccllcclcclcccccccccccccccc
ccc:ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclxkxdddxO0Oxdoc;'',;:ldxdlc:coolcc::ldxolc;;::,..,,;;;;;;'...'';cccc::;,,,,,,,'....,',;:oolccccccccccccccc:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc::cclcccccllccccclccclcllllclccc:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccclllccccclllcccccccccccccccccccccl
cc::cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclxOOxddxkkkdoool:;,.';ccc:::::;::::::cc;;;:cdddo:'''',;;;;;;,,;:codddolc:;;,,,;,,''',,,,;:llllc:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclllclllcccccccclllllllllllcccccccccccccccccccccccccccccccccccccccccccccccccccllccllccccccllccccccccccccllcccccccllcccccc
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclxkkkkO00koc;,'.';;,...;;::;::;,,;:::::::;;;::::::;'''',,,,;,;;:loxkkOkxdolc:;;;,,,'...',:lllclccccc::cccccc:ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc:cclllllllclllcccclllllllllllcccccccccccccccccccccccccccccccccccccccccccccccccccllcclllcccccccccccccccccllclccllccclccccccc
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccldddkOOO00OOOOxl,.';;'...,;;;;;;,;;;;:::;;::;,'',;;,',,,,,,,,;;:loodxxxxxxxddoolc:;;,...;cdkkdlllc:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccllllcllllllccclllllllclllllcccccccccccccccccccccccllccccccccccclccclcccllccccllcccccccccccccccllcclllccclccllccccccccccc
cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccloodOOkkkOOOOOOkxc,;:,. ..',;;;;;;'',,,,,,,;,...,;,,;;;,,,;;;:clllllcc::clodxxddolc;'',;:ccodlccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc:cclllllllllllllllllllllllllllc:ccccccccccccccccccccllccclllcccccccccllcccccccccccccccccclccccccllcccccccclccccccccccccccc
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclollxOkxxxxxxxddddoc;'.... ..,;;;,'....';,.','.',,;::::;;;;;::cloddddooc:;::cclddolc:;:::::cllllc:cccccccclcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclccccc:ccllllllllllllllllllllllllcllc:cccccccccccccccccccccccccllccccccccccccccccccccllccccccllllcccccccccccccccccccccccccccccll
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclccdkkxdooollccc:::;'.......... ..,,,;,''',;,.''',,,;:ccc:::::::::::cccclccc::::::cloolllc:ccccccllccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclccccc::cllllllllllllllllllllllllllllc:cccccccccccccccccccccccccccccccccccccccclllllccccclllccccccccccccccccccccccccccllllllllll
cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccoxdxkdl::::::cc;,,''.. .....',,,;;,,,,,'',;;:cloodollc::;;;;:;;,,;;;;::::::c:looooolcclllllllcccccccccccccccccccccccccclllcccccccccccccccccccccccccccclccclccccccccccccccccccccccllllllllllllllllllllllllllllc:cccccccccccccccccccccccccccccclllcclllllllllllcccccccccccccccccccccccccclllllllllllllllll
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccllllloooc:;,'',;;,,;:..... ....'',,,,,,,,;;;:ccooddxxxxxdol:;;;:ccc::;;;,;;;;;;clollllllllllllllcccccccccccccccccccclccccclccccccccccccccccccccccclcccccccccllcccclcccccccccccccccccllllllllllllllllllllllllllllccccccccccclcccccccccccclllclllllllllllccclllccccccccccccccccccccccllllllllllllllllllllllll
cccccccccccccccclccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc::;,,;:;.. ';;';c;'';;'. ....'',,,;;;;;;:clodddxxxxkkkkkkxdoddxxdol:,,,,;;,;:oxdlllllllllllllllcccccccccccccccclcccccccclccccclllcccccccccllcccclcccccccclllccccccccccccccccccccccclllllllllllllllllllllllllllcccccccccccccccllcccccccccccclcccccccccccccccccccccccccccccclllllllllllllllllllllllllllllll
ccc::cccccccccccccccccccclccccllcccccccccccclcccccccccccccccccccccccccccccccccccccccccccccccccclccol:;,,''''....','';:;,:;. ...',,,,;;;;;:ccloddxxxxxkkOOOO000Okxddool;'',,;;:loxOkoclllllllllllllcccccccccclccccccccccccccccclccllllllcccccccclcccccccccccclllcccccccccccccccllccccccllllllllllllllllllllllllllllccccccccccccccllccccccccccccccccccccccccccccccccccllllllllllllllllllllllllllllllllllllllll
ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclcccclllccccccccccccccccclllllo:;,,,',,,,,,,,'';::::,. ..',,;;;::::cccooddxxxxkkkOOO00000Okxolllc;;:::coxkO00dllllllllllllllccccccccccccccccccccccllllcclcclllllllcccccclllccccccccccclcccclcccccccccccccccccccclllllllllllllllllllllllllllllcccccccccllccccccccccccccccccccccccccccclllllllllllllllllllllllllllllllllllllllllllllllll
ccccccllccllccccccccccccccccccccccccccccccccccccccccclccccccccccccccccccccclllcclccccccllcccclcclccc:;;;,,,,,,;;;::;;:c::;'. .....',;;:::::ccllloddxxxxxkkkkOOO000000OkxdolooddxkOOO00Oolllllllllllllcccccccccccccccllllcclllllcllcclllllllcllccllllcccccccccccccccccccccccccccccclllcccccllllllllllllllllllllllllllllc:cccccccccccccccccccccccccccccccllllllllllllllllllllllllllllllllllllllllllllllllllllllll
ccccccccccccccclccllccllllllcccclccccccccccccccccccccccccccccccccccccccclllllllllcccllcclllllllcllcc:::::;;,',;;;:cl::lc:;;,,,,'...,;:::ccclollllooddddddxxxxkkkkOO00000OOOOOOO00OOOOO00xlllllllllllllccccccccccclcccclllcclllclccccclccccccccccccccccccccccccccccccccccccccccllcllllllccccllllllllllllllllllllllllllllc:cccccccccccccccccccccllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll
ccccccccccccccccccccclcccllcccclllclllclllllccccccccccccccccccccccccccccccccccccccccccccccccccccccccc:::;''...,;;;::;;:clcc:::::;;,;:::cccloooooooooooodddddddxxxkkOOOOO0000000KKKK00O0KOollllllllllllccccccccccccccccccccccccccccccccccccccccccccccccccllllllllllllllllllllcccccclcccccccclllllllllllllllllllllllllllllc:ccccccccccclllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll
cccccccccccccccccccccccccccccccccccccccccclllclccclcccllllllllcclllccccccccccccccccccccccccccccccccccc:;,.....,;;;:;;,,;;::clllllcc::ccllllllloooooooooooddddddxxkkkOOOOOOOOOOOOOO00K0KKKxllllllllllllcccccccccccccccccccccccccllllcclllllllllllcclllllllllllllcccllccllllllclccccccccccccccllllllllllllllllllllllllllllccllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll
cccccccccccccccccccccccccccccccccccccccccccccccccccccccllcccccccccccllcccccclllccllllllllllllllllllllcc:;;,..';:::;;,,'.'',,;::cc:::clloooolloddodddoooooddddddxxxkkOOOOOOOkxodxkO00KKKXXOolllllllllllccccccclccclllllllllllcclllcllllcllllllllllllcccccllllcccccccccccccccllcccccccccccc::clllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllool
llllllllllllccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccllllclllllllcc:;,..,;;;,,,,,''...',,;;;;;:loooooddddddddddddoooddddddxxxkkkkkkkkkxddOKXXXXKKXXXKxllllllllllllcccccccccccccccllcclllcllccclccccccccccccccccccccccccccccccccccccccccccccccccccccccccllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll
llllllllllllllllllllllllllllcllccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccllccc:,'';:;,,,,,,;,'...',,,,;;;clooddddoodddddddooddooodddddxxxxkkkkkkkOkxkkxdxxkkxxkOkolllllllllllccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllolllllllllllllllllllllllllllooloooloo
llllllllllllllllllllllllllllllllllllllllllllllcllcccccccccccccccccccccccccccccccccccccccccccccccccccccc:,.,cllc:;;;;;;;,,'',;;;;;;:llooddddodddddddddddooooodddddxxxkkkkkO0KOdc;..'',:cccoollllllllllllccccccccccccccccccccccccccccccccccccccccccccccccllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllloollllllllllllllollllolooooooooo
llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllcccccccccccccccccccccccccccccccccc::;;cllol:;;;:::;,'',;;;;;;:clloooodddooddddddoooooodddddddxxxkkOOO00K0ko:;;;:;clllllllllllllllllc:ccccccccccccccccccccclccclllcllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllollllllllllllloooolllllloooooooooollolll
llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllcllollcccc:;,'',;;,,,,;;;;;:::ccllloooooooooooooooooooodddddddxxkkkkkOO0KK0kdlclolllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllollllllllllllllllllllllllllllllllllllllllllllllllllllllllloooollllloollooolllloooooooollooooooloolllllcc
llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllollool::;,;;;:;'..',,,,;;;::::::ccclllllllooooooooooooooddddddddxxxxxdddxO0000Oxllollllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllolllllllllllllllllllllllllllllllllllllllllllllllllllllllllllollllllloollloollloooooooooollooollolllllcccc::::::
lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllldo:;;:cllll:'...;;;::ccccccccccccccllllllllloooooooooooodddddddddolclooollloollllllllllllllllllllllollllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllooolllloooollllllloooollloooloooooolooooooooolllllcccc::::::::::::::
llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllc:clooooollcc:;..';::clllllolcccccccccccllllllllllllloooooooooddddxkkkxdxxxxoclllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllloollllloollllllolllllllllllllllollllllllloooolllooooooolllllllloolloolloooloooolllllcccc::::;:::::::::::::::::
lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllc:::::::c:::;,',;;:clooooddolcccccccccccccccllllllllloooooooddddxkOOOkdlloddooloollllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllloollllllloolloollllollllllllllllllollooollllllllllloooloooooooolllloollllllloooooolllllllccc::::::;::::::::::::::::cccccccc
lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllc:::::::::;;,'''.,:cloodddddolcccccccccccllcclccclllllloooooddxxkOOOOkdoccclooooolollllllllllolllllllllllllllllollllllllllllllllllllllllllllllllllllllllllllllllllllllllllloolllllllllllllollooooooooooooolllloooooollllooooollllloooollooooooooooooooooollllllccccc::::::::::::::::::::::::ccccccclllllllo
lllllllllllllllllllllllllllllllllllllllllolllllllllllllllllllllllllllllllllllllllllllllllllllllllllllc::;:::;;::cc:;'.,:coodddxxddolc:cccllllllllllllclllllllllooodxxkO000K00kdoooolllllllllollllllllolllllllllolllloolloolllllllllllllllllllllllolllllllllllllllloolllllllllllllloollllooooolloooooooooooooooooooooooooolllloollooooooooooollooooooollllllcccc:::::::;:::::::::::::::::ccccccclllllllllllllllll
ooollllllllloolllllllllllllllllllllllllooollllllllllllllllllllllllllllllllllllllllllllllllllllllllloolc:;;;:::cclllllc:clodddxxxxxdolc::cccllllllllllllllllllllllooddxkO00KKKKK0kdooollllooloooooollooollllllllloolllllllllllllllllllllllllllllllllllllllllllooolllollllllllllllllllolloollooolooloolooooooooooooooooooooooolooollooooooollllllllccccc::::::::;:::::::::::::::ccccccccllllllllloolllllllllccc:::
lloooolllollloollllllllllllllllllllllllllooollllllllolllllllllllloolllllllllllolloolllllllllllllllllollc:;;:::::::::cclllodddxxxxxxddlc::::ccccccclllllllllllllllllloodxxkOOOOkkxdolooooooooooooolllooolllllllllooollloolllllllloolllooloollloolllllloollllooooollllollloollloolooloooooolloollooooooloooooooooooooooooooooooooollllllccccc:::::::;::::::::::::::::::::ccccccclllllllllloollllllllcccc::::cccccl
ooooolllllllllollllllolllllllolllooolllllloooollllllllllllollllllllllolllllllllllllllllllllllllloolllllccc:c::::::;;::lloodddxxxxkkxxdolcc::ccccccclcclllllllllllllllllloooddddoddoooooooooooooooooooooooooooooooloooooollllllllooollllllooollooolllooooooooolllloooooolllllloolllooooolooooollooooooooooooooooooooooooooooolc:::;;;;;;:;;;::::::::::::::::cccccccclllllllllllloollllllllcccc:::::ccccclllllllll
lllllllloooooolllooooollollooolllooooooolllooooolllllllllloooooooollooooooollooooollllooooolllooolloooolcccccc:::::::clooodddxxxkkkkkxdddoollllcccccclllllllllllloooollllloooooooooooooooooooooooooooooooooooooooollloooooooolllooolllllllllloooooooooooooooollooloooooooooooollloooooolooooooooooooooooooooooooooooooooooool:;,,;;;;;::::::::::cccccccccclllllllllloollolllllllccccc:::::ccccclllllllooolloollo
:::c:cccccclllllllooooooooooooolloooooollooooooolooolllooooollooolllooooooolooooooolooooollooooooloooooolc::::::;;;:clooooodddxxxxkkkkkkxxxdddolllcccccclllllllloooooooooooddddoooooooooooooooooooooooooooooooooooooooooooooooolooooolooolloooooooooooooooooooooooooooooooooooolloooooooollllllloooooooooooooooooooooooooooolc:;;;;:::::cccccccllllllllllloollllllllllccccc::cc:cccccclllllllloooooooooooooooolo
::::::::::::::::::cccccccclllllllllllooooooooooooooollloooooolooooooooooooooooooooooooooolooooooooooooool:::::::;;;cllooooodddxxxxkkkkkkkkkxxxddoolllcccllllloooooooodddddddddoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooolllllllllllcccccc::::::cloooooooooooooooooooooooooooolcccccccllllllllllllooolllllllllccccc::::cccccclllllllllooooooooooooooooooooooolooo
:::::::::::::::::::::::::::::::::::cccccccllllllllllllllllloooooooooooooooooooooooooooooooooooooooooooollc::c::::;:loooooooddddxxxkkkkkkkkkkxxxdddooollccccllllllooodddooooooooooooooooooooooooooooooooooooooooodxxkkOOOkkkkkxdooooooooooooooooooooooolollllllllllccccccc:::::::::::::::::::::::loooooooooooooooooooooooooooolllllllllllllolllllllccccccccccccccccclllllllooollooooolooooooooooooooooloooooooooo
lllllccccccccc:c:::::::::::::::::::::::::::::::::::::::cccccccccccllllllllllooooooooooooooooooooooooooooolc:::::::clooooooooddddxxxkkkkkkkkkkxxxxxddddoollcclllloooooooooooooooooooooooooooooooooooooooooooodxkO0KKK000OOOOOOOOkkkxolllllllllccccccccc::::::::::::::::::::::::::::::::::::::::::loooooooooooooooooooooooooooollllllllllllool::::::cccccccllllllllooooooooloooooooooooooooooooooooooooooooooooooo
loolooollollllllllllllccccccccc:::::::::::::::::::::::::::::::::::::::::::::cccccccccccccclllcllllllllllllc::::::cloooooooooddddxxxkkkkkkkkkxxxxxxxxxxxxxddollllooloooooooooooooooooooooooooooooooooooooolloO0OO0KNNNNNXK0OOOOOOOOkkxlc::::::::::::::::::::::::::::::::::::::cccccccccccllllllcclooooooooooooooooooooooooooooolllllllllollolccclllllllooolloooooollloolloooooolooooooooooooooooooooooooooooooooo
llllooooooooooooooooooooolllllllllllllcccccccccccccccc::c::::::::::::::::::::::::::::::::::::::::::::::::::::::;;:loodddoooooddddxxxkkkkkkkxxxxxxxxxxxxxxxxdolllolcllccccclooooooooooooooooooooooooooooooloxkxdxkO0KXXNNNNX0OxxkOOOOO0ko::::::::::::::ccccccccccccccccccllllllllllllllllolooollllloooooooooooooooooooooooooooolllllllloollollllllloooloooooooooooooooooolooooooooooooooooooooooooooooooooooooooo
::::ccccccllllllllllllloooloooooooooooloooollllllllllllllllllcccccccccccccccccccccccccccc::::::::::::::::::::::::cloooddoooooddddxxxkkkkkkkxxxxxdxxxxxxxxddddoollccll:::::cooooooooooooooooooooooooooooodddollllodxkkO0KXXNNNK0xddxkO00Odccccccccclllllllllllllllllloooolloooooooolllollllloollllloooooooooooooooooooooooooooollllllllollooolllllloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
llccccccccccc::cccccccccccllllllllloooooooooooooooooooooooooooooooolllllllllllllllllllllllllcclccccccccccccccc:::clooddddoooooddddxxxkkkkkkxxxddddxxdddddddddooollclolc:::coooooooooooooooooooooooooooxkkxlllllllllooxkO00KXXNNX0xooddddxdollllllooooooooooooooooooooolloolllllllcclcccclllloollllooooooooooooooooooooooooooooolllloloooooooollooloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
lllloooolllllllllllccccccccccccccccccccccclllllllllllllooooooooooooooooooooooooooooooooooooooooooooollllllllollcccooddddddooooodddxxxkkkkkkkxxxxxxxxxdddddddoooollllodollclooooooooooooooooooooooooodxxxxollc:;,;:clllodxkO0KXXNNNKOxdoooxdoolooooooooollllllllllllcccccccc::cc:ccccccccloolllllllooooooooooooooooooooooooooooolllollooooooolllooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooolllllllllllllcccccccccccccccccccccccccllllllllllllllllooooooooooooooooooooooooooooooooooloodddddddddoooddddxxkkkkkkkkkkkkkkkxxxddooooooolllldxdollloooooooooooooooooooooodddlclll:;:;,'''',;cclllodxO0KXNNNNXKOdoddlclccccccccccccccccccccccccccclllllllllllllllloooooollloooooooooooooooooooooooooooooollllooolooooollooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooolllollllllllllllccccccccccccccccccccccccccccccclllllllllllllllllllllloddddddddddddddddddxxkkkkkkkkkkkkkkkkkxxddoooooolllodkxolllooooooooooooooooooooddol::::::::cccc:;,'''',:llloxOO00KKXXXXKOxolcclcclclllllllllllllloooooooooooooooolllllllloooooollllooooooooooooooooooooooooooooolloooooooooooolooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooolllllllllllllllllllcccclccccccccccccccccldxxddxxxdddddddddddxxkkkkkkkkkkkxxxxxkkkxxddddooooodxkkdlllooooooooooooooooooddolc:ccc:::lxkOkkkxddoc:;,;codk000OOOKKKKXXKOdooooooooooooooooooooooooooooooooooooooooooollooooooolllooooooooooooooooooooooooooooolllooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooodxxxxxxxxxxdddxddddddxkkOOOkkkxxxxxxxxxxxxxddxxddddddxkkdooodxxdooooooooooooddolcllllccccloxkkkkOO00KKKKK00KKK00000OOKKKKKXXX0kdoooooooooooooooooooooooooooooooooooooooollloooooolllooooooooooooooooooooooooooooolllooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooxkkkkkxxxxxxxxxxxxddddxkOOOOOkkxxxdddddddddddxxxxxddxxkkOOOkdxO00OOkxxdooooooolllllllllccclloddddxxxkOKKKXXXK0OOO0KKK00KXXKKXXXXKOxoooooooooooooooooooooooooooooooooooooollloooooollloooooooooooooooooooooooooooooollooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooodxkOkkkkkkkkkkkkkkkxxdddxkOO0OOkxxddddddddooddxkkkkkxxkkkkOO00xloxkO0KKK0Okxollllllllllllcccclodooooooodxxxxk0KK0OOO00KK00KKKKKKXXXXX0kdoooooooooooooooooooooooooooooooooooolloooooollloooooooooooooooooooooooooooooollooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooodxkOOOOOkkkkkkkOkkkkkkxxdddxOO00OOxxdddooooooddkkkOOOkkkkkOOOOO0Oolooddxkkxxddoollooollllllcc:::clllccclloolccldk0KK00000000O0KKKKKKKKKXX0xooooooooooooooooooooooooooooooooooollooooooollooooooooooooooooddoooooooooooollooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooodxkOO00000OOOOOOOOOOOOOOkkxxddxkO000OkxddoooooddxkOOOOOOOOOOOOOOOO00d:cooooooooddooooooolllllllccc:::::,,,'':olccccldk00000O000OO00KKKKKKKKKX0xooooooooooooooooooooooooooooooooooolooooooolllooodoooooooodddddooooooooooooolooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooddxkOO00000000000OOOO0000000OOkkxxxxkO000OkdddddddxkkO00000OOOOOOO00OO000xl:cloddddddddoooollllllllllccc:cclcclodxxollllllodxO0000000OO0KKKKKKKXXXKKOdooooooooooooooooooooooooooooooooolooooooolllodoodoooooooddoooooooddddooooolloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooodxkkO00KKKKKKKKKKK00000000000KKK00OkkkxxkO0KK0kxdddxxkOO00KKK00OOOO0000000KK0kdc::coddddddooooolllllllllllccccoddxkkkxxxdoodddddoxO0000000O0KKKKKKKXXXXXK0kdoooooooooooooooooooooooooooooooloooooooollooooddoodddddddddddoodoooooooolloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooood
ooooooooooooooooooooooooooooooooodooooooooooooooooooooooooooooooooooooooooooooooooooooooodxkkO0KKKKKKKKKKKKKKKKKKKKKKKKKKKKKXKKK00OOkkxk0KKKOOkkOOO000KKXXKK0OO00KKKKK0KKXK0kol::clooooooolllllllllllllllllllodddoooddxdodddxxdddkO00000000KKKKKXXXXXXKXKOdooooooooooooooooooooooooooooooooooooooollooooodoodddddddddddoodooooodoolloooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
oooooooooooooooooooooooodoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooodxkO0KKKKKKKKKKKKKKKKKKKKXKKXXKKKKKKKXXXXXXXK00OkkkOKXK00000KKKKKXXXXKKKKKXXXXXXXXXXXXX0kdlccccllllllllllllllllllllllllllcclllllloddxxxdxdddddkO0000000KKKKKXXKXXXKKK0xoooooooooooooooooooooooooooooooooooooollooddddoodddddddddddddddddddddoolodooooooooooooooooooooooooooooooooooooooooooooooooooooooooooodddoooooooooooo
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooddddddoodkO0KKKKKKKKKKKKKKKKKKKKKXXXXXXXXXXXXXXXXNNXNNNXKK00OkO0KXKKKXXXXXXXXNNXXXXNNNNNNNNXXXNNNNNX0kddocccccccccclllllllllllllloddoooollllllooxkxxxdddddxkO00000000KKKKKKKKKKKKOdoooooooooooooooooooooooooooooooooooooolooddddddddddooddddddddoddooddooloooooooooooooooooooooooooooooooooooooooooooooooooooooddddooodddooddooooooood
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | true |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/functions_test.go | functions_test.go | package core_test
import (
"context"
"crypto/rand"
"io"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/anypb"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/dispatcher"
"github.com/v2fly/v2ray-core/v5/app/proxyman"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/serial"
"github.com/v2fly/v2ray-core/v5/proxy/freedom"
"github.com/v2fly/v2ray-core/v5/testing/servers/tcp"
"github.com/v2fly/v2ray-core/v5/testing/servers/udp"
)
func xor(b []byte) []byte {
r := make([]byte, len(b))
for i, v := range b {
r[i] = v ^ 'c'
}
return r
}
func xor2(b []byte) []byte {
r := make([]byte, len(b))
for i, v := range b {
r[i] = v ^ 'd'
}
return r
}
func TestV2RayDial(t *testing.T) {
tcpServer := tcp.Server{
MsgProcessor: xor,
}
dest, err := tcpServer.Start()
common.Must(err)
defer tcpServer.Close()
config := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.InboundConfig{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
cfgBytes, err := proto.Marshal(config)
common.Must(err)
server, err := core.StartInstance(core.FormatProtobuf, cfgBytes)
common.Must(err)
defer server.Close()
conn, err := core.Dial(context.Background(), server, dest)
common.Must(err)
defer conn.Close()
const size = 10240 * 1024
payload := make([]byte, size)
common.Must2(rand.Read(payload))
if _, err := conn.Write(payload); err != nil {
t.Fatal(err)
}
receive := make([]byte, size)
if _, err := io.ReadFull(conn, receive); err != nil {
t.Fatal("failed to read all response: ", err)
}
if r := cmp.Diff(xor(receive), payload); r != "" {
t.Error(r)
}
}
func TestV2RayDialUDPConn(t *testing.T) {
udpServer := udp.Server{
MsgProcessor: xor,
}
dest, err := udpServer.Start()
common.Must(err)
defer udpServer.Close()
config := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.InboundConfig{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
cfgBytes, err := proto.Marshal(config)
common.Must(err)
server, err := core.StartInstance(core.FormatProtobuf, cfgBytes)
common.Must(err)
defer server.Close()
conn, err := core.Dial(context.Background(), server, dest)
common.Must(err)
defer conn.Close()
const size = 1024
payload := make([]byte, size)
common.Must2(rand.Read(payload))
for i := 0; i < 2; i++ {
if _, err := conn.Write(payload); err != nil {
t.Fatal(err)
}
}
time.Sleep(time.Millisecond * 500)
receive := make([]byte, size*2)
for i := 0; i < 2; i++ {
n, err := conn.Read(receive)
if err != nil {
t.Fatal("expect no error, but got ", err)
}
if n != size {
t.Fatal("expect read size ", size, " but got ", n)
}
if r := cmp.Diff(xor(receive[:n]), payload); r != "" {
t.Fatal(r)
}
}
}
func TestV2RayDialUDP(t *testing.T) {
udpServer1 := udp.Server{
MsgProcessor: xor,
}
dest1, err := udpServer1.Start()
common.Must(err)
defer udpServer1.Close()
udpServer2 := udp.Server{
MsgProcessor: xor2,
}
dest2, err := udpServer2.Start()
common.Must(err)
defer udpServer2.Close()
config := &core.Config{
App: []*anypb.Any{
serial.ToTypedMessage(&dispatcher.Config{}),
serial.ToTypedMessage(&proxyman.InboundConfig{}),
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
},
Outbound: []*core.OutboundHandlerConfig{
{
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
},
},
}
cfgBytes, err := proto.Marshal(config)
common.Must(err)
server, err := core.StartInstance(core.FormatProtobuf, cfgBytes)
common.Must(err)
defer server.Close()
conn, err := core.DialUDP(context.Background(), server)
common.Must(err)
defer conn.Close()
const size = 1024
{
payload := make([]byte, size)
common.Must2(rand.Read(payload))
if _, err := conn.WriteTo(payload, &net.UDPAddr{
IP: dest1.Address.IP(),
Port: int(dest1.Port),
}); err != nil {
t.Fatal(err)
}
receive := make([]byte, size)
if _, _, err := conn.ReadFrom(receive); err != nil {
t.Fatal(err)
}
if r := cmp.Diff(xor(receive), payload); r != "" {
t.Error(r)
}
}
{
payload := make([]byte, size)
common.Must2(rand.Read(payload))
if _, err := conn.WriteTo(payload, &net.UDPAddr{
IP: dest2.Address.IP(),
Port: int(dest2.Port),
}); err != nil {
t.Fatal(err)
}
receive := make([]byte, size)
if _, _, err := conn.ReadFrom(receive); err != nil {
t.Fatal(err)
}
if r := cmp.Diff(xor2(receive), payload); r != "" {
t.Error(r)
}
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/app.go | app/app.go | // Package app contains feature implementations of V2Ray. The features may be enabled during runtime.
package app
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/restfulapi/restful_api.go | app/restfulapi/restful_api.go | package restfulapi
import (
"net/http"
"strings"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/render"
"github.com/go-playground/validator/v10"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/transport/internet"
)
var validate *validator.Validate
type StatsBound struct { // Better name?
Uplink int64 `json:"uplink"`
Downlink int64 `json:"downlink"`
}
func (rs *restfulService) tagStats(w http.ResponseWriter, r *http.Request) {
boundType := chi.URLParam(r, "bound_type")
tag := chi.URLParam(r, "tag")
if validate.Var(boundType, "required,oneof=inbounds outbounds") != nil ||
validate.Var(tag, "required,min=1,max=255") != nil {
render.Status(r, http.StatusUnprocessableEntity)
render.JSON(w, r, render.M{})
return
}
bound := boundType[:len(boundType)-1]
upCounter := rs.stats.GetCounter(bound + ">>>" + tag + ">>>traffic>>>uplink")
downCounter := rs.stats.GetCounter(bound + ">>>" + tag + ">>>traffic>>>downlink")
if upCounter == nil || downCounter == nil {
render.Status(r, http.StatusNotFound)
render.JSON(w, r, render.M{})
return
}
render.JSON(w, r, &StatsBound{
Uplink: upCounter.Value(),
Downlink: downCounter.Value(),
})
}
func (rs *restfulService) version(w http.ResponseWriter, r *http.Request) {
render.JSON(w, r, render.M{"version": core.Version()})
}
func (rs *restfulService) TokenAuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
header := r.Header.Get("Authorization")
text := strings.SplitN(header, " ", 2)
hasInvalidHeader := text[0] != "Bearer"
hasInvalidSecret := len(text) != 2 || text[1] != rs.config.AuthToken
if hasInvalidHeader || hasInvalidSecret {
render.Status(r, http.StatusUnauthorized)
render.JSON(w, r, render.M{})
return
}
next.ServeHTTP(w, r)
})
}
func (rs *restfulService) start() error {
r := chi.NewRouter()
r.Use(middleware.Heartbeat("/ping"))
validate = validator.New()
r.Route("/v1", func(r chi.Router) {
r.Get("/{bound_type}/{tag}/stats", rs.tagStats)
})
r.Get("/version", rs.version)
var listener net.Listener
var err error
address := net.ParseAddress(rs.config.ListenAddr)
switch {
case address.Family().IsIP():
listener, err = internet.ListenSystem(rs.ctx, &net.TCPAddr{IP: address.IP(), Port: int(rs.config.ListenPort)}, nil)
case strings.EqualFold(address.Domain(), "localhost"):
listener, err = internet.ListenSystem(rs.ctx, &net.TCPAddr{IP: net.IP{127, 0, 0, 1}, Port: int(rs.config.ListenPort)}, nil)
default:
return newError("restful api cannot listen on the address: ", address)
}
if err != nil {
return newError("restful api cannot listen on the port ", rs.config.ListenPort).Base(err)
}
go func() {
err := http.Serve(listener, r)
if err != nil {
newError("unable to serve restful api").WriteToLog()
}
}()
return nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/restfulapi/errors.generated.go | app/restfulapi/errors.generated.go | package restfulapi
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/restfulapi/service.go | app/restfulapi/service.go | package restfulapi
import (
"context"
"net"
"sync"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/features"
feature_stats "github.com/v2fly/v2ray-core/v5/features/stats"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
type restfulService struct {
listener net.Listener
config *Config
access sync.Mutex
stats feature_stats.Manager
ctx context.Context
}
func (rs *restfulService) Type() interface{} {
return (*struct{})(nil)
}
func (rs *restfulService) Start() error {
defer rs.access.Unlock()
rs.access.Lock()
return rs.start()
}
func (rs *restfulService) Close() error {
defer rs.access.Unlock()
rs.access.Lock()
if rs.listener != nil {
return rs.listener.Close()
}
return nil
}
func (rs *restfulService) init(config *Config, stats feature_stats.Manager) {
rs.stats = stats
rs.config = config
}
func newRestfulService(ctx context.Context, config *Config) (features.Feature, error) {
r := new(restfulService)
r.ctx = ctx
if err := core.RequireFeatures(ctx, func(stats feature_stats.Manager) {
r.init(config, stats)
}); err != nil {
return nil, err
}
return r, nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/restfulapi/service_test.go | app/restfulapi/service_test.go | package restfulapi
import (
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
func TestTypeReturnAnonymousType(t *testing.T) {
service := restfulService{}
serviceType := service.Type()
assert.Empty(t, reflect.TypeOf(serviceType).Name(), "must return anonymous type")
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/restfulapi/config.go | app/restfulapi/config.go | package restfulapi
import (
"context"
"github.com/v2fly/v2ray-core/v5/common"
)
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return newRestfulService(ctx, config.(*Config))
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/restfulapi/config.pb.go | app/restfulapi/config.pb.go | package restfulapi
import (
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
ListenAddr string `protobuf:"bytes,1,opt,name=listen_addr,json=listenAddr,proto3" json:"listen_addr,omitempty"`
ListenPort int32 `protobuf:"varint,2,opt,name=listen_port,json=listenPort,proto3" json:"listen_port,omitempty"`
AuthToken string `protobuf:"bytes,3,opt,name=auth_token,json=authToken,proto3" json:"auth_token,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_app_restfulapi_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_app_restfulapi_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_app_restfulapi_config_proto_rawDescGZIP(), []int{0}
}
func (x *Config) GetListenAddr() string {
if x != nil {
return x.ListenAddr
}
return ""
}
func (x *Config) GetListenPort() int32 {
if x != nil {
return x.ListenPort
}
return 0
}
func (x *Config) GetAuthToken() string {
if x != nil {
return x.AuthToken
}
return ""
}
var File_app_restfulapi_config_proto protoreflect.FileDescriptor
const file_app_restfulapi_config_proto_rawDesc = "" +
"\n" +
"\x1bapp/restfulapi/config.proto\x12\x14v2ray.app.restfulapi\x1a common/protoext/extensions.proto\"\x84\x01\n" +
"\x06Config\x12\x1f\n" +
"\vlisten_addr\x18\x01 \x01(\tR\n" +
"listenAddr\x12\x1f\n" +
"\vlisten_port\x18\x02 \x01(\x05R\n" +
"listenPort\x12\x1d\n" +
"\n" +
"auth_token\x18\x03 \x01(\tR\tauthToken:\x19\x82\xb5\x18\x15\n" +
"\aservice\x12\n" +
"restfulapiBa\n" +
"\x1acom.v2ray.core.app.restapiP\x01Z-github.com/v2fly/v2ray-core/v5/app/restfulapi\xaa\x02\x11V2Ray.App.Restapib\x06proto3"
var (
file_app_restfulapi_config_proto_rawDescOnce sync.Once
file_app_restfulapi_config_proto_rawDescData []byte
)
func file_app_restfulapi_config_proto_rawDescGZIP() []byte {
file_app_restfulapi_config_proto_rawDescOnce.Do(func() {
file_app_restfulapi_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_restfulapi_config_proto_rawDesc), len(file_app_restfulapi_config_proto_rawDesc)))
})
return file_app_restfulapi_config_proto_rawDescData
}
var file_app_restfulapi_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_app_restfulapi_config_proto_goTypes = []any{
(*Config)(nil), // 0: v2ray.app.restfulapi.Config
}
var file_app_restfulapi_config_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_app_restfulapi_config_proto_init() }
func file_app_restfulapi_config_proto_init() {
if File_app_restfulapi_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_restfulapi_config_proto_rawDesc), len(file_app_restfulapi_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_app_restfulapi_config_proto_goTypes,
DependencyIndexes: file_app_restfulapi_config_proto_depIdxs,
MessageInfos: file_app_restfulapi_config_proto_msgTypes,
}.Build()
File_app_restfulapi_config_proto = out.File
file_app_restfulapi_config_proto_goTypes = nil
file_app_restfulapi_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/errors.generated.go | app/tun/errors.generated.go | package tun
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/option.go | app/tun/option.go | package tun
import (
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
"gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
"gvisor.dev/gvisor/pkg/tcpip/stack"
"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
"github.com/v2fly/v2ray-core/v5/app/router/routercommon"
)
func CreateNIC(id tcpip.NICID, linkEndpoint stack.LinkEndpoint) StackOption {
return func(s *stack.Stack) error {
if err := s.CreateNICWithOptions(id, linkEndpoint,
stack.NICOptions{
Disabled: false,
QDisc: nil,
}); err != nil {
return newError("failed to create NIC:", err)
}
return nil
}
}
func SetPromiscuousMode(id tcpip.NICID, enable bool) StackOption {
return func(s *stack.Stack) error {
if err := s.SetPromiscuousMode(id, enable); err != nil {
return newError("failed to set promiscuous mode:", err)
}
return nil
}
}
func SetSpoofing(id tcpip.NICID, enable bool) StackOption {
return func(s *stack.Stack) error {
if err := s.SetSpoofing(id, enable); err != nil {
return newError("failed to set spoofing:", err)
}
return nil
}
}
func AddProtocolAddress(id tcpip.NICID, ips []*routercommon.CIDR) StackOption {
return func(s *stack.Stack) error {
for _, ip := range ips {
tcpIPAddr := tcpip.AddrFrom4Slice(ip.Ip)
protocolAddress := tcpip.ProtocolAddress{
AddressWithPrefix: tcpip.AddressWithPrefix{
Address: tcpIPAddr,
PrefixLen: int(ip.Prefix),
},
}
switch tcpIPAddr.Len() {
case 4:
protocolAddress.Protocol = ipv4.ProtocolNumber
case 16:
protocolAddress.Protocol = ipv6.ProtocolNumber
default:
return newError("invalid IP address length:", tcpIPAddr.Len())
}
if err := s.AddProtocolAddress(id, protocolAddress, stack.AddressProperties{}); err != nil {
return newError("failed to add protocol address:", err)
}
}
return nil
}
}
func SetRouteTable(id tcpip.NICID, routes []*routercommon.CIDR) StackOption {
return func(s *stack.Stack) error {
s.SetRouteTable(func() (table []tcpip.Route) {
for _, cidrs := range routes {
subnet := tcpip.AddressWithPrefix{
Address: tcpip.AddrFrom4Slice(cidrs.Ip),
PrefixLen: int(cidrs.Prefix),
}.Subnet()
route := tcpip.Route{
Destination: subnet,
NIC: id,
}
table = append(table, route)
}
return
}())
return nil
}
}
func SetTCPSendBufferSize(size int) StackOption {
return func(s *stack.Stack) error {
sendBufferSizeRangeOption := tcpip.TCPSendBufferSizeRangeOption{Min: tcp.MinBufferSize, Default: size, Max: tcp.MaxBufferSize}
if err := s.SetTransportProtocolOption(tcp.ProtocolNumber, &sendBufferSizeRangeOption); err != nil {
return newError("failed to set tcp send buffer size:", err)
}
return nil
}
}
func SetTCPReceiveBufferSize(size int) StackOption {
return func(s *stack.Stack) error {
receiveBufferSizeRangeOption := tcpip.TCPReceiveBufferSizeRangeOption{Min: tcp.MinBufferSize, Default: size, Max: tcp.MaxBufferSize}
if err := s.SetTransportProtocolOption(tcp.ProtocolNumber, &receiveBufferSizeRangeOption); err != nil {
return newError("failed to set tcp receive buffer size:", err)
}
return nil
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/handler_udp.go | app/tun/handler_udp.go | package tun
import (
"context"
"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
"gvisor.dev/gvisor/pkg/tcpip/stack"
gvisor_udp "gvisor.dev/gvisor/pkg/tcpip/transport/udp"
"gvisor.dev/gvisor/pkg/waiter"
tun_net "github.com/v2fly/v2ray-core/v5/app/tun/net"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
udp_proto "github.com/v2fly/v2ray-core/v5/common/protocol/udp"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/features/routing"
"github.com/v2fly/v2ray-core/v5/transport/internet/udp"
)
type UDPHandler struct {
ctx context.Context
dispatcher routing.Dispatcher
policyManager policy.Manager
config *Config
}
type udpConn struct {
*gonet.UDPConn
id stack.TransportEndpointID
}
func (c *udpConn) ID() *stack.TransportEndpointID {
return &c.id
}
func SetUDPHandler(ctx context.Context, dispatcher routing.Dispatcher, policyManager policy.Manager, config *Config) StackOption {
return func(s *stack.Stack) error {
udpForwarder := gvisor_udp.NewForwarder(s, func(r *gvisor_udp.ForwarderRequest) {
wg := new(waiter.Queue)
linkedEndpoint, err := r.CreateEndpoint(wg)
if err != nil {
newError("failed to create endpoint: ", err).WriteToLog(session.ExportIDToError(ctx))
return
}
conn := &udpConn{
UDPConn: gonet.NewUDPConn(s, wg, linkedEndpoint),
id: r.ID(),
}
handler := &UDPHandler{
ctx: ctx,
dispatcher: dispatcher,
policyManager: policyManager,
config: config,
}
go handler.Handle(conn)
})
s.SetTransportProtocolHandler(gvisor_udp.ProtocolNumber, udpForwarder.HandlePacket)
return nil
}
}
func (h *UDPHandler) Handle(conn tun_net.UDPConn) error {
defer conn.Close()
id := conn.ID()
ctx := session.ContextWithInbound(h.ctx, &session.Inbound{Tag: h.config.Tag})
content := new(session.Content)
if h.config.SniffingSettings != nil {
content.SniffingRequest.Enabled = h.config.SniffingSettings.Enabled
content.SniffingRequest.OverrideDestinationForProtocol = h.config.SniffingSettings.DestinationOverride
content.SniffingRequest.MetadataOnly = h.config.SniffingSettings.MetadataOnly
}
ctx = session.ContextWithContent(ctx, content)
udpDispatcherConstructor := udp.NewSplitDispatcher
dest := net.UDPDestination(tun_net.AddressFromTCPIPAddr(id.LocalAddress), net.Port(id.LocalPort))
src := net.UDPDestination(tun_net.AddressFromTCPIPAddr(id.RemoteAddress), net.Port(id.RemotePort))
udpServer := udpDispatcherConstructor(h.dispatcher, func(ctx context.Context, packet *udp_proto.Packet) {
if _, err := conn.WriteTo(packet.Payload.Bytes(), &net.UDPAddr{
IP: src.Address.IP(),
Port: int(src.Port),
}); err != nil {
newError("failed to write UDP packet").Base(err).WriteToLog()
}
})
for {
select {
case <-ctx.Done():
return nil
default:
var buffer [2048]byte
n, _, err := conn.ReadFrom(buffer[:])
if err != nil {
return newError("failed to read UDP packet").Base(err)
}
currentPacketCtx := ctx
udpServer.Dispatch(currentPacketCtx, dest, buf.FromBytes(buffer[:n]))
}
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/packetaddradaptar.go | app/tun/packetaddradaptar.go | package tun
import (
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/stack"
"github.com/v2fly/v2ray-core/v5/app/tun/device"
"github.com/v2fly/v2ray-core/v5/app/tun/tunsorter"
)
func NewDeviceWithSorter(overlay device.Device, sorter *tunsorter.TunSorter) device.Device {
return &packetAddrDevice{
Device: overlay,
sorter: sorter,
}
}
type packetAddrDevice struct {
device.Device
sorter *tunsorter.TunSorter
secondaryDispatcher stack.NetworkDispatcher
}
func (p *packetAddrDevice) DeliverNetworkPacket(protocol tcpip.NetworkProtocolNumber, pkt stack.PacketBufferPtr) {
buf := pkt.ToBuffer()
_, err := p.sorter.OnPacketReceived(buf.Flatten())
if err != nil {
p.secondaryDispatcher.DeliverNetworkPacket(protocol, pkt)
}
}
func (p *packetAddrDevice) DeliverLinkPacket(protocol tcpip.NetworkProtocolNumber, pkt stack.PacketBufferPtr) {
// TODO implement me
panic("implement me")
}
func (p *packetAddrDevice) Attach(dispatcher stack.NetworkDispatcher) {
p.secondaryDispatcher = dispatcher
p.Device.Attach(p)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/stack.go | app/tun/stack.go | package tun
import (
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
"gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
"gvisor.dev/gvisor/pkg/tcpip/stack"
"gvisor.dev/gvisor/pkg/tcpip/transport/icmp"
"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
"gvisor.dev/gvisor/pkg/tcpip/transport/udp"
)
type StackOption func(*stack.Stack) error
func (t *TUN) CreateStack(linkedEndpoint stack.LinkEndpoint) (*stack.Stack, error) {
s := stack.New(stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{
ipv4.NewProtocol,
ipv6.NewProtocol,
},
TransportProtocols: []stack.TransportProtocolFactory{
tcp.NewProtocol,
udp.NewProtocol,
icmp.NewProtocol4,
icmp.NewProtocol6,
},
})
nicID := tcpip.NICID(s.UniqueID())
opts := []StackOption{
SetTCPHandler(t.ctx, t.dispatcher, t.policyManager, t.config),
SetUDPHandler(t.ctx, t.dispatcher, t.policyManager, t.config),
CreateNIC(nicID, linkedEndpoint),
AddProtocolAddress(nicID, t.config.Ips),
SetRouteTable(nicID, t.config.Routes),
SetPromiscuousMode(nicID, t.config.EnablePromiscuousMode),
SetSpoofing(nicID, t.config.EnableSpoofing),
}
if t.config.SocketSettings != nil {
if size := t.config.SocketSettings.TxBufSize; size != 0 {
opts = append(opts, SetTCPSendBufferSize(int(size)))
}
if size := t.config.SocketSettings.RxBufSize; size != 0 {
opts = append(opts, SetTCPReceiveBufferSize(int(size)))
}
}
for _, opt := range opts {
if err := opt(s); err != nil {
return nil, err
}
}
return s, nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/handler_tcp.go | app/tun/handler_tcp.go | package tun
import (
"context"
"time"
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"
"gvisor.dev/gvisor/pkg/tcpip/header"
"gvisor.dev/gvisor/pkg/tcpip/stack"
"gvisor.dev/gvisor/pkg/tcpip/transport/tcp"
"gvisor.dev/gvisor/pkg/waiter"
tun_net "github.com/v2fly/v2ray-core/v5/app/tun/net"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/log"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/signal"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/features/routing"
internet "github.com/v2fly/v2ray-core/v5/transport/internet"
)
const (
rcvWnd = 0 // default settings
maxInFlight = 2 << 10
)
type tcpConn struct {
*gonet.TCPConn
id stack.TransportEndpointID
}
func (c *tcpConn) ID() *stack.TransportEndpointID {
return &c.id
}
type TCPHandler struct {
ctx context.Context
dispatcher routing.Dispatcher
policyManager policy.Manager
config *Config
}
func SetTCPHandler(ctx context.Context, dispatcher routing.Dispatcher, policyManager policy.Manager, config *Config) StackOption {
return func(s *stack.Stack) error {
tcpForwarder := tcp.NewForwarder(s, rcvWnd, maxInFlight, func(r *tcp.ForwarderRequest) {
wg := new(waiter.Queue)
linkedEndpoint, err := r.CreateEndpoint(wg)
if err != nil {
r.Complete(true)
return
}
defer r.Complete(false)
if config.SocketSettings != nil {
if err := applySocketOptions(s, linkedEndpoint, config.SocketSettings); err != nil {
newError("failed to apply socket options: ", err).WriteToLog(session.ExportIDToError(ctx))
}
}
conn := &tcpConn{
TCPConn: gonet.NewTCPConn(wg, linkedEndpoint),
id: r.ID(),
}
handler := &TCPHandler{
ctx: ctx,
dispatcher: dispatcher,
policyManager: policyManager,
config: config,
}
go handler.Handle(conn)
})
s.SetTransportProtocolHandler(tcp.ProtocolNumber, tcpForwarder.HandlePacket)
return nil
}
}
func (h *TCPHandler) Handle(conn tun_net.TCPConn) error {
defer conn.Close()
id := conn.ID()
ctx := session.ContextWithInbound(h.ctx, &session.Inbound{Tag: h.config.Tag})
sessionPolicy := h.policyManager.ForLevel(h.config.UserLevel)
dest := net.TCPDestination(tun_net.AddressFromTCPIPAddr(id.LocalAddress), net.Port(id.LocalPort))
src := net.TCPDestination(tun_net.AddressFromTCPIPAddr(id.RemoteAddress), net.Port(id.RemotePort))
ctx = log.ContextWithAccessMessage(ctx, &log.AccessMessage{
From: src,
To: dest,
Status: log.AccessAccepted,
Reason: "",
})
content := new(session.Content)
if h.config.SniffingSettings != nil {
content.SniffingRequest.Enabled = h.config.SniffingSettings.Enabled
content.SniffingRequest.OverrideDestinationForProtocol = h.config.SniffingSettings.DestinationOverride
content.SniffingRequest.MetadataOnly = h.config.SniffingSettings.MetadataOnly
}
ctx = session.ContextWithContent(ctx, content)
ctx, cancel := context.WithCancel(ctx)
timer := signal.CancelAfterInactivity(ctx, cancel, sessionPolicy.Timeouts.ConnectionIdle)
link, err := h.dispatcher.Dispatch(ctx, dest)
if err != nil {
return newError("failed to dispatch").Base(err)
}
responseDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.UplinkOnly)
if err := buf.Copy(link.Reader, buf.NewWriter(conn), buf.UpdateActivity(timer)); err != nil {
return newError("failed to transport all TCP response").Base(err)
}
return nil
}
requestDone := func() error {
defer timer.SetTimeout(sessionPolicy.Timeouts.DownlinkOnly)
if err := buf.Copy(buf.NewReader(conn), link.Writer, buf.UpdateActivity(timer)); err != nil {
return newError("failed to transport all TCP request").Base(err)
}
return nil
}
requestDoneAndCloseWriter := task.OnSuccess(requestDone, task.Close(link.Writer))
if err := task.Run(h.ctx, requestDoneAndCloseWriter, responseDone); err != nil {
common.Interrupt(link.Reader)
common.Interrupt(link.Writer)
return newError("connection ends").Base(err)
}
return nil
}
func applySocketOptions(s *stack.Stack, endpoint tcpip.Endpoint, config *internet.SocketConfig) tcpip.Error {
if config.TcpKeepAliveInterval > 0 {
interval := tcpip.KeepaliveIntervalOption(time.Duration(config.TcpKeepAliveInterval) * time.Second)
if err := endpoint.SetSockOpt(&interval); err != nil {
return err
}
}
if config.TcpKeepAliveIdle > 0 {
idle := tcpip.KeepaliveIdleOption(time.Duration(config.TcpKeepAliveIdle) * time.Second)
if err := endpoint.SetSockOpt(&idle); err != nil {
return err
}
}
if config.TcpKeepAliveInterval > 0 || config.TcpKeepAliveIdle > 0 {
endpoint.SocketOptions().SetKeepAlive(true)
}
{
var sendBufferSizeRangeOption tcpip.TCPSendBufferSizeRangeOption
if err := s.TransportProtocolOption(header.TCPProtocolNumber, &sendBufferSizeRangeOption); err == nil {
endpoint.SocketOptions().SetReceiveBufferSize(int64(sendBufferSizeRangeOption.Default), false)
}
var receiveBufferSizeRangeOption tcpip.TCPReceiveBufferSizeRangeOption
if err := s.TransportProtocolOption(header.TCPProtocolNumber, &receiveBufferSizeRangeOption); err == nil {
endpoint.SocketOptions().SetSendBufferSize(int64(receiveBufferSizeRangeOption.Default), false)
}
}
return nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/config.pb.go | app/tun/config.pb.go | package tun
import (
proxyman "github.com/v2fly/v2ray-core/v5/app/proxyman"
routercommon "github.com/v2fly/v2ray-core/v5/app/router/routercommon"
packetaddr "github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
internet "github.com/v2fly/v2ray-core/v5/transport/internet"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Mtu uint32 `protobuf:"varint,2,opt,name=mtu,proto3" json:"mtu,omitempty"`
UserLevel uint32 `protobuf:"varint,3,opt,name=user_level,json=userLevel,proto3" json:"user_level,omitempty"`
PacketEncoding packetaddr.PacketAddrType `protobuf:"varint,4,opt,name=packet_encoding,json=packetEncoding,proto3,enum=v2ray.core.net.packetaddr.PacketAddrType" json:"packet_encoding,omitempty"`
Tag string `protobuf:"bytes,5,opt,name=tag,proto3" json:"tag,omitempty"`
Ips []*routercommon.CIDR `protobuf:"bytes,6,rep,name=ips,proto3" json:"ips,omitempty"`
Routes []*routercommon.CIDR `protobuf:"bytes,7,rep,name=routes,proto3" json:"routes,omitempty"`
EnablePromiscuousMode bool `protobuf:"varint,8,opt,name=enable_promiscuous_mode,json=enablePromiscuousMode,proto3" json:"enable_promiscuous_mode,omitempty"`
EnableSpoofing bool `protobuf:"varint,9,opt,name=enable_spoofing,json=enableSpoofing,proto3" json:"enable_spoofing,omitempty"`
SocketSettings *internet.SocketConfig `protobuf:"bytes,10,opt,name=socket_settings,json=socketSettings,proto3" json:"socket_settings,omitempty"`
SniffingSettings *proxyman.SniffingConfig `protobuf:"bytes,11,opt,name=sniffing_settings,json=sniffingSettings,proto3" json:"sniffing_settings,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_app_tun_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_app_tun_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_app_tun_config_proto_rawDescGZIP(), []int{0}
}
func (x *Config) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *Config) GetMtu() uint32 {
if x != nil {
return x.Mtu
}
return 0
}
func (x *Config) GetUserLevel() uint32 {
if x != nil {
return x.UserLevel
}
return 0
}
func (x *Config) GetPacketEncoding() packetaddr.PacketAddrType {
if x != nil {
return x.PacketEncoding
}
return packetaddr.PacketAddrType(0)
}
func (x *Config) GetTag() string {
if x != nil {
return x.Tag
}
return ""
}
func (x *Config) GetIps() []*routercommon.CIDR {
if x != nil {
return x.Ips
}
return nil
}
func (x *Config) GetRoutes() []*routercommon.CIDR {
if x != nil {
return x.Routes
}
return nil
}
func (x *Config) GetEnablePromiscuousMode() bool {
if x != nil {
return x.EnablePromiscuousMode
}
return false
}
func (x *Config) GetEnableSpoofing() bool {
if x != nil {
return x.EnableSpoofing
}
return false
}
func (x *Config) GetSocketSettings() *internet.SocketConfig {
if x != nil {
return x.SocketSettings
}
return nil
}
func (x *Config) GetSniffingSettings() *proxyman.SniffingConfig {
if x != nil {
return x.SniffingSettings
}
return nil
}
var File_app_tun_config_proto protoreflect.FileDescriptor
const file_app_tun_config_proto_rawDesc = "" +
"\n" +
"\x14app/tun/config.proto\x12\x12v2ray.core.app.tun\x1a\x19app/proxyman/config.proto\x1a$app/router/routercommon/common.proto\x1a common/protoext/extensions.proto\x1a\"common/net/packetaddr/config.proto\x1a\x1ftransport/internet/config.proto\"\xd2\x04\n" +
"\x06Config\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\x12\x10\n" +
"\x03mtu\x18\x02 \x01(\rR\x03mtu\x12\x1d\n" +
"\n" +
"user_level\x18\x03 \x01(\rR\tuserLevel\x12R\n" +
"\x0fpacket_encoding\x18\x04 \x01(\x0e2).v2ray.core.net.packetaddr.PacketAddrTypeR\x0epacketEncoding\x12\x10\n" +
"\x03tag\x18\x05 \x01(\tR\x03tag\x12:\n" +
"\x03ips\x18\x06 \x03(\v2(.v2ray.core.app.router.routercommon.CIDRR\x03ips\x12@\n" +
"\x06routes\x18\a \x03(\v2(.v2ray.core.app.router.routercommon.CIDRR\x06routes\x126\n" +
"\x17enable_promiscuous_mode\x18\b \x01(\bR\x15enablePromiscuousMode\x12'\n" +
"\x0fenable_spoofing\x18\t \x01(\bR\x0eenableSpoofing\x12T\n" +
"\x0fsocket_settings\x18\n" +
" \x01(\v2+.v2ray.core.transport.internet.SocketConfigR\x0esocketSettings\x12T\n" +
"\x11sniffing_settings\x18\v \x01(\v2'.v2ray.core.app.proxyman.SniffingConfigR\x10sniffingSettings:\x12\x82\xb5\x18\x0e\n" +
"\aservice\x12\x03tunBW\n" +
"\x16com.v2ray.core.app.tunP\x01Z&github.com/v2fly/v2ray-core/v5/app/tun\xaa\x02\x12V2Ray.Core.App.Tunb\x06proto3"
var (
file_app_tun_config_proto_rawDescOnce sync.Once
file_app_tun_config_proto_rawDescData []byte
)
func file_app_tun_config_proto_rawDescGZIP() []byte {
file_app_tun_config_proto_rawDescOnce.Do(func() {
file_app_tun_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_tun_config_proto_rawDesc), len(file_app_tun_config_proto_rawDesc)))
})
return file_app_tun_config_proto_rawDescData
}
var file_app_tun_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_app_tun_config_proto_goTypes = []any{
(*Config)(nil), // 0: v2ray.core.app.tun.Config
(packetaddr.PacketAddrType)(0), // 1: v2ray.core.net.packetaddr.PacketAddrType
(*routercommon.CIDR)(nil), // 2: v2ray.core.app.router.routercommon.CIDR
(*internet.SocketConfig)(nil), // 3: v2ray.core.transport.internet.SocketConfig
(*proxyman.SniffingConfig)(nil), // 4: v2ray.core.app.proxyman.SniffingConfig
}
var file_app_tun_config_proto_depIdxs = []int32{
1, // 0: v2ray.core.app.tun.Config.packet_encoding:type_name -> v2ray.core.net.packetaddr.PacketAddrType
2, // 1: v2ray.core.app.tun.Config.ips:type_name -> v2ray.core.app.router.routercommon.CIDR
2, // 2: v2ray.core.app.tun.Config.routes:type_name -> v2ray.core.app.router.routercommon.CIDR
3, // 3: v2ray.core.app.tun.Config.socket_settings:type_name -> v2ray.core.transport.internet.SocketConfig
4, // 4: v2ray.core.app.tun.Config.sniffing_settings:type_name -> v2ray.core.app.proxyman.SniffingConfig
5, // [5:5] is the sub-list for method output_type
5, // [5:5] is the sub-list for method input_type
5, // [5:5] is the sub-list for extension type_name
5, // [5:5] is the sub-list for extension extendee
0, // [0:5] is the sub-list for field type_name
}
func init() { file_app_tun_config_proto_init() }
func file_app_tun_config_proto_init() {
if File_app_tun_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_tun_config_proto_rawDesc), len(file_app_tun_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_app_tun_config_proto_goTypes,
DependencyIndexes: file_app_tun_config_proto_depIdxs,
MessageInfos: file_app_tun_config_proto_msgTypes,
}.Build()
File_app_tun_config_proto = out.File
file_app_tun_config_proto_goTypes = nil
file_app_tun_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/handler.go | app/tun/handler.go | package tun
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/tun.go | app/tun/tun.go | //go:build !confonly
// +build !confonly
package tun
import (
"context"
"gvisor.dev/gvisor/pkg/tcpip/stack"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/app/tun/device"
"github.com/v2fly/v2ray-core/v5/app/tun/device/gvisor"
"github.com/v2fly/v2ray-core/v5/app/tun/tunsorter"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/features/routing"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
type TUN struct {
ctx context.Context
dispatcher routing.Dispatcher
policyManager policy.Manager
config *Config
stack *stack.Stack
}
func (t *TUN) Type() interface{} {
return (*TUN)(nil)
}
func (t *TUN) Start() error {
DeviceConstructor := gvisor.New
tunDevice, err := DeviceConstructor(device.Options{
Name: t.config.Name,
MTU: t.config.Mtu,
})
if err != nil {
return newError("failed to create device").Base(err).AtError()
}
if t.config.PacketEncoding != packetaddr.PacketAddrType_None {
writer := device.NewLinkWriterToWriter(tunDevice)
sorter := tunsorter.NewTunSorter(writer, t.dispatcher, t.config.PacketEncoding, t.ctx)
tunDeviceLayered := NewDeviceWithSorter(tunDevice, sorter)
tunDevice = tunDeviceLayered
}
stack, err := t.CreateStack(tunDevice)
if err != nil {
return newError("failed to create stack").Base(err).AtError()
}
t.stack = stack
return nil
}
func (t *TUN) Close() error {
if t.stack != nil {
t.stack.Close()
t.stack.Wait()
}
return nil
}
func (t *TUN) Init(ctx context.Context, config *Config, dispatcher routing.Dispatcher, policyManager policy.Manager) error {
t.ctx = ctx
t.config = config
t.dispatcher = dispatcher
t.policyManager = policyManager
return nil
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
tun := new(TUN)
err := core.RequireFeatures(ctx, func(d routing.Dispatcher, p policy.Manager) error {
return tun.Init(ctx, config.(*Config), d, p)
})
return tun, err
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/device/linkWriterToWriter.go | app/tun/device/linkWriterToWriter.go | package device
import (
"io"
"github.com/v2fly/v2ray-core/v5/common/errors"
"gvisor.dev/gvisor/pkg/buffer"
"gvisor.dev/gvisor/pkg/tcpip/stack"
)
func NewLinkWriterToWriter(writer stack.LinkWriter) io.Writer {
return &linkWriterToWriter{writer: writer}
}
type linkWriterToWriter struct {
writer stack.LinkWriter
}
func (l linkWriterToWriter) Write(p []byte) (n int, err error) {
buffer := buffer.MakeWithData(p)
packetBufferPtr := stack.NewPacketBuffer(stack.PacketBufferOptions{
Payload: buffer,
OnRelease: func() {
buffer.Release()
},
})
packetList := stack.PacketBufferList{}
packetList.PushBack(packetBufferPtr)
_, terr := l.writer.WritePackets(packetList)
if terr != nil {
return 0, newError("failed to write packet").Base(errors.New(terr.String())).AtError()
}
return len(p), nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/device/errors.generated.go | app/tun/device/errors.generated.go | package device
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/device/device.go | app/tun/device/device.go | package device
import (
"gvisor.dev/gvisor/pkg/tcpip/stack"
"github.com/v2fly/v2ray-core/v5/common"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
type Device interface {
stack.LinkEndpoint
common.Closable
}
type Options struct {
Name string
MTU uint32
}
type DeviceConstructor func(Options) (Device, error)
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/device/gvisor/errors.generated.go | app/tun/device/gvisor/errors.generated.go | package gvisor
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/device/gvisor/gvisor_others.go | app/tun/device/gvisor/gvisor_others.go | //go:build !linux || (linux && !(amd64 || arm64))
// +build !linux linux,!amd64,!arm64
package gvisor
import "github.com/v2fly/v2ray-core/v5/app/tun/device"
func New(options device.Options) (device.Device, error) {
return nil, newError("not supported").AtError()
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/device/gvisor/gvisor_linux.go | app/tun/device/gvisor/gvisor_linux.go | //go:build linux && ((linux && amd64) || (linux && arm64))
// +build linux
// +build linux,amd64 linux,arm64
package gvisor
import (
"fmt"
"unsafe"
"golang.org/x/sys/unix"
"gvisor.dev/gvisor/pkg/tcpip/stack"
"github.com/v2fly/v2ray-core/v5/app/tun/device"
"gvisor.dev/gvisor/pkg/tcpip/link/fdbased"
"gvisor.dev/gvisor/pkg/tcpip/link/rawfile"
"gvisor.dev/gvisor/pkg/tcpip/link/tun"
)
const (
ifReqSize = unix.IFNAMSIZ + 64
)
type GvisorTUN struct {
stack.LinkEndpoint
options device.Options
fd int
mtu uint32 // real MTU
}
func New(options device.Options) (device.Device, error) {
t := &GvisorTUN{options: options}
if len(options.Name) > unix.IFNAMSIZ {
return nil, newError("name too long").AtError()
}
fd, err := tun.Open(options.Name)
if err != nil {
return nil, newError("failed to open tun device").Base(err).AtError()
}
t.fd = fd
if options.MTU > 0 {
setMTU(options.Name, int(options.MTU))
}
mtu, err := rawfile.GetMTU(options.Name)
if err != nil {
return nil, newError("failed to get mtu").Base(err).AtError()
}
t.mtu = mtu
linkEndpoint, err := fdbased.New(&fdbased.Options{
FDs: []int{fd},
MTU: mtu,
// TUN is not need to process ethernet header.
EthernetHeader: false,
// Readv is the default dispatch mode and is the least performant of the
// dispatch options but the one that is supported by all underlying FD
// types.
PacketDispatchMode: fdbased.Readv,
MaxSyscallHeaderBytes: 0x00,
})
if err != nil {
return nil, newError("failed to create link endpoint").Base(err).AtError()
}
t.LinkEndpoint = linkEndpoint
return t, nil
}
func (t *GvisorTUN) Close() error {
return unix.Close(t.fd)
}
// Modified from golang.zx2c4.com/wireguard/tun/tun_linux.go
func setMTU(name string, n int) error {
// open datagram socket
fd, err := unix.Socket(
unix.AF_INET,
unix.SOCK_DGRAM|unix.SOCK_CLOEXEC,
0,
)
if err != nil {
return err
}
defer unix.Close(fd)
// do ioctl call
var ifr [ifReqSize]byte
copy(ifr[:], name)
*(*uint32)(unsafe.Pointer(&ifr[unix.IFNAMSIZ])) = uint32(n)
_, _, errno := unix.Syscall(
unix.SYS_IOCTL,
uintptr(fd),
uintptr(unix.SIOCSIFMTU),
uintptr(unsafe.Pointer(&ifr[0])),
)
if errno != 0 {
return fmt.Errorf("failed to set MTU of TUN device: %w", errno)
}
return nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/device/gvisor/gvisor.go | app/tun/device/gvisor/gvisor.go | package gvisor
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/tunsorter/tunsorter.go | app/tun/tunsorter/tunsorter.go | package tunsorter
import (
"context"
"io"
"sync"
"github.com/v2fly/v2ray-core/v5/app/tun/packetparse"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/net/packetaddr"
vudp "github.com/v2fly/v2ray-core/v5/common/protocol/udp"
"github.com/v2fly/v2ray-core/v5/features/routing"
"github.com/v2fly/v2ray-core/v5/transport/internet/udp"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
func NewTunSorter(tunWriter io.Writer, dispatcher routing.Dispatcher, packetAddrType packetaddr.PacketAddrType, ctx context.Context) *TunSorter {
return &TunSorter{
tunWriter: tunWriter,
dispatcher: dispatcher,
packetAddrType: packetAddrType,
ctx: ctx,
}
}
type TunSorter struct {
tunWriter io.Writer
dispatcher routing.Dispatcher
packetAddrType packetaddr.PacketAddrType
trackedConnections sync.Map
ctx context.Context
}
func (t *TunSorter) OnPacketReceived(b []byte) (n int, err error) {
src, dst, data, err := packetparse.TryParseAsUDPPacket(b)
if err != nil {
return 0, err
}
conn := newTrackedUDPConnection(src, t)
trackedConnection, loaded := t.trackedConnections.LoadOrStore(src.String(), conn)
conn = trackedConnection.(*trackedUDPConnection)
if !loaded {
t.onNewConnection(conn)
}
conn.onNewPacket(dst, data)
return len(b), nil
}
func (t *TunSorter) onNewConnection(connection *trackedUDPConnection) {
udpDispatcherConstructor := udp.NewSplitDispatcher
switch t.packetAddrType { // nolint: gocritic
case packetaddr.PacketAddrType_Packet:
ctx := context.WithValue(t.ctx, udp.DispatcherConnectionTerminationSignalReceiverMark, connection) // nolint:staticcheck
packetAddrDispatcherFactory := udp.NewPacketAddrDispatcherCreator(ctx)
udpDispatcherConstructor = packetAddrDispatcherFactory.NewPacketAddrDispatcher
}
udpDispatcher := udpDispatcherConstructor(t.dispatcher, func(ctx context.Context, packet *vudp.Packet) {
connection.onWritePacket(packet.Source, packet.Payload.Bytes())
})
connection.packetDispatcher = udpDispatcher
}
func (t *TunSorter) onWritePacket(src net.Destination, dest net.Destination, data []byte) {
data, err := packetparse.TryConstructUDPPacket(src, dest, data)
if err != nil {
newError("failed to construct udp packet").Base(err).WriteToLog()
return
}
_, err = t.tunWriter.Write(data)
if err != nil {
newError("failed to write udp packet to tun").Base(err).WriteToLog()
return
}
}
func newTrackedUDPConnection(src net.Destination, tunSorter *TunSorter) *trackedUDPConnection {
return &trackedUDPConnection{
tunSorter: tunSorter,
src: src,
}
}
type trackedUDPConnection struct {
packetDispatcher udp.DispatcherI
tunSorter *TunSorter
src net.Destination
}
func (t *trackedUDPConnection) onNewPacket(dst net.Destination, data []byte) {
t.packetDispatcher.Dispatch(context.Background(), dst, buf.FromBytes(data))
}
func (t *trackedUDPConnection) onWritePacket(src net.Destination, data []byte) {
t.tunSorter.onWritePacket(src, t.src, data)
}
func (t *trackedUDPConnection) Close() error {
t.tunSorter.trackedConnections.Delete(t.src.String())
return nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/tunsorter/errors.generated.go | app/tun/tunsorter/errors.generated.go | package tunsorter
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/net/net.go | app/tun/net/net.go | package net
import (
"github.com/v2fly/v2ray-core/v5/common/net"
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/stack"
)
type TCPConn interface {
net.Conn
ID() *stack.TransportEndpointID
}
type UDPConn interface {
net.Conn
net.PacketConn
ID() *stack.TransportEndpointID
}
func AddressFromTCPIPAddr(addr tcpip.Address) net.Address {
return net.IPAddress(addr.AsSlice())
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/packetparse/errors.generated.go | app/tun/packetparse/errors.generated.go | package packetparse
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/packetparse/packetParse.go | app/tun/packetparse/packetParse.go | package packetparse
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/tun/packetparse/udp.go | app/tun/packetparse/udp.go | package packetparse
import (
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/v2fly/v2ray-core/v5/common/net"
)
var (
errNotIPPacket = newError("not an IP packet")
errNotUDPPacket = newError("not a UDP packet")
)
var nullDestination = net.UnixDestination(net.DomainAddress("null"))
func TryParseAsUDPPacket(packet []byte) (src, dst net.Destination, data []byte, err error) {
parsedPacket := gopacket.NewPacket(packet, layers.LayerTypeIPv4, gopacket.DecodeOptions{
Lazy: true,
NoCopy: false,
SkipDecodeRecovery: false,
DecodeStreamsAsDatagrams: false,
})
var srcIP net.Address
var dstIP net.Address
ipv4Layer := parsedPacket.Layer(layers.LayerTypeIPv4)
if ipv4Layer == nil {
parsedPacketAsIPv6 := gopacket.NewPacket(packet, layers.LayerTypeIPv6, gopacket.DecodeOptions{
Lazy: true,
NoCopy: false,
SkipDecodeRecovery: false,
DecodeStreamsAsDatagrams: false,
})
ipv6Layer := parsedPacketAsIPv6.Layer(layers.LayerTypeIPv6)
if ipv6Layer == nil {
return nullDestination, nullDestination, nil, errNotIPPacket
}
ipv6 := ipv6Layer.(*layers.IPv6)
srcIP = net.IPAddress(ipv6.SrcIP)
dstIP = net.IPAddress(ipv6.DstIP)
parsedPacket = parsedPacketAsIPv6
} else {
ipv4 := ipv4Layer.(*layers.IPv4)
srcIP = net.IPAddress(ipv4.SrcIP)
dstIP = net.IPAddress(ipv4.DstIP)
}
udpLayer := parsedPacket.Layer(layers.LayerTypeUDP)
if udpLayer == nil {
return nullDestination, nullDestination, nil, errNotUDPPacket
}
udp := udpLayer.(*layers.UDP)
srcPort := net.Port(udp.SrcPort)
dstPort := net.Port(udp.DstPort)
src = net.UDPDestination(srcIP, srcPort)
dst = net.UDPDestination(dstIP, dstPort)
data = udp.Payload
return // nolint: nakedret
}
func TryConstructUDPPacket(src, dst net.Destination, data []byte) ([]byte, error) {
if src.Address.Family().IsIPv4() && dst.Address.Family().IsIPv4() {
return constructIPv4UDPPacket(src, dst, data)
}
if src.Address.Family().IsIPv6() && dst.Address.Family().IsIPv6() {
return constructIPv6UDPPacket(src, dst, data)
}
return nil, newError("not supported")
}
func constructIPv4UDPPacket(src, dst net.Destination, data []byte) ([]byte, error) {
ipv4 := &layers.IPv4{
Version: 4,
Protocol: layers.IPProtocolUDP,
SrcIP: src.Address.IP(),
DstIP: dst.Address.IP(),
TTL: 64, // set TTL to a reasonable non-zero value to allow non-local routing
}
udp := &layers.UDP{
SrcPort: layers.UDPPort(src.Port),
DstPort: layers.UDPPort(dst.Port),
}
err := udp.SetNetworkLayerForChecksum(ipv4)
if err != nil {
return nil, err
}
buffer := gopacket.NewSerializeBuffer()
if err := gopacket.SerializeLayers(buffer, gopacket.SerializeOptions{
FixLengths: true,
ComputeChecksums: true,
}, ipv4, udp, gopacket.Payload(data)); err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
func constructIPv6UDPPacket(src, dst net.Destination, data []byte) ([]byte, error) {
ipv6 := &layers.IPv6{
Version: 6,
NextHeader: layers.IPProtocolUDP,
SrcIP: src.Address.IP(),
DstIP: dst.Address.IP(),
HopLimit: 64,
}
udp := &layers.UDP{
SrcPort: layers.UDPPort(src.Port),
DstPort: layers.UDPPort(dst.Port),
}
err := udp.SetNetworkLayerForChecksum(ipv6)
if err != nil {
return nil, err
}
buffer := gopacket.NewSerializeBuffer()
if err := gopacket.SerializeLayers(buffer, gopacket.SerializeOptions{
FixLengths: true,
ComputeChecksums: true,
}, ipv6, udp, gopacket.Payload(data)); err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/instman/instman.go | app/instman/instman.go | package instman
import (
"context"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/features/extension"
)
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
type InstanceMgr struct {
config *Config // nolint: structcheck
instances map[string]*core.Instance
}
func (i InstanceMgr) Type() interface{} {
return extension.InstanceManagementType()
}
func (i InstanceMgr) Start() error {
return nil
}
func (i InstanceMgr) Close() error {
return nil
}
func (i InstanceMgr) ListInstance(ctx context.Context) ([]string, error) {
var instanceNames []string
for k := range i.instances {
instanceNames = append(instanceNames, k)
}
return instanceNames, nil
}
func (i InstanceMgr) AddInstance(ctx context.Context, name string, config []byte, configType string) error {
coreConfig, err := core.LoadConfig(configType, config)
if err != nil {
return newError("unable to load config").Base(err)
}
instance, err := core.New(coreConfig)
if err != nil {
return newError("unable to create instance").Base(err)
}
i.instances[name] = instance
return nil
}
func (i InstanceMgr) StartInstance(ctx context.Context, name string) error {
err := i.instances[name].Start()
if err != nil {
return newError("failed to start instance").Base(err)
}
return nil
}
func (i InstanceMgr) StopInstance(ctx context.Context, name string) error {
err := i.instances[name].Close()
if err != nil {
return newError("failed to stop instance").Base(err)
}
return nil
}
func (i InstanceMgr) UntrackInstance(ctx context.Context, name string) error {
delete(i.instances, name)
return nil
}
func NewInstanceMgr(ctx context.Context, config *Config) (extension.InstanceManagement, error) {
return InstanceMgr{instances: map[string]*core.Instance{}}, nil
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
var f extension.InstanceManagement
var err error
if f, err = NewInstanceMgr(ctx, config.(*Config)); err != nil {
return nil, err
}
return f, nil
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/instman/errors.generated.go | app/instman/errors.generated.go | package instman
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/instman/config.pb.go | app/instman/config.pb.go | package instman
import (
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_app_instman_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_app_instman_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_app_instman_config_proto_rawDescGZIP(), []int{0}
}
var File_app_instman_config_proto protoreflect.FileDescriptor
const file_app_instman_config_proto_rawDesc = "" +
"\n" +
"\x18app/instman/config.proto\x12\x16v2ray.core.app.instman\x1a common/protoext/extensions.proto\" \n" +
"\x06Config:\x16\x82\xb5\x18\x12\n" +
"\aservice\x12\ainstmanBc\n" +
"\x1acom.v2ray.core.app.instmanP\x01Z*github.com/v2fly/v2ray-core/v5/app/instman\xaa\x02\x16V2Ray.Core.App.Instmanb\x06proto3"
var (
file_app_instman_config_proto_rawDescOnce sync.Once
file_app_instman_config_proto_rawDescData []byte
)
func file_app_instman_config_proto_rawDescGZIP() []byte {
file_app_instman_config_proto_rawDescOnce.Do(func() {
file_app_instman_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_instman_config_proto_rawDesc), len(file_app_instman_config_proto_rawDesc)))
})
return file_app_instman_config_proto_rawDescData
}
var file_app_instman_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_app_instman_config_proto_goTypes = []any{
(*Config)(nil), // 0: v2ray.core.app.instman.Config
}
var file_app_instman_config_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_app_instman_config_proto_init() }
func file_app_instman_config_proto_init() {
if File_app_instman_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_instman_config_proto_rawDesc), len(file_app_instman_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_app_instman_config_proto_goTypes,
DependencyIndexes: file_app_instman_config_proto_depIdxs,
MessageInfos: file_app_instman_config_proto_msgTypes,
}.Build()
File_app_instman_config_proto = out.File
file_app_instman_config_proto_goTypes = nil
file_app_instman_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/instman/command/command.pb.go | app/instman/command/command.pb.go | package command
import (
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type ListInstanceReq struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ListInstanceReq) Reset() {
*x = ListInstanceReq{}
mi := &file_app_instman_command_command_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ListInstanceReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ListInstanceReq) ProtoMessage() {}
func (x *ListInstanceReq) ProtoReflect() protoreflect.Message {
mi := &file_app_instman_command_command_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ListInstanceReq.ProtoReflect.Descriptor instead.
func (*ListInstanceReq) Descriptor() ([]byte, []int) {
return file_app_instman_command_command_proto_rawDescGZIP(), []int{0}
}
type ListInstanceResp struct {
state protoimpl.MessageState `protogen:"open.v1"`
Name []string `protobuf:"bytes,1,rep,name=name,proto3" json:"name,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ListInstanceResp) Reset() {
*x = ListInstanceResp{}
mi := &file_app_instman_command_command_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ListInstanceResp) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ListInstanceResp) ProtoMessage() {}
func (x *ListInstanceResp) ProtoReflect() protoreflect.Message {
mi := &file_app_instman_command_command_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ListInstanceResp.ProtoReflect.Descriptor instead.
func (*ListInstanceResp) Descriptor() ([]byte, []int) {
return file_app_instman_command_command_proto_rawDescGZIP(), []int{1}
}
func (x *ListInstanceResp) GetName() []string {
if x != nil {
return x.Name
}
return nil
}
type AddInstanceReq struct {
state protoimpl.MessageState `protogen:"open.v1"`
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
ConfigType string `protobuf:"bytes,2,opt,name=configType,proto3" json:"configType,omitempty"`
ConfigContentB64 string `protobuf:"bytes,3,opt,name=configContentB64,proto3" json:"configContentB64,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *AddInstanceReq) Reset() {
*x = AddInstanceReq{}
mi := &file_app_instman_command_command_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *AddInstanceReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddInstanceReq) ProtoMessage() {}
func (x *AddInstanceReq) ProtoReflect() protoreflect.Message {
mi := &file_app_instman_command_command_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddInstanceReq.ProtoReflect.Descriptor instead.
func (*AddInstanceReq) Descriptor() ([]byte, []int) {
return file_app_instman_command_command_proto_rawDescGZIP(), []int{2}
}
func (x *AddInstanceReq) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *AddInstanceReq) GetConfigType() string {
if x != nil {
return x.ConfigType
}
return ""
}
func (x *AddInstanceReq) GetConfigContentB64() string {
if x != nil {
return x.ConfigContentB64
}
return ""
}
type AddInstanceResp struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *AddInstanceResp) Reset() {
*x = AddInstanceResp{}
mi := &file_app_instman_command_command_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *AddInstanceResp) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddInstanceResp) ProtoMessage() {}
func (x *AddInstanceResp) ProtoReflect() protoreflect.Message {
mi := &file_app_instman_command_command_proto_msgTypes[3]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddInstanceResp.ProtoReflect.Descriptor instead.
func (*AddInstanceResp) Descriptor() ([]byte, []int) {
return file_app_instman_command_command_proto_rawDescGZIP(), []int{3}
}
type StartInstanceReq struct {
state protoimpl.MessageState `protogen:"open.v1"`
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *StartInstanceReq) Reset() {
*x = StartInstanceReq{}
mi := &file_app_instman_command_command_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *StartInstanceReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*StartInstanceReq) ProtoMessage() {}
func (x *StartInstanceReq) ProtoReflect() protoreflect.Message {
mi := &file_app_instman_command_command_proto_msgTypes[4]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use StartInstanceReq.ProtoReflect.Descriptor instead.
func (*StartInstanceReq) Descriptor() ([]byte, []int) {
return file_app_instman_command_command_proto_rawDescGZIP(), []int{4}
}
func (x *StartInstanceReq) GetName() string {
if x != nil {
return x.Name
}
return ""
}
type StartInstanceResp struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *StartInstanceResp) Reset() {
*x = StartInstanceResp{}
mi := &file_app_instman_command_command_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *StartInstanceResp) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*StartInstanceResp) ProtoMessage() {}
func (x *StartInstanceResp) ProtoReflect() protoreflect.Message {
mi := &file_app_instman_command_command_proto_msgTypes[5]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use StartInstanceResp.ProtoReflect.Descriptor instead.
func (*StartInstanceResp) Descriptor() ([]byte, []int) {
return file_app_instman_command_command_proto_rawDescGZIP(), []int{5}
}
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_app_instman_command_command_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_app_instman_command_command_proto_msgTypes[6]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_app_instman_command_command_proto_rawDescGZIP(), []int{6}
}
var File_app_instman_command_command_proto protoreflect.FileDescriptor
const file_app_instman_command_command_proto_rawDesc = "" +
"\n" +
"!app/instman/command/command.proto\x12\x1ev2ray.core.app.instman.command\x1a common/protoext/extensions.proto\"\x11\n" +
"\x0fListInstanceReq\"&\n" +
"\x10ListInstanceResp\x12\x12\n" +
"\x04name\x18\x01 \x03(\tR\x04name\"p\n" +
"\x0eAddInstanceReq\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\x12\x1e\n" +
"\n" +
"configType\x18\x02 \x01(\tR\n" +
"configType\x12*\n" +
"\x10configContentB64\x18\x03 \x01(\tR\x10configContentB64\"\x11\n" +
"\x0fAddInstanceResp\"&\n" +
"\x10StartInstanceReq\x12\x12\n" +
"\x04name\x18\x01 \x01(\tR\x04name\"\x13\n" +
"\x11StartInstanceResp\"$\n" +
"\x06Config:\x1a\x82\xb5\x18\x16\n" +
"\vgrpcservice\x12\ainstman2\xf4\x02\n" +
"\x19InstanceManagementService\x12q\n" +
"\fListInstance\x12/.v2ray.core.app.instman.command.ListInstanceReq\x1a0.v2ray.core.app.instman.command.ListInstanceResp\x12n\n" +
"\vAddInstance\x12..v2ray.core.app.instman.command.AddInstanceReq\x1a/.v2ray.core.app.instman.command.AddInstanceResp\x12t\n" +
"\rStartInstance\x120.v2ray.core.app.instman.command.StartInstanceReq\x1a1.v2ray.core.app.instman.command.StartInstanceRespB\x7f\n" +
"&com.v2ray.core.app.observatory.instmanP\x01Z2github.com/v2fly/v2ray-core/v5/app/instman/command\xaa\x02\x1eV2Ray.Core.App.Instman.Commandb\x06proto3"
var (
file_app_instman_command_command_proto_rawDescOnce sync.Once
file_app_instman_command_command_proto_rawDescData []byte
)
func file_app_instman_command_command_proto_rawDescGZIP() []byte {
file_app_instman_command_command_proto_rawDescOnce.Do(func() {
file_app_instman_command_command_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_instman_command_command_proto_rawDesc), len(file_app_instman_command_command_proto_rawDesc)))
})
return file_app_instman_command_command_proto_rawDescData
}
var file_app_instman_command_command_proto_msgTypes = make([]protoimpl.MessageInfo, 7)
var file_app_instman_command_command_proto_goTypes = []any{
(*ListInstanceReq)(nil), // 0: v2ray.core.app.instman.command.ListInstanceReq
(*ListInstanceResp)(nil), // 1: v2ray.core.app.instman.command.ListInstanceResp
(*AddInstanceReq)(nil), // 2: v2ray.core.app.instman.command.AddInstanceReq
(*AddInstanceResp)(nil), // 3: v2ray.core.app.instman.command.AddInstanceResp
(*StartInstanceReq)(nil), // 4: v2ray.core.app.instman.command.StartInstanceReq
(*StartInstanceResp)(nil), // 5: v2ray.core.app.instman.command.StartInstanceResp
(*Config)(nil), // 6: v2ray.core.app.instman.command.Config
}
var file_app_instman_command_command_proto_depIdxs = []int32{
0, // 0: v2ray.core.app.instman.command.InstanceManagementService.ListInstance:input_type -> v2ray.core.app.instman.command.ListInstanceReq
2, // 1: v2ray.core.app.instman.command.InstanceManagementService.AddInstance:input_type -> v2ray.core.app.instman.command.AddInstanceReq
4, // 2: v2ray.core.app.instman.command.InstanceManagementService.StartInstance:input_type -> v2ray.core.app.instman.command.StartInstanceReq
1, // 3: v2ray.core.app.instman.command.InstanceManagementService.ListInstance:output_type -> v2ray.core.app.instman.command.ListInstanceResp
3, // 4: v2ray.core.app.instman.command.InstanceManagementService.AddInstance:output_type -> v2ray.core.app.instman.command.AddInstanceResp
5, // 5: v2ray.core.app.instman.command.InstanceManagementService.StartInstance:output_type -> v2ray.core.app.instman.command.StartInstanceResp
3, // [3:6] is the sub-list for method output_type
0, // [0:3] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_app_instman_command_command_proto_init() }
func file_app_instman_command_command_proto_init() {
if File_app_instman_command_command_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_instman_command_command_proto_rawDesc), len(file_app_instman_command_command_proto_rawDesc)),
NumEnums: 0,
NumMessages: 7,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_app_instman_command_command_proto_goTypes,
DependencyIndexes: file_app_instman_command_command_proto_depIdxs,
MessageInfos: file_app_instman_command_command_proto_msgTypes,
}.Build()
File_app_instman_command_command_proto = out.File
file_app_instman_command_command_proto_goTypes = nil
file_app_instman_command_command_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/instman/command/command_grpc.pb.go | app/instman/command/command_grpc.pb.go | package command
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
InstanceManagementService_ListInstance_FullMethodName = "/v2ray.core.app.instman.command.InstanceManagementService/ListInstance"
InstanceManagementService_AddInstance_FullMethodName = "/v2ray.core.app.instman.command.InstanceManagementService/AddInstance"
InstanceManagementService_StartInstance_FullMethodName = "/v2ray.core.app.instman.command.InstanceManagementService/StartInstance"
)
// InstanceManagementServiceClient is the client API for InstanceManagementService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type InstanceManagementServiceClient interface {
ListInstance(ctx context.Context, in *ListInstanceReq, opts ...grpc.CallOption) (*ListInstanceResp, error)
AddInstance(ctx context.Context, in *AddInstanceReq, opts ...grpc.CallOption) (*AddInstanceResp, error)
StartInstance(ctx context.Context, in *StartInstanceReq, opts ...grpc.CallOption) (*StartInstanceResp, error)
}
type instanceManagementServiceClient struct {
cc grpc.ClientConnInterface
}
func NewInstanceManagementServiceClient(cc grpc.ClientConnInterface) InstanceManagementServiceClient {
return &instanceManagementServiceClient{cc}
}
func (c *instanceManagementServiceClient) ListInstance(ctx context.Context, in *ListInstanceReq, opts ...grpc.CallOption) (*ListInstanceResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ListInstanceResp)
err := c.cc.Invoke(ctx, InstanceManagementService_ListInstance_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *instanceManagementServiceClient) AddInstance(ctx context.Context, in *AddInstanceReq, opts ...grpc.CallOption) (*AddInstanceResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(AddInstanceResp)
err := c.cc.Invoke(ctx, InstanceManagementService_AddInstance_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *instanceManagementServiceClient) StartInstance(ctx context.Context, in *StartInstanceReq, opts ...grpc.CallOption) (*StartInstanceResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(StartInstanceResp)
err := c.cc.Invoke(ctx, InstanceManagementService_StartInstance_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// InstanceManagementServiceServer is the server API for InstanceManagementService service.
// All implementations must embed UnimplementedInstanceManagementServiceServer
// for forward compatibility.
type InstanceManagementServiceServer interface {
ListInstance(context.Context, *ListInstanceReq) (*ListInstanceResp, error)
AddInstance(context.Context, *AddInstanceReq) (*AddInstanceResp, error)
StartInstance(context.Context, *StartInstanceReq) (*StartInstanceResp, error)
mustEmbedUnimplementedInstanceManagementServiceServer()
}
// UnimplementedInstanceManagementServiceServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedInstanceManagementServiceServer struct{}
func (UnimplementedInstanceManagementServiceServer) ListInstance(context.Context, *ListInstanceReq) (*ListInstanceResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method ListInstance not implemented")
}
func (UnimplementedInstanceManagementServiceServer) AddInstance(context.Context, *AddInstanceReq) (*AddInstanceResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method AddInstance not implemented")
}
func (UnimplementedInstanceManagementServiceServer) StartInstance(context.Context, *StartInstanceReq) (*StartInstanceResp, error) {
return nil, status.Errorf(codes.Unimplemented, "method StartInstance not implemented")
}
func (UnimplementedInstanceManagementServiceServer) mustEmbedUnimplementedInstanceManagementServiceServer() {
}
func (UnimplementedInstanceManagementServiceServer) testEmbeddedByValue() {}
// UnsafeInstanceManagementServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to InstanceManagementServiceServer will
// result in compilation errors.
type UnsafeInstanceManagementServiceServer interface {
mustEmbedUnimplementedInstanceManagementServiceServer()
}
func RegisterInstanceManagementServiceServer(s grpc.ServiceRegistrar, srv InstanceManagementServiceServer) {
// If the following call pancis, it indicates UnimplementedInstanceManagementServiceServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&InstanceManagementService_ServiceDesc, srv)
}
func _InstanceManagementService_ListInstance_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListInstanceReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(InstanceManagementServiceServer).ListInstance(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: InstanceManagementService_ListInstance_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(InstanceManagementServiceServer).ListInstance(ctx, req.(*ListInstanceReq))
}
return interceptor(ctx, in, info, handler)
}
func _InstanceManagementService_AddInstance_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(AddInstanceReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(InstanceManagementServiceServer).AddInstance(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: InstanceManagementService_AddInstance_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(InstanceManagementServiceServer).AddInstance(ctx, req.(*AddInstanceReq))
}
return interceptor(ctx, in, info, handler)
}
func _InstanceManagementService_StartInstance_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(StartInstanceReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(InstanceManagementServiceServer).StartInstance(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: InstanceManagementService_StartInstance_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(InstanceManagementServiceServer).StartInstance(ctx, req.(*StartInstanceReq))
}
return interceptor(ctx, in, info, handler)
}
// InstanceManagementService_ServiceDesc is the grpc.ServiceDesc for InstanceManagementService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var InstanceManagementService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "v2ray.core.app.instman.command.InstanceManagementService",
HandlerType: (*InstanceManagementServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "ListInstance",
Handler: _InstanceManagementService_ListInstance_Handler,
},
{
MethodName: "AddInstance",
Handler: _InstanceManagementService_AddInstance_Handler,
},
{
MethodName: "StartInstance",
Handler: _InstanceManagementService_StartInstance_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "app/instman/command/command.proto",
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/instman/command/command.go | app/instman/command/command.go | package command
import (
"context"
"encoding/base64"
"google.golang.org/grpc"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/features/extension"
)
type service struct {
UnimplementedInstanceManagementServiceServer
instman extension.InstanceManagement
}
func (s service) ListInstance(ctx context.Context, req *ListInstanceReq) (*ListInstanceResp, error) {
instanceNames, err := s.instman.ListInstance(ctx)
if err != nil {
return nil, err
}
return &ListInstanceResp{Name: instanceNames}, nil
}
func (s service) AddInstance(ctx context.Context, req *AddInstanceReq) (*AddInstanceResp, error) {
configContent, err := base64.StdEncoding.DecodeString(req.ConfigContentB64)
if err != nil {
return nil, err
}
err = s.instman.AddInstance(ctx, req.Name, configContent, req.ConfigType)
if err != nil {
return nil, err
}
return &AddInstanceResp{}, nil
}
func (s service) StartInstance(ctx context.Context, req *StartInstanceReq) (*StartInstanceResp, error) {
err := s.instman.StartInstance(ctx, req.Name)
if err != nil {
return nil, err
}
return &StartInstanceResp{}, nil
}
func (s service) Register(server *grpc.Server) {
RegisterInstanceManagementServiceServer(server, s)
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, cfg interface{}) (interface{}, error) {
s := core.MustFromContext(ctx)
sv := &service{}
err := s.RequireFeatures(func(instman extension.InstanceManagement) {
sv.instman = instman
})
if err != nil {
return nil, err
}
return sv, nil
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dispatcher/default.go | app/dispatcher/default.go | package dispatcher
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
import (
"context"
"strings"
"sync"
"time"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/common/log"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/strmatcher"
"github.com/v2fly/v2ray-core/v5/features/outbound"
"github.com/v2fly/v2ray-core/v5/features/policy"
"github.com/v2fly/v2ray-core/v5/features/routing"
routing_session "github.com/v2fly/v2ray-core/v5/features/routing/session"
"github.com/v2fly/v2ray-core/v5/features/stats"
"github.com/v2fly/v2ray-core/v5/transport"
"github.com/v2fly/v2ray-core/v5/transport/pipe"
)
var errSniffingTimeout = newError("timeout on sniffing")
type cachedReader struct {
sync.Mutex
reader *pipe.Reader
cache buf.MultiBuffer
}
func (r *cachedReader) Cache(b *buf.Buffer, deadline time.Duration) error {
mb, err := r.reader.ReadMultiBufferTimeout(deadline)
if err != nil {
return err
}
r.Lock()
if !mb.IsEmpty() {
r.cache, _ = buf.MergeMulti(r.cache, mb)
}
b.Clear()
rawBytes := b.Extend(b.Cap())
n := r.cache.Copy(rawBytes)
b.Resize(0, int32(n))
r.Unlock()
return nil
}
func (r *cachedReader) readInternal() buf.MultiBuffer {
r.Lock()
defer r.Unlock()
if r.cache != nil && !r.cache.IsEmpty() {
mb := r.cache
r.cache = nil
return mb
}
return nil
}
func (r *cachedReader) ReadMultiBuffer() (buf.MultiBuffer, error) {
mb := r.readInternal()
if mb != nil {
return mb, nil
}
return r.reader.ReadMultiBuffer()
}
func (r *cachedReader) ReadMultiBufferTimeout(timeout time.Duration) (buf.MultiBuffer, error) {
mb := r.readInternal()
if mb != nil {
return mb, nil
}
return r.reader.ReadMultiBufferTimeout(timeout)
}
func (r *cachedReader) Interrupt() {
r.Lock()
if r.cache != nil {
r.cache = buf.ReleaseMulti(r.cache)
}
r.Unlock()
r.reader.Interrupt()
}
// DefaultDispatcher is a default implementation of Dispatcher.
type DefaultDispatcher struct {
ohm outbound.Manager
router routing.Router
policy policy.Manager
stats stats.Manager
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
d := new(DefaultDispatcher)
if err := core.RequireFeatures(ctx, func(om outbound.Manager, router routing.Router, pm policy.Manager, sm stats.Manager) error {
return d.Init(config.(*Config), om, router, pm, sm)
}); err != nil {
return nil, err
}
return d, nil
}))
}
// Init initializes DefaultDispatcher.
func (d *DefaultDispatcher) Init(config *Config, om outbound.Manager, router routing.Router, pm policy.Manager, sm stats.Manager) error {
d.ohm = om
d.router = router
d.policy = pm
d.stats = sm
return nil
}
// Type implements common.HasType.
func (*DefaultDispatcher) Type() interface{} {
return routing.DispatcherType()
}
// Start implements common.Runnable.
func (*DefaultDispatcher) Start() error {
return nil
}
// Close implements common.Closable.
func (*DefaultDispatcher) Close() error { return nil }
func (d *DefaultDispatcher) getLink(ctx context.Context) (*transport.Link, *transport.Link) {
opt := pipe.OptionsFromContext(ctx)
uplinkReader, uplinkWriter := pipe.New(opt...)
downlinkReader, downlinkWriter := pipe.New(opt...)
inboundLink := &transport.Link{
Reader: downlinkReader,
Writer: uplinkWriter,
}
outboundLink := &transport.Link{
Reader: uplinkReader,
Writer: downlinkWriter,
}
sessionInbound := session.InboundFromContext(ctx)
var user *protocol.MemoryUser
if sessionInbound != nil {
user = sessionInbound.User
}
if user != nil && len(user.Email) > 0 {
p := d.policy.ForLevel(user.Level)
if p.Stats.UserUplink {
name := "user>>>" + user.Email + ">>>traffic>>>uplink"
if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
inboundLink.Writer = &SizeStatWriter{
Counter: c,
Writer: inboundLink.Writer,
}
}
}
if p.Stats.UserDownlink {
name := "user>>>" + user.Email + ">>>traffic>>>downlink"
if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
outboundLink.Writer = &SizeStatWriter{
Counter: c,
Writer: outboundLink.Writer,
}
}
}
}
return inboundLink, outboundLink
}
func shouldOverride(result SniffResult, domainOverride []string) bool {
if result.Domain() == "" {
return false
}
protocolString := result.Protocol()
if resComp, ok := result.(SnifferResultComposite); ok {
protocolString = resComp.ProtocolForDomainResult()
}
for _, p := range domainOverride {
if strings.HasPrefix(protocolString, p) || strings.HasSuffix(protocolString, p) {
return true
}
if resultSubset, ok := result.(SnifferIsProtoSubsetOf); ok {
if resultSubset.IsProtoSubsetOf(p) {
return true
}
}
}
return false
}
// Dispatch implements routing.Dispatcher.
func (d *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destination) (*transport.Link, error) {
if !destination.IsValid() {
panic("Dispatcher: Invalid destination.")
}
ob := &session.Outbound{
Target: destination,
}
ctx = session.ContextWithOutbound(ctx, ob)
inbound, outbound := d.getLink(ctx)
content := session.ContentFromContext(ctx)
if content == nil {
content = new(session.Content)
ctx = session.ContextWithContent(ctx, content)
}
sniffingRequest := content.SniffingRequest
if !sniffingRequest.Enabled {
go d.routedDispatch(ctx, outbound, destination)
} else {
go func() {
cReader := &cachedReader{
reader: outbound.Reader.(*pipe.Reader),
}
outbound.Reader = cReader
result, err := sniffer(ctx, cReader, sniffingRequest.MetadataOnly, destination.Network)
if err == nil {
content.Protocol = result.Protocol()
}
if err == nil && shouldOverride(result, sniffingRequest.OverrideDestinationForProtocol) {
if domain, err := strmatcher.ToDomain(result.Domain()); err == nil {
newError("sniffed domain: ", domain, " for ", destination).WriteToLog(session.ExportIDToError(ctx))
destination.Address = net.ParseAddress(domain)
ob.Target = destination
}
}
d.routedDispatch(ctx, outbound, destination)
}()
}
return inbound, nil
}
func sniffer(ctx context.Context, cReader *cachedReader, metadataOnly bool, network net.Network) (SniffResult, error) {
payload := buf.NewWithSize(32767)
defer payload.Release()
sniffer := NewSniffer(ctx)
metaresult, metadataErr := sniffer.SniffMetadata(ctx)
if metadataOnly {
return metaresult, metadataErr
}
contentResult, contentErr := func() (SniffResult, error) {
cacheDeadline := 200 * time.Millisecond
totalAttempt := 0
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
cachingStartingTimeStamp := time.Now()
cacheErr := cReader.Cache(payload, cacheDeadline)
cachingTimeElapsed := time.Since(cachingStartingTimeStamp)
cacheDeadline -= cachingTimeElapsed
if !payload.IsEmpty() {
result, err := sniffer.Sniff(ctx, payload.Bytes(), network)
switch err {
case common.ErrNoClue: // No Clue: protocol not matches, and sniffer cannot determine whether there will be a match or not
totalAttempt++
case protocol.ErrProtoNeedMoreData: // Protocol Need More Data: protocol matches, but need more data to complete sniffing
if cacheErr != nil { // Cache error (e.g. timeout) counts for failed attempt
totalAttempt++
}
default:
return result, err
}
}
if totalAttempt >= 2 || cacheDeadline <= 0 {
return nil, errSniffingTimeout
}
}
}
}()
if contentErr != nil && metadataErr == nil {
return metaresult, nil
}
if contentErr == nil && metadataErr == nil {
return CompositeResult(metaresult, contentResult), nil
}
return contentResult, contentErr
}
func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *transport.Link, destination net.Destination) {
var handler outbound.Handler
if forcedOutboundTag := session.GetForcedOutboundTagFromContext(ctx); forcedOutboundTag != "" {
ctx = session.SetForcedOutboundTagToContext(ctx, "")
if h := d.ohm.GetHandler(forcedOutboundTag); h != nil {
newError("taking platform initialized detour [", forcedOutboundTag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx))
handler = h
} else {
newError("non existing tag for platform initialized detour: ", forcedOutboundTag).AtError().WriteToLog(session.ExportIDToError(ctx))
common.Close(link.Writer)
common.Interrupt(link.Reader)
return
}
} else if d.router != nil {
if route, err := d.router.PickRoute(routing_session.AsRoutingContext(ctx)); err == nil {
tag := route.GetOutboundTag()
if h := d.ohm.GetHandler(tag); h != nil {
newError("taking detour [", tag, "] for [", destination, "]").WriteToLog(session.ExportIDToError(ctx))
handler = h
} else {
newError("non existing tag: ", tag).AtWarning().WriteToLog(session.ExportIDToError(ctx))
}
} else {
newError("default route for ", destination).AtWarning().WriteToLog(session.ExportIDToError(ctx))
}
}
if handler == nil {
handler = d.ohm.GetDefaultHandler()
}
if handler == nil {
newError("default outbound handler not exist").WriteToLog(session.ExportIDToError(ctx))
common.Close(link.Writer)
common.Interrupt(link.Reader)
return
}
if accessMessage := log.AccessMessageFromContext(ctx); accessMessage != nil {
if tag := handler.Tag(); tag != "" {
accessMessage.Detour = tag
if d.policy.ForSystem().OverrideAccessLogDest {
accessMessage.To = destination
}
}
log.Record(accessMessage)
}
handler.Dispatch(ctx, link)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dispatcher/stats.go | app/dispatcher/stats.go | package dispatcher
import (
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
"github.com/v2fly/v2ray-core/v5/features/stats"
)
type SizeStatWriter struct {
Counter stats.Counter
Writer buf.Writer
}
func (w *SizeStatWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
w.Counter.Add(int64(mb.Len()))
return w.Writer.WriteMultiBuffer(mb)
}
func (w *SizeStatWriter) Close() error {
return common.Close(w.Writer)
}
func (w *SizeStatWriter) Interrupt() {
common.Interrupt(w.Writer)
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dispatcher/errors.generated.go | app/dispatcher/errors.generated.go | package dispatcher
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dispatcher/sniffer.go | app/dispatcher/sniffer.go | package dispatcher
import (
"context"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/protocol"
"github.com/v2fly/v2ray-core/v5/common/protocol/bittorrent"
"github.com/v2fly/v2ray-core/v5/common/protocol/http"
"github.com/v2fly/v2ray-core/v5/common/protocol/quic"
"github.com/v2fly/v2ray-core/v5/common/protocol/tls"
)
type SniffResult interface {
Protocol() string
Domain() string
}
type protocolSniffer func(context.Context, []byte) (SniffResult, error)
type protocolSnifferWithMetadata struct {
protocolSniffer protocolSniffer
// A Metadata sniffer will be invoked on connection establishment only, with nil body,
// for both TCP and UDP connections
// It will not be shown as a traffic type for routing unless there is no other successful sniffing.
metadataSniffer bool
network net.Network
}
type Sniffer struct {
sniffer []protocolSnifferWithMetadata
}
func NewSniffer(ctx context.Context) *Sniffer {
ret := &Sniffer{
sniffer: []protocolSnifferWithMetadata{
{func(c context.Context, b []byte) (SniffResult, error) { return http.SniffHTTP(b) }, false, net.Network_TCP},
{func(c context.Context, b []byte) (SniffResult, error) { return tls.SniffTLS(b) }, false, net.Network_TCP},
{func(c context.Context, b []byte) (SniffResult, error) { return quic.SniffQUIC(b) }, false, net.Network_UDP},
{func(c context.Context, b []byte) (SniffResult, error) { return bittorrent.SniffBittorrent(b) }, false, net.Network_TCP},
{func(c context.Context, b []byte) (SniffResult, error) { return bittorrent.SniffUTP(b) }, false, net.Network_UDP},
},
}
if sniffer, err := newFakeDNSSniffer(ctx); err == nil {
others := ret.sniffer
ret.sniffer = append(ret.sniffer, sniffer)
fakeDNSThenOthers, err := newFakeDNSThenOthers(ctx, sniffer, others)
if err == nil {
ret.sniffer = append([]protocolSnifferWithMetadata{fakeDNSThenOthers}, ret.sniffer...)
}
}
return ret
}
var errUnknownContent = newError("unknown content")
func (s *Sniffer) Sniff(c context.Context, payload []byte, network net.Network) (SniffResult, error) {
var pendingSniffer []protocolSnifferWithMetadata
for _, si := range s.sniffer {
sniffer := si.protocolSniffer
if si.metadataSniffer {
continue
}
if si.network != network {
continue
}
result, err := sniffer(c, payload)
if err == common.ErrNoClue {
pendingSniffer = append(pendingSniffer, si)
continue
} else if err == protocol.ErrProtoNeedMoreData { // Sniffer protocol matched, but need more data to complete sniffing
s.sniffer = []protocolSnifferWithMetadata{si}
return nil, protocol.ErrProtoNeedMoreData
}
if err == nil && result != nil {
return result, nil
}
}
if len(pendingSniffer) > 0 {
s.sniffer = pendingSniffer
return nil, common.ErrNoClue
}
return nil, errUnknownContent
}
func (s *Sniffer) SniffMetadata(c context.Context) (SniffResult, error) {
var pendingSniffer []protocolSnifferWithMetadata
for _, si := range s.sniffer {
s := si.protocolSniffer
if !si.metadataSniffer {
pendingSniffer = append(pendingSniffer, si)
continue
}
result, err := s(c, nil)
if err == common.ErrNoClue {
pendingSniffer = append(pendingSniffer, si)
continue
}
if err == nil && result != nil {
return result, nil
}
}
if len(pendingSniffer) > 0 {
s.sniffer = pendingSniffer
return nil, common.ErrNoClue
}
return nil, errUnknownContent
}
func CompositeResult(domainResult SniffResult, protocolResult SniffResult) SniffResult {
return &compositeResult{domainResult: domainResult, protocolResult: protocolResult}
}
type compositeResult struct {
domainResult SniffResult
protocolResult SniffResult
}
func (c compositeResult) Protocol() string {
return c.protocolResult.Protocol()
}
func (c compositeResult) Domain() string {
return c.domainResult.Domain()
}
func (c compositeResult) ProtocolForDomainResult() string {
return c.domainResult.Protocol()
}
type SnifferResultComposite interface {
ProtocolForDomainResult() string
}
type SnifferIsProtoSubsetOf interface {
IsProtoSubsetOf(protocolName string) bool
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dispatcher/stats_test.go | app/dispatcher/stats_test.go | package dispatcher_test
import (
"testing"
. "github.com/v2fly/v2ray-core/v5/app/dispatcher"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/buf"
)
type TestCounter int64
func (c *TestCounter) Value() int64 {
return int64(*c)
}
func (c *TestCounter) Add(v int64) int64 {
x := int64(*c) + v
*c = TestCounter(x)
return x
}
func (c *TestCounter) Set(v int64) int64 {
*c = TestCounter(v)
return v
}
func TestStatsWriter(t *testing.T) {
var c TestCounter
writer := &SizeStatWriter{
Counter: &c,
Writer: buf.Discard,
}
mb := buf.MergeBytes(nil, []byte("abcd"))
common.Must(writer.WriteMultiBuffer(mb))
mb = buf.MergeBytes(nil, []byte("efg"))
common.Must(writer.WriteMultiBuffer(mb))
if c.Value() != 7 {
t.Fatal("unexpected counter value. want 7, but got ", c.Value())
}
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dispatcher/dispatcher.go | app/dispatcher/dispatcher.go | package dispatcher
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dispatcher/fakednssniffer.go | app/dispatcher/fakednssniffer.go | //go:build !confonly
// +build !confonly
package dispatcher
import (
"context"
"strings"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/features/dns"
)
// newFakeDNSSniffer Creates a Fake DNS metadata sniffer
func newFakeDNSSniffer(ctx context.Context) (protocolSnifferWithMetadata, error) {
var fakeDNSEngine dns.FakeDNSEngine
{
fakeDNSEngineFeat := core.MustFromContext(ctx).GetFeature((*dns.FakeDNSEngine)(nil))
if fakeDNSEngineFeat != nil {
fakeDNSEngine = fakeDNSEngineFeat.(dns.FakeDNSEngine)
}
}
if fakeDNSEngine == nil {
errNotInit := newError("FakeDNSEngine is not initialized, but such a sniffer is used").AtError()
return protocolSnifferWithMetadata{}, errNotInit
}
return protocolSnifferWithMetadata{protocolSniffer: func(ctx context.Context, bytes []byte) (SniffResult, error) {
Target := session.OutboundFromContext(ctx).Target
if Target.Network == net.Network_TCP || Target.Network == net.Network_UDP {
domainFromFakeDNS := fakeDNSEngine.GetDomainFromFakeDNS(Target.Address)
if domainFromFakeDNS != "" {
newError("fake dns got domain: ", domainFromFakeDNS, " for ip: ", Target.Address.String()).WriteToLog(session.ExportIDToError(ctx))
return &fakeDNSSniffResult{domainName: domainFromFakeDNS}, nil
}
}
if ipAddressInRangeValueI := ctx.Value(ipAddressInRange); ipAddressInRangeValueI != nil {
ipAddressInRangeValue := ipAddressInRangeValueI.(*ipAddressInRangeOpt)
if fkr0, ok := fakeDNSEngine.(dns.FakeDNSEngineRev0); ok {
inPool := fkr0.IsIPInIPPool(Target.Address)
ipAddressInRangeValue.addressInRange = &inPool
}
}
return nil, common.ErrNoClue
}, metadataSniffer: true}, nil
}
type fakeDNSSniffResult struct {
domainName string
}
func (fakeDNSSniffResult) Protocol() string {
return "fakedns"
}
func (f fakeDNSSniffResult) Domain() string {
return f.domainName
}
type fakeDNSExtraOpts int
const ipAddressInRange fakeDNSExtraOpts = 1
type ipAddressInRangeOpt struct {
addressInRange *bool
}
type DNSThenOthersSniffResult struct {
domainName string
protocolOriginalName string
}
func (f DNSThenOthersSniffResult) IsProtoSubsetOf(protocolName string) bool {
return strings.HasPrefix(protocolName, f.protocolOriginalName)
}
func (DNSThenOthersSniffResult) Protocol() string {
return "fakedns+others"
}
func (f DNSThenOthersSniffResult) Domain() string {
return f.domainName
}
func newFakeDNSThenOthers(ctx context.Context, fakeDNSSniffer protocolSnifferWithMetadata, others []protocolSnifferWithMetadata) (protocolSnifferWithMetadata, error) { // nolint: unparam
// ctx may be used in the future
_ = ctx
return protocolSnifferWithMetadata{
protocolSniffer: func(ctx context.Context, bytes []byte) (SniffResult, error) {
ipAddressInRangeValue := &ipAddressInRangeOpt{}
ctx = context.WithValue(ctx, ipAddressInRange, ipAddressInRangeValue)
result, err := fakeDNSSniffer.protocolSniffer(ctx, bytes)
if err == nil {
return result, nil
}
if ipAddressInRangeValue.addressInRange != nil {
if *ipAddressInRangeValue.addressInRange {
for _, v := range others {
if v.metadataSniffer || bytes != nil {
if result, err := v.protocolSniffer(ctx, bytes); err == nil {
return DNSThenOthersSniffResult{domainName: result.Domain(), protocolOriginalName: result.Protocol()}, nil
}
}
}
return nil, common.ErrNoClue
}
newError("ip address not in fake dns range, return as is").AtDebug().WriteToLog()
return nil, common.ErrNoClue
}
newError("fake dns sniffer did not set address in range option, assume false.").AtWarning().WriteToLog()
return nil, common.ErrNoClue
},
metadataSniffer: false,
}, nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/dispatcher/config.pb.go | app/dispatcher/config.pb.go | package dispatcher
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type SessionConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SessionConfig) Reset() {
*x = SessionConfig{}
mi := &file_app_dispatcher_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SessionConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SessionConfig) ProtoMessage() {}
func (x *SessionConfig) ProtoReflect() protoreflect.Message {
mi := &file_app_dispatcher_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SessionConfig.ProtoReflect.Descriptor instead.
func (*SessionConfig) Descriptor() ([]byte, []int) {
return file_app_dispatcher_config_proto_rawDescGZIP(), []int{0}
}
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
Settings *SessionConfig `protobuf:"bytes,1,opt,name=settings,proto3" json:"settings,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_app_dispatcher_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_app_dispatcher_config_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_app_dispatcher_config_proto_rawDescGZIP(), []int{1}
}
func (x *Config) GetSettings() *SessionConfig {
if x != nil {
return x.Settings
}
return nil
}
var File_app_dispatcher_config_proto protoreflect.FileDescriptor
const file_app_dispatcher_config_proto_rawDesc = "" +
"\n" +
"\x1bapp/dispatcher/config.proto\x12\x19v2ray.core.app.dispatcher\"\x15\n" +
"\rSessionConfigJ\x04\b\x01\x10\x02\"N\n" +
"\x06Config\x12D\n" +
"\bsettings\x18\x01 \x01(\v2(.v2ray.core.app.dispatcher.SessionConfigR\bsettingsBl\n" +
"\x1dcom.v2ray.core.app.dispatcherP\x01Z-github.com/v2fly/v2ray-core/v5/app/dispatcher\xaa\x02\x19V2Ray.Core.App.Dispatcherb\x06proto3"
var (
file_app_dispatcher_config_proto_rawDescOnce sync.Once
file_app_dispatcher_config_proto_rawDescData []byte
)
func file_app_dispatcher_config_proto_rawDescGZIP() []byte {
file_app_dispatcher_config_proto_rawDescOnce.Do(func() {
file_app_dispatcher_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_dispatcher_config_proto_rawDesc), len(file_app_dispatcher_config_proto_rawDesc)))
})
return file_app_dispatcher_config_proto_rawDescData
}
var file_app_dispatcher_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_app_dispatcher_config_proto_goTypes = []any{
(*SessionConfig)(nil), // 0: v2ray.core.app.dispatcher.SessionConfig
(*Config)(nil), // 1: v2ray.core.app.dispatcher.Config
}
var file_app_dispatcher_config_proto_depIdxs = []int32{
0, // 0: v2ray.core.app.dispatcher.Config.settings:type_name -> v2ray.core.app.dispatcher.SessionConfig
1, // [1:1] is the sub-list for method output_type
1, // [1:1] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_app_dispatcher_config_proto_init() }
func file_app_dispatcher_config_proto_init() {
if File_app_dispatcher_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_dispatcher_config_proto_rawDesc), len(file_app_dispatcher_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_app_dispatcher_config_proto_goTypes,
DependencyIndexes: file_app_dispatcher_config_proto_depIdxs,
MessageInfos: file_app_dispatcher_config_proto_msgTypes,
}.Build()
File_app_dispatcher_config_proto = out.File
file_app_dispatcher_config_proto_goTypes = nil
file_app_dispatcher_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/observatory/errors.generated.go | app/observatory/errors.generated.go | package observatory
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/observatory/observatory.go | app/observatory/observatory.go | package observatory
//go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/observatory/observer.go | app/observatory/observer.go | //go:build !confonly
// +build !confonly
package observatory
import (
"context"
"net"
"net/http"
"net/url"
"sort"
"sync"
"time"
"github.com/v2fly/v2ray-core/v5/app/persistentstorage"
"github.com/v2fly/v2ray-core/v5/app/persistentstorage/protostorage"
"github.com/v2fly/v2ray-core/v5/common/environment"
"github.com/v2fly/v2ray-core/v5/common/environment/envctx"
"github.com/golang/protobuf/proto"
core "github.com/v2fly/v2ray-core/v5"
"github.com/v2fly/v2ray-core/v5/common"
v2net "github.com/v2fly/v2ray-core/v5/common/net"
"github.com/v2fly/v2ray-core/v5/common/session"
"github.com/v2fly/v2ray-core/v5/common/signal/done"
"github.com/v2fly/v2ray-core/v5/common/task"
"github.com/v2fly/v2ray-core/v5/features/extension"
"github.com/v2fly/v2ray-core/v5/features/outbound"
"github.com/v2fly/v2ray-core/v5/transport/internet/tagged"
)
type Observer struct {
config *Config
ctx context.Context
statusLock sync.Mutex
status []*OutboundStatus
finished *done.Instance
ohm outbound.Manager
persistStorage persistentstorage.ScopedPersistentStorage
persistOutboundStatusProtoStorage protostorage.ProtoPersistentStorage
}
func (o *Observer) GetObservation(ctx context.Context) (proto.Message, error) {
return &ObservationResult{Status: o.status}, nil
}
func (o *Observer) Type() interface{} {
return extension.ObservatoryType()
}
func (o *Observer) Start() error {
if o.config != nil && len(o.config.SubjectSelector) != 0 {
if o.config.PersistentProbeResult {
appEnvironment := envctx.EnvironmentFromContext(o.ctx).(environment.AppEnvironment)
o.persistStorage = appEnvironment.PersistentStorage()
outboundStatusStorage, err := o.persistStorage.NarrowScope(o.ctx, []byte("outbound_status"))
if err != nil {
return newError("failed to get persistent storage for outbound_status").Base(err)
}
o.persistOutboundStatusProtoStorage = outboundStatusStorage.(protostorage.ProtoPersistentStorage)
list, err := outboundStatusStorage.List(o.ctx, []byte(""))
if err != nil {
newError("failed to list persisted outbound status").Base(err).WriteToLog()
} else {
for _, v := range list {
o.loadOutboundStatus(string(v))
}
}
}
o.finished = done.New()
go o.background()
}
return nil
}
func (o *Observer) Close() error {
if o.finished != nil {
return o.finished.Close()
}
return nil
}
func (o *Observer) background() {
for !o.finished.Done() {
hs, ok := o.ohm.(outbound.HandlerSelector)
if !ok {
newError("outbound.Manager is not a HandlerSelector").WriteToLog()
return
}
outbounds := hs.Select(o.config.SubjectSelector)
sort.Strings(outbounds)
o.updateStatus(outbounds)
slept := false
for _, v := range outbounds {
result := o.probe(v)
o.updateStatusForResult(v, &result)
if o.finished.Done() {
return
}
sleepTime := time.Second * 10
if o.config.ProbeInterval != 0 {
sleepTime = time.Duration(o.config.ProbeInterval)
}
time.Sleep(sleepTime)
slept = true
}
if !slept {
sleepTime := time.Second * 10
if o.config.ProbeInterval != 0 {
sleepTime = time.Duration(o.config.ProbeInterval)
}
time.Sleep(sleepTime)
}
}
}
func (o *Observer) updateStatus(outbounds []string) {
o.statusLock.Lock()
defer o.statusLock.Unlock()
// TODO should remove old inbound that is removed
_ = outbounds
}
func (o *Observer) probe(outbound string) ProbeResult {
errorCollectorForRequest := newErrorCollector()
httpTransport := http.Transport{
Proxy: func(*http.Request) (*url.URL, error) {
return nil, nil
},
DialContext: func(ctx context.Context, network string, addr string) (net.Conn, error) {
var connection net.Conn
taskErr := task.Run(ctx, func() error {
// MUST use V2Fly's built in context system
dest, err := v2net.ParseDestination(network + ":" + addr)
if err != nil {
return newError("cannot understand address").Base(err)
}
trackedCtx := session.TrackedConnectionError(o.ctx, errorCollectorForRequest)
conn, err := tagged.Dialer(trackedCtx, dest, outbound)
if err != nil {
return newError("cannot dial remote address ", dest).Base(err)
}
connection = conn
return nil
})
if taskErr != nil {
return nil, newError("cannot finish connection").Base(taskErr)
}
return connection, nil
},
TLSHandshakeTimeout: time.Second * 5,
}
httpClient := &http.Client{
Transport: &httpTransport,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
Jar: nil,
Timeout: time.Second * 5,
}
var GETTime time.Duration
err := task.Run(o.ctx, func() error {
startTime := time.Now()
probeURL := "https://api.v2fly.org/checkConnection.svgz"
if o.config.ProbeUrl != "" {
probeURL = o.config.ProbeUrl
}
response, err := httpClient.Get(probeURL)
if err != nil {
return newError("outbound failed to relay connection").Base(err)
}
if response.Body != nil {
response.Body.Close()
}
endTime := time.Now()
GETTime = endTime.Sub(startTime)
return nil
})
if err != nil {
fullerr := newError("underlying connection failed").Base(errorCollectorForRequest.UnderlyingError())
fullerr = newError("with outbound handler report").Base(fullerr)
fullerr = newError("GET request failed:", err).Base(fullerr)
fullerr = newError("the outbound ", outbound, " is dead:").Base(fullerr)
fullerr = fullerr.AtInfo()
fullerr.WriteToLog()
return ProbeResult{Alive: false, LastErrorReason: fullerr.Error()}
}
newError("the outbound ", outbound, " is alive:", GETTime.Seconds()).AtInfo().WriteToLog()
return ProbeResult{Alive: true, Delay: GETTime.Milliseconds()}
}
func (o *Observer) updateStatusForResult(outbound string, result *ProbeResult) {
o.statusLock.Lock()
defer o.statusLock.Unlock()
var status *OutboundStatus
if location := o.findStatusLocationLockHolderOnly(outbound); location != -1 {
status = o.status[location]
} else {
status = &OutboundStatus{}
o.status = append(o.status, status)
}
status.LastTryTime = time.Now().Unix()
status.OutboundTag = outbound
status.Alive = result.Alive
if result.Alive {
status.Delay = result.Delay
status.LastSeenTime = status.LastTryTime
status.LastErrorReason = ""
} else {
status.LastErrorReason = result.LastErrorReason
status.Delay = 99999999
}
if o.config.PersistentProbeResult {
err := o.persistOutboundStatusProtoStorage.PutProto(o.ctx, outbound, status)
if err != nil {
newError("failed to persist outbound status").Base(err).WriteToLog()
}
}
}
func (o *Observer) findStatusLocationLockHolderOnly(outbound string) int {
for i, v := range o.status {
if v.OutboundTag == outbound {
return i
}
}
return -1
}
func (o *Observer) loadOutboundStatus(name string) {
if o.persistOutboundStatusProtoStorage == nil {
return
}
status := &OutboundStatus{}
err := o.persistOutboundStatusProtoStorage.GetProto(o.ctx, name, status)
if err != nil {
newError("failed to load outbound status").Base(err).WriteToLog()
return
}
o.status = append(o.status, status)
}
func New(ctx context.Context, config *Config) (*Observer, error) {
obs := &Observer{
config: config,
ctx: ctx,
}
err := core.RequireFeatures(ctx, func(om outbound.Manager) {
obs.ohm = om
})
if err != nil {
return nil, newError("Cannot get depended features").Base(err)
}
return obs, nil
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return New(ctx, config.(*Config))
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/observatory/config.pb.go | app/observatory/config.pb.go | package observatory
import (
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type ObservationResult struct {
state protoimpl.MessageState `protogen:"open.v1"`
Status []*OutboundStatus `protobuf:"bytes,1,rep,name=status,proto3" json:"status,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ObservationResult) Reset() {
*x = ObservationResult{}
mi := &file_app_observatory_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ObservationResult) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ObservationResult) ProtoMessage() {}
func (x *ObservationResult) ProtoReflect() protoreflect.Message {
mi := &file_app_observatory_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ObservationResult.ProtoReflect.Descriptor instead.
func (*ObservationResult) Descriptor() ([]byte, []int) {
return file_app_observatory_config_proto_rawDescGZIP(), []int{0}
}
func (x *ObservationResult) GetStatus() []*OutboundStatus {
if x != nil {
return x.Status
}
return nil
}
type HealthPingMeasurementResult struct {
state protoimpl.MessageState `protogen:"open.v1"`
All int64 `protobuf:"varint,1,opt,name=all,proto3" json:"all,omitempty"`
Fail int64 `protobuf:"varint,2,opt,name=fail,proto3" json:"fail,omitempty"`
Deviation int64 `protobuf:"varint,3,opt,name=deviation,proto3" json:"deviation,omitempty"`
Average int64 `protobuf:"varint,4,opt,name=average,proto3" json:"average,omitempty"`
Max int64 `protobuf:"varint,5,opt,name=max,proto3" json:"max,omitempty"`
Min int64 `protobuf:"varint,6,opt,name=min,proto3" json:"min,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *HealthPingMeasurementResult) Reset() {
*x = HealthPingMeasurementResult{}
mi := &file_app_observatory_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *HealthPingMeasurementResult) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*HealthPingMeasurementResult) ProtoMessage() {}
func (x *HealthPingMeasurementResult) ProtoReflect() protoreflect.Message {
mi := &file_app_observatory_config_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use HealthPingMeasurementResult.ProtoReflect.Descriptor instead.
func (*HealthPingMeasurementResult) Descriptor() ([]byte, []int) {
return file_app_observatory_config_proto_rawDescGZIP(), []int{1}
}
func (x *HealthPingMeasurementResult) GetAll() int64 {
if x != nil {
return x.All
}
return 0
}
func (x *HealthPingMeasurementResult) GetFail() int64 {
if x != nil {
return x.Fail
}
return 0
}
func (x *HealthPingMeasurementResult) GetDeviation() int64 {
if x != nil {
return x.Deviation
}
return 0
}
func (x *HealthPingMeasurementResult) GetAverage() int64 {
if x != nil {
return x.Average
}
return 0
}
func (x *HealthPingMeasurementResult) GetMax() int64 {
if x != nil {
return x.Max
}
return 0
}
func (x *HealthPingMeasurementResult) GetMin() int64 {
if x != nil {
return x.Min
}
return 0
}
type OutboundStatus struct {
state protoimpl.MessageState `protogen:"open.v1"`
// @Document Whether this outbound is usable
// @Restriction ReadOnlyForUser
Alive bool `protobuf:"varint,1,opt,name=alive,proto3" json:"alive,omitempty"`
// @Document The time for probe request to finish.
// @Type time.ms
// @Restriction ReadOnlyForUser
Delay int64 `protobuf:"varint,2,opt,name=delay,proto3" json:"delay,omitempty"`
// @Document The last error caused this outbound failed to relay probe request
// @Restriction NotMachineReadable
LastErrorReason string `protobuf:"bytes,3,opt,name=last_error_reason,json=lastErrorReason,proto3" json:"last_error_reason,omitempty"`
// @Document The outbound tag for this Server
// @Type id.outboundTag
OutboundTag string `protobuf:"bytes,4,opt,name=outbound_tag,json=outboundTag,proto3" json:"outbound_tag,omitempty"`
// @Document The time this outbound is known to be alive
// @Type id.outboundTag
LastSeenTime int64 `protobuf:"varint,5,opt,name=last_seen_time,json=lastSeenTime,proto3" json:"last_seen_time,omitempty"`
// @Document The time this outbound is tried
// @Type id.outboundTag
LastTryTime int64 `protobuf:"varint,6,opt,name=last_try_time,json=lastTryTime,proto3" json:"last_try_time,omitempty"`
HealthPing *HealthPingMeasurementResult `protobuf:"bytes,7,opt,name=health_ping,json=healthPing,proto3" json:"health_ping,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *OutboundStatus) Reset() {
*x = OutboundStatus{}
mi := &file_app_observatory_config_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *OutboundStatus) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*OutboundStatus) ProtoMessage() {}
func (x *OutboundStatus) ProtoReflect() protoreflect.Message {
mi := &file_app_observatory_config_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use OutboundStatus.ProtoReflect.Descriptor instead.
func (*OutboundStatus) Descriptor() ([]byte, []int) {
return file_app_observatory_config_proto_rawDescGZIP(), []int{2}
}
func (x *OutboundStatus) GetAlive() bool {
if x != nil {
return x.Alive
}
return false
}
func (x *OutboundStatus) GetDelay() int64 {
if x != nil {
return x.Delay
}
return 0
}
func (x *OutboundStatus) GetLastErrorReason() string {
if x != nil {
return x.LastErrorReason
}
return ""
}
func (x *OutboundStatus) GetOutboundTag() string {
if x != nil {
return x.OutboundTag
}
return ""
}
func (x *OutboundStatus) GetLastSeenTime() int64 {
if x != nil {
return x.LastSeenTime
}
return 0
}
func (x *OutboundStatus) GetLastTryTime() int64 {
if x != nil {
return x.LastTryTime
}
return 0
}
func (x *OutboundStatus) GetHealthPing() *HealthPingMeasurementResult {
if x != nil {
return x.HealthPing
}
return nil
}
type ProbeResult struct {
state protoimpl.MessageState `protogen:"open.v1"`
// @Document Whether this outbound is usable
// @Restriction ReadOnlyForUser
Alive bool `protobuf:"varint,1,opt,name=alive,proto3" json:"alive,omitempty"`
// @Document The time for probe request to finish.
// @Type time.ms
// @Restriction ReadOnlyForUser
Delay int64 `protobuf:"varint,2,opt,name=delay,proto3" json:"delay,omitempty"`
// @Document The error caused this outbound failed to relay probe request
// @Restriction NotMachineReadable
LastErrorReason string `protobuf:"bytes,3,opt,name=last_error_reason,json=lastErrorReason,proto3" json:"last_error_reason,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ProbeResult) Reset() {
*x = ProbeResult{}
mi := &file_app_observatory_config_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ProbeResult) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ProbeResult) ProtoMessage() {}
func (x *ProbeResult) ProtoReflect() protoreflect.Message {
mi := &file_app_observatory_config_proto_msgTypes[3]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ProbeResult.ProtoReflect.Descriptor instead.
func (*ProbeResult) Descriptor() ([]byte, []int) {
return file_app_observatory_config_proto_rawDescGZIP(), []int{3}
}
func (x *ProbeResult) GetAlive() bool {
if x != nil {
return x.Alive
}
return false
}
func (x *ProbeResult) GetDelay() int64 {
if x != nil {
return x.Delay
}
return 0
}
func (x *ProbeResult) GetLastErrorReason() string {
if x != nil {
return x.LastErrorReason
}
return ""
}
type Intensity struct {
state protoimpl.MessageState `protogen:"open.v1"`
// @Document The time interval for a probe request in ms.
// @Type time.ms
ProbeInterval uint32 `protobuf:"varint,1,opt,name=probe_interval,json=probeInterval,proto3" json:"probe_interval,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Intensity) Reset() {
*x = Intensity{}
mi := &file_app_observatory_config_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Intensity) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Intensity) ProtoMessage() {}
func (x *Intensity) ProtoReflect() protoreflect.Message {
mi := &file_app_observatory_config_proto_msgTypes[4]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Intensity.ProtoReflect.Descriptor instead.
func (*Intensity) Descriptor() ([]byte, []int) {
return file_app_observatory_config_proto_rawDescGZIP(), []int{4}
}
func (x *Intensity) GetProbeInterval() uint32 {
if x != nil {
return x.ProbeInterval
}
return 0
}
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
// @Document The selectors for outbound under observation
SubjectSelector []string `protobuf:"bytes,2,rep,name=subject_selector,json=subjectSelector,proto3" json:"subject_selector,omitempty"`
ProbeUrl string `protobuf:"bytes,3,opt,name=probe_url,json=probeUrl,proto3" json:"probe_url,omitempty"`
ProbeInterval int64 `protobuf:"varint,4,opt,name=probe_interval,json=probeInterval,proto3" json:"probe_interval,omitempty"`
PersistentProbeResult bool `protobuf:"varint,5,opt,name=persistent_probe_result,json=persistentProbeResult,proto3" json:"persistent_probe_result,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_app_observatory_config_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_app_observatory_config_proto_msgTypes[5]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_app_observatory_config_proto_rawDescGZIP(), []int{5}
}
func (x *Config) GetSubjectSelector() []string {
if x != nil {
return x.SubjectSelector
}
return nil
}
func (x *Config) GetProbeUrl() string {
if x != nil {
return x.ProbeUrl
}
return ""
}
func (x *Config) GetProbeInterval() int64 {
if x != nil {
return x.ProbeInterval
}
return 0
}
func (x *Config) GetPersistentProbeResult() bool {
if x != nil {
return x.PersistentProbeResult
}
return false
}
var File_app_observatory_config_proto protoreflect.FileDescriptor
const file_app_observatory_config_proto_rawDesc = "" +
"\n" +
"\x1capp/observatory/config.proto\x12\x1av2ray.core.app.observatory\x1a common/protoext/extensions.proto\"W\n" +
"\x11ObservationResult\x12B\n" +
"\x06status\x18\x01 \x03(\v2*.v2ray.core.app.observatory.OutboundStatusR\x06status\"\x9f\x01\n" +
"\x1bHealthPingMeasurementResult\x12\x10\n" +
"\x03all\x18\x01 \x01(\x03R\x03all\x12\x12\n" +
"\x04fail\x18\x02 \x01(\x03R\x04fail\x12\x1c\n" +
"\tdeviation\x18\x03 \x01(\x03R\tdeviation\x12\x18\n" +
"\aaverage\x18\x04 \x01(\x03R\aaverage\x12\x10\n" +
"\x03max\x18\x05 \x01(\x03R\x03max\x12\x10\n" +
"\x03min\x18\x06 \x01(\x03R\x03min\"\xaf\x02\n" +
"\x0eOutboundStatus\x12\x14\n" +
"\x05alive\x18\x01 \x01(\bR\x05alive\x12\x14\n" +
"\x05delay\x18\x02 \x01(\x03R\x05delay\x12*\n" +
"\x11last_error_reason\x18\x03 \x01(\tR\x0flastErrorReason\x12!\n" +
"\foutbound_tag\x18\x04 \x01(\tR\voutboundTag\x12$\n" +
"\x0elast_seen_time\x18\x05 \x01(\x03R\flastSeenTime\x12\"\n" +
"\rlast_try_time\x18\x06 \x01(\x03R\vlastTryTime\x12X\n" +
"\vhealth_ping\x18\a \x01(\v27.v2ray.core.app.observatory.HealthPingMeasurementResultR\n" +
"healthPing\"e\n" +
"\vProbeResult\x12\x14\n" +
"\x05alive\x18\x01 \x01(\bR\x05alive\x12\x14\n" +
"\x05delay\x18\x02 \x01(\x03R\x05delay\x12*\n" +
"\x11last_error_reason\x18\x03 \x01(\tR\x0flastErrorReason\"2\n" +
"\tIntensity\x12%\n" +
"\x0eprobe_interval\x18\x01 \x01(\rR\rprobeInterval\"\xd5\x01\n" +
"\x06Config\x12)\n" +
"\x10subject_selector\x18\x02 \x03(\tR\x0fsubjectSelector\x12\x1b\n" +
"\tprobe_url\x18\x03 \x01(\tR\bprobeUrl\x12%\n" +
"\x0eprobe_interval\x18\x04 \x01(\x03R\rprobeInterval\x126\n" +
"\x17persistent_probe_result\x18\x05 \x01(\bR\x15persistentProbeResult:$\x82\xb5\x18 \n" +
"\aservice\x12\x15backgroundObservatoryBo\n" +
"\x1ecom.v2ray.core.app.observatoryP\x01Z.github.com/v2fly/v2ray-core/v5/app/observatory\xaa\x02\x1aV2Ray.Core.App.Observatoryb\x06proto3"
var (
file_app_observatory_config_proto_rawDescOnce sync.Once
file_app_observatory_config_proto_rawDescData []byte
)
func file_app_observatory_config_proto_rawDescGZIP() []byte {
file_app_observatory_config_proto_rawDescOnce.Do(func() {
file_app_observatory_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_observatory_config_proto_rawDesc), len(file_app_observatory_config_proto_rawDesc)))
})
return file_app_observatory_config_proto_rawDescData
}
var file_app_observatory_config_proto_msgTypes = make([]protoimpl.MessageInfo, 6)
var file_app_observatory_config_proto_goTypes = []any{
(*ObservationResult)(nil), // 0: v2ray.core.app.observatory.ObservationResult
(*HealthPingMeasurementResult)(nil), // 1: v2ray.core.app.observatory.HealthPingMeasurementResult
(*OutboundStatus)(nil), // 2: v2ray.core.app.observatory.OutboundStatus
(*ProbeResult)(nil), // 3: v2ray.core.app.observatory.ProbeResult
(*Intensity)(nil), // 4: v2ray.core.app.observatory.Intensity
(*Config)(nil), // 5: v2ray.core.app.observatory.Config
}
var file_app_observatory_config_proto_depIdxs = []int32{
2, // 0: v2ray.core.app.observatory.ObservationResult.status:type_name -> v2ray.core.app.observatory.OutboundStatus
1, // 1: v2ray.core.app.observatory.OutboundStatus.health_ping:type_name -> v2ray.core.app.observatory.HealthPingMeasurementResult
2, // [2:2] is the sub-list for method output_type
2, // [2:2] is the sub-list for method input_type
2, // [2:2] is the sub-list for extension type_name
2, // [2:2] is the sub-list for extension extendee
0, // [0:2] is the sub-list for field type_name
}
func init() { file_app_observatory_config_proto_init() }
func file_app_observatory_config_proto_init() {
if File_app_observatory_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_observatory_config_proto_rawDesc), len(file_app_observatory_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 6,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_app_observatory_config_proto_goTypes,
DependencyIndexes: file_app_observatory_config_proto_depIdxs,
MessageInfos: file_app_observatory_config_proto_msgTypes,
}.Build()
File_app_observatory_config_proto = out.File
file_app_observatory_config_proto_goTypes = nil
file_app_observatory_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/observatory/explainErrors.go | app/observatory/explainErrors.go | package observatory
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errorCollector struct {
errors *errors.Error
}
func (e *errorCollector) SubmitError(err error) {
if e.errors == nil {
e.errors = newError("underlying connection error").Base(err)
return
}
e.errors = e.errors.Base(newError("underlying connection error").Base(err))
}
func newErrorCollector() *errorCollector {
return &errorCollector{}
}
func (e *errorCollector) UnderlyingError() error {
if e.errors == nil {
return newError("failed to produce report")
}
return e.errors
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/observatory/multiobservatory/multi.go | app/observatory/multiobservatory/multi.go | package multiobservatory
import (
"context"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"github.com/v2fly/v2ray-core/v5/common"
"github.com/v2fly/v2ray-core/v5/common/taggedfeatures"
"github.com/v2fly/v2ray-core/v5/features"
"github.com/v2fly/v2ray-core/v5/features/extension"
)
type Observer struct {
features.TaggedFeatures
config *Config
ctx context.Context
}
func (o Observer) GetObservation(ctx context.Context) (proto.Message, error) {
return common.Must2(o.GetFeaturesByTag("")).(extension.Observatory).GetObservation(ctx)
}
func (o Observer) Type() interface{} {
return extension.ObservatoryType()
}
func New(ctx context.Context, config *Config) (*Observer, error) {
holder, err := taggedfeatures.NewHolderFromConfig(ctx, config.Holders, extension.ObservatoryType())
if err != nil {
return nil, err
}
return &Observer{config: config, ctx: ctx, TaggedFeatures: holder}, nil
}
func (x *Config) UnmarshalJSONPB(unmarshaler *jsonpb.Unmarshaler, bytes []byte) error {
var err error
x.Holders, err = taggedfeatures.LoadJSONConfig(context.TODO(), "service", "background", bytes)
return err
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return New(ctx, config.(*Config))
}))
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/observatory/multiobservatory/config.pb.go | app/observatory/multiobservatory/config.pb.go | package multiobservatory
import (
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
taggedfeatures "github.com/v2fly/v2ray-core/v5/common/taggedfeatures"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
Holders *taggedfeatures.Config `protobuf:"bytes,1,opt,name=holders,proto3" json:"holders,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_app_observatory_multiobservatory_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_app_observatory_multiobservatory_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_app_observatory_multiobservatory_config_proto_rawDescGZIP(), []int{0}
}
func (x *Config) GetHolders() *taggedfeatures.Config {
if x != nil {
return x.Holders
}
return nil
}
var File_app_observatory_multiobservatory_config_proto protoreflect.FileDescriptor
const file_app_observatory_multiobservatory_config_proto_rawDesc = "" +
"\n" +
"-app/observatory/multiobservatory/config.proto\x12+v2ray.core.app.observatory.multiobservatory\x1a$common/taggedfeatures/skeleton.proto\x1a common/protoext/extensions.proto\"m\n" +
"\x06Config\x12B\n" +
"\aholders\x18\x01 \x01(\v2(.v2ray.core.common.taggedfeatures.ConfigR\aholders:\x1f\x82\xb5\x18\x1b\n" +
"\aservice\x12\x10multiobservatoryB\xa2\x01\n" +
"/com.v2ray.core.app.observatory.multiObservatoryP\x01Z?github.com/v2fly/v2ray-core/v5/app/observatory/multiobservatory\xaa\x02+V2Ray.Core.App.Observatory.MultiObservatoryb\x06proto3"
var (
file_app_observatory_multiobservatory_config_proto_rawDescOnce sync.Once
file_app_observatory_multiobservatory_config_proto_rawDescData []byte
)
func file_app_observatory_multiobservatory_config_proto_rawDescGZIP() []byte {
file_app_observatory_multiobservatory_config_proto_rawDescOnce.Do(func() {
file_app_observatory_multiobservatory_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_observatory_multiobservatory_config_proto_rawDesc), len(file_app_observatory_multiobservatory_config_proto_rawDesc)))
})
return file_app_observatory_multiobservatory_config_proto_rawDescData
}
var file_app_observatory_multiobservatory_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_app_observatory_multiobservatory_config_proto_goTypes = []any{
(*Config)(nil), // 0: v2ray.core.app.observatory.multiobservatory.Config
(*taggedfeatures.Config)(nil), // 1: v2ray.core.common.taggedfeatures.Config
}
var file_app_observatory_multiobservatory_config_proto_depIdxs = []int32{
1, // 0: v2ray.core.app.observatory.multiobservatory.Config.holders:type_name -> v2ray.core.common.taggedfeatures.Config
1, // [1:1] is the sub-list for method output_type
1, // [1:1] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_app_observatory_multiobservatory_config_proto_init() }
func file_app_observatory_multiobservatory_config_proto_init() {
if File_app_observatory_multiobservatory_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_observatory_multiobservatory_config_proto_rawDesc), len(file_app_observatory_multiobservatory_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_app_observatory_multiobservatory_config_proto_goTypes,
DependencyIndexes: file_app_observatory_multiobservatory_config_proto_depIdxs,
MessageInfos: file_app_observatory_multiobservatory_config_proto_msgTypes,
}.Build()
File_app_observatory_multiobservatory_config_proto = out.File
file_app_observatory_multiobservatory_config_proto_goTypes = nil
file_app_observatory_multiobservatory_config_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/observatory/command/command.pb.go | app/observatory/command/command.pb.go | package command
import (
observatory "github.com/v2fly/v2ray-core/v5/app/observatory"
_ "github.com/v2fly/v2ray-core/v5/common/protoext"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type GetOutboundStatusRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Tag string `protobuf:"bytes,1,opt,name=Tag,proto3" json:"Tag,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetOutboundStatusRequest) Reset() {
*x = GetOutboundStatusRequest{}
mi := &file_app_observatory_command_command_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetOutboundStatusRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetOutboundStatusRequest) ProtoMessage() {}
func (x *GetOutboundStatusRequest) ProtoReflect() protoreflect.Message {
mi := &file_app_observatory_command_command_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetOutboundStatusRequest.ProtoReflect.Descriptor instead.
func (*GetOutboundStatusRequest) Descriptor() ([]byte, []int) {
return file_app_observatory_command_command_proto_rawDescGZIP(), []int{0}
}
func (x *GetOutboundStatusRequest) GetTag() string {
if x != nil {
return x.Tag
}
return ""
}
type GetOutboundStatusResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Status *observatory.ObservationResult `protobuf:"bytes,1,opt,name=status,proto3" json:"status,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetOutboundStatusResponse) Reset() {
*x = GetOutboundStatusResponse{}
mi := &file_app_observatory_command_command_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetOutboundStatusResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetOutboundStatusResponse) ProtoMessage() {}
func (x *GetOutboundStatusResponse) ProtoReflect() protoreflect.Message {
mi := &file_app_observatory_command_command_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetOutboundStatusResponse.ProtoReflect.Descriptor instead.
func (*GetOutboundStatusResponse) Descriptor() ([]byte, []int) {
return file_app_observatory_command_command_proto_rawDescGZIP(), []int{1}
}
func (x *GetOutboundStatusResponse) GetStatus() *observatory.ObservationResult {
if x != nil {
return x.Status
}
return nil
}
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_app_observatory_command_command_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_app_observatory_command_command_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
func (*Config) Descriptor() ([]byte, []int) {
return file_app_observatory_command_command_proto_rawDescGZIP(), []int{2}
}
var File_app_observatory_command_command_proto protoreflect.FileDescriptor
const file_app_observatory_command_command_proto_rawDesc = "" +
"\n" +
"%app/observatory/command/command.proto\x12\"v2ray.core.app.observatory.command\x1a common/protoext/extensions.proto\x1a\x1capp/observatory/config.proto\",\n" +
"\x18GetOutboundStatusRequest\x12\x10\n" +
"\x03Tag\x18\x01 \x01(\tR\x03Tag\"b\n" +
"\x19GetOutboundStatusResponse\x12E\n" +
"\x06status\x18\x01 \x01(\v2-.v2ray.core.app.observatory.ObservationResultR\x06status\"(\n" +
"\x06Config:\x1e\x82\xb5\x18\x1a\n" +
"\vgrpcservice\x12\vobservatory2\xa9\x01\n" +
"\x12ObservatoryService\x12\x92\x01\n" +
"\x11GetOutboundStatus\x12<.v2ray.core.app.observatory.command.GetOutboundStatusRequest\x1a=.v2ray.core.app.observatory.command.GetOutboundStatusResponse\"\x00B\x87\x01\n" +
"&com.v2ray.core.app.observatory.commandP\x01Z6github.com/v2fly/v2ray-core/v5/app/observatory/command\xaa\x02\"V2Ray.Core.App.Observatory.Commandb\x06proto3"
var (
file_app_observatory_command_command_proto_rawDescOnce sync.Once
file_app_observatory_command_command_proto_rawDescData []byte
)
func file_app_observatory_command_command_proto_rawDescGZIP() []byte {
file_app_observatory_command_command_proto_rawDescOnce.Do(func() {
file_app_observatory_command_command_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_observatory_command_command_proto_rawDesc), len(file_app_observatory_command_command_proto_rawDesc)))
})
return file_app_observatory_command_command_proto_rawDescData
}
var file_app_observatory_command_command_proto_msgTypes = make([]protoimpl.MessageInfo, 3)
var file_app_observatory_command_command_proto_goTypes = []any{
(*GetOutboundStatusRequest)(nil), // 0: v2ray.core.app.observatory.command.GetOutboundStatusRequest
(*GetOutboundStatusResponse)(nil), // 1: v2ray.core.app.observatory.command.GetOutboundStatusResponse
(*Config)(nil), // 2: v2ray.core.app.observatory.command.Config
(*observatory.ObservationResult)(nil), // 3: v2ray.core.app.observatory.ObservationResult
}
var file_app_observatory_command_command_proto_depIdxs = []int32{
3, // 0: v2ray.core.app.observatory.command.GetOutboundStatusResponse.status:type_name -> v2ray.core.app.observatory.ObservationResult
0, // 1: v2ray.core.app.observatory.command.ObservatoryService.GetOutboundStatus:input_type -> v2ray.core.app.observatory.command.GetOutboundStatusRequest
1, // 2: v2ray.core.app.observatory.command.ObservatoryService.GetOutboundStatus:output_type -> v2ray.core.app.observatory.command.GetOutboundStatusResponse
2, // [2:3] is the sub-list for method output_type
1, // [1:2] is the sub-list for method input_type
1, // [1:1] is the sub-list for extension type_name
1, // [1:1] is the sub-list for extension extendee
0, // [0:1] is the sub-list for field type_name
}
func init() { file_app_observatory_command_command_proto_init() }
func file_app_observatory_command_command_proto_init() {
if File_app_observatory_command_command_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_observatory_command_command_proto_rawDesc), len(file_app_observatory_command_command_proto_rawDesc)),
NumEnums: 0,
NumMessages: 3,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_app_observatory_command_command_proto_goTypes,
DependencyIndexes: file_app_observatory_command_command_proto_depIdxs,
MessageInfos: file_app_observatory_command_command_proto_msgTypes,
}.Build()
File_app_observatory_command_command_proto = out.File
file_app_observatory_command_command_proto_goTypes = nil
file_app_observatory_command_command_proto_depIdxs = nil
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
v2fly/v2ray-core | https://github.com/v2fly/v2ray-core/blob/b2c3b2506695d872162baeed95c9525fbfdbfda0/app/observatory/command/errors.generated.go | app/observatory/command/errors.generated.go | package command
import "github.com/v2fly/v2ray-core/v5/common/errors"
type errPathObjHolder struct{}
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).WithPathObj(errPathObjHolder{})
}
| go | MIT | b2c3b2506695d872162baeed95c9525fbfdbfda0 | 2026-01-07T08:36:12.135351Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.