summaryrefslogtreecommitdiffabout
path: root/dircond.c
blob: 682e1c3b3425016fd38038d590acf594878bf806 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <fcntl.h>
#include <syslog.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>
#include <errno.h>
#include <pwd.h>
#include <signal.h>
#include <time.h>
#include <sys/inotify.h>
#include <sys/wait.h>
#include <sys/stat.h>

/* Configuration settings */
const char *program_name;         /* This program name */
int foreground;                   /* Remain in the foreground */
int facility = -1;                /* Use this syslog facility for logging.
				     -1 means log to stderr */
int debug_level;                  /* Debug verbosity level */
unsigned handler_timeout = 5;     /* Timeout for handler program (seconds) */
int autowatch;                    /* Automatically add directories created
				     under watchpoints to the watcher. If set
				     to -1, nesting level is not limited. If
				     set to a positive value, this value limits
				     the nesting depth. */

/* Event codes */
enum {
	evt_create,                  /* file has been created */ 
	evt_delete,                  /* file has been deleted */
	evt_close,                   /* file has been modified and closed */
	evt_max                      /* number of handled events */
};

/* Handler flags. */
#define HF_NOWAIT 0x01       /* Don't wait for termination */
#define HF_STDOUT 0x02       /* Capture stdout */
#define HF_STDERR 0x04       /* Capture stderr */

/* Handler structure */
struct handler {
	int flags;           /* Handler flags */
	const char *prog;    /* Handler program (no arguments allowed) */
};

/* Array of handlers for each event */
struct handler handler[evt_max];

/* Process list */

/* Redirector codes */
#define REDIR_OUT 0
#define REDIR_ERR 1

/* A running process is described by this structure */
struct process {
	struct process *next, *prev;   
	int master;             /* Master process or redirector */
	pid_t pid;              /* PID */
	time_t start;           /* Time when the process started */
	pid_t redir[2];         /* If master==1, holds PIDs of redirector
				   processes (0 if no redirector) */
};

/* List of running processes */
struct process *proc_list;
/* List of available process slots */
struct process *proc_avail;
/* Declare functions for handling process lists */
#define LIST process
#define LIST_PUSH proc_push
#define LIST_POP proc_pop
#define LIST_UNLINK proc_unlink
#include "dlist.c"

/* Diagnostic functions */
const char *
severity(int prio)
{
	switch (prio) {
	case LOG_EMERG:
		return "EMERG";
	case LOG_ALERT:
		return "ALERT";
	case LOG_CRIT:
		return "CRIT";
	case LOG_ERR:
		return "ERROR";
	case LOG_WARNING:
		return "WARNING";
	case LOG_NOTICE:
		return "NOTICE";
	case LOG_INFO:
		return "INFO";
	case LOG_DEBUG:
		return "DEBUG";
	}
	return NULL;
}

void
vdiag(int prio, const char *fmt, va_list ap)
{
	const char *s;
	
	if (facility <= 0) {
		fprintf(stderr, "%s: ", program_name);
		s = severity(prio);
		if (s)
			fprintf(stderr, "[%s] ", s);
		vfprintf(stderr, fmt, ap);
		fputc('\n', stderr);
	} else {
		vsyslog(prio, fmt, ap);
	}
}

void
diag(int prio, const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	vdiag(prio, fmt, ap);
	va_end(ap);
}
	
static void
debugprt(const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	vdiag(LOG_DEBUG, fmt, ap);
	va_end(ap);
}

#define debug(l, c) do { if (debug_level>=(l)) debugprt c; } while(0)

/* Command line processing and auxiliary functions */

static void
set_program_name(const char *arg)
{
	char *p = strrchr(arg, '/');
	if (p)
		program_name = p + 1;
	else
		program_name = arg;
}

