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