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