1 /*-
2  * Taken from FreeBSD libutil
3  *
4  * Copyright (c) 2007 Dag-Erling Coïdan Smørgrav
5  * Copyright (c) 2005 Pawel Jakub Dawidek <pjd@FreeBSD.org>
6  * All rights reserved.
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 AUTHORS 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 AUTHORS 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 #include <sys/cdefs.h>
31 #ifdef __FBSDID
32 __FBSDID("$FreeBSD: src/lib/libutil/pidfile.c,v 1.9.2.1 2009/08/03 08:13:06 kensmith Exp $");
33 #endif
34 
35 #include <sys/param.h>
36 #include <sys/file.h>
37 #include <sys/stat.h>
38 
39 #include <stdarg.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <unistd.h>
43 #include <fcntl.h>
44 #include <string.h>
45 #include <time.h>
46 #include <err.h>
47 #include <errno.h>
48 
49 #include "pidfile.h"
50 
51 #ifndef EDOOFUS
52 #define EDOOFUS	EINVAL
53 #endif
54 
55 int
flopen(const char * path,int flags,...)56 flopen(const char *path, int flags, ...)
57 {
58 	int fd, operation, serrno, trunc;
59 	struct stat sb, fsb;
60 	mode_t mode;
61 
62 #ifdef O_EXLOCK
63 	flags &= ~O_EXLOCK;
64 #endif
65 
66 	mode = 0;
67 	if (flags & O_CREAT) {
68 		va_list ap;
69 
70 		va_start(ap, flags);
71 		mode = (mode_t)va_arg(ap, int); /* mode_t promoted to int */
72 		va_end(ap);
73 	}
74 
75         operation = LOCK_EX;
76         if (flags & O_NONBLOCK)
77                 operation |= LOCK_NB;
78 
79 	trunc = (flags & O_TRUNC);
80 	flags &= ~O_TRUNC;
81 
82 	for (;;) {
83 		if ((fd = open(path, flags, mode)) == -1)
84 			/* non-existent or no access */
85 			return (-1);
86 		if (flock(fd, operation) == -1) {
87 			/* unsupported or interrupted */
88 			serrno = errno;
89 			(void)close(fd);
90 			errno = serrno;
91 			return (-1);
92 		}
93 		if (stat(path, &sb) == -1) {
94 			/* disappeared from under our feet */
95 			(void)close(fd);
96 			continue;
97 		}
98 		if (fstat(fd, &fsb) == -1) {
99 			/* can't happen [tm] */
100 			serrno = errno;
101 			(void)close(fd);
102 			errno = serrno;
103 			return (-1);
104 		}
105 		if (sb.st_dev != fsb.st_dev ||
106 		    sb.st_ino != fsb.st_ino) {
107 			/* changed under our feet */
108 			(void)close(fd);
109 			continue;
110 		}
111 		if (trunc && ftruncate(fd, 0) != 0) {
112 			/* can't happen [tm] */
113 			serrno = errno;
114 			(void)close(fd);
115 			errno = serrno;
116 			return (-1);
117 		}
118 		return (fd);
119 	}
120 }
121 
122 static int _pidfile_remove(struct pidfh *pfh, int freeit);
123 
124 static int
pidfile_verify(struct pidfh * pfh)125 pidfile_verify(struct pidfh *pfh)
126 {
127 	struct stat sb;
128 
129 	if (pfh == NULL || pfh->pf_fd == -1)
130 		return (EDOOFUS);
131 	/*
132 	 * Check remembered descriptor.
133 	 */
134 	if (fstat(pfh->pf_fd, &sb) == -1)
135 		return (errno);
136 	if (sb.st_dev != pfh->pf_dev || sb.st_ino != pfh->pf_ino)
137 		return (EDOOFUS);
138 	return (0);
139 }
140 
141 static int
pidfile_read(const char * path,pid_t * pidptr)142 pidfile_read(const char *path, pid_t *pidptr)
143 {
144 	char buf[16], *endptr;
145 	int error, fd, i;
146 
147 	fd = open(path, O_RDONLY);
148 	if (fd == -1)
149 		return (errno);
150 
151 	i = read(fd, buf, sizeof(buf) - 1);
152 	error = errno;	/* Remember errno in case close() wants to change it. */
153 	close(fd);
154 	if (i == -1)
155 		return (error);
156 	else if (i == 0)
157 		return (EAGAIN);
158 	buf[i] = '\0';
159 
160 	*pidptr = strtol(buf, &endptr, 10);
161 	if (endptr != &buf[i])
162 		return (EINVAL);
163 
164 	return (0);
165 }
166 
167 struct pidfh *
pidfile_open(const char * path,mode_t mode,pid_t * pidptr)168 pidfile_open(const char *path, mode_t mode, pid_t *pidptr)
169 {
170 	struct pidfh *pfh;
171 	struct stat sb;
172 	int error, fd, len, count;
173 	struct timespec rqtp;
174 
175 	pfh = malloc(sizeof(*pfh));
176 	if (pfh == NULL)
177 		return (NULL);
178 
179 	if (path == NULL)
180 		return (NULL);
181 
182 	len = snprintf(pfh->pf_path, sizeof(pfh->pf_path),
183 	    "%s", path);
184 	if (len >= (int)sizeof(pfh->pf_path)) {
185 		free(pfh);
186 		errno = ENAMETOOLONG;
187 		return (NULL);
188 	}
189 
190 	/*
191 	 * Open the PID file and obtain exclusive lock.
192 	 * We truncate PID file here only to remove old PID immediatelly,
193 	 * PID file will be truncated again in pidfile_write(), so
194 	 * pidfile_write() can be called multiple times.
195 	 */
196 	fd = flopen(pfh->pf_path,
197 	    O_WRONLY | O_CREAT | O_TRUNC | O_NONBLOCK, mode);
198 	if (fd == -1) {
199 		count = 0;
200 		rqtp.tv_sec = 0;
201 		rqtp.tv_nsec = 5000000;
202 		if (errno == EWOULDBLOCK && pidptr != NULL) {
203 		again:
204 			errno = pidfile_read(pfh->pf_path, pidptr);
205 			if (errno == 0)
206 				errno = EEXIST;
207 			else if (errno == EAGAIN) {
208 				if (++count <= 3) {
209 					nanosleep(&rqtp, 0);
210 					goto again;
211 				}
212 			}
213 		}
214 		free(pfh);
215 		return (NULL);
216 	}
217 	/*
218 	 * Remember file information, so in pidfile_write() we are sure we write
219 	 * to the proper descriptor.
220 	 */
221 	if (fstat(fd, &sb) == -1) {
222 		error = errno;
223 		unlink(pfh->pf_path);
224 		close(fd);
225 		free(pfh);
226 		errno = error;
227 		return (NULL);
228 	}
229 
230 	pfh->pf_fd = fd;
231 	pfh->pf_dev = sb.st_dev;
232 	pfh->pf_ino = sb.st_ino;
233 
234 	return (pfh);
235 }
236 
237 int
pidfile_write(struct pidfh * pfh)238 pidfile_write(struct pidfh *pfh)
239 {
240 	char pidstr[16];
241 	int error, fd;
242 
243 	/*
244 	 * Check remembered descriptor, so we don't overwrite some other
245 	 * file if pidfile was closed and descriptor reused.
246 	 */
247 	errno = pidfile_verify(pfh);
248 	if (errno != 0) {
249 		/*
250 		 * Don't close descriptor, because we are not sure if it's ours.
251 		 */
252 		return (-1);
253 	}
254 	fd = pfh->pf_fd;
255 
256 	/*
257 	 * Truncate PID file, so multiple calls of pidfile_write() are allowed.
258 	 */
259 	if (ftruncate(fd, 0) == -1) {
260 		error = errno;
261 		_pidfile_remove(pfh, 0);
262 		errno = error;
263 		return (-1);
264 	}
265 
266 	snprintf(pidstr, sizeof(pidstr), "%u", getpid());
267 	if (pwrite(fd, pidstr, strlen(pidstr), 0) != (ssize_t)strlen(pidstr)) {
268 		error = errno;
269 		_pidfile_remove(pfh, 0);
270 		errno = error;
271 		return (-1);
272 	}
273 
274 	return (0);
275 }
276 
277 int
pidfile_close(struct pidfh * pfh)278 pidfile_close(struct pidfh *pfh)
279 {
280 	int error;
281 
282 	error = pidfile_verify(pfh);
283 	if (error != 0) {
284 		errno = error;
285 		return (-1);
286 	}
287 
288 	if (close(pfh->pf_fd) == -1)
289 		error = errno;
290 	free(pfh);
291 	if (error != 0) {
292 		errno = error;
293 		return (-1);
294 	}
295 	return (0);
296 }
297 
298 static int
_pidfile_remove(struct pidfh * pfh,int freeit)299 _pidfile_remove(struct pidfh *pfh, int freeit)
300 {
301 	int error;
302 
303 	error = pidfile_verify(pfh);
304 	if (error != 0) {
305 		errno = error;
306 		return (-1);
307 	}
308 
309 	if (unlink(pfh->pf_path) == -1)
310 		error = errno;
311 	if (close(pfh->pf_fd) == -1) {
312 		if (error == 0)
313 			error = errno;
314 	}
315 	if (freeit)
316 		free(pfh);
317 	else
318 		pfh->pf_fd = -1;
319 	if (error != 0) {
320 		errno = error;
321 		return (-1);
322 	}
323 	return (0);
324 }
325 
326 int
pidfile_remove(struct pidfh * pfh)327 pidfile_remove(struct pidfh *pfh)
328 {
329 
330 	return (_pidfile_remove(pfh, 1));
331 }
332