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// +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)
22//
23// NOTE: This package is a copy of golang.org/x/sys/windows/registry
24// with KeyInfo.ModTime removed to prevent dependency cycles.
25//
26package registry
27
28import (
29	"io"
30	"syscall"
31)
32
33const (
34	// Registry key security and access rights.
35	// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724878.aspx
36	// for details.
37	ALL_ACCESS         = 0xf003f
38	CREATE_LINK        = 0x00020
39	CREATE_SUB_KEY     = 0x00004
40	ENUMERATE_SUB_KEYS = 0x00008
41	EXECUTE            = 0x20019
42	NOTIFY             = 0x00010
43	QUERY_VALUE        = 0x00001
44	READ               = 0x20019
45	SET_VALUE          = 0x00002
46	WOW64_32KEY        = 0x00200
47	WOW64_64KEY        = 0x00100
48	WRITE              = 0x20006
49)
50
51// Key is a handle to an open Windows registry key.
52// Keys can be obtained by calling OpenKey; there are
53// also some predefined root keys such as CURRENT_USER.
54// Keys can be used directly in the Windows API.
55type Key syscall.Handle
56
57const (
58	// Windows defines some predefined root keys that are always open.
59	// An application can use these keys as entry points to the registry.
60	// Normally these keys are used in OpenKey to open new keys,
61	// but they can also be used anywhere a Key is required.
62	CLASSES_ROOT   = Key(syscall.HKEY_CLASSES_ROOT)
63	CURRENT_USER   = Key(syscall.HKEY_CURRENT_USER)
64	LOCAL_MACHINE  = Key(syscall.HKEY_LOCAL_MACHINE)
65	USERS          = Key(syscall.HKEY_USERS)
66	CURRENT_CONFIG = Key(syscall.HKEY_CURRENT_CONFIG)
67)
68
69// Close closes open key k.
70func (k Key) Close() error {
71	return syscall.RegCloseKey(syscall.Handle(k))
72}
73
74// OpenKey opens a new key with path name relative to key k.
75// It accepts any open key, including CURRENT_USER and others,
76// and returns the new key and an error.
77// The access parameter specifies desired access rights to the
78// key to be opened.
79func OpenKey(k Key, path string, access uint32) (Key, error) {
80	p, err := syscall.UTF16PtrFromString(path)
81	if err != nil {
82		return 0, err
83	}
84	var subkey syscall.Handle
85	err = syscall.RegOpenKeyEx(syscall.Handle(k), p, 0, access, &subkey)
86	if err != nil {
87		return 0, err
88	}
89	return Key(subkey), nil
90}
91
92// ReadSubKeyNames returns the names of subkeys of key k.
93// The parameter n controls the number of returned names,
94// analogous to the way os.File.Readdirnames works.
95func (k Key) ReadSubKeyNames(n int) ([]string, error) {
96	ki, err := k.Stat()
97	if err != nil {
98		return nil, err
99	}
100	names := make([]string, 0, ki.SubKeyCount)
101	buf := make([]uint16, ki.MaxSubKeyLen+1) // extra room for terminating zero byte
102loopItems:
103	for i := uint32(0); ; i++ {
104		if n > 0 {
105			if len(names) == n {
106				return names, nil
107			}
108		}
109		l := uint32(len(buf))
110		for {
111			err := syscall.RegEnumKeyEx(syscall.Handle(k), i, &buf[0], &l, nil, nil, nil, nil)
112			if err == nil {
113				break
114			}
115			if err == syscall.ERROR_MORE_DATA {
116				// Double buffer size and try again.
117				l = uint32(2 * len(buf))
118				buf = make([]uint16, l)
119				continue
120			}
121			if err == _ERROR_NO_MORE_ITEMS {
122				break loopItems
123			}
124			return names, err
125		}
126		names = append(names, syscall.UTF16ToString(buf[:l]))
127	}
128	if n > len(names) {
129		return names, io.EOF
130	}
131	return names, nil
132}
133
134// CreateKey creates a key named path under open key k.
135// CreateKey returns the new key and a boolean flag that reports
136// whether the key already existed.
137// The access parameter specifies the access rights for the key
138// to be created.
139func CreateKey(k Key, path string, access uint32) (newk Key, openedExisting bool, err error) {
140	var h syscall.Handle
141	var d uint32
142	err = regCreateKeyEx(syscall.Handle(k), syscall.StringToUTF16Ptr(path),
143		0, nil, _REG_OPTION_NON_VOLATILE, access, nil, &h, &d)
144	if err != nil {
145		return 0, false, err
146	}
147	return Key(h), d == _REG_OPENED_EXISTING_KEY, nil
148}
149
150// DeleteKey deletes the subkey path of key k and its values.
151func DeleteKey(k Key, path string) error {
152	return regDeleteKey(syscall.Handle(k), syscall.StringToUTF16Ptr(path))
153}
154
155// A KeyInfo describes the statistics of a key. It is returned by Stat.
156type KeyInfo struct {
157	SubKeyCount     uint32
158	MaxSubKeyLen    uint32 // size of the key's subkey with the longest name, in Unicode characters, not including the terminating zero byte
159	ValueCount      uint32
160	MaxValueNameLen uint32 // size of the key's longest value name, in Unicode characters, not including the terminating zero byte
161	MaxValueLen     uint32 // longest data component among the key's values, in bytes
162	lastWriteTime   syscall.Filetime
163}
164
165// Stat retrieves information about the open key k.
166func (k Key) Stat() (*KeyInfo, error) {
167	var ki KeyInfo
168	err := syscall.RegQueryInfoKey(syscall.Handle(k), nil, nil, nil,
169		&ki.SubKeyCount, &ki.MaxSubKeyLen, nil, &ki.ValueCount,
170		&ki.MaxValueNameLen, &ki.MaxValueLen, nil, &ki.lastWriteTime)
171	if err != nil {
172		return nil, err
173	}
174	return &ki, nil
175}
176