summaryrefslogtreecommitdiff
path: root/src/librc/librc-daemon.c
blob: 6e7d57fd236a6f17afdb33a3ae03e090450a33c7 (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
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
/*
  librc-daemon
  Finds PID for given daemon criteria
*/

/*
 * Copyright (c) 2007-2009 Roy Marples <roy@marples.name>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "librc.h"

#if defined(__linux__)
static bool
pid_is_exec(pid_t pid, const char *exec)
{
	char buffer[32];
	FILE *fp;
	int c;
	bool retval = false;

	exec = basename_c(exec);
	snprintf(buffer, sizeof(buffer), "/proc/%d/stat", pid);
	if ((fp = fopen(buffer, "r"))) {
		while ((c = getc(fp)) != EOF && c != '(')
			;
		if (c == '(') {
			while ((c = getc(fp)) != EOF && c == *exec)
				exec++;
			if (c == ')' && *exec == '\0')
				retval = true;
		}
		fclose(fp);
	}
	return retval;
}

static bool
pid_is_argv(pid_t pid, const char *const *argv)
{
	char cmdline[32];
	int fd;
	char buffer[PATH_MAX];
	char *p;
	ssize_t bytes;

	snprintf(cmdline, sizeof(cmdline), "/proc/%u/cmdline", pid);
	if ((fd = open(cmdline, O_RDONLY)) < 0)
		return false;
	bytes = read(fd, buffer, sizeof(buffer));
	close(fd);
	if (bytes == -1)
		return false;

	buffer[bytes] = '\0';
	p = buffer;
	while (*argv) {
		if (strcmp(*argv, p) != 0)
			return false;
		argv++;
		p += strlen(p) + 1;
		if ((unsigned)(p - buffer) > sizeof(buffer))
			return false;
	}
	return true;
}

RC_PIDLIST *
rc_find_pids(const char *exec, const char *const *argv, uid_t uid, pid_t pid)
{
	DIR *procdir;
	struct dirent *entry;
	pid_t p;
	char buffer[PATH_MAX];
	struct stat sb;
	pid_t runscript_pid = 0;
	char *pp;
	RC_PIDLIST *pids = NULL;
	RC_PID *pi;

	if ((procdir = opendir("/proc")) == NULL)
		return NULL;

	/*
	  We never match RC_RUNSCRIPT_PID if present so we avoid the below
	  scenario

	  /etc/init.d/ntpd stop does
	  start-stop-daemon --stop --name ntpd
	  catching /etc/init.d/ntpd stop

	  nasty
	*/

	if ((pp = getenv("RC_RUNSCRIPT_PID"))) {
		if (sscanf(pp, "%d", &runscript_pid) != 1)
			runscript_pid = 0;
	}

	while ((entry = readdir(procdir)) != NULL) {
		if (sscanf(entry->d_name, "%d", &p) != 1)
			continue;
		if (runscript_pid != 0 && runscript_pid == p)
			continue;
		if (pid != 0 && pid != p)
			continue;
		if (uid) {
			snprintf(buffer, sizeof(buffer), "/proc/%d", p);
			if (stat(buffer, &sb) != 0 || sb.st_uid != uid)
				continue;
		}
		if (exec && !pid_is_exec(p, exec))
			continue;
		if (argv &&
		    !pid_is_argv(p, (const char *const *)argv))
			continue;
		if (!pids) {
			pids = xmalloc(sizeof(*pids));
			LIST_INIT(pids);
		}
		pi = xmalloc(sizeof(*pi));
		pi->pid = p;
		LIST_INSERT_HEAD(pids, pi, entries);
	}
	closedir(procdir);
	return pids;
}
librc_hidden_def(rc_find_pids)

#elif BSD

