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