-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdaemon.c
2114 lines (1614 loc) · 52.4 KB
/
daemon.c
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
236
237
238
239
240
241
242
243
244
245
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* libslack - https://libslack.org
*
* Copyright (C) 1999-2004, 2010, 2020-2023 raf <[email protected]>
*
* 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, see <https://www.gnu.org/licenses/>.
*
* 20230824 raf <[email protected]>
*/
/*
=head1 NAME
I<libslack(daemon)> - daemon module
=head1 SYNOPSIS
#include <slack/std.h>
#include <slack/daemon.h>
typedef void daemon_config_parser_t(void *obj, const char *path, char *line, size_t lineno);
int daemon_started_by_init(void);
int daemon_started_by_inetd(void);
int daemon_prevent_core(void);
int daemon_revoke_privileges(void);
int daemon_become_user(uid_t uid, gid_t gid, char *user);
char *daemon_absolute_path(const char *path);
int daemon_path_is_safe(const char *path, char *explanation, size_t explanation_size);
void *daemon_parse_config(const char *path, void *obj, daemon_config_parser_t *parser);
int daemon_pidfile(const char *name);
int daemon_init(const char *name);
int daemon_close(void);
pid_t daemon_getpid(const char *name);
int daemon_is_running(const char *name);
int daemon_stop(const char *name);
=head1 DESCRIPTION
This module provides functions for writing daemons. There are many tasks
that need to be performed to correctly set up a daemon process. This can be
tedious. These functions perform these tasks for you.
=over 4
=cut
*/
#include "config.h"
#ifndef NO_POSIX_SOURCE
#define NO_POSIX_SOURCE /* For ELOOP on FreeBSD-8.0 */
#endif
#ifndef _BSD_SOURCE
#define _BSD_SOURCE /* For setgroups(2) and S_ISLNK(2) on Linux */
#endif
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE /* New name for _BSD_SOURCE */
#endif
#ifndef __BSD_VISIBLE
#define __BSD_VISIBLE 1 /* For setgroups(2) and initgroups(2) on FreeBSD-8.0 */
#endif
#ifndef _NETBSD_SOURCE
#define _NETBSD_SOURCE /* For endpwent, endgrent, setgroups, initgroups, lstat, readlink on NetBSD-5.0.2 */
#endif
#include "std.h"
#include <fcntl.h>
#include <pwd.h>
#include <grp.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/resource.h>
#include "daemon.h"
#include "mem.h"
#include "err.h"
#include "lim.h"
#include "fio.h"
#ifndef HAVE_SNPRINTF
#include "snprintf.h"
#endif
#ifndef TEST
static struct
{
pthread_mutex_t lock; /* Mutex lock for structure */
char *pidfile; /* Name of the locked pid file */
int pid_fd; /* Open file descriptor of the pid file */
dev_t pid_dev; /* Device that the pid file is on */
ino_t pid_inode; /* Inode of the pid file */
}
g =
{
PTHREAD_MUTEX_INITIALIZER, /* lock */
NULL, /* pidfile */
-1, /* pid_fd */
(dev_t)0, /* pid_dev */
(ino_t)0 /* pid_inode */
};
#define ptry(action) { int err = (action); if (err) return set_errno(err); }
/*
=item C<int daemon_started_by_init(void)>
If this process was started by I<init(8)> (i.e. if the parent process id is
1), returns 1. If not, returns C<0>. If it was, we might be getting
respawned so I<fork(2)> and I<exit(2)> would be a big mistake (and
unnecessary anyway, since there is no controlling terminal). On error,
returns C<-1> with C<errno> set appropriately.
=cut
*/
int daemon_started_by_init(void)
{
return (getppid() == 1);
}
/*
=item C<int daemon_started_by_inetd(void)>
If this process was started by I<inetd(8)> (i.e. if I<stdin> is a socket),
returns C<1>. If not, returns C<0>. On error, returns C<-1> with C<errno>
set appropriately. If it was, C<stdin>, C<stdout> and C<stderr> would be
opened to a socket. Closing them would be a big mistake. We also would not
need to I<fork(2)> and I<exit(2)> because there is no controlling terminal.
=cut
*/
int daemon_started_by_inetd(void)
{
size_t optlen = sizeof(int);
int optval;
return (getsockopt(STDIN_FILENO, SOL_SOCKET, SO_TYPE, &optval, (void *)&optlen) == 0);
}
/*
=item C<int daemon_prevent_core(void)>
Prevents core files from being generated. This is used to prevent leaking
sensitive information in daemons run by I<root>. On success, returns C<0>.
On error, returns C<-1> with C<errno> set appropriately.
=cut
*/
int daemon_prevent_core(void)
{
struct rlimit limit[1] = {{ 0, 0 }};
if (getrlimit(RLIMIT_CORE, limit) == -1)
return -1;
limit->rlim_cur = 0;
return setrlimit(RLIMIT_CORE, limit);
}
/*
=item C<int daemon_revoke_privileges(void)>
Revokes setuid and setgid privileges. Useful when your program does not
require any special privileges, and may become unsafe if incorrectly
installed with special privileges. Also useful when your program only
requires special privileges initially upon startup (e.g. binding to a
privileged socket). Performs the following tasks: Sets the effective gid to
the real gid if they differ. Checks that they no longer differ. Sets the
effective uid to the real uid if they differ. Checks that they no longer
differ. Also closes /etc/passwd and /etc/group in case they were opened by
I<root> and give access to user and group passwords. On success, returns
C<0>. On error, returns C<-1> with C<errno> set appropriately.
=cut
*/
int daemon_revoke_privileges(void)
{
uid_t uid = getuid();
gid_t gid = getgid();
uid_t euid = geteuid();
gid_t egid = getegid();
if (egid != gid && (setgid(gid) == -1 || getegid() != getgid()))
return -1;
if (euid != uid && (setuid(uid) == -1 || geteuid() != getuid()))
return -1;
endpwent();
endgrent();
return 0;
}
/*
=item C<int daemon_become_user(uid_t uid, gid_t gid, char *user)>
Changes the owner and group of the process to C<uid> and C<gid>,
respectively. If C<user> is not null, the supplementary group list will be
initialised with I<initgroups(3)>. Otherwise, the supplementary group list
will be cleared of all groups. On success, returns C<0>. On error, returns
C<-1> with C<errno> set appropriately. Only I<root> can use this function.
=cut
*/
int daemon_become_user(uid_t uid, gid_t gid, char *user)
{
gid_t gids[10];
int g = 0;
if (setgroups(0, NULL) == -1 || (g = getgroups(0, NULL)) != 0)
{
/* FreeBSD always returns the primary group */
if (g != 1 || getgroups(10, gids) != 1 || gids[0] != getgid())
return -1;
}
if (setgid(gid) == -1 || getgid() != gid || getegid() != gid)
return -1;
if (user && initgroups(user, gid) == -1)
return -1;
if (setuid(uid) == -1 || getuid() != uid || geteuid() != uid)
return -1;
return 0;
}
/*
=item C<char *daemon_absolute_path(const char *path)>
Returns C<path> converted into an absolute path. Cleans up any C<.> and
C<..> and C<//> and trailing C</> found in the returned path. Note that the
returned path looks canonical but isn't, because symbolic links are not
followed and expanded. It is the caller's responsibility to deallocate the
path returned with I<free(3)> or I<mem_release(3)> or I<mem_destroy(3)>. It
is strongly recommended to use I<mem_destroy(3)>, because it also sets the
pointer variable to C<null>. On success, returns the absolute path. On
error, returns C<null> with C<errno> set appropriately.
=cut
*/
char *daemon_absolute_path(const char *path)
{
size_t path_len;
char *abs_path;
char *p;
if (!path)
return set_errnull(EINVAL);
/* Make path absolute and mostly canonical (don't follow symbolic links) */
if (*path != PATH_SEP)
{
long lim = limit_path();
char *cwd = mem_create(lim, char);
size_t cwd_len;
int rc;
if (!cwd)
return NULL;
if (!getcwd(cwd, lim))
{
mem_release(cwd);
return NULL;
}
cwd_len = strlen(cwd);
if (cwd_len + 1 + strlen(path) >= lim)
{
mem_release(cwd);
return set_errnull(ENAMETOOLONG);
}
rc = snprintf(cwd + cwd_len, lim - cwd_len, "%c%s", PATH_SEP, path);
if (rc == -1 || rc >= lim - cwd_len)
{
mem_release(cwd);
return set_errnull(ENAMETOOLONG);
}
abs_path = cwd;
}
else
{
if (!(abs_path = mem_strdup(path)))
return NULL;
}
/* Clean up any // and . and .. in the absolute path */
path_len = strlen(abs_path);
for (p = abs_path; *p; ++p)
{
if (p[0] == PATH_SEP)
{
if (p[1] == PATH_SEP)
{
memmove(p, p + 1, path_len + 1 - (p + 1 - abs_path));
--path_len;
--p;
}
else if (p[1] == '.')
{
if (p[2] == PATH_SEP || p[2] == nul)
{
int keep_sep = (p == abs_path && p[2] == nul);
memmove(p + keep_sep, p + 2, path_len + 1 - (p + 2 - abs_path));
path_len -= 2 - keep_sep;
--p;
}
else if (p[2] == '.' && (p[3] == PATH_SEP || p[3] == nul))
{
char *scan, *parent;
int keep_sep;
for (scan = parent = p; scan > abs_path; )
{
if (*--scan == PATH_SEP)
{
parent = scan;
break;
}
}
keep_sep = (parent == abs_path && p[3] == nul);
memmove(parent + keep_sep, p + 3, path_len + 1 - (p + 3 - abs_path));
path_len -= p + 3 - parent;
p = parent - 1;
}
}
}
}
/* Strip off any trailing / */
while (path_len > 1 && abs_path[path_len - 1] == PATH_SEP)
abs_path[--path_len] = nul;
return abs_path;
}
/*
=item C<int daemon_path_is_safe(const char *path, char *explanation, size_t explanation_size)>
Checks that the file referred to by C<path> is not group- or world-writable.
Also checks that the containing directories are not group- or
world-writable, following symbolic links. Useful when you need to know
whether or not you can trust a user supplied configuration/command file
before reading and acting upon its contents. On success, returns C<1> if
C<path> is safe or C<0> if it is not. When the path is not safe, an
explanation is written to the C<explanation> buffer (if it is not C<null>).
No more than C<explanation_size> bytes including the terminating C<nul> byte
will be written to the C<explanation> buffer. On error, returns C<-1> with
C<errno> set appropriately.
=cut
*/
static int daemon_check_path(char *path, char *explanation, size_t explanation_size, int level)
{
struct stat status[1];
char *sep;
int rc;
if (level > 16)
return set_errno(ELOOP);
for (sep = path + strlen(path); sep; sep = strrchr(path, PATH_SEP))
{
sep[sep == path] = nul;
if (lstat(path, status) == -1)
return -1;
if (S_ISLNK(status->st_mode))
{
size_t lim;
char *sym_linked;
char *tmp;
lim = limit_path();
if (!(sym_linked = mem_create(lim, char)))
return -1;
memset(sym_linked, 0, lim);
if (readlink(path, sym_linked, lim) == -1)
{
mem_release(sym_linked);
return -1;
}
if (*sym_linked != PATH_SEP)
{
if (!(tmp = mem_create(lim, char)))
{
mem_release(sym_linked);
return -1;
}
rc = snprintf(tmp, lim, "%s%c..%c%s", path, PATH_SEP, PATH_SEP, sym_linked);
if (rc == -1 || rc >= lim)
{
mem_release(sym_linked);
mem_release(tmp);
return set_errno(ENAMETOOLONG);
}
rc = snprintf(sym_linked, lim, "%s", tmp);
mem_release(tmp);
if (rc == -1 || rc >= lim)
{
mem_release(sym_linked);
return set_errno(ENAMETOOLONG);
}
}
tmp = daemon_absolute_path(sym_linked);
mem_release(sym_linked);
if (!(sym_linked = tmp))
return -1;
rc = daemon_check_path(sym_linked, explanation, explanation_size, level + 1);
mem_release(sym_linked);
switch (rc)
{
case -1: return -1;
case 0: return 0;
case 1: break;
}
}
else if (status->st_mode & (S_IWGRP | S_IWOTH))
{
if (explanation)
{
snprintf(explanation, explanation_size, "%s is %s%s%swritable", path,
(status->st_mode & S_IWGRP) ? "group-" : "",
((status->st_mode & (S_IWGRP | S_IWOTH)) == (S_IWGRP | S_IWOTH)) ? " and " : "",
(status->st_mode & S_IWOTH) ? "world-" : ""
);
}
return 0;
}
if (sep == path)
break;
}
return 1;
}
int daemon_path_is_safe(const char *path, char *explanation, size_t explanation_size)
{
char *abs_path;
int rc;
if (!path)
return set_errno(EINVAL);
abs_path = daemon_absolute_path(path);
if (!abs_path)
return -1;
rc = daemon_check_path(abs_path, explanation, explanation_size, 0);
mem_release(abs_path);
return rc;
}
/*
=item C<void *daemon_parse_config(const char *path, void *obj, daemon_config_parser_t *parser)>
Parses the text configuration file named C<path>. Blank lines are ignored.
Comments (C<'#'> to end of line) are ignored. Lines that end with C<'\'> are
joined with the following line. There may be whitespace characters, and even
a comment, after the C<'\'> character, but nothing else. The C<parser>
function is called with the client supplied C<obj>, the file name, the line
and the line number as arguments. On success, returns C<obj>. On error,
returns C<null> (i.e. if the configuration file could not be read). Note:
Don't parse config files unless they are "safe" as determined by
I<daemon_path_is_safe(3)>.
=cut
*/
void *daemon_parse_config(const char *path, void *obj, daemon_config_parser_t *parser)
{
FILE *conf;
char line[BUFSIZ];
char buf[BUFSIZ];
int lineno;
int rc;
if (!(conf = fopen(path, "r")))
return NULL;
line[0] = nul;
for (lineno = 1; fgets(buf, BUFSIZ, conf); ++lineno)
{
char *start = buf;
char *end;
size_t length;
int cont_line;
/* Strip trailing comments */
if ((end = strchr(start, '#')))
*end = nul;
else
end = start + strlen(start);
/* Skip trailing spaces (allows comments after line continuation) */
while (end > start && isspace((int)(unsigned char)end[-1]))
--end;
/* Skip empty lines */
if (*start == nul || start == end)
continue;
/* Perform line continuation */
if ((cont_line = (end[-1] == '\\')))
--end;
length = strlen(line);
rc = snprintf(line + length, BUFSIZ - length, "%*.*s", (int)(end - start), (int)(end - start), start);
if (rc == -1 || rc >= BUFSIZ - length)
return NULL;
if (cont_line)
continue;
/* Parse the resulting line */
parser(obj, path, line, lineno);
line[0] = nul;
}
fclose(conf);
return obj;
}
/*
C<int daemon_construct_pidfile(const char *name, char **pidfile)>
Constructs the pidfile for the given C<name> in C<pidfile>. If C<name> is
already an absolute path, it is just copied into the new buffer directly. On
success, returns C<0>, and the resulting buffer in C<pidfile> must be
deallocated by the caller. On error, returns C<-1> with C<errno> set
appropriately.
*/
static int daemon_construct_pidfile(const char *name, char **pidfile)
{
long path_len;
const char *pid_dir;
char *suffix = ".pid";
size_t size;
/* Construct the pidfile */
path_len = limit_path();
pid_dir = (getuid()) ? USER_PID_DIR : ROOT_PID_DIR;
size = ((*name == PATH_SEP) ? strlen(name) : sizeof(pid_dir) + 1 + strlen(name) + strlen(suffix)) + 1;
if (size > path_len)
return set_errno(ENAMETOOLONG);
if (!*pidfile && !(*pidfile = mem_create(path_len, char)))
return -1;
if (*name == PATH_SEP)
snprintf(*pidfile, path_len, "%s", name);
else
snprintf(*pidfile, path_len, "%s%c%s%s", pid_dir, PATH_SEP, name, suffix);
return 0;
}
/*
C<int daemon_lock_pidfile(const char *pidfile)>
Open and lock the file referred to by C<pidfile>. On success, returns the
file descriptor of the opened and locked file. On error, returns C<-1> with
C<errno> set appropriately.
*/
static int daemon_lock_pidfile(char *pidfile)
{
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
struct stat statbuf_fd[1], statbuf_fs[1];
int pid_fd;
start:
/* This is broken over NFS (Linux). So pidfiles must reside locally. */
if ((pid_fd = open(pidfile, O_RDWR | O_CREAT | O_EXCL, mode)) == -1)
{
if (errno != EEXIST)
return -1;
/*
** The pidfile already exists. Is it locked?
** If so, another invocation is still alive.
** If not, the invocation that created it has died.
** Open the pidfile to attempt a lock.
*/
if ((pid_fd = open(pidfile, O_RDWR)) == -1)
{
/*
** We couldn't open the file. That means that it existed
** a moment ago but has been since been deleted. Maybe if
** we try again now, it'll work (unless another process is
** about to re-create it before we do, that is).
*/
if (errno == ENOENT)
goto start;
return -1;
}
}
if (fcntl_lock(pid_fd, F_SETLK, F_WRLCK, SEEK_SET, 0, 0) == -1)
{
close(pid_fd);
return -1;
}
/*
** The pidfile may have been unlinked, after we opened it, by another daemon
** process that was dying between the last open() and the fcntl(). But that
** shouldn't happen any more. There's no use hanging on to a locked file that
** doesn't exist (and there's nothing to stop another daemon process from
** creating and locking a new instance of the file. So, if the pidfile has
** been deleted, we abandon this lock and start again. Note that it may have
** been deleted and subsequently re-created by yet another daemon process just
** starting up, so check that that hasn't happened as well by comparing inode
** numbers. If it has, we also abandon this lock and start again.
*/
if (fstat(pid_fd, statbuf_fd) == -1)
{
/* This shouldn't happen */
close(pid_fd);
return -1;
}
if (stat(pidfile, statbuf_fs) == -1)
{
/* The pidfile has been unlinked so we start again */
if (errno == ENOENT)
{
close(pid_fd);
goto start;
}
close(pid_fd);
return -1;
}
else if (statbuf_fd->st_ino != statbuf_fs->st_ino)
{
/* The pidfile has been unlinked and re-created so we start again */
close(pid_fd);
goto start;
}
/* Prevent leaking this file descriptor into child processes. */
fcntl_set_fdflag(pid_fd, FD_CLOEXEC);
/* Record its dev and inode so we know not to delete the wrong pidfile later */
g.pid_dev = statbuf_fd->st_dev;
g.pid_inode = statbuf_fd->st_ino;
return pid_fd;
}
/*
C<int daemon_pidfile_unlocked(const char *name)>
Equivalent to I<daemon_pidfile(3)> except that the daemon module's mutex is
not locked and unlocked.
*/
static int daemon_pidfile_unlocked(const char *name)
{
char pid[32];
/* Check argument */
if (!name)
return set_errno(EINVAL);
/* Build the pidfile path */
if (daemon_construct_pidfile(name, &g.pidfile) == -1)
return -1;
/* Open it and lock it (if possible) */
if ((g.pid_fd = daemon_lock_pidfile(g.pidfile)) == -1)
{
mem_destroy(&g.pidfile);
return -1;
}
/* Store our pid */
snprintf(pid, 32, "%d\n", (int)getpid());
if (write(g.pid_fd, pid, strlen(pid)) != strlen(pid))
{
daemon_close();
return -1;
}
/*
** Flaw: If someone unceremoniously unlinks the pidfile,
** we won't know about it and nothing will stop another
** invocation from starting up. However, if that does happen,
** and another invocation does start, and then this invocation
** terminates, it won't delete the other instance's pidfile.
*/
return 0;
}
/*
=item C<int 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 locations for the
file is defined in C<ROOT_PID_DIR> for I<root> (C<"/var/run"> by default)
and C<USER_PID_DIR> for all other users (C<"/tmp"> by default). The name of
the file is the name of the daemon (given by the I<name> argument) followed
by C<".pid"> (If I<name> is an absolute file path, it is used as is). The
presence of this file will prevent two daemons with the same name from
running at the same time. On success, returns C<0>. On error, returns C<-1>
with C<errno> set appropriately. B<Note:> This is called by
I<daemon_init(3)>, so there is usually no need to call this function
directly.
=cut
*/
int daemon_pidfile(const char *name)
{
int rc;
ptry(pthread_mutex_lock(&g.lock))
rc = daemon_pidfile_unlocked(name);
ptry(pthread_mutex_unlock(&g.lock))
return rc;
}
/*
=item C<int daemon_init(const char *name)>
Initialises a daemon by performing the following tasks:
=over 4
=item *
If the process was not invoked by I<init(8)> (i.e. parent process id is 1)
or I<inetd(8)> (i.e. C<stdin> is a socket):
=over 4
=item *
Ignore C<SIGHUP> signals in case the current process session leader
terminates while attached to a controlling terminal causing us to
receive a C<SIGHUP> signal before we start our own process session below.
This can happen when the process that calls I<daemon_init(3)> was itself
invoked interactively via the shell builtin C<exec>. When this initial
process terminates below, the terminal emulator that invoked the shell also
terminates.
=item *
Background the process to lose process group leadership.
=item *
Start a new process session.
=item *
Background the process again to lose process session leadership. Under
I<SVR4>, this prevents the process from ever gaining a controlling terminal.
This is only necessary under I<SVR4>, but is always done for simplicity.
Note that ignoring C<SIGHUP> signals earlier means that when the newly
created process session leader terminates, then even if it has a controlling
terminal open, the newly backgrounded process won't receive the
corresponding C<SIGHUP> signal that is sent to all processes in the process
session's foreground process group, because it inherited signal dispositions
from the initial process.
=back
=item *
Change the current directory to the root directory so as not to hamper
umounts.
=item *
Clear the umask to enable explicit file creation modes.
=item *
Close all open file descriptors. If the process was invoked by I<inetd(8)>,
C<stdin>, C<stdout> and C<stderr> are left open, because they are open to a
socket.
=item *
Open C<stdin>, C<stdout> and C<stderr> to C</dev/null> in case something
requires them to be open. Of course, this is not done if the process was
invoked by I<inetd(8)>.
=item *
If C<name> is non-null, create and lock a file containing the process id of
the process. The presence of this locked file prevents two instances of a
daemon with the same name from running at the same time. The default
location of the pidfile is C</var/run> for I<root> (C</etc> on I<Solaris>,
C</opt/local/var/run> on I<macOS> when installed via I<macports>), and
C</tmp> for ordinary users.
=back
On success, returns C<0>. On error, returns C<-1> with C<errno> set
appropriately.
=cut
*/
int daemon_init(const char *name)
{
pid_t pid;
long nopen;
int fd;
/*
** Don't setup a daemon-friendly process context
** if started by init(8) or inetd(8).
*/
if (!(daemon_started_by_init() || daemon_started_by_inetd()))
{
/*
** Ignore SIGHUP signals in case the current process session leader
** terminates while attached to a controlling terminal causing us to
** receive a SIGHUP signal before we start our own process session below.
*/
struct sigaction act[1];
act->sa_handler = SIG_IGN;
sigemptyset(&act->sa_mask);
act->sa_flags = 0;
if (sigaction(SIGHUP, act, NULL) == -1)
return -1;
/*
** Background the process.
** Lose process session/group leadership.
*/
if ((pid = fork()) == -1)
return -1;
if (pid)
{
#ifndef DISABLE_DAEMON_INIT_EXIT_DELAY_MSEC
/*
** If the user has requested an exit delay because they use
** "exec daemon" to run KDE applications that are failing
** immediately, then delay the parent's exit by the given
** number of milliseconds.
**
** Note: We are not delaying the start of the client, just the
** exit of the initial parent process.
**
** Note Also: I have no idea why this delay seems to fix
** "exec daemon kde-app" failures.
**
** Also Note: This has nothing to do with daemon. The same
** failures occur with "exec kde-app".
**
** Also note: Setting DAEMON_INIT_EXIT_DELAY_MSEC to at least 400
** (i.e. 0.4 seconds) seems to be enough. Your mileage may vary.
*/
char *delay_var;
long delay_msec;
if ((delay_var = getenv("DAEMON_INIT_EXIT_DELAY_MSEC")) && (delay_msec = atol(delay_var)) > 0)
nap(delay_msec / 1000, (delay_msec & 1000) * 1000);
#endif
exit(EXIT_SUCCESS);
}
/* Become a process session leader. */
/* This can only fail when we're already a session leader. */
setsid();
/*
** Lose process session leadership to prevent gaining a controlling
** terminal in SVR4. Always do it in case we don't know what flavour
** of UNIX this system is.
*/
if ((pid = fork()) == -1)
return -1;
if (pid)
exit(EXIT_SUCCESS);
}
/* Enter the root directory to prevent hampering umounts. */
if (chdir(ROOT_DIR) == -1)
return -1;