golang.org/x/sys@v0.9.0/windows/registry/key.go (about)

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