]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/home/homed-home.c
Merge pull request #18990 from yuwata/network-dhcpv6-use-domains
[thirdparty/systemd.git] / src / home / homed-home.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
70a5db58
LP
2
3#if HAVE_LINUX_MEMFD_H
4#include <linux/memfd.h>
5#endif
6
7#include <sys/mman.h>
8#include <sys/quota.h>
9#include <sys/vfs.h>
10
11#include "blockdev-util.h"
12#include "btrfs-util.h"
13#include "bus-common-errors.h"
14#include "env-util.h"
15#include "errno-list.h"
16#include "errno-util.h"
17#include "fd-util.h"
18#include "fileio.h"
19#include "home-util.h"
20#include "homed-home-bus.h"
21#include "homed-home.h"
22#include "missing_syscall.h"
23#include "mkdir.h"
24#include "path-util.h"
25#include "process-util.h"
26#include "pwquality-util.h"
27#include "quota-util.h"
28#include "resize-fs.h"
29#include "set.h"
30#include "signal-util.h"
31#include "stat-util.h"
32#include "string-table.h"
33#include "strv.h"
34#include "user-record-sign.h"
35#include "user-record-util.h"
679badd7 36#include "user-record-pwquality.h"
70a5db58
LP
37#include "user-record.h"
38#include "user-util.h"
39
40#define HOME_USERS_MAX 500
41#define PENDING_OPERATIONS_MAX 100
42
43assert_cc(HOME_UID_MIN <= HOME_UID_MAX);
44assert_cc(HOME_USERS_MAX <= (HOME_UID_MAX - HOME_UID_MIN + 1));
45
46static int home_start_work(Home *h, const char *verb, UserRecord *hr, UserRecord *secret);
47
48DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(operation_hash_ops, void, trivial_hash_func, trivial_compare_func, Operation, operation_unref);
49
50static int suitable_home_record(UserRecord *hr) {
51 int r;
52
53 assert(hr);
54
55 if (!hr->user_name)
56 return -EUNATCH;
57
58 /* We are a bit more restrictive with what we accept as homed-managed user than what we accept in
59 * home records in general. Let's enforce the stricter rule here. */
60 if (!suitable_user_name(hr->user_name))
61 return -EINVAL;
62 if (!uid_is_valid(hr->uid))
63 return -EINVAL;
64
65 /* Insist we are outside of the dynamic and system range */
66 if (uid_is_system(hr->uid) || gid_is_system(user_record_gid(hr)) ||
67 uid_is_dynamic(hr->uid) || gid_is_dynamic(user_record_gid(hr)))
68 return -EADDRNOTAVAIL;
69
70 /* Insist that GID and UID match */
71 if (user_record_gid(hr) != (gid_t) hr->uid)
72 return -EBADSLT;
73
74 /* Similar for the realm */
75 if (hr->realm) {
76 r = suitable_realm(hr->realm);
77 if (r < 0)
78 return r;
79 if (r == 0)
80 return -EINVAL;
81 }
82
83 return 0;
84}
85
86int home_new(Manager *m, UserRecord *hr, const char *sysfs, Home **ret) {
87 _cleanup_(home_freep) Home *home = NULL;
88 _cleanup_free_ char *nm = NULL, *ns = NULL;
89 int r;
90
91 assert(m);
92 assert(hr);
93
94 r = suitable_home_record(hr);
95 if (r < 0)
96 return r;
97
98 if (hashmap_contains(m->homes_by_name, hr->user_name))
99 return -EBUSY;
100
101 if (hashmap_contains(m->homes_by_uid, UID_TO_PTR(hr->uid)))
102 return -EBUSY;
103
104 if (sysfs && hashmap_contains(m->homes_by_sysfs, sysfs))
105 return -EBUSY;
106
107 if (hashmap_size(m->homes_by_name) >= HOME_USERS_MAX)
108 return -EUSERS;
109
110 nm = strdup(hr->user_name);
111 if (!nm)
112 return -ENOMEM;
113
114 if (sysfs) {
115 ns = strdup(sysfs);
116 if (!ns)
117 return -ENOMEM;
118 }
119
120 home = new(Home, 1);
121 if (!home)
122 return -ENOMEM;
123
124 *home = (Home) {
125 .manager = m,
126 .user_name = TAKE_PTR(nm),
127 .uid = hr->uid,
128 .state = _HOME_STATE_INVALID,
129 .worker_stdout_fd = -1,
130 .sysfs = TAKE_PTR(ns),
131 .signed_locally = -1,
132 };
133
134 r = hashmap_put(m->homes_by_name, home->user_name, home);
135 if (r < 0)
136 return r;
137
138 r = hashmap_put(m->homes_by_uid, UID_TO_PTR(home->uid), home);
139 if (r < 0)
140 return r;
141
142 if (home->sysfs) {
143 r = hashmap_put(m->homes_by_sysfs, home->sysfs, home);
144 if (r < 0)
145 return r;
146 }
147
148 r = user_record_clone(hr, USER_RECORD_LOAD_MASK_SECRET, &home->record);
149 if (r < 0)
150 return r;
151
152 (void) bus_manager_emit_auto_login_changed(m);
153 (void) bus_home_emit_change(home);
154
155 if (ret)
156 *ret = TAKE_PTR(home);
157 else
158 TAKE_PTR(home);
159
160 return 0;
161}
162
163Home *home_free(Home *h) {
164
165 if (!h)
166 return NULL;
167
168 if (h->manager) {
169 (void) bus_home_emit_remove(h);
170 (void) bus_manager_emit_auto_login_changed(h->manager);
171
172 if (h->user_name)
173 (void) hashmap_remove_value(h->manager->homes_by_name, h->user_name, h);
174
175 if (uid_is_valid(h->uid))
176 (void) hashmap_remove_value(h->manager->homes_by_uid, UID_TO_PTR(h->uid), h);
177
178 if (h->sysfs)
179 (void) hashmap_remove_value(h->manager->homes_by_sysfs, h->sysfs, h);
180
181 if (h->worker_pid > 0)
182 (void) hashmap_remove_value(h->manager->homes_by_worker_pid, PID_TO_PTR(h->worker_pid), h);
183
184 if (h->manager->gc_focus == h)
185 h->manager->gc_focus = NULL;
186 }
187
188 user_record_unref(h->record);
189 user_record_unref(h->secret);
190
cf536638 191 h->worker_event_source = sd_event_source_disable_unref(h->worker_event_source);
70a5db58
LP
192 safe_close(h->worker_stdout_fd);
193 free(h->user_name);
194 free(h->sysfs);
195
cf536638
ZJS
196 h->ref_event_source_please_suspend = sd_event_source_disable_unref(h->ref_event_source_please_suspend);
197 h->ref_event_source_dont_suspend = sd_event_source_disable_unref(h->ref_event_source_dont_suspend);
70a5db58
LP
198
199 h->pending_operations = ordered_set_free(h->pending_operations);
cf536638
ZJS
200 h->pending_event_source = sd_event_source_disable_unref(h->pending_event_source);
201 h->deferred_change_event_source = sd_event_source_disable_unref(h->deferred_change_event_source);
70a5db58
LP
202
203 h->current_operation = operation_unref(h->current_operation);
204
205 return mfree(h);
206}
207
208int home_set_record(Home *h, UserRecord *hr) {
209 _cleanup_(user_record_unrefp) UserRecord *new_hr = NULL;
210 Home *other;
211 int r;
212
213 assert(h);
214 assert(h->user_name);
215 assert(h->record);
216 assert(hr);
217
218 if (user_record_equal(h->record, hr))
219 return 0;
220
221 r = suitable_home_record(hr);
222 if (r < 0)
223 return r;
224
225 if (!user_record_compatible(h->record, hr))
226 return -EREMCHG;
227
228 if (!FLAGS_SET(hr->mask, USER_RECORD_REGULAR) ||
229 FLAGS_SET(hr->mask, USER_RECORD_SECRET))
230 return -EINVAL;
231
232 if (FLAGS_SET(h->record->mask, USER_RECORD_STATUS)) {
233 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
234
235 /* Hmm, the existing record has status fields? If so, copy them over */
236
237 v = json_variant_ref(hr->json);
238 r = json_variant_set_field(&v, "status", json_variant_by_key(h->record->json, "status"));
239 if (r < 0)
240 return r;
241
242 new_hr = user_record_new();
243 if (!new_hr)
244 return -ENOMEM;
245
246 r = user_record_load(new_hr, v, USER_RECORD_LOAD_REFUSE_SECRET);
247 if (r < 0)
248 return r;
249
250 hr = new_hr;
251 }
252
253 other = hashmap_get(h->manager->homes_by_uid, UID_TO_PTR(hr->uid));
254 if (other && other != h)
255 return -EBUSY;
256
257 if (h->uid != hr->uid) {
258 r = hashmap_remove_and_replace(h->manager->homes_by_uid, UID_TO_PTR(h->uid), UID_TO_PTR(hr->uid), h);
259 if (r < 0)
260 return r;
261 }
262
263 user_record_unref(h->record);
264 h->record = user_record_ref(hr);
265 h->uid = h->record->uid;
266
267 /* The updated record might have a different autologin setting, trigger a PropertiesChanged event for it */
268 (void) bus_manager_emit_auto_login_changed(h->manager);
269 (void) bus_home_emit_change(h);
270
271 return 0;
272}
273
274int home_save_record(Home *h) {
275 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
276 _cleanup_free_ char *text = NULL;
277 const char *fn;
278 int r;
279
280 assert(h);
281
282 v = json_variant_ref(h->record->json);
283 r = json_variant_normalize(&v);
284 if (r < 0)
285 log_warning_errno(r, "User record could not be normalized.");
286
287 r = json_variant_format(v, JSON_FORMAT_PRETTY|JSON_FORMAT_NEWLINE, &text);
288 if (r < 0)
289 return r;
290
291 (void) mkdir("/var/lib/systemd/", 0755);
292 (void) mkdir("/var/lib/systemd/home/", 0700);
293
294 fn = strjoina("/var/lib/systemd/home/", h->user_name, ".identity");
295
e4005ffe 296 r = write_string_file(fn, text, WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_MODE_0600|WRITE_STRING_FILE_SYNC);
70a5db58
LP
297 if (r < 0)
298 return r;
299
300 return 0;
301}
302
303int home_unlink_record(Home *h) {
304 const char *fn;
305
306 assert(h);
307
308 fn = strjoina("/var/lib/systemd/home/", h->user_name, ".identity");
309 if (unlink(fn) < 0 && errno != ENOENT)
310 return -errno;
311
312 fn = strjoina("/run/systemd/home/", h->user_name, ".ref");
313 if (unlink(fn) < 0 && errno != ENOENT)
314 return -errno;
315
316 return 0;
317}
318
319static void home_set_state(Home *h, HomeState state) {
320 HomeState old_state, new_state;
321
322 assert(h);
323
324 old_state = home_get_state(h);
325 h->state = state;
326 new_state = home_get_state(h); /* Query the new state, since the 'state' variable might be set to -1,
327 * in which case we synthesize an high-level state on demand */
328
329 log_info("%s: changing state %s → %s", h->user_name,
330 home_state_to_string(old_state),
331 home_state_to_string(new_state));
332
333 if (HOME_STATE_IS_EXECUTING_OPERATION(old_state) && !HOME_STATE_IS_EXECUTING_OPERATION(new_state)) {
334 /* If we just finished executing some operation, process the queue of pending operations. And
335 * enqueue it for GC too. */
336
337 home_schedule_operation(h, NULL, NULL);
338 manager_enqueue_gc(h->manager, h);
339 }
340}
341
342static int home_parse_worker_stdout(int _fd, UserRecord **ret) {
343 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
344 _cleanup_close_ int fd = _fd; /* take possession, even on failure */
345 _cleanup_(user_record_unrefp) UserRecord *hr = NULL;
346 _cleanup_fclose_ FILE *f = NULL;
347 unsigned line, column;
348 struct stat st;
349 int r;
350
351 if (fstat(fd, &st) < 0)
352 return log_error_errno(errno, "Failed to stat stdout fd: %m");
353
354 assert(S_ISREG(st.st_mode));
355
356 if (st.st_size == 0) { /* empty record */
357 *ret = NULL;
358 return 0;
359 }
360
361 if (lseek(fd, SEEK_SET, 0) == (off_t) -1)
362 return log_error_errno(errno, "Failed to seek to beginning of memfd: %m");
363
4fa744a3 364 f = take_fdopen(&fd, "r");
70a5db58
LP
365 if (!f)
366 return log_error_errno(errno, "Failed to reopen memfd: %m");
367
70a5db58
LP
368 if (DEBUG_LOGGING) {
369 _cleanup_free_ char *text = NULL;
370
371 r = read_full_stream(f, &text, NULL);
372 if (r < 0)
373 return log_error_errno(r, "Failed to read from client: %m");
374
375 log_debug("Got from worker: %s", text);
376 rewind(f);
377 }
378
379 r = json_parse_file(f, "stdout", JSON_PARSE_SENSITIVE, &v, &line, &column);
380 if (r < 0)
381 return log_error_errno(r, "Failed to parse identity at %u:%u: %m", line, column);
382
383 hr = user_record_new();
384 if (!hr)
385 return log_oom();
386
387 r = user_record_load(hr, v, USER_RECORD_LOAD_REFUSE_SECRET);
388 if (r < 0)
389 return log_error_errno(r, "Failed to load home record identity: %m");
390
391 *ret = TAKE_PTR(hr);
392 return 1;
393}
394
395static int home_verify_user_record(Home *h, UserRecord *hr, bool *ret_signed_locally, sd_bus_error *ret_error) {
396 int is_signed;
397
398 assert(h);
399 assert(hr);
400 assert(ret_signed_locally);
401
402 is_signed = manager_verify_user_record(h->manager, hr);
403 switch (is_signed) {
404
405 case USER_RECORD_SIGNED_EXCLUSIVE:
406 log_info("Home %s is signed exclusively by our key, accepting.", hr->user_name);
407 *ret_signed_locally = true;
408 return 0;
409
410 case USER_RECORD_SIGNED:
411 log_info("Home %s is signed by our key (and others), accepting.", hr->user_name);
412 *ret_signed_locally = false;
413 return 0;
414
415 case USER_RECORD_FOREIGN:
416 log_info("Home %s is signed by foreign key we like, accepting.", hr->user_name);
417 *ret_signed_locally = false;
418 return 0;
419
420 case USER_RECORD_UNSIGNED:
421 sd_bus_error_setf(ret_error, BUS_ERROR_BAD_SIGNATURE, "User record %s is not signed at all, refusing.", hr->user_name);
422 return log_error_errno(SYNTHETIC_ERRNO(EPERM), "Home %s contains user record that is not signed at all, refusing.", hr->user_name);
423
424 case -ENOKEY:
425 sd_bus_error_setf(ret_error, BUS_ERROR_BAD_SIGNATURE, "User record %s is not signed by any known key, refusing.", hr->user_name);
80ace4f2 426 return log_error_errno(is_signed, "Home %s contains user record that is not signed by any known key, refusing.", hr->user_name);
70a5db58
LP
427
428 default:
429 assert(is_signed < 0);
430 return log_error_errno(is_signed, "Failed to verify signature on user record for %s, refusing fixation: %m", hr->user_name);
431 }
432}
433
434static int convert_worker_errno(Home *h, int e, sd_bus_error *error) {
435 /* Converts the error numbers the worker process returned into somewhat sensible dbus errors */
436
437 switch (e) {
438
439 case -EMSGSIZE:
162392b7 440 return sd_bus_error_setf(error, BUS_ERROR_BAD_HOME_SIZE, "File systems of this type cannot be shrunk");
70a5db58 441 case -ETXTBSY:
162392b7 442 return sd_bus_error_setf(error, BUS_ERROR_BAD_HOME_SIZE, "File systems of this type can only be shrunk offline");
70a5db58
LP
443 case -ERANGE:
444 return sd_bus_error_setf(error, BUS_ERROR_BAD_HOME_SIZE, "File system size too small");
445 case -ENOLINK:
446 return sd_bus_error_setf(error, SD_BUS_ERROR_NOT_SUPPORTED, "System does not support selected storage backend");
447 case -EPROTONOSUPPORT:
448 return sd_bus_error_setf(error, SD_BUS_ERROR_NOT_SUPPORTED, "System does not support selected file system");
449 case -ENOTTY:
450 return sd_bus_error_setf(error, SD_BUS_ERROR_NOT_SUPPORTED, "Operation not supported on storage backend");
451 case -ESOCKTNOSUPPORT:
452 return sd_bus_error_setf(error, SD_BUS_ERROR_NOT_SUPPORTED, "Operation not supported on file system");
453 case -ENOKEY:
454 return sd_bus_error_setf(error, BUS_ERROR_BAD_PASSWORD, "Password for home %s is incorrect or not sufficient for authentication.", h->user_name);
455 case -EBADSLT:
456 return sd_bus_error_setf(error, BUS_ERROR_BAD_PASSWORD_AND_NO_TOKEN, "Password for home %s is incorrect or not sufficient, and configured security token not found either.", h->user_name);
87d7893c
LP
457 case -EREMOTEIO:
458 return sd_bus_error_setf(error, BUS_ERROR_BAD_RECOVERY_KEY, "Recovery key for home %s is incorrect or not sufficient for authentication.", h->user_name);
70a5db58
LP
459 case -ENOANO:
460 return sd_bus_error_setf(error, BUS_ERROR_TOKEN_PIN_NEEDED, "PIN for security token required.");
461 case -ERFKILL:
462 return sd_bus_error_setf(error, BUS_ERROR_TOKEN_PROTECTED_AUTHENTICATION_PATH_NEEDED, "Security token requires protected authentication path.");
7b78db28
LP
463 case -EMEDIUMTYPE:
464 return sd_bus_error_setf(error, BUS_ERROR_TOKEN_USER_PRESENCE_NEEDED, "Security token requires user presence.");
465 case -ENOSTR:
466 return sd_bus_error_setf(error, BUS_ERROR_TOKEN_ACTION_TIMEOUT, "Token action timeout. (User was supposed to verify presence or similar, by interacting with the token, and didn't do that in time.)");
70a5db58
LP
467 case -EOWNERDEAD:
468 return sd_bus_error_setf(error, BUS_ERROR_TOKEN_PIN_LOCKED, "PIN of security token locked.");
469 case -ENOLCK:
470 return sd_bus_error_setf(error, BUS_ERROR_TOKEN_BAD_PIN, "Bad PIN of security token.");
471 case -ETOOMANYREFS:
472 return sd_bus_error_setf(error, BUS_ERROR_TOKEN_BAD_PIN_FEW_TRIES_LEFT, "Bad PIN of security token, and only a few tries left.");
473 case -EUCLEAN:
474 return sd_bus_error_setf(error, BUS_ERROR_TOKEN_BAD_PIN_ONE_TRY_LEFT, "Bad PIN of security token, and only one try left.");
475 case -EBUSY:
476 return sd_bus_error_setf(error, BUS_ERROR_HOME_BUSY, "Home %s is currently being used, or an operation on home %s is currently being executed.", h->user_name, h->user_name);
477 case -ENOEXEC:
478 return sd_bus_error_setf(error, BUS_ERROR_HOME_NOT_ACTIVE, "Home %s is currently not active", h->user_name);
479 case -ENOSPC:
480 return sd_bus_error_setf(error, BUS_ERROR_NO_DISK_SPACE, "Not enough disk space for home %s", h->user_name);
cbffdcec
LP
481 case -EKEYREVOKED:
482 return sd_bus_error_setf(error, BUS_ERROR_HOME_CANT_AUTHENTICATE, "Home %s has no password or other authentication mechanism defined.", h->user_name);
70a5db58
LP
483 }
484
485 return 0;
486}
487
488static void home_count_bad_authentication(Home *h, bool save) {
489 int r;
490
491 assert(h);
492
493 r = user_record_bad_authentication(h->record);
494 if (r < 0) {
495 log_warning_errno(r, "Failed to increase bad authentication counter, ignoring: %m");
496 return;
497 }
498
499 if (save) {
500 r = home_save_record(h);
501 if (r < 0)
502 log_warning_errno(r, "Failed to write home record to disk, ignoring: %m");
503 }
504}
505
506static void home_fixate_finish(Home *h, int ret, UserRecord *hr) {
507 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
508 _cleanup_(user_record_unrefp) UserRecord *secret = NULL;
509 bool signed_locally;
510 int r;
511
512 assert(h);
513 assert(IN_SET(h->state, HOME_FIXATING, HOME_FIXATING_FOR_ACTIVATION, HOME_FIXATING_FOR_ACQUIRE));
514
515 secret = TAKE_PTR(h->secret); /* Take possession */
516
517 if (ret < 0) {
518 if (ret == -ENOKEY)
519 (void) home_count_bad_authentication(h, false);
520
521 (void) convert_worker_errno(h, ret, &error);
522 r = log_error_errno(ret, "Fixation failed: %m");
523 goto fail;
524 }
525 if (!hr) {
526 r = log_error_errno(SYNTHETIC_ERRNO(EIO), "Did not receive user record from worker process, fixation failed.");
527 goto fail;
528 }
529
530 r = home_verify_user_record(h, hr, &signed_locally, &error);
531 if (r < 0)
532 goto fail;
533
534 r = home_set_record(h, hr);
535 if (r < 0) {
536 log_error_errno(r, "Failed to update home record: %m");
537 goto fail;
538 }
539
540 h->signed_locally = signed_locally;
541
542 /* When we finished fixating (and don't follow-up with activation), let's count this as good authentication */
543 if (h->state == HOME_FIXATING) {
544 r = user_record_good_authentication(h->record);
545 if (r < 0)
546 log_warning_errno(r, "Failed to increase good authentication counter, ignoring: %m");
547 }
548
549 r = home_save_record(h);
550 if (r < 0)
551 log_warning_errno(r, "Failed to write home record to disk, ignoring: %m");
552
553 if (IN_SET(h->state, HOME_FIXATING_FOR_ACTIVATION, HOME_FIXATING_FOR_ACQUIRE)) {
554
555 r = home_start_work(h, "activate", h->record, secret);
556 if (r < 0) {
557 h->current_operation = operation_result_unref(h->current_operation, r, NULL);
558 home_set_state(h, _HOME_STATE_INVALID);
559 } else
560 home_set_state(h, h->state == HOME_FIXATING_FOR_ACTIVATION ? HOME_ACTIVATING : HOME_ACTIVATING_FOR_ACQUIRE);
561
562 return;
563 }
564
565 log_debug("Fixation of %s completed.", h->user_name);
566
567 h->current_operation = operation_result_unref(h->current_operation, 0, NULL);
568
569 /* Reset the state to "invalid", which makes home_get_state() test if the image exists and returns
570 * HOME_ABSENT vs. HOME_INACTIVE as necessary. */
571 home_set_state(h, _HOME_STATE_INVALID);
572 return;
573
574fail:
575 /* If fixation fails, we stay in unfixated state! */
576 h->current_operation = operation_result_unref(h->current_operation, r, &error);
577 home_set_state(h, HOME_UNFIXATED);
578}
579
580static void home_activate_finish(Home *h, int ret, UserRecord *hr) {
581 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
582 int r;
583
584 assert(h);
585 assert(IN_SET(h->state, HOME_ACTIVATING, HOME_ACTIVATING_FOR_ACQUIRE));
586
587 if (ret < 0) {
588 if (ret == -ENOKEY)
589 home_count_bad_authentication(h, true);
590
591 (void) convert_worker_errno(h, ret, &error);
592 r = log_error_errno(ret, "Activation failed: %m");
593 goto finish;
594 }
595
596 if (hr) {
597 bool signed_locally;
598
599 r = home_verify_user_record(h, hr, &signed_locally, &error);
600 if (r < 0)
601 goto finish;
602
603 r = home_set_record(h, hr);
604 if (r < 0) {
605 log_error_errno(r, "Failed to update home record, ignoring: %m");
606 goto finish;
607 }
608
609 h->signed_locally = signed_locally;
610
611 r = user_record_good_authentication(h->record);
612 if (r < 0)
613 log_warning_errno(r, "Failed to increase good authentication counter, ignoring: %m");
614
615 r = home_save_record(h);
616 if (r < 0)
617 log_warning_errno(r, "Failed to write home record to disk, ignoring: %m");
618 }
619
620 log_debug("Activation of %s completed.", h->user_name);
621 r = 0;
622
623finish:
624 h->current_operation = operation_result_unref(h->current_operation, r, &error);
625 home_set_state(h, _HOME_STATE_INVALID);
626}
627
628static void home_deactivate_finish(Home *h, int ret, UserRecord *hr) {
629 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
630 int r;
631
632 assert(h);
633 assert(h->state == HOME_DEACTIVATING);
634 assert(!hr); /* We don't expect a record on this operation */
635
636 if (ret < 0) {
637 (void) convert_worker_errno(h, ret, &error);
638 r = log_error_errno(ret, "Deactivation of %s failed: %m", h->user_name);
639 goto finish;
640 }
641
642 log_debug("Deactivation of %s completed.", h->user_name);
643 r = 0;
644
645finish:
646 h->current_operation = operation_result_unref(h->current_operation, r, &error);
647 home_set_state(h, _HOME_STATE_INVALID);
648}
649
650static void home_remove_finish(Home *h, int ret, UserRecord *hr) {
651 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
652 Manager *m;
653 int r;
654
655 assert(h);
656 assert(h->state == HOME_REMOVING);
657 assert(!hr); /* We don't expect a record on this operation */
658
659 m = h->manager;
660
661 if (ret < 0 && ret != -EALREADY) {
662 (void) convert_worker_errno(h, ret, &error);
663 r = log_error_errno(ret, "Removing %s failed: %m", h->user_name);
664 goto fail;
665 }
666
667 /* For a couple of storage types we can't delete the actual data storage when called (such as LUKS on
668 * partitions like USB sticks, or so). Sometimes these storage locations are among those we normally
669 * automatically discover in /home or in udev. When such a home is deleted let's hence issue a rescan
670 * after completion, so that "unfixated" entries are rediscovered. */
671 if (!IN_SET(user_record_test_image_path(h->record), USER_TEST_UNDEFINED, USER_TEST_ABSENT))
672 manager_enqueue_rescan(m);
673
674 /* The image is now removed from disk. Now also remove our stored record */
675 r = home_unlink_record(h);
676 if (r < 0) {
677 log_error_errno(r, "Removing record file failed: %m");
678 goto fail;
679 }
680
681 log_debug("Removal of %s completed.", h->user_name);
682 h->current_operation = operation_result_unref(h->current_operation, 0, NULL);
683
684 /* Unload this record from memory too now. */
685 h = home_free(h);
686 return;
687
688fail:
689 h->current_operation = operation_result_unref(h->current_operation, r, &error);
690 home_set_state(h, _HOME_STATE_INVALID);
691}
692
693static void home_create_finish(Home *h, int ret, UserRecord *hr) {
694 int r;
695
696 assert(h);
697 assert(h->state == HOME_CREATING);
698
699 if (ret < 0) {
700 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
701
702 (void) convert_worker_errno(h, ret, &error);
703 log_error_errno(ret, "Operation on %s failed: %m", h->user_name);
704 h->current_operation = operation_result_unref(h->current_operation, ret, &error);
705
706 if (h->unregister_on_failure) {
707 (void) home_unlink_record(h);
708 h = home_free(h);
709 return;
710 }
711
712 home_set_state(h, _HOME_STATE_INVALID);
713 return;
714 }
715
716 if (hr) {
717 r = home_set_record(h, hr);
718 if (r < 0)
719 log_warning_errno(r, "Failed to update home record, ignoring: %m");
720 }
721
722 r = home_save_record(h);
723 if (r < 0)
724 log_warning_errno(r, "Failed to save record to disk, ignoring: %m");
725
726 log_debug("Creation of %s completed.", h->user_name);
727
728 h->current_operation = operation_result_unref(h->current_operation, 0, NULL);
729 home_set_state(h, _HOME_STATE_INVALID);
730}
731
732static void home_change_finish(Home *h, int ret, UserRecord *hr) {
733 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
734 int r;
735
736 assert(h);
737
738 if (ret < 0) {
739 if (ret == -ENOKEY)
740 (void) home_count_bad_authentication(h, true);
741
742 (void) convert_worker_errno(h, ret, &error);
743 r = log_error_errno(ret, "Change operation failed: %m");
744 goto finish;
745 }
746
747 if (hr) {
748 r = home_set_record(h, hr);
749 if (r < 0)
750 log_warning_errno(r, "Failed to update home record, ignoring: %m");
751 else {
752 r = user_record_good_authentication(h->record);
753 if (r < 0)
754 log_warning_errno(r, "Failed to increase good authentication counter, ignoring: %m");
755
756 r = home_save_record(h);
757 if (r < 0)
758 log_warning_errno(r, "Failed to write home record to disk, ignoring: %m");
759 }
760 }
761
762 log_debug("Change operation of %s completed.", h->user_name);
763 r = 0;
764
765finish:
766 h->current_operation = operation_result_unref(h->current_operation, r, &error);
767 home_set_state(h, _HOME_STATE_INVALID);
768}
769
770static void home_locking_finish(Home *h, int ret, UserRecord *hr) {
771 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
772 int r;
773
774 assert(h);
775 assert(h->state == HOME_LOCKING);
776
777 if (ret < 0) {
778 (void) convert_worker_errno(h, ret, &error);
779 r = log_error_errno(ret, "Locking operation failed: %m");
780 goto finish;
781 }
782
783 log_debug("Locking operation of %s completed.", h->user_name);
784 h->current_operation = operation_result_unref(h->current_operation, 0, NULL);
785 home_set_state(h, HOME_LOCKED);
786 return;
787
788finish:
789 /* If a specific home doesn't know the concept of locking, then that's totally OK, don't propagate
790 * the error if we are executing a LockAllHomes() operation. */
791
792 if (h->current_operation->type == OPERATION_LOCK_ALL && r == -ENOTTY)
793 h->current_operation = operation_result_unref(h->current_operation, 0, NULL);
794 else
795 h->current_operation = operation_result_unref(h->current_operation, r, &error);
796
797 home_set_state(h, _HOME_STATE_INVALID);
798}
799
800static void home_unlocking_finish(Home *h, int ret, UserRecord *hr) {
801 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
802 int r;
803
804 assert(h);
805 assert(IN_SET(h->state, HOME_UNLOCKING, HOME_UNLOCKING_FOR_ACQUIRE));
806
807 if (ret < 0) {
808 if (ret == -ENOKEY)
809 (void) home_count_bad_authentication(h, true);
810
811 (void) convert_worker_errno(h, ret, &error);
812 r = log_error_errno(ret, "Unlocking operation failed: %m");
813
814 /* Revert to locked state */
815 home_set_state(h, HOME_LOCKED);
816 h->current_operation = operation_result_unref(h->current_operation, r, &error);
817 return;
818 }
819
820 r = user_record_good_authentication(h->record);
821 if (r < 0)
822 log_warning_errno(r, "Failed to increase good authentication counter, ignoring: %m");
823 else {
824 r = home_save_record(h);
825 if (r < 0)
826 log_warning_errno(r, "Failed to write home record to disk, ignoring: %m");
827 }
828
829 log_debug("Unlocking operation of %s completed.", h->user_name);
830
831 h->current_operation = operation_result_unref(h->current_operation, r, &error);
832 home_set_state(h, _HOME_STATE_INVALID);
833 return;
834}
835
836static void home_authenticating_finish(Home *h, int ret, UserRecord *hr) {
837 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
838 int r;
839
840 assert(h);
841 assert(IN_SET(h->state, HOME_AUTHENTICATING, HOME_AUTHENTICATING_WHILE_ACTIVE, HOME_AUTHENTICATING_FOR_ACQUIRE));
842
843 if (ret < 0) {
844 if (ret == -ENOKEY)
845 (void) home_count_bad_authentication(h, true);
846
847 (void) convert_worker_errno(h, ret, &error);
848 r = log_error_errno(ret, "Authentication failed: %m");
849 goto finish;
850 }
851
852 if (hr) {
853 r = home_set_record(h, hr);
854 if (r < 0)
855 log_warning_errno(r, "Failed to update home record, ignoring: %m");
856 else {
857 r = user_record_good_authentication(h->record);
858 if (r < 0)
859 log_warning_errno(r, "Failed to increase good authentication counter, ignoring: %m");
860
861 r = home_save_record(h);
862 if (r < 0)
863 log_warning_errno(r, "Failed to write home record to disk, ignoring: %m");
864 }
865 }
866
867 log_debug("Authentication of %s completed.", h->user_name);
868 r = 0;
869
870finish:
871 h->current_operation = operation_result_unref(h->current_operation, r, &error);
872 home_set_state(h, _HOME_STATE_INVALID);
873}
874
875static int home_on_worker_process(sd_event_source *s, const siginfo_t *si, void *userdata) {
876 _cleanup_(user_record_unrefp) UserRecord *hr = NULL;
877 Home *h = userdata;
878 int ret;
879
880 assert(s);
881 assert(si);
882 assert(h);
883
884 assert(h->worker_pid == si->si_pid);
885 assert(h->worker_event_source);
886 assert(h->worker_stdout_fd >= 0);
887
888 (void) hashmap_remove_value(h->manager->homes_by_worker_pid, PID_TO_PTR(h->worker_pid), h);
889
890 h->worker_pid = 0;
cf536638 891 h->worker_event_source = sd_event_source_disable_unref(h->worker_event_source);
70a5db58
LP
892
893 if (si->si_code != CLD_EXITED) {
894 assert(IN_SET(si->si_code, CLD_KILLED, CLD_DUMPED));
895 ret = log_debug_errno(SYNTHETIC_ERRNO(EPROTO), "Worker process died abnormally with signal %s.", signal_to_string(si->si_status));
896 } else if (si->si_status != EXIT_SUCCESS) {
897 /* If we received an error code via sd_notify(), use it */
898 if (h->worker_error_code != 0)
899 ret = log_debug_errno(h->worker_error_code, "Worker reported error code %s.", errno_to_name(h->worker_error_code));
900 else
901 ret = log_debug_errno(SYNTHETIC_ERRNO(EPROTO), "Worker exited with exit code %i.", si->si_status);
902 } else
903 ret = home_parse_worker_stdout(TAKE_FD(h->worker_stdout_fd), &hr);
904
905 h->worker_stdout_fd = safe_close(h->worker_stdout_fd);
906
907 switch (h->state) {
908
909 case HOME_FIXATING:
910 case HOME_FIXATING_FOR_ACTIVATION:
911 case HOME_FIXATING_FOR_ACQUIRE:
912 home_fixate_finish(h, ret, hr);
913 break;
914
915 case HOME_ACTIVATING:
916 case HOME_ACTIVATING_FOR_ACQUIRE:
917 home_activate_finish(h, ret, hr);
918 break;
919
920 case HOME_DEACTIVATING:
921 home_deactivate_finish(h, ret, hr);
922 break;
923
924 case HOME_LOCKING:
925 home_locking_finish(h, ret, hr);
926 break;
927
928 case HOME_UNLOCKING:
929 case HOME_UNLOCKING_FOR_ACQUIRE:
930 home_unlocking_finish(h, ret, hr);
931 break;
932
933 case HOME_CREATING:
934 home_create_finish(h, ret, hr);
935 break;
936
937 case HOME_REMOVING:
938 home_remove_finish(h, ret, hr);
939 break;
940
941 case HOME_UPDATING:
942 case HOME_UPDATING_WHILE_ACTIVE:
943 case HOME_RESIZING:
944 case HOME_RESIZING_WHILE_ACTIVE:
945 case HOME_PASSWD:
946 case HOME_PASSWD_WHILE_ACTIVE:
947 home_change_finish(h, ret, hr);
948 break;
949
950 case HOME_AUTHENTICATING:
951 case HOME_AUTHENTICATING_WHILE_ACTIVE:
952 case HOME_AUTHENTICATING_FOR_ACQUIRE:
953 home_authenticating_finish(h, ret, hr);
954 break;
955
956 default:
957 assert_not_reached("Unexpected state after worker exited");
958 }
959
960 return 0;
961}
962
963static int home_start_work(Home *h, const char *verb, UserRecord *hr, UserRecord *secret) {
964 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
965 _cleanup_(erase_and_freep) char *formatted = NULL;
966 _cleanup_close_ int stdin_fd = -1, stdout_fd = -1;
967 pid_t pid = 0;
968 int r;
969
970 assert(h);
971 assert(verb);
972 assert(hr);
973
974 if (h->worker_pid != 0)
975 return -EBUSY;
976
977 assert(h->worker_stdout_fd < 0);
978 assert(!h->worker_event_source);
979
980 v = json_variant_ref(hr->json);
981
982 if (secret) {
983 JsonVariant *sub = NULL;
984
985 sub = json_variant_by_key(secret->json, "secret");
986 if (!sub)
987 return -ENOKEY;
988
989 r = json_variant_set_field(&v, "secret", sub);
990 if (r < 0)
991 return r;
992 }
993
994 r = json_variant_format(v, 0, &formatted);
995 if (r < 0)
996 return r;
997
998 stdin_fd = acquire_data_fd(formatted, strlen(formatted), 0);
999 if (stdin_fd < 0)
1000 return stdin_fd;
1001
1002 log_debug("Sending to worker: %s", formatted);
1003
1004 stdout_fd = memfd_create("homework-stdout", MFD_CLOEXEC);
1005 if (stdout_fd < 0)
1006 return -errno;
1007
1008 r = safe_fork_full("(sd-homework)",
1009 (int[]) { stdin_fd, stdout_fd }, 2,
7e0ed2e9 1010 FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_LOG|FORK_REOPEN_LOG, &pid);
70a5db58
LP
1011 if (r < 0)
1012 return r;
1013 if (r == 0) {
cc9886bc 1014 const char *homework, *suffix, *unix_path;
c06bcd4d 1015
70a5db58
LP
1016 /* Child */
1017
cc9886bc
LP
1018 suffix = getenv("SYSTEMD_HOME_DEBUG_SUFFIX");
1019 if (suffix)
1020 unix_path = strjoina("/run/systemd/home/notify.", suffix);
1021 else
1022 unix_path = "/run/systemd/home/notify";
1023
1024 if (setenv("NOTIFY_SOCKET", unix_path, 1) < 0) {
70a5db58
LP
1025 log_error_errno(errno, "Failed to set $NOTIFY_SOCKET: %m");
1026 _exit(EXIT_FAILURE);
1027 }
1028
c76dd733
LP
1029 if (h->manager->default_storage >= 0)
1030 if (setenv("SYSTEMD_HOME_DEFAULT_STORAGE", user_storage_to_string(h->manager->default_storage), 1) < 0) {
1031 log_error_errno(errno, "Failed to set $SYSTEMD_HOME_DEFAULT_STORAGE: %m");
1032 _exit(EXIT_FAILURE);
1033 }
1034
1035 if (h->manager->default_file_system_type)
1036 if (setenv("SYSTEMD_HOME_DEFAULT_FILE_SYSTEM_TYPE", h->manager->default_file_system_type, 1) < 0) {
1037 log_error_errno(errno, "Failed to set $SYSTEMD_HOME_DEFAULT_FILE_SYSTEM_TYPE: %m");
1038 _exit(EXIT_FAILURE);
1039 }
1040
d7548908
YW
1041 r = setenv_systemd_exec_pid(true);
1042 if (r < 0)
1043 log_warning_errno(r, "Failed to update $SYSTEMD_EXEC_PID, ignoring: %m");
1044
70a5db58
LP
1045 r = rearrange_stdio(stdin_fd, stdout_fd, STDERR_FILENO);
1046 if (r < 0) {
1047 log_error_errno(r, "Failed to rearrange stdin/stdout/stderr: %m");
1048 _exit(EXIT_FAILURE);
1049 }
1050
1051 stdin_fd = stdout_fd = -1; /* have been invalidated by rearrange_stdio() */
1052
c06bcd4d
LP
1053 /* Allow overriding the homework path via an environment variable, to make debugging
1054 * easier. */
1055 homework = getenv("SYSTEMD_HOMEWORK_PATH") ?: SYSTEMD_HOMEWORK_PATH;
1056
1057 execl(homework, homework, verb, NULL);
43269733 1058 log_error_errno(errno, "Failed to invoke %s: %m", homework);
70a5db58
LP
1059 _exit(EXIT_FAILURE);
1060 }
1061
1062 r = sd_event_add_child(h->manager->event, &h->worker_event_source, pid, WEXITED, home_on_worker_process, h);
1063 if (r < 0)
1064 return r;
1065
1066 (void) sd_event_source_set_description(h->worker_event_source, "worker");
1067
1068 r = hashmap_put(h->manager->homes_by_worker_pid, PID_TO_PTR(pid), h);
1069 if (r < 0) {
cf536638 1070 h->worker_event_source = sd_event_source_disable_unref(h->worker_event_source);
70a5db58
LP
1071 return r;
1072 }
1073
1074 h->worker_stdout_fd = TAKE_FD(stdout_fd);
1075 h->worker_pid = pid;
1076 h->worker_error_code = 0;
1077
1078 return 0;
1079}
1080
1081static int home_ratelimit(Home *h, sd_bus_error *error) {
1082 int r, ret;
1083
1084 assert(h);
1085
1086 ret = user_record_ratelimit(h->record);
1087 if (ret < 0)
1088 return ret;
1089
1090 if (h->state != HOME_UNFIXATED) {
1091 r = home_save_record(h);
1092 if (r < 0)
1093 log_warning_errno(r, "Failed to save updated record, ignoring: %m");
1094 }
1095
1096 if (ret == 0) {
1097 char buf[FORMAT_TIMESPAN_MAX];
1098 usec_t t, n;
1099
1100 n = now(CLOCK_REALTIME);
1101 t = user_record_ratelimit_next_try(h->record);
1102
1103 if (t != USEC_INFINITY && t > n)
1104 return sd_bus_error_setf(error, BUS_ERROR_AUTHENTICATION_LIMIT_HIT, "Too many login attempts, please try again in %s!",
1105 format_timespan(buf, sizeof(buf), t - n, USEC_PER_SEC));
1106
1107 return sd_bus_error_setf(error, BUS_ERROR_AUTHENTICATION_LIMIT_HIT, "Too many login attempts, please try again later.");
1108 }
1109
1110 return 0;
1111}
1112
1113static int home_fixate_internal(
1114 Home *h,
1115 UserRecord *secret,
1116 HomeState for_state,
1117 sd_bus_error *error) {
1118
1119 int r;
1120
1121 assert(h);
1122 assert(IN_SET(for_state, HOME_FIXATING, HOME_FIXATING_FOR_ACTIVATION, HOME_FIXATING_FOR_ACQUIRE));
1123
1124 r = home_start_work(h, "inspect", h->record, secret);
1125 if (r < 0)
1126 return r;
1127
3d3d6e10 1128 if (IN_SET(for_state, HOME_FIXATING_FOR_ACTIVATION, HOME_FIXATING_FOR_ACQUIRE)) {
70a5db58
LP
1129 /* Remember the secret data, since we need it for the activation again, later on. */
1130 user_record_unref(h->secret);
1131 h->secret = user_record_ref(secret);
1132 }
1133
1134 home_set_state(h, for_state);
1135 return 0;
1136}
1137
1138int home_fixate(Home *h, UserRecord *secret, sd_bus_error *error) {
1139 int r;
1140
1141 assert(h);
1142
1143 switch (home_get_state(h)) {
1144 case HOME_ABSENT:
1145 return sd_bus_error_setf(error, BUS_ERROR_HOME_ABSENT, "Home %s is currently missing or not plugged in.", h->user_name);
1146 case HOME_INACTIVE:
9be99f81 1147 case HOME_DIRTY:
70a5db58
LP
1148 case HOME_ACTIVE:
1149 case HOME_LOCKED:
1150 return sd_bus_error_setf(error, BUS_ERROR_HOME_ALREADY_FIXATED, "Home %s is already fixated.", h->user_name);
1151 case HOME_UNFIXATED:
1152 break;
1153 default:
1154 return sd_bus_error_setf(error, BUS_ERROR_HOME_BUSY, "An operation on home %s is currently being executed.", h->user_name);
1155 }
1156
1157 r = home_ratelimit(h, error);
1158 if (r < 0)
1159 return r;
1160
1161 return home_fixate_internal(h, secret, HOME_FIXATING, error);
1162}
1163
1164static int home_activate_internal(Home *h, UserRecord *secret, HomeState for_state, sd_bus_error *error) {
1165 int r;
1166
1167 assert(h);
1168 assert(IN_SET(for_state, HOME_ACTIVATING, HOME_ACTIVATING_FOR_ACQUIRE));
1169
1170 r = home_start_work(h, "activate", h->record, secret);
1171 if (r < 0)
1172 return r;
1173
1174 home_set_state(h, for_state);
1175 return 0;
1176}
1177
1178int home_activate(Home *h, UserRecord *secret, sd_bus_error *error) {
1179 int r;
1180
1181 assert(h);
1182
1183 switch (home_get_state(h)) {
1184 case HOME_UNFIXATED:
1185 return home_fixate_internal(h, secret, HOME_FIXATING_FOR_ACTIVATION, error);
1186 case HOME_ABSENT:
1187 return sd_bus_error_setf(error, BUS_ERROR_HOME_ABSENT, "Home %s is currently missing or not plugged in.", h->user_name);
1188 case HOME_ACTIVE:
1189 return sd_bus_error_setf(error, BUS_ERROR_HOME_ALREADY_ACTIVE, "Home %s is already active.", h->user_name);
1190 case HOME_LOCKED:
1191 return sd_bus_error_setf(error, BUS_ERROR_HOME_LOCKED, "Home %s is currently locked.", h->user_name);
1192 case HOME_INACTIVE:
9be99f81 1193 case HOME_DIRTY:
70a5db58
LP
1194 break;
1195 default:
1196 return sd_bus_error_setf(error, BUS_ERROR_HOME_BUSY, "An operation on home %s is currently being executed.", h->user_name);
1197 }
1198
1199 r = home_ratelimit(h, error);
1200 if (r < 0)
1201 return r;
1202
1203 return home_activate_internal(h, secret, HOME_ACTIVATING, error);
1204}
1205
1206static int home_authenticate_internal(Home *h, UserRecord *secret, HomeState for_state, sd_bus_error *error) {
1207 int r;
1208
1209 assert(h);
1210 assert(IN_SET(for_state, HOME_AUTHENTICATING, HOME_AUTHENTICATING_WHILE_ACTIVE, HOME_AUTHENTICATING_FOR_ACQUIRE));
1211
1212 r = home_start_work(h, "inspect", h->record, secret);
1213 if (r < 0)
1214 return r;
1215
1216 home_set_state(h, for_state);
1217 return 0;
1218}
1219
1220int home_authenticate(Home *h, UserRecord *secret, sd_bus_error *error) {
1221 HomeState state;
1222 int r;
1223
1224 assert(h);
1225
1226 state = home_get_state(h);
1227 switch (state) {
1228 case HOME_ABSENT:
1229 return sd_bus_error_setf(error, BUS_ERROR_HOME_ABSENT, "Home %s is currently missing or not plugged in.", h->user_name);
1230 case HOME_LOCKED:
1231 return sd_bus_error_setf(error, BUS_ERROR_HOME_LOCKED, "Home %s is currently locked.", h->user_name);
1232 case HOME_UNFIXATED:
1233 case HOME_INACTIVE:
9be99f81 1234 case HOME_DIRTY:
70a5db58
LP
1235 case HOME_ACTIVE:
1236 break;
1237 default:
1238 return sd_bus_error_setf(error, BUS_ERROR_HOME_BUSY, "An operation on home %s is currently being executed.", h->user_name);
1239 }
1240
1241 r = home_ratelimit(h, error);
1242 if (r < 0)
1243 return r;
1244
1245 return home_authenticate_internal(h, secret, state == HOME_ACTIVE ? HOME_AUTHENTICATING_WHILE_ACTIVE : HOME_AUTHENTICATING, error);
1246}
1247
1248static int home_deactivate_internal(Home *h, bool force, sd_bus_error *error) {
1249 int r;
1250
1251 assert(h);
1252
1253 r = home_start_work(h, force ? "deactivate-force" : "deactivate", h->record, NULL);
1254 if (r < 0)
1255 return r;
1256
1257 home_set_state(h, HOME_DEACTIVATING);
1258 return 0;
1259}
1260
1261int home_deactivate(Home *h, bool force, sd_bus_error *error) {
1262 assert(h);
1263
1264 switch (home_get_state(h)) {
1265 case HOME_UNFIXATED:
1266 case HOME_ABSENT:
1267 case HOME_INACTIVE:
9be99f81 1268 case HOME_DIRTY:
70a5db58
LP
1269 return sd_bus_error_setf(error, BUS_ERROR_HOME_NOT_ACTIVE, "Home %s not active.", h->user_name);
1270 case HOME_LOCKED:
1271 return sd_bus_error_setf(error, BUS_ERROR_HOME_LOCKED, "Home %s is currently locked.", h->user_name);
1272 case HOME_ACTIVE:
1273 break;
1274 default:
1275 return sd_bus_error_setf(error, BUS_ERROR_HOME_BUSY, "An operation on home %s is currently being executed.", h->user_name);
1276 }
1277
1278 return home_deactivate_internal(h, force, error);
1279}
1280
1281int home_create(Home *h, UserRecord *secret, sd_bus_error *error) {
1282 int r;
1283
1284 assert(h);
1285
1286 switch (home_get_state(h)) {
f9d525ae
LP
1287 case HOME_INACTIVE: {
1288 int t;
1289
70a5db58
LP
1290 if (h->record->storage < 0)
1291 break; /* if no storage is defined we don't know what precisely to look for, hence
1292 * HOME_INACTIVE is OK in that case too. */
1293
f9d525ae
LP
1294 t = user_record_test_image_path(h->record);
1295 if (IN_SET(t, USER_TEST_MAYBE, USER_TEST_UNDEFINED))
70a5db58
LP
1296 break; /* And if the image path test isn't conclusive, let's also go on */
1297
f9d525ae
LP
1298 if (IN_SET(t, -EBADFD, -ENOTDIR))
1299 return sd_bus_error_setf(error, BUS_ERROR_HOME_EXISTS, "Selected home image of user %s already exists or has wrong inode type.", h->user_name);
1300
1301 return sd_bus_error_setf(error, BUS_ERROR_HOME_EXISTS, "Selected home image of user %s already exists.", h->user_name);
1302 }
70a5db58 1303 case HOME_UNFIXATED:
9be99f81 1304 case HOME_DIRTY:
70a5db58
LP
1305 return sd_bus_error_setf(error, BUS_ERROR_HOME_EXISTS, "Home of user %s already exists.", h->user_name);
1306 case HOME_ABSENT:
1307 break;
1308 case HOME_ACTIVE:
1309 case HOME_LOCKED:
1310 default:
1311 return sd_bus_error_setf(error, BUS_ERROR_HOME_BUSY, "Home %s is currently being used, or an operation on home %s is currently being executed.", h->user_name, h->user_name);
1312 }
1313
1314 if (h->record->enforce_password_policy == false)
1315 log_debug("Password quality check turned off for account, skipping.");
1316 else {
679badd7 1317 r = user_record_quality_check_password(h->record, secret, error);
70a5db58
LP
1318 if (r < 0)
1319 return r;
1320 }
1321
1322 r = home_start_work(h, "create", h->record, secret);
1323 if (r < 0)
1324 return r;
1325
1326 home_set_state(h, HOME_CREATING);
1327 return 0;
1328}
1329
1330int home_remove(Home *h, sd_bus_error *error) {
1331 HomeState state;
1332 int r;
1333
1334 assert(h);
1335
1336 state = home_get_state(h);
1337 switch (state) {
1338 case HOME_ABSENT: /* If the home directory is absent, then this is just like unregistering */
1339 return home_unregister(h, error);
1340 case HOME_LOCKED:
1341 return sd_bus_error_setf(error, BUS_ERROR_HOME_LOCKED, "Home %s is currently locked.", h->user_name);
1342 case HOME_UNFIXATED:
1343 case HOME_INACTIVE:
9be99f81 1344 case HOME_DIRTY:
70a5db58
LP
1345 break;
1346 case HOME_ACTIVE:
1347 default:
1348 return sd_bus_error_setf(error, BUS_ERROR_HOME_BUSY, "Home %s is currently being used, or an operation on home %s is currently being executed.", h->user_name, h->user_name);
1349 }
1350
1351 r = home_start_work(h, "remove", h->record, NULL);
1352 if (r < 0)
1353 return r;
1354
1355 home_set_state(h, HOME_REMOVING);
1356 return 0;
1357}
1358
1359static int user_record_extend_with_binding(UserRecord *hr, UserRecord *with_binding, UserRecordLoadFlags flags, UserRecord **ret) {
1360 _cleanup_(json_variant_unrefp) JsonVariant *v = NULL;
1361 _cleanup_(user_record_unrefp) UserRecord *nr = NULL;
1362 JsonVariant *binding;
1363 int r;
1364
1365 assert(hr);
1366 assert(with_binding);
1367 assert(ret);
1368
1369 assert_se(v = json_variant_ref(hr->json));
1370
1371 binding = json_variant_by_key(with_binding->json, "binding");
1372 if (binding) {
1373 r = json_variant_set_field(&v, "binding", binding);
1374 if (r < 0)
1375 return r;
1376 }
1377
1378 nr = user_record_new();
1379 if (!nr)
1380 return -ENOMEM;
1381
1382 r = user_record_load(nr, v, flags);
1383 if (r < 0)
1384 return r;
1385
1386 *ret = TAKE_PTR(nr);
1387 return 0;
1388}
1389
7b78db28
LP
1390static int home_update_internal(
1391 Home *h,
1392 const char *verb,
1393 UserRecord *hr,
1394 UserRecord *secret,
1395 sd_bus_error *error) {
1396
70a5db58
LP
1397 _cleanup_(user_record_unrefp) UserRecord *new_hr = NULL, *saved_secret = NULL, *signed_hr = NULL;
1398 int r, c;
1399
1400 assert(h);
1401 assert(verb);
1402 assert(hr);
1403
1404 if (!user_record_compatible(hr, h->record))
1405 return sd_bus_error_setf(error, BUS_ERROR_HOME_RECORD_MISMATCH, "Updated user record is not compatible with existing one.");
1406 c = user_record_compare_last_change(hr, h->record); /* refuse downgrades */
1407 if (c < 0)
1408 return sd_bus_error_setf(error, BUS_ERROR_HOME_RECORD_DOWNGRADE, "Refusing to update to older home record.");
1409
1410 if (!secret && FLAGS_SET(hr->mask, USER_RECORD_SECRET)) {
1411 r = user_record_clone(hr, USER_RECORD_EXTRACT_SECRET, &saved_secret);
1412 if (r < 0)
1413 return r;
1414
1415 secret = saved_secret;
1416 }
1417
1418 r = manager_verify_user_record(h->manager, hr);
1419 switch (r) {
1420
1421 case USER_RECORD_UNSIGNED:
1422 if (h->signed_locally <= 0) /* If the existing record is not owned by us, don't accept an
1423 * unsigned new record. i.e. only implicitly sign new records
1424 * that where previously signed by us too. */
1425 return sd_bus_error_setf(error, BUS_ERROR_HOME_RECORD_SIGNED, "Home %s is signed and cannot be modified locally.", h->user_name);
1426
1427 /* The updated record is not signed, then do so now */
1428 r = manager_sign_user_record(h->manager, hr, &signed_hr, error);
1429 if (r < 0)
1430 return r;
1431
1432 hr = signed_hr;
1433 break;
1434
1435 case USER_RECORD_SIGNED_EXCLUSIVE:
1436 case USER_RECORD_SIGNED:
1437 case USER_RECORD_FOREIGN:
1438 /* Has already been signed. Great! */
1439 break;
1440
1441 case -ENOKEY:
1442 default:
1443 return r;
1444 }
1445
1446 r = user_record_extend_with_binding(hr, h->record, USER_RECORD_LOAD_MASK_SECRET, &new_hr);
1447 if (r < 0)
1448 return r;
1449
1450 if (c == 0) {
1451 /* different payload but same lastChangeUSec field? That's not cool! */
1452
1453 r = user_record_masked_equal(new_hr, h->record, USER_RECORD_REGULAR|USER_RECORD_PRIVILEGED|USER_RECORD_PER_MACHINE);
1454 if (r < 0)
1455 return r;
1456 if (r == 0)
1457 return sd_bus_error_setf(error, BUS_ERROR_HOME_RECORD_MISMATCH, "Home record different but timestamp remained the same, refusing.");
1458 }
1459
1460 r = home_start_work(h, verb, new_hr, secret);
1461 if (r < 0)
1462 return r;
1463
1464 return 0;
1465}
1466
1467int home_update(Home *h, UserRecord *hr, sd_bus_error *error) {
1468 HomeState state;
1469 int r;
1470
1471 assert(h);
1472 assert(hr);
1473
1474 state = home_get_state(h);
1475 switch (state) {
1476 case HOME_UNFIXATED:
1477 return sd_bus_error_setf(error, BUS_ERROR_HOME_UNFIXATED, "Home %s has not been fixated yet.", h->user_name);
1478 case HOME_ABSENT:
1479 return sd_bus_error_setf(error, BUS_ERROR_HOME_ABSENT, "Home %s is currently missing or not plugged in.", h->user_name);
1480 case HOME_LOCKED:
1481 return sd_bus_error_setf(error, BUS_ERROR_HOME_LOCKED, "Home %s is currently locked.", h->user_name);
1482 case HOME_INACTIVE:
9be99f81 1483 case HOME_DIRTY:
70a5db58
LP
1484 case HOME_ACTIVE:
1485 break;
1486 default:
1487 return sd_bus_error_setf(error, BUS_ERROR_HOME_BUSY, "An operation on home %s is currently being executed.", h->user_name);
1488 }
1489
1490 r = home_ratelimit(h, error);
1491 if (r < 0)
1492 return r;
1493
1494 r = home_update_internal(h, "update", hr, NULL, error);
1495 if (r < 0)
1496 return r;
1497
1498 home_set_state(h, state == HOME_ACTIVE ? HOME_UPDATING_WHILE_ACTIVE : HOME_UPDATING);
1499 return 0;
1500}
1501
1502int home_resize(Home *h, uint64_t disk_size, UserRecord *secret, sd_bus_error *error) {
1503 _cleanup_(user_record_unrefp) UserRecord *c = NULL;
1504 HomeState state;
1505 int r;
1506
1507 assert(h);
1508
1509 state = home_get_state(h);
1510 switch (state) {
1511 case HOME_UNFIXATED:
1512 return sd_bus_error_setf(error, BUS_ERROR_HOME_UNFIXATED, "Home %s has not been fixated yet.", h->user_name);
1513 case HOME_ABSENT:
1514 return sd_bus_error_setf(error, BUS_ERROR_HOME_ABSENT, "Home %s is currently missing or not plugged in.", h->user_name);
1515 case HOME_LOCKED:
1516 return sd_bus_error_setf(error, BUS_ERROR_HOME_LOCKED, "Home %s is currently locked.", h->user_name);
1517 case HOME_INACTIVE:
9be99f81 1518 case HOME_DIRTY:
70a5db58
LP
1519 case HOME_ACTIVE:
1520 break;
1521 default:
1522 return sd_bus_error_setf(error, BUS_ERROR_HOME_BUSY, "An operation on home %s is currently being executed.", h->user_name);
1523 }
1524
1525 r = home_ratelimit(h, error);
1526 if (r < 0)
1527 return r;
1528
1529 if (disk_size == UINT64_MAX || disk_size == h->record->disk_size) {
1530 if (h->record->disk_size == UINT64_MAX)
80ace4f2 1531 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "No disk size to resize to specified.");
70a5db58
LP
1532
1533 c = user_record_ref(h->record); /* Shortcut if size is unspecified or matches the record */
1534 } else {
1535 _cleanup_(user_record_unrefp) UserRecord *signed_c = NULL;
1536
1537 if (h->signed_locally <= 0) /* Don't allow changing of records not signed only by us */
1538 return sd_bus_error_setf(error, BUS_ERROR_HOME_RECORD_SIGNED, "Home %s is signed and cannot be modified locally.", h->user_name);
1539
1540 r = user_record_clone(h->record, USER_RECORD_LOAD_REFUSE_SECRET, &c);
1541 if (r < 0)
1542 return r;
1543
1544 r = user_record_set_disk_size(c, disk_size);
1545 if (r == -ERANGE)
1546 return sd_bus_error_setf(error, BUS_ERROR_BAD_HOME_SIZE, "Requested size for home %s out of acceptable range.", h->user_name);
1547 if (r < 0)
1548 return r;
1549
1550 r = user_record_update_last_changed(c, false);
1551 if (r == -ECHRNG)
1552 return sd_bus_error_setf(error, BUS_ERROR_HOME_RECORD_MISMATCH, "Record last change time of %s is newer than current time, cannot update.", h->user_name);
1553 if (r < 0)
1554 return r;
1555
1556 r = manager_sign_user_record(h->manager, c, &signed_c, error);
1557 if (r < 0)
1558 return r;
1559
1560 user_record_unref(c);
1561 c = TAKE_PTR(signed_c);
1562 }
1563
1564 r = home_update_internal(h, "resize", c, secret, error);
1565 if (r < 0)
1566 return r;
1567
1568 home_set_state(h, state == HOME_ACTIVE ? HOME_RESIZING_WHILE_ACTIVE : HOME_RESIZING);
1569 return 0;
1570}
1571
1572static int home_may_change_password(
1573 Home *h,
1574 sd_bus_error *error) {
1575
1576 int r;
1577
1578 assert(h);
1579
1580 r = user_record_test_password_change_required(h->record);
3e0b5486 1581 if (IN_SET(r, -EKEYREVOKED, -EOWNERDEAD, -EKEYEXPIRED, -ESTALE))
86b52a39 1582 return 0; /* expired in some form, but changing is allowed */
70a5db58
LP
1583 if (IN_SET(r, -EKEYREJECTED, -EROFS))
1584 return sd_bus_error_setf(error, SD_BUS_ERROR_ACCESS_DENIED, "Expiration settings of account %s do not allow changing of password.", h->user_name);
1585 if (r < 0)
1586 return log_error_errno(r, "Failed to test password expiry: %m");
1587
1588 return 0; /* not expired */
1589}
1590
1591int home_passwd(Home *h,
1592 UserRecord *new_secret,
1593 UserRecord *old_secret,
1594 sd_bus_error *error) {
1595
1596 _cleanup_(user_record_unrefp) UserRecord *c = NULL, *merged_secret = NULL, *signed_c = NULL;
1597 HomeState state;
1598 int r;
1599
1600 assert(h);
1601
1602 if (h->signed_locally <= 0) /* Don't allow changing of records not signed only by us */
1603 return sd_bus_error_setf(error, BUS_ERROR_HOME_RECORD_SIGNED, "Home %s is signed and cannot be modified locally.", h->user_name);
1604
1605 state = home_get_state(h);
1606 switch (state) {
1607 case HOME_UNFIXATED:
1608 return sd_bus_error_setf(error, BUS_ERROR_HOME_UNFIXATED, "Home %s has not been fixated yet.", h->user_name);
1609 case HOME_ABSENT:
1610 return sd_bus_error_setf(error, BUS_ERROR_HOME_ABSENT, "Home %s is currently missing or not plugged in.", h->user_name);
1611 case HOME_LOCKED:
1612 return sd_bus_error_setf(error, BUS_ERROR_HOME_LOCKED, "Home %s is currently locked.", h->user_name);
1613 case HOME_INACTIVE:
9be99f81 1614 case HOME_DIRTY:
70a5db58
LP
1615 case HOME_ACTIVE:
1616 break;
1617 default:
1618 return sd_bus_error_setf(error, BUS_ERROR_HOME_BUSY, "An operation on home %s is currently being executed.", h->user_name);
1619 }
1620
1621 r = home_ratelimit(h, error);
1622 if (r < 0)
1623 return r;
1624
1625 r = home_may_change_password(h, error);
1626 if (r < 0)
1627 return r;
1628
1629 r = user_record_clone(h->record, USER_RECORD_LOAD_REFUSE_SECRET, &c);
1630 if (r < 0)
1631 return r;
1632
1633 merged_secret = user_record_new();
1634 if (!merged_secret)
1635 return -ENOMEM;
1636
1637 r = user_record_merge_secret(merged_secret, old_secret);
1638 if (r < 0)
1639 return r;
1640
1641 r = user_record_merge_secret(merged_secret, new_secret);
1642 if (r < 0)
1643 return r;
1644
1645 if (!strv_isempty(new_secret->password)) {
1646 /* Update the password only if one is specified, otherwise let's just reuse the old password
1647 * data. This is useful as a way to propagate updated user records into the LUKS backends
1648 * properly. */
1649
1650 r = user_record_make_hashed_password(c, new_secret->password, /* extend = */ false);
1651 if (r < 0)
1652 return r;
1653
1654 r = user_record_set_password_change_now(c, -1 /* remove */);
1655 if (r < 0)
1656 return r;
1657 }
1658
1659 r = user_record_update_last_changed(c, true);
1660 if (r == -ECHRNG)
1661 return sd_bus_error_setf(error, BUS_ERROR_HOME_RECORD_MISMATCH, "Record last change time of %s is newer than current time, cannot update.", h->user_name);
1662 if (r < 0)
1663 return r;
1664
1665 r = manager_sign_user_record(h->manager, c, &signed_c, error);
1666 if (r < 0)
1667 return r;
1668
1669 if (c->enforce_password_policy == false)
1670 log_debug("Password quality check turned off for account, skipping.");
1671 else {
679badd7 1672 r = user_record_quality_check_password(c, merged_secret, error);
70a5db58
LP
1673 if (r < 0)
1674 return r;
1675 }
1676
1677 r = home_update_internal(h, "passwd", signed_c, merged_secret, error);
1678 if (r < 0)
1679 return r;
1680
1681 home_set_state(h, state == HOME_ACTIVE ? HOME_PASSWD_WHILE_ACTIVE : HOME_PASSWD);
1682 return 0;
1683}
1684
1685int home_unregister(Home *h, sd_bus_error *error) {
1686 int r;
1687
1688 assert(h);
1689
1690 switch (home_get_state(h)) {
1691 case HOME_UNFIXATED:
1692 return sd_bus_error_setf(error, BUS_ERROR_HOME_UNFIXATED, "Home %s is not registered.", h->user_name);
1693 case HOME_LOCKED:
1694 return sd_bus_error_setf(error, BUS_ERROR_HOME_LOCKED, "Home %s is currently locked.", h->user_name);
1695 case HOME_ABSENT:
1696 case HOME_INACTIVE:
9be99f81 1697 case HOME_DIRTY:
70a5db58
LP
1698 break;
1699 case HOME_ACTIVE:
1700 default:
1701 return sd_bus_error_setf(error, BUS_ERROR_HOME_BUSY, "Home %s is currently being used, or an operation on home %s is currently being executed.", h->user_name, h->user_name);
1702 }
1703
1704 r = home_unlink_record(h);
1705 if (r < 0)
1706 return r;
1707
1708 /* And destroy the whole entry. The caller needs to be prepared for that. */
1709 h = home_free(h);
1710 return 1;
1711}
1712
1713int home_lock(Home *h, sd_bus_error *error) {
1714 int r;
1715
1716 assert(h);
1717
1718 switch (home_get_state(h)) {
1719 case HOME_UNFIXATED:
1720 case HOME_ABSENT:
1721 case HOME_INACTIVE:
9be99f81 1722 case HOME_DIRTY:
70a5db58
LP
1723 return sd_bus_error_setf(error, BUS_ERROR_HOME_NOT_ACTIVE, "Home %s is not active.", h->user_name);
1724 case HOME_LOCKED:
1725 return sd_bus_error_setf(error, BUS_ERROR_HOME_LOCKED, "Home %s is already locked.", h->user_name);
1726 case HOME_ACTIVE:
1727 break;
1728 default:
1729 return sd_bus_error_setf(error, BUS_ERROR_HOME_BUSY, "An operation on home %s is currently being executed.", h->user_name);
1730 }
1731
1732 r = home_start_work(h, "lock", h->record, NULL);
1733 if (r < 0)
1734 return r;
1735
1736 home_set_state(h, HOME_LOCKING);
1737 return 0;
1738}
1739
1740static int home_unlock_internal(Home *h, UserRecord *secret, HomeState for_state, sd_bus_error *error) {
1741 int r;
1742
1743 assert(h);
1744 assert(IN_SET(for_state, HOME_UNLOCKING, HOME_UNLOCKING_FOR_ACQUIRE));
1745
1746 r = home_start_work(h, "unlock", h->record, secret);
1747 if (r < 0)
1748 return r;
1749
1750 home_set_state(h, for_state);
1751 return 0;
1752}
1753
1754int home_unlock(Home *h, UserRecord *secret, sd_bus_error *error) {
1755 int r;
1756 assert(h);
1757
1758 r = home_ratelimit(h, error);
1759 if (r < 0)
1760 return r;
1761
1762 switch (home_get_state(h)) {
1763 case HOME_UNFIXATED:
1764 case HOME_ABSENT:
1765 case HOME_INACTIVE:
1766 case HOME_ACTIVE:
9be99f81 1767 case HOME_DIRTY:
70a5db58
LP
1768 return sd_bus_error_setf(error, BUS_ERROR_HOME_NOT_LOCKED, "Home %s is not locked.", h->user_name);
1769 case HOME_LOCKED:
1770 break;
1771 default:
1772 return sd_bus_error_setf(error, BUS_ERROR_HOME_BUSY, "An operation on home %s is currently being executed.", h->user_name);
1773 }
1774
1775 return home_unlock_internal(h, secret, HOME_UNLOCKING, error);
1776}
1777
1778HomeState home_get_state(Home *h) {
9be99f81 1779 int r;
70a5db58
LP
1780 assert(h);
1781
1782 /* When the state field is initialized, it counts. */
1783 if (h->state >= 0)
1784 return h->state;
1785
1786 /* Otherwise, let's see if the home directory is mounted. If so, we assume for sure the home
1787 * directory is active */
1788 if (user_record_test_home_directory(h->record) == USER_TEST_MOUNTED)
1789 return HOME_ACTIVE;
1790
1791 /* And if we see the image being gone, we report this as absent */
9be99f81
LP
1792 r = user_record_test_image_path(h->record);
1793 if (r == USER_TEST_ABSENT)
70a5db58 1794 return HOME_ABSENT;
9be99f81
LP
1795 if (r == USER_TEST_DIRTY)
1796 return HOME_DIRTY;
70a5db58
LP
1797
1798 /* And for all other cases we return "inactive". */
1799 return HOME_INACTIVE;
1800}
1801
1802void home_process_notify(Home *h, char **l) {
1803 const char *e;
1804 int error;
1805 int r;
1806
1807 assert(h);
1808
1809 e = strv_env_get(l, "ERRNO");
1810 if (!e) {
1811 log_debug("Got notify message lacking ERRNO= field, ignoring.");
1812 return;
1813 }
1814
1815 r = safe_atoi(e, &error);
1816 if (r < 0) {
162392b7 1817 log_debug_errno(r, "Failed to parse received error number, ignoring: %s", e);
70a5db58
LP
1818 return;
1819 }
1820 if (error <= 0) {
1821 log_debug("Error number is out of range: %i", error);
1822 return;
1823 }
1824
1825 h->worker_error_code = error;
1826}
1827
1828int home_killall(Home *h) {
1829 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1830 _cleanup_free_ char *unit = NULL;
1831 int r;
1832
1833 assert(h);
1834
1835 if (!uid_is_valid(h->uid))
1836 return 0;
1837
1838 assert(h->uid > 0); /* We never should be UID 0 */
1839
1840 /* Let's kill everything matching the specified UID */
7e0ed2e9
SB
1841 r = safe_fork("(sd-killer)",
1842 FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_WAIT|FORK_LOG|FORK_REOPEN_LOG,
1843 NULL);
70a5db58
LP
1844 if (r < 0)
1845 return r;
1846 if (r == 0) {
1847 gid_t gid;
1848
1849 /* Child */
1850
1851 gid = user_record_gid(h->record);
1852 if (setresgid(gid, gid, gid) < 0) {
1853 log_error_errno(errno, "Failed to change GID to " GID_FMT ": %m", gid);
1854 _exit(EXIT_FAILURE);
1855 }
1856
1857 if (setgroups(0, NULL) < 0) {
1858 log_error_errno(errno, "Failed to reset auxiliary groups list: %m");
1859 _exit(EXIT_FAILURE);
1860 }
1861
1862 if (setresuid(h->uid, h->uid, h->uid) < 0) {
1863 log_error_errno(errno, "Failed to change UID to " UID_FMT ": %m", h->uid);
1864 _exit(EXIT_FAILURE);
1865 }
1866
1867 if (kill(-1, SIGKILL) < 0) {
1868 log_error_errno(errno, "Failed to kill all processes of UID " UID_FMT ": %m", h->uid);
1869 _exit(EXIT_FAILURE);
1870 }
1871
1872 _exit(EXIT_SUCCESS);
1873 }
1874
1875 /* Let's also kill everything in the user's slice */
1876 if (asprintf(&unit, "user-" UID_FMT ".slice", h->uid) < 0)
1877 return log_oom();
1878
1879 r = sd_bus_call_method(
1880 h->manager->bus,
1881 "org.freedesktop.systemd1",
1882 "/org/freedesktop/systemd1",
1883 "org.freedesktop.systemd1.Manager",
1884 "KillUnit",
1885 &error,
1886 NULL,
1887 "ssi", unit, "all", SIGKILL);
1888 if (r < 0)
1889 log_full_errno(sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_UNIT) ? LOG_DEBUG : LOG_WARNING,
1890 r, "Failed to kill login processes of user, ignoring: %s", bus_error_message(&error, r));
1891
1892 return 1;
1893}
1894
1895static int home_get_disk_status_luks(
1896 Home *h,
1897 HomeState state,
1898 uint64_t *ret_disk_size,
1899 uint64_t *ret_disk_usage,
1900 uint64_t *ret_disk_free,
1901 uint64_t *ret_disk_ceiling,
1902 uint64_t *ret_disk_floor) {
1903
1904 uint64_t disk_size = UINT64_MAX, disk_usage = UINT64_MAX, disk_free = UINT64_MAX,
1905 disk_ceiling = UINT64_MAX, disk_floor = UINT64_MAX,
1906 stat_used = UINT64_MAX, fs_size = UINT64_MAX, header_size = 0;
1907
1908 struct statfs sfs;
1909 const char *hd;
1910 int r;
1911
1912 assert(h);
1913 assert(ret_disk_size);
1914 assert(ret_disk_usage);
1915 assert(ret_disk_free);
1916 assert(ret_disk_ceiling);
1917
1918 if (state != HOME_ABSENT) {
1919 const char *ip;
1920
1921 ip = user_record_image_path(h->record);
1922 if (ip) {
1923 struct stat st;
1924
1925 if (stat(ip, &st) < 0)
1926 log_debug_errno(errno, "Failed to stat() %s, ignoring: %m", ip);
1927 else if (S_ISREG(st.st_mode)) {
1928 _cleanup_free_ char *parent = NULL;
1929
1930 disk_size = st.st_size;
1931 stat_used = st.st_blocks * 512;
1932
1933 parent = dirname_malloc(ip);
1934 if (!parent)
1935 return log_oom();
1936
1937 if (statfs(parent, &sfs) < 0)
1938 log_debug_errno(errno, "Failed to statfs() %s, ignoring: %m", parent);
1939 else
1940 disk_ceiling = stat_used + sfs.f_bsize * sfs.f_bavail;
1941
1942 } else if (S_ISBLK(st.st_mode)) {
1943 _cleanup_free_ char *szbuf = NULL;
1944 char p[SYS_BLOCK_PATH_MAX("/size")];
1945
1946 /* Let's read the size off sysfs, so that we don't have to open the device */
1947 xsprintf_sys_block_path(p, "/size", st.st_rdev);
1948 r = read_one_line_file(p, &szbuf);
1949 if (r < 0)
1950 log_debug_errno(r, "Failed to read %s, ignoring: %m", p);
1951 else {
1952 uint64_t sz;
1953
1954 r = safe_atou64(szbuf, &sz);
1955 if (r < 0)
1956 log_debug_errno(r, "Failed to parse %s, ignoring: %s", p, szbuf);
1957 else
1958 disk_size = sz * 512;
1959 }
1960 } else
1961 log_debug("Image path is not a block device or regular file, not able to acquire size.");
1962 }
1963 }
1964
1965 if (!HOME_STATE_IS_ACTIVE(state))
1966 goto finish;
1967
1968 hd = user_record_home_directory(h->record);
1969 if (!hd)
1970 goto finish;
1971
1972 if (statfs(hd, &sfs) < 0) {
80ace4f2 1973 log_debug_errno(errno, "Failed to statfs() %s, ignoring: %m", hd);
70a5db58
LP
1974 goto finish;
1975 }
1976
1977 disk_free = sfs.f_bsize * sfs.f_bavail;
1978 fs_size = sfs.f_bsize * sfs.f_blocks;
1979 if (disk_size != UINT64_MAX && disk_size > fs_size)
1980 header_size = disk_size - fs_size;
1981
1982 /* We take a perspective from the user here (as opposed to from the host): the used disk space is the
1983 * difference from the limit and what's free. This makes a difference if sparse mode is not used: in
1984 * that case the image is pre-allocated and thus appears all used from the host PoV but is not used
1985 * up at all yet from the user's PoV.
1986 *
1987 * That said, we use use the stat() reported loopback file size as upper boundary: our footprint can
1988 * never be larger than what we take up on the lowest layers. */
1989
1990 if (disk_size != UINT64_MAX && disk_size > disk_free) {
1991 disk_usage = disk_size - disk_free;
1992
1993 if (stat_used != UINT64_MAX && disk_usage > stat_used)
1994 disk_usage = stat_used;
1995 } else
1996 disk_usage = stat_used;
1997
1998 /* If we have the magic, determine floor preferably by magic */
1999 disk_floor = minimal_size_by_fs_magic(sfs.f_type) + header_size;
2000
2001finish:
2002 /* If we don't know the magic, go by file system name */
2003 if (disk_floor == UINT64_MAX)
2004 disk_floor = minimal_size_by_fs_name(user_record_file_system_type(h->record));
2005
2006 *ret_disk_size = disk_size;
2007 *ret_disk_usage = disk_usage;
2008 *ret_disk_free = disk_free;
2009 *ret_disk_ceiling = disk_ceiling;
2010 *ret_disk_floor = disk_floor;
2011
2012 return 0;
2013}
2014
2015static int home_get_disk_status_directory(
2016 Home *h,
2017 HomeState state,
2018 uint64_t *ret_disk_size,
2019 uint64_t *ret_disk_usage,
2020 uint64_t *ret_disk_free,
2021 uint64_t *ret_disk_ceiling,
2022 uint64_t *ret_disk_floor) {
2023
2024 uint64_t disk_size = UINT64_MAX, disk_usage = UINT64_MAX, disk_free = UINT64_MAX,
2025 disk_ceiling = UINT64_MAX, disk_floor = UINT64_MAX;
2026 struct statfs sfs;
2027 struct dqblk req;
2028 const char *path = NULL;
2029 int r;
2030
2031 assert(ret_disk_size);
2032 assert(ret_disk_usage);
2033 assert(ret_disk_free);
2034 assert(ret_disk_ceiling);
2035 assert(ret_disk_floor);
2036
2037 if (HOME_STATE_IS_ACTIVE(state))
2038 path = user_record_home_directory(h->record);
2039
2040 if (!path) {
2041 if (state == HOME_ABSENT)
2042 goto finish;
2043
2044 path = user_record_image_path(h->record);
2045 }
2046
2047 if (!path)
2048 goto finish;
2049
2050 if (statfs(path, &sfs) < 0)
2051 log_debug_errno(errno, "Failed to statfs() %s, ignoring: %m", path);
2052 else {
2053 disk_free = sfs.f_bsize * sfs.f_bavail;
2054 disk_size = sfs.f_bsize * sfs.f_blocks;
2055
2056 /* We don't initialize disk_usage from statfs() data here, since the device is likely not used
2057 * by us alone, and disk_usage should only reflect our own use. */
2058 }
2059
2060 if (IN_SET(h->record->storage, USER_CLASSIC, USER_DIRECTORY, USER_SUBVOLUME)) {
2061
2062 r = btrfs_is_subvol(path);
2063 if (r < 0)
2064 log_debug_errno(r, "Failed to determine whether %s is a btrfs subvolume: %m", path);
2065 else if (r > 0) {
2066 BtrfsQuotaInfo qi;
2067
2068 r = btrfs_subvol_get_subtree_quota(path, 0, &qi);
2069 if (r < 0)
2070 log_debug_errno(r, "Failed to query btrfs subtree quota, ignoring: %m");
2071 else {
2072 disk_usage = qi.referenced;
2073
2074 if (disk_free != UINT64_MAX) {
2075 disk_ceiling = qi.referenced + disk_free;
2076
2077 if (disk_size != UINT64_MAX && disk_ceiling > disk_size)
2078 disk_ceiling = disk_size;
2079 }
2080
2081 if (qi.referenced_max != UINT64_MAX) {
2082 if (disk_size != UINT64_MAX)
2083 disk_size = MIN(qi.referenced_max, disk_size);
2084 else
2085 disk_size = qi.referenced_max;
2086 }
2087
2088 if (disk_size != UINT64_MAX) {
2089 if (disk_size > disk_usage)
2090 disk_free = disk_size - disk_usage;
2091 else
2092 disk_free = 0;
2093 }
2094 }
2095
2096 goto finish;
2097 }
2098 }
2099
2100 if (IN_SET(h->record->storage, USER_CLASSIC, USER_DIRECTORY, USER_FSCRYPT)) {
2101 r = quotactl_path(QCMD_FIXED(Q_GETQUOTA, USRQUOTA), path, h->uid, &req);
2102 if (r < 0) {
2103 if (ERRNO_IS_NOT_SUPPORTED(r)) {
2104 log_debug_errno(r, "No UID quota support on %s.", path);
2105 goto finish;
2106 }
2107
2108 if (r != -ESRCH) {
2109 log_debug_errno(r, "Failed to query disk quota for UID " UID_FMT ": %m", h->uid);
2110 goto finish;
2111 }
2112
2113 disk_usage = 0; /* No record of this user? then nothing was used */
2114 } else {
2115 if (FLAGS_SET(req.dqb_valid, QIF_SPACE) && disk_free != UINT64_MAX) {
2116 disk_ceiling = req.dqb_curspace + disk_free;
2117
2118 if (disk_size != UINT64_MAX && disk_ceiling > disk_size)
2119 disk_ceiling = disk_size;
2120 }
2121
2122 if (FLAGS_SET(req.dqb_valid, QIF_BLIMITS)) {
2123 uint64_t q;
2124
2125 /* Take the minimum of the quota and the available disk space here */
2126 q = req.dqb_bhardlimit * QIF_DQBLKSIZE;
2127 if (disk_size != UINT64_MAX)
2128 disk_size = MIN(disk_size, q);
2129 else
2130 disk_size = q;
2131 }
2132 if (FLAGS_SET(req.dqb_valid, QIF_SPACE)) {
2133 disk_usage = req.dqb_curspace;
2134
2135 if (disk_size != UINT64_MAX) {
2136 if (disk_size > disk_usage)
2137 disk_free = disk_size - disk_usage;
2138 else
2139 disk_free = 0;
2140 }
2141 }
2142 }
2143 }
2144
2145finish:
2146 *ret_disk_size = disk_size;
2147 *ret_disk_usage = disk_usage;
2148 *ret_disk_free = disk_free;
2149 *ret_disk_ceiling = disk_ceiling;
2150 *ret_disk_floor = disk_floor;
2151
2152 return 0;
2153}
2154
2155int home_augment_status(
2156 Home *h,
2157 UserRecordLoadFlags flags,
2158 UserRecord **ret) {
2159
2160 uint64_t disk_size = UINT64_MAX, disk_usage = UINT64_MAX, disk_free = UINT64_MAX, disk_ceiling = UINT64_MAX, disk_floor = UINT64_MAX;
2161 _cleanup_(json_variant_unrefp) JsonVariant *j = NULL, *v = NULL, *m = NULL, *status = NULL;
2162 _cleanup_(user_record_unrefp) UserRecord *ur = NULL;
2163 char ids[SD_ID128_STRING_MAX];
2164 HomeState state;
2165 sd_id128_t id;
2166 int r;
2167
2168 assert(h);
2169 assert(ret);
2170
2171 /* We are supposed to add this, this can't be on hence. */
2172 assert(!FLAGS_SET(flags, USER_RECORD_STRIP_STATUS));
2173
2174 r = sd_id128_get_machine(&id);
2175 if (r < 0)
2176 return r;
2177
2178 state = home_get_state(h);
2179
2180 switch (h->record->storage) {
2181
2182 case USER_LUKS:
2183 r = home_get_disk_status_luks(h, state, &disk_size, &disk_usage, &disk_free, &disk_ceiling, &disk_floor);
2184 if (r < 0)
2185 return r;
2186
2187 break;
2188
2189 case USER_CLASSIC:
2190 case USER_DIRECTORY:
2191 case USER_SUBVOLUME:
2192 case USER_FSCRYPT:
2193 case USER_CIFS:
2194 r = home_get_disk_status_directory(h, state, &disk_size, &disk_usage, &disk_free, &disk_ceiling, &disk_floor);
2195 if (r < 0)
2196 return r;
2197
2198 break;
2199
2200 default:
2201 ; /* unset */
2202 }
2203
2204 if (disk_floor == UINT64_MAX || (disk_usage != UINT64_MAX && disk_floor < disk_usage))
2205 disk_floor = disk_usage;
2206 if (disk_floor == UINT64_MAX || disk_floor < USER_DISK_SIZE_MIN)
2207 disk_floor = USER_DISK_SIZE_MIN;
2208 if (disk_ceiling == UINT64_MAX || disk_ceiling > USER_DISK_SIZE_MAX)
2209 disk_ceiling = USER_DISK_SIZE_MAX;
2210
2211 r = json_build(&status,
2212 JSON_BUILD_OBJECT(
2213 JSON_BUILD_PAIR("state", JSON_BUILD_STRING(home_state_to_string(state))),
2214 JSON_BUILD_PAIR("service", JSON_BUILD_STRING("io.systemd.Home")),
2215 JSON_BUILD_PAIR_CONDITION(disk_size != UINT64_MAX, "diskSize", JSON_BUILD_UNSIGNED(disk_size)),
2216 JSON_BUILD_PAIR_CONDITION(disk_usage != UINT64_MAX, "diskUsage", JSON_BUILD_UNSIGNED(disk_usage)),
2217 JSON_BUILD_PAIR_CONDITION(disk_free != UINT64_MAX, "diskFree", JSON_BUILD_UNSIGNED(disk_free)),
2218 JSON_BUILD_PAIR_CONDITION(disk_ceiling != UINT64_MAX, "diskCeiling", JSON_BUILD_UNSIGNED(disk_ceiling)),
2219 JSON_BUILD_PAIR_CONDITION(disk_floor != UINT64_MAX, "diskFloor", JSON_BUILD_UNSIGNED(disk_floor)),
2220 JSON_BUILD_PAIR_CONDITION(h->signed_locally >= 0, "signedLocally", JSON_BUILD_BOOLEAN(h->signed_locally))
2221 ));
2222 if (r < 0)
2223 return r;
2224
2225 j = json_variant_ref(h->record->json);
2226 v = json_variant_ref(json_variant_by_key(j, "status"));
2227 m = json_variant_ref(json_variant_by_key(v, sd_id128_to_string(id, ids)));
2228
2229 r = json_variant_filter(&m, STRV_MAKE("diskSize", "diskUsage", "diskFree", "diskCeiling", "diskFloor", "signedLocally"));
2230 if (r < 0)
2231 return r;
2232
2233 r = json_variant_merge(&m, status);
2234 if (r < 0)
2235 return r;
2236
2237 r = json_variant_set_field(&v, ids, m);
2238 if (r < 0)
2239 return r;
2240
2241 r = json_variant_set_field(&j, "status", v);
2242 if (r < 0)
2243 return r;
2244
2245 ur = user_record_new();
2246 if (!ur)
2247 return -ENOMEM;
2248
2249 r = user_record_load(ur, j, flags);
2250 if (r < 0)
2251 return r;
2252
2253 ur->incomplete =
2254 FLAGS_SET(h->record->mask, USER_RECORD_PRIVILEGED) &&
2255 !FLAGS_SET(ur->mask, USER_RECORD_PRIVILEGED);
2256
2257 *ret = TAKE_PTR(ur);
2258 return 0;
2259}
2260
2261static int on_home_ref_eof(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
2262 _cleanup_(operation_unrefp) Operation *o = NULL;
2263 Home *h = userdata;
2264
2265 assert(s);
2266 assert(h);
2267
2268 if (h->ref_event_source_please_suspend == s)
2269 h->ref_event_source_please_suspend = sd_event_source_disable_unref(h->ref_event_source_please_suspend);
2270
2271 if (h->ref_event_source_dont_suspend == s)
2272 h->ref_event_source_dont_suspend = sd_event_source_disable_unref(h->ref_event_source_dont_suspend);
2273
2274 if (h->ref_event_source_dont_suspend || h->ref_event_source_please_suspend)
2275 return 0;
2276
2277 log_info("Got notification that all sessions of user %s ended, deactivating automatically.", h->user_name);
2278
2279 o = operation_new(OPERATION_PIPE_EOF, NULL);
2280 if (!o) {
2281 log_oom();
2282 return 0;
2283 }
2284
2285 home_schedule_operation(h, o, NULL);
2286 return 0;
2287}
2288
2289int home_create_fifo(Home *h, bool please_suspend) {
2290 _cleanup_close_ int ret_fd = -1;
2291 sd_event_source **ss;
2292 const char *fn, *suffix;
2293 int r;
2294
2295 assert(h);
2296
2297 if (please_suspend) {
2298 suffix = ".please-suspend";
2299 ss = &h->ref_event_source_please_suspend;
2300 } else {
2301 suffix = ".dont-suspend";
2302 ss = &h->ref_event_source_dont_suspend;
2303 }
2304
2305 fn = strjoina("/run/systemd/home/", h->user_name, suffix);
2306
2307 if (!*ss) {
2308 _cleanup_close_ int ref_fd = -1;
2309
2310 (void) mkdir("/run/systemd/home/", 0755);
2311 if (mkfifo(fn, 0600) < 0 && errno != EEXIST)
2312 return log_error_errno(errno, "Failed to create FIFO %s: %m", fn);
2313
2314 ref_fd = open(fn, O_RDONLY|O_CLOEXEC|O_NONBLOCK);
2315 if (ref_fd < 0)
2316 return log_error_errno(errno, "Failed to open FIFO %s for reading: %m", fn);
2317
2318 r = sd_event_add_io(h->manager->event, ss, ref_fd, 0, on_home_ref_eof, h);
2319 if (r < 0)
2320 return log_error_errno(r, "Failed to allocate reference FIFO event source: %m");
2321
2322 (void) sd_event_source_set_description(*ss, "acquire-ref");
2323
2324 r = sd_event_source_set_priority(*ss, SD_EVENT_PRIORITY_IDLE-1);
2325 if (r < 0)
2326 return r;
2327
2328 r = sd_event_source_set_io_fd_own(*ss, true);
2329 if (r < 0)
2330 return log_error_errno(r, "Failed to pass ownership of FIFO event fd to event source: %m");
2331
2332 TAKE_FD(ref_fd);
2333 }
2334
2335 ret_fd = open(fn, O_WRONLY|O_CLOEXEC|O_NONBLOCK);
2336 if (ret_fd < 0)
2337 return log_error_errno(errno, "Failed to open FIFO %s for writing: %m", fn);
2338
2339 return TAKE_FD(ret_fd);
2340}
2341
2342static int home_dispatch_acquire(Home *h, Operation *o) {
2343 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2344 int (*call)(Home *h, UserRecord *secret, HomeState for_state, sd_bus_error *error) = NULL;
2345 HomeState for_state;
2346 int r;
2347
2348 assert(h);
2349 assert(o);
2350 assert(o->type == OPERATION_ACQUIRE);
2351
2352 switch (home_get_state(h)) {
2353
2354 case HOME_UNFIXATED:
2355 for_state = HOME_FIXATING_FOR_ACQUIRE;
2356 call = home_fixate_internal;
2357 break;
2358
2359 case HOME_ABSENT:
2360 r = sd_bus_error_setf(&error, BUS_ERROR_HOME_ABSENT, "Home %s is currently missing or not plugged in.", h->user_name);
2361 break;
2362
2363 case HOME_INACTIVE:
9be99f81 2364 case HOME_DIRTY:
70a5db58
LP
2365 for_state = HOME_ACTIVATING_FOR_ACQUIRE;
2366 call = home_activate_internal;
2367 break;
2368
2369 case HOME_ACTIVE:
2370 for_state = HOME_AUTHENTICATING_FOR_ACQUIRE;
2371 call = home_authenticate_internal;
2372 break;
2373
2374 case HOME_LOCKED:
2375 for_state = HOME_UNLOCKING_FOR_ACQUIRE;
2376 call = home_unlock_internal;
2377 break;
2378
2379 default:
2380 /* All other cases means we are currently executing an operation, which means the job remains
2381 * pending. */
2382 return 0;
2383 }
2384
2385 assert(!h->current_operation);
2386
2387 if (call) {
2388 r = home_ratelimit(h, &error);
2389 if (r >= 0)
2390 r = call(h, o->secret, for_state, &error);
2391 }
2392
2393 if (r != 0) /* failure or completed */
2394 operation_result(o, r, &error);
2395 else /* ongoing */
2396 h->current_operation = operation_ref(o);
2397
2398 return 1;
2399}
2400
2401static int home_dispatch_release(Home *h, Operation *o) {
2402 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2403 int r;
2404
2405 assert(h);
2406 assert(o);
2407 assert(o->type == OPERATION_RELEASE);
2408
2409 if (h->ref_event_source_dont_suspend || h->ref_event_source_please_suspend)
2410 /* If there's now a reference again, then let's abort the release attempt */
2411 r = sd_bus_error_setf(&error, BUS_ERROR_HOME_BUSY, "Home %s is currently referenced.", h->user_name);
2412 else {
2413 switch (home_get_state(h)) {
2414
2415 case HOME_UNFIXATED:
2416 case HOME_ABSENT:
2417 case HOME_INACTIVE:
9be99f81 2418 case HOME_DIRTY:
a60416f3 2419 r = 1; /* done */
70a5db58
LP
2420 break;
2421
2422 case HOME_LOCKED:
2423 r = sd_bus_error_setf(&error, BUS_ERROR_HOME_LOCKED, "Home %s is currently locked.", h->user_name);
2424 break;
2425
2426 case HOME_ACTIVE:
2427 r = home_deactivate_internal(h, false, &error);
2428 break;
2429
2430 default:
2431 /* All other cases means we are currently executing an operation, which means the job remains
2432 * pending. */
2433 return 0;
2434 }
2435 }
2436
2437 assert(!h->current_operation);
2438
a60416f3 2439 if (r != 0) /* failure or completed */
70a5db58
LP
2440 operation_result(o, r, &error);
2441 else /* ongoing */
2442 h->current_operation = operation_ref(o);
2443
2444 return 1;
2445}
2446
2447static int home_dispatch_lock_all(Home *h, Operation *o) {
2448 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2449 int r;
2450
2451 assert(h);
2452 assert(o);
2453 assert(o->type == OPERATION_LOCK_ALL);
2454
2455 switch (home_get_state(h)) {
2456
2457 case HOME_UNFIXATED:
2458 case HOME_ABSENT:
2459 case HOME_INACTIVE:
9be99f81 2460 case HOME_DIRTY:
70a5db58 2461 log_info("Home %s is not active, no locking necessary.", h->user_name);
a60416f3 2462 r = 1; /* done */
70a5db58
LP
2463 break;
2464
2465 case HOME_LOCKED:
2466 log_info("Home %s is already locked.", h->user_name);
a60416f3 2467 r = 1; /* done */
70a5db58
LP
2468 break;
2469
2470 case HOME_ACTIVE:
2471 log_info("Locking home %s.", h->user_name);
2472 r = home_lock(h, &error);
2473 break;
2474
2475 default:
2476 /* All other cases means we are currently executing an operation, which means the job remains
2477 * pending. */
2478 return 0;
2479 }
2480
2481 assert(!h->current_operation);
2482
2483 if (r != 0) /* failure or completed */
2484 operation_result(o, r, &error);
2485 else /* ongoing */
2486 h->current_operation = operation_ref(o);
2487
2488 return 1;
2489}
2490
d1f6e01e
LP
2491static int home_dispatch_deactivate_all(Home *h, Operation *o) {
2492 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2493 int r;
2494
2495 assert(h);
2496 assert(o);
2497 assert(o->type == OPERATION_DEACTIVATE_ALL);
2498
2499 switch (home_get_state(h)) {
2500
2501 case HOME_UNFIXATED:
2502 case HOME_ABSENT:
2503 case HOME_INACTIVE:
2504 case HOME_DIRTY:
2505 log_info("Home %s is already deactivated.", h->user_name);
2506 r = 1; /* done */
2507 break;
2508
2509 case HOME_LOCKED:
2510 log_info("Home %s is currently locked, not deactivating.", h->user_name);
2511 r = 1; /* done */
2512 break;
2513
2514 case HOME_ACTIVE:
2515 log_info("Deactivating home %s.", h->user_name);
2516 r = home_deactivate_internal(h, false, &error);
2517 break;
2518
2519 default:
2520 /* All other cases means we are currently executing an operation, which means the job remains
2521 * pending. */
2522 return 0;
2523 }
2524
2525 assert(!h->current_operation);
2526
2527 if (r != 0) /* failure or completed */
2528 operation_result(o, r, &error);
2529 else /* ongoing */
2530 h->current_operation = operation_ref(o);
2531
2532 return 1;
2533}
2534
70a5db58
LP
2535static int home_dispatch_pipe_eof(Home *h, Operation *o) {
2536 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2537 int r;
2538
2539 assert(h);
2540 assert(o);
2541 assert(o->type == OPERATION_PIPE_EOF);
2542
2543 if (h->ref_event_source_please_suspend || h->ref_event_source_dont_suspend)
2544 return 1; /* Hmm, there's a reference again, let's cancel this */
2545
2546 switch (home_get_state(h)) {
2547
2548 case HOME_UNFIXATED:
2549 case HOME_ABSENT:
2550 case HOME_INACTIVE:
9be99f81 2551 case HOME_DIRTY:
70a5db58
LP
2552 log_info("Home %s already deactivated, no automatic deactivation needed.", h->user_name);
2553 break;
2554
2555 case HOME_DEACTIVATING:
2556 log_info("Home %s is already being deactivated, automatic deactivated unnecessary.", h->user_name);
2557 break;
2558
2559 case HOME_ACTIVE:
2560 r = home_deactivate_internal(h, false, &error);
2561 if (r < 0)
2562 log_warning_errno(r, "Failed to deactivate %s, ignoring: %s", h->user_name, bus_error_message(&error, r));
2563 break;
2564
2565 case HOME_LOCKED:
2566 default:
2567 /* If the device is locked or any operation is being executed, let's leave this pending */
2568 return 0;
2569 }
2570
2571 /* Note that we don't call operation_fail() or operation_success() here, because this kind of
2572 * operation has no message associated with it, and thus there's no need to propagate success. */
2573
2574 assert(!o->message);
2575 return 1;
2576}
2577
2578static int home_dispatch_deactivate_force(Home *h, Operation *o) {
2579 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2580 int r;
2581
2582 assert(h);
2583 assert(o);
2584 assert(o->type == OPERATION_DEACTIVATE_FORCE);
2585
2586 switch (home_get_state(h)) {
2587
2588 case HOME_UNFIXATED:
2589 case HOME_ABSENT:
2590 case HOME_INACTIVE:
9be99f81 2591 case HOME_DIRTY:
70a5db58
LP
2592 log_debug("Home %s already deactivated, no forced deactivation due to unplug needed.", h->user_name);
2593 break;
2594
2595 case HOME_DEACTIVATING:
2596 log_debug("Home %s is already being deactivated, forced deactivation due to unplug unnecessary.", h->user_name);
2597 break;
2598
2599 case HOME_ACTIVE:
2600 case HOME_LOCKED:
2601 r = home_deactivate_internal(h, true, &error);
2602 if (r < 0)
2603 log_warning_errno(r, "Failed to forcibly deactivate %s, ignoring: %s", h->user_name, bus_error_message(&error, r));
2604 break;
2605
2606 default:
2607 /* If any operation is being executed, let's leave this pending */
2608 return 0;
2609 }
2610
2611 /* Note that we don't call operation_fail() or operation_success() here, because this kind of
2612 * operation has no message associated with it, and thus there's no need to propagate success. */
2613
2614 assert(!o->message);
2615 return 1;
2616}
2617
2618static int on_pending(sd_event_source *s, void *userdata) {
2619 Home *h = userdata;
2620 Operation *o;
2621 int r;
2622
2623 assert(s);
2624 assert(h);
2625
2626 o = ordered_set_first(h->pending_operations);
2627 if (o) {
2628 static int (* const operation_table[_OPERATION_MAX])(Home *h, Operation *o) = {
2629 [OPERATION_ACQUIRE] = home_dispatch_acquire,
2630 [OPERATION_RELEASE] = home_dispatch_release,
2631 [OPERATION_LOCK_ALL] = home_dispatch_lock_all,
d1f6e01e 2632 [OPERATION_DEACTIVATE_ALL] = home_dispatch_deactivate_all,
70a5db58
LP
2633 [OPERATION_PIPE_EOF] = home_dispatch_pipe_eof,
2634 [OPERATION_DEACTIVATE_FORCE] = home_dispatch_deactivate_force,
2635 };
2636
2637 assert(operation_table[o->type]);
2638 r = operation_table[o->type](h, o);
2639 if (r != 0) {
2640 /* The operation completed, let's remove it from the pending list, and exit while
2641 * leaving the event source enabled as it is. */
2642 assert_se(ordered_set_remove(h->pending_operations, o) == o);
2643 operation_unref(o);
2644 return 0;
2645 }
2646 }
2647
2648 /* Nothing to do anymore, let's turn off this event source */
2649 r = sd_event_source_set_enabled(s, SD_EVENT_OFF);
2650 if (r < 0)
2651 return log_error_errno(r, "Failed to disable event source: %m");
2652
2653 return 0;
2654}
2655
2656int home_schedule_operation(Home *h, Operation *o, sd_bus_error *error) {
2657 int r;
2658
2659 assert(h);
2660
2661 if (o) {
2662 if (ordered_set_size(h->pending_operations) >= PENDING_OPERATIONS_MAX)
2663 return sd_bus_error_setf(error, BUS_ERROR_TOO_MANY_OPERATIONS, "Too many client operations requested");
2664
65ca9b53 2665 r = ordered_set_ensure_put(&h->pending_operations, &operation_hash_ops, o);
70a5db58
LP
2666 if (r < 0)
2667 return r;
2668
2669 operation_ref(o);
2670 }
2671
2672 if (!h->pending_event_source) {
2673 r = sd_event_add_defer(h->manager->event, &h->pending_event_source, on_pending, h);
2674 if (r < 0)
2675 return log_error_errno(r, "Failed to allocate pending defer event source: %m");
2676
2677 (void) sd_event_source_set_description(h->pending_event_source, "pending");
2678
2679 r = sd_event_source_set_priority(h->pending_event_source, SD_EVENT_PRIORITY_IDLE);
2680 if (r < 0)
2681 return r;
2682 }
2683
2684 r = sd_event_source_set_enabled(h->pending_event_source, SD_EVENT_ON);
2685 if (r < 0)
2686 return log_error_errno(r, "Failed to trigger pending event source: %m");
2687
2688 return 0;
2689}
2690
2691static int home_get_image_path_seat(Home *h, char **ret) {
2692 _cleanup_(sd_device_unrefp) sd_device *d = NULL;
2693 _cleanup_free_ char *c = NULL;
2694 const char *ip, *seat;
2695 struct stat st;
2696 int r;
2697
2698 assert(h);
2699
2700 if (user_record_storage(h->record) != USER_LUKS)
2701 return -ENXIO;
2702
2703 ip = user_record_image_path(h->record);
2704 if (!ip)
2705 return -ENXIO;
2706
2707 if (!path_startswith(ip, "/dev/"))
2708 return -ENXIO;
2709
2710 if (stat(ip, &st) < 0)
2711 return -errno;
2712
2713 if (!S_ISBLK(st.st_mode))
2714 return -ENOTBLK;
2715
930aa88f 2716 r = sd_device_new_from_stat_rdev(&d, &st);
70a5db58
LP
2717 if (r < 0)
2718 return r;
2719
2720 r = sd_device_get_property_value(d, "ID_SEAT", &seat);
2721 if (r == -ENOENT) /* no property means seat0 */
2722 seat = "seat0";
2723 else if (r < 0)
2724 return r;
2725
2726 c = strdup(seat);
2727 if (!c)
2728 return -ENOMEM;
2729
2730 *ret = TAKE_PTR(c);
2731 return 0;
2732}
2733
2734int home_auto_login(Home *h, char ***ret_seats) {
2735 _cleanup_free_ char *seat = NULL, *seat2 = NULL;
2736
2737 assert(h);
2738 assert(ret_seats);
2739
2740 (void) home_get_image_path_seat(h, &seat);
2741
2742 if (h->record->auto_login > 0 && !streq_ptr(seat, "seat0")) {
2743 /* For now, when the auto-login boolean is set for a user, let's make it mean
2744 * "seat0". Eventually we can extend the concept and allow configuration of any kind of seat,
2745 * but let's keep simple initially, most likely the feature is interesting on single-user
2746 * systems anyway, only.
2747 *
2748 * We filter out users marked for auto-login in we know for sure their home directory is
2749 * absent. */
2750
2751 if (user_record_test_image_path(h->record) != USER_TEST_ABSENT) {
2752 seat2 = strdup("seat0");
2753 if (!seat2)
2754 return -ENOMEM;
2755 }
2756 }
2757
2758 if (seat || seat2) {
2759 _cleanup_strv_free_ char **list = NULL;
2760 size_t i = 0;
2761
2762 list = new(char*, 3);
2763 if (!list)
2764 return -ENOMEM;
2765
2766 if (seat)
2767 list[i++] = TAKE_PTR(seat);
2768 if (seat2)
2769 list[i++] = TAKE_PTR(seat2);
2770
2771 list[i] = NULL;
2772 *ret_seats = TAKE_PTR(list);
2773 return 1;
2774 }
2775
2776 *ret_seats = NULL;
2777 return 0;
2778}
2779
2780int home_set_current_message(Home *h, sd_bus_message *m) {
2781 assert(h);
2782
2783 if (!m)
2784 return 0;
2785
2786 if (h->current_operation)
2787 return -EBUSY;
2788
2789 h->current_operation = operation_new(OPERATION_IMMEDIATE, m);
2790 if (!h->current_operation)
2791 return -ENOMEM;
2792
2793 return 1;
2794}
2795
9796a9fb
LP
2796int home_wait_for_worker(Home *h) {
2797 assert(h);
2798
2799 if (h->worker_pid <= 0)
2800 return 0;
2801
2802 log_info("Worker process for home %s is still running while exiting. Waiting for it to finish.", h->user_name);
2803 (void) wait_for_terminate(h->worker_pid, NULL);
2804 (void) hashmap_remove_value(h->manager->homes_by_worker_pid, PID_TO_PTR(h->worker_pid), h);
2805 h->worker_pid = 0;
2806 return 1;
2807}
2808
70a5db58
LP
2809static const char* const home_state_table[_HOME_STATE_MAX] = {
2810 [HOME_UNFIXATED] = "unfixated",
2811 [HOME_ABSENT] = "absent",
2812 [HOME_INACTIVE] = "inactive",
9be99f81 2813 [HOME_DIRTY] = "dirty",
70a5db58
LP
2814 [HOME_FIXATING] = "fixating",
2815 [HOME_FIXATING_FOR_ACTIVATION] = "fixating-for-activation",
2816 [HOME_FIXATING_FOR_ACQUIRE] = "fixating-for-acquire",
2817 [HOME_ACTIVATING] = "activating",
2818 [HOME_ACTIVATING_FOR_ACQUIRE] = "activating-for-acquire",
2819 [HOME_DEACTIVATING] = "deactivating",
2820 [HOME_ACTIVE] = "active",
2821 [HOME_LOCKING] = "locking",
2822 [HOME_LOCKED] = "locked",
2823 [HOME_UNLOCKING] = "unlocking",
2824 [HOME_UNLOCKING_FOR_ACQUIRE] = "unlocking-for-acquire",
2825 [HOME_CREATING] = "creating",
2826 [HOME_REMOVING] = "removing",
2827 [HOME_UPDATING] = "updating",
2828 [HOME_UPDATING_WHILE_ACTIVE] = "updating-while-active",
2829 [HOME_RESIZING] = "resizing",
2830 [HOME_RESIZING_WHILE_ACTIVE] = "resizing-while-active",
2831 [HOME_PASSWD] = "passwd",
2832 [HOME_PASSWD_WHILE_ACTIVE] = "passwd-while-active",
2833 [HOME_AUTHENTICATING] = "authenticating",
2834 [HOME_AUTHENTICATING_WHILE_ACTIVE] = "authenticating-while-active",
2835 [HOME_AUTHENTICATING_FOR_ACQUIRE] = "authenticating-for-acquire",
2836};
2837
2838DEFINE_STRING_TABLE_LOOKUP(home_state, HomeState);