xref: /freebsd/usr.sbin/autofs/autounmountd.c (revision 28f42739a547ffe0b5dfaaf9f49fb4c4813aa232)
1 /*-
2  * Copyright (c) 2014 The FreeBSD Foundation
3  * All rights reserved.
4  *
5  * This software was developed by Edward Tomasz Napierala under sponsorship
6  * from the FreeBSD Foundation.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/types.h>
35 #include <sys/event.h>
36 #include <sys/mount.h>
37 #include <sys/time.h>
38 #include <assert.h>
39 #include <errno.h>
40 #include <stdbool.h>
41 #include <stdint.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46 #include <libutil.h>
47 
48 #include "common.h"
49 
50 #define AUTOUNMOUNTD_PIDFILE	"/var/run/autounmountd.pid"
51 
52 struct automounted_fs {
53 	TAILQ_ENTRY(automounted_fs)	af_next;
54 	time_t				af_mount_time;
55 	bool				af_mark;
56 	fsid_t				af_fsid;
57 	char				af_mountpoint[MNAMELEN];
58 };
59 
60 static TAILQ_HEAD(, automounted_fs)	automounted;
61 
62 static struct automounted_fs *
63 automounted_find(fsid_t fsid)
64 {
65 	struct automounted_fs *af;
66 
67 	TAILQ_FOREACH(af, &automounted, af_next) {
68 		if (af->af_fsid.val[0] == fsid.val[0] &&
69 		    af->af_fsid.val[1] == fsid.val[1])
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(sizeof(*af), 1);
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_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 	}
174 
175 	free(fsid_str);
176 
177 	return (error);
178 }
179 
180 static double
181 expire_automounted(double expiration_time)
182 {
183 	struct automounted_fs *af, *tmpaf;
184 	time_t now;
185 	double mounted_for, mounted_max = 0;
186 	int error;
187 
188 	now = time(NULL);
189 
190 	log_debugx("expiring automounted filesystems");
191 
192 	TAILQ_FOREACH_SAFE(af, &automounted, af_next, tmpaf) {
193 		mounted_for = difftime(now, af->af_mount_time);
194 
195 		if (mounted_for < expiration_time) {
196 			log_debugx("skipping %s (FSID:%d:%d), mounted "
197 			    "for %.0f seconds", af->af_mountpoint,
198 			    af->af_fsid.val[0], af->af_fsid.val[1],
199 			    mounted_for);
200 
201 			if (mounted_for > mounted_max)
202 				mounted_max = mounted_for;
203 
204 			continue;
205 		}
206 
207 		log_debugx("filesystem mounted on %s (FSID:%d:%d), "
208 		    "was mounted for %.0f seconds; unmounting",
209 		    af->af_mountpoint, af->af_fsid.val[0], af->af_fsid.val[1],
210 		    mounted_for);
211 		error = unmount_by_fsid(af->af_fsid, af->af_mountpoint);
212 		if (error != 0) {
213 			if (mounted_for > mounted_max)
214 				mounted_max = mounted_for;
215 		}
216 	}
217 
218 	return (mounted_max);
219 }
220 
221 static void
222 usage_autounmountd(void)
223 {
224 
225 	fprintf(stderr, "usage: autounmountd [-r time][-t time][-dv]\n");
226 	exit(1);
227 }
228 
229 static void
230 do_wait(int kq, double sleep_time)
231 {
232 	struct timespec timeout;
233 	struct kevent unused;
234 	int error;
235 
236 	assert(sleep_time > 0);
237 	timeout.tv_sec = sleep_time;
238 	timeout.tv_nsec = 0;
239 
240 	log_debugx("waiting for filesystem event for %.0f seconds", sleep_time);
241 	error = kevent(kq, NULL, 0, &unused, 1, &timeout);
242 	if (error < 0)
243 		log_err(1, "kevent");
244 
245 	if (error == 0)
246 		log_debugx("timeout reached");
247 	else
248 		log_debugx("got filesystem event");
249 }
250 
251 int
252 main_autounmountd(int argc, char **argv)
253 {
254 	struct kevent event;
255 	struct pidfh *pidfh;
256 	pid_t otherpid;
257 	const char *pidfile_path = AUTOUNMOUNTD_PIDFILE;
258 	int ch, debug = 0, error, kq;
259 	double expiration_time = 600, retry_time = 600, mounted_max, sleep_time;
260 	bool dont_daemonize = false;
261 
262 	while ((ch = getopt(argc, argv, "dr:t:v")) != -1) {
263 		switch (ch) {
264 		case 'd':
265 			dont_daemonize = true;
266 			debug++;
267 			break;
268 		case 'r':
269 			retry_time = atoi(optarg);
270 			break;
271 		case 't':
272 			expiration_time = atoi(optarg);
273 			break;
274 		case 'v':
275 			debug++;
276 			break;
277 		case '?':
278 		default:
279 			usage_autounmountd();
280 		}
281 	}
282 	argc -= optind;
283 	if (argc != 0)
284 		usage_autounmountd();
285 
286 	if (retry_time <= 0)
287 		log_errx(1, "retry time must be greater than zero");
288 	if (expiration_time <= 0)
289 		log_errx(1, "expiration time must be greater than zero");
290 
291 	log_init(debug);
292 
293 	pidfh = pidfile_open(pidfile_path, 0600, &otherpid);
294 	if (pidfh == NULL) {
295 		if (errno == EEXIST) {
296 			log_errx(1, "daemon already running, pid: %jd.",
297 			    (intmax_t)otherpid);
298 		}
299 		log_err(1, "cannot open or create pidfile \"%s\"",
300 		    pidfile_path);
301 	}
302 
303 	if (dont_daemonize == false) {
304 		if (daemon(0, 0) == -1) {
305 			log_warn("cannot daemonize");
306 			pidfile_remove(pidfh);
307 			exit(1);
308 		}
309 	}
310 
311 	pidfile_write(pidfh);
312 
313 	TAILQ_INIT(&automounted);
314 
315 	kq = kqueue();
316 	if (kq < 0)
317 		log_err(1, "kqueue");
318 
319 	EV_SET(&event, 0, EVFILT_FS, EV_ADD | EV_CLEAR, 0, 0, NULL);
320 	error = kevent(kq, &event, 1, NULL, 0, NULL);
321 	if (error < 0)
322 		log_err(1, "kevent");
323 
324 	for (;;) {
325 		refresh_automounted();
326 		mounted_max = expire_automounted(expiration_time);
327 		if (mounted_max < expiration_time) {
328 			sleep_time = difftime(expiration_time, mounted_max);
329 			log_debugx("some filesystems expire in %.0f seconds",
330 			    sleep_time);
331 		} else {
332 			sleep_time = retry_time;
333 			log_debugx("some expired filesystems remain mounted, "
334 			    "will retry in %.0f seconds", sleep_time);
335 		}
336 
337 		do_wait(kq, sleep_time);
338 	}
339 
340 	return (0);
341 }
342