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