key.go 6.3 KB

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