Merge branch 'vendor/FILE'
[dragonfly.git] / contrib / bind / bin / rndc / unix / os.c
1 /*
2  * Copyright (C) 2004, 2005, 2007  Internet Systems Consortium, Inc. ("ISC")
3  * Copyright (C) 2001  Internet Software Consortium.
4  *
5  * Permission to use, copy, modify, and/or distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15  * PERFORMANCE OF THIS SOFTWARE.
16  */
17
18 /* $Id: os.c,v 1.10 2007/06/19 23:46:59 tbox Exp $ */
19
20 /*! \file */
21
22 #include <config.h>
23
24 #include <rndc/os.h>
25
26 #include <fcntl.h>
27 #include <unistd.h>
28 #include <sys/types.h>
29 #include <pwd.h>
30 #include <errno.h>
31 #include <stdio.h>
32 #include <sys/stat.h>
33
34 int
35 set_user(FILE *fd, const char *user) {
36         struct passwd *pw;
37
38         pw = getpwnam(user);
39         if (pw == NULL) {
40                 errno = EINVAL;
41                 return (-1);
42         }
43         return (fchown(fileno(fd), pw->pw_uid, -1));
44 }
45
46 FILE *
47 safe_create(const char *filename) {
48         int fd;
49         FILE *f;
50         struct stat sb;
51         int flags = O_WRONLY;
52
53         if (stat(filename, &sb) == -1) {
54                 if (errno != ENOENT)
55                         return (NULL);
56                 flags = O_WRONLY | O_CREAT | O_EXCL;
57         } else if ((sb.st_mode & S_IFREG) == 0) {
58                 errno = EOPNOTSUPP;
59                 return (NULL);
60         } else
61                 flags = O_WRONLY | O_TRUNC;
62
63         fd = open(filename, flags, S_IRUSR | S_IWUSR);
64         if (fd == -1)
65                 return (NULL);
66         f = fdopen(fd, "w");
67         if (f == NULL)
68                 close(fd);
69         return (f);
70 }