# if defined(__NetBSD__) || defined(__OpenBSD__)
#  define _KVM_GETPROC2
#  define _KINFO_PROC kinfo_proc2
#  define _KVM_GETARGV kvm_getargv2
#  define _GET_KINFO_UID(kp) (kp.p_ruid)
#  define _GET_KINFO_COMM(kp) (kp.p_comm)
#  define _GET_KINFO_PID(kp) (kp.p_pid)
#  define _KVM_PATH NULL
#  define _KVM_FLAGS KVM_NO_FILES
# else
#  ifndef KERN_PROC_PROC
#    define KERN_PROC_PROC KERN_PROC_ALL
#  endif
#  define _KINFO_PROC kinfo_proc
#  define _KVM_GETARGV kvm_getargv
#  if defined(__DragonFly__)
#    define _GET_KINFO_UID(kp) (kp.kp_ruid)
#    define _GET_KINFO_COMM(kp) (kp.kp_comm)
#    define _GET_KINFO_PID(kp) (kp.kp_pid)
#  else
#    define _GET_KINFO_UID(kp) (kp.ki_ruid)
#    define _GET_KINFO_COMM(kp) (kp.ki_comm)
#    define _GET_KINFO_PID(kp) (kp.ki_pid)
#  endif
#  define _KVM_PATH _PATH_DEVNULL
#  define _KVM_FLAGS O_RDONLY
# endif

RC_PIDLIST *
rc_find_pids(const char *exec, const char *const *argv, uid_t uid, pid_t pid)
{
	static kvm_t *kd = NULL;
	char errbuf[_POSIX2_LINE_MAX];
	struct _KINFO_PROC *kp;
	int i;
	int processes = 0;
	int pargc = 0;
	char **pargv;
	RC_PIDLIST *pids = NULL;
	RC_PID *pi;
	pid_t p;
	const char *const *arg;
	int match;

	if ((kd = kvm_openfiles(_KVM_PATH, _KVM_PATH,
		    NULL, _KVM_FLAGS, errbuf)) == NULL)
	{
		fprintf(stderr, "kvm_open: %s\n", errbuf);
		return NULL;
	}

#ifdef _KVM_GETPROC2
	kp = kvm_getproc2(kd, KERN_PROC_ALL, 0, sizeof(*kp), &processes);
#else
	kp = kvm_getprocs(kd, KERN_PROC_PROC, 0, &processes);
#endif
	if ((kp == NULL && processes > 0) || (kp != NULL && processes < 0)) {
		fprintf(stderr, "kvm_getprocs: %s\n", kvm_geterr(kd));
		kvm_close(kd);
		return NULL;
	}

	if (exec)
		exec = basename_c(exec);
	for (i = 0; i < processes; i++) {
		p = _GET_KINFO_PID(kp[i]);
		if (pid != 0 && pid != p)
			continue;
		if (uid != 0 && uid != _GET_KINFO_UID(kp[i]))
			continue;
		if (exec) {
			if (!_GET_KINFO_COMM(kp[i]) ||
			    strcmp(exec, _GET_KINFO_COMM(kp[i])) != 0)
				continue;
		}
		if (argv && *argv) {
			pargv = _KVM_GETARGV(kd, &kp[i], pargc);
			if (!pargv || !*pargv)
				continue;
			arg = argv;
			match = 1;
			while (*arg && *pargv)
				if (strcmp(*arg++, *pargv++) != 0) {
					match = 0;
					break;
				}
			if (!match)
				continue;
		}
		if (!pids) {
			pids = xmalloc(sizeof(*pids));
			LIST_INIT(pids);
		}
		pi = xmalloc(sizeof(*pi));
		pi->pid = p;
		LIST_INSERT_HEAD(pids, pi, entries);
	}
	kvm_close(kd);

	return pids;
}
librc_hidden_def(rc_find_pids)

#else
#  error "Platform not supported!"
#endif

static bool
_match_daemon(const char *path, const char *file, RC_STRINGLIST *match)
{
	char *line = NULL;
	size_t len = 0;
	char ffile[PATH_MAX];
	FILE *fp;
	RC_STRING *m;

	snprintf(ffile, sizeof(ffile), "%s/%s", path, file);
	fp = fopen(ffile, "r");

	if (!fp)
		return false;

	while ((rc_getline(&line, &len, fp))) {
		TAILQ_FOREACH(m, match, entries)
		    if (strcmp(line, m->value) == 0) {
			    TAILQ_REMOVE(match, m, entries);
			    break;
		    }
		if (!TAILQ_FIRST(match))
			break;
	}
	fclose(fp);
	free(line);
	if (TAILQ_FIRST(match))
		return false;
	return true;
}

