daemon.c 11.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
/* daemon.c
 *
 * Derived from
 * http://www.zip.com.au/~raf2/lib/software/daemon
 *
 * $Id$
 */

/* lsh, an implementation of the ssh protocol
 *
11
 * Copyright (C) 1999, 2002, raf, Niels Möller
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program 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
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "daemon.h"

Niels Möller's avatar
Niels Möller committed
30
31
#include "format.h"
#include "werror.h"
Niels Möller's avatar
Niels Möller committed
32
#include "xalloc.h"
Niels Möller's avatar
Niels Möller committed
33

34
35
#include <stdlib.h>
#include <stdio.h>
Niels Möller's avatar
Niels Möller committed
36
#include <string.h>
37
38
39
40

#include <unistd.h>

/* For setrlimit */
41
#include <sys/time.h>    /* Needed on BSD */
42
43
44
45
46
47
#include <sys/resource.h>

#include <errno.h>
#include <signal.h>
#include <fcntl.h>

48
#include <sys/types.h>
49
50
#include <sys/stat.h>
#include <sys/socket.h>
51
#include <sys/wait.h>
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

#ifndef PID_DIR
#define PID_DIR "/var/run"
#endif

#ifndef ROOT_DIR
#define ROOT_DIR "/"
#endif

#ifndef PID_SUFFIX
#define PID_SUFFIX ".pid"
#endif

/*
** struct lsh_string *daemon_pidfile(const char *name)
**
** Creates a pid file for a daemon and locks it.
** The file has one line containing the process id of the daemon.
** The well-known location for the file is defined in PID_DIR
** ("/var/run" by default). The name of the file is the name of
** the daemon (given by the name argument) followed by ".pid".
**
** Returns 1 on success or 0 on failure (with errno set
** appropriately). Reasons for failure are: ENAMETOOLONG If the pid
** file's path is longer than the system path limit. open(2).
** fcntl(2). write(2). */


int daemon_pidfile(const char *name)
{
  int fd;
  
  /* Try to open the file atomically. This provides sufficient locking
   * on normal (non-NFS) file systems. */

  fd = open(name, O_WRONLY | O_CREAT | O_EXCL, 0644);

  if (fd < 0)
    {
      if (errno != EEXIST)
	{
93
94
	  werror("Failed to open pid file '%z' %e\n",
		 name, errno);
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
	  return 0;
	}

      werror("Pid file '%z' already exists.\n", name);
      return 0;
      
      /* FIXME: Various trickery to detect and ignore stale pid files.
       * Disabled for now. */
#if 0
      /* Attempt to lock and read the file */
      {
	struct flock lock;
	lock.l_type = F_WRLCK;
	lock.l_whence = SEEK_SET;
	lock.l_start = 0;
	lock.l_len = 0;

	int fd = open(name, O_RDWR);
	
	if (fcntl(fd, F_SETLK, &lock) < 0)
	  {
	    werror("pid file '%z' exists and is locked.\n");
	    return 0;
	  }
      }
      fd = open(name, O_RDONLY);
      if (fd < 0)
	{
123
124
	  werror("Pid file '%z' already exists, and is unreadable %e\n",
		 name, errno);
125
126
127
128
129
130
131
132
133
134
135
136
	  return 0;
	}
      {
	/* Read some characters */
#define BUF_SIZE 20
	char buffer[BUF_SIZE];
	
	int length = read(fd, buffer, BUF_SIZE);
	close(fd);
	
	if (length < 0)
	  {
137
138
	    werror("Pid file '%z' already exists, but read failed %e\n",
		   name, errno);
139
140
141
142
	    return 0;
	  }
	if ( !length|| !buffer[0] || (length == BUF_SIZE) )
	  {
143
144
	    werror("Pid file '%z' already exists, but contents is garbled.\n",
		   name);
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
	    return 0;
	  }

	buffer[length] = '\0';
	
	{
	  long other;
	  char *end;

	  /* FIXME: strtol is somewhat inconvenient, too forgiving,
	   * and possibly locale dependent. */
	  other = strtol(buffer, &end, 10);
	  errno = 0;
	  
	  if ( (errno == ERANGE) || (end != buffer + length)
	       || (other <= 0) || (other != (pid_t) other))
	    {
162
163
	      werror("Pid file '%z' already exists, but contents is garbled.\n",
		     name);
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
	      return 0;
	    }

	  if ( (kill((pid_t) other, 0) < 0)
	       && (errno == SRCH))
	    {
	      werror("pid lock '%z' owned by process %i, which appear to be dead.\n",
		     name, other);
	      /* We could try to be clever and delete the file in this
	       * case, but then we get into race conditions if two
	       * processes tries to do that simultaneously. */
	    }
	  else
	    werror("pid lock '%z' owned by process %i, which appears to be alive.\n");
	  return 0;
	}
      }
#endif 
    }
  else
    {
Niels Möller's avatar
Niels Möller committed
185
      struct lsh_string *pid = ssh_format("%di", getpid());
186

Niels Möller's avatar
Niels Möller committed
187
      int res = write(fd, pid->data, pid->length);
188
189
      close(fd);
      
Niels Möller's avatar
Niels Möller committed
190
      if ( (res > 0) && ((unsigned) res == pid->length) )
Niels Möller's avatar
Niels Möller committed
191
192
193
194
195
	{
	  /* Success! */
	  lsh_string_free(pid);
	  return 1;
	}
196
      werror("Writing pid file '%z' failed %e\n", name, errno);
197
198
199

      /* Attempt unlinking file */
      if (unlink(name) < 0)
200
201
	werror("Unlinking pid file '%z' failed %e\n",
	       name, errno);
Niels Möller's avatar
Niels Möller committed
202
203
204
      
      lsh_string_free(pid);
	  
205
206
207
      return 0;
    }
}
Niels Möller's avatar
Niels Möller committed
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
/*
** int daemon_started_by_init(void)
**
** Determines whether or not this process was started by init(8).
** If it was, we might be getting respawned so fork(2) and exit(2)
** would be a big mistake.
*/

