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