]> git.ipfire.org Git - thirdparty/systemd.git/blame - test/test-systemd-tmpfiles.py
test: fix a syntax error in test-ukify
[thirdparty/systemd.git] / test / test-systemd-tmpfiles.py
CommitLineData
d9daae55 1#!/usr/bin/env python3
db9ecf05 2# SPDX-License-Identifier: LGPL-2.1-or-later
d9daae55 3#
d8a0bcfd
YW
4# systemd is free software; you can redistribute it and/or modify it
5# under the terms of the GNU Lesser General Public License as published by
6# the Free Software Foundation; either version 2.1 of the License, or
7# (at your option) any later version.
d9daae55 8
5a8575ef 9import os
d9daae55 10import sys
03025f46 11import socket
d9daae55 12import subprocess
03025f46
ZJS
13import tempfile
14import pwd
b75f0c69 15import grp
f582e61b 16from pathlib import Path
03025f46
ZJS
17
18try:
19 from systemd import id128
20except ImportError:
21 id128 = None
d9daae55
ZJS
22
23EX_DATAERR = 65 # from sysexits.h
7488492a
ZJS
24EXIT_TEST_SKIP = 77
25
26try:
27 subprocess.run
28except AttributeError:
29 sys.exit(EXIT_TEST_SKIP)
d9daae55 30
59ca366c 31exe_with_args = sys.argv[1:]
458e8d6d 32temp_dir = tempfile.TemporaryDirectory(prefix='test-systemd-tmpfiles.')
d9daae55 33
03025f46 34def test_line(line, *, user, returncode=EX_DATAERR, extra={}):
5a8575ef 35 args = ['--user'] if user else []
59ca366c
EV
36 print('Running {} on {!r}'.format(' '.join(exe_with_args + args), line))
37 c = subprocess.run(exe_with_args + ['--create', '-'] + args,
7488492a
ZJS
38 input=line, stdout=subprocess.PIPE, universal_newlines=True,
39 **extra)
5a8575ef
ZJS
40 assert c.returncode == returncode, c
41
42def test_invalids(*, user):
43 test_line('asdfa', user=user)
44 test_line('f "open quote', user=user)
45 test_line('f closed quote""', user=user)
46 test_line('Y /unknown/letter', user=user)
47 test_line('w non/absolute/path', user=user)
48 test_line('s', user=user) # s is for short
49 test_line('f!! /too/many/bangs', user=user)
50 test_line('f++ /too/many/plusses', user=user)
51 test_line('f+!+ /too/many/plusses', user=user)
52 test_line('f!+! /too/many/bangs', user=user)
c46c3233 53 test_line('f== /too/many/equals', user=user)
5a8575ef
ZJS
54 test_line('w /unresolved/argument - - - - "%Y"', user=user)
55 test_line('w /unresolved/argument/sandwich - - - - "%v%Y%v"', user=user)
56 test_line('w /unresolved/filename/%Y - - - - "whatever"', user=user)
57 test_line('w /unresolved/filename/sandwich/%v%Y%v - - - - "whatever"', user=user)
5238e957
BB
58 test_line('w - - - - - "no file specified"', user=user)
59 test_line('C - - - - - "no file specified"', user=user)
5a8575ef
ZJS
60 test_line('C non/absolute/path - - - - -', user=user)
61 test_line('b - - - - - -', user=user)
62 test_line('b 1234 - - - - -', user=user)
63 test_line('c - - - - - -', user=user)
64 test_line('c 1234 - - - - -', user=user)
65 test_line('t - - -', user=user)
66 test_line('T - - -', user=user)
67 test_line('a - - -', user=user)
68 test_line('A - - -', user=user)
69 test_line('h - - -', user=user)
70 test_line('H - - -', user=user)
71
a6dffbb7 72def test_uninitialized_t():
5a8575ef
ZJS
73 if os.getuid() == 0:
74 return
75
03025f46 76 test_line('w /foo - - - - "specifier for --user %t"',
60f42f7e 77 user=True, returncode=0, extra={'env':{'HOME': os.getenv('HOME')}})
03025f46 78
c46c3233 79def test_content(line, expected, *, user, extra={}, subpath='/arg', path_cb=None):
458e8d6d 80 d = tempfile.TemporaryDirectory(prefix='test-content.', dir=temp_dir.name)
c46c3233
AW
81 if path_cb is not None:
82 path_cb(d.name, subpath)
83 arg = d.name + subpath
03025f46
ZJS
84 spec = line.format(arg)
85 test_line(spec, user=user, returncode=0, extra=extra)
86 content = open(arg).read()
87 print('expect: {!r}\nactual: {!r}'.format(expected, content))
88 assert content == expected
89
90def test_valid_specifiers(*, user):
91 test_content('f {} - - - - two words', 'two words', user=user)
b2d896f0 92 if id128 and os.path.isfile('/etc/machine-id'):
df1172fe
ZJS
93 try:
94 test_content('f {} - - - - %m', '{}'.format(id128.get_machine().hex), user=user)
95 except AssertionError as e:
96 print(e)
97 print('/etc/machine-id: {!r}'.format(open('/etc/machine-id').read()))
98 print('/proc/cmdline: {!r}'.format(open('/proc/cmdline').read()))
99 print('skipping')
03025f46
ZJS
100 test_content('f {} - - - - %b', '{}'.format(id128.get_boot().hex), user=user)
101 test_content('f {} - - - - %H', '{}'.format(socket.gethostname()), user=user)
102 test_content('f {} - - - - %v', '{}'.format(os.uname().release), user=user)
172e9cc3
ZJS
103 test_content('f {} - - - - %U', '{}'.format(os.getuid() if user else 0), user=user)
104 test_content('f {} - - - - %G', '{}'.format(os.getgid() if user else 0), user=user)
03025f46 105
60f42f7e
DDM
106 try:
107 puser = pwd.getpwuid(os.getuid() if user else 0)
108 except KeyError:
109 puser = None
b75f0c69 110
60f42f7e
DDM
111 if puser:
112 test_content('f {} - - - - %u', '{}'.format(puser.pw_name), user=user)
113
114 try:
115 pgroup = grp.getgrgid(os.getgid() if user else 0)
116 except KeyError:
117 pgroup = None
118
119 if pgroup:
120 test_content('f {} - - - - %g', '{}'.format(pgroup.gr_name), user=user)
2f813b8a
ZJS
121
122 # Note that %h is the only specifier in which we look the environment,
123 # because we check $HOME. Should we even be doing that?
124 home = os.path.expanduser("~")
125 test_content('f {} - - - - %h', '{}'.format(home), user=user)
03025f46
ZJS
126
127 xdg_runtime_dir = os.getenv('XDG_RUNTIME_DIR')
128 if xdg_runtime_dir is not None or not user:
129 test_content('f {} - - - - %t',
130 xdg_runtime_dir if user else '/run',
131 user=user)
132
133 xdg_config_home = os.getenv('XDG_CONFIG_HOME')
134 if xdg_config_home is not None or not user:
135 test_content('f {} - - - - %S',
136 xdg_config_home if user else '/var/lib',
137 user=user)
138
139 xdg_cache_home = os.getenv('XDG_CACHE_HOME')
140 if xdg_cache_home is not None or not user:
141 test_content('f {} - - - - %C',
142 xdg_cache_home if user else '/var/cache',
143 user=user)
144
145 if xdg_config_home is not None or not user:
146 test_content('f {} - - - - %L',
147 xdg_config_home + '/log' if user else '/var/log',
148 user=user)
149
150 test_content('f {} - - - - %%', '%', user=user)
d9daae55 151
c46c3233
AW
152def mkfifo(parent, subpath):
153 os.makedirs(parent, mode=0o755, exist_ok=True)
154 first_component = subpath.split('/')[1]
155 path = parent + '/' + first_component
156 print('path: {}'.format(path))
157 os.mkfifo(path)
158
159def mkdir(parent, subpath):
160 first_component = subpath.split('/')[1]
161 path = parent + '/' + first_component
162 os.makedirs(path, mode=0o755, exist_ok=True)
163 os.symlink(path, path + '/self', target_is_directory=True)
164
165def symlink(parent, subpath):
166 link_path = parent + '/link-target'
167 os.makedirs(parent, mode=0o755, exist_ok=True)
168 with open(link_path, 'wb') as f:
169 f.write(b'target')
170 first_component = subpath.split('/')[1]
171 path = parent + '/' + first_component
172 os.symlink(link_path, path, target_is_directory=True)
173
174def file(parent, subpath):
175 content = 'file-' + subpath.split('/')[1]
176 path = parent + subpath
177 os.makedirs(os.path.dirname(path), mode=0o755, exist_ok=True)
178 with open(path, 'wb') as f:
179 f.write(content.encode())
180
181def valid_symlink(parent, subpath):
182 target = 'link-target'
183 link_path = parent + target
184 os.makedirs(link_path, mode=0o755, exist_ok=True)
185 first_component = subpath.split('/')[1]
186 path = parent + '/' + first_component
187 os.symlink(target, path, target_is_directory=True)
188
189def test_hard_cleanup(*, user):
190 type_cbs = [None, file, mkdir, symlink]
191 if 'mkfifo' in dir(os):
192 type_cbs.append(mkfifo)
193
194 for type_cb in type_cbs:
195 for subpath in ['/shallow', '/deep/1/2']:
196 label = '{}-{}'.format('None' if type_cb is None else type_cb.__name__, subpath.split('/')[1])
197 test_content('f= {} - - - - ' + label, label, user=user, subpath=subpath, path_cb=type_cb)
198
199 # Test the case that a valid symlink is in the path.
200 label = 'valid_symlink-deep'
201 test_content('f= {} - - - - ' + label, label, user=user, subpath='/deep/1/2', path_cb=valid_symlink)
202
708daf42 203def test_base64():
015ddd4b 204 test_content('f~ {} - - - - UGlmZgpQYWZmClB1ZmYgCg==', "Piff\nPaff\nPuff \n", user=False)
708daf42 205
f582e61b
MY
206def test_conditionalized_execute_bit():
207 c = subprocess.run(exe_with_args + ['--version', '|', 'grep', '-F', '+ACL'], shell=True, stdout=subprocess.DEVNULL)
208 if c.returncode != 0:
209 return 0
210
211 d = tempfile.TemporaryDirectory(prefix='test-acl.', dir=temp_dir.name)
212 temp = Path(d.name) / "cond_exec"
213 temp.touch()
214 temp.chmod(0o644)
215
216 test_line(f"a {temp} - - - - u:root:Xwr", user=False, returncode=0)
217 c = subprocess.run(["getfacl", "-Ec", temp],
218 stdout=subprocess.PIPE, check=True, text=True)
219 assert "user:root:rw-" in c.stdout
220
221 temp.chmod(0o755)
222 test_line(f"a+ {temp} - - - - u:root:Xwr,g:root:rX", user=False, returncode=0)
223 c = subprocess.run(["getfacl", "-Ec", temp],
224 stdout=subprocess.PIPE, check=True, text=True)
225 assert "user:root:rwx" in c.stdout and "group:root:r-x" in c.stdout
226
d9daae55 227if __name__ == '__main__':
5a8575ef
ZJS
228 test_invalids(user=False)
229 test_invalids(user=True)
a6dffbb7 230 test_uninitialized_t()
03025f46
ZJS
231
232 test_valid_specifiers(user=False)
233 test_valid_specifiers(user=True)
c46c3233
AW
234
235 test_hard_cleanup(user=False)
236 test_hard_cleanup(user=True)
708daf42
LP
237
238 test_base64()
f582e61b
MY
239
240 test_conditionalized_execute_bit()