wininfo_windows.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. //go:build windows
  2. package wininfo
  3. import (
  4. "encoding/binary"
  5. "errors"
  6. "strconv"
  7. "strings"
  8. "unsafe"
  9. "github.com/yusufpapurcu/wmi"
  10. "golang.org/x/sys/windows"
  11. "golang.org/x/sys/windows/registry"
  12. )
  13. var (
  14. kernel32 = windows.NewLazySystemDLL("kernel32.dll")
  15. procGlobalMemoryStatusEx = kernel32.NewProc("GlobalMemoryStatusEx")
  16. procGetSystemTimes = kernel32.NewProc("GetSystemTimes")
  17. procGetPhysicallyInstalledSystemMemory = kernel32.NewProc("GetPhysicallyInstalledSystemMemory")
  18. //Device setup classes and the disk device interface (devguid.h, ntddstor.h)
  19. guidDevClassUSB = windows.GUID{Data1: 0x36fc9e60, Data2: 0xc465, Data3: 0x11cf, Data4: [8]byte{0x80, 0x56, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00}}
  20. guidDevClassDiskDrive = windows.GUID{Data1: 0x4d36e967, Data2: 0xe325, Data3: 0x11ce, Data4: [8]byte{0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18}}
  21. guidDevInterfaceDisk = windows.GUID{Data1: 0x53f56307, Data2: 0xb6bf, Data3: 0x11d0, Data4: [8]byte{0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b}}
  22. )
  23. const (
  24. ioctlDiskGetDriveGeometryEx = 0x000700a0 //IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, FILE_ANY_ACCESS
  25. )
  26. // call runs a kernel32 function that returns a BOOL
  27. func call(proc *windows.LazyProc, args ...uintptr) error {
  28. if err := proc.Find(); err != nil {
  29. return err
  30. }
  31. r, _, err := proc.Call(args...)
  32. if r == 0 {
  33. return err
  34. }
  35. return nil
  36. }
  37. // ProcessorInfo reads the first CPU from the registry
  38. func ProcessorInfo() (Processor, error) {
  39. k, err := registry.OpenKey(registry.LOCAL_MACHINE, `HARDWARE\DESCRIPTION\System\CentralProcessor\0`, registry.QUERY_VALUE)
  40. if err != nil {
  41. return Processor{}, err
  42. }
  43. defer k.Close()
  44. p := Processor{}
  45. if s, _, err := k.GetStringValue("ProcessorNameString"); err == nil {
  46. p.Name = strings.TrimSpace(s)
  47. }
  48. if s, _, err := k.GetStringValue("Identifier"); err == nil {
  49. p.Identifier = strings.TrimSpace(s)
  50. }
  51. if v, _, err := k.GetIntegerValue("~MHz"); err == nil {
  52. p.MHz = uint32(v)
  53. }
  54. return p, nil
  55. }
  56. // OSName is the Windows edition, e.g. Microsoft Windows 11 Pro
  57. func OSName() (string, error) {
  58. k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion`, registry.QUERY_VALUE)
  59. if err != nil {
  60. return "", err
  61. }
  62. defer k.Close()
  63. product, _, err := k.GetStringValue("ProductName")
  64. if err != nil {
  65. return "", err
  66. }
  67. build := 0
  68. if s, _, err := k.GetStringValue("CurrentBuildNumber"); err == nil {
  69. build, _ = strconv.Atoi(s)
  70. }
  71. return osDisplayName(product, build), nil
  72. }
  73. // memoryStatusEx is MEMORYSTATUSEX
  74. type memoryStatusEx struct {
  75. Length uint32
  76. MemoryLoad uint32
  77. TotalPhys uint64
  78. AvailPhys uint64
  79. TotalPageFile uint64
  80. AvailPageFile uint64
  81. TotalVirtual uint64
  82. AvailVirtual uint64
  83. AvailExtendedVirtual uint64
  84. }
  85. // MemoryStatus is the physical memory Windows can use and how much is free
  86. func MemoryStatus() (Memory, error) {
  87. m := memoryStatusEx{}
  88. m.Length = uint32(unsafe.Sizeof(m))
  89. if err := call(procGlobalMemoryStatusEx, uintptr(unsafe.Pointer(&m))); err != nil {
  90. return Memory{}, err
  91. }
  92. return Memory{Total: m.TotalPhys, Available: m.AvailPhys}, nil
  93. }
  94. // InstalledMemory is the memory installed in the machine in bytes, the sum
  95. // of its memory modules. It falls back to the usable memory when the
  96. // firmware does not report it (some virtual machines).
  97. func InstalledMemory() (uint64, error) {
  98. var kb uint64
  99. if err := call(procGetPhysicallyInstalledSystemMemory, uintptr(unsafe.Pointer(&kb))); err == nil && kb > 0 {
  100. return kb * 1024, nil
  101. }
  102. m, err := MemoryStatus()
  103. if err != nil {
  104. return 0, err
  105. }
  106. return m.Total, nil
  107. }
  108. func filetime(f windows.Filetime) uint64 {
  109. return uint64(f.HighDateTime)<<32 | uint64(f.LowDateTime)
  110. }
  111. // SystemTimes samples the system wide CPU times; compare two samples with
  112. // CPULoad
  113. func SystemTimes() (CPUTimes, error) {
  114. var idle, kernel, user windows.Filetime
  115. if err := call(procGetSystemTimes, uintptr(unsafe.Pointer(&idle)), uintptr(unsafe.Pointer(&kernel)), uintptr(unsafe.Pointer(&user))); err != nil {
  116. return CPUTimes{}, err
  117. }
  118. return CPUTimes{Idle: filetime(idle), Kernel: filetime(kernel), User: filetime(user)}, nil
  119. }
  120. // LogicalDisks lists the drive letters with their file system and space
  121. func LogicalDisks() ([]LogicalDisk, error) {
  122. mask, err := windows.GetLogicalDrives()
  123. if err != nil {
  124. return nil, err
  125. }
  126. disks := []LogicalDisk{}
  127. for i := 0; i < 26; i++ {
  128. if mask&(1<<uint(i)) == 0 {
  129. continue
  130. }
  131. letter := string(rune('A'+i)) + ":"
  132. root, err := windows.UTF16PtrFromString(letter + `\`)
  133. if err != nil {
  134. continue
  135. }
  136. if windows.GetDriveType(root) == windows.DRIVE_NO_ROOT_DIR {
  137. continue
  138. }
  139. disk := LogicalDisk{Root: letter}
  140. fsName := make([]uint16, windows.MAX_PATH+1)
  141. if windows.GetVolumeInformation(root, nil, 0, nil, nil, nil, &fsName[0], uint32(len(fsName))) == nil {
  142. disk.FileSystem = windows.UTF16ToString(fsName)
  143. }
  144. var freeToCaller, total, free uint64
  145. if windows.GetDiskFreeSpaceEx(root, &freeToCaller, &total, &free) == nil {
  146. disk.Size, disk.Free, disk.Ready = total, free, true
  147. }
  148. disks = append(disks, disk)
  149. }
  150. return disks, nil
  151. }
  152. // NetAdapters lists the network adapters known to the IP stack, with their
  153. // link state, speed and duplex
  154. func NetAdapters() ([]NetAdapter, error) {
  155. flags := uint32(windows.GAA_FLAG_SKIP_UNICAST | windows.GAA_FLAG_SKIP_ANYCAST | windows.GAA_FLAG_SKIP_MULTICAST | windows.GAA_FLAG_SKIP_DNS_SERVER)
  156. size := uint32(16 << 10)
  157. var buf []byte
  158. for attempt := 0; ; attempt++ {
  159. buf = make([]byte, size)
  160. err := windows.GetAdaptersAddresses(windows.AF_UNSPEC, flags, 0, (*windows.IpAdapterAddresses)(unsafe.Pointer(&buf[0])), &size)
  161. if err == nil {
  162. break
  163. }
  164. if errors.Is(err, windows.ERROR_NO_DATA) {
  165. return []NetAdapter{}, nil
  166. }
  167. //Adapters can appear between the two calls: grow and retry a few times
  168. if !errors.Is(err, windows.ERROR_BUFFER_OVERFLOW) || attempt >= 3 {
  169. return nil, err
  170. }
  171. }
  172. list := []NetAdapter{}
  173. for a := (*windows.IpAdapterAddresses)(unsafe.Pointer(&buf[0])); a != nil; a = a.Next {
  174. list = append(list, NetAdapter{
  175. Name: windows.UTF16PtrToString(a.FriendlyName),
  176. Description: windows.UTF16PtrToString(a.Description),
  177. OperStatus: a.OperStatus,
  178. Speed: a.TransmitLinkSpeed,
  179. Loopback: a.IfType == windows.IF_TYPE_SOFTWARE_LOOPBACK,
  180. })
  181. }
  182. duplex := adapterDuplexes()
  183. for i := range list {
  184. list[i].Duplex = duplex[list[i].Name]
  185. }
  186. return list, nil
  187. }
  188. // msftNetAdapter is the part of MSFT_NetAdapter (root\StandardCimv2) the IP
  189. // Helper API does not report. Its Name is the adapter's friendly name.
  190. type msftNetAdapter struct {
  191. Name string
  192. FullDuplex *bool
  193. }
  194. /*
  195. adapterDuplexes reads the duplex state of the adapters the way Get-NetAdapter
  196. does, from MSFT_NetAdapter, but through WMI in this process (COM), so no
  197. PowerShell is started. The legacy NDIS query IOCTL cannot do it: it only
  198. passes a fixed list of OIDs, and the duplex state is not on it. Adapters
  199. without a value are left out, so they read as DuplexUnknown.
  200. */
  201. func adapterDuplexes() map[string]Duplex {
  202. result := map[string]Duplex{}
  203. rows := []msftNetAdapter{}
  204. client := &wmi.Client{PtrNil: true}
  205. if err := client.Query("SELECT Name, FullDuplex FROM MSFT_NetAdapter", &rows, nil, `root\StandardCimv2`); err != nil {
  206. return result
  207. }
  208. for _, row := range rows {
  209. if row.FullDuplex == nil {
  210. continue
  211. }
  212. if *row.FullDuplex {
  213. result[row.Name] = DuplexFull
  214. } else {
  215. result[row.Name] = DuplexHalf
  216. }
  217. }
  218. return result
  219. }
  220. // deviceName is the first non empty registry name of a device
  221. func deviceName(set windows.DevInfo, data *windows.DevInfoData, properties ...windows.SPDRP) string {
  222. for _, property := range properties {
  223. value, err := set.DeviceRegistryProperty(data, property)
  224. if err != nil {
  225. continue
  226. }
  227. if s, ok := value.(string); ok && strings.TrimSpace(s) != "" {
  228. return strings.TrimSpace(s)
  229. }
  230. }
  231. return ""
  232. }
  233. // eachPresentDevice calls fn for every device of a setup class that is
  234. // plugged in
  235. func eachPresentDevice(class *windows.GUID, fn func(set windows.DevInfo, data *windows.DevInfoData)) error {
  236. set, err := windows.SetupDiGetClassDevsEx(class, "", 0, windows.DIGCF_PRESENT, 0, "")
  237. if err != nil {
  238. return err
  239. }
  240. defer set.Close()
  241. for i := 0; ; i++ {
  242. data, err := set.EnumDeviceInfo(i)
  243. if err != nil {
  244. //ERROR_NO_MORE_ITEMS ends the list; anything else would repeat
  245. break
  246. }
  247. fn(set, data)
  248. }
  249. return nil
  250. }
  251. // USBDevices lists the description of every USB device and hub that is
  252. // plugged in, like Win32_USBHub. Host controllers (PCI devices) are left
  253. // out.
  254. func USBDevices() ([]string, error) {
  255. names := []string{}
  256. err := eachPresentDevice(&guidDevClassUSB, func(set windows.DevInfo, data *windows.DevInfoData) {
  257. id, err := set.DeviceInstanceID(data)
  258. if err != nil || !strings.HasPrefix(strings.ToUpper(id), `USB\`) {
  259. return
  260. }
  261. if name := deviceName(set, data, windows.SPDRP_DEVICEDESC, windows.SPDRP_FRIENDLYNAME); name != "" {
  262. names = append(names, name)
  263. }
  264. })
  265. return names, err
  266. }
  267. // PhysicalDisks lists the disk drives with their model and size
  268. func PhysicalDisks() ([]PhysicalDisk, error) {
  269. disks := []PhysicalDisk{}
  270. err := eachPresentDevice(&guidDevClassDiskDrive, func(set windows.DevInfo, data *windows.DevInfoData) {
  271. disk := PhysicalDisk{Model: deviceName(set, data, windows.SPDRP_FRIENDLYNAME, windows.SPDRP_DEVICEDESC)}
  272. if id, err := set.DeviceInstanceID(data); err == nil {
  273. paths, err := windows.CM_Get_Device_Interface_List(id, &guidDevInterfaceDisk, windows.CM_GET_DEVICE_INTERFACE_LIST_PRESENT)
  274. if err == nil && len(paths) > 0 {
  275. disk.Size = diskSize(paths[0])
  276. }
  277. }
  278. disks = append(disks, disk)
  279. })
  280. return disks, err
  281. }
  282. // diskSize asks a disk for its size. Opening it without read or write access
  283. // is enough for the geometry and needs no administrator rights.
  284. func diskSize(devicePath string) uint64 {
  285. path, err := windows.UTF16PtrFromString(devicePath)
  286. if err != nil {
  287. return 0
  288. }
  289. h, err := windows.CreateFile(path, 0, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, 0, 0)
  290. if err != nil {
  291. return 0
  292. }
  293. defer windows.CloseHandle(h)
  294. //DISK_GEOMETRY_EX: a 24 byte DISK_GEOMETRY, then the disk size (LARGE_INTEGER)
  295. buf := make([]byte, 256)
  296. var n uint32
  297. if windows.DeviceIoControl(h, ioctlDiskGetDriveGeometryEx, nil, 0, &buf[0], uint32(len(buf)), &n, nil) != nil || n < 32 {
  298. return 0
  299. }
  300. size := int64(binary.LittleEndian.Uint64(buf[24:32]))
  301. if size < 0 {
  302. return 0
  303. }
  304. return uint64(size)
  305. }