key.go 6.4 KB

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