key.go

  1// Copyright 2015 The Go Authors. All rights reserved.
  2// Use of this source code is governed by a BSD-style
  3// license that can be found in the LICENSE file.
  4
  5//go:build windows
  6
  7// Package registry provides access to the Windows registry.
  8//
  9// Here is a simple example, opening a registry key and reading a string value from it.
 10//
 11//	k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion`, registry.QUERY_VALUE)
 12//	if err != nil {
 13//		log.Fatal(err)
 14//	}
 15//	defer k.Close()
 16//
 17//	s, _, err := k.GetStringValue("SystemRoot")
 18//	if err != nil {
 19//		log.Fatal(err)
 20//	}
 21//	fmt.Printf("Windows system root is %q\n", s)
 22package registry
 23
 24import (
 25	"io"
 26	"runtime"
 27	"syscall"
 28	"time"
 29)
 30
 31const (
 32	// Registry key security and access rights.
 33	// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724878.aspx
 34	// for details.
 35	ALL_ACCESS         = 0xf003f
 36	CREATE_LINK        = 0x00020
 37	CREATE_SUB_KEY     = 0x00004
 38	ENUMERATE_SUB_KEYS = 0x00008
 39	EXECUTE            = 0x20019
 40	NOTIFY             = 0x00010
 41	QUERY_VALUE        = 0x00001
 42	READ               = 0x20019
 43	SET_VALUE          = 0x00002
 44	WOW64_32KEY        = 0x00200
 45	WOW64_64KEY        = 0x00100
 46	WRITE              = 0x20006
 47)
 48
 49// Key is a handle to an open Windows registry key.
 50// Keys can be obtained by calling OpenKey; there are
 51// also some predefined root keys such as CURRENT_USER.
 52// Keys can be used directly in the Windows API.
 53type Key syscall.Handle
 54
 55const (
 56	// Windows defines some predefined root keys that are always open.
 57	// An application can use these keys as entry points to the registry.
 58	// Normally these keys are used in OpenKey to open new keys,
 59	// but they can also be used anywhere a Key is required.
 60	CLASSES_ROOT     = Key(syscall.HKEY_CLASSES_ROOT)
 61	CURRENT_USER     = Key(syscall.HKEY_CURRENT_USER)
 62	LOCAL_MACHINE    = Key(syscall.HKEY_LOCAL_MACHINE)
 63	USERS            = Key(syscall.HKEY_USERS)
 64	CURRENT_CONFIG   = Key(syscall.HKEY_CURRENT_CONFIG)
 65	PERFORMANCE_DATA = Key(syscall.HKEY_PERFORMANCE_DATA)
 66)
 67
 68// Close closes open key k.
 69func (k Key) Close() error {
 70	return syscall.RegCloseKey(syscall.Handle(k))
 71}
 72
 73// OpenKey opens a new key with path name relative to key k.
 74// It accepts any open key, including CURRENT_USER and others,
 75// and returns the new key and an error.
 76// The access parameter specifies desired access rights to the
 77// key to be opened.
 78func OpenKey(k Key, path string, access uint32) (Key, error) {
 79	p, err := syscall.UTF16PtrFromString(path)
 80	if err != nil {
 81		return 0, err
 82	}
 83	var subkey syscall.Handle
 84	err = syscall.RegOpenKeyEx(syscall.Handle(k), p, 0, access, &subkey)
 85	if err != nil {
 86		return 0, err
 87	}
 88	return Key(subkey), nil
 89}
 90
 91// OpenRemoteKey opens a predefined registry key on another
 92// computer pcname. The key to be opened is specified by k, but
 93// can only be one of LOCAL_MACHINE, PERFORMANCE_DATA or USERS.
 94// If pcname is "", OpenRemoteKey returns local computer key.
 95func OpenRemoteKey(pcname string, k Key) (Key, error) {
 96	var err error
 97	var p *uint16
 98	if pcname != "" {
 99		p, err = syscall.UTF16PtrFromString(`\\` + pcname)
100		if err != nil {
101			return 0, err
102		}
103	}
104	var remoteKey syscall.Handle
105	err = regConnectRegistry(p, syscall.Handle(k), &remoteKey)
106	if err != nil {
107		return 0, err
108	}
109	return Key(remoteKey), nil
110}
111
112// ReadSubKeyNames returns the names of subkeys of key k.
113// The parameter n controls the number of returned names,
114// analogous to the way os.File.Readdirnames works.
115func (k Key) ReadSubKeyNames(n int) ([]string, error) {
116	// RegEnumKeyEx must be called repeatedly and to completion.
117	// During this time, this goroutine cannot migrate away from
118	// its current thread. See https://golang.org/issue/49320 and
119	// https://golang.org/issue/49466.
120	runtime.LockOSThread()
121	defer runtime.UnlockOSThread()
122
123	names := make([]string, 0)
124	// Registry key size limit is 255 bytes and described there:
125	// https://msdn.microsoft.com/library/windows/desktop/ms724872.aspx
126	buf := make([]uint16, 256) //plus extra room for terminating zero byte
127loopItems:
128	for i := uint32(0); ; i++ {
129		if n > 0 {
130			if len(names) == n {
131				return names, nil
132			}
133		}
134		l := uint32(len(buf))
135		for {
136			err := syscall.RegEnumKeyEx(syscall.Handle(k), i, &buf[0], &l, nil, nil, nil, nil)
137			if err == nil {
138				break
139			}
140			if err == syscall.ERROR_MORE_DATA {
141				// Double buffer size and try again.
142				l = uint32(2 * len(buf))
143				buf = make([]uint16, l)
144				continue
145			}
146			if err == _ERROR_NO_MORE_ITEMS {
147				break loopItems
148			}
149			return names, err
150		}
151		names = append(names, syscall.UTF16ToString(buf[:l]))
152	}
153	if n > len(names) {
154		return names, io.EOF
155	}
156	return names, nil
157}
158
159// CreateKey creates a key named path under open key k.
160// CreateKey returns the new key and a boolean flag that reports
161// whether the key already existed.
162// The access parameter specifies the access rights for the key
163// to be created.
164func CreateKey(k Key, path string, access uint32) (newk Key, openedExisting bool, err error) {
165	var h syscall.Handle
166	var d uint32
167	var pathPointer *uint16
168	pathPointer, err = syscall.UTF16PtrFromString(path)
169	if err != nil {
170		return 0, false, err
171	}
172	err = regCreateKeyEx(syscall.Handle(k), pathPointer,
173		0, nil, _REG_OPTION_NON_VOLATILE, access, nil, &h, &d)
174	if err != nil {
175		return 0, false, err
176	}
177	return Key(h), d == _REG_OPENED_EXISTING_KEY, nil
178}
179
180// DeleteKey deletes the subkey path of key k and its values.
181func DeleteKey(k Key, path string) error {
182	pathPointer, err := syscall.UTF16PtrFromString(path)
183	if err != nil {
184		return err
185	}
186	return regDeleteKey(syscall.Handle(k), pathPointer)
187}
188
189// A KeyInfo describes the statistics of a key. It is returned by Stat.
190type KeyInfo struct {
191	SubKeyCount     uint32
192	MaxSubKeyLen    uint32 // size of the key's subkey with the longest name, in Unicode characters, not including the terminating zero byte
193	ValueCount      uint32
194	MaxValueNameLen uint32 // size of the key's longest value name, in Unicode characters, not including the terminating zero byte
195	MaxValueLen     uint32 // longest data component among the key's values, in bytes
196	lastWriteTime   syscall.Filetime
197}
198
199// ModTime returns the key's last write time.
200func (ki *KeyInfo) ModTime() time.Time {
201	return time.Unix(0, ki.lastWriteTime.Nanoseconds())
202}
203
204// Stat retrieves information about the open key k.
205func (k Key) Stat() (*KeyInfo, error) {
206	var ki KeyInfo
207	err := syscall.RegQueryInfoKey(syscall.Handle(k), nil, nil, nil,
208		&ki.SubKeyCount, &ki.MaxSubKeyLen, nil, &ki.ValueCount,
209		&ki.MaxValueNameLen, &ki.MaxValueLen, nil, &ki.lastWriteTime)
210	if err != nil {
211		return nil, err
212	}
213	return &ki, nil
214}