static int
read_facility(const char *arg)
{
	static struct transtab { int f; char *s; } ftab[] = {
		{ LOG_AUTH, "auth" },
		{ LOG_AUTHPRIV, "authpriv" },
		{ LOG_CRON, "cron" },
		{ LOG_DAEMON, "daemon" },
		{ LOG_FTP, "ftp" },
		{ LOG_LOCAL0, "local0" },
		{ LOG_LOCAL1, "local1" },
		{ LOG_LOCAL2, "local2" },
		{ LOG_LOCAL3, "local3" },
		{ LOG_LOCAL4, "local4" },
		{ LOG_LOCAL5, "local5" },
		{ LOG_LOCAL6, "local6" },
		{ LOG_LOCAL7, "local7" },
		{ LOG_LPR, "lpr" },
		{ LOG_MAIL, "mail" },
		{ LOG_NEWS, "news" },
		{ LOG_USER, "user" },
		{ LOG_UUCP, "uucp" },
		{ 0, NULL }
	};
	struct transtab *p;
	char *s;
	unsigned long n;
	
	for (p = ftab; p->s; p++) {
		if (strcmp(p->s, arg) == 0)
			return p->f;
	}
	n = strtoul(arg, &s, 10);
	if (*s) {
		diag(LOG_CRIT, "unknown facility: %s", arg);
		exit(1);
	}
	if (n > 256) {
		diag(LOG_CRIT, "facility out of range: %s", arg);
		exit(1);
	}
	return n;
}

void
set_handler(const char *arg)
{
	int len;
	int n = -1;

	/* Event code */
	len = strcspn(arg,",");
	if (strncmp(arg, "create", len) == 0)
		n = evt_create;
	else if (strncmp(arg, "delete", len) == 0)
		n = evt_delete;
	else if (strncmp(arg, "close", len) == 0)
		n = evt_close;
	else {
		diag(LOG_CRIT, "unrecognized event: %*.*s", len, len, arg);
		exit(1);
	}

	/* flag */
	handler[n].flags = 0;

	for (arg += len; *arg == ','; arg += len) {
		++arg;
		len = strcspn(arg, ",");
		if (arg[len] == 0)
			break;
		if (strncmp(arg, "wait", len) == 0)
			handler[n].flags &= ~HF_NOWAIT;
		else if (strncmp(arg, "nowait", len) == 0)
			handler[n].flags |= HF_NOWAIT;
		else if (strncmp(arg, "stdout", len) == 0)
			handler[n].flags |= HF_STDOUT;
		else if (strncmp(arg, "stderr", len) == 0)
			handler[n].flags |= HF_STDERR;
		else {
			diag(LOG_CRIT, "unknown flag %*.*s", len, len, arg);
			exit(1);
		}
	}
	
	if (*arg == 0) {
		diag(LOG_CRIT, "bad handler specification: %s", arg);
		exit(1);
	}
	handler[n].prog = arg;
}

/* Memory allocation with error checking */
void *
emalloc(size_t size)
{
	void *p = malloc(size);
	if (!p) {
		diag(LOG_CRIT, "not enough memory");
		exit(2);
	}
	return p;
}

void *
ecalloc(size_t nmemb, size_t size)
{
	void *p = calloc(nmemb, size);
	if (!p) {
		diag(LOG_CRIT, "not enough memory");
		exit(2);
	}
	return p;
}

/* Create a full file name from directory and file name */
char *
mkfilename(const char *dir, const char *file)
{
	char *tmp;
	size_t dirlen = strlen(dir);
	size_t fillen = strlen(file);
	size_t len;

	while (dirlen > 0 && dir[dirlen-1] == '/')
		dirlen--;

	len = dirlen + (dir[0] ? 1 : 0) + fillen;
	tmp = malloc(len + 1);
	if (tmp) {
		memcpy(tmp, dir, dirlen);
		if (dir[0])
			tmp[dirlen++] = '/';
		memcpy(tmp + dirlen, file, fillen);
		tmp[len] = 0;
	}
	return tmp;
}

void
signal_setup(void (*sf) (int))
{
	signal(SIGTERM, sf);
	signal(SIGQUIT, sf);
	signal(SIGINT, sf);
	signal(SIGHUP, sf);
	signal(SIGALRM, sf);
	signal(SIGUSR1, sf);
	signal(SIGUSR2, sf);
}

static void
close_fds(fd_set *fdset)
{
	int i;

	for (i = sysconf(_SC_OPEN_MAX); i >= 0; i--) {
		if (fdset && FD_ISSET(i, fdset))
			continue;
		close(i);
	}
}

