hardwareinfo.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. package hardwareinfo
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "os/exec"
  7. "runtime"
  8. "strings"
  9. "imuslab.com/arozos/mod/info/logger"
  10. "imuslab.com/arozos/mod/utils"
  11. )
  12. /*
  13. Hardware Info
  14. author: tobychui
  15. This module is a migrated module from the original system.info.go script
  16. */
  17. type CPUInfo struct {
  18. Model string
  19. Freq string
  20. Instruction string
  21. Hardware string
  22. Revision string
  23. }
  24. type LogicalDisk struct {
  25. DriveLetter string
  26. FileSystem string
  27. FreeSpace string
  28. }
  29. type ArOZInfo struct {
  30. BuildVersion string
  31. DeviceVendor string
  32. DeviceModel string
  33. VendorIcon string
  34. SN string
  35. HostOS string
  36. CPUArch string
  37. HostName string
  38. }
  39. type Server struct {
  40. hostInfo ArOZInfo
  41. }
  42. func NewInfoServer(a ArOZInfo) *Server {
  43. return &Server{
  44. hostInfo: a,
  45. }
  46. }
  47. /*
  48. PrintSystemHardwareDebugMessage print system information on Windows.
  49. Which is lagging but helpful for debugging wmic on Windows
  50. */
  51. func PrintSystemHardwareDebugMessage() {
  52. logger.PrintAndLog("Hardwareinfo", "Windows Version: "+wmicGetinfo("os", "Caption")[0], nil)
  53. logger.PrintAndLog("Hardwareinfo", "Total Memory: "+wmicGetinfo("ComputerSystem", "TotalPhysicalMemory")[0]+"B", nil)
  54. logger.PrintAndLog("Hardwareinfo", "Processor: "+wmicGetinfo("cpu", "Name")[0], nil)
  55. logger.PrintAndLog("Hardwareinfo", "Following disk was detected:", nil)
  56. for _, info := range wmicGetinfo("diskdrive", "Model") {
  57. logger.PrintAndLog("Hardwareinfo", fmt.Sprint(info), nil)
  58. }
  59. }
  60. func (s *Server) GetArOZInfo(w http.ResponseWriter, r *http.Request) {
  61. var jsonData []byte
  62. jsonData, err := json.Marshal(s.hostInfo)
  63. if err != nil {
  64. logger.PrintAndLog("Hardwareinfo", fmt.Sprint(err), nil)
  65. return
  66. }
  67. loadImage, _ := utils.GetPara(r, "icon")
  68. if loadImage != "true" {
  69. t := ArOZInfo{}
  70. json.Unmarshal(jsonData, &t)
  71. t.VendorIcon = ""
  72. jsonData, _ = json.Marshal(t)
  73. }
  74. utils.SendJSONResponse(w, string(jsonData))
  75. }
  76. // wmicClassName maps classic `wmic` aliases to CIM / Win32 class names.
  77. func wmicClassName(wmicName string) string {
  78. if len(wmicName) > 6 && wmicName[0:6] == "Win32_" {
  79. return wmicName
  80. }
  81. switch strings.ToLower(wmicName) {
  82. case "cpu":
  83. return "Win32_Processor"
  84. case "os":
  85. return "Win32_OperatingSystem"
  86. case "computersystem":
  87. return "Win32_ComputerSystem"
  88. case "diskdrive":
  89. return "Win32_DiskDrive"
  90. case "nic":
  91. return "Win32_NetworkAdapter"
  92. case "logicaldisk":
  93. return "Win32_LogicalDisk"
  94. case "memorychip":
  95. return "Win32_PhysicalMemory"
  96. default:
  97. return "Win32_" + wmicName
  98. }
  99. }
  100. // cimGetinfo reads a WMI property via PowerShell Get-CimInstance.
  101. // Modern Windows 11 (24H2+) no longer ships `wmic.exe` by default; CIM is the
  102. // supported replacement and exposes the same Win32_* properties.
  103. func cimGetinfo(wmicName string, itemName string) []string {
  104. className := wmicClassName(wmicName)
  105. psClass := strings.ReplaceAll(className, "'", "''")
  106. psItem := strings.ReplaceAll(itemName, "'", "''")
  107. script := fmt.Sprintf(
  108. "Get-CimInstance -ClassName '%s' | ForEach-Object { $p = $_.PSObject.Properties['%s']; if ($null -ne $p -and $null -ne $p.Value) { [string]$p.Value } }",
  109. psClass, psItem,
  110. )
  111. cmd := exec.Command("powershell.exe",
  112. "-NoProfile",
  113. "-NonInteractive",
  114. "-WindowStyle", "Hidden",
  115. "-ExecutionPolicy", "Bypass",
  116. "-Command", script,
  117. )
  118. out, err := cmd.CombinedOutput()
  119. if err != nil {
  120. return nil
  121. }
  122. var info []string
  123. for _, line := range strings.Split(string(out), "\n") {
  124. line = strings.TrimSpace(strings.ReplaceAll(line, "\r", ""))
  125. if line != "" {
  126. info = append(info, line)
  127. }
  128. }
  129. return info
  130. }
  131. // legacyWmicGetinfo keeps the original `wmic` path for older Windows hosts
  132. // that still ship the binary (pre-removal / optional Feature on Demand).
  133. func legacyWmicGetinfo(wmicName string, itemName string) []string {
  134. var info []string
  135. cmd := exec.Command("wmic", wmicName, "list", "full", "/format:list")
  136. if wmicName == "os" {
  137. cmd = exec.Command("wmic", wmicName, "get", "*", "/format:list")
  138. }
  139. if len(wmicName) > 6 && wmicName[0:6] == "Win32_" {
  140. cmd = exec.Command("wmic", "path", wmicName, "get", "*", "/format:list")
  141. }
  142. out, _ := cmd.CombinedOutput()
  143. for _, strConfig := range strings.Split(string(out), "\n") {
  144. if strings.Contains(strConfig, "=") {
  145. parts := strings.SplitN(strConfig, "=", 2)
  146. if parts[0] == itemName {
  147. info = append(info, strings.Replace(parts[1], "\r", "", -1))
  148. }
  149. }
  150. }
  151. return info
  152. }
  153. func wmicGetinfo(wmicName string, itemName string) []string {
  154. if runtime.GOOS == "windows" {
  155. // Prefer CIM: wmic.exe was removed from many Windows 11 installs.
  156. if info := cimGetinfo(wmicName, itemName); len(info) > 0 {
  157. return info
  158. }
  159. if info := legacyWmicGetinfo(wmicName, itemName); len(info) > 0 {
  160. return info
  161. }
  162. }
  163. return []string{"Undefined"}
  164. }
  165. func filterGrepResults(result string, sep string) string {
  166. if strings.Contains(result, sep) == false {
  167. return result
  168. }
  169. tmp := strings.Split(result, sep)
  170. resultString := tmp[1]
  171. return strings.TrimSpace(resultString)
  172. }
  173. // cimGetinfoRows reads multiple WMI properties of the same class in a single
  174. // query, keeping the values of one instance together on one row. Properties
  175. // that are null (or missing on that instance) come back as an empty string so
  176. // every row always has len(itemNames) columns.
  177. func cimGetinfoRows(wmicName string, itemNames []string) [][]string {
  178. className := wmicClassName(wmicName)
  179. psClass := strings.ReplaceAll(className, "'", "''")
  180. quotedItems := make([]string, 0, len(itemNames))
  181. for _, itemName := range itemNames {
  182. quotedItems = append(quotedItems, "'"+strings.ReplaceAll(itemName, "'", "''")+"'")
  183. }
  184. script := fmt.Sprintf(
  185. "Get-CimInstance -ClassName '%s' | ForEach-Object { $o = $_; (@(%s) | ForEach-Object { $p = $o.PSObject.Properties[$_]; if ($null -ne $p -and $null -ne $p.Value) { [string]$p.Value } else { '' } }) -join \"`t\" }",
  186. psClass, strings.Join(quotedItems, ","),
  187. )
  188. cmd := exec.Command("powershell.exe",
  189. "-NoProfile",
  190. "-NonInteractive",
  191. "-WindowStyle", "Hidden",
  192. "-ExecutionPolicy", "Bypass",
  193. "-Command", script,
  194. )
  195. out, err := cmd.CombinedOutput()
  196. if err != nil {
  197. return nil
  198. }
  199. var rows [][]string
  200. for _, line := range strings.Split(string(out), "\n") {
  201. line = strings.ReplaceAll(line, "\r", "")
  202. if strings.TrimSpace(line) == "" {
  203. continue
  204. }
  205. cols := strings.Split(line, "\t")
  206. if len(cols) != len(itemNames) {
  207. //Unexpected output shape, discard this row instead of misaligning it
  208. continue
  209. }
  210. for i := range cols {
  211. cols[i] = strings.TrimSpace(cols[i])
  212. }
  213. rows = append(rows, cols)
  214. }
  215. return rows
  216. }
  217. /*
  218. wmicGetinfoRows returns the requested properties grouped per instance, so the
  219. caller never has to zip together separately queried slices. Querying each
  220. property on its own is racy: hardware can appear or disappear (e.g. a USB drive
  221. being unplugged) between two queries, and null values are skipped by CIM, both
  222. of which used to misalign the resulting slices.
  223. */
  224. func wmicGetinfoRows(wmicName string, itemNames ...string) [][]string {
  225. if len(itemNames) == 0 || runtime.GOOS != "windows" {
  226. return nil
  227. }
  228. if rows := cimGetinfoRows(wmicName, itemNames); len(rows) > 0 {
  229. return rows
  230. }
  231. //CIM unavailable, fall back to the legacy per-property wmic queries and
  232. //trim everything down to the shortest result to stay in bounds.
  233. columns := make([][]string, 0, len(itemNames))
  234. shortest := -1
  235. for _, itemName := range itemNames {
  236. values := legacyWmicGetinfo(wmicName, itemName)
  237. if shortest == -1 || len(values) < shortest {
  238. shortest = len(values)
  239. }
  240. columns = append(columns, values)
  241. }
  242. var rows [][]string
  243. for i := 0; i < shortest; i++ {
  244. row := make([]string, 0, len(columns))
  245. for _, column := range columns {
  246. row = append(row, column[i])
  247. }
  248. rows = append(rows, row)
  249. }
  250. return rows
  251. }