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