void
storepid(const char *pidfile)
{
	FILE *fp = fopen(pidfile, "w");
	if (!fp) {
		diag(LOG_ERR, "cannot open pidfile %s for writing: %s",
		     pidfile, strerror(errno));
	} else {
		fprintf(fp, "%lu\n", (unsigned long) getpid());
		fclose(fp);
	}
}

void
setuser(const char *user)
{
	struct passwd *pw;

	pw = getpwnam(user);
	if (!pw) {
		diag(LOG_CRIT, "getpwnam(%s): %s", user, strerror(errno));
		exit(2);
	}
	if (pw->pw_uid == 0)
		return;
	if (setgid(pw->pw_gid)) {
		diag(LOG_CRIT, "setgid(%lu): %s", (unsigned long) pw->pw_gid,
		     strerror(errno));
		exit(2);
	}
	if (setuid(pw->pw_uid)) {
		diag(LOG_CRIT, "setuid(%lu): %s", (unsigned long) pw->pw_uid,
		     strerror(errno));
		exit(2);
	}
}

/* Process list handling (high-level) */

struct process *
register_process(pid_t pid, time_t t)
{
	struct process *p;

	if (proc_avail)
		p = proc_pop(&proc_avail);
	else
		p = emalloc(sizeof(*p));
	memset(p, 0, sizeof(*p));
	p->master = 0;
	p->pid = pid;
	p->start = t;
	proc_push(&proc_list, p);
	return p;
}

void
deregister_process(pid_t pid, time_t t)
{
	struct process *p;

	for (p = proc_list; p; p = p->next)
		if (p->pid == pid) {
			if (p->prev)
				p->prev->next = p->next;
			else
				proc_list = p;
			if (p->next)
				p->next->prev = p->prev;
			free(p);
			break;
		}
}

struct process *
process_lookup(pid_t pid)
{
	struct process *p;

	for (p = proc_list; p; p = p->next)
		if (p->pid == pid)
			return p;
	return NULL;
}

static void
print_status(pid_t pid, int status, int expect_term)
{
	if (WIFEXITED(status)) {
		if (WEXITSTATUS(status) == 0)
			debug(1, ("process %lu exited successfully",
				  (unsigned long) pid));
		else
			diag(LOG_ERR, "process %lu failed with status %d",
			     (unsigned long) pid, WEXITSTATUS(status));
	} else if (WIFSIGNALED(status)) {
		int prio;

		if (expect_term && WTERMSIG(status) == SIGTERM)
			prio = LOG_DEBUG;
		else
			prio = LOG_ERR;

		diag(prio, "process %lu terminated on signal %d",
		     (unsigned long) pid, WTERMSIG(status));
	} else if (WIFSTOPPED(status))
		diag(LOG_ERR, "process %lu stopped on signal %d",
		     (unsigned long) pid, WSTOPSIG(status));
#ifdef WCOREDUMP
	else if (WCOREDUMP(status))
		diag(LOG_ERR,
		     "process %lu dumped core", (unsigned long) pid);
#endif
	else
		diag(LOG_ERR,
		     "process %lu terminated with unrecognized status",
		     (unsigned long) pid);
}

void
process_cleanup(int expect_term)
{
	pid_t pid;
	int status;

	while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
		struct process *p = process_lookup(pid);
		print_status(pid, status, expect_term);
		if (p) {
			if (p->master) {
				if (p->redir[REDIR_OUT])
					kill(p->redir[REDIR_OUT], SIGKILL);
				if (p->redir[REDIR_ERR])
					kill(p->redir[REDIR_ERR], SIGKILL);
			}
			p->pid = 0;
			proc_unlink(&proc_list, p);
			proc_push(&proc_avail, p);
		}
	}
}

void
process_timeouts()
{
	struct process *p;
	time_t now = time(NULL);
	time_t alarm_time = 0, x;

	debug(2, ("begin scanning process list"));
	for (p = proc_list; p; p = p->next) {
		x = now - p->start;
		if (x >= handler_timeout) {
			diag(LOG_ERR, "process %lu timed out",
			     (unsigned long) p->pid);
			kill(p->pid, SIGKILL);
		} else if (alarm_time == 0 || handler_timeout - x< alarm_time)
			alarm_time = handler_timeout - x;
	}

	if (alarm_time) {
		debug(2, ("scheduling alarm in %lu seconds",
			  (unsigned long) alarm_time));
		alarm(alarm_time);
	}
	debug(2, ("end scanning process list"));
}

