]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/mount.c
Split out part of mount-util.c into mountpoint-util.c
[thirdparty/systemd.git] / src / core / mount.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <signal.h>
5 #include <stdio.h>
6 #include <sys/epoll.h>
7
8 #include <libmount.h>
9
10 #include "sd-messages.h"
11
12 #include "alloc-util.h"
13 #include "dbus-mount.h"
14 #include "device.h"
15 #include "escape.h"
16 #include "exit-status.h"
17 #include "format-util.h"
18 #include "fstab-util.h"
19 #include "log.h"
20 #include "manager.h"
21 #include "mkdir.h"
22 #include "mount-setup.h"
23 #include "mount.h"
24 #include "mountpoint-util.h"
25 #include "parse-util.h"
26 #include "path-util.h"
27 #include "process-util.h"
28 #include "serialize.h"
29 #include "special.h"
30 #include "string-table.h"
31 #include "string-util.h"
32 #include "strv.h"
33 #include "unit-name.h"
34 #include "unit.h"
35
36 #define RETRY_UMOUNT_MAX 32
37
38 DEFINE_TRIVIAL_CLEANUP_FUNC(struct libmnt_table*, mnt_free_table);
39 DEFINE_TRIVIAL_CLEANUP_FUNC(struct libmnt_iter*, mnt_free_iter);
40
41 static const UnitActiveState state_translation_table[_MOUNT_STATE_MAX] = {
42 [MOUNT_DEAD] = UNIT_INACTIVE,
43 [MOUNT_MOUNTING] = UNIT_ACTIVATING,
44 [MOUNT_MOUNTING_DONE] = UNIT_ACTIVATING,
45 [MOUNT_MOUNTED] = UNIT_ACTIVE,
46 [MOUNT_REMOUNTING] = UNIT_RELOADING,
47 [MOUNT_UNMOUNTING] = UNIT_DEACTIVATING,
48 [MOUNT_REMOUNTING_SIGTERM] = UNIT_RELOADING,
49 [MOUNT_REMOUNTING_SIGKILL] = UNIT_RELOADING,
50 [MOUNT_UNMOUNTING_SIGTERM] = UNIT_DEACTIVATING,
51 [MOUNT_UNMOUNTING_SIGKILL] = UNIT_DEACTIVATING,
52 [MOUNT_FAILED] = UNIT_FAILED
53 };
54
55 static int mount_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
56 static int mount_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata);
57
58 static bool MOUNT_STATE_WITH_PROCESS(MountState state) {
59 return IN_SET(state,
60 MOUNT_MOUNTING,
61 MOUNT_MOUNTING_DONE,
62 MOUNT_REMOUNTING,
63 MOUNT_REMOUNTING_SIGTERM,
64 MOUNT_REMOUNTING_SIGKILL,
65 MOUNT_UNMOUNTING,
66 MOUNT_UNMOUNTING_SIGTERM,
67 MOUNT_UNMOUNTING_SIGKILL);
68 }
69
70 static bool mount_needs_network(const char *options, const char *fstype) {
71 if (fstab_test_option(options, "_netdev\0"))
72 return true;
73
74 if (fstype && fstype_is_network(fstype))
75 return true;
76
77 return false;
78 }
79
80 static bool mount_is_network(const MountParameters *p) {
81 assert(p);
82
83 return mount_needs_network(p->options, p->fstype);
84 }
85
86 static bool mount_is_loop(const MountParameters *p) {
87 assert(p);
88
89 if (fstab_test_option(p->options, "loop\0"))
90 return true;
91
92 return false;
93 }
94
95 static bool mount_is_bind(const MountParameters *p) {
96 assert(p);
97
98 if (fstab_test_option(p->options, "bind\0" "rbind\0"))
99 return true;
100
101 if (p->fstype && STR_IN_SET(p->fstype, "bind", "rbind"))
102 return true;
103
104 return false;
105 }
106
107 static bool mount_is_auto(const MountParameters *p) {
108 assert(p);
109
110 return !fstab_test_option(p->options, "noauto\0");
111 }
112
113 static bool mount_is_automount(const MountParameters *p) {
114 assert(p);
115
116 return fstab_test_option(p->options,
117 "comment=systemd.automount\0"
118 "x-systemd.automount\0");
119 }
120
121 static bool mount_is_bound_to_device(const Mount *m) {
122 const MountParameters *p;
123
124 if (m->from_fragment)
125 return true;
126
127 p = &m->parameters_proc_self_mountinfo;
128 return fstab_test_option(p->options, "x-systemd.device-bound\0");
129 }
130
131 static bool needs_quota(const MountParameters *p) {
132 assert(p);
133
134 /* Quotas are not enabled on network filesystems,
135 * but we want them, for example, on storage connected via iscsi */
136 if (p->fstype && fstype_is_network(p->fstype))
137 return false;
138
139 if (mount_is_bind(p))
140 return false;
141
142 return fstab_test_option(p->options,
143 "usrquota\0" "grpquota\0" "quota\0" "usrjquota\0" "grpjquota\0");
144 }
145
146 static void mount_init(Unit *u) {
147 Mount *m = MOUNT(u);
148
149 assert(u);
150 assert(u->load_state == UNIT_STUB);
151
152 m->timeout_usec = u->manager->default_timeout_start_usec;
153
154 m->exec_context.std_output = u->manager->default_std_output;
155 m->exec_context.std_error = u->manager->default_std_error;
156
157 m->directory_mode = 0755;
158
159 /* We need to make sure that /usr/bin/mount is always called
160 * in the same process group as us, so that the autofs kernel
161 * side doesn't send us another mount request while we are
162 * already trying to comply its last one. */
163 m->exec_context.same_pgrp = true;
164
165 m->control_command_id = _MOUNT_EXEC_COMMAND_INVALID;
166
167 u->ignore_on_isolate = true;
168 }
169
170 static int mount_arm_timer(Mount *m, usec_t usec) {
171 int r;
172
173 assert(m);
174
175 if (m->timer_event_source) {
176 r = sd_event_source_set_time(m->timer_event_source, usec);
177 if (r < 0)
178 return r;
179
180 return sd_event_source_set_enabled(m->timer_event_source, SD_EVENT_ONESHOT);
181 }
182
183 if (usec == USEC_INFINITY)
184 return 0;
185
186 r = sd_event_add_time(
187 UNIT(m)->manager->event,
188 &m->timer_event_source,
189 CLOCK_MONOTONIC,
190 usec, 0,
191 mount_dispatch_timer, m);
192 if (r < 0)
193 return r;
194
195 (void) sd_event_source_set_description(m->timer_event_source, "mount-timer");
196
197 return 0;
198 }
199
200 static void mount_unwatch_control_pid(Mount *m) {
201 assert(m);
202
203 if (m->control_pid <= 0)
204 return;
205
206 unit_unwatch_pid(UNIT(m), m->control_pid);
207 m->control_pid = 0;
208 }
209
210 static void mount_parameters_done(MountParameters *p) {
211 assert(p);
212
213 free(p->what);
214 free(p->options);
215 free(p->fstype);
216
217 p->what = p->options = p->fstype = NULL;
218 }
219
220 static void mount_done(Unit *u) {
221 Mount *m = MOUNT(u);
222
223 assert(m);
224
225 m->where = mfree(m->where);
226
227 mount_parameters_done(&m->parameters_proc_self_mountinfo);
228 mount_parameters_done(&m->parameters_fragment);
229
230 m->exec_runtime = exec_runtime_unref(m->exec_runtime, false);
231 exec_command_done_array(m->exec_command, _MOUNT_EXEC_COMMAND_MAX);
232 m->control_command = NULL;
233
234 dynamic_creds_unref(&m->dynamic_creds);
235
236 mount_unwatch_control_pid(m);
237
238 m->timer_event_source = sd_event_source_unref(m->timer_event_source);
239 }
240
241 _pure_ static MountParameters* get_mount_parameters_fragment(Mount *m) {
242 assert(m);
243
244 if (m->from_fragment)
245 return &m->parameters_fragment;
246
247 return NULL;
248 }
249
250 _pure_ static MountParameters* get_mount_parameters(Mount *m) {
251 assert(m);
252
253 if (m->from_proc_self_mountinfo)
254 return &m->parameters_proc_self_mountinfo;
255
256 return get_mount_parameters_fragment(m);
257 }
258
259 static int mount_add_mount_dependencies(Mount *m) {
260 MountParameters *pm;
261 Unit *other;
262 Iterator i;
263 Set *s;
264 int r;
265
266 assert(m);
267
268 if (!path_equal(m->where, "/")) {
269 _cleanup_free_ char *parent = NULL;
270
271 /* Adds in links to other mount points that might lie further up in the hierarchy */
272
273 parent = dirname_malloc(m->where);
274 if (!parent)
275 return -ENOMEM;
276
277 r = unit_require_mounts_for(UNIT(m), parent, UNIT_DEPENDENCY_IMPLICIT);
278 if (r < 0)
279 return r;
280 }
281
282 /* Adds in dependencies to other mount points that might be needed for the source path (if this is a bind mount
283 * or a loop mount) to be available. */
284 pm = get_mount_parameters_fragment(m);
285 if (pm && pm->what &&
286 path_is_absolute(pm->what) &&
287 (mount_is_bind(pm) || mount_is_loop(pm) || !mount_is_network(pm))) {
288
289 r = unit_require_mounts_for(UNIT(m), pm->what, UNIT_DEPENDENCY_FILE);
290 if (r < 0)
291 return r;
292 }
293
294 /* Adds in dependencies to other units that use this path or paths further down in the hierarchy */
295 s = manager_get_units_requiring_mounts_for(UNIT(m)->manager, m->where);
296 SET_FOREACH(other, s, i) {
297
298 if (other->load_state != UNIT_LOADED)
299 continue;
300
301 if (other == UNIT(m))
302 continue;
303
304 r = unit_add_dependency(other, UNIT_AFTER, UNIT(m), true, UNIT_DEPENDENCY_PATH);
305 if (r < 0)
306 return r;
307
308 if (UNIT(m)->fragment_path) {
309 /* If we have fragment configuration, then make this dependency required */
310 r = unit_add_dependency(other, UNIT_REQUIRES, UNIT(m), true, UNIT_DEPENDENCY_PATH);
311 if (r < 0)
312 return r;
313 }
314 }
315
316 return 0;
317 }
318
319 static int mount_add_device_dependencies(Mount *m) {
320 bool device_wants_mount = false;
321 UnitDependencyMask mask;
322 MountParameters *p;
323 UnitDependency dep;
324 int r;
325
326 assert(m);
327
328 p = get_mount_parameters(m);
329 if (!p)
330 return 0;
331
332 if (!p->what)
333 return 0;
334
335 if (mount_is_bind(p))
336 return 0;
337
338 if (!is_device_path(p->what))
339 return 0;
340
341 /* /dev/root is a really weird thing, it's not a real device,
342 * but just a path the kernel exports for the root file system
343 * specified on the kernel command line. Ignore it here. */
344 if (path_equal(p->what, "/dev/root"))
345 return 0;
346
347 if (path_equal(m->where, "/"))
348 return 0;
349
350 if (mount_is_auto(p) && !mount_is_automount(p) && MANAGER_IS_SYSTEM(UNIT(m)->manager))
351 device_wants_mount = true;
352
353 /* Mount units from /proc/self/mountinfo are not bound to devices
354 * by default since they're subject to races when devices are
355 * unplugged. But the user can still force this dep with an
356 * appropriate option (or udev property) so the mount units are
357 * automatically stopped when the device disappears suddenly. */
358 dep = mount_is_bound_to_device(m) ? UNIT_BINDS_TO : UNIT_REQUIRES;
359
360 mask = m->from_fragment ? UNIT_DEPENDENCY_FILE : UNIT_DEPENDENCY_MOUNTINFO_IMPLICIT;
361
362 r = unit_add_node_dependency(UNIT(m), p->what, device_wants_mount, dep, mask);
363 if (r < 0)
364 return r;
365
366 return 0;
367 }
368
369 static int mount_add_quota_dependencies(Mount *m) {
370 UnitDependencyMask mask;
371 MountParameters *p;
372 int r;
373
374 assert(m);
375
376 if (!MANAGER_IS_SYSTEM(UNIT(m)->manager))
377 return 0;
378
379 p = get_mount_parameters_fragment(m);
380 if (!p)
381 return 0;
382
383 if (!needs_quota(p))
384 return 0;
385
386 mask = m->from_fragment ? UNIT_DEPENDENCY_FILE : UNIT_DEPENDENCY_MOUNTINFO_IMPLICIT;
387
388 r = unit_add_two_dependencies_by_name(UNIT(m), UNIT_BEFORE, UNIT_WANTS, SPECIAL_QUOTACHECK_SERVICE, true, mask);
389 if (r < 0)
390 return r;
391
392 r = unit_add_two_dependencies_by_name(UNIT(m), UNIT_BEFORE, UNIT_WANTS, SPECIAL_QUOTAON_SERVICE, true, mask);
393 if (r < 0)
394 return r;
395
396 return 0;
397 }
398
399 static bool mount_is_extrinsic(Mount *m) {
400 MountParameters *p;
401 assert(m);
402
403 /* Returns true for all units that are "magic" and should be excluded from the usual start-up and shutdown
404 * dependencies. We call them "extrinsic" here, as they are generally mounted outside of the systemd dependency
405 * logic. We shouldn't attempt to manage them ourselves but it's fine if the user operates on them with us. */
406
407 if (!MANAGER_IS_SYSTEM(UNIT(m)->manager)) /* We only automatically manage mounts if we are in system mode */
408 return true;
409
410 if (PATH_IN_SET(m->where, /* Don't bother with the OS data itself */
411 "/",
412 "/usr"))
413 return true;
414
415 if (PATH_STARTSWITH_SET(m->where,
416 "/run/initramfs", /* This should stay around from before we boot until after we shutdown */
417 "/proc", /* All of this is API VFS */
418 "/sys", /* … dito … */
419 "/dev")) /* … dito … */
420 return true;
421
422 /* If this is an initrd mount, and we are not in the initrd, then leave this around forever, too. */
423 p = get_mount_parameters(m);
424 if (p && fstab_test_option(p->options, "x-initrd.mount\0") && !in_initrd())
425 return true;
426
427 return false;
428 }
429
430 static int mount_add_default_dependencies(Mount *m) {
431 UnitDependencyMask mask;
432 int r;
433 MountParameters *p;
434 const char *after;
435
436 assert(m);
437
438 if (!UNIT(m)->default_dependencies)
439 return 0;
440
441 /* We do not add any default dependencies to /, /usr or /run/initramfs/, since they are guaranteed to stay
442 * mounted the whole time, since our system is on it. Also, don't bother with anything mounted below virtual
443 * file systems, it's also going to be virtual, and hence not worth the effort. */
444 if (mount_is_extrinsic(m))
445 return 0;
446
447 p = get_mount_parameters(m);
448 if (!p)
449 return 0;
450
451 mask = m->from_fragment ? UNIT_DEPENDENCY_FILE : UNIT_DEPENDENCY_MOUNTINFO_DEFAULT;
452
453 if (mount_is_network(p)) {
454 /* We order ourselves after network.target. This is
455 * primarily useful at shutdown: services that take
456 * down the network should order themselves before
457 * network.target, so that they are shut down only
458 * after this mount unit is stopped. */
459
460 r = unit_add_dependency_by_name(UNIT(m), UNIT_AFTER, SPECIAL_NETWORK_TARGET, true, mask);
461 if (r < 0)
462 return r;
463
464 /* We pull in network-online.target, and order
465 * ourselves after it. This is useful at start-up to
466 * actively pull in tools that want to be started
467 * before we start mounting network file systems, and
468 * whose purpose it is to delay this until the network
469 * is "up". */
470
471 r = unit_add_two_dependencies_by_name(UNIT(m), UNIT_WANTS, UNIT_AFTER, SPECIAL_NETWORK_ONLINE_TARGET, true, mask);
472 if (r < 0)
473 return r;
474
475 after = SPECIAL_REMOTE_FS_PRE_TARGET;
476 } else
477 after = SPECIAL_LOCAL_FS_PRE_TARGET;
478
479 r = unit_add_dependency_by_name(UNIT(m), UNIT_AFTER, after, true, mask);
480 if (r < 0)
481 return r;
482
483 r = unit_add_two_dependencies_by_name(UNIT(m), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_UMOUNT_TARGET, true, mask);
484 if (r < 0)
485 return r;
486
487 /* If this is a tmpfs mount then we have to unmount it before we try to deactivate swaps */
488 if (streq_ptr(p->fstype, "tmpfs")) {
489 r = unit_add_dependency_by_name(UNIT(m), UNIT_AFTER, SPECIAL_SWAP_TARGET, true, mask);
490 if (r < 0)
491 return r;
492 }
493
494 return 0;
495 }
496
497 static int mount_verify(Mount *m) {
498 _cleanup_free_ char *e = NULL;
499 MountParameters *p;
500 int r;
501
502 assert(m);
503
504 if (UNIT(m)->load_state != UNIT_LOADED)
505 return 0;
506
507 if (!m->from_fragment && !m->from_proc_self_mountinfo && !UNIT(m)->perpetual)
508 return -ENOENT;
509
510 r = unit_name_from_path(m->where, ".mount", &e);
511 if (r < 0)
512 return log_unit_error_errno(UNIT(m), r, "Failed to generate unit name from mount path: %m");
513
514 if (!unit_has_name(UNIT(m), e)) {
515 log_unit_error(UNIT(m), "Where= setting doesn't match unit name. Refusing.");
516 return -ENOEXEC;
517 }
518
519 if (mount_point_is_api(m->where) || mount_point_ignore(m->where)) {
520 log_unit_error(UNIT(m), "Cannot create mount unit for API file system %s. Refusing.", m->where);
521 return -ENOEXEC;
522 }
523
524 p = get_mount_parameters_fragment(m);
525 if (p && !p->what) {
526 log_unit_error(UNIT(m), "What= setting is missing. Refusing.");
527 return -ENOEXEC;
528 }
529
530 if (m->exec_context.pam_name && m->kill_context.kill_mode != KILL_CONTROL_GROUP) {
531 log_unit_error(UNIT(m), "Unit has PAM enabled. Kill mode must be set to control-group'. Refusing.");
532 return -ENOEXEC;
533 }
534
535 return 0;
536 }
537
538 static int mount_add_extras(Mount *m) {
539 Unit *u = UNIT(m);
540 int r;
541
542 assert(m);
543
544 if (u->fragment_path)
545 m->from_fragment = true;
546
547 if (!m->where) {
548 r = unit_name_to_path(u->id, &m->where);
549 if (r < 0)
550 return r;
551 }
552
553 path_simplify(m->where, false);
554
555 if (!u->description) {
556 r = unit_set_description(u, m->where);
557 if (r < 0)
558 return r;
559 }
560
561 r = mount_add_device_dependencies(m);
562 if (r < 0)
563 return r;
564
565 r = mount_add_mount_dependencies(m);
566 if (r < 0)
567 return r;
568
569 r = mount_add_quota_dependencies(m);
570 if (r < 0)
571 return r;
572
573 r = unit_patch_contexts(u);
574 if (r < 0)
575 return r;
576
577 r = unit_add_exec_dependencies(u, &m->exec_context);
578 if (r < 0)
579 return r;
580
581 r = unit_set_default_slice(u);
582 if (r < 0)
583 return r;
584
585 r = mount_add_default_dependencies(m);
586 if (r < 0)
587 return r;
588
589 return 0;
590 }
591
592 static int mount_load_root_mount(Unit *u) {
593 assert(u);
594
595 if (!unit_has_name(u, SPECIAL_ROOT_MOUNT))
596 return 0;
597
598 u->perpetual = true;
599 u->default_dependencies = false;
600
601 /* The stdio/kmsg bridge socket is on /, in order to avoid a dep loop, don't use kmsg logging for -.mount */
602 MOUNT(u)->exec_context.std_output = EXEC_OUTPUT_NULL;
603 MOUNT(u)->exec_context.std_input = EXEC_INPUT_NULL;
604
605 if (!u->description)
606 u->description = strdup("Root Mount");
607
608 return 1;
609 }
610
611 static int mount_load(Unit *u) {
612 Mount *m = MOUNT(u);
613 int r;
614
615 assert(u);
616 assert(u->load_state == UNIT_STUB);
617
618 r = mount_load_root_mount(u);
619 if (r < 0)
620 return r;
621
622 if (m->from_proc_self_mountinfo || u->perpetual)
623 r = unit_load_fragment_and_dropin_optional(u);
624 else
625 r = unit_load_fragment_and_dropin(u);
626 if (r < 0)
627 return r;
628
629 /* This is a new unit? Then let's add in some extras */
630 if (u->load_state == UNIT_LOADED) {
631 r = mount_add_extras(m);
632 if (r < 0)
633 return r;
634 }
635
636 return mount_verify(m);
637 }
638
639 static void mount_set_state(Mount *m, MountState state) {
640 MountState old_state;
641 assert(m);
642
643 old_state = m->state;
644 m->state = state;
645
646 if (!MOUNT_STATE_WITH_PROCESS(state)) {
647 m->timer_event_source = sd_event_source_unref(m->timer_event_source);
648 mount_unwatch_control_pid(m);
649 m->control_command = NULL;
650 m->control_command_id = _MOUNT_EXEC_COMMAND_INVALID;
651 }
652
653 if (state != old_state)
654 log_unit_debug(UNIT(m), "Changed %s -> %s", mount_state_to_string(old_state), mount_state_to_string(state));
655
656 unit_notify(UNIT(m), state_translation_table[old_state], state_translation_table[state],
657 m->reload_result == MOUNT_SUCCESS ? 0 : UNIT_NOTIFY_RELOAD_FAILURE);
658 }
659
660 static int mount_coldplug(Unit *u) {
661 Mount *m = MOUNT(u);
662 MountState new_state = MOUNT_DEAD;
663 int r;
664
665 assert(m);
666 assert(m->state == MOUNT_DEAD);
667
668 if (m->deserialized_state != m->state)
669 new_state = m->deserialized_state;
670 else if (m->from_proc_self_mountinfo)
671 new_state = MOUNT_MOUNTED;
672
673 if (new_state == m->state)
674 return 0;
675
676 if (m->control_pid > 0 &&
677 pid_is_unwaited(m->control_pid) &&
678 MOUNT_STATE_WITH_PROCESS(new_state)) {
679
680 r = unit_watch_pid(UNIT(m), m->control_pid);
681 if (r < 0)
682 return r;
683
684 r = mount_arm_timer(m, usec_add(u->state_change_timestamp.monotonic, m->timeout_usec));
685 if (r < 0)
686 return r;
687 }
688
689 if (!IN_SET(new_state, MOUNT_DEAD, MOUNT_FAILED)) {
690 (void) unit_setup_dynamic_creds(u);
691 (void) unit_setup_exec_runtime(u);
692 }
693
694 mount_set_state(m, new_state);
695 return 0;
696 }
697
698 static void mount_dump(Unit *u, FILE *f, const char *prefix) {
699 char buf[FORMAT_TIMESPAN_MAX];
700 Mount *m = MOUNT(u);
701 MountParameters *p;
702
703 assert(m);
704 assert(f);
705
706 p = get_mount_parameters(m);
707
708 fprintf(f,
709 "%sMount State: %s\n"
710 "%sResult: %s\n"
711 "%sWhere: %s\n"
712 "%sWhat: %s\n"
713 "%sFile System Type: %s\n"
714 "%sOptions: %s\n"
715 "%sFrom /proc/self/mountinfo: %s\n"
716 "%sFrom fragment: %s\n"
717 "%sExtrinsic: %s\n"
718 "%sDirectoryMode: %04o\n"
719 "%sSloppyOptions: %s\n"
720 "%sLazyUnmount: %s\n"
721 "%sForceUnmount: %s\n"
722 "%sTimoutSec: %s\n",
723 prefix, mount_state_to_string(m->state),
724 prefix, mount_result_to_string(m->result),
725 prefix, m->where,
726 prefix, p ? strna(p->what) : "n/a",
727 prefix, p ? strna(p->fstype) : "n/a",
728 prefix, p ? strna(p->options) : "n/a",
729 prefix, yes_no(m->from_proc_self_mountinfo),
730 prefix, yes_no(m->from_fragment),
731 prefix, yes_no(mount_is_extrinsic(m)),
732 prefix, m->directory_mode,
733 prefix, yes_no(m->sloppy_options),
734 prefix, yes_no(m->lazy_unmount),
735 prefix, yes_no(m->force_unmount),
736 prefix, format_timespan(buf, sizeof(buf), m->timeout_usec, USEC_PER_SEC));
737
738 if (m->control_pid > 0)
739 fprintf(f,
740 "%sControl PID: "PID_FMT"\n",
741 prefix, m->control_pid);
742
743 exec_context_dump(&m->exec_context, f, prefix);
744 kill_context_dump(&m->kill_context, f, prefix);
745 cgroup_context_dump(&m->cgroup_context, f, prefix);
746 }
747
748 static int mount_spawn(Mount *m, ExecCommand *c, pid_t *_pid) {
749
750 _cleanup_(exec_params_clear) ExecParameters exec_params = {
751 .flags = EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN,
752 .stdin_fd = -1,
753 .stdout_fd = -1,
754 .stderr_fd = -1,
755 .exec_fd = -1,
756 };
757 pid_t pid;
758 int r;
759
760 assert(m);
761 assert(c);
762 assert(_pid);
763
764 r = unit_prepare_exec(UNIT(m));
765 if (r < 0)
766 return r;
767
768 r = mount_arm_timer(m, usec_add(now(CLOCK_MONOTONIC), m->timeout_usec));
769 if (r < 0)
770 return r;
771
772 r = unit_set_exec_params(UNIT(m), &exec_params);
773 if (r < 0)
774 return r;
775
776 r = exec_spawn(UNIT(m),
777 c,
778 &m->exec_context,
779 &exec_params,
780 m->exec_runtime,
781 &m->dynamic_creds,
782 &pid);
783 if (r < 0)
784 return r;
785
786 r = unit_watch_pid(UNIT(m), pid);
787 if (r < 0)
788 /* FIXME: we need to do something here */
789 return r;
790
791 *_pid = pid;
792
793 return 0;
794 }
795
796 static void mount_enter_dead(Mount *m, MountResult f) {
797 assert(m);
798
799 if (m->result == MOUNT_SUCCESS)
800 m->result = f;
801
802 unit_log_result(UNIT(m), m->result == MOUNT_SUCCESS, mount_result_to_string(m->result));
803 mount_set_state(m, m->result != MOUNT_SUCCESS ? MOUNT_FAILED : MOUNT_DEAD);
804
805 m->exec_runtime = exec_runtime_unref(m->exec_runtime, true);
806
807 exec_context_destroy_runtime_directory(&m->exec_context, UNIT(m)->manager->prefix[EXEC_DIRECTORY_RUNTIME]);
808
809 unit_unref_uid_gid(UNIT(m), true);
810
811 dynamic_creds_destroy(&m->dynamic_creds);
812 }
813
814 static void mount_enter_mounted(Mount *m, MountResult f) {
815 assert(m);
816
817 if (m->result == MOUNT_SUCCESS)
818 m->result = f;
819
820 mount_set_state(m, MOUNT_MOUNTED);
821 }
822
823 static void mount_enter_dead_or_mounted(Mount *m, MountResult f) {
824 assert(m);
825
826 /* Enter DEAD or MOUNTED state, depending on what the kernel currently says about the mount point. We use this
827 * whenever we executed an operation, so that our internal state reflects what the kernel says again, after all
828 * ultimately we just mirror the kernel's internal state on this. */
829
830 if (m->from_proc_self_mountinfo)
831 mount_enter_mounted(m, f);
832 else
833 mount_enter_dead(m, f);
834 }
835
836 static int state_to_kill_operation(MountState state) {
837 switch (state) {
838
839 case MOUNT_REMOUNTING_SIGTERM:
840 case MOUNT_UNMOUNTING_SIGTERM:
841 return KILL_TERMINATE;
842
843 case MOUNT_REMOUNTING_SIGKILL:
844 case MOUNT_UNMOUNTING_SIGKILL:
845 return KILL_KILL;
846
847 default:
848 return _KILL_OPERATION_INVALID;
849 }
850 }
851
852 static void mount_enter_signal(Mount *m, MountState state, MountResult f) {
853 int r;
854
855 assert(m);
856
857 if (m->result == MOUNT_SUCCESS)
858 m->result = f;
859
860 r = unit_kill_context(
861 UNIT(m),
862 &m->kill_context,
863 state_to_kill_operation(state),
864 -1,
865 m->control_pid,
866 false);
867 if (r < 0)
868 goto fail;
869
870 if (r > 0) {
871 r = mount_arm_timer(m, usec_add(now(CLOCK_MONOTONIC), m->timeout_usec));
872 if (r < 0)
873 goto fail;
874
875 mount_set_state(m, state);
876 } else if (state == MOUNT_REMOUNTING_SIGTERM && m->kill_context.send_sigkill)
877 mount_enter_signal(m, MOUNT_REMOUNTING_SIGKILL, MOUNT_SUCCESS);
878 else if (IN_SET(state, MOUNT_REMOUNTING_SIGTERM, MOUNT_REMOUNTING_SIGKILL))
879 mount_enter_mounted(m, MOUNT_SUCCESS);
880 else if (state == MOUNT_UNMOUNTING_SIGTERM && m->kill_context.send_sigkill)
881 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGKILL, MOUNT_SUCCESS);
882 else
883 mount_enter_dead_or_mounted(m, MOUNT_SUCCESS);
884
885 return;
886
887 fail:
888 log_unit_warning_errno(UNIT(m), r, "Failed to kill processes: %m");
889 mount_enter_dead_or_mounted(m, MOUNT_FAILURE_RESOURCES);
890 }
891
892 static void mount_enter_unmounting(Mount *m) {
893 int r;
894
895 assert(m);
896
897 /* Start counting our attempts */
898 if (!IN_SET(m->state,
899 MOUNT_UNMOUNTING,
900 MOUNT_UNMOUNTING_SIGTERM,
901 MOUNT_UNMOUNTING_SIGKILL))
902 m->n_retry_umount = 0;
903
904 m->control_command_id = MOUNT_EXEC_UNMOUNT;
905 m->control_command = m->exec_command + MOUNT_EXEC_UNMOUNT;
906
907 r = exec_command_set(m->control_command, UMOUNT_PATH, m->where, "-c", NULL);
908 if (r >= 0 && m->lazy_unmount)
909 r = exec_command_append(m->control_command, "-l", NULL);
910 if (r >= 0 && m->force_unmount)
911 r = exec_command_append(m->control_command, "-f", NULL);
912 if (r < 0)
913 goto fail;
914
915 mount_unwatch_control_pid(m);
916
917 r = mount_spawn(m, m->control_command, &m->control_pid);
918 if (r < 0)
919 goto fail;
920
921 mount_set_state(m, MOUNT_UNMOUNTING);
922
923 return;
924
925 fail:
926 log_unit_warning_errno(UNIT(m), r, "Failed to run 'umount' task: %m");
927 mount_enter_dead_or_mounted(m, MOUNT_FAILURE_RESOURCES);
928 }
929
930 static void mount_enter_mounting(Mount *m) {
931 int r;
932 MountParameters *p;
933
934 assert(m);
935
936 r = unit_fail_if_noncanonical(UNIT(m), m->where);
937 if (r < 0)
938 goto fail;
939
940 (void) mkdir_p_label(m->where, m->directory_mode);
941
942 unit_warn_if_dir_nonempty(UNIT(m), m->where);
943
944 unit_warn_leftover_processes(UNIT(m));
945
946 m->control_command_id = MOUNT_EXEC_MOUNT;
947 m->control_command = m->exec_command + MOUNT_EXEC_MOUNT;
948
949 /* Create the source directory for bind-mounts if needed */
950 p = get_mount_parameters_fragment(m);
951 if (p && mount_is_bind(p))
952 (void) mkdir_p_label(p->what, m->directory_mode);
953
954 if (p) {
955 _cleanup_free_ char *opts = NULL;
956
957 r = fstab_filter_options(p->options, "nofail\0" "noauto\0" "auto\0", NULL, NULL, &opts);
958 if (r < 0)
959 goto fail;
960
961 r = exec_command_set(m->control_command, MOUNT_PATH, p->what, m->where, NULL);
962 if (r >= 0 && m->sloppy_options)
963 r = exec_command_append(m->control_command, "-s", NULL);
964 if (r >= 0 && p->fstype)
965 r = exec_command_append(m->control_command, "-t", p->fstype, NULL);
966 if (r >= 0 && !isempty(opts))
967 r = exec_command_append(m->control_command, "-o", opts, NULL);
968 } else
969 r = -ENOENT;
970 if (r < 0)
971 goto fail;
972
973 mount_unwatch_control_pid(m);
974
975 r = mount_spawn(m, m->control_command, &m->control_pid);
976 if (r < 0)
977 goto fail;
978
979 mount_set_state(m, MOUNT_MOUNTING);
980
981 return;
982
983 fail:
984 log_unit_warning_errno(UNIT(m), r, "Failed to run 'mount' task: %m");
985 mount_enter_dead_or_mounted(m, MOUNT_FAILURE_RESOURCES);
986 }
987
988 static void mount_set_reload_result(Mount *m, MountResult result) {
989 assert(m);
990
991 /* Only store the first error we encounter */
992 if (m->reload_result != MOUNT_SUCCESS)
993 return;
994
995 m->reload_result = result;
996 }
997
998 static void mount_enter_remounting(Mount *m) {
999 int r;
1000 MountParameters *p;
1001
1002 assert(m);
1003
1004 /* Reset reload result when we are about to start a new remount operation */
1005 m->reload_result = MOUNT_SUCCESS;
1006
1007 m->control_command_id = MOUNT_EXEC_REMOUNT;
1008 m->control_command = m->exec_command + MOUNT_EXEC_REMOUNT;
1009
1010 p = get_mount_parameters_fragment(m);
1011 if (p) {
1012 const char *o;
1013
1014 if (p->options)
1015 o = strjoina("remount,", p->options);
1016 else
1017 o = "remount";
1018
1019 r = exec_command_set(m->control_command, MOUNT_PATH,
1020 p->what, m->where,
1021 "-o", o, NULL);
1022 if (r >= 0 && m->sloppy_options)
1023 r = exec_command_append(m->control_command, "-s", NULL);
1024 if (r >= 0 && p->fstype)
1025 r = exec_command_append(m->control_command, "-t", p->fstype, NULL);
1026 } else
1027 r = -ENOENT;
1028 if (r < 0)
1029 goto fail;
1030
1031 mount_unwatch_control_pid(m);
1032
1033 r = mount_spawn(m, m->control_command, &m->control_pid);
1034 if (r < 0)
1035 goto fail;
1036
1037 mount_set_state(m, MOUNT_REMOUNTING);
1038
1039 return;
1040
1041 fail:
1042 log_unit_warning_errno(UNIT(m), r, "Failed to run 'remount' task: %m");
1043 mount_set_reload_result(m, MOUNT_FAILURE_RESOURCES);
1044 mount_enter_dead_or_mounted(m, MOUNT_SUCCESS);
1045 }
1046
1047 static int mount_start(Unit *u) {
1048 Mount *m = MOUNT(u);
1049 int r;
1050
1051 assert(m);
1052
1053 /* We cannot fulfill this request right now, try again later
1054 * please! */
1055 if (IN_SET(m->state,
1056 MOUNT_UNMOUNTING,
1057 MOUNT_UNMOUNTING_SIGTERM,
1058 MOUNT_UNMOUNTING_SIGKILL))
1059 return -EAGAIN;
1060
1061 /* Already on it! */
1062 if (m->state == MOUNT_MOUNTING)
1063 return 0;
1064
1065 assert(IN_SET(m->state, MOUNT_DEAD, MOUNT_FAILED));
1066
1067 r = unit_start_limit_test(u);
1068 if (r < 0) {
1069 mount_enter_dead(m, MOUNT_FAILURE_START_LIMIT_HIT);
1070 return r;
1071 }
1072
1073 r = unit_acquire_invocation_id(u);
1074 if (r < 0)
1075 return r;
1076
1077 m->result = MOUNT_SUCCESS;
1078 m->reload_result = MOUNT_SUCCESS;
1079 exec_command_reset_status_array(m->exec_command, _MOUNT_EXEC_COMMAND_MAX);
1080
1081 u->reset_accounting = true;
1082
1083 mount_enter_mounting(m);
1084 return 1;
1085 }
1086
1087 static int mount_stop(Unit *u) {
1088 Mount *m = MOUNT(u);
1089
1090 assert(m);
1091
1092 switch (m->state) {
1093
1094 case MOUNT_UNMOUNTING:
1095 case MOUNT_UNMOUNTING_SIGKILL:
1096 case MOUNT_UNMOUNTING_SIGTERM:
1097 /* Already on it */
1098 return 0;
1099
1100 case MOUNT_MOUNTING:
1101 case MOUNT_MOUNTING_DONE:
1102 case MOUNT_REMOUNTING:
1103 /* If we are still waiting for /bin/mount, we go directly into kill mode. */
1104 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGTERM, MOUNT_SUCCESS);
1105 return 0;
1106
1107 case MOUNT_REMOUNTING_SIGTERM:
1108 /* If we are already waiting for a hung remount, convert this to the matching unmounting state */
1109 mount_set_state(m, MOUNT_UNMOUNTING_SIGTERM);
1110 return 0;
1111
1112 case MOUNT_REMOUNTING_SIGKILL:
1113 /* as above */
1114 mount_set_state(m, MOUNT_UNMOUNTING_SIGKILL);
1115 return 0;
1116
1117 case MOUNT_MOUNTED:
1118 mount_enter_unmounting(m);
1119 return 1;
1120
1121 default:
1122 assert_not_reached("Unexpected state.");
1123 }
1124 }
1125
1126 static int mount_reload(Unit *u) {
1127 Mount *m = MOUNT(u);
1128
1129 assert(m);
1130 assert(m->state == MOUNT_MOUNTED);
1131
1132 mount_enter_remounting(m);
1133
1134 return 1;
1135 }
1136
1137 static int mount_serialize(Unit *u, FILE *f, FDSet *fds) {
1138 Mount *m = MOUNT(u);
1139
1140 assert(m);
1141 assert(f);
1142 assert(fds);
1143
1144 (void) serialize_item(f, "state", mount_state_to_string(m->state));
1145 (void) serialize_item(f, "result", mount_result_to_string(m->result));
1146 (void) serialize_item(f, "reload-result", mount_result_to_string(m->reload_result));
1147
1148 if (m->control_pid > 0)
1149 (void) serialize_item_format(f, "control-pid", PID_FMT, m->control_pid);
1150
1151 if (m->control_command_id >= 0)
1152 (void) serialize_item(f, "control-command", mount_exec_command_to_string(m->control_command_id));
1153
1154 return 0;
1155 }
1156
1157 static int mount_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1158 Mount *m = MOUNT(u);
1159
1160 assert(u);
1161 assert(key);
1162 assert(value);
1163 assert(fds);
1164
1165 if (streq(key, "state")) {
1166 MountState state;
1167
1168 if ((state = mount_state_from_string(value)) < 0)
1169 log_unit_debug(u, "Failed to parse state value: %s", value);
1170 else
1171 m->deserialized_state = state;
1172 } else if (streq(key, "result")) {
1173 MountResult f;
1174
1175 f = mount_result_from_string(value);
1176 if (f < 0)
1177 log_unit_debug(u, "Failed to parse result value: %s", value);
1178 else if (f != MOUNT_SUCCESS)
1179 m->result = f;
1180
1181 } else if (streq(key, "reload-result")) {
1182 MountResult f;
1183
1184 f = mount_result_from_string(value);
1185 if (f < 0)
1186 log_unit_debug(u, "Failed to parse reload result value: %s", value);
1187 else if (f != MOUNT_SUCCESS)
1188 m->reload_result = f;
1189
1190 } else if (streq(key, "control-pid")) {
1191 pid_t pid;
1192
1193 if (parse_pid(value, &pid) < 0)
1194 log_unit_debug(u, "Failed to parse control-pid value: %s", value);
1195 else
1196 m->control_pid = pid;
1197 } else if (streq(key, "control-command")) {
1198 MountExecCommand id;
1199
1200 id = mount_exec_command_from_string(value);
1201 if (id < 0)
1202 log_unit_debug(u, "Failed to parse exec-command value: %s", value);
1203 else {
1204 m->control_command_id = id;
1205 m->control_command = m->exec_command + id;
1206 }
1207 } else
1208 log_unit_debug(u, "Unknown serialization key: %s", key);
1209
1210 return 0;
1211 }
1212
1213 _pure_ static UnitActiveState mount_active_state(Unit *u) {
1214 assert(u);
1215
1216 return state_translation_table[MOUNT(u)->state];
1217 }
1218
1219 _pure_ static const char *mount_sub_state_to_string(Unit *u) {
1220 assert(u);
1221
1222 return mount_state_to_string(MOUNT(u)->state);
1223 }
1224
1225 _pure_ static bool mount_may_gc(Unit *u) {
1226 Mount *m = MOUNT(u);
1227
1228 assert(m);
1229
1230 if (m->from_proc_self_mountinfo)
1231 return false;
1232
1233 return true;
1234 }
1235
1236 static void mount_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1237 Mount *m = MOUNT(u);
1238 MountResult f;
1239
1240 assert(m);
1241 assert(pid >= 0);
1242
1243 if (pid != m->control_pid)
1244 return;
1245
1246 m->control_pid = 0;
1247
1248 if (is_clean_exit(code, status, EXIT_CLEAN_COMMAND, NULL))
1249 f = MOUNT_SUCCESS;
1250 else if (code == CLD_EXITED)
1251 f = MOUNT_FAILURE_EXIT_CODE;
1252 else if (code == CLD_KILLED)
1253 f = MOUNT_FAILURE_SIGNAL;
1254 else if (code == CLD_DUMPED)
1255 f = MOUNT_FAILURE_CORE_DUMP;
1256 else
1257 assert_not_reached("Unknown code");
1258
1259 if (IN_SET(m->state, MOUNT_REMOUNTING, MOUNT_REMOUNTING_SIGKILL, MOUNT_REMOUNTING_SIGTERM))
1260 mount_set_reload_result(m, f);
1261 else if (m->result == MOUNT_SUCCESS)
1262 m->result = f;
1263
1264 if (m->control_command) {
1265 exec_status_exit(&m->control_command->exec_status, &m->exec_context, pid, code, status);
1266
1267 m->control_command = NULL;
1268 m->control_command_id = _MOUNT_EXEC_COMMAND_INVALID;
1269 }
1270
1271 unit_log_process_exit(
1272 u, f == MOUNT_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
1273 "Mount process",
1274 mount_exec_command_to_string(m->control_command_id),
1275 code, status);
1276
1277 /* Note that due to the io event priority logic, we can be sure the new mountinfo is loaded
1278 * before we process the SIGCHLD for the mount command. */
1279
1280 switch (m->state) {
1281
1282 case MOUNT_MOUNTING:
1283 /* Our mount point has not appeared in mountinfo. Something went wrong. */
1284
1285 if (f == MOUNT_SUCCESS) {
1286 /* Either /bin/mount has an unexpected definition of success,
1287 * or someone raced us and we lost. */
1288 log_unit_warning(UNIT(m), "Mount process finished, but there is no mount.");
1289 f = MOUNT_FAILURE_PROTOCOL;
1290 }
1291 mount_enter_dead(m, f);
1292 break;
1293
1294 case MOUNT_MOUNTING_DONE:
1295 mount_enter_mounted(m, f);
1296 break;
1297
1298 case MOUNT_REMOUNTING:
1299 case MOUNT_REMOUNTING_SIGTERM:
1300 case MOUNT_REMOUNTING_SIGKILL:
1301 mount_enter_dead_or_mounted(m, MOUNT_SUCCESS);
1302 break;
1303
1304 case MOUNT_UNMOUNTING:
1305
1306 if (f == MOUNT_SUCCESS && m->from_proc_self_mountinfo) {
1307
1308 /* Still a mount point? If so, let's try again. Most likely there were multiple mount points
1309 * stacked on top of each other. We might exceed the timeout specified by the user overall,
1310 * but we will stop as soon as any one umount times out. */
1311
1312 if (m->n_retry_umount < RETRY_UMOUNT_MAX) {
1313 log_unit_debug(u, "Mount still present, trying again.");
1314 m->n_retry_umount++;
1315 mount_enter_unmounting(m);
1316 } else {
1317 log_unit_warning(u, "Mount still present after %u attempts to unmount, giving up.", m->n_retry_umount);
1318 mount_enter_mounted(m, f);
1319 }
1320 } else
1321 mount_enter_dead_or_mounted(m, f);
1322
1323 break;
1324
1325 case MOUNT_UNMOUNTING_SIGKILL:
1326 case MOUNT_UNMOUNTING_SIGTERM:
1327 mount_enter_dead_or_mounted(m, f);
1328 break;
1329
1330 default:
1331 assert_not_reached("Uh, control process died at wrong time.");
1332 }
1333
1334 /* Notify clients about changed exit status */
1335 unit_add_to_dbus_queue(u);
1336 }
1337
1338 static int mount_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
1339 Mount *m = MOUNT(userdata);
1340
1341 assert(m);
1342 assert(m->timer_event_source == source);
1343
1344 switch (m->state) {
1345
1346 case MOUNT_MOUNTING:
1347 case MOUNT_MOUNTING_DONE:
1348 log_unit_warning(UNIT(m), "Mounting timed out. Terminating.");
1349 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGTERM, MOUNT_FAILURE_TIMEOUT);
1350 break;
1351
1352 case MOUNT_REMOUNTING:
1353 log_unit_warning(UNIT(m), "Remounting timed out. Terminating remount process.");
1354 mount_set_reload_result(m, MOUNT_FAILURE_TIMEOUT);
1355 mount_enter_signal(m, MOUNT_REMOUNTING_SIGTERM, MOUNT_SUCCESS);
1356 break;
1357
1358 case MOUNT_REMOUNTING_SIGTERM:
1359 mount_set_reload_result(m, MOUNT_FAILURE_TIMEOUT);
1360
1361 if (m->kill_context.send_sigkill) {
1362 log_unit_warning(UNIT(m), "Remounting timed out. Killing.");
1363 mount_enter_signal(m, MOUNT_REMOUNTING_SIGKILL, MOUNT_SUCCESS);
1364 } else {
1365 log_unit_warning(UNIT(m), "Remounting timed out. Skipping SIGKILL. Ignoring.");
1366 mount_enter_dead_or_mounted(m, MOUNT_SUCCESS);
1367 }
1368 break;
1369
1370 case MOUNT_REMOUNTING_SIGKILL:
1371 mount_set_reload_result(m, MOUNT_FAILURE_TIMEOUT);
1372
1373 log_unit_warning(UNIT(m), "Mount process still around after SIGKILL. Ignoring.");
1374 mount_enter_dead_or_mounted(m, MOUNT_SUCCESS);
1375 break;
1376
1377 case MOUNT_UNMOUNTING:
1378 log_unit_warning(UNIT(m), "Unmounting timed out. Terminating.");
1379 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGTERM, MOUNT_FAILURE_TIMEOUT);
1380 break;
1381
1382 case MOUNT_UNMOUNTING_SIGTERM:
1383 if (m->kill_context.send_sigkill) {
1384 log_unit_warning(UNIT(m), "Mount process timed out. Killing.");
1385 mount_enter_signal(m, MOUNT_UNMOUNTING_SIGKILL, MOUNT_FAILURE_TIMEOUT);
1386 } else {
1387 log_unit_warning(UNIT(m), "Mount process timed out. Skipping SIGKILL. Ignoring.");
1388 mount_enter_dead_or_mounted(m, MOUNT_FAILURE_TIMEOUT);
1389 }
1390 break;
1391
1392 case MOUNT_UNMOUNTING_SIGKILL:
1393 log_unit_warning(UNIT(m), "Mount process still around after SIGKILL. Ignoring.");
1394 mount_enter_dead_or_mounted(m, MOUNT_FAILURE_TIMEOUT);
1395 break;
1396
1397 default:
1398 assert_not_reached("Timeout at wrong time.");
1399 }
1400
1401 return 0;
1402 }
1403
1404 typedef struct {
1405 bool is_mounted;
1406 bool just_mounted;
1407 bool just_changed;
1408 } MountSetupFlags;
1409
1410 static int mount_setup_new_unit(
1411 Unit *u,
1412 const char *what,
1413 const char *where,
1414 const char *options,
1415 const char *fstype,
1416 MountSetupFlags *flags) {
1417
1418 MountParameters *p;
1419
1420 assert(u);
1421 assert(flags);
1422
1423 u->source_path = strdup("/proc/self/mountinfo");
1424 MOUNT(u)->where = strdup(where);
1425 if (!u->source_path || !MOUNT(u)->where)
1426 return -ENOMEM;
1427
1428 /* Make sure to initialize those fields before mount_is_extrinsic(). */
1429 MOUNT(u)->from_proc_self_mountinfo = true;
1430 p = &MOUNT(u)->parameters_proc_self_mountinfo;
1431
1432 p->what = strdup(what);
1433 p->options = strdup(options);
1434 p->fstype = strdup(fstype);
1435 if (!p->what || !p->options || !p->fstype)
1436 return -ENOMEM;
1437
1438 if (!mount_is_extrinsic(MOUNT(u))) {
1439 const char *target;
1440 int r;
1441
1442 target = mount_is_network(p) ? SPECIAL_REMOTE_FS_TARGET : SPECIAL_LOCAL_FS_TARGET;
1443 r = unit_add_dependency_by_name(u, UNIT_BEFORE, target, true, UNIT_DEPENDENCY_MOUNTINFO_IMPLICIT);
1444 if (r < 0)
1445 return r;
1446
1447 r = unit_add_dependency_by_name(u, UNIT_CONFLICTS, SPECIAL_UMOUNT_TARGET, true, UNIT_DEPENDENCY_MOUNTINFO_IMPLICIT);
1448 if (r < 0)
1449 return r;
1450 }
1451
1452 unit_add_to_load_queue(u);
1453 flags->is_mounted = true;
1454 flags->just_mounted = true;
1455 flags->just_changed = true;
1456
1457 return 0;
1458 }
1459
1460 static int mount_setup_existing_unit(
1461 Unit *u,
1462 const char *what,
1463 const char *where,
1464 const char *options,
1465 const char *fstype,
1466 MountSetupFlags *flags) {
1467
1468 MountParameters *p;
1469 bool load_extras = false;
1470 int r1, r2, r3;
1471
1472 assert(u);
1473 assert(flags);
1474
1475 if (!MOUNT(u)->where) {
1476 MOUNT(u)->where = strdup(where);
1477 if (!MOUNT(u)->where)
1478 return -ENOMEM;
1479 }
1480
1481 /* Make sure to initialize those fields before mount_is_extrinsic(). */
1482 p = &MOUNT(u)->parameters_proc_self_mountinfo;
1483
1484 r1 = free_and_strdup(&p->what, what);
1485 r2 = free_and_strdup(&p->options, options);
1486 r3 = free_and_strdup(&p->fstype, fstype);
1487 if (r1 < 0 || r2 < 0 || r3 < 0)
1488 return -ENOMEM;
1489
1490 flags->just_changed = r1 > 0 || r2 > 0 || r3 > 0;
1491 flags->is_mounted = true;
1492 flags->just_mounted = !MOUNT(u)->from_proc_self_mountinfo || MOUNT(u)->just_mounted;
1493
1494 MOUNT(u)->from_proc_self_mountinfo = true;
1495
1496 if (!mount_is_extrinsic(MOUNT(u)) && mount_is_network(p)) {
1497 /* _netdev option may have shown up late, or on a
1498 * remount. Add remote-fs dependencies, even though
1499 * local-fs ones may already be there.
1500 *
1501 * Note: due to a current limitation (we don't track
1502 * in the dependency "Set*" objects who created a
1503 * dependency), we can only add deps, never lose them,
1504 * until the next full daemon-reload. */
1505 unit_add_dependency_by_name(u, UNIT_BEFORE, SPECIAL_REMOTE_FS_TARGET, true, UNIT_DEPENDENCY_MOUNTINFO_IMPLICIT);
1506 load_extras = true;
1507 }
1508
1509 if (u->load_state == UNIT_NOT_FOUND) {
1510 u->load_state = UNIT_LOADED;
1511 u->load_error = 0;
1512
1513 /* Load in the extras later on, after we
1514 * finished initialization of the unit */
1515
1516 /* FIXME: since we're going to load the unit later on, why setting load_extras=true ? */
1517 load_extras = true;
1518 flags->just_changed = true;
1519 }
1520
1521 if (load_extras)
1522 return mount_add_extras(MOUNT(u));
1523
1524 return 0;
1525 }
1526
1527 static int mount_setup_unit(
1528 Manager *m,
1529 const char *what,
1530 const char *where,
1531 const char *options,
1532 const char *fstype,
1533 bool set_flags) {
1534
1535 _cleanup_free_ char *e = NULL;
1536 MountSetupFlags flags;
1537 Unit *u;
1538 int r;
1539
1540 assert(m);
1541 assert(what);
1542 assert(where);
1543 assert(options);
1544 assert(fstype);
1545
1546 /* Ignore API mount points. They should never be referenced in
1547 * dependencies ever. */
1548 if (mount_point_is_api(where) || mount_point_ignore(where))
1549 return 0;
1550
1551 if (streq(fstype, "autofs"))
1552 return 0;
1553
1554 /* probably some kind of swap, ignore */
1555 if (!is_path(where))
1556 return 0;
1557
1558 r = unit_name_from_path(where, ".mount", &e);
1559 if (r < 0)
1560 return r;
1561
1562 u = manager_get_unit(m, e);
1563 if (!u) {
1564 /* First time we see this mount point meaning that it's
1565 * not been initiated by a mount unit but rather by the
1566 * sysadmin having called mount(8) directly. */
1567 r = unit_new_for_name(m, sizeof(Mount), e, &u);
1568 if (r < 0)
1569 goto fail;
1570
1571 r = mount_setup_new_unit(u, what, where, options, fstype, &flags);
1572 if (r < 0)
1573 unit_free(u);
1574 } else
1575 r = mount_setup_existing_unit(u, what, where, options, fstype, &flags);
1576
1577 if (r < 0)
1578 goto fail;
1579
1580 if (set_flags) {
1581 MOUNT(u)->is_mounted = flags.is_mounted;
1582 MOUNT(u)->just_mounted = flags.just_mounted;
1583 MOUNT(u)->just_changed = flags.just_changed;
1584 }
1585
1586 if (flags.just_changed)
1587 unit_add_to_dbus_queue(u);
1588
1589 return 0;
1590 fail:
1591 return log_warning_errno(r, "Failed to set up mount unit: %m");
1592 }
1593
1594 static int mount_load_proc_self_mountinfo(Manager *m, bool set_flags) {
1595 _cleanup_(mnt_free_tablep) struct libmnt_table *t = NULL;
1596 _cleanup_(mnt_free_iterp) struct libmnt_iter *i = NULL;
1597 int r = 0;
1598
1599 assert(m);
1600
1601 t = mnt_new_table();
1602 i = mnt_new_iter(MNT_ITER_FORWARD);
1603 if (!t || !i)
1604 return log_oom();
1605
1606 r = mnt_table_parse_mtab(t, NULL);
1607 if (r < 0)
1608 return log_error_errno(r, "Failed to parse /proc/self/mountinfo: %m");
1609
1610 r = 0;
1611 for (;;) {
1612 struct libmnt_fs *fs;
1613 const char *device, *path, *options, *fstype;
1614 _cleanup_free_ char *d = NULL, *p = NULL;
1615 int k;
1616
1617 k = mnt_table_next_fs(t, i, &fs);
1618 if (k == 1)
1619 break;
1620 if (k < 0)
1621 return log_error_errno(k, "Failed to get next entry from /proc/self/mountinfo: %m");
1622
1623 device = mnt_fs_get_source(fs);
1624 path = mnt_fs_get_target(fs);
1625 options = mnt_fs_get_options(fs);
1626 fstype = mnt_fs_get_fstype(fs);
1627
1628 if (!device || !path)
1629 continue;
1630
1631 if (cunescape(device, UNESCAPE_RELAX, &d) < 0)
1632 return log_oom();
1633
1634 if (cunescape(path, UNESCAPE_RELAX, &p) < 0)
1635 return log_oom();
1636
1637 device_found_node(m, d, DEVICE_FOUND_MOUNT, DEVICE_FOUND_MOUNT);
1638
1639 k = mount_setup_unit(m, d, p, options, fstype, set_flags);
1640 if (r == 0 && k < 0)
1641 r = k;
1642 }
1643
1644 return r;
1645 }
1646
1647 static void mount_shutdown(Manager *m) {
1648 assert(m);
1649
1650 m->mount_event_source = sd_event_source_unref(m->mount_event_source);
1651
1652 mnt_unref_monitor(m->mount_monitor);
1653 m->mount_monitor = NULL;
1654 }
1655
1656 static int mount_get_timeout(Unit *u, usec_t *timeout) {
1657 Mount *m = MOUNT(u);
1658 usec_t t;
1659 int r;
1660
1661 if (!m->timer_event_source)
1662 return 0;
1663
1664 r = sd_event_source_get_time(m->timer_event_source, &t);
1665 if (r < 0)
1666 return r;
1667 if (t == USEC_INFINITY)
1668 return 0;
1669
1670 *timeout = t;
1671 return 1;
1672 }
1673
1674 static void mount_enumerate_perpetual(Manager *m) {
1675 Unit *u;
1676 int r;
1677
1678 assert(m);
1679
1680 /* Whatever happens, we know for sure that the root directory is around, and cannot go away. Let's
1681 * unconditionally synthesize it here and mark it as perpetual. */
1682
1683 u = manager_get_unit(m, SPECIAL_ROOT_MOUNT);
1684 if (!u) {
1685 r = unit_new_for_name(m, sizeof(Mount), SPECIAL_ROOT_MOUNT, &u);
1686 if (r < 0) {
1687 log_error_errno(r, "Failed to allocate the special " SPECIAL_ROOT_MOUNT " unit: %m");
1688 return;
1689 }
1690 }
1691
1692 u->perpetual = true;
1693 MOUNT(u)->deserialized_state = MOUNT_MOUNTED;
1694
1695 unit_add_to_load_queue(u);
1696 unit_add_to_dbus_queue(u);
1697 }
1698
1699 static bool mount_is_mounted(Mount *m) {
1700 assert(m);
1701
1702 return UNIT(m)->perpetual || m->is_mounted;
1703 }
1704
1705 static void mount_enumerate(Manager *m) {
1706 int r;
1707
1708 assert(m);
1709
1710 mnt_init_debug(0);
1711
1712 if (!m->mount_monitor) {
1713 int fd;
1714
1715 m->mount_monitor = mnt_new_monitor();
1716 if (!m->mount_monitor) {
1717 log_oom();
1718 goto fail;
1719 }
1720
1721 r = mnt_monitor_enable_kernel(m->mount_monitor, 1);
1722 if (r < 0) {
1723 log_error_errno(r, "Failed to enable watching of kernel mount events: %m");
1724 goto fail;
1725 }
1726
1727 r = mnt_monitor_enable_userspace(m->mount_monitor, 1, NULL);
1728 if (r < 0) {
1729 log_error_errno(r, "Failed to enable watching of userspace mount events: %m");
1730 goto fail;
1731 }
1732
1733 /* mnt_unref_monitor() will close the fd */
1734 fd = r = mnt_monitor_get_fd(m->mount_monitor);
1735 if (r < 0) {
1736 log_error_errno(r, "Failed to acquire watch file descriptor: %m");
1737 goto fail;
1738 }
1739
1740 r = sd_event_add_io(m->event, &m->mount_event_source, fd, EPOLLIN, mount_dispatch_io, m);
1741 if (r < 0) {
1742 log_error_errno(r, "Failed to watch mount file descriptor: %m");
1743 goto fail;
1744 }
1745
1746 r = sd_event_source_set_priority(m->mount_event_source, SD_EVENT_PRIORITY_NORMAL-10);
1747 if (r < 0) {
1748 log_error_errno(r, "Failed to adjust mount watch priority: %m");
1749 goto fail;
1750 }
1751
1752 (void) sd_event_source_set_description(m->mount_event_source, "mount-monitor-dispatch");
1753 }
1754
1755 r = mount_load_proc_self_mountinfo(m, false);
1756 if (r < 0)
1757 goto fail;
1758
1759 return;
1760
1761 fail:
1762 mount_shutdown(m);
1763 }
1764
1765 static int mount_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
1766 _cleanup_set_free_ Set *around = NULL, *gone = NULL;
1767 Manager *m = userdata;
1768 const char *what;
1769 Iterator i;
1770 Unit *u;
1771 int r;
1772
1773 assert(m);
1774 assert(revents & EPOLLIN);
1775
1776 if (fd == mnt_monitor_get_fd(m->mount_monitor)) {
1777 bool rescan = false;
1778
1779 /* Drain all events and verify that the event is valid.
1780 *
1781 * Note that libmount also monitors /run/mount mkdir if the
1782 * directory does not exist yet. The mkdir may generate event
1783 * which is irrelevant for us.
1784 *
1785 * error: r < 0; valid: r == 0, false positive: rc == 1 */
1786 do {
1787 r = mnt_monitor_next_change(m->mount_monitor, NULL, NULL);
1788 if (r == 0)
1789 rescan = true;
1790 else if (r < 0)
1791 return log_error_errno(r, "Failed to drain libmount events: %m");
1792 } while (r == 0);
1793
1794 log_debug("libmount event [rescan: %s]", yes_no(rescan));
1795 if (!rescan)
1796 return 0;
1797 }
1798
1799 r = mount_load_proc_self_mountinfo(m, true);
1800 if (r < 0) {
1801 /* Reset flags, just in case, for later calls */
1802 LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_MOUNT]) {
1803 Mount *mount = MOUNT(u);
1804
1805 mount->is_mounted = mount->just_mounted = mount->just_changed = false;
1806 }
1807
1808 return 0;
1809 }
1810
1811 manager_dispatch_load_queue(m);
1812
1813 LIST_FOREACH(units_by_type, u, m->units_by_type[UNIT_MOUNT]) {
1814 Mount *mount = MOUNT(u);
1815
1816 if (!mount_is_mounted(mount)) {
1817
1818 /* A mount point is not around right now. It
1819 * might be gone, or might never have
1820 * existed. */
1821
1822 if (mount->from_proc_self_mountinfo &&
1823 mount->parameters_proc_self_mountinfo.what) {
1824
1825 /* Remember that this device might just have disappeared */
1826 if (set_ensure_allocated(&gone, &path_hash_ops) < 0 ||
1827 set_put(gone, mount->parameters_proc_self_mountinfo.what) < 0)
1828 log_oom(); /* we don't care too much about OOM here... */
1829 }
1830
1831 mount->from_proc_self_mountinfo = false;
1832
1833 switch (mount->state) {
1834
1835 case MOUNT_MOUNTED:
1836 /* This has just been unmounted by
1837 * somebody else, follow the state
1838 * change. */
1839 mount->result = MOUNT_SUCCESS; /* make sure we forget any earlier umount failures */
1840 mount_enter_dead(mount, MOUNT_SUCCESS);
1841 break;
1842
1843 default:
1844 break;
1845 }
1846
1847 } else if (mount->just_mounted || mount->just_changed) {
1848
1849 /* A mount point was added or changed */
1850
1851 switch (mount->state) {
1852
1853 case MOUNT_DEAD:
1854 case MOUNT_FAILED:
1855
1856 /* This has just been mounted by somebody else, follow the state change, but let's
1857 * generate a new invocation ID for this implicitly and automatically. */
1858 (void) unit_acquire_invocation_id(UNIT(mount));
1859 mount_enter_mounted(mount, MOUNT_SUCCESS);
1860 break;
1861
1862 case MOUNT_MOUNTING:
1863 mount_set_state(mount, MOUNT_MOUNTING_DONE);
1864 break;
1865
1866 default:
1867 /* Nothing really changed, but let's
1868 * issue an notification call
1869 * nonetheless, in case somebody is
1870 * waiting for this. (e.g. file system
1871 * ro/rw remounts.) */
1872 mount_set_state(mount, mount->state);
1873 break;
1874 }
1875 }
1876
1877 if (mount_is_mounted(mount) &&
1878 mount->from_proc_self_mountinfo &&
1879 mount->parameters_proc_self_mountinfo.what) {
1880
1881 if (set_ensure_allocated(&around, &path_hash_ops) < 0 ||
1882 set_put(around, mount->parameters_proc_self_mountinfo.what) < 0)
1883 log_oom();
1884 }
1885
1886 /* Reset the flags for later calls */
1887 mount->is_mounted = mount->just_mounted = mount->just_changed = false;
1888 }
1889
1890 SET_FOREACH(what, gone, i) {
1891 if (set_contains(around, what))
1892 continue;
1893
1894 /* Let the device units know that the device is no longer mounted */
1895 device_found_node(m, what, 0, DEVICE_FOUND_MOUNT);
1896 }
1897
1898 return 0;
1899 }
1900
1901 static void mount_reset_failed(Unit *u) {
1902 Mount *m = MOUNT(u);
1903
1904 assert(m);
1905
1906 if (m->state == MOUNT_FAILED)
1907 mount_set_state(m, MOUNT_DEAD);
1908
1909 m->result = MOUNT_SUCCESS;
1910 m->reload_result = MOUNT_SUCCESS;
1911 }
1912
1913 static int mount_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
1914 Mount *m = MOUNT(u);
1915
1916 assert(m);
1917
1918 return unit_kill_common(u, who, signo, -1, MOUNT(u)->control_pid, error);
1919 }
1920
1921 static int mount_control_pid(Unit *u) {
1922 Mount *m = MOUNT(u);
1923
1924 assert(m);
1925
1926 return m->control_pid;
1927 }
1928
1929 static const char* const mount_exec_command_table[_MOUNT_EXEC_COMMAND_MAX] = {
1930 [MOUNT_EXEC_MOUNT] = "ExecMount",
1931 [MOUNT_EXEC_UNMOUNT] = "ExecUnmount",
1932 [MOUNT_EXEC_REMOUNT] = "ExecRemount",
1933 };
1934
1935 DEFINE_STRING_TABLE_LOOKUP(mount_exec_command, MountExecCommand);
1936
1937 static const char* const mount_result_table[_MOUNT_RESULT_MAX] = {
1938 [MOUNT_SUCCESS] = "success",
1939 [MOUNT_FAILURE_RESOURCES] = "resources",
1940 [MOUNT_FAILURE_TIMEOUT] = "timeout",
1941 [MOUNT_FAILURE_EXIT_CODE] = "exit-code",
1942 [MOUNT_FAILURE_SIGNAL] = "signal",
1943 [MOUNT_FAILURE_CORE_DUMP] = "core-dump",
1944 [MOUNT_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
1945 [MOUNT_FAILURE_PROTOCOL] = "protocol",
1946 };
1947
1948 DEFINE_STRING_TABLE_LOOKUP(mount_result, MountResult);
1949
1950 const UnitVTable mount_vtable = {
1951 .object_size = sizeof(Mount),
1952 .exec_context_offset = offsetof(Mount, exec_context),
1953 .cgroup_context_offset = offsetof(Mount, cgroup_context),
1954 .kill_context_offset = offsetof(Mount, kill_context),
1955 .exec_runtime_offset = offsetof(Mount, exec_runtime),
1956 .dynamic_creds_offset = offsetof(Mount, dynamic_creds),
1957
1958 .sections =
1959 "Unit\0"
1960 "Mount\0"
1961 "Install\0",
1962 .private_section = "Mount",
1963
1964 .init = mount_init,
1965 .load = mount_load,
1966 .done = mount_done,
1967
1968 .coldplug = mount_coldplug,
1969
1970 .dump = mount_dump,
1971
1972 .start = mount_start,
1973 .stop = mount_stop,
1974 .reload = mount_reload,
1975
1976 .kill = mount_kill,
1977
1978 .serialize = mount_serialize,
1979 .deserialize_item = mount_deserialize_item,
1980
1981 .active_state = mount_active_state,
1982 .sub_state_to_string = mount_sub_state_to_string,
1983
1984 .may_gc = mount_may_gc,
1985
1986 .sigchld_event = mount_sigchld_event,
1987
1988 .reset_failed = mount_reset_failed,
1989
1990 .control_pid = mount_control_pid,
1991
1992 .bus_vtable = bus_mount_vtable,
1993 .bus_set_property = bus_mount_set_property,
1994 .bus_commit_properties = bus_mount_commit_properties,
1995
1996 .get_timeout = mount_get_timeout,
1997
1998 .can_transient = true,
1999
2000 .enumerate_perpetual = mount_enumerate_perpetual,
2001 .enumerate = mount_enumerate,
2002 .shutdown = mount_shutdown,
2003
2004 .status_message_formats = {
2005 .starting_stopping = {
2006 [0] = "Mounting %s...",
2007 [1] = "Unmounting %s...",
2008 },
2009 .finished_start_job = {
2010 [JOB_DONE] = "Mounted %s.",
2011 [JOB_FAILED] = "Failed to mount %s.",
2012 [JOB_TIMEOUT] = "Timed out mounting %s.",
2013 },
2014 .finished_stop_job = {
2015 [JOB_DONE] = "Unmounted %s.",
2016 [JOB_FAILED] = "Failed unmounting %s.",
2017 [JOB_TIMEOUT] = "Timed out unmounting %s.",
2018 },
2019 },
2020 };