make depend
[darkstat] / pidfile.c
1 /* darkstat 3
2 * copyright (c) 2007-2011 Emil Mikulic.
3 *
4 * pidfile.h: pidfile manglement
5 *
6 * Permission to use, copy, modify, and distribute this file for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 #include "err.h"
20 #include "str.h"
21 #include "pidfile.h"
22
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <pwd.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28
29 static int pidfd = -1;
30 static const char *pidname = NULL;
31
32 void
33 pidfile_create(const char *chroot_dir, const char *filename,
34 const char *privdrop_user)
35 {
36 struct passwd *pw;
37
38 if (pidfd != -1)
39 errx(1, "pidfile already created");
40
41 errno = 0;
42 pw = getpwnam(privdrop_user);
43
44 if (pw == NULL) {
45 if (errno == 0)
46 errx(1, "getpwnam(\"%s\") failed: no such user", privdrop_user);
47 else
48 err(1, "getpwnam(\"%s\") failed", privdrop_user);
49 }
50
51 if (chdir(chroot_dir) == -1)
52 err(1, "chdir(\"%s\") failed", chroot_dir);
53 pidname = filename;
54 pidfd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0600);
55 if (pidfd == -1)
56 err(1, "couldn't not create pidfile");
57 if (chown(filename, pw->pw_uid, pw->pw_gid) == -1)
58 err(1, "couldn't chown pidfile");
59 }
60
61 void
62 pidfile_write_close(void)
63 {
64 struct str *s;
65 size_t len;
66 char *buf;
67
68 if (pidfd == -1)
69 errx(1, "cannot write pidfile: not created");
70
71 s = str_make();
72 str_appendf(s, "%u\n", (unsigned int)getpid());
73 str_extract(s, &len, &buf);
74
75 if (write(pidfd, buf, len) != (int)len)
76 err(1, "couldn't write to pidfile");
77 free(buf);
78 if (close(pidfd) == -1)
79 warn("problem closing pidfile");
80 }
81
82 void
83 pidfile_unlink(void)
84 {
85 if (pidname == NULL)
86 return; /* pidfile wasn't created */
87 if (unlink(pidname) == -1)
88 warn("problem unlinking pidfile");
89 }
90
91 /* vim:set ts=3 sw=3 tw=78 et: */