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