]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/login/logind-user.c
basic: rename util.h to logarithm.h
[thirdparty/systemd.git] / src / login / logind-user.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
20263082 2
4f5dd394 3#include <errno.h>
20263082 4#include <unistd.h>
20263082 5
b5efdb8a 6#include "alloc-util.h"
90558f31 7#include "bus-common-errors.h"
cc377381 8#include "bus-error.h"
4f5dd394 9#include "bus-util.h"
f5058264 10#include "cgroup-util.h"
66cdd0f2 11#include "clean-ipc.h"
686d13b9 12#include "env-file.h"
4f5dd394 13#include "escape.h"
3ffd4af2 14#include "fd-util.h"
4f5dd394 15#include "fileio.h"
f97b34a6 16#include "format-util.h"
f4f15635 17#include "fs-util.h"
4f5dd394 18#include "hashmap.h"
9e281beb 19#include "label.h"
eefc66aa 20#include "limits-util.h"
6ecda0fb 21#include "logind-dbus.h"
6ecda0fb 22#include "logind-user-dbus.h"
ed5033fd 23#include "logind-user.h"
35cd0ba5 24#include "mkdir-label.h"
6bedfcbb 25#include "parse-util.h"
4f5dd394 26#include "path-util.h"
ed5033fd 27#include "percent-util.h"
4f5dd394 28#include "rm-rf.h"
d68c645b 29#include "serialize.h"
4f5dd394 30#include "special.h"
90558f31 31#include "stdio-util.h"
8b43440b 32#include "string-table.h"
4e5b605a 33#include "strv.h"
e4de7287 34#include "tmpfile-util.h"
b085d224 35#include "uid-alloc-range.h"
4f5dd394 36#include "unit-name.h"
ee104e11 37#include "user-util.h"
20263082 38
d5ac9d06
LP
39int user_new(User **ret,
40 Manager *m,
22c902fa 41 UserRecord *ur) {
d5ac9d06 42
157f5057 43 _cleanup_(user_freep) User *u = NULL;
6230bf75 44 char lu[DECIMAL_STR_MAX(uid_t) + 1];
6230bf75 45 int r;
20263082 46
8c29a457 47 assert(ret);
20263082 48 assert(m);
22c902fa
LP
49 assert(ur);
50
51 if (!ur->user_name)
52 return -EINVAL;
53
54 if (!uid_is_valid(ur->uid))
55 return -EINVAL;
20263082 56
8c29a457 57 u = new(User, 1);
20263082 58 if (!u)
157f5057
DH
59 return -ENOMEM;
60
8c29a457
LP
61 *u = (User) {
62 .manager = m,
22c902fa 63 .user_record = user_record_ref(ur),
9afe9efb 64 .last_session_timestamp = USEC_INFINITY,
8c29a457 65 };
20263082 66
22c902fa 67 if (asprintf(&u->state_file, "/run/systemd/users/" UID_FMT, ur->uid) < 0)
d5ac9d06
LP
68 return -ENOMEM;
69
22c902fa 70 if (asprintf(&u->runtime_path, "/run/user/" UID_FMT, ur->uid) < 0)
157f5057 71 return -ENOMEM;
f9e4283d 72
22c902fa 73 xsprintf(lu, UID_FMT, ur->uid);
6230bf75
DH
74 r = slice_build_subslice(SPECIAL_USER_SLICE, lu, &u->slice);
75 if (r < 0)
157f5057 76 return r;
6230bf75 77
b690ef12
DH
78 r = unit_name_build("user", lu, ".service", &u->service);
79 if (r < 0)
80 return r;
81
25a1ab4e
LP
82 r = unit_name_build("user-runtime-dir", lu, ".service", &u->runtime_dir_service);
83 if (r < 0)
84 return r;
85
22c902fa 86 r = hashmap_put(m->users, UID_TO_PTR(ur->uid), u);
157f5057
DH
87 if (r < 0)
88 return r;
20263082 89
157f5057
DH
90 r = hashmap_put(m->user_units, u->slice, u);
91 if (r < 0)
92 return r;
9444b1f2 93
b690ef12
DH
94 r = hashmap_put(m->user_units, u->service, u);
95 if (r < 0)
96 return r;
97
25a1ab4e
LP
98 r = hashmap_put(m->user_units, u->runtime_dir_service, u);
99 if (r < 0)
100 return r;
101
8c29a457 102 *ret = TAKE_PTR(u);
157f5057 103 return 0;
20263082
LP
104}
105
157f5057
DH
106User *user_free(User *u) {
107 if (!u)
108 return NULL;
20263082 109
14c3baca 110 if (u->in_gc_queue)
71fda00f 111 LIST_REMOVE(gc_queue, u->manager->user_gc_queue, u);
14c3baca 112
20263082
LP
113 while (u->sessions)
114 session_free(u->sessions);
115
157f5057
DH
116 if (u->service)
117 hashmap_remove_value(u->manager->user_units, u->service, u);
118
25a1ab4e
LP
119 if (u->runtime_dir_service)
120 hashmap_remove_value(u->manager->user_units, u->runtime_dir_service, u);
121
157f5057
DH
122 if (u->slice)
123 hashmap_remove_value(u->manager->user_units, u->slice, u);
fb6becb4 124
22c902fa 125 hashmap_remove_value(u->manager->users, UID_TO_PTR(u->user_record->uid), u);
6230bf75 126
22c902fa 127 sd_event_source_unref(u->timer_event_source);
9afe9efb 128
157f5057 129 u->service_job = mfree(u->service_job);
fb6becb4 130
157f5057 131 u->service = mfree(u->service);
25a1ab4e 132 u->runtime_dir_service = mfree(u->runtime_dir_service);
157f5057
DH
133 u->slice = mfree(u->slice);
134 u->runtime_path = mfree(u->runtime_path);
135 u->state_file = mfree(u->state_file);
22c902fa
LP
136
137 user_record_unref(u->user_record);
20263082 138
157f5057 139 return mfree(u);
20263082
LP
140}
141
71161305 142static int user_save_internal(User *u) {
9444b1f2
LP
143 _cleanup_free_ char *temp_path = NULL;
144 _cleanup_fclose_ FILE *f = NULL;
20263082
LP
145 int r;
146
147 assert(u);
148 assert(u->state_file);
149
37c1d5e9 150 r = mkdir_safe_label("/run/systemd/users", 0755, 0, 0, MKDIR_WARN_MODE);
20263082 151 if (r < 0)
dacd6cee 152 goto fail;
20263082 153
14c3baca
LP
154 r = fopen_temporary(u->state_file, &f, &temp_path);
155 if (r < 0)
dacd6cee 156 goto fail;
14c3baca 157
0d536673 158 (void) fchmod(fileno(f), 0644);
20263082
LP
159
160 fprintf(f,
14c3baca 161 "# This is private data. Do not parse.\n"
20263082 162 "NAME=%s\n"
d865bc02
LP
163 "STATE=%s\n" /* friendly user-facing state */
164 "STOPPING=%s\n", /* low-level state */
22c902fa 165 u->user_record->user_name,
d865bc02
LP
166 user_state_to_string(user_get_state(u)),
167 yes_no(u->stopping));
20263082 168
f9e4283d 169 /* LEGACY: no-one reads RUNTIME= anymore, drop it at some point */
20263082 170 if (u->runtime_path)
9444b1f2 171 fprintf(f, "RUNTIME=%s\n", u->runtime_path);
20263082 172
fb6becb4
LP
173 if (u->service_job)
174 fprintf(f, "SERVICE_JOB=%s\n", u->service_job);
9444b1f2 175
20263082 176 if (u->display)
9444b1f2
LP
177 fprintf(f, "DISPLAY=%s\n", u->display->id);
178
179 if (dual_timestamp_is_set(&u->timestamp))
20263082 180 fprintf(f,
90b2de37
ZJS
181 "REALTIME="USEC_FMT"\n"
182 "MONOTONIC="USEC_FMT"\n",
183 u->timestamp.realtime,
184 u->timestamp.monotonic);
20263082 185
9afe9efb
LP
186 if (u->last_session_timestamp != USEC_INFINITY)
187 fprintf(f, "LAST_SESSION_TIMESTAMP=" USEC_FMT "\n",
188 u->last_session_timestamp);
189
034a2a52 190 if (u->sessions) {
9b958eff 191 bool first;
034a2a52 192
0d536673 193 fputs("SESSIONS=", f);
9b958eff 194 first = true;
034a2a52 195 LIST_FOREACH(sessions_by_user, i, u->sessions) {
9b958eff
LP
196 if (first)
197 first = false;
198 else
0d536673 199 fputc(' ', f);
9b958eff 200
0d536673 201 fputs(i->id, f);
034a2a52
LP
202 }
203
0d536673 204 fputs("\nSEATS=", f);
9b958eff 205 first = true;
034a2a52 206 LIST_FOREACH(sessions_by_user, i, u->sessions) {
9b958eff
LP
207 if (!i->seat)
208 continue;
209
210 if (first)
211 first = false;
212 else
0d536673 213 fputc(' ', f);
9b958eff 214
0d536673 215 fputs(i->seat->id, f);
034a2a52
LP
216 }
217
0d536673 218 fputs("\nACTIVE_SESSIONS=", f);
9b958eff
LP
219 first = true;
220 LIST_FOREACH(sessions_by_user, i, u->sessions) {
221 if (!session_is_active(i))
222 continue;
223
224 if (first)
225 first = false;
226 else
0d536673 227 fputc(' ', f);
9b958eff 228
0d536673 229 fputs(i->id, f);
9b958eff 230 }
034a2a52 231
0d536673 232 fputs("\nONLINE_SESSIONS=", f);
2dc8f41a
CG
233 first = true;
234 LIST_FOREACH(sessions_by_user, i, u->sessions) {
235 if (session_get_state(i) == SESSION_CLOSING)
236 continue;
237
238 if (first)
239 first = false;
240 else
0d536673 241 fputc(' ', f);
2dc8f41a 242
0d536673 243 fputs(i->id, f);
2dc8f41a
CG
244 }
245
0d536673 246 fputs("\nACTIVE_SEATS=", f);
9b958eff 247 first = true;
034a2a52 248 LIST_FOREACH(sessions_by_user, i, u->sessions) {
9b958eff
LP
249 if (!session_is_active(i) || !i->seat)
250 continue;
251
252 if (first)
253 first = false;
254 else
0d536673 255 fputc(' ', f);
47acb2f1 256
0d536673 257 fputs(i->seat->id, f);
034a2a52 258 }
2dc8f41a 259
0d536673 260 fputs("\nONLINE_SEATS=", f);
2dc8f41a
CG
261 first = true;
262 LIST_FOREACH(sessions_by_user, i, u->sessions) {
263 if (session_get_state(i) == SESSION_CLOSING || !i->seat)
264 continue;
265
266 if (first)
267 first = false;
268 else
0d536673 269 fputc(' ', f);
2dc8f41a 270
0d536673 271 fputs(i->seat->id, f);
2dc8f41a 272 }
0d536673 273 fputc('\n', f);
034a2a52
LP
274 }
275
dacd6cee
LP
276 r = fflush_and_check(f);
277 if (r < 0)
278 goto fail;
14c3baca 279
dacd6cee 280 if (rename(temp_path, u->state_file) < 0) {
20263082 281 r = -errno;
dacd6cee 282 goto fail;
20263082
LP
283 }
284
dacd6cee
LP
285 return 0;
286
287fail:
288 (void) unlink(u->state_file);
289
290 if (temp_path)
291 (void) unlink(temp_path);
14c3baca 292
dacd6cee 293 return log_error_errno(r, "Failed to save user data %s: %m", u->state_file);
20263082
LP
294}
295
71161305
SM
296int user_save(User *u) {
297 assert(u);
298
299 if (!u->started)
300 return 0;
301
8c29a457 302 return user_save_internal(u);
71161305
SM
303}
304
20263082 305int user_load(User *u) {
9afe9efb 306 _cleanup_free_ char *realtime = NULL, *monotonic = NULL, *stopping = NULL, *last_session_timestamp = NULL;
9444b1f2 307 int r;
20263082
LP
308
309 assert(u);
310
aa8fbc74 311 r = parse_env_file(NULL, u->state_file,
9afe9efb
LP
312 "SERVICE_JOB", &u->service_job,
313 "STOPPING", &stopping,
314 "REALTIME", &realtime,
315 "MONOTONIC", &monotonic,
13df9c39 316 "LAST_SESSION_TIMESTAMP", &last_session_timestamp);
1c8280fd
LP
317 if (r == -ENOENT)
318 return 0;
319 if (r < 0)
d710aaf7 320 return log_error_errno(r, "Failed to read %s: %m", u->state_file);
20263082 321
d865bc02
LP
322 if (stopping) {
323 r = parse_boolean(stopping);
324 if (r < 0)
325 log_debug_errno(r, "Failed to parse 'STOPPING' boolean: %s", stopping);
326 else
327 u->stopping = r;
328 }
329
b895a735 330 if (realtime)
d68c645b 331 (void) deserialize_usec(realtime, &u->timestamp.realtime);
b895a735 332 if (monotonic)
d68c645b 333 (void) deserialize_usec(monotonic, &u->timestamp.monotonic);
9afe9efb 334 if (last_session_timestamp)
d68c645b 335 (void) deserialize_usec(last_session_timestamp, &u->last_session_timestamp);
9444b1f2 336
d865bc02 337 return 0;
20263082
LP
338}
339
25a1ab4e 340static void user_start_service(User *u) {
4afd3348 341 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
fb6becb4
LP
342 int r;
343
20263082
LP
344 assert(u);
345
25a1ab4e
LP
346 /* Start the service containing the "systemd --user" instance (user@.service). Note that we don't explicitly
347 * start the per-user slice or the systemd-runtime-dir@.service instance, as those are pulled in both by
348 * user@.service and the session scopes as dependencies. */
349
b690ef12 350 u->service_job = mfree(u->service_job);
fb6becb4 351
25a1ab4e 352 r = manager_start_unit(u->manager, u->service, &error, &u->service_job);
545a30a9 353 if (r < 0)
03b6fa0c
MS
354 log_full_errno(sd_bus_error_has_name(&error, BUS_ERROR_UNIT_MASKED) ? LOG_DEBUG : LOG_WARNING, r,
355 "Failed to start user service '%s', ignoring: %s", u->service, bus_error_message(&error, r));
20263082
LP
356}
357
e8e4b7a0 358static int update_slice_callback(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
99534007 359 _cleanup_(user_record_unrefp) UserRecord *ur = ASSERT_PTR(userdata);
80c8c786
YW
360 const sd_bus_error *e;
361 int r;
e8e4b7a0
LP
362
363 assert(m);
e8e4b7a0 364
80c8c786
YW
365 e = sd_bus_message_get_error(m);
366 if (e) {
367 r = sd_bus_error_get_errno(e);
368 log_warning_errno(r,
e8e4b7a0
LP
369 "Failed to update slice of %s, ignoring: %s",
370 ur->user_name,
80c8c786 371 bus_error_message(e, r));
e8e4b7a0
LP
372
373 return 0;
374 }
375
376 log_debug("Successfully set slice parameters of %s.", ur->user_name);
377 return 0;
378}
379
380static int user_update_slice(User *u) {
381 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
382 int r;
383
384 assert(u);
385
386 if (u->user_record->tasks_max == UINT64_MAX &&
387 u->user_record->memory_high == UINT64_MAX &&
388 u->user_record->memory_max == UINT64_MAX &&
389 u->user_record->cpu_weight == UINT64_MAX &&
390 u->user_record->io_weight == UINT64_MAX)
391 return 0;
392
393 r = sd_bus_message_new_method_call(
394 u->manager->bus,
395 &m,
396 "org.freedesktop.systemd1",
397 "/org/freedesktop/systemd1",
398 "org.freedesktop.systemd1.Manager",
399 "SetUnitProperties");
400 if (r < 0)
401 return bus_log_create_error(r);
402
403 r = sd_bus_message_append(m, "sb", u->slice, true);
404 if (r < 0)
405 return bus_log_create_error(r);
406
407 r = sd_bus_message_open_container(m, 'a', "(sv)");
408 if (r < 0)
409 return bus_log_create_error(r);
410
b0a94df9
ZJS
411 const struct {
412 const char *name;
413 uint64_t value;
414 } settings[] = {
415 { "TasksMax", u->user_record->tasks_max },
416 { "MemoryMax", u->user_record->memory_max },
417 { "MemoryHigh", u->user_record->memory_high },
418 { "CPUWeight", u->user_record->cpu_weight },
419 { "IOWeight", u->user_record->io_weight },
420 };
e8e4b7a0 421
b0a94df9
ZJS
422 for (size_t i = 0; i < ELEMENTSOF(settings); i++)
423 if (settings[i].value != UINT64_MAX) {
424 r = sd_bus_message_append(m, "(sv)", settings[i].name, "t", settings[i].value);
425 if (r < 0)
426 return bus_log_create_error(r);
427 }
e8e4b7a0
LP
428
429 r = sd_bus_message_close_container(m);
430 if (r < 0)
431 return bus_log_create_error(r);
432
433 r = sd_bus_call_async(u->manager->bus, NULL, m, update_slice_callback, u->user_record, 0);
434 if (r < 0)
435 return log_error_errno(r, "Failed to change user slice properties: %m");
436
437 /* Ref the user record pointer, so that the slot keeps it pinned */
438 user_record_ref(u->user_record);
439
440 return 0;
441}
442
513cf7da 443int user_start(User *u) {
20263082
LP
444 assert(u);
445
a832ab6f 446 if (u->started && !u->stopping)
9418f147
LP
447 return 0;
448
25a1ab4e 449 /* If u->stopping is set, the user is marked for removal and service stop-jobs are queued. We have to clear
5238e957 450 * that flag before queueing the start-jobs again. If they succeed, the user object can be re-used just fine
25a1ab4e
LP
451 * (pid1 takes care of job-ordering and proper restart), but if they fail, we want to force another user_stop()
452 * so possibly pending units are stopped. */
a832ab6f
DH
453 u->stopping = false;
454
a9f0f5e5 455 if (!u->started)
22c902fa 456 log_debug("Starting services for new user %s.", u->user_record->user_name);
a832ab6f 457
25a1ab4e
LP
458 /* Save the user data so far, because pam_systemd will read the XDG_RUNTIME_DIR out of it while starting up
459 * systemd --user. We need to do user_save_internal() because we have not "officially" started yet. */
71161305
SM
460 user_save_internal(u);
461
e8e4b7a0
LP
462 /* Set slice parameters */
463 (void) user_update_slice(u);
464
25a1ab4e 465 /* Start user@UID.service */
513cf7da 466 user_start_service(u);
20263082 467
a832ab6f
DH
468 if (!u->started) {
469 if (!dual_timestamp_is_set(&u->timestamp))
470 dual_timestamp_get(&u->timestamp);
471 user_send_signal(u, true);
472 u->started = true;
473 }
9418f147 474
7f7bb946
LP
475 /* Save new user data */
476 user_save(u);
477
20263082
LP
478 return 0;
479}
480
1a42ce09 481static void user_stop_service(User *u, bool force) {
4afd3348 482 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
fb6becb4 483 int r;
20263082 484
20263082 485 assert(u);
25a1ab4e 486 assert(u->service);
20263082 487
25a1ab4e
LP
488 /* The reverse of user_start_service(). Note that we only stop user@UID.service here, and let StopWhenUnneeded=
489 * deal with the slice and the user-runtime-dir@.service instance. */
20263082 490
25a1ab4e 491 u->service_job = mfree(u->service_job);
20263082 492
1a42ce09 493 r = manager_stop_unit(u->manager, u->service, force ? "replace" : "fail", &error, &u->service_job);
fb2367ed 494 if (r < 0)
25a1ab4e 495 log_warning_errno(r, "Failed to stop user service '%s', ignoring: %s", u->service, bus_error_message(&error, r));
fb6becb4 496}
20263082 497
9bb69af4 498int user_stop(User *u, bool force) {
25a1ab4e 499 int r = 0;
03677889 500
20263082
LP
501 assert(u);
502
25a1ab4e
LP
503 /* This is called whenever we begin with tearing down a user record. It's called in two cases: explicit API
504 * request to do so via the bus (in which case 'force' is true) and automatically due to GC, if there's no
505 * session left pinning it (in which case 'force' is false). Note that this just initiates tearing down of the
506 * user, the User object will remain in memory until user_finalize() is called, see below. */
507
508 if (!u->started)
509 return 0;
510
511 if (u->stopping) { /* Stop jobs have already been queued */
b58b227a 512 user_save(u);
25a1ab4e 513 return 0;
b58b227a
DH
514 }
515
20263082 516 LIST_FOREACH(sessions_by_user, s, u->sessions) {
25a1ab4e
LP
517 int k;
518
9bb69af4 519 k = session_stop(s, force);
20263082
LP
520 if (k < 0)
521 r = k;
522 }
523
1a42ce09 524 user_stop_service(u, force);
20263082 525
5f41d1f1
LP
526 u->stopping = true;
527
405e0255
LP
528 user_save(u);
529
530 return r;
531}
532
533int user_finalize(User *u) {
405e0255
LP
534 int r = 0, k;
535
536 assert(u);
537
25a1ab4e
LP
538 /* Called when the user is really ready to be freed, i.e. when all unit stop jobs and suchlike for it are
539 * done. This is called as a result of an earlier user_done() when all jobs are completed. */
540
405e0255 541 if (u->started)
22c902fa 542 log_debug("User %s logged out.", u->user_record->user_name);
405e0255
LP
543
544 LIST_FOREACH(sessions_by_user, s, u->sessions) {
545 k = session_finalize(s);
546 if (k < 0)
547 r = k;
548 }
549
00d9ef85
LP
550 /* Clean SysV + POSIX IPC objects, but only if this is not a system user. Background: in many setups cronjobs
551 * are run in full PAM and thus logind sessions, even if the code run doesn't belong to actual users but to
552 * system components. Since enable RemoveIPC= globally for all users, we need to be a bit careful with such
553 * cases, as we shouldn't accidentally remove a system service's IPC objects while it is running, just because
554 * a cronjob running as the same user just finished. Hence: exclude system users generally from IPC clean-up,
555 * and do it only for normal users. */
22c902fa
LP
556 if (u->manager->remove_ipc && !uid_is_system(u->user_record->uid)) {
557 k = clean_ipc_by_uid(u->user_record->uid);
66cdd0f2
LP
558 if (k < 0)
559 r = k;
560 }
561
75bbdf47 562 (void) unlink(u->state_file);
d2f92cdf
LP
563 user_add_to_gc_queue(u);
564
405e0255 565 if (u->started) {
ed18b08b 566 user_send_signal(u, false);
405e0255
LP
567 u->started = false;
568 }
9418f147 569
20263082
LP
570 return r;
571}
572
a185c5aa 573int user_get_idle_hint(User *u, dual_timestamp *t) {
a185c5aa 574 bool idle_hint = true;
5cb14b37 575 dual_timestamp ts = DUAL_TIMESTAMP_NULL;
a185c5aa
LP
576
577 assert(u);
578
579 LIST_FOREACH(sessions_by_user, s, u->sessions) {
580 dual_timestamp k;
581 int ih;
582
583 ih = session_get_idle_hint(s, &k);
584 if (ih < 0)
585 return ih;
586
587 if (!ih) {
588 if (!idle_hint) {
589 if (k.monotonic < ts.monotonic)
590 ts = k;
591 } else {
592 idle_hint = false;
593 ts = k;
594 }
595 } else if (idle_hint) {
596
597 if (k.monotonic > ts.monotonic)
598 ts = k;
599 }
600 }
601
602 if (t)
603 *t = ts;
604
605 return idle_hint;
606}
607
3a9f7a30 608int user_check_linger_file(User *u) {
cc377381
LP
609 _cleanup_free_ char *cc = NULL;
610 char *p = NULL;
e96cd586 611
22c902fa 612 cc = cescape(u->user_record->user_name);
cc377381 613 if (!cc)
e96cd586
LP
614 return -ENOMEM;
615
63c372cb 616 p = strjoina("/var/lib/systemd/linger/", cc);
6996df9b
LP
617 if (access(p, F_OK) < 0) {
618 if (errno != ENOENT)
619 return -errno;
e96cd586 620
6996df9b
LP
621 return false;
622 }
623
624 return true;
e96cd586
LP
625}
626
4e5b605a 627static bool user_unit_active(User *u) {
4e5b605a
LP
628 int r;
629
630 assert(u->service);
631 assert(u->runtime_dir_service);
632 assert(u->slice);
633
634 FOREACH_STRING(i, u->service, u->runtime_dir_service, u->slice) {
635 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
636
637 r = manager_unit_is_active(u->manager, i, &error);
638 if (r < 0)
bbd26200 639 log_debug_errno(r, "Failed to determine whether unit '%s' is active, ignoring: %s", i, bus_error_message(&error, r));
4e5b605a
LP
640 if (r != 0)
641 return true;
642 }
643
644 return false;
645}
646
d510589f
LP
647static usec_t user_get_stop_delay(User *u) {
648 assert(u);
649
650 if (u->user_record->stop_delay_usec != UINT64_MAX)
651 return u->user_record->stop_delay_usec;
652
653 if (user_record_removable(u->user_record) > 0)
654 return 0; /* For removable users lower the stop delay to zero */
655
656 return u->manager->user_stop_delay;
657}
658
5c093a23 659bool user_may_gc(User *u, bool drop_not_started) {
bd26aee1
LP
660 int r;
661
20263082
LP
662 assert(u);
663
4a4b033f 664 if (drop_not_started && !u->started)
5c093a23 665 return true;
932e3ee7 666
20263082 667 if (u->sessions)
5c093a23 668 return false;
20263082 669
9afe9efb 670 if (u->last_session_timestamp != USEC_INFINITY) {
d510589f
LP
671 usec_t user_stop_delay;
672
9afe9efb
LP
673 /* All sessions have been closed. Let's see if we shall leave the user record around for a bit */
674
d510589f
LP
675 user_stop_delay = user_get_stop_delay(u);
676
677 if (user_stop_delay == USEC_INFINITY)
9afe9efb 678 return false; /* Leave it around forever! */
d510589f
LP
679 if (user_stop_delay > 0 &&
680 now(CLOCK_MONOTONIC) < usec_add(u->last_session_timestamp, user_stop_delay))
9afe9efb
LP
681 return false; /* Leave it around for a bit longer. */
682 }
683
4e5b605a
LP
684 /* Is this a user that shall stay around forever ("linger")? Before we say "no" to GC'ing for lingering users, let's check
685 * if any of the three units that we maintain for this user is still around. If none of them is,
686 * there's no need to keep this user around even if lingering is enabled. */
687 if (user_check_linger_file(u) > 0 && user_unit_active(u))
5c093a23 688 return false;
20263082 689
bd26aee1
LP
690 /* Check if our job is still pending */
691 if (u->service_job) {
692 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
cc377381 693
bd26aee1
LP
694 r = manager_job_is_active(u->manager, u->service_job, &error);
695 if (r < 0)
696 log_debug_errno(r, "Failed to determine whether job '%s' is pending, ignoring: %s", u->service_job, bus_error_message(&error, r));
697 if (r != 0)
698 return false;
699 }
700
701 /* Note that we don't care if the three units we manage for each user object are up or not, as we are managing
702 * their state rather than tracking it. */
405e0255 703
5c093a23 704 return true;
20263082
LP
705}
706
14c3baca
LP
707void user_add_to_gc_queue(User *u) {
708 assert(u);
709
710 if (u->in_gc_queue)
711 return;
712
71fda00f 713 LIST_PREPEND(gc_queue, u->manager->user_gc_queue, u);
14c3baca
LP
714 u->in_gc_queue = true;
715}
716
20263082 717UserState user_get_state(User *u) {
20263082
LP
718 assert(u);
719
5f41d1f1
LP
720 if (u->stopping)
721 return USER_CLOSING;
722
25a1ab4e 723 if (!u->started || u->service_job)
405e0255 724 return USER_OPENING;
c9caad80 725
5f41d1f1
LP
726 if (u->sessions) {
727 bool all_closing = true;
728
729 LIST_FOREACH(sessions_by_user, i, u->sessions) {
00555a2e
DH
730 SessionState state;
731
732 state = session_get_state(i);
733 if (state == SESSION_ACTIVE)
5f41d1f1 734 return USER_ACTIVE;
00555a2e 735 if (state != SESSION_CLOSING)
5f41d1f1
LP
736 all_closing = false;
737 }
20263082 738
c9caad80 739 return all_closing ? USER_CLOSING : USER_ONLINE;
5f41d1f1 740 }
e96cd586 741
4e5b605a 742 if (user_check_linger_file(u) > 0 && user_unit_active(u))
e96cd586
LP
743 return USER_LINGERING;
744
745 return USER_CLOSING;
20263082
LP
746}
747
de07ab16 748int user_kill(User *u, int signo) {
de07ab16
LP
749 assert(u);
750
fb6becb4 751 return manager_kill_unit(u->manager, u->slice, KILL_ALL, signo, NULL);
de07ab16
LP
752}
753
cde40acc 754static bool elect_display_filter(Session *s) {
04857cd8 755 /* Return true if the session is a candidate for the user’s ‘primary session’ or ‘display’. */
7ffeb45c
PW
756 assert(s);
757
a2dcb1d7 758 return IN_SET(s->class, SESSION_USER, SESSION_GREETER) && s->started && !s->stopping;
7ffeb45c
PW
759}
760
cde40acc 761static int elect_display_compare(Session *s1, Session *s2) {
7ffeb45c 762 /* Indexed by SessionType. Lower numbers mean more preferred. */
469df514 763 static const int type_ranks[_SESSION_TYPE_MAX] = {
7ffeb45c
PW
764 [SESSION_UNSPECIFIED] = 0,
765 [SESSION_TTY] = -2,
766 [SESSION_X11] = -3,
767 [SESSION_WAYLAND] = -3,
768 [SESSION_MIR] = -3,
769 [SESSION_WEB] = -1,
770 };
771
772 /* Calculate the partial order relationship between s1 and s2,
773 * returning < 0 if s1 is preferred as the user’s ‘primary session’,
774 * 0 if s1 and s2 are equally preferred or incomparable, or > 0 if s2
775 * is preferred.
776 *
777 * s1 or s2 may be NULL. */
b9460fdc
RC
778 if (!s1 && !s2)
779 return 0;
780
7ffeb45c
PW
781 if ((s1 == NULL) != (s2 == NULL))
782 return (s1 == NULL) - (s2 == NULL);
783
784 if (s1->stopping != s2->stopping)
785 return s1->stopping - s2->stopping;
786
787 if ((s1->class != SESSION_USER) != (s2->class != SESSION_USER))
788 return (s1->class != SESSION_USER) - (s2->class != SESSION_USER);
789
790 if ((s1->type == _SESSION_TYPE_INVALID) != (s2->type == _SESSION_TYPE_INVALID))
791 return (s1->type == _SESSION_TYPE_INVALID) - (s2->type == _SESSION_TYPE_INVALID);
792
793 if (s1->type != s2->type)
794 return type_ranks[s1->type] - type_ranks[s2->type];
795
796 return 0;
797}
798
952d3260 799void user_elect_display(User *u) {
952d3260
LP
800 assert(u);
801
04857cd8
LP
802 /* This elects a primary session for each user, which we call the "display". We try to keep the assignment
803 * stable, but we "upgrade" to better choices. */
22c902fa 804 log_debug("Electing new display for user %s", u->user_record->user_name);
952d3260
LP
805
806 LIST_FOREACH(sessions_by_user, s, u->sessions) {
7ffeb45c
PW
807 if (!elect_display_filter(s)) {
808 log_debug("Ignoring session %s", s->id);
952d3260 809 continue;
7ffeb45c 810 }
952d3260 811
7ffeb45c
PW
812 if (elect_display_compare(s, u->display) < 0) {
813 log_debug("Choosing session %s in preference to %s", s->id, u->display ? u->display->id : "-");
814 u->display = s;
815 }
e9e74f28 816 }
952d3260
LP
817}
818
9afe9efb 819static int user_stop_timeout_callback(sd_event_source *es, uint64_t usec, void *userdata) {
99534007 820 User *u = ASSERT_PTR(userdata);
9afe9efb 821
9afe9efb
LP
822 user_add_to_gc_queue(u);
823
824 return 0;
825}
826
827void user_update_last_session_timer(User *u) {
d510589f 828 usec_t user_stop_delay;
9afe9efb
LP
829 int r;
830
831 assert(u);
832
833 if (u->sessions) {
834 /* There are sessions, turn off the timer */
835 u->last_session_timestamp = USEC_INFINITY;
836 u->timer_event_source = sd_event_source_unref(u->timer_event_source);
837 return;
838 }
839
840 if (u->last_session_timestamp != USEC_INFINITY)
841 return; /* Timer already started */
842
843 u->last_session_timestamp = now(CLOCK_MONOTONIC);
844
845 assert(!u->timer_event_source);
846
d510589f 847 user_stop_delay = user_get_stop_delay(u);
0da36375 848 if (!timestamp_is_set(user_stop_delay))
9afe9efb
LP
849 return;
850
851 if (sd_event_get_state(u->manager->event) == SD_EVENT_FINISHED) {
852 log_debug("Not allocating user stop timeout, since we are already exiting.");
853 return;
854 }
855
856 r = sd_event_add_time(u->manager->event,
857 &u->timer_event_source,
858 CLOCK_MONOTONIC,
d510589f 859 usec_add(u->last_session_timestamp, user_stop_delay), 0,
9afe9efb
LP
860 user_stop_timeout_callback, u);
861 if (r < 0)
862 log_warning_errno(r, "Failed to enqueue user stop event source, ignoring: %m");
863
5291f26d 864 if (DEBUG_LOGGING)
9afe9efb 865 log_debug("Last session of user '%s' logged out, terminating user context in %s.",
22c902fa 866 u->user_record->user_name,
5291f26d 867 FORMAT_TIMESPAN(user_stop_delay, USEC_PER_MSEC));
9afe9efb
LP
868}
869
20263082
LP
870static const char* const user_state_table[_USER_STATE_MAX] = {
871 [USER_OFFLINE] = "offline",
fb6becb4 872 [USER_OPENING] = "opening",
20263082
LP
873 [USER_LINGERING] = "lingering",
874 [USER_ONLINE] = "online",
e96cd586
LP
875 [USER_ACTIVE] = "active",
876 [USER_CLOSING] = "closing"
20263082
LP
877};
878
879DEFINE_STRING_TABLE_LOOKUP(user_state, UserState);
1c231f56
LP
880
881int config_parse_tmpfs_size(
882 const char* unit,
883 const char *filename,
884 unsigned line,
885 const char *section,
886 unsigned section_line,
887 const char *lvalue,
888 int ltype,
889 const char *rvalue,
890 void *data,
891 void *userdata) {
892
99534007 893 uint64_t *sz = ASSERT_PTR(data);
1c231f56
LP
894 int r;
895
896 assert(filename);
897 assert(lvalue);
898 assert(rvalue);
1c231f56 899
9184ca48 900 /* First, try to parse as percentage */
fe845b5e
LP
901 r = parse_permyriad(rvalue);
902 if (r > 0)
903 *sz = physical_memory_scale(r, 10000U);
9184ca48 904 else {
59f448cf 905 uint64_t k;
1c231f56 906
9184ca48
LP
907 /* If the passed argument was not a percentage, or out of range, parse as byte size */
908
59f448cf 909 r = parse_size(rvalue, 1024, &k);
1e5f4e8b
YW
910 if (r >= 0 && (k <= 0 || (uint64_t) (size_t) k != k))
911 r = -ERANGE;
912 if (r < 0) {
196d41bc 913 log_syntax(unit, LOG_WARNING, filename, line, r, "Failed to parse size value '%s', ignoring: %m", rvalue);
1c231f56
LP
914 return 0;
915 }
916
59f448cf 917 *sz = PAGE_ALIGN((size_t) k);
1c231f56
LP
918 }
919
920 return 0;
921}
c06eec15 922
28414939
ZJS
923int config_parse_compat_user_tasks_max(
924 const char *unit,
c06eec15
LP
925 const char *filename,
926 unsigned line,
927 const char *section,
928 unsigned section_line,
929 const char *lvalue,
930 int ltype,
931 const char *rvalue,
932 void *data,
933 void *userdata) {
934
c06eec15
LP
935 assert(filename);
936 assert(lvalue);
937 assert(rvalue);
c06eec15 938
28414939
ZJS
939 log_syntax(unit, LOG_NOTICE, filename, line, 0,
940 "Support for option %s= has been removed.",
941 lvalue);
948f7ce4 942 log_info("Hint: try creating /etc/systemd/system/user-.slice.d/50-limits.conf with:\n"
28414939
ZJS
943 " [Slice]\n"
944 " TasksMax=%s",
945 rvalue);
c06eec15
LP
946 return 0;
947}