xref: /freebsd/sbin/devd/devd.cc (revision 38535d6cab17b86db2806866ab9b7a2a30c1ab90)
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 void
640 config::expand_one(const char *&src, string &dst)
641 {
642 	int count;
643 	string buffer;
644 
645 	src++;
646 	// $$ -> $
647 	if (*src == '$') {
648 		dst += *src++;
649 		return;
650 	}
651 
652 	// $(foo) -> $(foo)
653 	// Not sure if I want to support this or not, so for now we just pass
654 	// it through.
655 	if (*src == '(') {
656 		dst += '$';
657 		count = 1;
658 		/* If the string ends before ) is matched , return. */
659 		while (count > 0 && *src) {
660 			if (*src == ')')
661 				count--;
662 			else if (*src == '(')
663 				count++;
664 			dst += *src++;
665 		}
666 		return;
667 	}
668 
669 	// $[^-A-Za-z_*] -> $\1
670 	if (!isalpha(*src) && *src != '_' && *src != '-' && *src != '*') {
671 		dst += '$';
672 		dst += *src++;
673 		return;
674 	}
675 
676 	// $var -> replace with value
677 	do {
678 		buffer += *src++;
679 	} while (is_id_char(*src));
680 	dst.append(get_variable(buffer));
681 }
682 
683 const string
684 config::expand_string(const char *src, const char *prepend, const char *append)
685 {
686 	const char *var_at;
687 	string dst;
688 
689 	/*
690 	 * 128 bytes is enough for 2427 of 2438 expansions that happen
691 	 * while parsing config files, as tested on 2013-01-30.
692 	 */
693 	dst.reserve(128);
694 
695 	if (prepend != NULL)
696 		dst = prepend;
697 
698 	for (;;) {
699 		var_at = strchr(src, '$');
700 		if (var_at == NULL) {
701 			dst.append(src);
702 			break;
703 		}
704 		dst.append(src, var_at - src);
705 		src = var_at;
706 		expand_one(src, dst);
707 	}
708 
709 	if (append != NULL)
710 		dst.append(append);
711 
712 	return (dst);
713 }
714 
715 bool
716 config::chop_var(char *&buffer, char *&lhs, char *&rhs) const
717 {
718 	char *walker;
719 
720 	if (*buffer == '\0')
721 		return (false);
722 	walker = lhs = buffer;
723 	while (is_id_char(*walker))
724 		walker++;
725 	if (*walker != '=')
726 		return (false);
727 	walker++;		// skip =
728 	if (*walker == '"') {
729 		walker++;	// skip "
730 		rhs = walker;
731 		while (*walker && *walker != '"') {
732 			// Skip \" ... We leave it in the string and strip the \ later.
733 			// due to the super simplistic parser that we have here.
734 			if (*walker == '\\' && walker[1] == '"')
735 				walker++;
736 			walker++;
737 		}
738 		if (*walker != '"')
739 			return (false);
740 		rhs[-2] = '\0';
741 		*walker++ = '\0';
742 	} else {
743 		rhs = walker;
744 		while (*walker && !isspace(*walker))
745 			walker++;
746 		if (*walker != '\0')
747 			*walker++ = '\0';
748 		rhs[-1] = '\0';
749 	}
750 	while (isspace(*walker))
751 		walker++;
752 	buffer = walker;
753 	return (true);
754 }
755 
756 
757 char *
758 config::set_vars(char *buffer)
759 {
760 	char *lhs;
761 	char *rhs;
762 
763 	while (1) {
764 		if (!chop_var(buffer, lhs, rhs))
765 			break;
766 		set_variable(lhs, rhs);
767 	}
768 	return (buffer);
769 }
770 
771 void
772 config::find_and_execute(char type)
773 {
774 	vector<event_proc *> *l;
775 	vector<event_proc *>::const_iterator i;
776 	const char *s;
777 
778 	switch (type) {
779 	default:
780 		return;
781 	case notify:
782 		l = &_notify_list;
783 		s = "notify";
784 		break;
785 	case nomatch:
786 		l = &_nomatch_list;
787 		s = "nomatch";
788 		break;
789 	case attach:
790 		l = &_attach_list;
791 		s = "attach";
792 		break;
793 	case detach:
794 		l = &_detach_list;
795 		s = "detach";
796 		break;
797 	}
798 	devdlog(LOG_DEBUG, "Processing %s event\n", s);
799 	for (i = l->begin(); i != l->end(); ++i) {
800 		if ((*i)->matches(*this)) {
801 			(*i)->run(*this);
802 			break;
803 		}
804 	}
805 
806 }
807 
808 
809 static void
810 process_event(char *buffer)
811 {
812 	char type;
813 	char *sp;
814 	struct timeval tv;
815 	char *timestr;
816 
817 	sp = buffer + 1;
818 	devdlog(LOG_INFO, "Processing event '%s'\n", buffer);
819 	type = *buffer++;
820 	cfg.push_var_table();
821 	// $* is the entire line
822 	cfg.set_variable("*", buffer - 1);
823 	// $_ is the entire line without the initial character
824 	cfg.set_variable("_", buffer);
825 
826 	// Save the time this happened (as approximated by when we got
827 	// around to processing it).
828 	gettimeofday(&tv, NULL);
829 	asprintf(&timestr, "%jd.%06ld", (uintmax_t)tv.tv_sec, tv.tv_usec);
830 	cfg.set_variable("timestamp", timestr);
831 	free(timestr);
832 
833 	// Match doesn't have a device, and the format is a little
834 	// different, so handle it separately.
835 	switch (type) {
836 	case notify:
837 		//! (k=v)*
838 		sp = cfg.set_vars(sp);
839 		break;
840 	case nomatch:
841 		//? at location pnp-info on bus
842 		sp = strchr(sp, ' ');
843 		if (sp == NULL)
844 			return;	/* Can't happen? */
845 		*sp++ = '\0';
846 		while (isspace(*sp))
847 			sp++;
848 		if (strncmp(sp, "at ", 3) == 0)
849 			sp += 3;
850 		sp = cfg.set_vars(sp);
851 		while (isspace(*sp))
852 			sp++;
853 		if (strncmp(sp, "on ", 3) == 0)
854 			cfg.set_variable("bus", sp + 3);
855 		break;
856 	case attach:	/*FALLTHROUGH*/
857 	case detach:
858 		sp = strchr(sp, ' ');
859 		if (sp == NULL)
860 			return;	/* Can't happen? */
861 		*sp++ = '\0';
862 		cfg.set_variable("device-name", buffer);
863 		while (isspace(*sp))
864 			sp++;
865 		if (strncmp(sp, "at ", 3) == 0)
866 			sp += 3;
867 		sp = cfg.set_vars(sp);
868 		while (isspace(*sp))
869 			sp++;
870 		if (strncmp(sp, "on ", 3) == 0)
871 			cfg.set_variable("bus", sp + 3);
872 		break;
873 	}
874 
875 	cfg.find_and_execute(type);
876 	cfg.pop_var_table();
877 }
878 
879 int
880 create_socket(const char *name, int socktype)
881 {
882 	int fd, slen;
883 	struct sockaddr_un sun;
884 
885 	if ((fd = socket(PF_LOCAL, socktype, 0)) < 0)
886 		err(1, "socket");
887 	bzero(&sun, sizeof(sun));
888 	sun.sun_family = AF_UNIX;
889 	strlcpy(sun.sun_path, name, sizeof(sun.sun_path));
890 	slen = SUN_LEN(&sun);
891 	unlink(name);
892 	if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
893 	    	err(1, "fcntl");
894 	if (::bind(fd, (struct sockaddr *) & sun, slen) < 0)
895 		err(1, "bind");
896 	listen(fd, 4);
897 	if (chown(name, 0, 0))	/* XXX - root.wheel */
898 		err(1, "chown");
899 	if (chmod(name, 0666))
900 		err(1, "chmod");
901 	return (fd);
902 }
903 
904 static unsigned int max_clients = 10;	/* Default, can be overridden on cmdline. */
905 static unsigned int num_clients;
906 
907 static list<client_t> clients;
908 
909 void
910 notify_clients(const char *data, int len)
911 {
912 	list<client_t>::iterator i;
913 
914 	/*
915 	 * Deliver the data to all clients.  Throw clients overboard at the
916 	 * first sign of trouble.  This reaps clients who've died or closed
917 	 * their sockets, and also clients who are alive but failing to keep up
918 	 * (or who are maliciously not reading, to consume buffer space in
919 	 * kernel memory or tie up the limited number of available connections).
920 	 */
921 	for (i = clients.begin(); i != clients.end(); ) {
922 		int flags;
923 		if (i->socktype == SOCK_SEQPACKET)
924 			flags = MSG_EOR;
925 		else
926 			flags = 0;
927 
928 		if (send(i->fd, data, len, flags) != len) {
929 			--num_clients;
930 			close(i->fd);
931 			i = clients.erase(i);
932 			devdlog(LOG_WARNING, "notify_clients: send() failed; "
933 			    "dropping unresponsive client\n");
934 		} else
935 			++i;
936 	}
937 }
938 
939 void
940 check_clients(void)
941 {
942 	int s;
943 	struct pollfd pfd;
944 	list<client_t>::iterator i;
945 
946 	/*
947 	 * Check all existing clients to see if any of them have disappeared.
948 	 * Normally we reap clients when we get an error trying to send them an
949 	 * event.  This check eliminates the problem of an ever-growing list of
950 	 * zombie clients because we're never writing to them on a system
951 	 * without frequent device-change activity.
952 	 */
953 	pfd.events = 0;
954 	for (i = clients.begin(); i != clients.end(); ) {
955 		pfd.fd = i->fd;
956 		s = poll(&pfd, 1, 0);
957 		if ((s < 0 && s != EINTR ) ||
958 		    (s > 0 && (pfd.revents & POLLHUP))) {
959 			--num_clients;
960 			close(i->fd);
961 			i = clients.erase(i);
962 			devdlog(LOG_NOTICE, "check_clients:  "
963 			    "dropping disconnected client\n");
964 		} else
965 			++i;
966 	}
967 }
968 
969 void
970 new_client(int fd, int socktype)
971 {
972 	client_t s;
973 	int sndbuf_size;
974 
975 	/*
976 	 * First go reap any zombie clients, then accept the connection, and
977 	 * shut down the read side to stop clients from consuming kernel memory
978 	 * by sending large buffers full of data we'll never read.
979 	 */
980 	check_clients();
981 	s.socktype = socktype;
982 	s.fd = accept(fd, NULL, NULL);
983 	if (s.fd != -1) {
984 		sndbuf_size = CLIENT_BUFSIZE;
985 		if (setsockopt(s.fd, SOL_SOCKET, SO_SNDBUF, &sndbuf_size,
986 		    sizeof(sndbuf_size)))
987 			err(1, "setsockopt");
988 		shutdown(s.fd, SHUT_RD);
989 		clients.push_back(s);
990 		++num_clients;
991 	} else
992 		err(1, "accept");
993 }
994 
995 static void
996 event_loop(void)
997 {
998 	int rv;
999 	int fd;
1000 	char buffer[DEVCTL_MAXBUF];
1001 	int once = 0;
1002 	int stream_fd, seqpacket_fd, max_fd;
1003 	int accepting;
1004 	timeval tv;
1005 	fd_set fds;
1006 
1007 	fd = open(PATH_DEVCTL, O_RDONLY | O_CLOEXEC);
1008 	if (fd == -1)
1009 		err(1, "Can't open devctl device %s", PATH_DEVCTL);
1010 	stream_fd = create_socket(STREAMPIPE, SOCK_STREAM);
1011 	seqpacket_fd = create_socket(SEQPACKETPIPE, SOCK_SEQPACKET);
1012 	accepting = 1;
1013 	max_fd = max(fd, max(stream_fd, seqpacket_fd)) + 1;
1014 	while (!romeo_must_die) {
1015 		if (!once && !no_daemon && !daemonize_quick) {
1016 			// Check to see if we have any events pending.
1017 			tv.tv_sec = 0;
1018 			tv.tv_usec = 0;
1019 			FD_ZERO(&fds);
1020 			FD_SET(fd, &fds);
1021 			rv = select(fd + 1, &fds, NULL, NULL, &tv);
1022 			// No events -> we've processed all pending events
1023 			if (rv == 0) {
1024 				devdlog(LOG_DEBUG, "Calling daemon\n");
1025 				cfg.remove_pidfile();
1026 				cfg.open_pidfile();
1027 				daemon(0, 0);
1028 				cfg.write_pidfile();
1029 				once++;
1030 			}
1031 		}
1032 		/*
1033 		 * When we've already got the max number of clients, stop
1034 		 * accepting new connections (don't put the listening sockets in
1035 		 * the set), shrink the accept() queue to reject connections
1036 		 * quickly, and poll the existing clients more often, so that we
1037 		 * notice more quickly when any of them disappear to free up
1038 		 * client slots.
1039 		 */
1040 		FD_ZERO(&fds);
1041 		FD_SET(fd, &fds);
1042 		if (num_clients < max_clients) {
1043 			if (!accepting) {
1044 				listen(stream_fd, max_clients);
1045 				listen(seqpacket_fd, max_clients);
1046 				accepting = 1;
1047 			}
1048 			FD_SET(stream_fd, &fds);
1049 			FD_SET(seqpacket_fd, &fds);
1050 			tv.tv_sec = 60;
1051 			tv.tv_usec = 0;
1052 		} else {
1053 			if (accepting) {
1054 				listen(stream_fd, 0);
1055 				listen(seqpacket_fd, 0);
1056 				accepting = 0;
1057 			}
1058 			tv.tv_sec = 2;
1059 			tv.tv_usec = 0;
1060 		}
1061 		rv = select(max_fd, &fds, NULL, NULL, &tv);
1062 		if (got_siginfo) {
1063 			devdlog(LOG_NOTICE, "Events received so far=%u\n",
1064 			    total_events);
1065 			got_siginfo = 0;
1066 		}
1067 		if (rv == -1) {
1068 			if (errno == EINTR)
1069 				continue;
1070 			err(1, "select");
1071 		} else if (rv == 0)
1072 			check_clients();
1073 		if (FD_ISSET(fd, &fds)) {
1074 			rv = read(fd, buffer, sizeof(buffer) - 1);
1075 			if (rv > 0) {
1076 				total_events++;
1077 				if (rv == sizeof(buffer) - 1) {
1078 					devdlog(LOG_WARNING, "Warning: "
1079 					    "available event data exceeded "
1080 					    "buffer space\n");
1081 				}
1082 				notify_clients(buffer, rv);
1083 				buffer[rv] = '\0';
1084 				while (buffer[--rv] == '\n')
1085 					buffer[rv] = '\0';
1086 				try {
1087 					process_event(buffer);
1088 				}
1089 				catch (const std::length_error& e) {
1090 					devdlog(LOG_ERR, "Dropping event %s "
1091 					    "due to low memory", buffer);
1092 				}
1093 			} else if (rv < 0) {
1094 				if (errno != EINTR)
1095 					break;
1096 			} else {
1097 				/* EOF */
1098 				break;
1099 			}
1100 		}
1101 		if (FD_ISSET(stream_fd, &fds))
1102 			new_client(stream_fd, SOCK_STREAM);
1103 		/*
1104 		 * Aside from the socket type, both sockets use the same
1105 		 * protocol, so we can process clients the same way.
1106 		 */
1107 		if (FD_ISSET(seqpacket_fd, &fds))
1108 			new_client(seqpacket_fd, SOCK_SEQPACKET);
1109 	}
1110 	cfg.remove_pidfile();
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