static RC_STRINGLIST *
_match_list(const char *exec, const char *const *argv, const char *pidfile)
{
	RC_STRINGLIST *match = rc_stringlist_new();
	int i = 0;
	size_t l;
	char *m;

	if (exec) {
		l = strlen(exec) + 6;
		m = xmalloc(sizeof(char) * l);
		snprintf(m, l, "exec=%s", exec);
		rc_stringlist_add(match, m);
		free(m);
	}

	while (argv && argv[i]) {
		l = strlen(*argv) + strlen("argv_=") + 16;
		m = xmalloc(sizeof(char) * l);
		snprintf(m, l, "argv_0=%s", argv[i++]);
		rc_stringlist_add(match, m);
		free(m);
	}

	if (pidfile) {
		l = strlen(pidfile) + 9;
		m = xmalloc(sizeof(char) * l);
		snprintf(m, l, "pidfile=%s", pidfile);
		rc_stringlist_add(match, m);
		free(m);
	}

	return match;
}

bool
rc_service_daemon_set(const char *service, const char *exec,
    const char *const *argv,
    const char *pidfile, bool started)
{
	char dirpath[PATH_MAX];
	char file[PATH_MAX];
	int nfiles = 0;
	char oldfile[PATH_MAX] = { '\0' };
	bool retval = false;
	DIR *dp;
	struct dirent *d;
	RC_STRINGLIST *match;
	int i = 0;
	FILE *fp;

	if (!exec && !pidfile) {
		errno = EINVAL;
		return false;
	}

	snprintf(dirpath, sizeof(dirpath), RC_SVCDIR "/daemons/%s",
	    basename_c(service));

	/* Regardless, erase any existing daemon info */
	if ((dp = opendir(dirpath))) {
		match = _match_list(exec, argv, pidfile);
		while ((d = readdir(dp))) {
			if (d->d_name[0] == '.')
				continue;

			snprintf(file, sizeof(file), "%s/%s",
			    dirpath, d->d_name);
			nfiles++;

			if (!*oldfile) {
				if (_match_daemon(dirpath, d->d_name, match)) {
					unlink(file);
					strlcpy(oldfile, file, sizeof(oldfile));
					nfiles--;
				}
			} else {
				rename(file, oldfile);
				strlcpy(oldfile, file, sizeof(oldfile));
			}
		}
		closedir(dp);
		rc_stringlist_free(match);
	}

	/* Now store our daemon info */
	if (started) {
		if (mkdir(dirpath, 0755) == 0 || errno == EEXIST) {
			snprintf(file, sizeof(file), "%s/%03d",
			    dirpath, nfiles + 1);
			if ((fp = fopen(file, "w"))) {
				fprintf(fp, "exec=");
				if (exec)
					fprintf(fp, "%s", exec);
				while (argv && argv[i]) {
					fprintf(fp, "\nargv_%d=%s", i, argv[i]);
					i++;
				}
				fprintf(fp, "\npidfile=");
				if (pidfile)
					fprintf(fp, "%s", pidfile);
				fprintf(fp, "\n");
				fclose(fp);
				retval = true;
			}
		}
	} else
		retval = true;

	return retval;
}
librc_hidden_def(rc_service_daemon_set)

bool
rc_service_started_daemon(const char *service,
    const char *exec, const char *const *argv, int indx)
{
	char dirpath[PATH_MAX];
	char file[16];
	RC_STRINGLIST *match;
	bool retval = false;
	DIR *dp;
	struct dirent *d;

	if (!service || !exec)
		return false;

	snprintf(dirpath, sizeof(dirpath), RC_SVCDIR "/daemons/%s",
	    basename_c(service));
	match = _match_list(exec, argv, NULL);

	if (indx > 0) {
		snprintf(file, sizeof(file), "%03d", indx);
		retval = _match_daemon(dirpath, file, match);
	} else {
		if ((dp = opendir(dirpath))) {
			while ((d = readdir(dp))) {
				if (d->d_name[0] == '.')
					continue;
				retval = _match_daemon(dirpath, d->d_name, match);
				if (retval)
					break;
			}
			closedir(dp);
		}
	}

	rc_stringlist_free(match);
	return retval;
}
librc_hidden_def(rc_service_started_daemon)