/* Operations with handlers and redirections */

static void
redir_exit(int sig)
{
	_exit(0);
}

int
open_redirector(const char *tag, int prio, pid_t *return_pid)
{
	int p[2];
	FILE *fp;
	char buf[512];
	pid_t pid;
	fd_set fdset;

	if (pipe(p)) {
		diag(LOG_ERR,
		     "cannot start redirector for %s, pipe failed: %s",
		     tag, strerror(errno));
		return -1;
	}
	switch (pid = fork()) {
	case 0:
		/* Redirector process */
		FD_ZERO(&fdset);
		FD_SET(p[0], &fdset);
		if (facility <= 0)
			FD_SET(2, &fdset);
		close_fds(&fdset);
		
		alarm(0);
		signal_setup(redir_exit);

		fp = fdopen(p[0], "r");
		if (fp == NULL)
			_exit(1);
		if (facility >= 0) 
			openlog(tag, LOG_PID, facility);

		while (fgets(buf, sizeof(buf), fp) > 0) {
			int len = strlen(buf);
			if (len && buf[len-1] == '\n')
				buf[len-1] = 0;
			diag(prio, "%s", buf);
		}
		_exit(0);
      
	case -1:
		diag(LOG_CRIT,
		     "cannot run redirector `%s': fork failed: %s",
		     tag, strerror(errno));
		return -1;

	default:
		debug(1, ("redirector for %s started, pid=%lu",
			  tag, (unsigned long) pid));
		close (p[0]);
		*return_pid = pid;
		return p[1];
	}
}

static int
run_handler(int event, const char *dir, const char *file)
{
	pid_t pid;
	char buf[1024];
	int redir_fd[2] = { -1, -1 };
	pid_t redir_pid[2];
	struct process *p;
	struct handler *hp = &handler[event];

	if (!hp->prog)
		return 0;

	debug(1, ("starting %s, dir=%s, file=%s", hp->prog, dir, file));
	if (hp->flags & HF_STDERR)
		redir_fd[REDIR_ERR] = open_redirector(hp->prog, LOG_INFO,
						      &redir_pid[REDIR_ERR]);
	if (hp->flags & HF_STDOUT)
		redir_fd[REDIR_OUT] = open_redirector(hp->prog, LOG_ERR,
						      &redir_pid[REDIR_OUT]);
	
	pid = fork();
	if (pid == -1) {
		close(redir_fd[REDIR_OUT]);
		close(redir_fd[REDIR_ERR]);
		diag(LOG_ERR, "fork: %s", strerror(errno));
		return -1;
	}
	
	if (pid == 0) {		
		/* child */
		char *argv[2];
		fd_set fdset;

		if (chdir(dir)) {
			diag(LOG_CRIT, "cannot change to %s: %s",
			     dir, strerror(errno));
			exit(1);
		}

		FD_ZERO(&fdset);

		if (redir_fd[REDIR_OUT] != -1) {
			if (redir_fd[REDIR_OUT] != 1 &&
			    dup2(redir_fd[REDIR_OUT], 1) == -1) {
				diag(LOG_ERR, "dup2: %s", strerror(errno));
				_exit(127);
			}
			FD_SET(1, &fdset);
		}
		if (redir_fd[REDIR_ERR] != -1) {
			if (redir_fd[REDIR_ERR] != 2 &&
			    dup2(redir_fd[REDIR_ERR], 2) == -1) {
				diag(LOG_ERR, "dup2: %s", strerror(errno));
				_exit(127);
			}
			FD_SET(2, &fdset);
		}
		close_fds(&fdset);
		alarm(0);
		signal_setup(SIG_DFL);
		signal(SIGCHLD, SIG_DFL);
		argv[0] = (char*) hp->prog;
		argv[1] = NULL;
		snprintf(buf, sizeof buf, "%d", event);
		setenv("DIRCOND_EVENT", buf, 1);
		setenv("DIRCOND_FILE", file, 1);
		execv(argv[0], argv);
		_exit(127);
	}

	/* master */
	debug(1, ("%s running; dir=%s, file=%s, pid=%lu",
		  hp->prog, dir, file, (unsigned long)pid));

	p = register_process(pid, time(NULL));
	
	memcpy(p->redir, redir_pid, sizeof(p->redir));
	p->master = 1;
	
	close(redir_fd[REDIR_OUT]);
	close(redir_fd[REDIR_ERR]);

	if (hp->flags & HF_NOWAIT) {
		return 0;
	}

	debug(1, ("waiting for %s (%lu) to terminate",
		  hp->prog, (unsigned long)pid));
	while (time(NULL) - p->start < 2*handler_timeout) {
		sleep(1);
		process_cleanup(1);
		if (p->pid == 0)
			break;
	}
	return 0;
}

			
/* Directory watcher functions */