int daemon_started_by_init(void)
{
  return (getppid() == 1);
}

/*
** int daemon_started_by_inetd(void)
**
** Determines whether or not this process was started by inetd(8).
** If it was, stdin, stdout and stderr would be opened to a socket.
** Closing them would be a big mistake. We also wouldn't need to
** fork(2) and exec(2) because there isn't a controlling terminal
** in sight.
*/

/* FIXME: Do we need to detect if the socket is listening or connected
 * to a peer? */
234
235
int
daemon_started_by_inetd(void)
236
237
238
239
240
241
242
243
{
  int optval;
  socklen_t optlen = sizeof(optval);
  
  return (getsockopt(STDIN_FILENO, SOL_SOCKET, SO_TYPE, &optval, &optlen) == 0);
}

/* Disable core files */
244
245
int
daemon_disable_core(void)
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
{
  struct rlimit limit = { 0, 0 };

  /*
  ** Disable core files to prevent security holes.
  */

  if (getrlimit(RLIMIT_CORE, &limit) == -1)
    return 0;

  limit.rlim_cur = 0;

  if (setrlimit(RLIMIT_CORE, &limit) == -1)
    return 0;

  return 1;
}

/*
** int daemon_init(void)
**
** Initialises a daemon:
** Disables core files to prevent security holes.
** If the process wasn't started by init(8) or inetd(8):
**   Backgrounds the process to lose process group leadership.
**   Becomes a process session leader.
**   When SVR4 is defined:
**     Backgrounds the process again to lose process group leadership.
**     This prevents the process from gaining a controlling terminal.
**     Under BSD, you must still include O_NOCTTY when opening terminals
**     to prevent the process from gaining a controlling terminal.
** Changes directory to the root directory so as not to hamper umounts.
** Clears the umask to enable explicit file modes.
** If the process wasn't started by inetd(8):
**   Closes all files (as determined by sysconf(2)).
**   Opens stdin, stdout and stderr to /dev/null in case something needs them.
** If the hup parameter is non-null,
**   Registers a SIGHUP handler.
** If the term parameter is non-null,
**   Registers a SIGTERM handler.
** If the name parameter is non-null,
**   Places the process id in the file system and locks it.
**
** Returns DAEMON_NORMAL, DAEMON_INIT or DAEMON_INETD on success, 0 on
** error (with errno set appropriately).
** 
** Reasons for failure are: getrlimit(2), setrlimit(2), fork(2), chdir(2),
** sysconf(2), open(2), dup2(2), daemon_pidfile(), sigemptyset(2),
** sigaddset(2), sigaction(2). */

