OpenVPN
compat-daemon.c
Go to the documentation of this file.
1 /*
2  * OpenVPN -- An application to securely tunnel IP networks
3  * over a single UDP port, with support for SSL/TLS-based
4  * session authentication and key exchange,
5  * packet encryption, packet authentication, and
6  * packet compression.
7  *
8  * Copyright (C) 2011 - David Sommerseth <davids@redhat.com>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License version 2
12  * as published by the Free Software Foundation.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License along
20  * with this program; if not, write to the Free Software Foundation, Inc.,
21  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  */
23 
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #elif defined(_MSC_VER)
27 #include "config-msvc.h"
28 #endif
29 
30 #ifndef HAVE_DAEMON
31 
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
35 
36 #ifdef HAVE_STDLIB_H
37 #include <stdlib.h>
38 #endif
39 
40 #ifdef HAVE_SYS_TYPES_H
41 #include <sys/types.h>
42 #endif
43 
44 #ifdef HAVE_SYS_STAT_H
45 #include <sys/stat.h>
46 #endif
47 
48 #ifdef HAVE_FCNTL_H
49 #include <fcntl.h>
50 #endif
51 
52 #ifdef HAVE_ERRNO_H
53 #include <errno.h>
54 #endif
55 
56 int
57 daemon(int nochdir, int noclose)
58 {
59 #if defined(HAVE_FORK) && defined(HAVE_SETSID)
60  switch (fork())
61  {
62  case -1:
63  return (-1);
64 
65  case 0:
66  break;
67 
68  default:
69  exit(0);
70  }
71 
72  if (setsid() == -1)
73  {
74  return (-1);
75  }
76 
77  if (!nochdir)
78  {
79  chdir("/");
80  }
81 
82  if (!noclose)
83  {
84 #if defined(HAVE_DUP) && defined(HAVE_DUP2)
85  int fd;
86  if ((fd = open("/dev/null", O_RDWR, 0)) != -1)
87  {
88  dup2(fd, 0);
89  dup2(fd, 1);
90  dup2(fd, 2);
91  if (fd > 2)
92  {
93  close(fd);
94  }
95  }
96 #endif
97  }
98 
99  return 0;
100 #else /* if defined(HAVE_FORK) && defined(HAVE_SETSID) */
101  (void)nochdir;
102  (void)noclose;
103  errno = EFAULT;
104  return -1;
105 #endif /* if defined(HAVE_FORK) && defined(HAVE_SETSID) */
106 }
107 
108 #endif /* ifndef HAVE_DAEMON */
109 
int daemon(int nochdir, int noclose)
Definition: compat-daemon.c:57