key.go 6.3 KB

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