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