forked from CloudStack-extras/CloudStack-archive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdaemonize.c
332 lines (294 loc) · 8.52 KB
/
daemonize.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
/*
UNIX daemonizer. Daemonizes any non-interactive console program and watches over it.
Whenever a signal is sent to this process, it halts the daemonized process as well.
To compile: cc -o daemonize daemonize.c
Usage: ./daemonize -?
Users of this: catalina initscript
*/
#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
#include <stdlib.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <errno.h>
#include <pwd.h>
#define RUNNING_DIR "/"
#define PIDFILE "/var/run/daemonize.pid"
#define VARLOGFILE "/var/log/daemon.log"
#define PROGNAME "daemonized"
#define DEFAULTUSER "root"
char * pidfile = PIDFILE;
char * varlogfile = VARLOGFILE;
char * progname = PROGNAME;
char * user = PROGNAME;
void initialize_syslog(const char*pn) {
openlog(pn,LOG_PID,LOG_DAEMON);
syslog(LOG_INFO, "syslog connection opened");
}
void cleanup_syslog() {
syslog(LOG_INFO, "syslog connection closed");
closelog();
}
int killed = 0;
int killsignal = 0;
int pidfile_fd;
int varlogfile_fd;
int uid = 0; int gid = 0;
struct passwd *creds;
void signal_handler(sig)
int sig;
{
killsignal = sig;
switch(sig) {
case SIGCHLD:
syslog(LOG_INFO,"sigchild signal caught");
break;
case SIGHUP:
syslog(LOG_INFO,"hangup signal caught");
killed = 1;
break;
case SIGTERM:
syslog(LOG_INFO,"terminate signal caught");
killed = 1;
break;
case SIGINT:
syslog(LOG_INFO,"keyboard interrupt signal caught");
killed = 1;
break;
}
}
int daemonize(const char*prog_name)
{
char str[10];
int i;
int bufsize=1024; char *buf = malloc(1024);
umask( S_IWGRP | S_IROTH | S_IWOTH ); /* set newly created file permissions */
/* test logfile */
varlogfile_fd=open(varlogfile,O_RDWR|O_CREAT|O_APPEND,0666);
if (varlogfile_fd == -1) {
snprintf(buf,bufsize,"Could not open output file %s -- exiting",varlogfile); perror(buf);
return 1; /* exitvalue */
}
if (uid != 0) {
chown(varlogfile,uid,gid);
}
close(varlogfile_fd);
pidfile_fd=open(pidfile,O_RDWR|O_CREAT,0666);
if (pidfile_fd<0) {
snprintf(buf,bufsize,"The PID file %s cannot be opened -- exiting",pidfile); perror(buf);
return 2; /* exitvalue */
}
if (lockf(pidfile_fd,F_TEST,0)==1) {
snprintf(buf,bufsize,"A daemon is already running (cannot lock PID file %s) -- exiting",pidfile); perror(buf);
return 3; /* exitvalue */
}
close(pidfile_fd);
if(getppid()==1) return 0; /* already a daemon */
i=fork();
if (i < 0) return 4; /* exitvalue */ /* fork error */
if (i > 0) exit(0); /* parent exits */
/* child (daemon) continues */
setsid(); /* obtain a new process group */
chdir(RUNNING_DIR); /* change running directory */
/* close FDs and reopen to logfile */
for (i=getdtablesize();i>=0;--i) close(i); /* close all descriptors */
varlogfile_fd=open(varlogfile,O_RDWR|O_APPEND,0666); dup(varlogfile_fd); dup(varlogfile_fd); /* handle standart I/O */
initialize_syslog(prog_name); /* set up syslog */
/* PID file */
pidfile_fd=open(pidfile,O_RDWR|O_CREAT,0666);
if (pidfile_fd<0) {
syslog(LOG_ERR,"The PID file %s cannot be opened (%m) -- exiting",pidfile);
return 2; /* exitvalue */
}
if (lockf(pidfile_fd,F_TLOCK,0)<0) {
syslog(LOG_ERR,"A daemon is already running -- cannot lock PID file %s (%m) -- exiting",pidfile);
return 3; /* exitvalue */
}
/* first instance continues */
/* record pid to pidfile */
sprintf(str,"%d\n",getpid());
if (write(pidfile_fd,str,strlen(str)) < strlen(str)) {
syslog(LOG_ERR,"Could not write PID into PID file %s (%m) -- exiting",pidfile);
return 5; /* exitvalue */
}
signal(SIGTSTP,SIG_IGN); /* ignore tty signals */
signal(SIGTTOU,SIG_IGN);
signal(SIGTTIN,SIG_IGN);
signal(SIGHUP,signal_handler); /* catch hangup signal */
signal(SIGTERM,signal_handler); /* catch kill signal */
signal(SIGINT,signal_handler); /* catch keyboard interrupt signal */
return 0;
}
void cleanup() {
cleanup_syslog();
unlink(pidfile);
close(pidfile_fd);
close(varlogfile_fd);
}
void usage(char * cmdname) {
fprintf (stderr,
"Usage: %s [options...] -- <command> [command-specific arguments...]\n"
"Daemonize any program.\n"
"\n"
"Options:\n"
"\n"
" -l <logfile>: log stdout/stderr to this *absolute* path (default "VARLOGFILE")\n"
" -u <username>: setuid() to this user name before starting the program (default "DEFAULTUSER")\n"
" -p <pidfile>: lock and write the PID to this *absolute* path (default "PIDFILE")\n"
" -n <progname>: name the daemon assumes (default "PROGNAME")\n"
" -h: show this usage guide\n"
"\n"
"Exit status:\n"
" 0 if daemonized correctly\n"
" other if an error took place\n"
"", cmdname);
exit(0);
}
int parse_args(int argc,char ** argv) {
int index;
int c;
// pidfile = PIDFILE;
// varlogfile = VARLOGFILE;
// progname = PROGNAME;
opterr = 0;
while ((c = getopt (argc, argv, "l:p:n:u:")) != -1)
switch (c)
{
case 'l':
varlogfile = optarg;
break;
case 'p':
pidfile = optarg;
break;
case 'n':
progname = optarg;
break;
case 'u':
if (getuid() != 0) {
fprintf (stderr, "-u can only be used by root.\nSee help with -h\n", user);
exit(64);
}
user = optarg;
creds = getpwnam(user);
if (creds == NULL) {
fprintf (stderr, "User %s was not found in the user database.\nSee help with -h\n", user);
exit(63);
}
uid = creds->pw_uid; gid = creds->pw_gid;
break;
// case 'h':
// break;
// usage(argv[0]); /* halts after this */
case '?':
if (optopt == '?' || optopt == 'h')
usage(argv[0]); /* halts after this */
if (optopt == 'l' || optopt == 'p' || optopt == 'n')
fprintf (stderr, "Option -%c requires an argument.\nSee help with -h\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\nSee help with -h\n", optopt);
else
fprintf (stderr, "Unknown option character `\\x%x'.\nSee help with -h\n", optopt);
exit(64); /* exitvalue */
default:
abort ();
}
for (index = optind; index < argc; index++);
if (index == optind) {
fprintf (stderr, "You need to specify a command to run.\nSee help with -h\n", optopt);
exit(64); /* exitvalue */
}
return optind;
}
int main(int argc, char** argv)
{
/* parse command line arguments, we will use the first non-option one as the starting point */
int i;
char ** newargv = calloc(argc+1, sizeof(char**));
int startat = parse_args(argc,argv);
int newargc = argc - startat;
for (i = startat; i < argc; i++) { newargv[i-startat] = argv[i]; }
/* try and daemonize */
int daemonret = daemonize(progname);
if (daemonret) exit(daemonret);
syslog(LOG_INFO,"successfully daemonized");
/* fork */
int pid, wpid, status, execret;
syslog(LOG_INFO,"starting %s in subprocess",newargv[0]);
pid = fork();
if (pid < 0) {
/* failed to fork, damnit! */
syslog(LOG_ERR,"could not fork to run %s as a child process (%m)",newargv[0]);
exit(4); /* exitvalue */
}
else if (pid == 0) {
/* child */
if (uid != 0) {
execret = setgid(gid);
if (execret == -1) {
syslog(LOG_ERR,"could not setgid() to gid %d",gid);
exit(8); /* exitvalue */
}
execret = setuid(uid);
if (execret == -1) {
syslog(LOG_ERR,"could not setuid() to uid %d",uid);
exit(8); /* exitvalue */
}
}
execret = execvp(newargv[0],newargv);
if (errno == 2) {
syslog(LOG_ERR,"could not run program: no such file or directory");
exit(127);
}
if (errno == 13) {
syslog(LOG_ERR,"could not run program: permission denied");
exit(126);
}
syslog(LOG_ERR,"could not run program: unknown reason");
exit(255);
}
/* parent continues here */
syslog(LOG_INFO,"successfully started subprocess -- PID %d",pid);
int finalexit = 0;
int waitret = 0;
while (1) {
if (killed) {
kill(pid,killsignal);
killed = 0;
}
waitret = waitpid(pid,&status,WNOHANG);
if (waitret == pid) break;
usleep(250000);
}
if WIFEXITED(status) {
switch (WEXITSTATUS(status)) {
case 0:
syslog(LOG_INFO,"%s exited normally",newargv[0]);
break;
case 126:
syslog(LOG_ERR,"%s: permission denied",newargv[0]);
finalexit = 126; /* exitvalue */
break;
case 127:
syslog(LOG_ERR,"%s: command not found",newargv[0]);
finalexit = 127; /* exitvalue */
break;
default:
syslog(LOG_INFO,"%s exited abnormally with status %d",newargv[0],WEXITSTATUS(status));
finalexit = 6; /* exitvalue */
}
}
if WIFSIGNALED(status) {
syslog(LOG_INFO,"%s was killed with signal %d",newargv[0],WTERMSIG(status));
finalexit = 7; /* exitvalue */
}
syslog(LOG_INFO,"shutting down");
cleanup();
exit(finalexit);
}
/* EOF */