xref: /freebsd/sbin/devd/devd.cc (revision d0b2dbfa0ecf2bbc9709efc5e20baf8e4b44bbbf)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause AND BSD-2-Clause
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 #include <sys/param.h>
68 #include <sys/socket.h>
69 #include <sys/stat.h>
70 #include <sys/sysctl.h>
71 #include <sys/types.h>
72 #include <sys/wait.h>
73 #include <sys/un.h>
74 
75 #include <cctype>
76 #include <cerrno>
77 #include <cstdlib>
78 #include <cstdio>
79 #include <csignal>
80 #include <cstring>
81 #include <cstdarg>
82 
83 #include <dirent.h>
84 #include <err.h>
85 #include <fcntl.h>
86 #include <libutil.h>
87 #include <paths.h>
88 #include <poll.h>
89 #include <regex.h>
90 #include <syslog.h>
91 #include <unistd.h>
92 
93 #include <algorithm>
94 #include <map>
95 #include <string>
96 #include <list>
97 #include <stdexcept>
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 
141 static const char notify = '!';
142 static const char nomatch = '?';
143 static const char attach = '+';
144 static const char detach = '-';
145 
146 static struct pidfh *pfh;
147 
148 static int no_daemon = 0;
149 static int daemonize_quick = 0;
150 static int quiet_mode = 0;
151 static unsigned total_events = 0;
152 static volatile sig_atomic_t got_siginfo = 0;
153 static volatile sig_atomic_t romeo_must_die = 0;
154 
155 static const char *configfile = CF;
156 
157 static void devdlog(int priority, const char* message, ...)
158 	__printflike(2, 3);
159 static void event_loop(void);
160 static void usage(void) __dead2;
161 
162 template <class T> void
163 delete_and_clear(vector<T *> &v)
164 {
165 	typename vector<T *>::const_iterator i;
166 
167 	for (i = v.begin(); i != v.end(); ++i)
168 		delete *i;
169 	v.clear();
170 }
171 
172 static config cfg;
173 
174 static const char *curr_cf = NULL;
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 /*
456  * Called recursively as new files are included, so current stack of old names
457  * saved in each instance of 'old' on the call stack. Called single threaded
458  * so global varaibles curr_cf and lineno (and all of yacc's parser state)
459  * are safe to access w/o a lock.
460  */
461 void
462 config::parse_one_file(const char *fn)
463 {
464 	const char *old;
465 
466 	devdlog(LOG_DEBUG, "Parsing %s\n", fn);
467 	yyin = fopen(fn, "r");
468 	old = curr_cf;
469 	curr_cf = fn;
470 	if (yyin == NULL)
471 		err(1, "Cannot open config file %s", fn);
472 	lineno = 1;
473 	if (yyparse() != 0)
474 		errx(1, "Cannot parse %s at line %d", fn, lineno);
475 	fclose(yyin);
476 	curr_cf = old;
477 }
478 
479 void
480 config::parse_files_in_dir(const char *dirname)
481 {
482 	DIR *dirp;
483 	struct dirent *dp;
484 	char path[PATH_MAX];
485 
486 	devdlog(LOG_DEBUG, "Parsing files in %s\n", dirname);
487 	dirp = opendir(dirname);
488 	if (dirp == NULL)
489 		return;
490 	readdir(dirp);		/* Skip . */
491 	readdir(dirp);		/* Skip .. */
492 	while ((dp = readdir(dirp)) != NULL) {
493 		if (strcmp(dp->d_name + dp->d_namlen - 5, ".conf") == 0) {
494 			snprintf(path, sizeof(path), "%s/%s",
495 			    dirname, dp->d_name);
496 			parse_one_file(path);
497 		}
498 	}
499 	closedir(dirp);
500 }
501 
502 class epv_greater {
503 public:
504 	int operator()(event_proc *const&l1, event_proc *const&l2) const
505 	{
506 		return (l1->get_priority() > l2->get_priority());
507 	}
508 };
509 
510 void
511 config::sort_vector(vector<event_proc *> &v)
512 {
513 	stable_sort(v.begin(), v.end(), epv_greater());
514 }
515 
516 void
517 config::parse(void)
518 {
519 	vector<string>::const_iterator i;
520 
521 	parse_one_file(configfile);
522 	for (i = _dir_list.begin(); i != _dir_list.end(); ++i)
523 		parse_files_in_dir((*i).c_str());
524 	sort_vector(_attach_list);
525 	sort_vector(_detach_list);
526 	sort_vector(_nomatch_list);
527 	sort_vector(_notify_list);
528 }
529 
530 void
531 config::open_pidfile()
532 {
533 	pid_t otherpid;
534 
535 	if (_pidfile.empty())
536 		return;
537 	pfh = pidfile_open(_pidfile.c_str(), 0600, &otherpid);
538 	if (pfh == NULL) {
539 		if (errno == EEXIST)
540 			errx(1, "devd already running, pid: %d", (int)otherpid);
541 		warn("cannot open pid file");
542 	}
543 }
544 
545 void
546 config::write_pidfile()
547 {
548 
549 	pidfile_write(pfh);
550 }
551 
552 void
553 config::close_pidfile()
554 {
555 
556 	pidfile_close(pfh);
557 }
558 
559 void
560 config::remove_pidfile()
561 {
562 
563 	pidfile_remove(pfh);
564 }
565 
566 void
567 config::add_attach(int prio, event_proc *p)
568 {
569 	p->set_priority(prio);
570 	_attach_list.push_back(p);
571 }
572 
573 void
574 config::add_detach(int prio, event_proc *p)
575 {
576 	p->set_priority(prio);
577 	_detach_list.push_back(p);
578 }
579 
580 void
581 config::add_directory(const char *dir)
582 {
583 	_dir_list.push_back(string(dir));
584 }
585 
586 void
587 config::add_nomatch(int prio, event_proc *p)
588 {
589 	p->set_priority(prio);
590 	_nomatch_list.push_back(p);
591 }
592 
593 void
594 config::add_notify(int prio, event_proc *p)
595 {
596 	p->set_priority(prio);
597 	_notify_list.push_back(p);
598 }
599 
600 void
601 config::set_pidfile(const char *fn)
602 {
603 	_pidfile = fn;
604 }
605 
606 void
607 config::push_var_table()
608 {
609 	var_list *vl;
610 
611 	vl = new var_list();
612 	_var_list_table.push_back(vl);
613 	devdlog(LOG_DEBUG, "Pushing table\n");
614 }
615 
616 void
617 config::pop_var_table()
618 {
619 	delete _var_list_table.back();
620 	_var_list_table.pop_back();
621 	devdlog(LOG_DEBUG, "Popping table\n");
622 }
623 
624 void
625 config::set_variable(const char *var, const char *val)
626 {
627 	_var_list_table.back()->set_variable(var, val);
628 }
629 
630 const string &
631 config::get_variable(const string &var)
632 {
633 	vector<var_list *>::reverse_iterator i;
634 
635 	for (i = _var_list_table.rbegin(); i != _var_list_table.rend(); ++i) {
636 		if ((*i)->is_set(var))
637 			return ((*i)->get_variable(var));
638 	}
639 	return (var_list::nothing);
640 }
641 
642 bool
643 config::is_id_char(char ch) const
644 {
645 	return (ch != '\0' && (isalpha(ch) || isdigit(ch) || ch == '_' ||
646 	    ch == '-'));
647 }
648 
649 string
650 config::shell_quote(const string &s)
651 {
652 	string buffer;
653 	const char *cs, *ce;
654 	char c;
655 
656 	/*
657 	 * Enclose the string in $' ' with escapes for ' and / characters making
658 	 * it one argument and ensuring the shell won't be affected by its
659 	 * usual list of candidates.
660 	 */
661 	buffer.reserve(s.length() * 3 / 2);
662 	buffer += '$';
663 	buffer += '\'';
664 	cs = s.c_str();
665 	ce = cs + strlen(cs);
666 	for (; cs < ce; cs++) {
667 		c = *cs;
668 		if (c == '\'' || c == '\\') {
669 			buffer += '\\';
670 		}
671 		buffer += c;
672 	}
673 	buffer += '\'';
674 
675 	return buffer;
676 }
677 
678 void
679 config::expand_one(const char *&src, string &dst, bool is_shell)
680 {
681 	int count;
682 	string buffer;
683 
684 	src++;
685 	// $$ -> $
686 	if (*src == '$') {
687 		dst += *src++;
688 		return;
689 	}
690 
691 	// $(foo) -> $(foo)
692 	// This is the escape hatch for passing down shell subcommands
693 	if (*src == '(') {
694 		dst += '$';
695 		count = 0;
696 		/* If the string ends before ) is matched , return. */
697 		do {
698 			if (*src == ')')
699 				count--;
700 			else if (*src == '(')
701 				count++;
702 			dst += *src++;
703 		} while (count > 0 && *src);
704 		return;
705 	}
706 
707 	// $[^-A-Za-z_*] -> $\1
708 	if (!isalpha(*src) && *src != '_' && *src != '-' && *src != '*') {
709 		dst += '$';
710 		dst += *src++;
711 		return;
712 	}
713 
714 	// $var -> replace with value
715 	do {
716 		buffer += *src++;
717 	} while (is_id_char(*src));
718 	dst.append(is_shell ? shell_quote(get_variable(buffer)) : get_variable(buffer));
719 }
720 
721 const string
722 config::expand_string(const char *src, const char *prepend, const char *append)
723 {
724 	const char *var_at;
725 	string dst;
726 
727 	/*
728 	 * 128 bytes is enough for 2427 of 2438 expansions that happen
729 	 * while parsing config files, as tested on 2013-01-30.
730 	 */
731 	dst.reserve(128);
732 
733 	if (prepend != NULL)
734 		dst = prepend;
735 
736 	for (;;) {
737 		var_at = strchr(src, '$');
738 		if (var_at == NULL) {
739 			dst.append(src);
740 			break;
741 		}
742 		dst.append(src, var_at - src);
743 		src = var_at;
744 		expand_one(src, dst, prepend == NULL);
745 	}
746 
747 	if (append != NULL)
748 		dst.append(append);
749 
750 	return (dst);
751 }
752 
753 bool
754 config::chop_var(char *&buffer, char *&lhs, char *&rhs) const
755 {
756 	char *walker;
757 
758 	if (*buffer == '\0')
759 		return (false);
760 	walker = lhs = buffer;
761 	while (is_id_char(*walker))
762 		walker++;
763 	if (*walker != '=')
764 		return (false);
765 	walker++;		// skip =
766 	if (*walker == '"') {
767 		walker++;	// skip "
768 		rhs = walker;
769 		while (*walker && *walker != '"') {
770 			// Skip \" ... We leave it in the string and strip the \ later.
771 			// due to the super simplistic parser that we have here.
772 			if (*walker == '\\' && walker[1] == '"')
773 				walker++;
774 			walker++;
775 		}
776 		if (*walker != '"')
777 			return (false);
778 		rhs[-2] = '\0';
779 		*walker++ = '\0';
780 	} else {
781 		rhs = walker;
782 		while (*walker && !isspace(*walker))
783 			walker++;
784 		if (*walker != '\0')
785 			*walker++ = '\0';
786 		rhs[-1] = '\0';
787 	}
788 	while (isspace(*walker))
789 		walker++;
790 	buffer = walker;
791 	return (true);
792 }
793 
794 
795 char *
796 config::set_vars(char *buffer)
797 {
798 	char *lhs;
799 	char *rhs;
800 
801 	while (1) {
802 		if (!chop_var(buffer, lhs, rhs))
803 			break;
804 		set_variable(lhs, rhs);
805 	}
806 	return (buffer);
807 }
808 
809 void
810 config::find_and_execute(char type)
811 {
812 	vector<event_proc *> *l;
813 	vector<event_proc *>::const_iterator i;
814 	const char *s;
815 
816 	switch (type) {
817 	default:
818 		return;
819 	case notify:
820 		l = &_notify_list;
821 		s = "notify";
822 		break;
823 	case nomatch:
824 		l = &_nomatch_list;
825 		s = "nomatch";
826 		break;
827 	case attach:
828 		l = &_attach_list;
829 		s = "attach";
830 		break;
831 	case detach:
832 		l = &_detach_list;
833 		s = "detach";
834 		break;
835 	}
836 	devdlog(LOG_DEBUG, "Processing %s event\n", s);
837 	for (i = l->begin(); i != l->end(); ++i) {
838 		if ((*i)->matches(*this)) {
839 			(*i)->run(*this);
840 			break;
841 		}
842 	}
843 
844 }
845 
846 
847 static void
848 process_event(char *buffer)
849 {
850 	char type;
851 	char *sp;
852 	struct timeval tv;
853 	char *timestr;
854 
855 	sp = buffer + 1;
856 	devdlog(LOG_INFO, "Processing event '%s'\n", buffer);
857 	type = *buffer++;
858 	cfg.push_var_table();
859 	// $* is the entire line
860 	cfg.set_variable("*", buffer - 1);
861 	// $_ is the entire line without the initial character
862 	cfg.set_variable("_", buffer);
863 
864 	// Save the time this happened (as approximated by when we got
865 	// around to processing it).
866 	gettimeofday(&tv, NULL);
867 	asprintf(&timestr, "%jd.%06ld", (uintmax_t)tv.tv_sec, tv.tv_usec);
868 	cfg.set_variable("timestamp", timestr);
869 	free(timestr);
870 
871 	// Match doesn't have a device, and the format is a little
872 	// different, so handle it separately.
873 	switch (type) {
874 	case notify:
875 		//! (k=v)*
876 		sp = cfg.set_vars(sp);
877 		break;
878 	case nomatch:
879 		//? at location pnp-info on bus
880 		sp = strchr(sp, ' ');
881 		if (sp == NULL)
882 			return;	/* Can't happen? */
883 		*sp++ = '\0';
884 		while (isspace(*sp))
885 			sp++;
886 		if (strncmp(sp, "at ", 3) == 0)
887 			sp += 3;
888 		sp = cfg.set_vars(sp);
889 		while (isspace(*sp))
890 			sp++;
891 		if (strncmp(sp, "on ", 3) == 0)
892 			cfg.set_variable("bus", sp + 3);
893 		break;
894 	case attach:	/*FALLTHROUGH*/
895 	case detach:
896 		sp = strchr(sp, ' ');
897 		if (sp == NULL)
898 			return;	/* Can't happen? */
899 		*sp++ = '\0';
900 		cfg.set_variable("device-name", buffer);
901 		while (isspace(*sp))
902 			sp++;
903 		if (strncmp(sp, "at ", 3) == 0)
904 			sp += 3;
905 		sp = cfg.set_vars(sp);
906 		while (isspace(*sp))
907 			sp++;
908 		if (strncmp(sp, "on ", 3) == 0)
909 			cfg.set_variable("bus", sp + 3);
910 		break;
911 	}
912 
913 	cfg.find_and_execute(type);
914 	cfg.pop_var_table();
915 }
916 
917 static int
918 create_socket(const char *name, int socktype)
919 {
920 	int fd, slen;
921 	struct sockaddr_un sun;
922 
923 	if ((fd = socket(PF_LOCAL, socktype, 0)) < 0)
924 		err(1, "socket");
925 	bzero(&sun, sizeof(sun));
926 	sun.sun_family = AF_UNIX;
927 	strlcpy(sun.sun_path, name, sizeof(sun.sun_path));
928 	slen = SUN_LEN(&sun);
929 	unlink(name);
930 	if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
931 	    	err(1, "fcntl");
932 	if (::bind(fd, (struct sockaddr *) & sun, slen) < 0)
933 		err(1, "bind");
934 	listen(fd, 4);
935 	if (chown(name, 0, 0))	/* XXX - root.wheel */
936 		err(1, "chown");
937 	if (chmod(name, 0666))
938 		err(1, "chmod");
939 	return (fd);
940 }
941 
942 static unsigned int max_clients = 10;	/* Default, can be overridden on cmdline. */
943 static unsigned int num_clients;
944 
945 static list<client_t> clients;
946 
947 static void
948 notify_clients(const char *data, int len)
949 {
950 	list<client_t>::iterator i;
951 
952 	/*
953 	 * Deliver the data to all clients.  Throw clients overboard at the
954 	 * first sign of trouble.  This reaps clients who've died or closed
955 	 * their sockets, and also clients who are alive but failing to keep up
956 	 * (or who are maliciously not reading, to consume buffer space in
957 	 * kernel memory or tie up the limited number of available connections).
958 	 */
959 	for (i = clients.begin(); i != clients.end(); ) {
960 		int flags;
961 		if (i->socktype == SOCK_SEQPACKET)
962 			flags = MSG_EOR;
963 		else
964 			flags = 0;
965 
966 		if (send(i->fd, data, len, flags) != len) {
967 			--num_clients;
968 			close(i->fd);
969 			i = clients.erase(i);
970 			devdlog(LOG_WARNING, "notify_clients: send() failed; "
971 			    "dropping unresponsive client\n");
972 		} else
973 			++i;
974 	}
975 }
976 
977 static void
978 check_clients(void)
979 {
980 	int s;
981 	struct pollfd pfd;
982 	list<client_t>::iterator i;
983 
984 	/*
985 	 * Check all existing clients to see if any of them have disappeared.
986 	 * Normally we reap clients when we get an error trying to send them an
987 	 * event.  This check eliminates the problem of an ever-growing list of
988 	 * zombie clients because we're never writing to them on a system
989 	 * without frequent device-change activity.
990 	 */
991 	pfd.events = 0;
992 	for (i = clients.begin(); i != clients.end(); ) {
993 		pfd.fd = i->fd;
994 		s = poll(&pfd, 1, 0);
995 		if ((s < 0 && s != EINTR ) ||
996 		    (s > 0 && (pfd.revents & POLLHUP))) {
997 			--num_clients;
998 			close(i->fd);
999 			i = clients.erase(i);
1000 			devdlog(LOG_NOTICE, "check_clients:  "
1001 			    "dropping disconnected client\n");
1002 		} else
1003 			++i;
1004 	}
1005 }
1006 
1007 static void
1008 new_client(int fd, int socktype)
1009 {
1010 	client_t s;
1011 	int sndbuf_size;
1012 
1013 	/*
1014 	 * First go reap any zombie clients, then accept the connection, and
1015 	 * shut down the read side to stop clients from consuming kernel memory
1016 	 * by sending large buffers full of data we'll never read.
1017 	 */
1018 	check_clients();
1019 	s.socktype = socktype;
1020 	s.fd = accept(fd, NULL, NULL);
1021 	if (s.fd != -1) {
1022 		sndbuf_size = CLIENT_BUFSIZE;
1023 		if (setsockopt(s.fd, SOL_SOCKET, SO_SNDBUF, &sndbuf_size,
1024 		    sizeof(sndbuf_size)))
1025 			err(1, "setsockopt");
1026 		shutdown(s.fd, SHUT_RD);
1027 		clients.push_back(s);
1028 		++num_clients;
1029 	} else
1030 		err(1, "accept");
1031 }
1032 
1033 static void
1034 event_loop(void)
1035 {
1036 	int rv;
1037 	int fd;
1038 	char buffer[DEVCTL_MAXBUF];
1039 	int once = 0;
1040 	int stream_fd, seqpacket_fd, max_fd;
1041 	int accepting;
1042 	timeval tv;
1043 	fd_set fds;
1044 
1045 	fd = open(PATH_DEVCTL, O_RDONLY | O_CLOEXEC);
1046 	if (fd == -1)
1047 		err(1, "Can't open devctl device %s", PATH_DEVCTL);
1048 	stream_fd = create_socket(STREAMPIPE, SOCK_STREAM);
1049 	seqpacket_fd = create_socket(SEQPACKETPIPE, SOCK_SEQPACKET);
1050 	accepting = 1;
1051 	max_fd = max(fd, max(stream_fd, seqpacket_fd)) + 1;
1052 	while (!romeo_must_die) {
1053 		if (!once && !no_daemon && !daemonize_quick) {
1054 			// Check to see if we have any events pending.
1055 			tv.tv_sec = 0;
1056 			tv.tv_usec = 0;
1057 			FD_ZERO(&fds);
1058 			FD_SET(fd, &fds);
1059 			rv = select(fd + 1, &fds, NULL, NULL, &tv);
1060 			// No events -> we've processed all pending events
1061 			if (rv == 0) {
1062 				devdlog(LOG_DEBUG, "Calling daemon\n");
1063 				cfg.remove_pidfile();
1064 				cfg.open_pidfile();
1065 				daemon(0, 0);
1066 				cfg.write_pidfile();
1067 				once++;
1068 			}
1069 		}
1070 		/*
1071 		 * When we've already got the max number of clients, stop
1072 		 * accepting new connections (don't put the listening sockets in
1073 		 * the set), shrink the accept() queue to reject connections
1074 		 * quickly, and poll the existing clients more often, so that we
1075 		 * notice more quickly when any of them disappear to free up
1076 		 * client slots.
1077 		 */
1078 		FD_ZERO(&fds);
1079 		FD_SET(fd, &fds);
1080 		if (num_clients < max_clients) {
1081 			if (!accepting) {
1082 				listen(stream_fd, max_clients);
1083 				listen(seqpacket_fd, max_clients);
1084 				accepting = 1;
1085 			}
1086 			FD_SET(stream_fd, &fds);
1087 			FD_SET(seqpacket_fd, &fds);
1088 			tv.tv_sec = 60;
1089 			tv.tv_usec = 0;
1090 		} else {
1091 			if (accepting) {
1092 				listen(stream_fd, 0);
1093 				listen(seqpacket_fd, 0);
1094 				accepting = 0;
1095 			}
1096 			tv.tv_sec = 2;
1097 			tv.tv_usec = 0;
1098 		}
1099 		rv = select(max_fd, &fds, NULL, NULL, &tv);
1100 		if (got_siginfo) {
1101 			devdlog(LOG_NOTICE, "Events received so far=%u\n",
1102 			    total_events);
1103 			got_siginfo = 0;
1104 		}
1105 		if (rv == -1) {
1106 			if (errno == EINTR)
1107 				continue;
1108 			err(1, "select");
1109 		} else if (rv == 0)
1110 			check_clients();
1111 		if (FD_ISSET(fd, &fds)) {
1112 			rv = read(fd, buffer, sizeof(buffer) - 1);
1113 			if (rv > 0) {
1114 				total_events++;
1115 				if (rv == sizeof(buffer) - 1) {
1116 					devdlog(LOG_WARNING, "Warning: "
1117 					    "available event data exceeded "
1118 					    "buffer space\n");
1119 				}
1120 				notify_clients(buffer, rv);
1121 				buffer[rv] = '\0';
1122 				while (buffer[--rv] == '\n')
1123 					buffer[rv] = '\0';
1124 				try {
1125 					process_event(buffer);
1126 				}
1127 				catch (const std::length_error& e) {
1128 					devdlog(LOG_ERR, "Dropping event %s "
1129 					    "due to low memory", buffer);
1130 				}
1131 			} else if (rv < 0) {
1132 				if (errno != EINTR)
1133 					break;
1134 			} else {
1135 				/* EOF */
1136 				break;
1137 			}
1138 		}
1139 		if (FD_ISSET(stream_fd, &fds))
1140 			new_client(stream_fd, SOCK_STREAM);
1141 		/*
1142 		 * Aside from the socket type, both sockets use the same
1143 		 * protocol, so we can process clients the same way.
1144 		 */
1145 		if (FD_ISSET(seqpacket_fd, &fds))
1146 			new_client(seqpacket_fd, SOCK_SEQPACKET);
1147 	}
1148 	cfg.remove_pidfile();
1149 	close(seqpacket_fd);
1150 	close(stream_fd);
1151 	close(fd);
1152 }
1153 
1154 /*
1155  * functions that the parser uses.
1156  */
1157 void
1158 add_attach(int prio, event_proc *p)
1159 {
1160 	cfg.add_attach(prio, p);
1161 }
1162 
1163 void
1164 add_detach(int prio, event_proc *p)
1165 {
1166 	cfg.add_detach(prio, p);
1167 }
1168 
1169 void
1170 add_directory(const char *dir)
1171 {
1172 	cfg.add_directory(dir);
1173 	free(const_cast<char *>(dir));
1174 }
1175 
1176 void
1177 add_nomatch(int prio, event_proc *p)
1178 {
1179 	cfg.add_nomatch(prio, p);
1180 }
1181 
1182 void
1183 add_notify(int prio, event_proc *p)
1184 {
1185 	cfg.add_notify(prio, p);
1186 }
1187 
1188 event_proc *
1189 add_to_event_proc(event_proc *ep, eps *eps)
1190 {
1191 	if (ep == NULL)
1192 		ep = new event_proc();
1193 	ep->add(eps);
1194 	return (ep);
1195 }
1196 
1197 eps *
1198 new_action(const char *cmd)
1199 {
1200 	eps *e = new action(cmd);
1201 	free(const_cast<char *>(cmd));
1202 	return (e);
1203 }
1204 
1205 eps *
1206 new_match(const char *var, const char *re)
1207 {
1208 	/*
1209 	 * In FreeBSD 14, we changed the system=kern to system=kernel for the
1210 	 * resume message to match all the other 'kernel' messages. Generate a
1211 	 * warning for the life of 14.x that we've 'fixed' the file on the fly,
1212 	 * but make it a fatal error in 15.x and newer.
1213 	 */
1214 	if (strcmp(var, "kern") == 0) {
1215 #if __FreeBSD_version < 1500000
1216 		devdlog(LOG_WARNING,
1217 		    "Changing deprecated system='kern' to new name 'kernel' in %s line %d.",
1218 		    curr_cf, lineno);
1219 		free(const_cast<char *>(var));
1220 		var = strdup("kernel");
1221 #elif  __FreeBSD_version < 1600000
1222 		errx(1, "Encountered deprecated system=\"kern\" rule in %s line %d",
1223 		    curr_cf, lineno);
1224 #else
1225 #error "Remove this gross hack"
1226 #endif
1227 	}
1228 
1229 	eps *e = new match(cfg, var, re);
1230 	free(const_cast<char *>(var));
1231 	free(const_cast<char *>(re));
1232 	return (e);
1233 }
1234 
1235 eps *
1236 new_media(const char *var, const char *re)
1237 {
1238 	eps *e = new media(cfg, var, re);
1239 	free(const_cast<char *>(var));
1240 	free(const_cast<char *>(re));
1241 	return (e);
1242 }
1243 
1244 void
1245 set_pidfile(const char *name)
1246 {
1247 	cfg.set_pidfile(name);
1248 	free(const_cast<char *>(name));
1249 }
1250 
1251 void
1252 set_variable(const char *var, const char *val)
1253 {
1254 	cfg.set_variable(var, val);
1255 	free(const_cast<char *>(var));
1256 	free(const_cast<char *>(val));
1257 }
1258 
1259 
1260 
1261 static void
1262 gensighand(int)
1263 {
1264 	romeo_must_die = 1;
1265 }
1266 
1267 /*
1268  * SIGINFO handler.  Will print useful statistics to the syslog or stderr
1269  * as appropriate
1270  */
1271 static void
1272 siginfohand(int)
1273 {
1274 	got_siginfo = 1;
1275 }
1276 
1277 /*
1278  * Local logging function.  Prints to syslog if we're daemonized; stderr
1279  * otherwise.
1280  */
1281 static void
1282 devdlog(int priority, const char* fmt, ...)
1283 {
1284 	va_list argp;
1285 
1286 	va_start(argp, fmt);
1287 	if (no_daemon)
1288 		vfprintf(stderr, fmt, argp);
1289 	else if (quiet_mode == 0 || priority <= LOG_WARNING)
1290 		vsyslog(priority, fmt, argp);
1291 	va_end(argp);
1292 }
1293 
1294 static void
1295 usage()
1296 {
1297 	fprintf(stderr, "usage: %s [-dnq] [-l connlimit] [-f file]\n",
1298 	    getprogname());
1299 	exit(1);
1300 }
1301 
1302 static void
1303 check_devd_enabled()
1304 {
1305 	int val = 0;
1306 	size_t len;
1307 
1308 	len = sizeof(val);
1309 	if (sysctlbyname(SYSCTL, &val, &len, NULL, 0) != 0)
1310 		errx(1, "devctl sysctl missing from kernel!");
1311 	if (val == 0) {
1312 		warnx("Setting " SYSCTL " to 1000");
1313 		val = 1000;
1314 		if (sysctlbyname(SYSCTL, NULL, NULL, &val, sizeof(val)))
1315 			err(1, "sysctlbyname");
1316 	}
1317 }
1318 
1319 /*
1320  * main
1321  */
1322 int
1323 main(int argc, char **argv)
1324 {
1325 	int ch;
1326 
1327 	check_devd_enabled();
1328 	while ((ch = getopt(argc, argv, "df:l:nq")) != -1) {
1329 		switch (ch) {
1330 		case 'd':
1331 			no_daemon = 1;
1332 			break;
1333 		case 'f':
1334 			configfile = optarg;
1335 			break;
1336 		case 'l':
1337 			max_clients = MAX(1, strtoul(optarg, NULL, 0));
1338 			break;
1339 		case 'n':
1340 			daemonize_quick = 1;
1341 			break;
1342 		case 'q':
1343 			quiet_mode = 1;
1344 			break;
1345 		default:
1346 			usage();
1347 		}
1348 	}
1349 
1350 	cfg.parse();
1351 	if (!no_daemon && daemonize_quick) {
1352 		cfg.open_pidfile();
1353 		daemon(0, 0);
1354 		cfg.write_pidfile();
1355 	}
1356 	signal(SIGPIPE, SIG_IGN);
1357 	signal(SIGHUP, gensighand);
1358 	signal(SIGINT, gensighand);
1359 	signal(SIGTERM, gensighand);
1360 	signal(SIGINFO, siginfohand);
1361 	event_loop();
1362 	return (0);
1363 }
1364