xref: /freebsd-14.2/sbin/devd/devd.cc (revision 0285e9b1)
13054f218SWarner Losh /*-
2b8f92ce4SWarner Losh  * Copyright (c) 2002-2010 M. Warner Losh.
33054f218SWarner Losh  * All rights reserved.
43054f218SWarner Losh  *
53054f218SWarner Losh  * Redistribution and use in source and binary forms, with or without
63054f218SWarner Losh  * modification, are permitted provided that the following conditions
73054f218SWarner Losh  * are met:
83054f218SWarner Losh  * 1. Redistributions of source code must retain the above copyright
93054f218SWarner Losh  *    notice, this list of conditions and the following disclaimer.
103054f218SWarner Losh  * 2. Redistributions in binary form must reproduce the above copyright
113054f218SWarner Losh  *    notice, this list of conditions and the following disclaimer in the
123054f218SWarner Losh  *    documentation and/or other materials provided with the distribution.
133054f218SWarner Losh  *
143054f218SWarner Losh  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
153054f218SWarner Losh  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
163054f218SWarner Losh  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
173054f218SWarner Losh  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
183054f218SWarner Losh  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
193054f218SWarner Losh  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
203054f218SWarner Losh  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
213054f218SWarner Losh  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
223054f218SWarner Losh  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
233054f218SWarner Losh  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
243054f218SWarner Losh  * SUCH DAMAGE.
25b8f92ce4SWarner Losh  *
26b8f92ce4SWarner Losh  * my_system is a variation on lib/libc/stdlib/system.c:
27b8f92ce4SWarner Losh  *
28b8f92ce4SWarner Losh  * Copyright (c) 1988, 1993
29b8f92ce4SWarner Losh  *	The Regents of the University of California.  All rights reserved.
30b8f92ce4SWarner Losh  *
31b8f92ce4SWarner Losh  * Redistribution and use in source and binary forms, with or without
32b8f92ce4SWarner Losh  * modification, are permitted provided that the following conditions
33b8f92ce4SWarner Losh  * are met:
34b8f92ce4SWarner Losh  * 1. Redistributions of source code must retain the above copyright
35b8f92ce4SWarner Losh  *    notice, this list of conditions and the following disclaimer.
36b8f92ce4SWarner Losh  * 2. Redistributions in binary form must reproduce the above copyright
37b8f92ce4SWarner Losh  *    notice, this list of conditions and the following disclaimer in the
38b8f92ce4SWarner Losh  *    documentation and/or other materials provided with the distribution.
39b8f92ce4SWarner Losh  * 4. Neither the name of the University nor the names of its contributors
40b8f92ce4SWarner Losh  *    may be used to endorse or promote products derived from this software
41b8f92ce4SWarner Losh  *    without specific prior written permission.
42b8f92ce4SWarner Losh  *
43b8f92ce4SWarner Losh  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
44b8f92ce4SWarner Losh  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45b8f92ce4SWarner Losh  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46b8f92ce4SWarner Losh  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
47b8f92ce4SWarner Losh  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
48b8f92ce4SWarner Losh  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
49b8f92ce4SWarner Losh  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50b8f92ce4SWarner Losh  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
51b8f92ce4SWarner Losh  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
52b8f92ce4SWarner Losh  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53b8f92ce4SWarner Losh  * SUCH DAMAGE.
543054f218SWarner Losh  */
553054f218SWarner Losh 
563054f218SWarner Losh /*
573054f218SWarner Losh  * DEVD control daemon.
583054f218SWarner Losh  */
593054f218SWarner Losh 
603054f218SWarner Losh // TODO list:
613054f218SWarner Losh //	o devd.conf and devd man pages need a lot of help:
62251bedd1SWarner Losh //	  - devd needs to document the unix domain socket
633054f218SWarner Losh //	  - devd.conf needs more details on the supported statements.
643054f218SWarner Losh 
653054f218SWarner Losh #include <sys/cdefs.h>
663054f218SWarner Losh __FBSDID("$FreeBSD$");
673054f218SWarner Losh 
683054f218SWarner Losh #include <sys/param.h>
69251bedd1SWarner Losh #include <sys/socket.h>
70251bedd1SWarner Losh #include <sys/stat.h>
719c180898SWarner Losh #include <sys/sysctl.h>
72251bedd1SWarner Losh #include <sys/types.h>
73b8f92ce4SWarner Losh #include <sys/wait.h>
74251bedd1SWarner Losh #include <sys/un.h>
753054f218SWarner Losh 
76d005340fSEitan Adler #include <cctype>
77d005340fSEitan Adler #include <cerrno>
78d005340fSEitan Adler #include <cstdlib>
79d005340fSEitan Adler #include <cstdio>
80d005340fSEitan Adler #include <csignal>
81d005340fSEitan Adler #include <cstring>
82d005340fSEitan Adler 
833054f218SWarner Losh #include <dirent.h>
843054f218SWarner Losh #include <err.h>
853054f218SWarner Losh #include <fcntl.h>
861a0cc6b1SPawel Jakub Dawidek #include <libutil.h>
87b8f92ce4SWarner Losh #include <paths.h>
88e1334f93SIan Lepore #include <poll.h>
895102ef84SWarner Losh #include <regex.h>
906d1014a3SAlan Somers #include <syslog.h>
913054f218SWarner Losh #include <unistd.h>
923054f218SWarner Losh 
938b823408SWarner Losh #include <algorithm>
943054f218SWarner Losh #include <map>
953054f218SWarner Losh #include <string>
96251bedd1SWarner Losh #include <list>
973054f218SWarner Losh #include <vector>
983054f218SWarner Losh 
996aeeca8eSWarner Losh #include "devd.h"		/* C compatible definitions */
1006aeeca8eSWarner Losh #include "devd.hh"		/* C++ class definitions */
1013054f218SWarner Losh 
102251bedd1SWarner Losh #define PIPE "/var/run/devd.pipe"
1033054f218SWarner Losh #define CF "/etc/devd.conf"
1049c180898SWarner Losh #define SYSCTL "hw.bus.devctl_disable"
1053054f218SWarner Losh 
1063054f218SWarner Losh using namespace std;
1073054f218SWarner Losh 
1083054f218SWarner Losh extern FILE *yyin;
1093054f218SWarner Losh extern int lineno;
1103054f218SWarner Losh 
111842ccec5SWarner Losh static const char notify = '!';
1128b823408SWarner Losh static const char nomatch = '?';
1138b823408SWarner Losh static const char attach = '+';
1148b823408SWarner Losh static const char detach = '-';
1158b823408SWarner Losh 
1161a0cc6b1SPawel Jakub Dawidek static struct pidfh *pfh;
1171a0cc6b1SPawel Jakub Dawidek 
1183054f218SWarner Losh int dflag;
119812f53a7SWarner Losh int nflag;
120be685e01SAlan Somers static unsigned total_events = 0;
121be685e01SAlan Somers static volatile sig_atomic_t got_siginfo = 0;
122fcdcaa88SEitan Adler static volatile sig_atomic_t romeo_must_die = 0;
1233054f218SWarner Losh 
1248334958aSJoseph Koshy static const char *configfile = CF;
1258334958aSJoseph Koshy 
1266d1014a3SAlan Somers static void devdlog(int priority, const char* message, ...);
1273054f218SWarner Losh static void event_loop(void);
1283054f218SWarner Losh static void usage(void);
1293054f218SWarner Losh 
1308b823408SWarner Losh template <class T> void
1318b823408SWarner Losh delete_and_clear(vector<T *> &v)
1328b823408SWarner Losh {
1338b823408SWarner Losh 	typename vector<T *>::const_iterator i;
1343054f218SWarner Losh 
135edee691dSEitan Adler 	for (i = v.begin(); i != v.end(); ++i)
1368b823408SWarner Losh 		delete *i;
1378b823408SWarner Losh 	v.clear();
1388b823408SWarner Losh }
1398b823408SWarner Losh 
1403054f218SWarner Losh config cfg;
1413054f218SWarner Losh 
1423054f218SWarner Losh event_proc::event_proc() : _prio(-1)
1433054f218SWarner Losh {
1445dfc0f6cSIan Lepore 	_epsvec.reserve(4);
1453054f218SWarner Losh }
1463054f218SWarner Losh 
1473054f218SWarner Losh event_proc::~event_proc()
1483054f218SWarner Losh {
14913f8bb71SAlexander Nedotsukov 	delete_and_clear(_epsvec);
1503054f218SWarner Losh }
1513054f218SWarner Losh 
1523054f218SWarner Losh void
1533054f218SWarner Losh event_proc::add(eps *eps)
1543054f218SWarner Losh {
1553054f218SWarner Losh 	_epsvec.push_back(eps);
1563054f218SWarner Losh }
1573054f218SWarner Losh 
1583054f218SWarner Losh bool
159ef370346SEitan Adler event_proc::matches(config &c) const
1603054f218SWarner Losh {
1613054f218SWarner Losh 	vector<eps *>::const_iterator i;
1623054f218SWarner Losh 
163edee691dSEitan Adler 	for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
1643054f218SWarner Losh 		if (!(*i)->do_match(c))
1653054f218SWarner Losh 			return (false);
1663054f218SWarner Losh 	return (true);
1673054f218SWarner Losh }
1683054f218SWarner Losh 
1693054f218SWarner Losh bool
170ef370346SEitan Adler event_proc::run(config &c) const
1713054f218SWarner Losh {
1723054f218SWarner Losh 	vector<eps *>::const_iterator i;
1733054f218SWarner Losh 
174edee691dSEitan Adler 	for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
1753054f218SWarner Losh 		if (!(*i)->do_action(c))
1763054f218SWarner Losh 			return (false);
1773054f218SWarner Losh 	return (true);
1783054f218SWarner Losh }
1793054f218SWarner Losh 
1803054f218SWarner Losh action::action(const char *cmd)
1813054f218SWarner Losh 	: _cmd(cmd)
1823054f218SWarner Losh {
1833054f218SWarner Losh 	// nothing
1843054f218SWarner Losh }
1853054f218SWarner Losh 
1863054f218SWarner Losh action::~action()
1873054f218SWarner Losh {
1883054f218SWarner Losh 	// nothing
1893054f218SWarner Losh }
1903054f218SWarner Losh 
191b8f92ce4SWarner Losh static int
192b8f92ce4SWarner Losh my_system(const char *command)
193b8f92ce4SWarner Losh {
194b8f92ce4SWarner Losh 	pid_t pid, savedpid;
195b8f92ce4SWarner Losh 	int pstat;
196b8f92ce4SWarner Losh 	struct sigaction ign, intact, quitact;
197b8f92ce4SWarner Losh 	sigset_t newsigblock, oldsigblock;
198b8f92ce4SWarner Losh 
199b8f92ce4SWarner Losh 	if (!command)		/* just checking... */
200b8f92ce4SWarner Losh 		return (1);
201b8f92ce4SWarner Losh 
202b8f92ce4SWarner Losh 	/*
203b8f92ce4SWarner Losh 	 * Ignore SIGINT and SIGQUIT, block SIGCHLD. Remember to save
204b8f92ce4SWarner Losh 	 * existing signal dispositions.
205b8f92ce4SWarner Losh 	 */
206b8f92ce4SWarner Losh 	ign.sa_handler = SIG_IGN;
207b8f92ce4SWarner Losh 	::sigemptyset(&ign.sa_mask);
208b8f92ce4SWarner Losh 	ign.sa_flags = 0;
209b8f92ce4SWarner Losh 	::sigaction(SIGINT, &ign, &intact);
210b8f92ce4SWarner Losh 	::sigaction(SIGQUIT, &ign, &quitact);
211b8f92ce4SWarner Losh 	::sigemptyset(&newsigblock);
212b8f92ce4SWarner Losh 	::sigaddset(&newsigblock, SIGCHLD);
213b8f92ce4SWarner Losh 	::sigprocmask(SIG_BLOCK, &newsigblock, &oldsigblock);
214b8f92ce4SWarner Losh 	switch (pid = ::fork()) {
215b8f92ce4SWarner Losh 	case -1:			/* error */
216b8f92ce4SWarner Losh 		break;
217b8f92ce4SWarner Losh 	case 0:				/* child */
218b8f92ce4SWarner Losh 		/*
219b8f92ce4SWarner Losh 		 * Restore original signal dispositions and exec the command.
220b8f92ce4SWarner Losh 		 */
221b8f92ce4SWarner Losh 		::sigaction(SIGINT, &intact, NULL);
222b8f92ce4SWarner Losh 		::sigaction(SIGQUIT,  &quitact, NULL);
223b8f92ce4SWarner Losh 		::sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
224b8f92ce4SWarner Losh 		/*
225b8f92ce4SWarner Losh 		 * Close the PID file, and all other open descriptors.
226b8f92ce4SWarner Losh 		 * Inherit std{in,out,err} only.
227b8f92ce4SWarner Losh 		 */
228b8f92ce4SWarner Losh 		cfg.close_pidfile();
229b8f92ce4SWarner Losh 		::closefrom(3);
230b8f92ce4SWarner Losh 		::execl(_PATH_BSHELL, "sh", "-c", command, (char *)NULL);
231b8f92ce4SWarner Losh 		::_exit(127);
232b8f92ce4SWarner Losh 	default:			/* parent */
233b8f92ce4SWarner Losh 		savedpid = pid;
234b8f92ce4SWarner Losh 		do {
235b8f92ce4SWarner Losh 			pid = ::wait4(savedpid, &pstat, 0, (struct rusage *)0);
236b8f92ce4SWarner Losh 		} while (pid == -1 && errno == EINTR);
237b8f92ce4SWarner Losh 		break;
238b8f92ce4SWarner Losh 	}
239b8f92ce4SWarner Losh 	::sigaction(SIGINT, &intact, NULL);
240b8f92ce4SWarner Losh 	::sigaction(SIGQUIT,  &quitact, NULL);
241b8f92ce4SWarner Losh 	::sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
242b8f92ce4SWarner Losh 	return (pid == -1 ? -1 : pstat);
243b8f92ce4SWarner Losh }
244b8f92ce4SWarner Losh 
2453054f218SWarner Losh bool
2465102ef84SWarner Losh action::do_action(config &c)
2473054f218SWarner Losh {
2485dfc0f6cSIan Lepore 	string s = c.expand_string(_cmd.c_str());
2496d1014a3SAlan Somers 	devdlog(LOG_NOTICE, "Executing '%s'\n", s.c_str());
250b8f92ce4SWarner Losh 	my_system(s.c_str());
2513054f218SWarner Losh 	return (true);
2523054f218SWarner Losh }
2533054f218SWarner Losh 
2545dfc0f6cSIan Lepore match::match(config &c, const char *var, const char *re) :
2555dfc0f6cSIan Lepore 	_inv(re[0] == '!'),
2565dfc0f6cSIan Lepore 	_var(var),
2575dfc0f6cSIan Lepore 	_re(c.expand_string(_inv ? re + 1 : re, "^", "$"))
2583054f218SWarner Losh {
2599cb4a7bdSWarner Losh 	regcomp(&_regex, _re.c_str(), REG_EXTENDED | REG_NOSUB | REG_ICASE);
2603054f218SWarner Losh }
2613054f218SWarner Losh 
2623054f218SWarner Losh match::~match()
2633054f218SWarner Losh {
2645102ef84SWarner Losh 	regfree(&_regex);
2653054f218SWarner Losh }
2663054f218SWarner Losh 
2673054f218SWarner Losh bool
2685102ef84SWarner Losh match::do_match(config &c)
2693054f218SWarner Losh {
2705bf08422SUlf Lilleengen 	const string &value = c.get_variable(_var);
2715102ef84SWarner Losh 	bool retval;
2725102ef84SWarner Losh 
2736d1014a3SAlan Somers 	/*
2746d1014a3SAlan Somers 	 * This function gets called WAY too often to justify calling syslog()
2756d1014a3SAlan Somers 	 * each time, even at LOG_DEBUG.  Because if syslogd isn't running, it
2766d1014a3SAlan Somers 	 * can consume excessive amounts of systime inside of connect().  Only
2776d1014a3SAlan Somers 	 * log when we're in -d mode.
2786d1014a3SAlan Somers 	 */
2796d1014a3SAlan Somers 	if (dflag) {
2806d1014a3SAlan Somers 		devdlog(LOG_DEBUG, "Testing %s=%s against %s, invert=%d\n",
2810321b694SHiroki Sato 		    _var.c_str(), value.c_str(), _re.c_str(), _inv);
2826d1014a3SAlan Somers 	}
2838b823408SWarner Losh 
2845102ef84SWarner Losh 	retval = (regexec(&_regex, value.c_str(), 0, NULL, 0) == 0);
2850321b694SHiroki Sato 	if (_inv == 1)
2860321b694SHiroki Sato 		retval = (retval == 0) ? 1 : 0;
2870321b694SHiroki Sato 
288*0285e9b1SAlan Somers 	return (retval);
2893054f218SWarner Losh }
2903054f218SWarner Losh 
291cd70782bSWarner Losh #include <sys/sockio.h>
292cd70782bSWarner Losh #include <net/if.h>
293cd70782bSWarner Losh #include <net/if_media.h>
294cd70782bSWarner Losh 
29594d2d4ebSBrooks Davis media::media(config &, const char *var, const char *type)
296cd70782bSWarner Losh 	: _var(var), _type(-1)
297cd70782bSWarner Losh {
298cd70782bSWarner Losh 	static struct ifmedia_description media_types[] = {
299cd70782bSWarner Losh 		{ IFM_ETHER,		"Ethernet" },
300cd70782bSWarner Losh 		{ IFM_TOKEN,		"Tokenring" },
301cd70782bSWarner Losh 		{ IFM_FDDI,		"FDDI" },
302cd70782bSWarner Losh 		{ IFM_IEEE80211,	"802.11" },
303cd70782bSWarner Losh 		{ IFM_ATM,		"ATM" },
304cd70782bSWarner Losh 		{ -1,			"unknown" },
305cd70782bSWarner Losh 		{ 0, NULL },
306cd70782bSWarner Losh 	};
307edee691dSEitan Adler 	for (int i = 0; media_types[i].ifmt_string != NULL; ++i)
308cd70782bSWarner Losh 		if (strcasecmp(type, media_types[i].ifmt_string) == 0) {
309cd70782bSWarner Losh 			_type = media_types[i].ifmt_word;
310cd70782bSWarner Losh 			break;
311cd70782bSWarner Losh 		}
312cd70782bSWarner Losh }
313cd70782bSWarner Losh 
314cd70782bSWarner Losh media::~media()
315cd70782bSWarner Losh {
316cd70782bSWarner Losh }
317cd70782bSWarner Losh 
318cd70782bSWarner Losh bool
319cd70782bSWarner Losh media::do_match(config &c)
320cd70782bSWarner Losh {
32109c47e76SWarner Losh 	string value;
322cd70782bSWarner Losh 	struct ifmediareq ifmr;
323cd70782bSWarner Losh 	bool retval;
324cd70782bSWarner Losh 	int s;
325cd70782bSWarner Losh 
32609c47e76SWarner Losh 	// Since we can be called from both a device attach/detach
32709c47e76SWarner Losh 	// context where device-name is defined and what we want,
32809c47e76SWarner Losh 	// as well as from a link status context, where subsystem is
32909c47e76SWarner Losh 	// the name of interest, first try device-name and fall back
33009c47e76SWarner Losh 	// to subsystem if none exists.
33109c47e76SWarner Losh 	value = c.get_variable("device-name");
332a6393aa1SEitan Adler 	if (value.empty())
333de02eec8SWarner Losh 		value = c.get_variable("subsystem");
3346d1014a3SAlan Somers 	devdlog(LOG_DEBUG, "Testing media type of %s against 0x%x\n",
335cd70782bSWarner Losh 		    value.c_str(), _type);
336cd70782bSWarner Losh 
337cd70782bSWarner Losh 	retval = false;
338cd70782bSWarner Losh 
339cd70782bSWarner Losh 	s = socket(PF_INET, SOCK_DGRAM, 0);
340cd70782bSWarner Losh 	if (s >= 0) {
341cd70782bSWarner Losh 		memset(&ifmr, 0, sizeof(ifmr));
342cd70782bSWarner Losh 		strncpy(ifmr.ifm_name, value.c_str(), sizeof(ifmr.ifm_name));
343cd70782bSWarner Losh 
344cd70782bSWarner Losh 		if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0 &&
345cd70782bSWarner Losh 		    ifmr.ifm_status & IFM_AVALID) {
3466d1014a3SAlan Somers 			devdlog(LOG_DEBUG, "%s has media type 0x%x\n",
347cd70782bSWarner Losh 				    value.c_str(), IFM_TYPE(ifmr.ifm_active));
348cd70782bSWarner Losh 			retval = (IFM_TYPE(ifmr.ifm_active) == _type);
349cd70782bSWarner Losh 		} else if (_type == -1) {
3506d1014a3SAlan Somers 			devdlog(LOG_DEBUG, "%s has unknown media type\n",
351cd70782bSWarner Losh 				    value.c_str());
352cd70782bSWarner Losh 			retval = true;
353cd70782bSWarner Losh 		}
354cd70782bSWarner Losh 		close(s);
355cd70782bSWarner Losh 	}
356cd70782bSWarner Losh 
357*0285e9b1SAlan Somers 	return (retval);
358cd70782bSWarner Losh }
359cd70782bSWarner Losh 
3603054f218SWarner Losh const string var_list::bogus = "_$_$_$_$_B_O_G_U_S_$_$_$_$_";
3613054f218SWarner Losh const string var_list::nothing = "";
3623054f218SWarner Losh 
3633054f218SWarner Losh const string &
3643054f218SWarner Losh var_list::get_variable(const string &var) const
3653054f218SWarner Losh {
3663054f218SWarner Losh 	map<string, string>::const_iterator i;
3673054f218SWarner Losh 
3683054f218SWarner Losh 	i = _vars.find(var);
3693054f218SWarner Losh 	if (i == _vars.end())
3708b823408SWarner Losh 		return (var_list::bogus);
3713054f218SWarner Losh 	return (i->second);
3723054f218SWarner Losh }
3733054f218SWarner Losh 
3743054f218SWarner Losh bool
3753054f218SWarner Losh var_list::is_set(const string &var) const
3763054f218SWarner Losh {
3773054f218SWarner Losh 	return (_vars.find(var) != _vars.end());
3783054f218SWarner Losh }
3793054f218SWarner Losh 
3803054f218SWarner Losh void
3813054f218SWarner Losh var_list::set_variable(const string &var, const string &val)
3823054f218SWarner Losh {
3836d1014a3SAlan Somers 	/*
3846d1014a3SAlan Somers 	 * This function gets called WAY too often to justify calling syslog()
3856d1014a3SAlan Somers 	 * each time, even at LOG_DEBUG.  Because if syslogd isn't running, it
3866d1014a3SAlan Somers 	 * can consume excessive amounts of systime inside of connect().  Only
3876d1014a3SAlan Somers 	 * log when we're in -d mode.
3886d1014a3SAlan Somers 	 */
3896d1014a3SAlan Somers 	if (dflag)
3906d1014a3SAlan Somers 		devdlog(LOG_DEBUG, "setting %s=%s\n", var.c_str(), val.c_str());
3913054f218SWarner Losh 	_vars[var] = val;
3923054f218SWarner Losh }
3933054f218SWarner Losh 
3943054f218SWarner Losh void
3953054f218SWarner Losh config::reset(void)
3963054f218SWarner Losh {
3973054f218SWarner Losh 	_dir_list.clear();
3988b823408SWarner Losh 	delete_and_clear(_var_list_table);
3998b823408SWarner Losh 	delete_and_clear(_attach_list);
4008b823408SWarner Losh 	delete_and_clear(_detach_list);
4018b823408SWarner Losh 	delete_and_clear(_nomatch_list);
402842ccec5SWarner Losh 	delete_and_clear(_notify_list);
4033054f218SWarner Losh }
4043054f218SWarner Losh 
4053054f218SWarner Losh void
4063054f218SWarner Losh config::parse_one_file(const char *fn)
4073054f218SWarner Losh {
4086d1014a3SAlan Somers 	devdlog(LOG_DEBUG, "Parsing %s\n", fn);
4093054f218SWarner Losh 	yyin = fopen(fn, "r");
4103054f218SWarner Losh 	if (yyin == NULL)
4113054f218SWarner Losh 		err(1, "Cannot open config file %s", fn);
4124a3050fcSMaxim Konovalov 	lineno = 1;
4133054f218SWarner Losh 	if (yyparse() != 0)
4143054f218SWarner Losh 		errx(1, "Cannot parse %s at line %d", fn, lineno);
4153054f218SWarner Losh 	fclose(yyin);
4163054f218SWarner Losh }
4173054f218SWarner Losh 
4183054f218SWarner Losh void
4193054f218SWarner Losh config::parse_files_in_dir(const char *dirname)
4203054f218SWarner Losh {
4213054f218SWarner Losh 	DIR *dirp;
4223054f218SWarner Losh 	struct dirent *dp;
4233054f218SWarner Losh 	char path[PATH_MAX];
4243054f218SWarner Losh 
4256d1014a3SAlan Somers 	devdlog(LOG_DEBUG, "Parsing files in %s\n", dirname);
4263054f218SWarner Losh 	dirp = opendir(dirname);
4273054f218SWarner Losh 	if (dirp == NULL)
4283054f218SWarner Losh 		return;
4293054f218SWarner Losh 	readdir(dirp);		/* Skip . */
4303054f218SWarner Losh 	readdir(dirp);		/* Skip .. */
4313054f218SWarner Losh 	while ((dp = readdir(dirp)) != NULL) {
4323054f218SWarner Losh 		if (strcmp(dp->d_name + dp->d_namlen - 5, ".conf") == 0) {
4333054f218SWarner Losh 			snprintf(path, sizeof(path), "%s/%s",
4343054f218SWarner Losh 			    dirname, dp->d_name);
4353054f218SWarner Losh 			parse_one_file(path);
4363054f218SWarner Losh 		}
4373054f218SWarner Losh 	}
4385983e891SKevin Lo 	closedir(dirp);
4393054f218SWarner Losh }
4403054f218SWarner Losh 
4418b823408SWarner Losh class epv_greater {
4428b823408SWarner Losh public:
443ef370346SEitan Adler 	int operator()(event_proc *const&l1, event_proc *const&l2) const
4448b823408SWarner Losh 	{
4458b823408SWarner Losh 		return (l1->get_priority() > l2->get_priority());
4468b823408SWarner Losh 	}
4478b823408SWarner Losh };
4488b823408SWarner Losh 
4498b823408SWarner Losh void
4508b823408SWarner Losh config::sort_vector(vector<event_proc *> &v)
4518b823408SWarner Losh {
4520c04d185SDimitry Andric 	stable_sort(v.begin(), v.end(), epv_greater());
4538b823408SWarner Losh }
4548b823408SWarner Losh 
4553054f218SWarner Losh void
4563054f218SWarner Losh config::parse(void)
4573054f218SWarner Losh {
4583054f218SWarner Losh 	vector<string>::const_iterator i;
4593054f218SWarner Losh 
4608334958aSJoseph Koshy 	parse_one_file(configfile);
461edee691dSEitan Adler 	for (i = _dir_list.begin(); i != _dir_list.end(); ++i)
4623054f218SWarner Losh 		parse_files_in_dir((*i).c_str());
4638b823408SWarner Losh 	sort_vector(_attach_list);
4648b823408SWarner Losh 	sort_vector(_detach_list);
4658b823408SWarner Losh 	sort_vector(_nomatch_list);
466842ccec5SWarner Losh 	sort_vector(_notify_list);
4673054f218SWarner Losh }
4683054f218SWarner Losh 
4693054f218SWarner Losh void
4701a0cc6b1SPawel Jakub Dawidek config::open_pidfile()
4713054f218SWarner Losh {
4721a0cc6b1SPawel Jakub Dawidek 	pid_t otherpid;
4733054f218SWarner Losh 
4745a3b1a3dSEitan Adler 	if (_pidfile.empty())
4753054f218SWarner Losh 		return;
4761a0cc6b1SPawel Jakub Dawidek 	pfh = pidfile_open(_pidfile.c_str(), 0600, &otherpid);
4771a0cc6b1SPawel Jakub Dawidek 	if (pfh == NULL) {
4781a0cc6b1SPawel Jakub Dawidek 		if (errno == EEXIST)
4791a0cc6b1SPawel Jakub Dawidek 			errx(1, "devd already running, pid: %d", (int)otherpid);
4801a0cc6b1SPawel Jakub Dawidek 		warn("cannot open pid file");
4811a0cc6b1SPawel Jakub Dawidek 	}
4821a0cc6b1SPawel Jakub Dawidek }
4831a0cc6b1SPawel Jakub Dawidek 
4841a0cc6b1SPawel Jakub Dawidek void
4851a0cc6b1SPawel Jakub Dawidek config::write_pidfile()
4861a0cc6b1SPawel Jakub Dawidek {
4871a0cc6b1SPawel Jakub Dawidek 
4881a0cc6b1SPawel Jakub Dawidek 	pidfile_write(pfh);
4891a0cc6b1SPawel Jakub Dawidek }
4901a0cc6b1SPawel Jakub Dawidek 
4911a0cc6b1SPawel Jakub Dawidek void
492b8f92ce4SWarner Losh config::close_pidfile()
493b8f92ce4SWarner Losh {
494b8f92ce4SWarner Losh 
495b8f92ce4SWarner Losh 	pidfile_close(pfh);
496b8f92ce4SWarner Losh }
497b8f92ce4SWarner Losh 
498b8f92ce4SWarner Losh void
4991a0cc6b1SPawel Jakub Dawidek config::remove_pidfile()
5001a0cc6b1SPawel Jakub Dawidek {
5011a0cc6b1SPawel Jakub Dawidek 
5021a0cc6b1SPawel Jakub Dawidek 	pidfile_remove(pfh);
5033054f218SWarner Losh }
5043054f218SWarner Losh 
5053054f218SWarner Losh void
5063054f218SWarner Losh config::add_attach(int prio, event_proc *p)
5073054f218SWarner Losh {
5083054f218SWarner Losh 	p->set_priority(prio);
5093054f218SWarner Losh 	_attach_list.push_back(p);
5103054f218SWarner Losh }
5113054f218SWarner Losh 
5123054f218SWarner Losh void
5133054f218SWarner Losh config::add_detach(int prio, event_proc *p)
5143054f218SWarner Losh {
5153054f218SWarner Losh 	p->set_priority(prio);
5163054f218SWarner Losh 	_detach_list.push_back(p);
5173054f218SWarner Losh }
5183054f218SWarner Losh 
5193054f218SWarner Losh void
5203054f218SWarner Losh config::add_directory(const char *dir)
5213054f218SWarner Losh {
5223054f218SWarner Losh 	_dir_list.push_back(string(dir));
5233054f218SWarner Losh }
5243054f218SWarner Losh 
5253054f218SWarner Losh void
5263054f218SWarner Losh config::add_nomatch(int prio, event_proc *p)
5273054f218SWarner Losh {
5283054f218SWarner Losh 	p->set_priority(prio);
5293054f218SWarner Losh 	_nomatch_list.push_back(p);
5303054f218SWarner Losh }
5313054f218SWarner Losh 
5323054f218SWarner Losh void
533842ccec5SWarner Losh config::add_notify(int prio, event_proc *p)
534842ccec5SWarner Losh {
535842ccec5SWarner Losh 	p->set_priority(prio);
536842ccec5SWarner Losh 	_notify_list.push_back(p);
537842ccec5SWarner Losh }
538842ccec5SWarner Losh 
539842ccec5SWarner Losh void
5403054f218SWarner Losh config::set_pidfile(const char *fn)
5413054f218SWarner Losh {
5425a3b1a3dSEitan Adler 	_pidfile = fn;
5433054f218SWarner Losh }
5443054f218SWarner Losh 
5453054f218SWarner Losh void
5463054f218SWarner Losh config::push_var_table()
5473054f218SWarner Losh {
5483054f218SWarner Losh 	var_list *vl;
5493054f218SWarner Losh 
5503054f218SWarner Losh 	vl = new var_list();
5513054f218SWarner Losh 	_var_list_table.push_back(vl);
5526d1014a3SAlan Somers 	devdlog(LOG_DEBUG, "Pushing table\n");
5533054f218SWarner Losh }
5543054f218SWarner Losh 
5553054f218SWarner Losh void
5563054f218SWarner Losh config::pop_var_table()
5573054f218SWarner Losh {
5583054f218SWarner Losh 	delete _var_list_table.back();
5593054f218SWarner Losh 	_var_list_table.pop_back();
5606d1014a3SAlan Somers 	devdlog(LOG_DEBUG, "Popping table\n");
5613054f218SWarner Losh }
5623054f218SWarner Losh 
5633054f218SWarner Losh void
5643054f218SWarner Losh config::set_variable(const char *var, const char *val)
5653054f218SWarner Losh {
5663054f218SWarner Losh 	_var_list_table.back()->set_variable(var, val);
5673054f218SWarner Losh }
5683054f218SWarner Losh 
5693054f218SWarner Losh const string &
5703054f218SWarner Losh config::get_variable(const string &var)
5713054f218SWarner Losh {
5723054f218SWarner Losh 	vector<var_list *>::reverse_iterator i;
5733054f218SWarner Losh 
574edee691dSEitan Adler 	for (i = _var_list_table.rbegin(); i != _var_list_table.rend(); ++i) {
5753054f218SWarner Losh 		if ((*i)->is_set(var))
5768b823408SWarner Losh 			return ((*i)->get_variable(var));
5773054f218SWarner Losh 	}
5783054f218SWarner Losh 	return (var_list::nothing);
5793054f218SWarner Losh }
5803054f218SWarner Losh 
5818b823408SWarner Losh bool
582ef370346SEitan Adler config::is_id_char(char ch) const
5838b823408SWarner Losh {
5848b823408SWarner Losh 	return (ch != '\0' && (isalpha(ch) || isdigit(ch) || ch == '_' ||
5858b823408SWarner Losh 	    ch == '-'));
5868b823408SWarner Losh }
5878b823408SWarner Losh 
5885102ef84SWarner Losh void
5896cabd675SWarner Losh config::expand_one(const char *&src, string &dst)
5903054f218SWarner Losh {
5915102ef84SWarner Losh 	int count;
5925bf08422SUlf Lilleengen 	string buffer;
5935102ef84SWarner Losh 
5948b823408SWarner Losh 	src++;
5955102ef84SWarner Losh 	// $$ -> $
5965102ef84SWarner Losh 	if (*src == '$') {
5977d9e9c60SEitan Adler 		dst += *src++;
5985102ef84SWarner Losh 		return;
5995102ef84SWarner Losh 	}
6005102ef84SWarner Losh 
6015102ef84SWarner Losh 	// $(foo) -> $(foo)
6028b823408SWarner Losh 	// Not sure if I want to support this or not, so for now we just pass
6038b823408SWarner Losh 	// it through.
6045102ef84SWarner Losh 	if (*src == '(') {
6057d9e9c60SEitan Adler 		dst += '$';
6065102ef84SWarner Losh 		count = 1;
6076cabd675SWarner Losh 		/* If the string ends before ) is matched , return. */
6086cabd675SWarner Losh 		while (count > 0 && *src) {
6095102ef84SWarner Losh 			if (*src == ')')
6105102ef84SWarner Losh 				count--;
6115102ef84SWarner Losh 			else if (*src == '(')
6125102ef84SWarner Losh 				count++;
6137d9e9c60SEitan Adler 			dst += *src++;
6145102ef84SWarner Losh 		}
6155102ef84SWarner Losh 		return;
6165102ef84SWarner Losh 	}
6175102ef84SWarner Losh 
6184cb9d1beSEitan Adler 	// $[^A-Za-z] -> $\1
6195102ef84SWarner Losh 	if (!isalpha(*src)) {
6207d9e9c60SEitan Adler 		dst += '$';
6217d9e9c60SEitan Adler 		dst += *src++;
6225102ef84SWarner Losh 		return;
6235102ef84SWarner Losh 	}
6245102ef84SWarner Losh 
6255102ef84SWarner Losh 	// $var -> replace with value
6266cabd675SWarner Losh 	do {
6277d9e9c60SEitan Adler 		buffer += *src++;
62866ff6821SWarner Losh 	} while (is_id_char(*src));
6295a3b1a3dSEitan Adler 	dst.append(get_variable(buffer));
6305102ef84SWarner Losh }
6315102ef84SWarner Losh 
6325102ef84SWarner Losh const string
6335dfc0f6cSIan Lepore config::expand_string(const char *src, const char *prepend, const char *append)
6345102ef84SWarner Losh {
6355dfc0f6cSIan Lepore 	const char *var_at;
6366cabd675SWarner Losh 	string dst;
6375102ef84SWarner Losh 
6385dfc0f6cSIan Lepore 	/*
6395dfc0f6cSIan Lepore 	 * 128 bytes is enough for 2427 of 2438 expansions that happen
6405dfc0f6cSIan Lepore 	 * while parsing config files, as tested on 2013-01-30.
6415dfc0f6cSIan Lepore 	 */
6425dfc0f6cSIan Lepore 	dst.reserve(128);
6435dfc0f6cSIan Lepore 
6445dfc0f6cSIan Lepore 	if (prepend != NULL)
6455dfc0f6cSIan Lepore 		dst = prepend;
6465dfc0f6cSIan Lepore 
6475dfc0f6cSIan Lepore 	for (;;) {
6485dfc0f6cSIan Lepore 		var_at = strchr(src, '$');
6495dfc0f6cSIan Lepore 		if (var_at == NULL) {
6505dfc0f6cSIan Lepore 			dst.append(src);
6515dfc0f6cSIan Lepore 			break;
6525102ef84SWarner Losh 		}
6535dfc0f6cSIan Lepore 		dst.append(src, var_at - src);
6545dfc0f6cSIan Lepore 		src = var_at;
6555dfc0f6cSIan Lepore 		expand_one(src, dst);
6565dfc0f6cSIan Lepore 	}
6575dfc0f6cSIan Lepore 
6585dfc0f6cSIan Lepore 	if (append != NULL)
6595dfc0f6cSIan Lepore 		dst.append(append);
6605102ef84SWarner Losh 
6616cabd675SWarner Losh 	return (dst);
6623054f218SWarner Losh }
6633054f218SWarner Losh 
6648b823408SWarner Losh bool
66511fd1366SEitan Adler config::chop_var(char *&buffer, char *&lhs, char *&rhs) const
6668b823408SWarner Losh {
6678b823408SWarner Losh 	char *walker;
6688b823408SWarner Losh 
6698b823408SWarner Losh 	if (*buffer == '\0')
6708b823408SWarner Losh 		return (false);
6718b823408SWarner Losh 	walker = lhs = buffer;
6728b823408SWarner Losh 	while (is_id_char(*walker))
6738b823408SWarner Losh 		walker++;
6748b823408SWarner Losh 	if (*walker != '=')
6758b823408SWarner Losh 		return (false);
6768b823408SWarner Losh 	walker++;		// skip =
6778b823408SWarner Losh 	if (*walker == '"') {
6788b823408SWarner Losh 		walker++;	// skip "
6798b823408SWarner Losh 		rhs = walker;
6808b823408SWarner Losh 		while (*walker && *walker != '"')
6818b823408SWarner Losh 			walker++;
6828b823408SWarner Losh 		if (*walker != '"')
6838b823408SWarner Losh 			return (false);
6848b823408SWarner Losh 		rhs[-2] = '\0';
6858b823408SWarner Losh 		*walker++ = '\0';
6868b823408SWarner Losh 	} else {
6878b823408SWarner Losh 		rhs = walker;
6888b823408SWarner Losh 		while (*walker && !isspace(*walker))
6898b823408SWarner Losh 			walker++;
6908b823408SWarner Losh 		if (*walker != '\0')
6918b823408SWarner Losh 			*walker++ = '\0';
6928b823408SWarner Losh 		rhs[-1] = '\0';
6938b823408SWarner Losh 	}
694b1ee04b1SWarner Losh 	while (isspace(*walker))
695b1ee04b1SWarner Losh 		walker++;
6968b823408SWarner Losh 	buffer = walker;
6978b823408SWarner Losh 	return (true);
6988b823408SWarner Losh }
6998b823408SWarner Losh 
7008b823408SWarner Losh 
7018b823408SWarner Losh char *
7028b823408SWarner Losh config::set_vars(char *buffer)
7038b823408SWarner Losh {
7048b823408SWarner Losh 	char *lhs;
7058b823408SWarner Losh 	char *rhs;
7068b823408SWarner Losh 
7078b823408SWarner Losh 	while (1) {
7088b823408SWarner Losh 		if (!chop_var(buffer, lhs, rhs))
7098b823408SWarner Losh 			break;
7108b823408SWarner Losh 		set_variable(lhs, rhs);
7118b823408SWarner Losh 	}
7128b823408SWarner Losh 	return (buffer);
7138b823408SWarner Losh }
7148b823408SWarner Losh 
7158b823408SWarner Losh void
7168b823408SWarner Losh config::find_and_execute(char type)
7178b823408SWarner Losh {
7188b823408SWarner Losh 	vector<event_proc *> *l;
7198b823408SWarner Losh 	vector<event_proc *>::const_iterator i;
72094d2d4ebSBrooks Davis 	const char *s;
7218b823408SWarner Losh 
7228b823408SWarner Losh 	switch (type) {
7238b823408SWarner Losh 	default:
7248b823408SWarner Losh 		return;
725842ccec5SWarner Losh 	case notify:
726842ccec5SWarner Losh 		l = &_notify_list;
727842ccec5SWarner Losh 		s = "notify";
728842ccec5SWarner Losh 		break;
7298b823408SWarner Losh 	case nomatch:
7308b823408SWarner Losh 		l = &_nomatch_list;
7318b823408SWarner Losh 		s = "nomatch";
7328b823408SWarner Losh 		break;
7338b823408SWarner Losh 	case attach:
7348b823408SWarner Losh 		l = &_attach_list;
7358b823408SWarner Losh 		s = "attach";
7368b823408SWarner Losh 		break;
7378b823408SWarner Losh 	case detach:
7388b823408SWarner Losh 		l = &_detach_list;
7398b823408SWarner Losh 		s = "detach";
7408b823408SWarner Losh 		break;
7418b823408SWarner Losh 	}
7426d1014a3SAlan Somers 	devdlog(LOG_DEBUG, "Processing %s event\n", s);
743edee691dSEitan Adler 	for (i = l->begin(); i != l->end(); ++i) {
7448b823408SWarner Losh 		if ((*i)->matches(*this)) {
7458b823408SWarner Losh 			(*i)->run(*this);
7468b823408SWarner Losh 			break;
7478b823408SWarner Losh 		}
7488b823408SWarner Losh 	}
7498b823408SWarner Losh 
7508b823408SWarner Losh }
7518b823408SWarner Losh 
752*0285e9b1SAlan Somers 
7533054f218SWarner Losh static void
7548b823408SWarner Losh process_event(char *buffer)
7553054f218SWarner Losh {
7563054f218SWarner Losh 	char type;
7573054f218SWarner Losh 	char *sp;
7583054f218SWarner Losh 
7598b823408SWarner Losh 	sp = buffer + 1;
7606d1014a3SAlan Somers 	devdlog(LOG_DEBUG, "Processing event '%s'\n", buffer);
7613054f218SWarner Losh 	type = *buffer++;
7628b823408SWarner Losh 	cfg.push_var_table();
7638b823408SWarner Losh 	// No match doesn't have a device, and the format is a little
7648b823408SWarner Losh 	// different, so handle it separately.
765842ccec5SWarner Losh 	switch (type) {
766842ccec5SWarner Losh 	case notify:
767842ccec5SWarner Losh 		sp = cfg.set_vars(sp);
768842ccec5SWarner Losh 		break;
769842ccec5SWarner Losh 	case nomatch:
770528d3f79SWarner Losh 		//? at location pnp-info on bus
771528d3f79SWarner Losh 		sp = strchr(sp, ' ');
772528d3f79SWarner Losh 		if (sp == NULL)
773528d3f79SWarner Losh 			return;	/* Can't happen? */
774528d3f79SWarner Losh 		*sp++ = '\0';
7759b6cb520SWarner Losh 		while (isspace(*sp))
7769b6cb520SWarner Losh 			sp++;
777842ccec5SWarner Losh 		if (strncmp(sp, "at ", 3) == 0)
778842ccec5SWarner Losh 			sp += 3;
779842ccec5SWarner Losh 		sp = cfg.set_vars(sp);
7809b6cb520SWarner Losh 		while (isspace(*sp))
7819b6cb520SWarner Losh 			sp++;
782842ccec5SWarner Losh 		if (strncmp(sp, "on ", 3) == 0)
783842ccec5SWarner Losh 			cfg.set_variable("bus", sp + 3);
784842ccec5SWarner Losh 		break;
785842ccec5SWarner Losh 	case attach:	/*FALLTHROUGH*/
786842ccec5SWarner Losh 	case detach:
7878b823408SWarner Losh 		sp = strchr(sp, ' ');
7883054f218SWarner Losh 		if (sp == NULL)
7893054f218SWarner Losh 			return;	/* Can't happen? */
7908b823408SWarner Losh 		*sp++ = '\0';
7918b823408SWarner Losh 		cfg.set_variable("device-name", buffer);
7929b6cb520SWarner Losh 		while (isspace(*sp))
7939b6cb520SWarner Losh 			sp++;
7948b823408SWarner Losh 		if (strncmp(sp, "at ", 3) == 0)
7958b823408SWarner Losh 			sp += 3;
7968b823408SWarner Losh 		sp = cfg.set_vars(sp);
7979b6cb520SWarner Losh 		while (isspace(*sp))
7989b6cb520SWarner Losh 			sp++;
7998b823408SWarner Losh 		if (strncmp(sp, "on ", 3) == 0)
8008b823408SWarner Losh 			cfg.set_variable("bus", sp + 3);
801842ccec5SWarner Losh 		break;
802b1ee04b1SWarner Losh 	}
803b1ee04b1SWarner Losh 
8048b823408SWarner Losh 	cfg.find_and_execute(type);
8058b823408SWarner Losh 	cfg.pop_var_table();
8063054f218SWarner Losh }
8073054f218SWarner Losh 
808251bedd1SWarner Losh int
809251bedd1SWarner Losh create_socket(const char *name)
810251bedd1SWarner Losh {
811251bedd1SWarner Losh 	int fd, slen;
812251bedd1SWarner Losh 	struct sockaddr_un sun;
813251bedd1SWarner Losh 
814251bedd1SWarner Losh 	if ((fd = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0)
815251bedd1SWarner Losh 		err(1, "socket");
816251bedd1SWarner Losh 	bzero(&sun, sizeof(sun));
817251bedd1SWarner Losh 	sun.sun_family = AF_UNIX;
818251bedd1SWarner Losh 	strlcpy(sun.sun_path, name, sizeof(sun.sun_path));
819251bedd1SWarner Losh 	slen = SUN_LEN(&sun);
820251bedd1SWarner Losh 	unlink(name);
821e60fa014SJoe Marcus Clarke 	if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
822e60fa014SJoe Marcus Clarke 	    	err(1, "fcntl");
8235d586d29SDimitry Andric 	if (::bind(fd, (struct sockaddr *) & sun, slen) < 0)
824251bedd1SWarner Losh 		err(1, "bind");
825251bedd1SWarner Losh 	listen(fd, 4);
82683818929SJoe Marcus Clarke 	chown(name, 0, 0);	/* XXX - root.wheel */
827e60fa014SJoe Marcus Clarke 	chmod(name, 0666);
828251bedd1SWarner Losh 	return (fd);
829251bedd1SWarner Losh }
830251bedd1SWarner Losh 
831e1334f93SIan Lepore unsigned int max_clients = 10;	/* Default, can be overriden on cmdline. */
832e1334f93SIan Lepore unsigned int num_clients;
833251bedd1SWarner Losh list<int> clients;
834251bedd1SWarner Losh 
835251bedd1SWarner Losh void
836251bedd1SWarner Losh notify_clients(const char *data, int len)
837251bedd1SWarner Losh {
838e1334f93SIan Lepore 	list<int>::iterator i;
839251bedd1SWarner Losh 
840e1334f93SIan Lepore 	/*
841e1334f93SIan Lepore 	 * Deliver the data to all clients.  Throw clients overboard at the
842e1334f93SIan Lepore 	 * first sign of trouble.  This reaps clients who've died or closed
843e1334f93SIan Lepore 	 * their sockets, and also clients who are alive but failing to keep up
844e1334f93SIan Lepore 	 * (or who are maliciously not reading, to consume buffer space in
845e1334f93SIan Lepore 	 * kernel memory or tie up the limited number of available connections).
846e1334f93SIan Lepore 	 */
847e1334f93SIan Lepore 	for (i = clients.begin(); i != clients.end(); ) {
848e1334f93SIan Lepore 		if (write(*i, data, len) != len) {
849e1334f93SIan Lepore 			--num_clients;
850251bedd1SWarner Losh 			close(*i);
851e1334f93SIan Lepore 			i = clients.erase(i);
8526d1014a3SAlan Somers 			devdlog(LOG_WARNING, "notify_clients: write() failed; "
8536d1014a3SAlan Somers 			    "dropping unresponsive client\n");
854e1334f93SIan Lepore 		} else
855e1334f93SIan Lepore 			++i;
856251bedd1SWarner Losh 	}
857251bedd1SWarner Losh }
858251bedd1SWarner Losh 
859e1334f93SIan Lepore void
860e1334f93SIan Lepore check_clients(void)
861e1334f93SIan Lepore {
862e1334f93SIan Lepore 	int s;
863e1334f93SIan Lepore 	struct pollfd pfd;
864e1334f93SIan Lepore 	list<int>::iterator i;
865e1334f93SIan Lepore 
866e1334f93SIan Lepore 	/*
867e1334f93SIan Lepore 	 * Check all existing clients to see if any of them have disappeared.
868e1334f93SIan Lepore 	 * Normally we reap clients when we get an error trying to send them an
869e1334f93SIan Lepore 	 * event.  This check eliminates the problem of an ever-growing list of
870e1334f93SIan Lepore 	 * zombie clients because we're never writing to them on a system
871e1334f93SIan Lepore 	 * without frequent device-change activity.
872e1334f93SIan Lepore 	 */
873e1334f93SIan Lepore 	pfd.events = 0;
874e1334f93SIan Lepore 	for (i = clients.begin(); i != clients.end(); ) {
875e1334f93SIan Lepore 		pfd.fd = *i;
876e1334f93SIan Lepore 		s = poll(&pfd, 1, 0);
877e1334f93SIan Lepore 		if ((s < 0 && s != EINTR ) ||
878e1334f93SIan Lepore 		    (s > 0 && (pfd.revents & POLLHUP))) {
879e1334f93SIan Lepore 			--num_clients;
880e1334f93SIan Lepore 			close(*i);
881e1334f93SIan Lepore 			i = clients.erase(i);
8826d1014a3SAlan Somers 			devdlog(LOG_NOTICE, "check_clients:  "
8836d1014a3SAlan Somers 			    "dropping disconnected client\n");
884e1334f93SIan Lepore 		} else
885e1334f93SIan Lepore 			++i;
886e1334f93SIan Lepore 	}
887251bedd1SWarner Losh }
888251bedd1SWarner Losh 
889251bedd1SWarner Losh void
890251bedd1SWarner Losh new_client(int fd)
891251bedd1SWarner Losh {
892251bedd1SWarner Losh 	int s;
893251bedd1SWarner Losh 
894e1334f93SIan Lepore 	/*
895e1334f93SIan Lepore 	 * First go reap any zombie clients, then accept the connection, and
896e1334f93SIan Lepore 	 * shut down the read side to stop clients from consuming kernel memory
897e1334f93SIan Lepore 	 * by sending large buffers full of data we'll never read.
898e1334f93SIan Lepore 	 */
899e1334f93SIan Lepore 	check_clients();
900251bedd1SWarner Losh 	s = accept(fd, NULL, NULL);
901e1334f93SIan Lepore 	if (s != -1) {
902e1334f93SIan Lepore 		shutdown(s, SHUT_RD);
903251bedd1SWarner Losh 		clients.push_back(s);
904e1334f93SIan Lepore 		++num_clients;
905e1334f93SIan Lepore 	}
906251bedd1SWarner Losh }
907251bedd1SWarner Losh 
9083054f218SWarner Losh static void
9093054f218SWarner Losh event_loop(void)
9103054f218SWarner Losh {
9113054f218SWarner Losh 	int rv;
9123054f218SWarner Losh 	int fd;
9133054f218SWarner Losh 	char buffer[DEVCTL_MAXBUF];
9145a882d77SWarner Losh 	int once = 0;
915251bedd1SWarner Losh 	int server_fd, max_fd;
916e1334f93SIan Lepore 	int accepting;
9175a882d77SWarner Losh 	timeval tv;
9185a882d77SWarner Losh 	fd_set fds;
9193054f218SWarner Losh 
920901610f4SPawel Jakub Dawidek 	fd = open(PATH_DEVCTL, O_RDONLY | O_CLOEXEC);
9213054f218SWarner Losh 	if (fd == -1)
922251bedd1SWarner Losh 		err(1, "Can't open devctl device %s", PATH_DEVCTL);
923251bedd1SWarner Losh 	server_fd = create_socket(PIPE);
924e1334f93SIan Lepore 	accepting = 1;
925251bedd1SWarner Losh 	max_fd = max(fd, server_fd) + 1;
92667ae3bf1SEitan Adler 	while (!romeo_must_die) {
9275a882d77SWarner Losh 		if (!once && !dflag && !nflag) {
9285a882d77SWarner Losh 			// Check to see if we have any events pending.
9295a882d77SWarner Losh 			tv.tv_sec = 0;
9305a882d77SWarner Losh 			tv.tv_usec = 0;
9315a882d77SWarner Losh 			FD_ZERO(&fds);
9325a882d77SWarner Losh 			FD_SET(fd, &fds);
9335a882d77SWarner Losh 			rv = select(fd + 1, &fds, &fds, &fds, &tv);
9345a882d77SWarner Losh 			// No events -> we've processed all pending events
935f3059505SWarner Losh 			if (rv == 0) {
9366d1014a3SAlan Somers 				devdlog(LOG_DEBUG, "Calling daemon\n");
9371a0cc6b1SPawel Jakub Dawidek 				cfg.remove_pidfile();
9381a0cc6b1SPawel Jakub Dawidek 				cfg.open_pidfile();
9395a882d77SWarner Losh 				daemon(0, 0);
9401a0cc6b1SPawel Jakub Dawidek 				cfg.write_pidfile();
9415a882d77SWarner Losh 				once++;
9425a882d77SWarner Losh 			}
9435a882d77SWarner Losh 		}
944e1334f93SIan Lepore 		/*
945e1334f93SIan Lepore 		 * When we've already got the max number of clients, stop
946e1334f93SIan Lepore 		 * accepting new connections (don't put server_fd in the set),
947e1334f93SIan Lepore 		 * shrink the accept() queue to reject connections quickly, and
948e1334f93SIan Lepore 		 * poll the existing clients more often, so that we notice more
949e1334f93SIan Lepore 		 * quickly when any of them disappear to free up client slots.
950e1334f93SIan Lepore 		 */
951251bedd1SWarner Losh 		FD_ZERO(&fds);
952251bedd1SWarner Losh 		FD_SET(fd, &fds);
953e1334f93SIan Lepore 		if (num_clients < max_clients) {
954e1334f93SIan Lepore 			if (!accepting) {
955e1334f93SIan Lepore 				listen(server_fd, max_clients);
956e1334f93SIan Lepore 				accepting = 1;
957e1334f93SIan Lepore 			}
958251bedd1SWarner Losh 			FD_SET(server_fd, &fds);
959e1334f93SIan Lepore 			tv.tv_sec = 60;
960e1334f93SIan Lepore 			tv.tv_usec = 0;
961e1334f93SIan Lepore 		} else {
962e1334f93SIan Lepore 			if (accepting) {
963e1334f93SIan Lepore 				listen(server_fd, 0);
964e1334f93SIan Lepore 				accepting = 0;
965e1334f93SIan Lepore 			}
966e1334f93SIan Lepore 			tv.tv_sec = 2;
967e1334f93SIan Lepore 			tv.tv_usec = 0;
968e1334f93SIan Lepore 		}
969e1334f93SIan Lepore 		rv = select(max_fd, &fds, NULL, NULL, &tv);
970be685e01SAlan Somers 		if (got_siginfo) {
971be685e01SAlan Somers 			devdlog(LOG_INFO, "Events received so far=%ld\n",
972be685e01SAlan Somers 			    total_events);
973be685e01SAlan Somers 			got_siginfo = 0;
974be685e01SAlan Somers 		}
975251bedd1SWarner Losh 		if (rv == -1) {
976251bedd1SWarner Losh 			if (errno == EINTR)
977251bedd1SWarner Losh 				continue;
978251bedd1SWarner Losh 			err(1, "select");
979e1334f93SIan Lepore 		} else if (rv == 0)
980e1334f93SIan Lepore 			check_clients();
981251bedd1SWarner Losh 		if (FD_ISSET(fd, &fds)) {
9823054f218SWarner Losh 			rv = read(fd, buffer, sizeof(buffer) - 1);
9833054f218SWarner Losh 			if (rv > 0) {
984be685e01SAlan Somers 				total_events++;
9856d1014a3SAlan Somers 				if (rv == sizeof(buffer) - 1) {
9866d1014a3SAlan Somers 					devdlog(LOG_WARNING, "Warning: "
9876d1014a3SAlan Somers 					    "available event data exceeded "
9886d1014a3SAlan Somers 					    "buffer space\n");
9896d1014a3SAlan Somers 				}
990251bedd1SWarner Losh 				notify_clients(buffer, rv);
9913054f218SWarner Losh 				buffer[rv] = '\0';
9923054f218SWarner Losh 				while (buffer[--rv] == '\n')
9933054f218SWarner Losh 					buffer[rv] = '\0';
9943054f218SWarner Losh 				process_event(buffer);
9953054f218SWarner Losh 			} else if (rv < 0) {
9963054f218SWarner Losh 				if (errno != EINTR)
9973054f218SWarner Losh 					break;
9983054f218SWarner Losh 			} else {
9993054f218SWarner Losh 				/* EOF */
10003054f218SWarner Losh 				break;
10013054f218SWarner Losh 			}
10023054f218SWarner Losh 		}
1003251bedd1SWarner Losh 		if (FD_ISSET(server_fd, &fds))
1004251bedd1SWarner Losh 			new_client(server_fd);
1005251bedd1SWarner Losh 	}
10063054f218SWarner Losh 	close(fd);
10073054f218SWarner Losh }
1008*0285e9b1SAlan Somers 
10093054f218SWarner Losh /*
10103054f218SWarner Losh  * functions that the parser uses.
10113054f218SWarner Losh  */
10123054f218SWarner Losh void
10133054f218SWarner Losh add_attach(int prio, event_proc *p)
10143054f218SWarner Losh {
10153054f218SWarner Losh 	cfg.add_attach(prio, p);
10163054f218SWarner Losh }
10173054f218SWarner Losh 
10183054f218SWarner Losh void
10193054f218SWarner Losh add_detach(int prio, event_proc *p)
10203054f218SWarner Losh {
10213054f218SWarner Losh 	cfg.add_detach(prio, p);
10223054f218SWarner Losh }
10233054f218SWarner Losh 
10243054f218SWarner Losh void
10253054f218SWarner Losh add_directory(const char *dir)
10263054f218SWarner Losh {
10273054f218SWarner Losh 	cfg.add_directory(dir);
10283054f218SWarner Losh 	free(const_cast<char *>(dir));
10293054f218SWarner Losh }
10303054f218SWarner Losh 
10313054f218SWarner Losh void
10323054f218SWarner Losh add_nomatch(int prio, event_proc *p)
10333054f218SWarner Losh {
10343054f218SWarner Losh 	cfg.add_nomatch(prio, p);
10353054f218SWarner Losh }
10363054f218SWarner Losh 
1037842ccec5SWarner Losh void
1038842ccec5SWarner Losh add_notify(int prio, event_proc *p)
1039842ccec5SWarner Losh {
1040842ccec5SWarner Losh 	cfg.add_notify(prio, p);
1041842ccec5SWarner Losh }
1042842ccec5SWarner Losh 
10433054f218SWarner Losh event_proc *
10443054f218SWarner Losh add_to_event_proc(event_proc *ep, eps *eps)
10453054f218SWarner Losh {
10463054f218SWarner Losh 	if (ep == NULL)
10473054f218SWarner Losh 		ep = new event_proc();
10483054f218SWarner Losh 	ep->add(eps);
10493054f218SWarner Losh 	return (ep);
10503054f218SWarner Losh }
10513054f218SWarner Losh 
10523054f218SWarner Losh eps *
10533054f218SWarner Losh new_action(const char *cmd)
10543054f218SWarner Losh {
10553054f218SWarner Losh 	eps *e = new action(cmd);
10563054f218SWarner Losh 	free(const_cast<char *>(cmd));
10573054f218SWarner Losh 	return (e);
10583054f218SWarner Losh }
10593054f218SWarner Losh 
10603054f218SWarner Losh eps *
10613054f218SWarner Losh new_match(const char *var, const char *re)
10623054f218SWarner Losh {
10635102ef84SWarner Losh 	eps *e = new match(cfg, var, re);
10643054f218SWarner Losh 	free(const_cast<char *>(var));
10653054f218SWarner Losh 	free(const_cast<char *>(re));
10663054f218SWarner Losh 	return (e);
10673054f218SWarner Losh }
10683054f218SWarner Losh 
1069cd70782bSWarner Losh eps *
1070cd70782bSWarner Losh new_media(const char *var, const char *re)
1071cd70782bSWarner Losh {
1072cd70782bSWarner Losh 	eps *e = new media(cfg, var, re);
1073cd70782bSWarner Losh 	free(const_cast<char *>(var));
1074cd70782bSWarner Losh 	free(const_cast<char *>(re));
1075cd70782bSWarner Losh 	return (e);
1076cd70782bSWarner Losh }
1077cd70782bSWarner Losh 
10783054f218SWarner Losh void
10793054f218SWarner Losh set_pidfile(const char *name)
10803054f218SWarner Losh {
10813054f218SWarner Losh 	cfg.set_pidfile(name);
10823054f218SWarner Losh 	free(const_cast<char *>(name));
10833054f218SWarner Losh }
10843054f218SWarner Losh 
10853054f218SWarner Losh void
10863054f218SWarner Losh set_variable(const char *var, const char *val)
10873054f218SWarner Losh {
10883054f218SWarner Losh 	cfg.set_variable(var, val);
10893054f218SWarner Losh 	free(const_cast<char *>(var));
10903054f218SWarner Losh 	free(const_cast<char *>(val));
10913054f218SWarner Losh }
10923054f218SWarner Losh 
1093*0285e9b1SAlan Somers 
10943054f218SWarner Losh 
10953054f218SWarner Losh static void
10963054f218SWarner Losh gensighand(int)
10973054f218SWarner Losh {
1098fcdcaa88SEitan Adler 	romeo_must_die = 1;
10993054f218SWarner Losh }
11003054f218SWarner Losh 
11016d1014a3SAlan Somers /*
1102be685e01SAlan Somers  * SIGINFO handler.  Will print useful statistics to the syslog or stderr
1103be685e01SAlan Somers  * as appropriate
1104be685e01SAlan Somers  */
1105be685e01SAlan Somers static void
1106be685e01SAlan Somers siginfohand(int)
1107be685e01SAlan Somers {
1108be685e01SAlan Somers 	got_siginfo = 1;
1109be685e01SAlan Somers }
1110be685e01SAlan Somers 
1111be685e01SAlan Somers /*
11126d1014a3SAlan Somers  * Local logging function.  Prints to syslog if we're daemonized; syslog
11136d1014a3SAlan Somers  * otherwise.
11146d1014a3SAlan Somers  */
11156d1014a3SAlan Somers static void
11166d1014a3SAlan Somers devdlog(int priority, const char* fmt, ...)
11176d1014a3SAlan Somers {
11186d1014a3SAlan Somers 	va_list argp;
11196d1014a3SAlan Somers 
11206d1014a3SAlan Somers 	va_start(argp, fmt);
11216d1014a3SAlan Somers 	if (dflag)
11226d1014a3SAlan Somers 		vfprintf(stderr, fmt, argp);
11236d1014a3SAlan Somers 	else
11246d1014a3SAlan Somers 		vsyslog(priority, fmt, argp);
11256d1014a3SAlan Somers 	va_end(argp);
11266d1014a3SAlan Somers }
11276d1014a3SAlan Somers 
11283054f218SWarner Losh static void
11293054f218SWarner Losh usage()
11303054f218SWarner Losh {
11316d1014a3SAlan Somers 	fprintf(stderr, "usage: %s [-dn] [-l connlimit] [-f file]\n",
1132e1334f93SIan Lepore 	    getprogname());
11333054f218SWarner Losh 	exit(1);
11343054f218SWarner Losh }
11353054f218SWarner Losh 
11369c180898SWarner Losh static void
11379c180898SWarner Losh check_devd_enabled()
11389c180898SWarner Losh {
11399c180898SWarner Losh 	int val = 0;
11409c180898SWarner Losh 	size_t len;
11419c180898SWarner Losh 
11429c180898SWarner Losh 	len = sizeof(val);
114379f92e25SWarner Losh 	if (sysctlbyname(SYSCTL, &val, &len, NULL, 0) != 0)
11449c180898SWarner Losh 		errx(1, "devctl sysctl missing from kernel!");
11459c180898SWarner Losh 	if (val) {
11469c180898SWarner Losh 		warnx("Setting " SYSCTL " to 0");
11479c180898SWarner Losh 		val = 0;
11489c180898SWarner Losh 		sysctlbyname(SYSCTL, NULL, NULL, &val, sizeof(val));
11499c180898SWarner Losh 	}
11509c180898SWarner Losh }
11519c180898SWarner Losh 
11523054f218SWarner Losh /*
11533054f218SWarner Losh  * main
11543054f218SWarner Losh  */
11553054f218SWarner Losh int
11563054f218SWarner Losh main(int argc, char **argv)
11573054f218SWarner Losh {
11583054f218SWarner Losh 	int ch;
11593054f218SWarner Losh 
11609c180898SWarner Losh 	check_devd_enabled();
11616d1014a3SAlan Somers 	while ((ch = getopt(argc, argv, "df:l:n")) != -1) {
11623054f218SWarner Losh 		switch (ch) {
11633054f218SWarner Losh 		case 'd':
11643054f218SWarner Losh 			dflag++;
11653054f218SWarner Losh 			break;
11668334958aSJoseph Koshy 		case 'f':
11678334958aSJoseph Koshy 			configfile = optarg;
11688334958aSJoseph Koshy 			break;
1169e1334f93SIan Lepore 		case 'l':
1170e1334f93SIan Lepore 			max_clients = MAX(1, strtoul(optarg, NULL, 0));
1171e1334f93SIan Lepore 			break;
11725a882d77SWarner Losh 		case 'n':
11735a882d77SWarner Losh 			nflag++;
11745a882d77SWarner Losh 			break;
11753054f218SWarner Losh 		default:
11763054f218SWarner Losh 			usage();
11773054f218SWarner Losh 		}
11783054f218SWarner Losh 	}
11793054f218SWarner Losh 
11803054f218SWarner Losh 	cfg.parse();
1181fd6a8f23SWarner Losh 	if (!dflag && nflag) {
11821a0cc6b1SPawel Jakub Dawidek 		cfg.open_pidfile();
11833054f218SWarner Losh 		daemon(0, 0);
11841a0cc6b1SPawel Jakub Dawidek 		cfg.write_pidfile();
1185fd6a8f23SWarner Losh 	}
1186f32a7686SWarner Losh 	signal(SIGPIPE, SIG_IGN);
11873054f218SWarner Losh 	signal(SIGHUP, gensighand);
11883054f218SWarner Losh 	signal(SIGINT, gensighand);
11893054f218SWarner Losh 	signal(SIGTERM, gensighand);
1190be685e01SAlan Somers 	signal(SIGINFO, siginfohand);
11913054f218SWarner Losh 	event_loop();
11923054f218SWarner Losh 	return (0);
11933054f218SWarner Losh }
1194