-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathsysteminfo_utils.go
More file actions
607 lines (548 loc) · 15.9 KB
/
systeminfo_utils.go
File metadata and controls
607 lines (548 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
// SPDX-FileCopyrightText: 2022 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later
package updateplatform
import (
"bufio"
"bytes"
"crypto"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"github.com/godbus/dbus/v5"
"github.com/jouyouyun/hardware/utils"
utils2 "github.com/linuxdeepin/go-lib/utils"
"github.com/linuxdeepin/lastore-daemon/src/internal/system"
hhardware "github.com/jouyouyun/hardware"
)
const (
cpuInfoFilePath = "/proc/cpuinfo"
cpuKeyDelim = ":"
cpuKeyLoongArchCPUModel = "Model Name"
cpuKeyName = "model name"
cpuKeySWCPU = "cpu"
cpuKeyARMProcessor = "Processor"
cpuKeyHWHardware = "Hardware"
lscpuKeyModelName = "Model name"
lscpuKeyDelim = ":"
lscpuCmd = "lscpu"
)
const (
customInfoPath = "/usr/share/deepin/custom-note/info.json"
)
const (
helperDBusName = "com.deepin.sync.Helper"
helperDBusPath = "/com/deepin/sync/Helper"
helperDBusInterface = helperDBusName
)
type SystemInfo struct {
SystemName string
ProductType string
EditionName string
Version string
HardwareId string
Processor string
Arch string
Custom string
SN string
HardwareVersion string
OEMID string
ProjectId string
Baseline string
SystemType string
MachineType string
Mac string
}
const (
OemNotCustomState = "0"
OemCustomState = "1"
)
func getSystemInfo(includeDiskInfo bool, getHardwareIdByHelper bool) SystemInfo {
systemInfo := SystemInfo{
Custom: OemNotCustomState,
}
osVersionInfoMap, err := GetOSVersionInfo(CacheVersion)
if err != nil {
logger.Warning("failed to get os-version:", err)
} else {
systemInfo.SystemName = osVersionInfoMap["SystemName"]
systemInfo.ProductType = osVersionInfoMap["ProductType"]
systemInfo.EditionName = osVersionInfoMap["EditionName"]
systemInfo.Version = strings.Join([]string{
osVersionInfoMap["MajorVersion"],
osVersionInfoMap["MinorVersion"],
osVersionInfoMap["OsBuild"]},
".")
}
systemInfo.HardwareId = GetHardwareId(includeDiskInfo, getHardwareIdByHelper)
if err != nil {
logger.Warning("failed to get hardwareId:", err)
}
systemInfo.Processor, err = getProcessorModelName()
if err != nil {
logger.Warning("failed to get modelName:", err)
} else if len(systemInfo.Processor) > 100 {
systemInfo.Processor = systemInfo.Processor[0:100] // 按照需求,长度超过100时,只取前100个字符
}
systemInfo.Arch, err = GetArchInfo()
if err != nil {
logger.Warning("failed to get Arch:", err)
}
systemInfo.SN, err = getSN()
if err != nil {
logger.Warning("failed to get SN:", err)
}
isCustom, oemId, err := getCustomInfoAndOemId()
if err != nil {
logger.Warningf("failed to get oemId by /etc/oem-info :%v, start get oemId by /etc/.oemid", err)
systemInfo.Custom = OemNotCustomState
// 当从oem-info文件解析出错(通常为文件不存在的情况),需要从/etc/.oemid重新读取oemid
oemId, err = getOEMID()
if err != nil {
logger.Warning(err)
}
} else if isCustom {
systemInfo.Custom = OemCustomState
}
systemInfo.OEMID = oemId
systemInfo.HardwareVersion, err = getHardwareVersion()
if err != nil {
logger.Warning("failed to get HardwareVersion:", err)
}
systemInfo.ProjectId, err = getProjectID(customInfoPath)
if err != nil {
logger.Warning("failed to get project id:", err)
}
systemInfo.Baseline = getCurrentBaseline()
systemInfo.SystemType = getCurrentSystemType()
systemInfo.MachineType = getMachineType()
systemInfo.Mac, err = getDefaultMac()
if err != nil {
logger.Warning("failed to get Mac:", err)
}
return systemInfo
}
func loadFile(filepath string) ([]string, error) {
f, err := os.Open(filepath)
if err != nil {
return nil, err
}
defer func() {
_ = f.Close()
}()
var lines []string
scanner := bufio.NewScanner(bufio.NewReader(f))
for scanner.Scan() {
line := scanner.Text()
lines = append(lines, line)
}
if scanner.Err() != nil {
return nil, scanner.Err()
}
return lines, nil
}
func GetOSVersionInfo(filePath string) (map[string]string, error) {
versionLines, err := loadFile(filePath)
if err != nil {
logger.Warning("failed to load os-version file:", err)
return nil, err
}
osVersionInfoMap := make(map[string]string)
for _, item := range versionLines {
itemSlice := strings.SplitN(item, "=", 2)
if len(itemSlice) < 2 {
continue
}
key := strings.TrimSpace(itemSlice[0])
value := strings.TrimSpace(itemSlice[1])
osVersionInfoMap[key] = value
}
// 判断必要内容是否存在
necessaryKey := []string{"SystemName", "ProductType", "EditionName", "MajorVersion", "MinorVersion", "OsBuild"}
for _, key := range necessaryKey {
if value := osVersionInfoMap[key]; value == "" {
return nil, errors.New("os-version lack necessary content")
}
}
return osVersionInfoMap, nil
}
func GetHardwareId(includeDiskInfo bool, getByHelper bool) string {
if getByHelper {
return getHardwareIdByHelper()
}
hhardware.IncludeDiskInfo = includeDiskInfo
machineID, err := hhardware.GenMachineID()
if err != nil {
logger.Warningf("failed to get hardware id: %v ", err.Error())
return ""
}
return machineID
}
type Hardware struct {
ID string `json:"id"`
Hostname string `json:"hostname"`
Username string `json:"username"`
OS string `json:"os"`
CPU string `json:"cpu"`
Laptop bool `json:"laptop"`
Memory int64 `json:"memory"`
DiskTotal int64 `json:"disk_total"`
NetworkCardList string `json:"network_cards"`
DiskList string `json:"disk_list"`
DMI DMI `json:"dmi"`
}
type DMI struct {
BiosVendor string `json:"bios_vendor"`
BiosVersion string `json:"bios_version"`
BiosDate string `json:"bios_date"`
BoardName string `json:"board_name"`
BoardSerial string `json:"board_serial"`
BoardVendor string `json:"board_vendor"`
BoardVersion string `json:"board_version"`
ProductName string `json:"product_name"`
ProductFamily string `json:"product_family"`
ProductSerial string `json:"product_serial"`
ProductUUID string `json:"product_uuid"`
ProductVersion string `json:"product_version"`
}
func getHardwareIdByHelper() string {
logger.Info("start get hardware id by helper")
systemBus, err := dbus.SystemBus()
if err != nil {
logger.Warning("failed to get system bus:", err)
return ""
}
var hw = Hardware{
DMI: DMI{},
}
helperObj := systemBus.Object(helperDBusName, helperDBusPath)
err = helperObj.Call(helperDBusInterface+".GetHardware", 0).Store(&hw)
if err != nil {
logger.Warning("failed to get hardware info by helper:", err)
return ""
}
logger.Info("hardwareId is:", hw.ID)
return hw.ID
}
func getProcessorModelName() (string, error) {
processor, err := getProcessorInfo(cpuInfoFilePath)
if err != nil {
logger.Warning("Get cpu info failed:", err)
return "", err
}
if processor != "" {
return processor, nil
}
res, err := runLsCpu() // 当 `/proc/cpuinfo` 中无法获取到处理器名称时,通过 `lscpu` 命令来获取
if err != nil {
logger.Warning("run lscpu failed:", err)
return "", nil
}
return getCPUInfoFromMap(lscpuKeyModelName, res)
}
func getProcessorInfo(file string) (string, error) {
data, err := parseInfoFile(file, cpuKeyDelim)
if err != nil {
return "", err
}
// loongarch
cpu, _ := getCPUInfoFromMap(cpuKeyLoongArchCPUModel, data)
if len(cpu) != 0 {
return cpu, nil
}
cpu, _ = getCPUInfoFromMap(cpuKeySWCPU, data)
if len(cpu) != 0 {
return cpu, nil
}
// huawei kirin
cpu, _ = getCPUInfoFromMap(cpuKeyHWHardware, data)
if len(cpu) != 0 {
return cpu, nil
}
// arm
cpu, _ = getCPUInfoFromMap(cpuKeyARMProcessor, data)
if len(cpu) != 0 {
return cpu, nil
}
return getCPUInfoFromMap(cpuKeyName, data)
}
func getCPUInfoFromMap(nameKey string, data map[string]string) (string, error) {
value, ok := data[nameKey]
if !ok {
return "", fmt.Errorf("can not find the key %q", nameKey)
}
var name string
array := strings.Split(value, " ")
for i, v := range array {
if len(v) == 0 {
continue
}
name += v
if i != len(array)-1 {
name += " "
}
}
return name, nil
}
func runLsCpu() (map[string]string, error) {
cmd := exec.Command(lscpuCmd)
cmd.Env = []string{"LC_ALL=C"}
out, err := cmd.Output()
if err != nil {
return nil, err
}
lines := strings.Split(string(out), "\n")
res := make(map[string]string, len(lines))
for _, line := range lines {
items := strings.Split(line, lscpuKeyDelim)
if len(items) != 2 {
continue
}
res[strings.TrimSpace(items[0])] = strings.TrimSpace(items[1])
}
return res, nil
}
func parseInfoFile(file, delim string) (map[string]string, error) {
content, err := os.ReadFile(file)
if err != nil {
return nil, err
}
var ret = make(map[string]string)
lines := strings.Split(string(content), "\n")
for _, line := range lines {
if len(line) == 0 {
continue
}
array := strings.Split(line, delim)
if len(array) != 2 {
continue
}
ret[strings.TrimSpace(array[0])] = strings.TrimSpace(array[1])
}
return ret, nil
}
func GetArchInfo() (string, error) {
arch, err := exec.Command("dpkg", "--print-architecture").Output()
if err != nil {
logger.Warningf("GetSystemArchitecture failed:%v\n", arch)
return "", err
}
return strings.TrimSpace(string(arch)), nil
}
// 获取激活码
func getSN() (string, error) {
logger.Debug("start get SN")
systemBus, err := dbus.SystemBus()
if err != nil {
return "", err
}
object := systemBus.Object("com.deepin.license", "/com/deepin/license/Info")
var ret dbus.Variant
err = object.Call("org.freedesktop.DBus.Properties.Get", 0, "com.deepin.license.Info", "ActiveCode").Store(&ret)
if err != nil {
return "", err
}
v := ret.Value().(string)
logger.Debug("end get SN")
return v, nil
}
type oemInfo struct {
Basic struct {
IsoId string `json:"iso_id"`
TimeStamp uint64 `json:"timestamp"`
} `json:"basic"`
CustomInfo struct {
CustomizedKernel bool `json:"customized_kernel"`
} `json:"custom_info"`
}
const (
oemInfoFile = "/etc/oem-info"
oemSignFile = "/var/uos/.oem-shadow"
oemPubKey = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwzVS35kJl3mhSJssD3S5\nEzjJbFoAD+VsMSy2nS7WQA2XH0aPAWjgCeU+1ScYdBOWz+zWsnK77fGm96HueAuT\nhQEJ9J+ISJUuYBYCc6ovc35gxnhCmP2Qof+/vw98+uKnf1aTDI1imNCWOd/shSbL\nOBn5xFXPsQld1HJqahOuQZOguNIWvrvT7RtmQb77iu576gVLc948HreXKOPD57uK\nJoA2KcoUt95hd94wYyphCuE4onjPcIlpJQfda6PP+HO2Xwze3ltIG6hJSSAEK4R9\n8GnaOTqvslWVI9QFLCIyQ63dbbnASYFTWpDXTlPJsss64vfWOuEjwIyzzQDJNOzN\nFQIDAQAB\n-----END PUBLIC KEY-----"
)
func getCustomInfoAndOemId() (bool, string, error) {
if !utils2.IsFileExist(oemInfoFile) || !utils2.IsFileExist(oemSignFile) {
return false, "", errors.New("oemInfoFile or oemSignFile not exist")
}
var info oemInfo
err := system.DecodeJson(oemInfoFile, &info)
if err != nil {
return false, "", err
}
if !verifyOemFile(oemPubKey, oemInfoFile) {
logger.Warning("verify oem-info failure")
return false, "", errors.New("verify oem-info failure")
}
return info.CustomInfo.CustomizedKernel, info.Basic.IsoId, nil
}
// 定制标识校验
func verifyOemFile(key, file string) bool {
// pem解码
block, _ := pem.Decode([]byte(key))
if block == nil {
return false
}
// 解析得到一个公钥interface
pubKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
logger.Warning(err)
return false
}
// 转为rsa公钥
publicKey := pubKeyInterface.(*rsa.PublicKey)
// sha256计算
hash := sha256.New()
encContent, err := os.ReadFile(file)
if err != nil {
logger.Warning(err)
return false
}
_, err = hash.Write(encContent)
if err != nil {
logger.Warning(err)
return false
}
hashed := hash.Sum(nil)
// 读取签名文件
srBuf, err := os.ReadFile(oemSignFile)
if err != nil {
logger.Warning(err)
return false
}
// 签名认证
return rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, hashed, srBuf) == nil
}
func getHardwareVersion() (string, error) {
res, err := exec.Command("dmidecode", "-s", "system-version").Output()
if err != nil {
return "", err
}
return string(res), nil
}
const oemFilePath = "/etc/.oemid"
func getOEMID() (string, error) {
content, err := os.ReadFile(oemFilePath)
if err != nil {
return "", err
}
return string(content), nil
}
type ProjectInfo struct {
Id string `json:"id"`
}
func getProjectID(fileName string) (string, error) {
content, err := os.ReadFile(fileName)
if err != nil {
return "", err
}
info := new(ProjectInfo)
err = json.Unmarshal(content, info)
if err != nil {
return "", err
}
return info.Id, nil
}
func getMachineType() string {
const dmiDirPrefix = "/sys/class/dmi/id"
var files = []string{
"product_family",
"product_name",
"product_sku",
}
var content []string
for _, key := range files {
value, err := utils.ReadFileContent(filepath.Join(dmiDirPrefix, key))
if err != nil {
continue
}
content = append(content, value)
}
return strings.Join(content, " ")
}
var _tokenUpdateMu sync.Mutex
// UpdateTokenConfigFile 更新 99lastore-token.conf 文件的内容
func UpdateTokenConfigFile(includeDiskInfo bool, getHardwareIdByHelper bool) string {
logger.Infof("UpdateTokenConfigFile includeDiskInfo: %v, getHardwareIdByHelper: %v", includeDiskInfo, getHardwareIdByHelper)
logger.Debug("start updateTokenConfigFile")
_tokenUpdateMu.Lock()
defer _tokenUpdateMu.Unlock()
logger.Debug("start getSystemInfo")
systemInfo := getSystemInfo(includeDiskInfo, getHardwareIdByHelper)
logger.Debug("end getSystemInfo")
tokenPath := "/etc/apt/apt.conf.d/99lastore-token.conf"
var tokenSlice []string
tokenSlice = append(tokenSlice, "a="+systemInfo.SystemName)
tokenSlice = append(tokenSlice, "b="+systemInfo.ProductType)
tokenSlice = append(tokenSlice, "c="+systemInfo.EditionName)
tokenSlice = append(tokenSlice, "v="+systemInfo.Version)
tokenSlice = append(tokenSlice, "i="+systemInfo.HardwareId)
tokenSlice = append(tokenSlice, "m="+systemInfo.Processor)
tokenSlice = append(tokenSlice, "ac="+systemInfo.Arch)
tokenSlice = append(tokenSlice, "cu="+systemInfo.Custom)
tokenSlice = append(tokenSlice, "sn="+systemInfo.SN)
tokenSlice = append(tokenSlice, "vs="+systemInfo.HardwareVersion)
tokenSlice = append(tokenSlice, "oid="+systemInfo.OEMID)
tokenSlice = append(tokenSlice, "pid="+systemInfo.ProjectId)
tokenSlice = append(tokenSlice, "baseline="+systemInfo.Baseline)
tokenSlice = append(tokenSlice, "st="+systemInfo.SystemType)
tokenSlice = append(tokenSlice, "mt="+systemInfo.MachineType)
tokenSlice = append(tokenSlice, "mac="+systemInfo.Mac)
token := strings.Join(tokenSlice, ";")
token = strings.Replace(token, "\n", "", -1)
tokenContent := []byte("Acquire::SmartMirrors::Token \"" + token + "\";\n")
existingContent, err := os.ReadFile(tokenPath)
if err == nil && bytes.Equal(existingContent, tokenContent) {
logger.Debug("token content unchanged, skip writing")
return token
}
err = os.WriteFile(tokenPath, tokenContent, 0644)
if err != nil {
logger.Warning(err)
}
return token
}
func getDefaultMac() (string, error) {
res, err := exec.Command("route", "-n").Output()
if err != nil {
return "", err
}
dev := getDefaultRouteIface(string(res))
if len(dev) == 0 {
return "", nil
}
mac, err := os.ReadFile(filepath.Join("/sys/class/net", dev, "address"))
if err != nil {
return "", err
}
return strings.TrimSpace(string(mac)), nil
}
func getDefaultRouteIface(routeOutput string) string {
lines := strings.Split(routeOutput, "\n")
for _, line := range lines {
fields := strings.Fields(line)
if len(fields) < 8 {
continue
}
if fields[0] == "0.0.0.0" {
return fields[len(fields)-1]
}
}
return ""
}
func getClientPackageInfo(client string) string {
o, err := exec.Command("/usr/bin/dpkg-query", "-W", "-f", "${Version}", "--", client).Output()
if err != nil {
logger.Warning(err)
return ""
}
return fmt.Sprintf("client=%v&version=%v", client, string(o))
}