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 #endif
27 
28 #ifndef HAVE_DAEMON
29 
30 #ifdef HAVE_UNISTD_H
31 #include <unistd.h>
32 #endif
33 
34 #include <stdlib.h>
35 
36 #ifdef HAVE_SYS_TYPES_H
37 #include <sys/types.h>
38 #endif
39 
40 #ifdef HAVE_SYS_STAT_H
41 #include <sys/stat.h>
42 #endif
43 
44 #ifdef HAVE_FCNTL_H
45 #include <fcntl.h>
46 #endif
47 
48 #include <errno.h>
49 
50 int
51 daemon(int nochdir, int noclose)
52 {
53 #if defined(HAVE_FORK) && defined(HAVE_SETSID)
54  switch (fork())
55  {
56  case -1:
57  return (-1);
58 
59  case 0:
60  break;
61 
62  default:
63  exit(0);
64  }
65 
66  if (setsid() == -1)
67  {
68  return (-1);
69  }
70 
71  if (!nochdir)
72  {
73  if (chdir("/") == -1)
74  {
75  return (-1);
76  }
77  }
78 
79  if (!noclose)
80  {
81 #if defined(HAVE_DUP) && defined(HAVE_DUP2)
82  int fd;
83  if ((fd = open("/dev/null", O_RDWR, 0)) != -1)
84  {
85  dup2(fd, 0);
86  dup2(fd, 1);
87  dup2(fd, 2);
88  if (fd > 2)
89  {
90  close(fd);
91  }
92  }
93 #endif
94  }
95 
96  return 0;
97 #else /* if defined(HAVE_FORK) && defined(HAVE_SETSID) */
98  (void)nochdir;
99  (void)noclose;
100  errno = EFAULT;
101  return -1;
102 #endif /* if defined(HAVE_FORK) && defined(HAVE_SETSID) */
103 }
104 
105 #endif /* ifndef HAVE_DAEMON */
daemon
int daemon(int nochdir, int noclose)
Definition: compat-daemon.c:51
config.h