/* A directory watcher is described by the following structure */
struct dirwatcher {
	struct dirwatcher *next, *prev;
	struct dirwatcher *parent;        /* Points to the parent watcher.
					     NULL for top-level watchers */
	char *name;                       /* Pathname being watched */
	int wd;                           /* Watch descriptor */
};

/* A doubly-linked list of active watchers */
struct dirwatcher *dirwatcher_list;
/* Declare low-level functions for handling the watchers list */
#define LIST dirwatcher
#define LIST_PUSH dirwatcher_push
#define LIST_POP dirwatcher_pop
#define LIST_UNLINK dirwatcher_unlink
#include "dlist.c"

/* Free the allocated watcher (must have been unlinked from the list first) */
void
dirwatcher_free(struct dirwatcher *dwp)
{
	free(dwp->name);
	free(dwp);
}

/* Create a new watcher and attach it to the list. */
struct dirwatcher *
dirwatcher_create(int ifd, const char *name)
{
	struct dirwatcher *dwp;
	int wd;

	debug(1, ("creating watcher %s", name));
	dwp = malloc(sizeof(*dwp));
	if (!dwp) {
		diag(LOG_ERR, "not enough memory");
		return NULL;
	}
	dwp->name = strdup(name);
	if (!dwp->name) {
		diag(LOG_ERR, "not enough memory");
		free(dwp);
		return NULL;
	}
	dwp->parent = NULL;
	
	wd = inotify_add_watch(ifd, name,
			       IN_DELETE|IN_CREATE|IN_CLOSE_WRITE);
	if (wd == -1) {
		diag(LOG_ERR, "cannot set watch on %s: %s",
		     name, strerror(errno));
		dirwatcher_free(dwp);
		return NULL;
	}
	
	dwp->wd = wd;
	dirwatcher_push(&dirwatcher_list, dwp);
	
	return dwp;
}

/* Destroy a watcher, unlink it and reclaim the allocated memory. */
void
dirwatcher_destroy(int ifd, struct dirwatcher *dwp)
{
	debug(1, ("removing watcher %s", dwp->name));
	dirwatcher_unlink(&dirwatcher_list, dwp);
	inotify_rm_watch(ifd, dwp->wd);
	dirwatcher_free(dwp);
}

/* Find a watcher with the given descriptor */
struct dirwatcher *
dirwatcher_find_wd(int wd)
{
	struct dirwatcher *dwp;
	
	for (dwp = dirwatcher_list; dwp; dwp = dwp->next)
		if (dwp->wd == wd)
			break;
	return dwp;
}

/* Find a watcher with the given pathname */
struct dirwatcher *
dirwatcher_find_name(const char *name)
{
	struct dirwatcher *dwp;
	
	for (dwp = dirwatcher_list; dwp; dwp = dwp->next)
		if (strcmp(dwp->name, name) == 0)
			break;
	return dwp;
}

/* Compare full pathname with a directory and file name.  Return
   semantics is the same as in strcmp(2). */
