Arthur de Jong

Open Source / Free Software developer

summaryrefslogtreecommitdiffstats
path: root/nslcd/daemonize.c
blob: d11d358ab881cf47c6c13f02fe5f7351dc112a6d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
/*
   daemoninze.c - functions for properly daemonising an application

   Copyright (C) 2014-2015 Arthur de Jong

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
   02110-1301 USA
*/

#include "config.h"

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef HAVE_PTHREAD_H
#include <pthread.h>
#endif /* HAVE_PTHREAD_H */

#include "daemonize.h"
#include "log.h"

/* the write end of a pipe that is used to signal the fact that the child
   process has finished initialising (see daemonize_daemon() and
   daemonize_ready() for details) */
static int daemonizefd = -1;

void daemonize_closefds(void)
{
  int i;
  /* close all file descriptors (except stdin/out/err) */
  i = sysconf(_SC_OPEN_MAX) - 1;
  /* if the system does not have OPEN_MAX just close the first 32 and
     hope we closed enough */
  if (i < 0)
    i = 32;
  for (; i > 3; i--)
    close(i);
}

void daemonize_redirect_stdio(void)
{
  /* close stdin, stdout and stderr */
  (void)close(0);   /* stdin */
  (void)close(1);   /* stdout */
  (void)close(2);   /* stderr */
  /* reconnect to /dev/null */
  (void)open("/dev/null", O_RDWR);  /* stdin, fd=0 */
  (void)dup(0);     /* stdout, fd=1 */
  (void)dup(0);     /* stderr, fd=2 */
}

/* try to fill the buffer until EOF or error */
static int read_response(int fd, char *buffer, size_t bufsz)
{
  int rc;
  size_t r = 0;
  while (r < bufsz)
  {
    rc = read(fd, buffer + r, bufsz - r);
    if (rc == 0)
      break;
    else if (rc > 0)
      r += rc;
    else if ((errno == EINTR) || (errno == EAGAIN))
      continue; /* ignore these errors and try again */
    else
    {
      log_log(LOG_ERR, "read_response(): read() failed: %s", strerror(errno));
      return -1;
    }
  }
  return r;
}

/* The parent process calling daemonize_daemon() will end up here on success */
static int wait_for_response(int fd)
{
  int i, l, rc;
  char buffer[1024];
  /* read return code */
  errno = 0;
  i = read_response(fd, (void *)&rc, sizeof(int));
  log_log(LOG_DEBUG, "DEBUG: wait_for_response(): i=%d, rc=%d", i, rc);
  if (i != sizeof(int))
  {
    log_log(LOG_ERR, "wait_for_response(): read_response() returned %d (expected %d)",
            i, (int)sizeof(int));
    if (errno == 0)
#ifdef ENODATA
      errno = ENODATA;
#else
      errno = ENOATTR;
#endif
    return -1;
  }
  /* read string length */
  i = read_response(fd, (void *)&l, sizeof(int));
  log_log(LOG_DEBUG, "DEBUG: wait_for_response(): i=%d, l=%d", i, l);
  if ((i != sizeof(int)) || (l <= 0))
    _exit(rc);
  /* read string */
  if ((size_t)l > (sizeof(buffer) - 1))
    l = sizeof(buffer) - 1;
  i = read_response(fd, buffer, l);
  buffer[l] = '\0';
  if (i == l)
    fprintf(stderr, "%s", buffer);
  _exit(rc);
}

static void closefd(void)
{
  if (daemonizefd >= 0)
  {
    close(daemonizefd);
    daemonizefd = -1;
  }
}

int daemonize_daemon(void)
{
  int pipefds[2];
  int i;
  /* set up a pipe for communication */
  if (pipe(pipefds) < 0)
  {
    log_log(LOG_ERR, "pipe() failed: %s", strerror(errno));
    return -1;
  }
  /* set O_NONBLOCK on the write end to ensure that a call to
     daemonize_ready() will not lock the application */
  if ((i = fcntl(pipefds[1], F_GETFL, 0)) < 0)
  {
    log_log(LOG_ERR, "fcntl() failed: %s", strerror(errno));
    close(pipefds[0]);
    close(pipefds[1]);
    return -1;
  }
  if (fcntl(pipefds[1], F_SETFL, i | O_NONBLOCK) < 0)
  {
    log_log(LOG_ERR, "fcntl() failed: %s", strerror(errno));
    close(pipefds[0]);
    close(pipefds[1]);
    return -1;
  }
  /* fork() and exit() to detach from the parent process */
  switch (fork())
  {
    case 0:
      /* we are the child, close read end of pipe */
      close(pipefds[0]);
      break;
    case -1:
      /* we are the parent, but have an error */
      log_log(LOG_ERR, "fork() failed: %s", strerror(errno));
      close(pipefds[0]);
      close(pipefds[1]);
      return -1;
    default:
      /* we are the parent, close write end and wait for information */
      close(pipefds[1]);
      return wait_for_response(pipefds[0]);
  }
  /* become process leader */
  if (setsid() < 0)
  {
    log_log(LOG_ERR, "setsid() failed: %s", strerror(errno));
    close(pipefds[1]);
    _exit(EXIT_FAILURE);
  }
  /* fork again so we cannot allocate a pty */
  switch (fork())
  {
    case 0:
      /* we are the child */
      break;
    case -1:
      /* we are the parent, but have an error */
      log_log(LOG_ERR, "fork() failed: %s", strerror(errno));
      close(pipefds[1]);
      _exit(EXIT_FAILURE);
    default:
      /* we are the parent and we're done */
      close(pipefds[1]);
      _exit(EXIT_SUCCESS);
  }
  daemonizefd = pipefds[1];
  /* close the file descriptor on exec (ignore errors) */
  fcntl(daemonizefd, F_SETFD, FD_CLOEXEC);
#ifdef HAVE_PTHREAD_ATFORK
  /* handle any other forks by closing daemonizefd first */
  (void)pthread_atfork(NULL, NULL, closefd);
#endif /* HAVE_PTHREAD_ATFORK */
  return 0;
}

void daemonize_ready(int status, const char *message)
{
  int l;
  if (daemonizefd >= 0)
  {
    /* we ignore any errors writing */
    (void)write(daemonizefd, &status, sizeof(int));
    if ((message == NULL) || (message[0] == '\0'))
    {
      l = 0;
      (void)write(daemonizefd, &l, sizeof(int));
    }
    else
    {
      l = strlen(message);
      (void)write(daemonizefd, &l, sizeof(int));
      (void)write(daemonizefd, message, l);
    }
    (void)close(daemonizefd);
    daemonizefd = -1;
  }
}