nitc: fix calling extern constructors from extern code in separate compiler
[nit.git] / lib / privileges.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2013 Alexis Laferrière <alexis.laf@xymus.net>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Process privileges management utilities
18 #
19 # Used mainly by daemons and such to aquire resources as su and
20 # then drop back to a restricted user.
21 module privileges
22
23 import opts
24
25 redef class Text
26 # Does the operating system know the user named `self`?
27 fun user_exists: Bool
28 do
29 var passwd = new Passwd.from_name(to_s)
30 return not passwd.address_is_null
31 end
32
33 # Does the operating system know the group named `self`?
34 fun group_exists: Bool
35 do
36 var passwd = new Group.from_name(to_s)
37 return not passwd.address_is_null
38 end
39 end
40
41 # Class to manage user groups
42 class UserGroup
43
44 # User name
45 var user: String
46
47 # Group name
48 var group: nullable String
49
50 # Drop privileges of the running program to those of `self`
51 #
52 # require: `user.user_exists and (group == null or group.group_exists)`
53 fun drop_privileges
54 do
55 var passwd = new Passwd.from_name(user)
56 assert not passwd.address_is_null
57 var uid = passwd.uid
58
59 var group = group
60 var gid
61 if group != null then
62 var gpasswd = new Group.from_name(group)
63 assert not gpasswd.address_is_null
64 gid = gpasswd.gid
65 else gid = passwd.gid
66
67 sys.gid = gid
68 sys.uid = uid
69 end
70 end
71
72 # Option to ask for a username and group
73 class OptionUserAndGroup
74 super OptionParameter
75
76 redef type VALUE: nullable UserGroup
77
78 # Create an `OptionUserAndGroup` for dropping privileges
79 init for_dropping_privileges
80 do
81 init("Drop privileges to user:group or simply user", null, ["-u", "--usergroup"])
82 end
83
84 redef fun convert(str)
85 do
86 var words = str.split(":")
87 if words.length == 1 then
88 return new UserGroup(str, null)
89 else if words.length == 2 then
90 return new UserGroup(words[0], words[1])
91 else
92 errors.add("Option {names.join(", ")} expected parameter in the format \"user:group\" or simply \"user\".\n")
93 return null
94 end
95 end
96 end