forked from linuxdeepin/dde-daemon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
320 lines (279 loc) · 7.02 KB
/
utils.go
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
/*
* Copyright (C) 2013 ~ 2018 Deepin Technology Co., Ltd.
*
* Author: jouyouyun <jouyouwen717@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package accounts
import (
"bufio"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/godbus/dbus"
polkit "github.com/linuxdeepin/go-dbus-factory/org.freedesktop.policykit1"
"pkg.deepin.io/dde/daemon/accounts/users"
"pkg.deepin.io/lib/encoding/kv"
"pkg.deepin.io/lib/graphic"
"pkg.deepin.io/lib/utils"
)
const (
polkitActionUserAdministration = "com.deepin.daemon.accounts.user-administration"
polkitActionChangeOwnData = "com.deepin.daemon.accounts.change-own-user-data"
polkitActionEnableAutoLogin = "com.deepin.daemon.accounts.enable-auto-login"
polkitActionDisableAutoLogin = "com.deepin.daemon.accounts.disable-auto-login"
polkitActionEnableNoPasswordLogin = "com.deepin.daemon.accounts.enable-nopass-login"
polkitActionDisableNoPasswordLogin = "com.deepin.daemon.accounts.disable-nopass-login"
polkitActionSetKeyboardLayout = "com.deepin.daemon.accounts.set-keyboard-layout"
systemLocaleFile = "/etc/default/locale"
systemdLocaleFile = "/etc/locale.conf"
defaultLocale = "en_US.UTF-8"
layoutDelimiter = ";"
defaultLayout = "us" + layoutDelimiter
defaultLayoutFile = "/etc/default/keyboard"
)
type ErrCodeType int32
const (
// 未知错误
ErrCodeUnkown ErrCodeType = iota
// 权限认证失败
ErrCodeAuthFailed
// 执行命令失败
ErrCodeExecFailed
// 传入的参数不合法
ErrCodeParamInvalid
)
func (code ErrCodeType) String() string {
switch code {
case ErrCodeUnkown:
return "Unkown error"
case ErrCodeAuthFailed:
return "Policykit authentication failed"
case ErrCodeExecFailed:
return "Exec command failed"
case ErrCodeParamInvalid:
return "Invalid parameters"
}
return "Unkown error"
}
// return icons uris
func getUserStandardIcons() []string {
imgs, err := graphic.GetImagesInDir(userIconsDir)
if err != nil {
return nil
}
var icons []string
for _, img := range imgs {
img = utils.EncodeURI(img, utils.SCHEME_FILE)
if strings.Contains(img, "guest") || img == defaultUserIcon {
continue
}
icons = append(icons, img)
}
return icons
}
func getNewUserCustomIconDest(username string) string {
ns := time.Now().UnixNano()
base := username + "-" + strconv.FormatInt(ns, 36)
return filepath.Join(userCustomIconsDir, base)
}
func isStrInArray(str string, array []string) bool {
for _, v := range array {
if v == str {
return true
}
}
return false
}
func isStrvEqual(l1, l2 []string) bool {
if len(l1) != len(l2) {
return false
}
sort.Strings(l1)
sort.Strings(l2)
for i, v := range l1 {
if v != l2[i] {
return false
}
}
return true
}
func checkAccountType(accountType int) error {
switch accountType {
case users.UserTypeStandard, users.UserTypeAdmin:
return nil
default:
return fmt.Errorf("invalid account type %d", accountType)
}
}
func checkAuth(actionId string, sysBusName string) error {
ret, err := checkAuthByPolkit(actionId, sysBusName)
if err != nil {
return err
}
if !ret.IsAuthorized {
inf, err := getDetailsKey(ret.Details, "polkit.dismissed")
if err == nil {
if dismiss, ok := inf.(string); ok {
if dismiss != "" {
return errors.New("")
}
}
}
return fmt.Errorf(ErrCodeAuthFailed.String())
}
return nil
}
func checkAuthByPolkit(actionId string, sysBusName string) (ret polkit.AuthorizationResult, err error) {
systemBus, err := dbus.SystemBus()
if err != nil {
return
}
authority := polkit.NewAuthority(systemBus)
subject := polkit.MakeSubject(polkit.SubjectKindSystemBusName)
subject.SetDetail("name", sysBusName)
ret, err = authority.CheckAuthorization(0, subject,
actionId, nil,
polkit.CheckAuthorizationFlagsAllowUserInteraction, "")
if err != nil {
logger.Warningf("call check auth failed, err: %v", err)
return
}
logger.Debugf("call check auth success, ret: %v", ret)
return
}
func getDetailsKey(details map[string]dbus.Variant, key string) (interface{}, error) {
result, ok := details[key]
if !ok {
return nil, errors.New("key dont exist in details")
}
if utils.IsInterfaceNil(result) {
return nil, errors.New("result is nil")
}
return result.Value(), nil
}
func getDefaultLocale() (locale string) {
files := [...]string{
systemLocaleFile,
systemdLocaleFile,
}
for _, file := range files {
locale = getLocaleFromFile(file)
if locale != "" {
// get locale success
break
}
}
if locale == "" {
return defaultLocale
}
return strings.Trim(locale, "\"'")
}
func getLocaleFromFile(file string) string {
f, err := os.Open(file)
if err != nil {
return ""
}
defer f.Close()
r := kv.NewReader(f)
r.Delim = '='
r.Comment = '#'
r.TrimSpace = kv.TrimLeadingTailingSpace
for {
pair, err := r.Read()
if err == io.EOF {
break
} else if err != nil {
return ""
}
if pair.Key == "LANG" {
return pair.Value
}
}
return ""
}
func getDefaultLayout() string {
layout, err := getSystemLayout(defaultLayoutFile)
if err != nil {
logger.Warning("failed to get system default layout:", err)
return defaultLayout
}
return layout
}
func getSystemLayout(file string) (string, error) {
fr, err := os.Open(file)
if err != nil {
return "", err
}
defer fr.Close()
var (
found int
layout string
variant string
regLayout = regexp.MustCompile(`^XKBLAYOUT=`)
regVariant = regexp.MustCompile(`^XKBVARIANT=`)
scanner = bufio.NewScanner(fr)
)
for scanner.Scan() {
if found == 2 {
break
}
var line = scanner.Text()
if regLayout.MatchString(line) {
layout = strings.Trim(getValueFromLine(line, "="), "\"")
found += 1
continue
}
if regVariant.MatchString(line) {
variant = strings.Trim(getValueFromLine(line, "="), "\"")
found += 1
}
}
if len(layout) == 0 {
return "", fmt.Errorf("not found default layout")
}
return layout + layoutDelimiter + variant, nil
}
func getValueFromLine(line, delim string) string {
array := strings.Split(line, delim)
if len(array) != 2 {
return ""
}
return strings.TrimSpace(array[1])
}
// Get available shells from '/etc/shells'
func getAvailableShells(file string) []string {
contents, err := ioutil.ReadFile(file)
if err != nil || len(contents) == 0 {
return nil
}
var shells []string
lines := strings.Split(string(contents), "\n")
for _, line := range lines {
if line == "" || line[0] == '#' {
continue
}
shells = append(shells, line)
}
return shells
}