xref: /freebsd/sbin/devd/devd.cc (revision d9f0ce31900a48d1a2bfc1c8c86f79d1e831451a)
1 /*-
2  * Copyright (c) 2002-2010 M. Warner Losh.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * my_system is a variation on lib/libc/stdlib/system.c:
27  *
28  * Copyright (c) 1988, 1993
29  *	The Regents of the University of California.  All rights reserved.
30  *
31  * Redistribution and use in source and binary forms, with or without
32  * modification, are permitted provided that the following conditions
33  * are met:
34  * 1. Redistributions of source code must retain the above copyright
35  *    notice, this list of conditions and the following disclaimer.
36  * 2. Redistributions in binary form must reproduce the above copyright
37  *    notice, this list of conditions and the following disclaimer in the
38  *    documentation and/or other materials provided with the distribution.
39  * 4. Neither the name of the University nor the names of its contributors
40  *    may be used to endorse or promote products derived from this software
41  *    without specific prior written permission.
42  *
43  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
44  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
47  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
48  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
49  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
51  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
52  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53  * SUCH DAMAGE.
54  */
55 
56 /*
57  * DEVD control daemon.
58  */
59 
60 // TODO list:
61 //	o devd.conf and devd man pages need a lot of help:
62 //	  - devd needs to document the unix domain socket
63 //	  - devd.conf needs more details on the supported statements.
64 
65 #include <sys/cdefs.h>
66 __FBSDID("$FreeBSD$");
67 
68 #include <sys/param.h>
69 #include <sys/socket.h>
70 #include <sys/stat.h>
71 #include <sys/sysctl.h>
72 #include <sys/types.h>
73 #include <sys/wait.h>
74 #include <sys/un.h>
75 
76 #include <cctype>
77 #include <cerrno>
78 #include <cstdlib>
79 #include <cstdio>
80 #include <csignal>
81 #include <cstring>
82 #include <cstdarg>
83 
84 #include <dirent.h>
85 #include <err.h>
86 #include <fcntl.h>
87 #include <libutil.h>
88 #include <paths.h>
89 #include <poll.h>
90 #include <regex.h>
91 #include <syslog.h>
92 #include <unistd.h>
93 
94 #include <algorithm>
95 #include <map>
96 #include <string>
97 #include <list>
98 #include <vector>
99 
100 #include "devd.h"		/* C compatible definitions */
101 #include "devd.hh"		/* C++ class definitions */
102 
103 #define STREAMPIPE "/var/run/devd.pipe"
104 #define SEQPACKETPIPE "/var/run/devd.seqpacket.pipe"
105 #define CF "/etc/devd.conf"
106 #define SYSCTL "hw.bus.devctl_queue"
107 
108 /*
109  * Since the client socket is nonblocking, we must increase its send buffer to
110  * handle brief event storms.  On FreeBSD, AF_UNIX sockets don't have a receive
111  * buffer, so the client can't increase the buffersize by itself.
112  *
113  * For example, when creating a ZFS pool, devd emits one 165 character
114  * resource.fs.zfs.statechange message for each vdev in the pool.  The kernel
115  * allocates a 4608B mbuf for each message.  Modern technology places a limit of
116  * roughly 450 drives/rack, and it's unlikely that a zpool will ever be larger
117  * than that.
118  *
119  * 450 drives * 165 bytes / drive = 74250B of data in the sockbuf
120  * 450 drives * 4608B / drive = 2073600B of mbufs in the sockbuf
121  *
122  * We can't directly set the sockbuf's mbuf limit, but we can do it indirectly.
123  * The kernel sets it to the minimum of a hard-coded maximum value and sbcc *
124  * kern.ipc.sockbuf_waste_factor, where sbcc is the socket buffer size set by
125  * the user.  The default value of kern.ipc.sockbuf_waste_factor is 8.  If we
126  * set the bufsize to 256k and use the kern.ipc.sockbuf_waste_factor, then the
127  * kernel will set the mbuf limit to 2MB, which is just large enough for 450
128  * drives.  It also happens to be the same as the hardcoded maximum value.
129  */
130 #define CLIENT_BUFSIZE 262144
131 
132 using namespace std;
133 
134 typedef struct client {
135 	int fd;
136 	int socktype;
137 } client_t;
138 
139 extern FILE *yyin;
140 extern int lineno;
141 
142 static const char notify = '!';
143 static const char nomatch = '?';
144 static const char attach = '+';
145 static const char detach = '-';
146 
147 static struct pidfh *pfh;
148 
149 static int no_daemon = 0;
150 static int daemonize_quick = 0;
151 static int quiet_mode = 0;
152 static unsigned total_events = 0;
153 static volatile sig_atomic_t got_siginfo = 0;
154 static volatile sig_atomic_t romeo_must_die = 0;
155 
156 static const char *configfile = CF;
157 
158 static void devdlog(int priority, const char* message, ...)
159 	__printflike(2, 3);
160 static void event_loop(void);
161 static void usage(void);
162 
163 template <class T> void
164 delete_and_clear(vector<T *> &v)
165 {
166 	typename vector<T *>::const_iterator i;
167 
168 	for (i = v.begin(); i != v.end(); ++i)
169 		delete *i;
170 	v.clear();
171 }
172 
173 config cfg;
174 
175 event_proc::event_proc() : _prio(-1)
176 {
177 	_epsvec.reserve(4);
178 }
179 
180 event_proc::~event_proc()
181 {
182 	delete_and_clear(_epsvec);
183 }
184 
185 void
186 event_proc::add(eps *eps)
187 {
188 	_epsvec.push_back(eps);
189 }
190 
191 bool
192 event_proc::matches(config &c) const
193 {
194 	vector<eps *>::const_iterator i;
195 
196 	for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
197 		if (!(*i)->do_match(c))
198 			return (false);
199 	return (true);
200 }
201 
202 bool
203 event_proc::run(config &c) const
204 {
205 	vector<eps *>::const_iterator i;
206 
207 	for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
208 		if (!(*i)->do_action(c))
209 			return (false);
210 	return (true);
211 }
212 
213 action::action(const char *cmd)
214 	: _cmd(cmd)
215 {
216 	// nothing
217 }
218 
219 action::~action()
220 {
221 	// nothing
222 }
223 
224 static int
225 my_system(const char *command)
226 {
227 	pid_t pid, savedpid;
228 	int pstat;
229 	struct sigaction ign, intact, quitact;
230 	sigset_t newsigblock, oldsigblock;
231 
232 	if (!command)		/* just checking... */
233 		return (1);
234 
235 	/*
236 	 * Ignore SIGINT and SIGQUIT, block SIGCHLD. Remember to save
237 	 * existing signal dispositions.
238 	 */
239 	ign.sa_handler = SIG_IGN;
240 	::sigemptyset(&ign.sa_mask);
241 	ign.sa_flags = 0;
242 	::sigaction(SIGINT, &ign, &intact);
243 	::sigaction(SIGQUIT, &ign, &quitact);
244 	::sigemptyset(&newsigblock);
245 	::sigaddset(&newsigblock, SIGCHLD);
246 	::sigprocmask(SIG_BLOCK, &newsigblock, &oldsigblock);
247 	switch (pid = ::fork()) {
248 	case -1:			/* error */
249 		break;
250 	case 0:				/* child */
251 		/*
252 		 * Restore original signal dispositions and exec the command.
253 		 */
254 		::sigaction(SIGINT, &intact, NULL);
255 		::sigaction(SIGQUIT,  &quitact, NULL);
256 		::sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
257 		/*
258 		 * Close the PID file, and all other open descriptors.
259 		 * Inherit std{in,out,err} only.
260 		 */
261 		cfg.close_pidfile();
262 		::closefrom(3);
263 		::execl(_PATH_BSHELL, "sh", "-c", command, (char *)NULL);
264 		::_exit(127);
265 	default:			/* parent */
266 		savedpid = pid;
267 		do {
268 			pid = ::wait4(savedpid, &pstat, 0, (struct rusage *)0);
269 		} while (pid == -1 && errno == EINTR);
270 		break;
271 	}
272 	::sigaction(SIGINT, &intact, NULL);
273 	::sigaction(SIGQUIT,  &quitact, NULL);
274 	::sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
275 	return (pid == -1 ? -1 : pstat);
276 }
277 
278 bool
279 action::do_action(config &c)
280 {
281 	string s = c.expand_string(_cmd.c_str());
282 	devdlog(LOG_INFO, "Executing '%s'\n", s.c_str());
283 	my_system(s.c_str());
284 	return (true);
285 }
286 
287 match::match(config &c, const char *var, const char *re) :
288 	_inv(re[0] == '!'),
289 	_var(var),
290 	_re(c.expand_string(_inv ? re + 1 : re, "^", "$"))
291 {
292 	regcomp(&_regex, _re.c_str(), REG_EXTENDED | REG_NOSUB | REG_ICASE);
293 }
294 
295 match::~match()
296 {
297 	regfree(&_regex);
298 }
299 
300 bool
301 match::do_match(config &c)
302 {
303 	const string &value = c.get_variable(_var);
304 	bool retval;
305 
306 	/*
307 	 * This function gets called WAY too often to justify calling syslog()
308 	 * each time, even at LOG_DEBUG.  Because if syslogd isn't running, it
309 	 * can consume excessive amounts of systime inside of connect().  Only
310 	 * log when we're in -d mode.
311 	 */
312 	if (no_daemon) {
313 		devdlog(LOG_DEBUG, "Testing %s=%s against %s, invert=%d\n",
314 		    _var.c_str(), value.c_str(), _re.c_str(), _inv);
315 	}
316 
317 	retval = (regexec(&_regex, value.c_str(), 0, NULL, 0) == 0);
318 	if (_inv == 1)
319 		retval = (retval == 0) ? 1 : 0;
320 
321 	return (retval);
322 }
323 
324 #include <sys/sockio.h>
325 #include <net/if.h>
326 #include <net/if_media.h>
327 
328 media::media(config &, const char *var, const char *type)
329 	: _var(var), _type(-1)
330 {
331 	static struct ifmedia_description media_types[] = {
332 		{ IFM_ETHER,		"Ethernet" },
333 		{ IFM_TOKEN,		"Tokenring" },
334 		{ IFM_FDDI,		"FDDI" },
335 		{ IFM_IEEE80211,	"802.11" },
336 		{ IFM_ATM,		"ATM" },
337 		{ -1,			"unknown" },
338 		{ 0, NULL },
339 	};
340 	for (int i = 0; media_types[i].ifmt_string != NULL; ++i)
341 		if (strcasecmp(type, media_types[i].ifmt_string) == 0) {
342 			_type = media_types[i].ifmt_word;
343 			break;
344 		}
345 }
346 
347 media::~media()
348 {
349 }
350 
351 bool
352 media::do_match(config &c)
353 {
354 	string value;
355 	struct ifmediareq ifmr;
356 	bool retval;
357 	int s;
358 
359 	// Since we can be called from both a device attach/detach
360 	// context where device-name is defined and what we want,
361 	// as well as from a link status context, where subsystem is
362 	// the name of interest, first try device-name and fall back
363 	// to subsystem if none exists.
364 	value = c.get_variable("device-name");
365 	if (value.empty())
366 		value = c.get_variable("subsystem");
367 	devdlog(LOG_DEBUG, "Testing media type of %s against 0x%x\n",
368 		    value.c_str(), _type);
369 
370 	retval = false;
371 
372 	s = socket(PF_INET, SOCK_DGRAM, 0);
373 	if (s >= 0) {
374 		memset(&ifmr, 0, sizeof(ifmr));
375 		strncpy(ifmr.ifm_name, value.c_str(), sizeof(ifmr.ifm_name));
376 
377 		if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0 &&
378 		    ifmr.ifm_status & IFM_AVALID) {
379 			devdlog(LOG_DEBUG, "%s has media type 0x%x\n",
380 				    value.c_str(), IFM_TYPE(ifmr.ifm_active));
381 			retval = (IFM_TYPE(ifmr.ifm_active) == _type);
382 		} else if (_type == -1) {
383 			devdlog(LOG_DEBUG, "%s has unknown media type\n",
384 				    value.c_str());
385 			retval = true;
386 		}
387 		close(s);
388 	}
389 
390 	return (retval);
391 }
392 
393 const string var_list::bogus = "_$_$_$_$_B_O_G_U_S_$_$_$_$_";
394 const string var_list::nothing = "";
395 
396 const string &
397 var_list::get_variable(const string &var) const
398 {
399 	map<string, string>::const_iterator i;
400 
401 	i = _vars.find(var);
402 	if (i == _vars.end())
403 		return (var_list::bogus);
404 	return (i->second);
405 }
406 
407 bool
408 var_list::is_set(const string &var) const
409 {
410 	return (_vars.find(var) != _vars.end());
411 }
412 
413 void
414 var_list::set_variable(const string &var, const string &val)
415 {
416 	/*
417 	 * This function gets called WAY too often to justify calling syslog()
418 	 * each time, even at LOG_DEBUG.  Because if syslogd isn't running, it
419 	 * can consume excessive amounts of systime inside of connect().  Only
420 	 * log when we're in -d mode.
421 	 */
422 	if (no_daemon)
423 		devdlog(LOG_DEBUG, "setting %s=%s\n", var.c_str(), val.c_str());
424 	_vars[var] = val;
425 }
426 
427 void
428 config::reset(void)
429 {
430 	_dir_list.clear();
431 	delete_and_clear(_var_list_table);
432 	delete_and_clear(_attach_list);
433 	delete_and_clear(_detach_list);
434 	delete_and_clear(_nomatch_list);
435 	delete_and_clear(_notify_list);
436 }
437 
438 void
439 config::parse_one_file(const char *fn)
440 {
441 	devdlog(LOG_DEBUG, "Parsing %s\n", fn);
442 	yyin = fopen(fn, "r");
443 	if (yyin == NULL)
444 		err(1, "Cannot open config file %s", fn);
445 	lineno = 1;
446 	if (yyparse() != 0)
447 		errx(1, "Cannot parse %s at line %d", fn, lineno);
448 	fclose(yyin);
449 }
450 
451 void
452 config::parse_files_in_dir(const char *dirname)
453 {
454 	DIR *dirp;
455 	struct dirent *dp;
456 	char path[PATH_MAX];
457 
458 	devdlog(LOG_DEBUG, "Parsing files in %s\n", dirname);
459 	dirp = opendir(dirname);
460 	if (dirp == NULL)
461 		return;
462 	readdir(dirp);		/* Skip . */
463 	readdir(dirp);		/* Skip .. */
464 	while ((dp = readdir(dirp)) != NULL) {
465 		if (strcmp(dp->d_name + dp->d_namlen - 5, ".conf") == 0) {
466 			snprintf(path, sizeof(path), "%s/%s",
467 			    dirname, dp->d_name);
468 			parse_one_file(path);
469 		}
470 	}
471 	closedir(dirp);
472 }
473 
474 class epv_greater {
475 public:
476 	int operator()(event_proc *const&l1, event_proc *const&l2) const
477 	{
478 		return (l1->get_priority() > l2->get_priority());
479 	}
480 };
481 
482 void
483 config::sort_vector(vector<event_proc *> &v)
484 {
485 	stable_sort(v.begin(), v.end(), epv_greater());
486 }
487 
488 void
489 config::parse(void)
490 {
491 	vector<string>::const_iterator i;
492 
493 	parse_one_file(configfile);
494 	for (i = _dir_list.begin(); i != _dir_list.end(); ++i)
495 		parse_files_in_dir((*i).c_str());
496 	sort_vector(_attach_list);
497 	sort_vector(_detach_list);
498 	sort_vector(_nomatch_list);
499 	sort_vector(_notify_list);
500 }
501 
502 void
503 config::open_pidfile()
504 {
505 	pid_t otherpid;
506 
507 	if (_pidfile.empty())
508 		return;
509 	pfh = pidfile_open(_pidfile.c_str(), 0600, &otherpid);
510 	if (pfh == NULL) {
511 		if (errno == EEXIST)
512 			errx(1, "devd already running, pid: %d", (int)otherpid);
513 		warn("cannot open pid file");
514 	}
515 }
516 
517 void
518 config::write_pidfile()
519 {
520 
521 	pidfile_write(pfh);
522 }
523 
524 void
525 config::close_pidfile()
526 {
527 
528 	pidfile_close(pfh);
529 }
530 
531 void
532 config::remove_pidfile()
533 {
534 
535 	pidfile_remove(pfh);
536 }
537 
538 void
539 config::add_attach(int prio, event_proc *p)
540 {
541 	p->set_priority(prio);
542 	_attach_list.push_back(p);
543 }
544 
545 void
546 config::add_detach(int prio, event_proc *p)
547 {
548 	p->set_priority(prio);
549 	_detach_list.push_back(p);
550 }
551 
552 void
553 config::add_directory(const char *dir)
554 {
555 	_dir_list.push_back(string(dir));
556 }
557 
558 void
559 config::add_nomatch(int prio, event_proc *p)
560 {
561 	p->set_priority(prio);
562 	_nomatch_list.push_back(p);
563 }
564 
565 void
566 config::add_notify(int prio, event_proc *p)
567 {
568 	p->set_priority(prio);
569 	_notify_list.push_back(p);
570 }
571 
572 void
573 config::set_pidfile(const char *fn)
574 {
575 	_pidfile = fn;
576 }
577 
578 void
579 config::push_var_table()
580 {
581 	var_list *vl;
582 
583 	vl = new var_list();
584 	_var_list_table.push_back(vl);
585 	devdlog(LOG_DEBUG, "Pushing table\n");
586 }
587 
588 void
589 config::pop_var_table()
590 {
591 	delete _var_list_table.back();
592 	_var_list_table.pop_back();
593 	devdlog(LOG_DEBUG, "Popping table\n");
594 }
595 
596 void
597 config::set_variable(const char *var, const char *val)
598 {
599 	_var_list_table.back()->set_variable(var, val);
600 }
601 
602 const string &
603 config::get_variable(const string &var)
604 {
605 	vector<var_list *>::reverse_iterator i;
606 
607 	for (i = _var_list_table.rbegin(); i != _var_list_table.rend(); ++i) {
608 		if ((*i)->is_set(var))
609 			return ((*i)->get_variable(var));
610 	}
611 	return (var_list::nothing);
612 }
613 
614 bool
615 config::is_id_char(char ch) const
616 {
617 	return (ch != '\0' && (isalpha(ch) || isdigit(ch) || ch == '_' ||
618 	    ch == '-'));
619 }
620 
621 void
622 config::expand_one(const char *&src, string &dst)
623 {
624 	int count;
625 	string buffer;
626 
627 	src++;
628 	// $$ -> $
629 	if (*src == '$') {
630 		dst += *src++;
631 		return;
632 	}
633 
634 	// $(foo) -> $(foo)
635 	// Not sure if I want to support this or not, so for now we just pass
636 	// it through.
637 	if (*src == '(') {
638 		dst += '$';
639 		count = 1;
640 		/* If the string ends before ) is matched , return. */
641 		while (count > 0 && *src) {
642 			if (*src == ')')
643 				count--;
644 			else if (*src == '(')
645 				count++;
646 			dst += *src++;
647 		}
648 		return;
649 	}
650 
651 	// $[^-A-Za-z_*] -> $\1
652 	if (!isalpha(*src) && *src != '_' && *src != '-' && *src != '*') {
653 		dst += '$';
654 		dst += *src++;
655 		return;
656 	}
657 
658 	// $var -> replace with value
659 	do {
660 		buffer += *src++;
661 	} while (is_id_char(*src));
662 	dst.append(get_variable(buffer));
663 }
664 
665 const string
666 config::expand_string(const char *src, const char *prepend, const char *append)
667 {
668 	const char *var_at;
669 	string dst;
670 
671 	/*
672 	 * 128 bytes is enough for 2427 of 2438 expansions that happen
673 	 * while parsing config files, as tested on 2013-01-30.
674 	 */
675 	dst.reserve(128);
676 
677 	if (prepend != NULL)
678 		dst = prepend;
679 
680 	for (;;) {
681 		var_at = strchr(src, '$');
682 		if (var_at == NULL) {
683 			dst.append(src);
684 			break;
685 		}
686 		dst.append(src, var_at - src);
687 		src = var_at;
688 		expand_one(src, dst);
689 	}
690 
691 	if (append != NULL)
692 		dst.append(append);
693 
694 	return (dst);
695 }
696 
697 bool
698 config::chop_var(char *&buffer, char *&lhs, char *&rhs) const
699 {
700 	char *walker;
701 
702 	if (*buffer == '\0')
703 		return (false);
704 	walker = lhs = buffer;
705 	while (is_id_char(*walker))
706 		walker++;
707 	if (*walker != '=')
708 		return (false);
709 	walker++;		// skip =
710 	if (*walker == '"') {
711 		walker++;	// skip "
712 		rhs = walker;
713 		while (*walker && *walker != '"')
714 			walker++;
715 		if (*walker != '"')
716 			return (false);
717 		rhs[-2] = '\0';
718 		*walker++ = '\0';
719 	} else {
720 		rhs = walker;
721 		while (*walker && !isspace(*walker))
722 			walker++;
723 		if (*walker != '\0')
724 			*walker++ = '\0';
725 		rhs[-1] = '\0';
726 	}
727 	while (isspace(*walker))
728 		walker++;
729 	buffer = walker;
730 	return (true);
731 }
732 
733 
734 char *
735 config::set_vars(char *buffer)
736 {
737 	char *lhs;
738 	char *rhs;
739 
740 	while (1) {
741 		if (!chop_var(buffer, lhs, rhs))
742 			break;
743 		set_variable(lhs, rhs);
744 	}
745 	return (buffer);
746 }
747 
748 void
749 config::find_and_execute(char type)
750 {
751 	vector<event_proc *> *l;
752 	vector<event_proc *>::const_iterator i;
753 	const char *s;
754 
755 	switch (type) {
756 	default:
757 		return;
758 	case notify:
759 		l = &_notify_list;
760 		s = "notify";
761 		break;
762 	case nomatch:
763 		l = &_nomatch_list;
764 		s = "nomatch";
765 		break;
766 	case attach:
767 		l = &_attach_list;
768 		s = "attach";
769 		break;
770 	case detach:
771 		l = &_detach_list;
772 		s = "detach";
773 		break;
774 	}
775 	devdlog(LOG_DEBUG, "Processing %s event\n", s);
776 	for (i = l->begin(); i != l->end(); ++i) {
777 		if ((*i)->matches(*this)) {
778 			(*i)->run(*this);
779 			break;
780 		}
781 	}
782 
783 }
784 
785 
786 static void
787 process_event(char *buffer)
788 {
789 	char type;
790 	char *sp;
791 	struct timeval tv;
792 	char *timestr;
793 
794 	sp = buffer + 1;
795 	devdlog(LOG_INFO, "Processing event '%s'\n", buffer);
796 	type = *buffer++;
797 	cfg.push_var_table();
798 	// $* is the entire line
799 	cfg.set_variable("*", buffer - 1);
800 	// $_ is the entire line without the initial character
801 	cfg.set_variable("_", buffer);
802 
803 	// Save the time this happened (as approximated by when we got
804 	// around to processing it).
805 	gettimeofday(&tv, NULL);
806 	asprintf(&timestr, "%jd.%06ld", (uintmax_t)tv.tv_sec, tv.tv_usec);
807 	cfg.set_variable("timestamp", timestr);
808 	free(timestr);
809 
810 	// Match doesn't have a device, and the format is a little
811 	// different, so handle it separately.
812 	switch (type) {
813 	case notify:
814 		//! (k=v)*
815 		sp = cfg.set_vars(sp);
816 		break;
817 	case nomatch:
818 		//? at location pnp-info on bus
819 		sp = strchr(sp, ' ');
820 		if (sp == NULL)
821 			return;	/* Can't happen? */
822 		*sp++ = '\0';
823 		while (isspace(*sp))
824 			sp++;
825 		if (strncmp(sp, "at ", 3) == 0)
826 			sp += 3;
827 		sp = cfg.set_vars(sp);
828 		while (isspace(*sp))
829 			sp++;
830 		if (strncmp(sp, "on ", 3) == 0)
831 			cfg.set_variable("bus", sp + 3);
832 		break;
833 	case attach:	/*FALLTHROUGH*/
834 	case detach:
835 		sp = strchr(sp, ' ');
836 		if (sp == NULL)
837 			return;	/* Can't happen? */
838 		*sp++ = '\0';
839 		cfg.set_variable("device-name", buffer);
840 		while (isspace(*sp))
841 			sp++;
842 		if (strncmp(sp, "at ", 3) == 0)
843 			sp += 3;
844 		sp = cfg.set_vars(sp);
845 		while (isspace(*sp))
846 			sp++;
847 		if (strncmp(sp, "on ", 3) == 0)
848 			cfg.set_variable("bus", sp + 3);
849 		break;
850 	}
851 
852 	cfg.find_and_execute(type);
853 	cfg.pop_var_table();
854 }
855 
856 int
857 create_socket(const char *name, int socktype)
858 {
859 	int fd, slen;
860 	struct sockaddr_un sun;
861 
862 	if ((fd = socket(PF_LOCAL, socktype, 0)) < 0)
863 		err(1, "socket");
864 	bzero(&sun, sizeof(sun));
865 	sun.sun_family = AF_UNIX;
866 	strlcpy(sun.sun_path, name, sizeof(sun.sun_path));
867 	slen = SUN_LEN(&sun);
868 	unlink(name);
869 	if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
870 	    	err(1, "fcntl");
871 	if (::bind(fd, (struct sockaddr *) & sun, slen) < 0)
872 		err(1, "bind");
873 	listen(fd, 4);
874 	chown(name, 0, 0);	/* XXX - root.wheel */
875 	chmod(name, 0666);
876 	return (fd);
877 }
878 
879 unsigned int max_clients = 10;	/* Default, can be overridden on cmdline. */
880 unsigned int num_clients;
881 
882 list<client_t> clients;
883 
884 void
885 notify_clients(const char *data, int len)
886 {
887 	list<client_t>::iterator i;
888 
889 	/*
890 	 * Deliver the data to all clients.  Throw clients overboard at the
891 	 * first sign of trouble.  This reaps clients who've died or closed
892 	 * their sockets, and also clients who are alive but failing to keep up
893 	 * (or who are maliciously not reading, to consume buffer space in
894 	 * kernel memory or tie up the limited number of available connections).
895 	 */
896 	for (i = clients.begin(); i != clients.end(); ) {
897 		int flags;
898 		if (i->socktype == SOCK_SEQPACKET)
899 			flags = MSG_EOR;
900 		else
901 			flags = 0;
902 
903 		if (send(i->fd, data, len, flags) != len) {
904 			--num_clients;
905 			close(i->fd);
906 			i = clients.erase(i);
907 			devdlog(LOG_WARNING, "notify_clients: send() failed; "
908 			    "dropping unresponsive client\n");
909 		} else
910 			++i;
911 	}
912 }
913 
914 void
915 check_clients(void)
916 {
917 	int s;
918 	struct pollfd pfd;
919 	list<client_t>::iterator i;
920 
921 	/*
922 	 * Check all existing clients to see if any of them have disappeared.
923 	 * Normally we reap clients when we get an error trying to send them an
924 	 * event.  This check eliminates the problem of an ever-growing list of
925 	 * zombie clients because we're never writing to them on a system
926 	 * without frequent device-change activity.
927 	 */
928 	pfd.events = 0;
929 	for (i = clients.begin(); i != clients.end(); ) {
930 		pfd.fd = i->fd;
931 		s = poll(&pfd, 1, 0);
932 		if ((s < 0 && s != EINTR ) ||
933 		    (s > 0 && (pfd.revents & POLLHUP))) {
934 			--num_clients;
935 			close(i->fd);
936 			i = clients.erase(i);
937 			devdlog(LOG_NOTICE, "check_clients:  "
938 			    "dropping disconnected client\n");
939 		} else
940 			++i;
941 	}
942 }
943 
944 void
945 new_client(int fd, int socktype)
946 {
947 	client_t s;
948 	int sndbuf_size;
949 
950 	/*
951 	 * First go reap any zombie clients, then accept the connection, and
952 	 * shut down the read side to stop clients from consuming kernel memory
953 	 * by sending large buffers full of data we'll never read.
954 	 */
955 	check_clients();
956 	s.socktype = socktype;
957 	s.fd = accept(fd, NULL, NULL);
958 	if (s.fd != -1) {
959 		sndbuf_size = CLIENT_BUFSIZE;
960 		if (setsockopt(s.fd, SOL_SOCKET, SO_SNDBUF, &sndbuf_size,
961 		    sizeof(sndbuf_size)))
962 			err(1, "setsockopt");
963 		shutdown(s.fd, SHUT_RD);
964 		clients.push_back(s);
965 		++num_clients;
966 	} else
967 		err(1, "accept");
968 }
969 
970 static void
971 event_loop(void)
972 {
973 	int rv;
974 	int fd;
975 	char buffer[DEVCTL_MAXBUF];
976 	int once = 0;
977 	int stream_fd, seqpacket_fd, max_fd;
978 	int accepting;
979 	timeval tv;
980 	fd_set fds;
981 
982 	fd = open(PATH_DEVCTL, O_RDONLY | O_CLOEXEC);
983 	if (fd == -1)
984 		err(1, "Can't open devctl device %s", PATH_DEVCTL);
985 	stream_fd = create_socket(STREAMPIPE, SOCK_STREAM);
986 	seqpacket_fd = create_socket(SEQPACKETPIPE, SOCK_SEQPACKET);
987 	accepting = 1;
988 	max_fd = max(fd, max(stream_fd, seqpacket_fd)) + 1;
989 	while (!romeo_must_die) {
990 		if (!once && !no_daemon && !daemonize_quick) {
991 			// Check to see if we have any events pending.
992 			tv.tv_sec = 0;
993 			tv.tv_usec = 0;
994 			FD_ZERO(&fds);
995 			FD_SET(fd, &fds);
996 			rv = select(fd + 1, &fds, &fds, &fds, &tv);
997 			// No events -> we've processed all pending events
998 			if (rv == 0) {
999 				devdlog(LOG_DEBUG, "Calling daemon\n");
1000 				cfg.remove_pidfile();
1001 				cfg.open_pidfile();
1002 				daemon(0, 0);
1003 				cfg.write_pidfile();
1004 				once++;
1005 			}
1006 		}
1007 		/*
1008 		 * When we've already got the max number of clients, stop
1009 		 * accepting new connections (don't put the listening sockets in
1010 		 * the set), shrink the accept() queue to reject connections
1011 		 * quickly, and poll the existing clients more often, so that we
1012 		 * notice more quickly when any of them disappear to free up
1013 		 * client slots.
1014 		 */
1015 		FD_ZERO(&fds);
1016 		FD_SET(fd, &fds);
1017 		if (num_clients < max_clients) {
1018 			if (!accepting) {
1019 				listen(stream_fd, max_clients);
1020 				listen(seqpacket_fd, max_clients);
1021 				accepting = 1;
1022 			}
1023 			FD_SET(stream_fd, &fds);
1024 			FD_SET(seqpacket_fd, &fds);
1025 			tv.tv_sec = 60;
1026 			tv.tv_usec = 0;
1027 		} else {
1028 			if (accepting) {
1029 				listen(stream_fd, 0);
1030 				listen(seqpacket_fd, 0);
1031 				accepting = 0;
1032 			}
1033 			tv.tv_sec = 2;
1034 			tv.tv_usec = 0;
1035 		}
1036 		rv = select(max_fd, &fds, NULL, NULL, &tv);
1037 		if (got_siginfo) {
1038 			devdlog(LOG_NOTICE, "Events received so far=%u\n",
1039 			    total_events);
1040 			got_siginfo = 0;
1041 		}
1042 		if (rv == -1) {
1043 			if (errno == EINTR)
1044 				continue;
1045 			err(1, "select");
1046 		} else if (rv == 0)
1047 			check_clients();
1048 		if (FD_ISSET(fd, &fds)) {
1049 			rv = read(fd, buffer, sizeof(buffer) - 1);
1050 			if (rv > 0) {
1051 				total_events++;
1052 				if (rv == sizeof(buffer) - 1) {
1053 					devdlog(LOG_WARNING, "Warning: "
1054 					    "available event data exceeded "
1055 					    "buffer space\n");
1056 				}
1057 				notify_clients(buffer, rv);
1058 				buffer[rv] = '\0';
1059 				while (buffer[--rv] == '\n')
1060 					buffer[rv] = '\0';
1061 				process_event(buffer);
1062 			} else if (rv < 0) {
1063 				if (errno != EINTR)
1064 					break;
1065 			} else {
1066 				/* EOF */
1067 				break;
1068 			}
1069 		}
1070 		if (FD_ISSET(stream_fd, &fds))
1071 			new_client(stream_fd, SOCK_STREAM);
1072 		/*
1073 		 * Aside from the socket type, both sockets use the same
1074 		 * protocol, so we can process clients the same way.
1075 		 */
1076 		if (FD_ISSET(seqpacket_fd, &fds))
1077 			new_client(seqpacket_fd, SOCK_SEQPACKET);
1078 	}
1079 	close(fd);
1080 }
1081 
1082 /*
1083  * functions that the parser uses.
1084  */
1085 void
1086 add_attach(int prio, event_proc *p)
1087 {
1088 	cfg.add_attach(prio, p);
1089 }
1090 
1091 void
1092 add_detach(int prio, event_proc *p)
1093 {
1094 	cfg.add_detach(prio, p);
1095 }
1096 
1097 void
1098 add_directory(const char *dir)
1099 {
1100 	cfg.add_directory(dir);
1101 	free(const_cast<char *>(dir));
1102 }
1103 
1104 void
1105 add_nomatch(int prio, event_proc *p)
1106 {
1107 	cfg.add_nomatch(prio, p);
1108 }
1109 
1110 void
1111 add_notify(int prio, event_proc *p)
1112 {
1113 	cfg.add_notify(prio, p);
1114 }
1115 
1116 event_proc *
1117 add_to_event_proc(event_proc *ep, eps *eps)
1118 {
1119 	if (ep == NULL)
1120 		ep = new event_proc();
1121 	ep->add(eps);
1122 	return (ep);
1123 }
1124 
1125 eps *
1126 new_action(const char *cmd)
1127 {
1128 	eps *e = new action(cmd);
1129 	free(const_cast<char *>(cmd));
1130 	return (e);
1131 }
1132 
1133 eps *
1134 new_match(const char *var, const char *re)
1135 {
1136 	eps *e = new match(cfg, var, re);
1137 	free(const_cast<char *>(var));
1138 	free(const_cast<char *>(re));
1139 	return (e);
1140 }
1141 
1142 eps *
1143 new_media(const char *var, const char *re)
1144 {
1145 	eps *e = new media(cfg, var, re);
1146 	free(const_cast<char *>(var));
1147 	free(const_cast<char *>(re));
1148 	return (e);
1149 }
1150 
1151 void
1152 set_pidfile(const char *name)
1153 {
1154 	cfg.set_pidfile(name);
1155 	free(const_cast<char *>(name));
1156 }
1157 
1158 void
1159 set_variable(const char *var, const char *val)
1160 {
1161 	cfg.set_variable(var, val);
1162 	free(const_cast<char *>(var));
1163 	free(const_cast<char *>(val));
1164 }
1165 
1166 
1167 
1168 static void
1169 gensighand(int)
1170 {
1171 	romeo_must_die = 1;
1172 }
1173 
1174 /*
1175  * SIGINFO handler.  Will print useful statistics to the syslog or stderr
1176  * as appropriate
1177  */
1178 static void
1179 siginfohand(int)
1180 {
1181 	got_siginfo = 1;
1182 }
1183 
1184 /*
1185  * Local logging function.  Prints to syslog if we're daemonized; stderr
1186  * otherwise.
1187  */
1188 static void
1189 devdlog(int priority, const char* fmt, ...)
1190 {
1191 	va_list argp;
1192 
1193 	va_start(argp, fmt);
1194 	if (no_daemon)
1195 		vfprintf(stderr, fmt, argp);
1196 	else if ((! quiet_mode) || (priority <= LOG_WARNING))
1197 		vsyslog(priority, fmt, argp);
1198 	va_end(argp);
1199 }
1200 
1201 static void
1202 usage()
1203 {
1204 	fprintf(stderr, "usage: %s [-dnq] [-l connlimit] [-f file]\n",
1205 	    getprogname());
1206 	exit(1);
1207 }
1208 
1209 static void
1210 check_devd_enabled()
1211 {
1212 	int val = 0;
1213 	size_t len;
1214 
1215 	len = sizeof(val);
1216 	if (sysctlbyname(SYSCTL, &val, &len, NULL, 0) != 0)
1217 		errx(1, "devctl sysctl missing from kernel!");
1218 	if (val == 0) {
1219 		warnx("Setting " SYSCTL " to 1000");
1220 		val = 1000;
1221 		sysctlbyname(SYSCTL, NULL, NULL, &val, sizeof(val));
1222 	}
1223 }
1224 
1225 /*
1226  * main
1227  */
1228 int
1229 main(int argc, char **argv)
1230 {
1231 	int ch;
1232 
1233 	check_devd_enabled();
1234 	while ((ch = getopt(argc, argv, "df:l:nq")) != -1) {
1235 		switch (ch) {
1236 		case 'd':
1237 			no_daemon = 1;
1238 			break;
1239 		case 'f':
1240 			configfile = optarg;
1241 			break;
1242 		case 'l':
1243 			max_clients = MAX(1, strtoul(optarg, NULL, 0));
1244 			break;
1245 		case 'n':
1246 			daemonize_quick = 1;
1247 			break;
1248 		case 'q':
1249 			quiet_mode = 1;
1250 			break;
1251 		default:
1252 			usage();
1253 		}
1254 	}
1255 
1256 	cfg.parse();
1257 	if (!no_daemon && daemonize_quick) {
1258 		cfg.open_pidfile();
1259 		daemon(0, 0);
1260 		cfg.write_pidfile();
1261 	}
1262 	signal(SIGPIPE, SIG_IGN);
1263 	signal(SIGHUP, gensighand);
1264 	signal(SIGINT, gensighand);
1265 	signal(SIGTERM, gensighand);
1266 	signal(SIGINFO, siginfohand);
1267 	event_loop();
1268 	return (0);
1269 }
1270