/
099_scriptlets.py
311 lines (266 loc) · 8.97 KB
/
099_scriptlets.py
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
import io
import shlex
# hooks for account setup
_acct_setup = r"""
local USERADD USERMOD
[ -z "$system_users" -a -z "$system_groups" ] && return 0
if command -v useradd >/dev/null 2>&1; then
USERADD="useradd"
fi
if command -v usermod >/dev/null 2>&1; then
USERMOD="usermod"
fi
show_acct_details() {
echo " Account: $1"
echo " Description: '$2'"
echo " Homedir: '$3'"
echo " Shell: '$4'"
[ -n "$5" ] && echo " Additional groups: '$5'"
}
group_add() {
local _pretty_grname _grname _gid
if ! command -v groupadd >/dev/null 2>&1; then
echo "WARNING: cannot create $1 system group (missing groupadd)"
echo "The following group must be created manually: $1"
return 0
fi
_grname="${1%:*}"
_gid="${1##*:}"
[ "${_grname}" = "${_gid}" ] && _gid=
_pretty_grname="${_grname}${_gid:+ (gid: ${_gid})}"
groupadd -r ${_grname} ${_gid:+-g ${_gid}} >/dev/null 2>&1
case $? in
0) echo "Created ${_pretty_grname} system group." ;;
9) ;;
*) echo "ERROR: failed to create system group ${_pretty_grname}!"; return 1;;
esac
return 0
}
# System groups required by a package.
for grp in ${system_groups}; do
group_add $grp || return 1
done
# System user/group required by a package.
for acct in ${system_users}; do
_uname="${acct%:*}"
_uid="${acct##*:}"
[ "${_uname}" = "${_uid}" ] && _uid=
eval homedir="\$${_uname}_homedir"
eval shell="\$${_uname}_shell"
eval descr="\$${_uname}_descr"
eval groups="\$${_uname}_groups"
eval pgroup="\$${_uname}_pgroup"
[ -z "$homedir" ] && homedir="/var/empty"
[ -z "$shell" ] && shell="/usr/bin/nologin"
[ -z "$descr" ] && descr="${_uname} user"
[ -n "$groups" ] && user_groups="-G $groups"
if [ -n "${_uid}" ]; then
use_id="-u ${_uid} -g ${pgroup:-${_uid}}"
_pretty_uname="${_uname} (uid: ${_uid})"
else
use_id="-g ${pgroup:-${_uname}}"
_pretty_uname="${_uname}"
fi
if [ -z "$USERADD" -o -z "$USERMOD" ]; then
echo "WARNING: cannot create ${_uname} system account (missing useradd or usermod)"
echo "The following system account must be created:"
show_acct_details "${_pretty_uname}" "${descr}" "${homedir}" "${shell}" "${groups}"
continue
fi
group_add ${pgroup:-${acct}} || return 1
${USERADD} -c "${descr}" -d "${homedir}" \
${use_id} ${pgroup:+-N} -s "${shell}" \
${user_groups} -r ${_uname} >/dev/null 2>&1
case $? in
0)
echo "Created ${_pretty_uname} system user."
${USERMOD} -L ${_uname} >/dev/null 2>&1
if [ $? -ne 0 ]; then
echo "WARNING: unable to lock password for ${_uname} system account"
fi
;;
9)
${USERMOD} -c "${descr}" -d "${homedir}" \
-s "${shell}" -g "${pgroup:-${_uname}}" \
${user_groups} ${_uname} >/dev/null 2>&1
if [ $? -eq 0 ]; then
echo "Updated ${_uname} system user."
else
echo "WARNING: unable to modify ${_uname} system account"
echo "Please verify that account is compatible with these settings:"
show_acct_details "${_pretty_uname}" \
"${descr}" "${homedir}" "${shell}" "${groups}"
continue
fi
;;
*)
echo "ERROR: failed to create system user ${_pretty_uname}!"
return 1
;;
esac
done
"""
_acct_drop = r"""
local USERMOD
[ -z "$system_users" ] && return 0
if command -v usermod >/dev/null 2>&1; then
USERMOD="usermod"
fi
for acct in ${system_users}; do
_uname="${acct%:*}"
comment="$( (getent passwd "${_uname}" | cut -d: -f5 | head -n1) 2>/dev/null )"
comment="${comment:-user} - removed package ${1}"
if [ -z "$USERMOD" ]; then
echo "WARNING: cannot disable ${_uname} system user (missing usermod)"
continue
fi
${USERMOD} -L -d /var/empty -s /usr/bin/false \
-c "${comment}" ${_uname} >/dev/null 2>&1
if [ $? -eq 0 ]; then
echo "Disabled ${_uname} system user."
fi
done
"""
# all known hook scriptlets
_hookscripts = {
"system_accounts": {
"pre-install": _acct_setup,
"pre-upgrade": _acct_setup,
"post-deinstall": _acct_drop,
},
}
def _handle_accounts(pkg, _add_hook):
# handle system groups
if len(pkg.system_groups) > 0:
_add_hook(
"system_accounts", {"system_groups": " ".join(pkg.system_groups)}
)
# handle system users
if len(pkg.system_users) > 0:
evars = {}
usrs = []
for u in pkg.system_users:
uname = None
uid = None
# TODO: validation
if isinstance(u, dict):
uname = u["name"]
uid = u["id"]
# the form can be with or without id
if uid:
usrs.append(f"{uname}:{uid}")
else:
usrs.append(uname)
# optional fields
if "home" in u:
evars[f"{uname}_homedir"] = u["home"]
if "shell" in u:
evars[f"{uname}_shell"] = u["shell"]
if "desc" in u:
evars[f"{uname}_descr"] = u["desc"]
if "groups" in u:
evars[f"{uname}_groups"] = ",".join(u["groups"])
if "pgroup" in u:
evars[f"{uname}_pgroup"] = u["pgroup"]
else:
usrs.append(u)
# add the main var
evars["system_users"] = " ".join(usrs)
# add the hook
_add_hook("system_accounts", evars)
def invoke(pkg):
# base
_hooks = {
"pre-install": "",
"pre-upgrade": "",
"pre-deinstall": "",
"post-install": "",
"post-upgrade": "",
"post-deinstall": "",
"trigger": "",
}
# executable hooks to invoke
_reghooks = {}
def _add_hook(hookn, evars):
if hookn in _reghooks:
_reghooks[hookn].update(evars)
else:
_reghooks[hookn] = evars
# handle individual hooks
_handle_accounts(pkg, _add_hook)
# add executable scriptlets
for h in _reghooks:
envs = _reghooks[h]
# go through every target
for tgt in _hookscripts[h]:
if tgt not in _hooks:
# this should never happen unless we are buggy
pkg.error(f"unknown hook: {tgt}")
# export env vars for the hook
for e in envs:
_hooks[tgt] += f"{e}={shlex.quote(envs[e])}\n"
# export the scriptlet as function
_hooks[tgt] += f"\n_{h}_invoke() " + "{\n"
for ln in io.StringIO(_hookscripts[h][tgt]):
# empty lines
if len(ln.strip()) == 0:
_hooks[tgt] += "\n"
continue
# add the line, indent as needed
_hooks[tgt] += f" {ln.rstrip()}\n"
# end the function
_hooks[tgt] += " return 0\n}\n"
# insert the hook
pkg.log(f"added hook '{h}' for scriptlet '{tgt}'")
_hooks[tgt] += (
f"_{h}_invoke '{pkg.pkgname}' '{pkg.pkgver}'" + " || exit $?\n"
)
# add user scriptlets
for h in _hooks:
up = pkg.rparent.template_path / f"{pkg.pkgname}.{h}"
# scriptlets can be generated or can be files
if h in pkg.scriptlets:
sr = pkg.scriptlets[h]
elif up.is_file():
# read entire thing into the buffer
sr = up.read_text()
else:
sr = None
if sr:
# strip shebang
if sr.startswith("#!"):
nl = sr.find("\n")
if nl < 0:
# no newline found so it was just a comment
sr = ""
else:
sr = sr[nl + 1 :].strip()
# append cleared up scriptlet
if len(sr) > 0:
_hooks[h] += "# package script\n"
_hooks[h] += "set -e\n\n"
_hooks[h] += sr
# log
pkg.log(f"added package scriptlet '{h}'")
# set up scriptlet dir
scdir = pkg.statedir / "scriptlets"
if scdir.is_dir():
# remove potential leftovers for this package
for sc in scdir.glob(f"{pkg.pkgname}.*"):
sc.unlink()
else:
scdir.mkdir()
# generate
for h in _hooks:
s = _hooks[h].strip()
# got nothing, do not generate
if len(s) == 0:
continue
# for triggers, ensure we trigger on something
if h == "trigger" and len(pkg.triggers) == 0:
pkg.error("trigger scriptlet provided but no triggers")
# create file
with open(scdir / f"{pkg.pkgname}.{h}", "w") as sf:
sf.write("#!/bin/sh\n\n")
sf.write(s)
sf.write("\n")