int daemon_init(void)
{
  int mode = DAEMON_NORMAL;

  if (daemon_started_by_init())
    mode = DAEMON_INIT;
  else if (daemon_started_by_inetd())
    mode = DAEMON_INETD;
  
  /*
  ** Don't setup a daemon-friendly process context
  ** if started by init(8) or inetd(8).
  */

  if (mode == DAEMON_NORMAL)
    {
312
313
      pid_t child;
      
314
315
316
317
318
319
320
321
322
323
324
325
326
      /*
      ** Background the process.
      ** Lose process group leadership.
      */

      switch (fork())
	{
	case -1:
	  return 0;
	case 0:
	  /* Child */
	  break;
	default:
327
	  /* Parent */
328
329
330
331
332
333
334
	  exit(0);
	}
      /*
      ** Become a process session leader.
      */

      if (setsid() < 0)
335
	fatal("daemon_init: setsid failed.\n");
336
337
338
339
340
341

      /*
      ** Lose process session leadership
      ** to prevent gaining a controlling
      ** terminal in SVR4.
      */
342
      switch (child = fork())
343
344
345
346
347
348
	{
	case -1:
	  return 0;
	case 0:
	  break;
	default:
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
	  {
	    int status;
	    int res;

	    do {
	      res = waitpid(child, &status, 0);
	    } while (res < 0 && errno == EINTR);

	    if (!res < 0)
	      werror("deamon.c: waitpid failed %e\n", errno);
	    else if (WIFEXITED(status))
	      werror("deamon.c: process exited with status %i\n",
		     WEXITSTATUS(status));
	    else if (WIFSIGNALED(status))
	      werror("deamon.c: process died from signal %i\n",
		     WTERMSIG(status));
	    else
	      werror("deamon.c: process died, wait status: %i\n",
		     status);

	    _exit(0);
	  }
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
	}
    }

  /*
  ** Enter the root directory to prevent hampering umounts.
  */

  if (chdir(ROOT_DIR) == -1)
    return 0;

  /*
  ** Clear umask to enable explicit file modes.
  */

  umask(0);

  {
    int fd;

    fd = open("/dev/null", O_RDWR);

    if (fd < 0)
      return 0;

    /* Don't close stdin if we are started from inetd. */

    if ( (mode != DAEMON_INETD)
	 && (dup2(fd, STDIN_FILENO) < 0))
      {
	werror("daemon_init: Failed to redirect stdin to /dev/null.\n");
	close(fd);
	return 0;
      }

    if ( (dup2(fd, STDOUT_FILENO) < 0)
	 || (dup2(fd, STDERR_FILENO) < 0) )
      {
	werror("daemon_init: Failed to redirect stdout and stderr to /dev/null.\n");
	close(fd);
	return 0;
      }

    close(fd);

    /* It seems unfriendly to try toclose all fds (and on some
     * systems, e.g. the HURD, there are no limits to the number of
     * open files. It should be good enough to take care of stdio. */
    
#if 0
    /*
    ** Close all open files.
    ** Don't forget to open any future
    ** tty devices with O_NOCTTY so as
    ** to prevent gaining a controlling
    ** terminal (not necessary with SVR4).
    */
    
    if ((nopen = limit_open()) == -1)
      return -1;
    
    for (fd = 0; fd < nopen; ++fd)
      close(fd);
    
    /*
    ** Open stdin, stdout and stderr to /dev/null
    ** just in case someone expects them to be open.
    */

    if ((fd = open("/dev/null", O_RDWR)) == -1)
      return -1;

    /*
    ** This is only needed for very strange
    ** (hypothetical) posix implementations
    ** where STDIN_FILENO != 0 or STDOUT_FILE != 1
    ** or STERR_FILENO != 2 (yeah, right).
    */

    if (fd != STDIN_FILENO)
      {
	if (dup2(fd, STDIN_FILENO) == -1)
	  return -1;

	close(fd);
      }

    if (dup2(STDIN_FILENO, STDOUT_FILENO) == -1)
      return -1;

    if (dup2(STDIN_FILENO, STDERR_FILENO) == -1)
      return -1;
#endif
  }
  
#if 0
  /*
  ** Register a SIGHUP handler, if required.
  */

  if (hup && signal_set_handler(SIGHUP, 0, hup) == -1)
    return -1;

  /*
  ** Register a SIGTERM handler, if required.
  */

  if (term && signal_set_handler(SIGTERM, 0, term) == -1)
    return -1;
#endif

  return 1;
}

/*
** int daemon_close()
**
** Unlinks the daemon's (locked) process id file.
*/

int daemon_close(const char *name)
{
  if (unlink(name) < 0)
    {
494
495
      werror("daemon_close: Unlink of pid file '%z' failed %e\n",
	     name, errno);
496
497
498
499
      return 0;
    }
  return 1;
}