xref: /freebsd/usr.sbin/autofs/autounmountd.c (revision f7c32ed617858bcd22f8d1b03199099d50125721)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2014 The FreeBSD Foundation
5  *
6  * This software was developed by Edward Tomasz Napierala under sponsorship
7  * from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include <sys/types.h>
36 #include <sys/event.h>
37 #include <sys/mount.h>
38 #include <sys/time.h>
39 #include <assert.h>
40 #include <errno.h>
41 #include <libutil.h>
42 #include <stdbool.h>
43 #include <stdint.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48 
49 #include "common.h"
50 
51 #define AUTOUNMOUNTD_PIDFILE	"/var/run/autounmountd.pid"
52 
53 struct automounted_fs {
54 	TAILQ_ENTRY(automounted_fs)	af_next;
55 	time_t				af_mount_time;
56 	bool				af_mark;
57 	fsid_t				af_fsid;
58 	char				af_mountpoint[MNAMELEN];
59 };
60 
61 static TAILQ_HEAD(, automounted_fs)	automounted;
62 
63 static struct automounted_fs *
64 automounted_find(fsid_t fsid)
65 {
66 	struct automounted_fs *af;
67 
68 	TAILQ_FOREACH(af, &automounted, af_next) {
69 		if (fsidcmp(&af->af_fsid, &fsid) == 0)
70 			return (af);
71 	}
72 
73 	return (NULL);
74 }
75 
76 static struct automounted_fs *
77 automounted_add(fsid_t fsid, const char *mountpoint)
78 {
79 	struct automounted_fs *af;
80 
81 	af = calloc(1, sizeof(*af));
82 	if (af == NULL)
83 		log_err(1, "calloc");
84 	af->af_mount_time = time(NULL);
85 	af->af_fsid = fsid;
86 	strlcpy(af->af_mountpoint, mountpoint, sizeof(af->af_mountpoint));
87 
88 	TAILQ_INSERT_TAIL(&automounted, af, af_next);
89 
90 	return (af);
91 }
92 
93 static void
94 automounted_remove(struct automounted_fs *af)
95 {
96 
97 	TAILQ_REMOVE(&automounted, af, af_next);
98 	free(af);
99 }
100 
101 static void
102 refresh_automounted(void)
103 {
104 	struct automounted_fs *af, *tmpaf;
105 	struct statfs *mntbuf;
106 	int i, nitems;
107 
108 	nitems = getmntinfo(&mntbuf, MNT_WAIT);
109 	if (nitems <= 0)
110 		log_err(1, "getmntinfo");
111 
112 	log_debugx("refreshing list of automounted filesystems");
113 
114 	TAILQ_FOREACH(af, &automounted, af_next)
115 		af->af_mark = false;
116 
117 	for (i = 0; i < nitems; i++) {
118 		if (strcmp(mntbuf[i].f_fstypename, "autofs") == 0) {
119 			log_debugx("skipping %s, filesystem type is autofs",
120 			    mntbuf[i].f_mntonname);
121 			continue;
122 		}
123 
124 		if ((mntbuf[i].f_flags & MNT_AUTOMOUNTED) == 0) {
125 			log_debugx("skipping %s, not automounted",
126 			    mntbuf[i].f_mntonname);
127 			continue;
128 		}
129 
130 		af = automounted_find(mntbuf[i].f_fsid);
131 		if (af == NULL) {
132 			log_debugx("new automounted filesystem found on %s "
133 			    "(FSID:%d:%d)", mntbuf[i].f_mntonname,
134 			    mntbuf[i].f_fsid.val[0], mntbuf[i].f_fsid.val[1]);
135 			af = automounted_add(mntbuf[i].f_fsid,
136 			    mntbuf[i].f_mntonname);
137 		} else {
138 			log_debugx("already known automounted filesystem "
139 			    "found on %s (FSID:%d:%d)", mntbuf[i].f_mntonname,
140 			    mntbuf[i].f_fsid.val[0], mntbuf[i].f_fsid.val[1]);
141 		}
142 		af->af_mark = true;
143 	}
144 
145 	TAILQ_FOREACH_SAFE(af, &automounted, af_next, tmpaf) {
146 		if (af->af_mark)
147 			continue;
148 		log_debugx("lost filesystem mounted on %s (FSID:%d:%d)",
149 		    af->af_mountpoint, af->af_fsid.val[0], af->af_fsid.val[1]);
150 		automounted_remove(af);
151 	}
152 }
153 
154 static int
155 unmount_by_fsid(const fsid_t fsid, const char *mountpoint)
156 {
157 	char *fsid_str;
158 	int error, ret;
159 
160 	ret = asprintf(&fsid_str, "FSID:%d:%d", fsid.val[0], fsid.val[1]);
161 	if (ret < 0)
162 		log_err(1, "asprintf");
163 
164 	error = unmount(fsid_str, MNT_NONBUSY | MNT_BYFSID);
165 	if (error != 0) {
166 		if (errno == EBUSY) {
167 			log_debugx("cannot unmount %s (%s): %s",
168 			    mountpoint, fsid_str, strerror(errno));
169 		} else {
170 			log_warn("cannot unmount %s (%s)",
171 			    mountpoint, fsid_str);
172 		}
173 	} else
174 		rpc_umntall();
175 
176 	free(fsid_str);
177 
178 	return (error);
179 }
180 
181 static time_t
182 expire_automounted(time_t expiration_time)
183 {
184 	struct automounted_fs *af, *tmpaf;
185 	time_t now;
186 	time_t mounted_for, mounted_max = -1;
187 	int error;
188 
189 	now = time(NULL);
190 
191 	log_debugx("expiring automounted filesystems");
192 
193 	TAILQ_FOREACH_SAFE(af, &automounted, af_next, tmpaf) {
194 		mounted_for = difftime(now, af->af_mount_time);
195 
196 		if (mounted_for < expiration_time) {
197 			log_debugx("skipping %s (FSID:%d:%d), mounted "
198 			    "for %jd  seconds", af->af_mountpoint,
199 			    af->af_fsid.val[0], af->af_fsid.val[1],
200 			    (intmax_t)mounted_for);
201 
202 			if (mounted_for > mounted_max)
203 				mounted_max = mounted_for;
204 
205 			continue;
206 		}
207 
208 		log_debugx("filesystem mounted on %s (FSID:%d:%d), "
209 		    "was mounted for %ld seconds; unmounting",
210 		    af->af_mountpoint, af->af_fsid.val[0], af->af_fsid.val[1],
211 		    (long)mounted_for);
212 		error = unmount_by_fsid(af->af_fsid, af->af_mountpoint);
213 		if (error != 0) {
214 			if (mounted_for > mounted_max)
215 				mounted_max = mounted_for;
216 		}
217 	}
218 
219 	return (mounted_max);
220 }
221 
222 static void
223 usage_autounmountd(void)
224 {
225 
226 	fprintf(stderr, "usage: autounmountd [-r time][-t time][-dv]\n");
227 	exit(1);
228 }
229 
230 static void
231 do_wait(int kq, time_t sleep_time)
232 {
233 	struct timespec timeout;
234 	struct kevent unused;
235 	int nevents;
236 
237 	if (sleep_time != -1) {
238 		assert(sleep_time > 0);
239 		timeout.tv_sec = sleep_time;
240 		timeout.tv_nsec = 0;
241 
242 		log_debugx("waiting for filesystem event for %ld seconds",
243 		    (long)sleep_time);
244 		nevents = kevent(kq, NULL, 0, &unused, 1, &timeout);
245 	} else {
246 		log_debugx("waiting for filesystem event");
247 		nevents = kevent(kq, NULL, 0, &unused, 1, NULL);
248 	}
249 	if (nevents < 0) {
250 		if (errno == EINTR)
251 			return;
252 		log_err(1, "kevent");
253 	}
254 
255 	if (nevents == 0) {
256 		log_debugx("timeout reached");
257 		assert(sleep_time > 0);
258 	} else {
259 		log_debugx("got filesystem event");
260 	}
261 }
262 
263 int
264 main_autounmountd(int argc, char **argv)
265 {
266 	struct kevent event;
267 	struct pidfh *pidfh;
268 	pid_t otherpid;
269 	const char *pidfile_path = AUTOUNMOUNTD_PIDFILE;
270 	int ch, debug = 0, error, kq;
271 	time_t expiration_time = 600, retry_time = 600, mounted_max, sleep_time;
272 	bool dont_daemonize = false;
273 
274 	while ((ch = getopt(argc, argv, "dr:t:v")) != -1) {
275 		switch (ch) {
276 		case 'd':
277 			dont_daemonize = true;
278 			debug++;
279 			break;
280 		case 'r':
281 			retry_time = atoi(optarg);
282 			break;
283 		case 't':
284 			expiration_time = atoi(optarg);
285 			break;
286 		case 'v':
287 			debug++;
288 			break;
289 		case '?':
290 		default:
291 			usage_autounmountd();
292 		}
293 	}
294 	argc -= optind;
295 	if (argc != 0)
296 		usage_autounmountd();
297 
298 	if (retry_time <= 0)
299 		log_errx(1, "retry time must be greater than zero");
300 	if (expiration_time <= 0)
301 		log_errx(1, "expiration time must be greater than zero");
302 
303 	log_init(debug);
304 
305 	pidfh = pidfile_open(pidfile_path, 0600, &otherpid);
306 	if (pidfh == NULL) {
307 		if (errno == EEXIST) {
308 			log_errx(1, "daemon already running, pid: %jd.",
309 			    (intmax_t)otherpid);
310 		}
311 		log_err(1, "cannot open or create pidfile \"%s\"",
312 		    pidfile_path);
313 	}
314 
315 	if (dont_daemonize == false) {
316 		if (daemon(0, 0) == -1) {
317 			log_warn("cannot daemonize");
318 			pidfile_remove(pidfh);
319 			exit(1);
320 		}
321 	}
322 
323 	pidfile_write(pidfh);
324 
325 	TAILQ_INIT(&automounted);
326 
327 	kq = kqueue();
328 	if (kq < 0)
329 		log_err(1, "kqueue");
330 
331 	EV_SET(&event, 0, EVFILT_FS, EV_ADD | EV_CLEAR, VQ_MOUNT | VQ_UNMOUNT, 0, NULL);
332 	error = kevent(kq, &event, 1, NULL, 0, NULL);
333 	if (error < 0)
334 		log_err(1, "kevent");
335 
336 	for (;;) {
337 		refresh_automounted();
338 		mounted_max = expire_automounted(expiration_time);
339 		if (mounted_max == -1) {
340 			sleep_time = mounted_max;
341 			log_debugx("no filesystems to expire");
342 		} else if (mounted_max < expiration_time) {
343 			sleep_time = difftime(expiration_time, mounted_max);
344 			log_debugx("some filesystems expire in %ld  seconds",
345 			    (long)sleep_time);
346 		} else {
347 			sleep_time = retry_time;
348 			log_debugx("some expired filesystems remain mounted, "
349 			    "will retry in %ld  seconds", (long)sleep_time);
350 		}
351 
352 		do_wait(kq, sleep_time);
353 	}
354 
355 	return (0);
356 }
357