bool
rc_service_daemons_crashed(const char *service)
{
	char dirpath[PATH_MAX];
	DIR *dp;
	struct dirent *d;
	char *path = dirpath;
	FILE *fp;
	char *line = NULL;
	size_t len = 0;
	char **argv = NULL;
	char *exec = NULL;
	char *name = NULL;
	char *pidfile = NULL;
	pid_t pid = 0;
	RC_PIDLIST *pids;
	RC_PID *p1;
	RC_PID *p2;
	char *p;
	char *token;
	bool retval = false;
	RC_STRINGLIST *list = NULL;
	RC_STRING *s;
	size_t i;

	path += snprintf(dirpath, sizeof(dirpath), RC_SVCDIR "/daemons/%s",
	    basename_c(service));

	if (!(dp = opendir(dirpath)))
		return false;

	while ((d = readdir(dp))) {
		if (d->d_name[0] == '.')
			continue;

		snprintf(path, sizeof(dirpath) - (path - dirpath), "/%s",
		    d->d_name);
		fp = fopen(dirpath, "r");
		if (!fp)
			break;

		while ((rc_getline(&line, &len, fp))) {
			p = line;
			if ((token = strsep(&p, "=")) == NULL || !p)
				continue;

			if (!*p)
				continue;

			if (strcmp(token, "exec") == 0) {
				if (exec)
					free(exec);
				exec = xstrdup(p);
			} else if (strncmp(token, "argv_", 5) == 0) {
				if (!list)
					list = rc_stringlist_new();
				rc_stringlist_add(list, p);
			} else if (strcmp(token, "name") == 0) {
				if (name)
					free(name);
				name = xstrdup(p);
			} else if (strcmp(token, "pidfile") == 0) {
				pidfile = xstrdup(p);
				break;
			}
		}
		fclose(fp);

		pid = 0;
		if (pidfile) {
			retval = true;
			if ((fp = fopen(pidfile, "r"))) {
				if (fscanf(fp, "%d", &pid) == 1)
					retval = false;
				fclose(fp);
			}
			free(pidfile);
			pidfile = NULL;

			/* We have the pid, so no need to match
			   on exec or name */
			free(exec);
			exec = NULL;
			free(name);
			name = NULL;
		} else {
			if (exec) {
				if (!list)
					list = rc_stringlist_new();
				if (!TAILQ_FIRST(list))
					rc_stringlist_add(list, exec);

				free(exec);
				exec = NULL;
			}

			if (list) {
				/* We need to flatten our linked list
				   into an array */
				i = 0;
				TAILQ_FOREACH(s, list, entries)
				    i++;
				argv = xmalloc(sizeof(char *) * (i + 1));
				i = 0;
				TAILQ_FOREACH(s, list, entries)
				    argv[i++] = s->value;
				argv[i] = '\0';
			}
		}

		if (!retval) {
			if (pid != 0) {
				if (kill(pid, 0) == -1 && errno == ESRCH)
					retval = true;
			} else if ((pids = rc_find_pids(exec,
				    (const char *const *)argv,
				    0, pid)))
			{
				p1 = LIST_FIRST(pids);
				while (p1) {
					p2 = LIST_NEXT(p1, entries);
					free(p1);
					p1 = p2;
				}
				free(pids);
			} else
				retval = true;
		}
		rc_stringlist_free(list);
		list = NULL;
		free(argv);
		argv = NULL;
		free(exec);
		exec = NULL;
		free(name);
		name = NULL;
		if (retval)
			break;
	}
	closedir(dp);
	free(line);

	return retval;
}
librc_hidden_def(rc_service_daemons_crashed)