int
name2cmp(const char *pathname, const char *dir, const char *name)
{
	int c;
	
	for (; *pathname && *dir; pathname++, dir++)
		if (c = *pathname - *dir)
			return c;
	while (*pathname && *pathname == '/')
		++pathname;
	while (*dir && *dir == '/')
		++dir;
	if (*dir)
		return - *dir;

	for (; *pathname && *name; pathname++, name++)
		if (c = *pathname - *name)
			return c;
	if (*pathname)
		return *pathname;
	if (*name)
		return - *name;
	return 0;
}

/* Remove a watcher identified by its directory and file name */
void
remove_watcher(int ifd, const char *dir, const char *name)
{
	struct dirwatcher *dwp;
	for (dwp = dirwatcher_list; dwp; dwp = dwp->next)
		if (name2cmp(dwp->name, dir, name) == 0) {
			dirwatcher_destroy(ifd, dwp);
			return;
		}
}

/* Return nesting level of a watcher */
int
dirlevel(struct dirwatcher *dw)
{
	int lev = 0;
	while (dw = dw->parent)
		++lev;
	return lev;
}

/* Check if a new watcher must be created and create it if so.

   A watcher must be created if (1) autowatch has negative value,
   or (2) it has a positive value and the nesting level of the parent
   watcher does not exceed it.

   Return 0 on success, -1 on error.
*/
int
check_new_watcher(int ifd, const char *dir, const char *name)
{
	int rc;
	char *fname;
	struct stat st;
	struct dirwatcher *parent;

	if (autowatch == 0)
		return 0;
	parent = dirwatcher_find_name(dir);
	if (autowatch > 0 && dirlevel(parent) >= autowatch)
		return 0;
	
	fname = mkfilename(dir, name);
	if (!fname) {
		diag(LOG_ERR, "cannot create watcher %s/%s: not enough memory",
		     dir, name);
		return -1;
	}

	if (stat(fname, &st)) {
		diag(LOG_ERR, "cannot create watcher %s/%s, stat failed: %s",
		     dir, name, strerror(errno));
		rc = -1;
	} else if (S_ISDIR(st.st_mode)) {
		struct dirwatcher *dwp = dirwatcher_create(ifd, fname);
		if (dwp) {
			rc = 0;
			dwp->parent = parent;
		} else
			rc = -1;
	} else
		rc = 0;
	free(fname);
	return rc;
}

/* Output a help summary. Return a code suitable for exit(2). */
int
help()
{
	printf("Usage: %s [OPTIONS] DIR [DIR...]\n", program_name);
	printf("OPTIONS are:\n\n");

	printf("   -a            automatically watch created directories\n");
	printf("   -d            increase debug verbosity\n");
        printf("   -f            run in the foreground\n");
	printf("   -F FACILITY   log under this syslog facility\n");
	printf("   -l N          automatically watch new directories located\n");
	printf("                 up to Nth nesting level\n");
	printf("   -P FILE       write PID to FILE\n");
	printf("   -p EVENT,[FLAG[,FLAG...],]COMMAND\n");
	printf("                 start COMMAND upon EVENT\n");
	printf("   -T TIMEOUT    set timeout for external commands\n");
        printf("   -t TAG        log with this syslog tag\n");
	printf("   -u USER       run as this USER\n");
		   
	printf("   -h            output this help summary\n\n");
	printf("Report bugs to <gray+dircond@gnu.org.ua>.\n");
		
	return 0;
}

int signo = 0;

void
sigmain(int sig)
{
	signo = sig;
	signal(sig, sigmain);
}

char buffer[4096];

