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