lib: intro `user_exists` and `group_exists`
[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 a user and set his privileges back to default (program privileges)
51 fun drop_privileges
52 do
53 var passwd = new Passwd.from_name(user)
54 var uid = passwd.uid
55
56 var group = group
57 var gid
58 if group != null then
59 var gpasswd = new Group.from_name(group)
60 gid = gpasswd.gid
61 else gid = passwd.gid
62
63 sys.gid = gid
64 sys.uid = uid
65 end
66 end
67
68 # Option to ask for a username and group
69 class OptionUserAndGroup
70 super OptionParameter
71
72 redef type VALUE: nullable UserGroup
73
74 init for_dropping_privileges do init("Drop privileges to user:group or simply user", "-u", "--usergroup")
75 init(help: String, names: String...) do super(help, null, names)
76
77 redef fun convert(str)
78 do
79 var words = str.split(":")
80 if words.length == 1 then
81 return new UserGroup(str, null)
82 else if words.length == 2 then
83 return new UserGroup(words[0], words[1])
84 else
85 errors.add("Option {names.join(", ")} expected parameter in the format \"user:group\" or simply \"user\".\n")
86 abort # FIXME only for nitc, remove and replace with next line when FFI is working in nitg
87 #return null
88 end
89 end
90 end