int
main(int argc, char **argv)
{
	int ifd, c, i;
	char *tag = NULL;
	int fac = LOG_DAEMON;
	struct dirwatcher *dp;
	char *pidfile = NULL;
	char *user = "nobody";
	
	set_program_name(argv[0]);
	
	while ((c = getopt(argc, argv, "adF:fhl:P:p:T:t:u:")) != EOF) {
		switch (c) {
		case 'a':
			autowatch = -1;
			break;
		case 'd':
			debug_level++;
			break;
		case 'f':
			foreground++;
			break;
		case 'h':
			exit(help());
			break;
		case 'l':
			autowatch = atoi(optarg);
			break;
		case 'T':
			handler_timeout = atoi(optarg);
			break;
		case 't':
			tag = optarg;
			break;
		case 'F':
			fac = read_facility(optarg);
			break;
		case 'P':
			pidfile = optarg;
			break;
		case 'p':
			set_handler(optarg);
			break;
		case 'u':
			user = optarg;
			if (!getpwnam(user)) {
				diag(LOG_CRIT, "no such user: %s", user);
				exit(1);
			}
			break;
		default:
			exit(1);
		}
	}

	argc -= optind;
	argv += optind;

	if (argc == 0) {
		diag(LOG_CRIT, "not enough arguments");
		exit(1);
	}

	ifd = inotify_init();
	if (ifd == -1) {
		diag(LOG_CRIT, "inotify_init: %s", strerror(errno));
		exit(1);
	}

	for (i = 0; i < argc; i++) {
		if (!dirwatcher_create(ifd, argv[i])) {
			diag(LOG_CRIT, "cannot create watcher; exiting");
			exit(1);
		}
	}

	/* Become a daemon */
	if (!foreground) {
		if (daemon(0, 0)) {
			diag(LOG_CRIT, "daemon: %s", strerror(errno));
			exit(1);
		}
	}
	
	facility = fac;
	if (facility >= 0)
		openlog(tag, LOG_PID, facility);

	diag(LOG_INFO, "started");

	/* Write pidfile */
	if (pidfile)
		storepid(pidfile);

	/* Relinquish superuser privileges */
	if (getuid() == 0)
		setuser(user);

	signal_setup(sigmain);
	signal(SIGCHLD, sigmain);
	
	/* Main loop */
	while (1) {
		struct inotify_event *ep;
		size_t size;
		ssize_t rdbytes;

		process_timeouts();
		process_cleanup(0);

		rdbytes = read(ifd, buffer, sizeof(buffer));
		if (rdbytes == -1) {
			if (errno == EINTR) {
				if (signo == SIGCHLD || signo == SIGALRM)
					continue;
				diag(LOG_NOTICE, "got signal %d", signo);
				break;
			}
			
			diag(LOG_NOTICE, "read failed: %s", strerror(errno));
			break;
		}
		
		ep = (struct inotify_event *) buffer;
		while (rdbytes) {
			if (ep->wd >= 0) {
				int ev = -1;
				dp = dirwatcher_find_wd(ep->wd);
				if (ep->mask & IN_IGNORED)
					/* nothing */;
				else if (ep->mask & IN_Q_OVERFLOW)
					diag(LOG_NOTICE,
					     "event queue overflow");
				else if (ep->mask & IN_UNMOUNT)
					/* FIXME: not sure if there's
					   anything to do. Perhaps we should
					   deregister the watched dirs that
					   were located under the mountpoint
					*/;
				else if (!dp) {
					if (ep->name)
						diag(LOG_NOTICE,
						     "unrecognized event %x"
						     "for %s", ep->mask,
						     ep->name);
					else
						diag(LOG_NOTICE,
						     "unrecognized event %x",
						     ep->mask);
				} else if (ep->mask & IN_CREATE) {
					ev = evt_create;
					debug(1, ("%s/%s created",
						  dp->name, ep->name));
					check_new_watcher(ifd,
							  dp->name, ep->name);
				} else if (ep->mask & IN_DELETE) {
					ev = evt_delete;
					debug(1, ("%s/%s deleted",
						  dp->name, ep->name));
					remove_watcher(ifd, dp->name,
						       ep->name);
				} else if (ep->mask & IN_CLOSE_WRITE) {
					ev = evt_close;
					debug(1, ("%s/%s written",
						  dp->name, ep->name));
				} else
					diag(LOG_NOTICE,
					     "%s/%s: unexpected event %x",
					     dp->name, ep->name, ep->mask);

				if (ev >= 0 && ev < evt_max) {
					run_handler(ev, dp->name, ep->name);
				}
			}
			size = sizeof(*ep) + ep->len;
			ep = (struct inotify_event *) ((char*) ep + size);
			rdbytes -= size;
		}
	}
	diag(LOG_INFO, "stopped");

	return 0;
}

Return to:

Send suggestions and report system problems to the System administrator.