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