xref: /freebsd/lib/libutil/pidfile.c (revision f7c32ed617858bcd22f8d1b03199099d50125721)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2005 Pawel Jakub Dawidek <pjd@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/capsicum.h>
34 #include <sys/file.h>
35 #include <sys/stat.h>
36 
37 #include <err.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <libgen.h>
41 #include <libutil.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <time.h>
46 #include <unistd.h>
47 
48 struct pidfh {
49 	int	pf_dirfd;
50 	int	pf_fd;
51 	char	pf_dir[MAXPATHLEN + 1];
52 	char	pf_filename[MAXPATHLEN + 1];
53 	dev_t	pf_dev;
54 	ino_t	pf_ino;
55 };
56 
57 static int _pidfile_remove(struct pidfh *pfh, int freeit);
58 
59 static int
60 pidfile_verify(const struct pidfh *pfh)
61 {
62 	struct stat sb;
63 
64 	if (pfh == NULL || pfh->pf_fd == -1)
65 		return (EDOOFUS);
66 	/*
67 	 * Check remembered descriptor.
68 	 */
69 	if (fstat(pfh->pf_fd, &sb) == -1)
70 		return (errno);
71 	if (sb.st_dev != pfh->pf_dev || sb.st_ino != pfh->pf_ino)
72 		return (EDOOFUS);
73 	return (0);
74 }
75 
76 static int
77 pidfile_read(int dirfd, const char *filename, pid_t *pidptr)
78 {
79 	char buf[16], *endptr;
80 	int error, fd, i;
81 
82 	fd = openat(dirfd, filename, O_RDONLY | O_CLOEXEC);
83 	if (fd == -1)
84 		return (errno);
85 
86 	i = read(fd, buf, sizeof(buf) - 1);
87 	error = errno;	/* Remember errno in case close() wants to change it. */
88 	close(fd);
89 	if (i == -1)
90 		return (error);
91 	else if (i == 0)
92 		return (EAGAIN);
93 	buf[i] = '\0';
94 
95 	*pidptr = strtol(buf, &endptr, 10);
96 	if (endptr != &buf[i])
97 		return (EINVAL);
98 
99 	return (0);
100 }
101 
102 struct pidfh *
103 pidfile_open(const char *pathp, mode_t mode, pid_t *pidptr)
104 {
105 	char path[MAXPATHLEN];
106 	struct pidfh *pfh;
107 	struct stat sb;
108 	int error, fd, dirfd, dirlen, filenamelen, count;
109 	struct timespec rqtp;
110 	cap_rights_t caprights;
111 
112 	pfh = malloc(sizeof(*pfh));
113 	if (pfh == NULL)
114 		return (NULL);
115 
116 	if (pathp == NULL) {
117 		dirlen = snprintf(pfh->pf_dir, sizeof(pfh->pf_dir),
118 		    "/var/run/");
119 		filenamelen = snprintf(pfh->pf_filename,
120 		    sizeof(pfh->pf_filename), "%s.pid", getprogname());
121 	} else {
122 		if (strlcpy(path, pathp, sizeof(path)) >= sizeof(path)) {
123 			free(pfh);
124 			errno = ENAMETOOLONG;
125 			return (NULL);
126 		}
127 		dirlen = strlcpy(pfh->pf_dir, dirname(path),
128 		    sizeof(pfh->pf_dir));
129 		(void)strlcpy(path, pathp, sizeof(path));
130 		filenamelen = strlcpy(pfh->pf_filename, basename(path),
131 		    sizeof(pfh->pf_filename));
132 	}
133 
134 	if (dirlen >= (int)sizeof(pfh->pf_dir) ||
135 	    filenamelen >= (int)sizeof(pfh->pf_filename)) {
136 		free(pfh);
137 		errno = ENAMETOOLONG;
138 		return (NULL);
139 	}
140 
141 	dirfd = open(pfh->pf_dir, O_CLOEXEC | O_DIRECTORY | O_NONBLOCK);
142 	if (dirfd == -1) {
143 		error = errno;
144 		free(pfh);
145 		errno = error;
146 		return (NULL);
147 	}
148 
149 	/*
150 	 * Open the PID file and obtain exclusive lock.
151 	 * We truncate PID file here only to remove old PID immediately,
152 	 * PID file will be truncated again in pidfile_write(), so
153 	 * pidfile_write() can be called multiple times.
154 	 */
155 	fd = flopenat(dirfd, pfh->pf_filename,
156 	    O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NONBLOCK, mode);
157 	if (fd == -1) {
158 		if (errno == EWOULDBLOCK) {
159 			if (pidptr == NULL) {
160 				errno = EEXIST;
161 			} else {
162 				count = 20;
163 				rqtp.tv_sec = 0;
164 				rqtp.tv_nsec = 5000000;
165 				for (;;) {
166 					errno = pidfile_read(dirfd,
167 					    pfh->pf_filename, pidptr);
168 					if (errno != EAGAIN || --count == 0)
169 						break;
170 					nanosleep(&rqtp, 0);
171 				}
172 				if (errno == EAGAIN)
173 					*pidptr = -1;
174 				if (errno == 0 || errno == EAGAIN)
175 					errno = EEXIST;
176 			}
177 		}
178 		error = errno;
179 		close(dirfd);
180 		free(pfh);
181 		errno = error;
182 		return (NULL);
183 	}
184 
185 	/*
186 	 * Remember file information, so in pidfile_write() we are sure we write
187 	 * to the proper descriptor.
188 	 */
189 	if (fstat(fd, &sb) == -1) {
190 		goto failed;
191 	}
192 
193 	if (cap_rights_limit(dirfd,
194 	    cap_rights_init(&caprights, CAP_UNLINKAT)) < 0 && errno != ENOSYS) {
195 		goto failed;
196 	}
197 
198 	if (cap_rights_limit(fd, cap_rights_init(&caprights, CAP_PWRITE,
199 	    CAP_FSTAT, CAP_FTRUNCATE, CAP_EVENT)) < 0 &&
200 	    errno != ENOSYS) {
201 		goto failed;
202 	}
203 
204 	pfh->pf_dirfd = dirfd;
205 	pfh->pf_fd = fd;
206 	pfh->pf_dev = sb.st_dev;
207 	pfh->pf_ino = sb.st_ino;
208 
209 	return (pfh);
210 
211 failed:
212 	error = errno;
213 	unlinkat(dirfd, pfh->pf_filename, 0);
214 	close(dirfd);
215 	close(fd);
216 	free(pfh);
217 	errno = error;
218 	return (NULL);
219 }
220 
221 int
222 pidfile_write(struct pidfh *pfh)
223 {
224 	char pidstr[16];
225 	int error, fd;
226 
227 	/*
228 	 * Check remembered descriptor, so we don't overwrite some other
229 	 * file if pidfile was closed and descriptor reused.
230 	 */
231 	errno = pidfile_verify(pfh);
232 	if (errno != 0) {
233 		/*
234 		 * Don't close descriptor, because we are not sure if it's ours.
235 		 */
236 		return (-1);
237 	}
238 	fd = pfh->pf_fd;
239 
240 	/*
241 	 * Truncate PID file, so multiple calls of pidfile_write() are allowed.
242 	 */
243 	if (ftruncate(fd, 0) == -1) {
244 		error = errno;
245 		_pidfile_remove(pfh, 0);
246 		errno = error;
247 		return (-1);
248 	}
249 
250 	snprintf(pidstr, sizeof(pidstr), "%u", getpid());
251 	if (pwrite(fd, pidstr, strlen(pidstr), 0) != (ssize_t)strlen(pidstr)) {
252 		error = errno;
253 		_pidfile_remove(pfh, 0);
254 		errno = error;
255 		return (-1);
256 	}
257 
258 	return (0);
259 }
260 
261 int
262 pidfile_close(struct pidfh *pfh)
263 {
264 	int error;
265 
266 	error = pidfile_verify(pfh);
267 	if (error != 0) {
268 		errno = error;
269 		return (-1);
270 	}
271 
272 	if (close(pfh->pf_fd) == -1)
273 		error = errno;
274 	if (close(pfh->pf_dirfd) == -1 && error == 0)
275 		error = errno;
276 
277 	free(pfh);
278 	if (error != 0) {
279 		errno = error;
280 		return (-1);
281 	}
282 	return (0);
283 }
284 
285 static int
286 _pidfile_remove(struct pidfh *pfh, int freeit)
287 {
288 	int error;
289 
290 	error = pidfile_verify(pfh);
291 	if (error != 0) {
292 		errno = error;
293 		return (-1);
294 	}
295 
296 	if (funlinkat(pfh->pf_dirfd, pfh->pf_filename, pfh->pf_fd, 0) == -1) {
297 		if (errno == EDEADLK)
298 			return (-1);
299 		error = errno;
300 	}
301 	if (close(pfh->pf_fd) == -1 && error == 0)
302 		error = errno;
303 	if (close(pfh->pf_dirfd) == -1 && error == 0)
304 		error = errno;
305 	if (freeit)
306 		free(pfh);
307 	else
308 		pfh->pf_fd = -1;
309 	if (error != 0) {
310 		errno = error;
311 		return (-1);
312 	}
313 	return (0);
314 }
315 
316 int
317 pidfile_remove(struct pidfh *pfh)
318 {
319 
320 	return (_pidfile_remove(pfh, 1));
321 }
322 
323 int
324 pidfile_fileno(const struct pidfh *pfh)
325 {
326 
327 	if (pfh == NULL || pfh->pf_fd == -1) {
328 		errno = EDOOFUS;
329 		return (-1);
330 	}
331 	return (pfh->pf_fd);
332 }
333