-
Notifications
You must be signed in to change notification settings - Fork 0
/
ownership.go
107 lines (94 loc) · 1.9 KB
/
ownership.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
package pmq_responder
import (
"errors"
"fmt"
"os"
"os/user"
"strconv"
)
type Ownership struct {
Group string
Username string
}
type User struct {
Uid int
Gid int
}
type Group struct {
Gid int
}
func idToInt(idStr string) int {
id, err := strconv.Atoi(idStr)
if err != nil {
// ... handle error
panic(err)
}
return id
}
func (o *Ownership) HasUser() (bool, *User, error) {
if len(o.Username) > 0 {
osUser, err := user.Lookup(o.Username)
if err != nil {
return false, nil, err
}
mqUser := User{
Uid: idToInt(osUser.Uid),
Gid: idToInt(osUser.Gid),
}
return true, &mqUser, nil
}
return false, nil, nil
}
func (o *Ownership) HasGroup() (bool, *Group, error) {
if len(o.Group) > 0 {
osGroup, err := user.LookupGroup(o.Group)
if err != nil {
return false, nil, err
}
mqGroup := Group{
Gid: idToInt(osGroup.Gid),
}
return true, &mqGroup, nil
}
return false, nil, nil
}
func (o *Ownership) IsValid() bool {
hasGroup, _, err := o.HasGroup()
if err != nil {
return false
}
hasUser, _, err := o.HasUser()
if err != nil {
return false
}
if hasGroup && !hasUser {
fmt.Println("Cannot infer user from the group alone")
return false
}
return hasGroup || hasUser
}
func ApplyPermissions(o *Ownership, config *QueueConfig) error {
if o != nil {
hasGroup, group, err := o.HasGroup()
if err != nil {
return errors.New("Cannot get group")
}
hasUser, user, err := o.HasUser()
if err != nil {
return errors.New("Cannot get user")
}
if hasGroup || hasUser {
err = os.Chmod(config.GetFile(), os.FileMode(config.Mode))
} else {
return os.Chmod(config.GetFile(), os.FileMode(config.Mode))
}
if hasGroup && hasUser {
err = os.Chown(config.GetFile(), user.Gid, group.Gid)
} else if hasUser {
err = os.Chown(config.GetFile(), user.Gid, user.Gid)
}
return err
} else {
return os.Chmod(config.GetFile(), os.FileMode(config.Mode))
}
}