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