xref: /freebsd-14.2/sbin/devd/devd.cc (revision 67ae3bf1)
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 
765102ef84SWarner Losh #include <ctype.h>
773054f218SWarner Losh #include <dirent.h>
783054f218SWarner Losh #include <errno.h>
793054f218SWarner Losh #include <err.h>
803054f218SWarner Losh #include <fcntl.h>
811a0cc6b1SPawel Jakub Dawidek #include <libutil.h>
82b8f92ce4SWarner Losh #include <paths.h>
83e1334f93SIan Lepore #include <poll.h>
845102ef84SWarner Losh #include <regex.h>
85f32a7686SWarner Losh #include <signal.h>
863054f218SWarner Losh #include <stdlib.h>
873054f218SWarner Losh #include <stdio.h>
883054f218SWarner Losh #include <string.h>
893054f218SWarner Losh #include <unistd.h>
903054f218SWarner Losh 
918b823408SWarner Losh #include <algorithm>
923054f218SWarner Losh #include <map>
933054f218SWarner Losh #include <string>
94251bedd1SWarner Losh #include <list>
953054f218SWarner Losh #include <vector>
963054f218SWarner Losh 
976aeeca8eSWarner Losh #include "devd.h"		/* C compatible definitions */
986aeeca8eSWarner Losh #include "devd.hh"		/* C++ class definitions */
993054f218SWarner Losh 
100251bedd1SWarner Losh #define PIPE "/var/run/devd.pipe"
1013054f218SWarner Losh #define CF "/etc/devd.conf"
1029c180898SWarner Losh #define SYSCTL "hw.bus.devctl_disable"
1033054f218SWarner Losh 
1043054f218SWarner Losh using namespace std;
1053054f218SWarner Losh 
1063054f218SWarner Losh extern FILE *yyin;
1073054f218SWarner Losh extern int lineno;
1083054f218SWarner Losh 
109842ccec5SWarner Losh static const char notify = '!';
1108b823408SWarner Losh static const char nomatch = '?';
1118b823408SWarner Losh static const char attach = '+';
1128b823408SWarner Losh static const char detach = '-';
1138b823408SWarner Losh 
1141a0cc6b1SPawel Jakub Dawidek static struct pidfh *pfh;
1151a0cc6b1SPawel Jakub Dawidek 
1165a882d77SWarner Losh int Dflag;
1173054f218SWarner Losh int dflag;
118812f53a7SWarner Losh int nflag;
119fcdcaa88SEitan Adler static volatile sig_atomic_t romeo_must_die = 0;
1203054f218SWarner Losh 
1218334958aSJoseph Koshy static const char *configfile = CF;
1228334958aSJoseph Koshy 
1233054f218SWarner Losh static void event_loop(void);
1243054f218SWarner Losh static void usage(void);
1253054f218SWarner Losh 
1268b823408SWarner Losh template <class T> void
1278b823408SWarner Losh delete_and_clear(vector<T *> &v)
1288b823408SWarner Losh {
1298b823408SWarner Losh 	typename vector<T *>::const_iterator i;
1303054f218SWarner Losh 
131edee691dSEitan Adler 	for (i = v.begin(); i != v.end(); ++i)
1328b823408SWarner Losh 		delete *i;
1338b823408SWarner Losh 	v.clear();
1348b823408SWarner Losh }
1358b823408SWarner Losh 
1363054f218SWarner Losh config cfg;
1373054f218SWarner Losh 
1383054f218SWarner Losh event_proc::event_proc() : _prio(-1)
1393054f218SWarner Losh {
1405dfc0f6cSIan Lepore 	_epsvec.reserve(4);
1413054f218SWarner Losh }
1423054f218SWarner Losh 
1433054f218SWarner Losh event_proc::~event_proc()
1443054f218SWarner Losh {
14513f8bb71SAlexander Nedotsukov 	delete_and_clear(_epsvec);
1463054f218SWarner Losh }
1473054f218SWarner Losh 
1483054f218SWarner Losh void
1493054f218SWarner Losh event_proc::add(eps *eps)
1503054f218SWarner Losh {
1513054f218SWarner Losh 	_epsvec.push_back(eps);
1523054f218SWarner Losh }
1533054f218SWarner Losh 
1543054f218SWarner Losh bool
155ef370346SEitan Adler event_proc::matches(config &c) const
1563054f218SWarner Losh {
1573054f218SWarner Losh 	vector<eps *>::const_iterator i;
1583054f218SWarner Losh 
159edee691dSEitan Adler 	for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
1603054f218SWarner Losh 		if (!(*i)->do_match(c))
1613054f218SWarner Losh 			return (false);
1623054f218SWarner Losh 	return (true);
1633054f218SWarner Losh }
1643054f218SWarner Losh 
1653054f218SWarner Losh bool
166ef370346SEitan Adler event_proc::run(config &c) const
1673054f218SWarner Losh {
1683054f218SWarner Losh 	vector<eps *>::const_iterator i;
1693054f218SWarner Losh 
170edee691dSEitan Adler 	for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
1713054f218SWarner Losh 		if (!(*i)->do_action(c))
1723054f218SWarner Losh 			return (false);
1733054f218SWarner Losh 	return (true);
1743054f218SWarner Losh }
1753054f218SWarner Losh 
1763054f218SWarner Losh action::action(const char *cmd)
1773054f218SWarner Losh 	: _cmd(cmd)
1783054f218SWarner Losh {
1793054f218SWarner Losh 	// nothing
1803054f218SWarner Losh }
1813054f218SWarner Losh 
1823054f218SWarner Losh action::~action()
1833054f218SWarner Losh {
1843054f218SWarner Losh 	// nothing
1853054f218SWarner Losh }
1863054f218SWarner Losh 
187b8f92ce4SWarner Losh static int
188b8f92ce4SWarner Losh my_system(const char *command)
189b8f92ce4SWarner Losh {
190b8f92ce4SWarner Losh 	pid_t pid, savedpid;
191b8f92ce4SWarner Losh 	int pstat;
192b8f92ce4SWarner Losh 	struct sigaction ign, intact, quitact;
193b8f92ce4SWarner Losh 	sigset_t newsigblock, oldsigblock;
194b8f92ce4SWarner Losh 
195b8f92ce4SWarner Losh 	if (!command)		/* just checking... */
196b8f92ce4SWarner Losh 		return(1);
197b8f92ce4SWarner Losh 
198b8f92ce4SWarner Losh 	/*
199b8f92ce4SWarner Losh 	 * Ignore SIGINT and SIGQUIT, block SIGCHLD. Remember to save
200b8f92ce4SWarner Losh 	 * existing signal dispositions.
201b8f92ce4SWarner Losh 	 */
202b8f92ce4SWarner Losh 	ign.sa_handler = SIG_IGN;
203b8f92ce4SWarner Losh 	::sigemptyset(&ign.sa_mask);
204b8f92ce4SWarner Losh 	ign.sa_flags = 0;
205b8f92ce4SWarner Losh 	::sigaction(SIGINT, &ign, &intact);
206b8f92ce4SWarner Losh 	::sigaction(SIGQUIT, &ign, &quitact);
207b8f92ce4SWarner Losh 	::sigemptyset(&newsigblock);
208b8f92ce4SWarner Losh 	::sigaddset(&newsigblock, SIGCHLD);
209b8f92ce4SWarner Losh 	::sigprocmask(SIG_BLOCK, &newsigblock, &oldsigblock);
210b8f92ce4SWarner Losh 	switch (pid = ::fork()) {
211b8f92ce4SWarner Losh 	case -1:			/* error */
212b8f92ce4SWarner Losh 		break;
213b8f92ce4SWarner Losh 	case 0:				/* child */
214b8f92ce4SWarner Losh 		/*
215b8f92ce4SWarner Losh 		 * Restore original signal dispositions and exec the command.
216b8f92ce4SWarner Losh 		 */
217b8f92ce4SWarner Losh 		::sigaction(SIGINT, &intact, NULL);
218b8f92ce4SWarner Losh 		::sigaction(SIGQUIT,  &quitact, NULL);
219b8f92ce4SWarner Losh 		::sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
220b8f92ce4SWarner Losh 		/*
221b8f92ce4SWarner Losh 		 * Close the PID file, and all other open descriptors.
222b8f92ce4SWarner Losh 		 * Inherit std{in,out,err} only.
223b8f92ce4SWarner Losh 		 */
224b8f92ce4SWarner Losh 		cfg.close_pidfile();
225b8f92ce4SWarner Losh 		::closefrom(3);
226b8f92ce4SWarner Losh 		::execl(_PATH_BSHELL, "sh", "-c", command, (char *)NULL);
227b8f92ce4SWarner Losh 		::_exit(127);
228b8f92ce4SWarner Losh 	default:			/* parent */
229b8f92ce4SWarner Losh 		savedpid = pid;
230b8f92ce4SWarner Losh 		do {
231b8f92ce4SWarner Losh 			pid = ::wait4(savedpid, &pstat, 0, (struct rusage *)0);
232b8f92ce4SWarner Losh 		} while (pid == -1 && errno == EINTR);
233b8f92ce4SWarner Losh 		break;
234b8f92ce4SWarner Losh 	}
235b8f92ce4SWarner Losh 	::sigaction(SIGINT, &intact, NULL);
236b8f92ce4SWarner Losh 	::sigaction(SIGQUIT,  &quitact, NULL);
237b8f92ce4SWarner Losh 	::sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
238b8f92ce4SWarner Losh 	return (pid == -1 ? -1 : pstat);
239b8f92ce4SWarner Losh }
240b8f92ce4SWarner Losh 
2413054f218SWarner Losh bool
2425102ef84SWarner Losh action::do_action(config &c)
2433054f218SWarner Losh {
2445dfc0f6cSIan Lepore 	string s = c.expand_string(_cmd.c_str());
2455a882d77SWarner Losh 	if (Dflag)
2468b823408SWarner Losh 		fprintf(stderr, "Executing '%s'\n", s.c_str());
247b8f92ce4SWarner Losh 	my_system(s.c_str());
2483054f218SWarner Losh 	return (true);
2493054f218SWarner Losh }
2503054f218SWarner Losh 
2515dfc0f6cSIan Lepore match::match(config &c, const char *var, const char *re) :
2525dfc0f6cSIan Lepore 	_inv(re[0] == '!'),
2535dfc0f6cSIan Lepore 	_var(var),
2545dfc0f6cSIan Lepore 	_re(c.expand_string(_inv ? re + 1 : re, "^", "$"))
2553054f218SWarner Losh {
2569cb4a7bdSWarner Losh 	regcomp(&_regex, _re.c_str(), REG_EXTENDED | REG_NOSUB | REG_ICASE);
2573054f218SWarner Losh }
2583054f218SWarner Losh 
2593054f218SWarner Losh match::~match()
2603054f218SWarner Losh {
2615102ef84SWarner Losh 	regfree(&_regex);
2623054f218SWarner Losh }
2633054f218SWarner Losh 
2643054f218SWarner Losh bool
2655102ef84SWarner Losh match::do_match(config &c)
2663054f218SWarner Losh {
2675bf08422SUlf Lilleengen 	const string &value = c.get_variable(_var);
2685102ef84SWarner Losh 	bool retval;
2695102ef84SWarner Losh 
2705a882d77SWarner Losh 	if (Dflag)
2710321b694SHiroki Sato 		fprintf(stderr, "Testing %s=%s against %s, invert=%d\n",
2720321b694SHiroki Sato 		    _var.c_str(), value.c_str(), _re.c_str(), _inv);
2738b823408SWarner Losh 
2745102ef84SWarner Losh 	retval = (regexec(&_regex, value.c_str(), 0, NULL, 0) == 0);
2750321b694SHiroki Sato 	if (_inv == 1)
2760321b694SHiroki Sato 		retval = (retval == 0) ? 1 : 0;
2770321b694SHiroki Sato 
2785102ef84SWarner Losh 	return retval;
2793054f218SWarner Losh }
2803054f218SWarner Losh 
281cd70782bSWarner Losh #include <sys/sockio.h>
282cd70782bSWarner Losh #include <net/if.h>
283cd70782bSWarner Losh #include <net/if_media.h>
284cd70782bSWarner Losh 
28594d2d4ebSBrooks Davis media::media(config &, const char *var, const char *type)
286cd70782bSWarner Losh 	: _var(var), _type(-1)
287cd70782bSWarner Losh {
288cd70782bSWarner Losh 	static struct ifmedia_description media_types[] = {
289cd70782bSWarner Losh 		{ IFM_ETHER,		"Ethernet" },
290cd70782bSWarner Losh 		{ IFM_TOKEN,		"Tokenring" },
291cd70782bSWarner Losh 		{ IFM_FDDI,		"FDDI" },
292cd70782bSWarner Losh 		{ IFM_IEEE80211,	"802.11" },
293cd70782bSWarner Losh 		{ IFM_ATM,		"ATM" },
294cd70782bSWarner Losh 		{ -1,			"unknown" },
295cd70782bSWarner Losh 		{ 0, NULL },
296cd70782bSWarner Losh 	};
297edee691dSEitan Adler 	for (int i = 0; media_types[i].ifmt_string != NULL; ++i)
298cd70782bSWarner Losh 		if (strcasecmp(type, media_types[i].ifmt_string) == 0) {
299cd70782bSWarner Losh 			_type = media_types[i].ifmt_word;
300cd70782bSWarner Losh 			break;
301cd70782bSWarner Losh 		}
302cd70782bSWarner Losh }
303cd70782bSWarner Losh 
304cd70782bSWarner Losh media::~media()
305cd70782bSWarner Losh {
306cd70782bSWarner Losh }
307cd70782bSWarner Losh 
308cd70782bSWarner Losh bool
309cd70782bSWarner Losh media::do_match(config &c)
310cd70782bSWarner Losh {
31109c47e76SWarner Losh 	string value;
312cd70782bSWarner Losh 	struct ifmediareq ifmr;
313cd70782bSWarner Losh 	bool retval;
314cd70782bSWarner Losh 	int s;
315cd70782bSWarner Losh 
31609c47e76SWarner Losh 	// Since we can be called from both a device attach/detach
31709c47e76SWarner Losh 	// context where device-name is defined and what we want,
31809c47e76SWarner Losh 	// as well as from a link status context, where subsystem is
31909c47e76SWarner Losh 	// the name of interest, first try device-name and fall back
32009c47e76SWarner Losh 	// to subsystem if none exists.
32109c47e76SWarner Losh 	value = c.get_variable("device-name");
32209c47e76SWarner Losh 	if (value.length() == 0)
323de02eec8SWarner Losh 		value = c.get_variable("subsystem");
324cd70782bSWarner Losh 	if (Dflag)
325cd70782bSWarner Losh 		fprintf(stderr, "Testing media type of %s against 0x%x\n",
326cd70782bSWarner Losh 		    value.c_str(), _type);
327cd70782bSWarner Losh 
328cd70782bSWarner Losh 	retval = false;
329cd70782bSWarner Losh 
330cd70782bSWarner Losh 	s = socket(PF_INET, SOCK_DGRAM, 0);
331cd70782bSWarner Losh 	if (s >= 0) {
332cd70782bSWarner Losh 		memset(&ifmr, 0, sizeof(ifmr));
333cd70782bSWarner Losh 		strncpy(ifmr.ifm_name, value.c_str(), sizeof(ifmr.ifm_name));
334cd70782bSWarner Losh 
335cd70782bSWarner Losh 		if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0 &&
336cd70782bSWarner Losh 		    ifmr.ifm_status & IFM_AVALID) {
337cd70782bSWarner Losh 			if (Dflag)
338cd70782bSWarner Losh 				fprintf(stderr, "%s has media type 0x%x\n",
339cd70782bSWarner Losh 				    value.c_str(), IFM_TYPE(ifmr.ifm_active));
340cd70782bSWarner Losh 			retval = (IFM_TYPE(ifmr.ifm_active) == _type);
341cd70782bSWarner Losh 		} else if (_type == -1) {
342cd70782bSWarner Losh 			if (Dflag)
343cd70782bSWarner Losh 				fprintf(stderr, "%s has unknown media type\n",
344cd70782bSWarner Losh 				    value.c_str());
345cd70782bSWarner Losh 			retval = true;
346cd70782bSWarner Losh 		}
347cd70782bSWarner Losh 		close(s);
348cd70782bSWarner Losh 	}
349cd70782bSWarner Losh 
350cd70782bSWarner Losh 	return retval;
351cd70782bSWarner Losh }
352cd70782bSWarner Losh 
3533054f218SWarner Losh const string var_list::bogus = "_$_$_$_$_B_O_G_U_S_$_$_$_$_";
3543054f218SWarner Losh const string var_list::nothing = "";
3553054f218SWarner Losh 
3563054f218SWarner Losh const string &
3573054f218SWarner Losh var_list::get_variable(const string &var) const
3583054f218SWarner Losh {
3593054f218SWarner Losh 	map<string, string>::const_iterator i;
3603054f218SWarner Losh 
3613054f218SWarner Losh 	i = _vars.find(var);
3623054f218SWarner Losh 	if (i == _vars.end())
3638b823408SWarner Losh 		return (var_list::bogus);
3643054f218SWarner Losh 	return (i->second);
3653054f218SWarner Losh }
3663054f218SWarner Losh 
3673054f218SWarner Losh bool
3683054f218SWarner Losh var_list::is_set(const string &var) const
3693054f218SWarner Losh {
3703054f218SWarner Losh 	return (_vars.find(var) != _vars.end());
3713054f218SWarner Losh }
3723054f218SWarner Losh 
3733054f218SWarner Losh void
3743054f218SWarner Losh var_list::set_variable(const string &var, const string &val)
3753054f218SWarner Losh {
3765a882d77SWarner Losh 	if (Dflag)
377528d3f79SWarner Losh 		fprintf(stderr, "setting %s=%s\n", var.c_str(), val.c_str());
3783054f218SWarner Losh 	_vars[var] = val;
3793054f218SWarner Losh }
3803054f218SWarner Losh 
3813054f218SWarner Losh void
3823054f218SWarner Losh config::reset(void)
3833054f218SWarner Losh {
3843054f218SWarner Losh 	_dir_list.clear();
3858b823408SWarner Losh 	delete_and_clear(_var_list_table);
3868b823408SWarner Losh 	delete_and_clear(_attach_list);
3878b823408SWarner Losh 	delete_and_clear(_detach_list);
3888b823408SWarner Losh 	delete_and_clear(_nomatch_list);
389842ccec5SWarner Losh 	delete_and_clear(_notify_list);
3903054f218SWarner Losh }
3913054f218SWarner Losh 
3923054f218SWarner Losh void
3933054f218SWarner Losh config::parse_one_file(const char *fn)
3943054f218SWarner Losh {
3955a882d77SWarner Losh 	if (Dflag)
3960f3311c5SPoul-Henning Kamp 		fprintf(stderr, "Parsing %s\n", fn);
3973054f218SWarner Losh 	yyin = fopen(fn, "r");
3983054f218SWarner Losh 	if (yyin == NULL)
3993054f218SWarner Losh 		err(1, "Cannot open config file %s", fn);
4004a3050fcSMaxim Konovalov 	lineno = 1;
4013054f218SWarner Losh 	if (yyparse() != 0)
4023054f218SWarner Losh 		errx(1, "Cannot parse %s at line %d", fn, lineno);
4033054f218SWarner Losh 	fclose(yyin);
4043054f218SWarner Losh }
4053054f218SWarner Losh 
4063054f218SWarner Losh void
4073054f218SWarner Losh config::parse_files_in_dir(const char *dirname)
4083054f218SWarner Losh {
4093054f218SWarner Losh 	DIR *dirp;
4103054f218SWarner Losh 	struct dirent *dp;
4113054f218SWarner Losh 	char path[PATH_MAX];
4123054f218SWarner Losh 
4135a882d77SWarner Losh 	if (Dflag)
4140f3311c5SPoul-Henning Kamp 		fprintf(stderr, "Parsing files in %s\n", dirname);
4153054f218SWarner Losh 	dirp = opendir(dirname);
4163054f218SWarner Losh 	if (dirp == NULL)
4173054f218SWarner Losh 		return;
4183054f218SWarner Losh 	readdir(dirp);		/* Skip . */
4193054f218SWarner Losh 	readdir(dirp);		/* Skip .. */
4203054f218SWarner Losh 	while ((dp = readdir(dirp)) != NULL) {
4213054f218SWarner Losh 		if (strcmp(dp->d_name + dp->d_namlen - 5, ".conf") == 0) {
4223054f218SWarner Losh 			snprintf(path, sizeof(path), "%s/%s",
4233054f218SWarner Losh 			    dirname, dp->d_name);
4243054f218SWarner Losh 			parse_one_file(path);
4253054f218SWarner Losh 		}
4263054f218SWarner Losh 	}
4275983e891SKevin Lo 	closedir(dirp);
4283054f218SWarner Losh }
4293054f218SWarner Losh 
4308b823408SWarner Losh class epv_greater {
4318b823408SWarner Losh public:
432ef370346SEitan Adler 	int operator()(event_proc *const&l1, event_proc *const&l2) const
4338b823408SWarner Losh 	{
4348b823408SWarner Losh 		return (l1->get_priority() > l2->get_priority());
4358b823408SWarner Losh 	}
4368b823408SWarner Losh };
4378b823408SWarner Losh 
4388b823408SWarner Losh void
4398b823408SWarner Losh config::sort_vector(vector<event_proc *> &v)
4408b823408SWarner Losh {
4410c04d185SDimitry Andric 	stable_sort(v.begin(), v.end(), epv_greater());
4428b823408SWarner Losh }
4438b823408SWarner Losh 
4443054f218SWarner Losh void
4453054f218SWarner Losh config::parse(void)
4463054f218SWarner Losh {
4473054f218SWarner Losh 	vector<string>::const_iterator i;
4483054f218SWarner Losh 
4498334958aSJoseph Koshy 	parse_one_file(configfile);
450edee691dSEitan Adler 	for (i = _dir_list.begin(); i != _dir_list.end(); ++i)
4513054f218SWarner Losh 		parse_files_in_dir((*i).c_str());
4528b823408SWarner Losh 	sort_vector(_attach_list);
4538b823408SWarner Losh 	sort_vector(_detach_list);
4548b823408SWarner Losh 	sort_vector(_nomatch_list);
455842ccec5SWarner Losh 	sort_vector(_notify_list);
4563054f218SWarner Losh }
4573054f218SWarner Losh 
4583054f218SWarner Losh void
4591a0cc6b1SPawel Jakub Dawidek config::open_pidfile()
4603054f218SWarner Losh {
4611a0cc6b1SPawel Jakub Dawidek 	pid_t otherpid;
4623054f218SWarner Losh 
4633054f218SWarner Losh 	if (_pidfile == "")
4643054f218SWarner Losh 		return;
4651a0cc6b1SPawel Jakub Dawidek 	pfh = pidfile_open(_pidfile.c_str(), 0600, &otherpid);
4661a0cc6b1SPawel Jakub Dawidek 	if (pfh == NULL) {
4671a0cc6b1SPawel Jakub Dawidek 		if (errno == EEXIST)
4681a0cc6b1SPawel Jakub Dawidek 			errx(1, "devd already running, pid: %d", (int)otherpid);
4691a0cc6b1SPawel Jakub Dawidek 		warn("cannot open pid file");
4701a0cc6b1SPawel Jakub Dawidek 	}
4711a0cc6b1SPawel Jakub Dawidek }
4721a0cc6b1SPawel Jakub Dawidek 
4731a0cc6b1SPawel Jakub Dawidek void
4741a0cc6b1SPawel Jakub Dawidek config::write_pidfile()
4751a0cc6b1SPawel Jakub Dawidek {
4761a0cc6b1SPawel Jakub Dawidek 
4771a0cc6b1SPawel Jakub Dawidek 	pidfile_write(pfh);
4781a0cc6b1SPawel Jakub Dawidek }
4791a0cc6b1SPawel Jakub Dawidek 
4801a0cc6b1SPawel Jakub Dawidek void
481b8f92ce4SWarner Losh config::close_pidfile()
482b8f92ce4SWarner Losh {
483b8f92ce4SWarner Losh 
484b8f92ce4SWarner Losh 	pidfile_close(pfh);
485b8f92ce4SWarner Losh }
486b8f92ce4SWarner Losh 
487b8f92ce4SWarner Losh void
4881a0cc6b1SPawel Jakub Dawidek config::remove_pidfile()
4891a0cc6b1SPawel Jakub Dawidek {
4901a0cc6b1SPawel Jakub Dawidek 
4911a0cc6b1SPawel Jakub Dawidek 	pidfile_remove(pfh);
4923054f218SWarner Losh }
4933054f218SWarner Losh 
4943054f218SWarner Losh void
4953054f218SWarner Losh config::add_attach(int prio, event_proc *p)
4963054f218SWarner Losh {
4973054f218SWarner Losh 	p->set_priority(prio);
4983054f218SWarner Losh 	_attach_list.push_back(p);
4993054f218SWarner Losh }
5003054f218SWarner Losh 
5013054f218SWarner Losh void
5023054f218SWarner Losh config::add_detach(int prio, event_proc *p)
5033054f218SWarner Losh {
5043054f218SWarner Losh 	p->set_priority(prio);
5053054f218SWarner Losh 	_detach_list.push_back(p);
5063054f218SWarner Losh }
5073054f218SWarner Losh 
5083054f218SWarner Losh void
5093054f218SWarner Losh config::add_directory(const char *dir)
5103054f218SWarner Losh {
5113054f218SWarner Losh 	_dir_list.push_back(string(dir));
5123054f218SWarner Losh }
5133054f218SWarner Losh 
5143054f218SWarner Losh void
5153054f218SWarner Losh config::add_nomatch(int prio, event_proc *p)
5163054f218SWarner Losh {
5173054f218SWarner Losh 	p->set_priority(prio);
5183054f218SWarner Losh 	_nomatch_list.push_back(p);
5193054f218SWarner Losh }
5203054f218SWarner Losh 
5213054f218SWarner Losh void
522842ccec5SWarner Losh config::add_notify(int prio, event_proc *p)
523842ccec5SWarner Losh {
524842ccec5SWarner Losh 	p->set_priority(prio);
525842ccec5SWarner Losh 	_notify_list.push_back(p);
526842ccec5SWarner Losh }
527842ccec5SWarner Losh 
528842ccec5SWarner Losh void
5293054f218SWarner Losh config::set_pidfile(const char *fn)
5303054f218SWarner Losh {
5313054f218SWarner Losh 	_pidfile = string(fn);
5323054f218SWarner Losh }
5333054f218SWarner Losh 
5343054f218SWarner Losh void
5353054f218SWarner Losh config::push_var_table()
5363054f218SWarner Losh {
5373054f218SWarner Losh 	var_list *vl;
5383054f218SWarner Losh 
5393054f218SWarner Losh 	vl = new var_list();
5403054f218SWarner Losh 	_var_list_table.push_back(vl);
5415a882d77SWarner Losh 	if (Dflag)
5428b823408SWarner Losh 		fprintf(stderr, "Pushing table\n");
5433054f218SWarner Losh }
5443054f218SWarner Losh 
5453054f218SWarner Losh void
5463054f218SWarner Losh config::pop_var_table()
5473054f218SWarner Losh {
5483054f218SWarner Losh 	delete _var_list_table.back();
5493054f218SWarner Losh 	_var_list_table.pop_back();
5505a882d77SWarner Losh 	if (Dflag)
5518b823408SWarner Losh 		fprintf(stderr, "Popping table\n");
5523054f218SWarner Losh }
5533054f218SWarner Losh 
5543054f218SWarner Losh void
5553054f218SWarner Losh config::set_variable(const char *var, const char *val)
5563054f218SWarner Losh {
5573054f218SWarner Losh 	_var_list_table.back()->set_variable(var, val);
5583054f218SWarner Losh }
5593054f218SWarner Losh 
5603054f218SWarner Losh const string &
5613054f218SWarner Losh config::get_variable(const string &var)
5623054f218SWarner Losh {
5633054f218SWarner Losh 	vector<var_list *>::reverse_iterator i;
5643054f218SWarner Losh 
565edee691dSEitan Adler 	for (i = _var_list_table.rbegin(); i != _var_list_table.rend(); ++i) {
5663054f218SWarner Losh 		if ((*i)->is_set(var))
5678b823408SWarner Losh 			return ((*i)->get_variable(var));
5683054f218SWarner Losh 	}
5693054f218SWarner Losh 	return (var_list::nothing);
5703054f218SWarner Losh }
5713054f218SWarner Losh 
5728b823408SWarner Losh bool
573ef370346SEitan Adler config::is_id_char(char ch) const
5748b823408SWarner Losh {
5758b823408SWarner Losh 	return (ch != '\0' && (isalpha(ch) || isdigit(ch) || ch == '_' ||
5768b823408SWarner Losh 	    ch == '-'));
5778b823408SWarner Losh }
5788b823408SWarner Losh 
5795102ef84SWarner Losh void
5806cabd675SWarner Losh config::expand_one(const char *&src, string &dst)
5813054f218SWarner Losh {
5825102ef84SWarner Losh 	int count;
5835bf08422SUlf Lilleengen 	string buffer;
5845102ef84SWarner Losh 
5858b823408SWarner Losh 	src++;
5865102ef84SWarner Losh 	// $$ -> $
5875102ef84SWarner Losh 	if (*src == '$') {
5886cabd675SWarner Losh 		dst.append(src++, 1);
5895102ef84SWarner Losh 		return;
5905102ef84SWarner Losh 	}
5915102ef84SWarner Losh 
5925102ef84SWarner Losh 	// $(foo) -> $(foo)
5938b823408SWarner Losh 	// Not sure if I want to support this or not, so for now we just pass
5948b823408SWarner Losh 	// it through.
5955102ef84SWarner Losh 	if (*src == '(') {
5966cabd675SWarner Losh 		dst.append("$");
5975102ef84SWarner Losh 		count = 1;
5986cabd675SWarner Losh 		/* If the string ends before ) is matched , return. */
5996cabd675SWarner Losh 		while (count > 0 && *src) {
6005102ef84SWarner Losh 			if (*src == ')')
6015102ef84SWarner Losh 				count--;
6025102ef84SWarner Losh 			else if (*src == '(')
6035102ef84SWarner Losh 				count++;
6046cabd675SWarner Losh 			dst.append(src++, 1);
6055102ef84SWarner Losh 		}
6065102ef84SWarner Losh 		return;
6075102ef84SWarner Losh 	}
6085102ef84SWarner Losh 
6095102ef84SWarner Losh 	// ${^A-Za-z] -> $\1
6105102ef84SWarner Losh 	if (!isalpha(*src)) {
6116cabd675SWarner Losh 		dst.append("$");
6126cabd675SWarner Losh 		dst.append(src++, 1);
6135102ef84SWarner Losh 		return;
6145102ef84SWarner Losh 	}
6155102ef84SWarner Losh 
6165102ef84SWarner Losh 	// $var -> replace with value
6176cabd675SWarner Losh 	do {
6186cabd675SWarner Losh 		buffer.append(src++, 1);
61966ff6821SWarner Losh 	} while (is_id_char(*src));
6205bf08422SUlf Lilleengen 	dst.append(get_variable(buffer.c_str()));
6215102ef84SWarner Losh }
6225102ef84SWarner Losh 
6235102ef84SWarner Losh const string
6245dfc0f6cSIan Lepore config::expand_string(const char *src, const char *prepend, const char *append)
6255102ef84SWarner Losh {
6265dfc0f6cSIan Lepore 	const char *var_at;
6276cabd675SWarner Losh 	string dst;
6285102ef84SWarner Losh 
6295dfc0f6cSIan Lepore 	/*
6305dfc0f6cSIan Lepore 	 * 128 bytes is enough for 2427 of 2438 expansions that happen
6315dfc0f6cSIan Lepore 	 * while parsing config files, as tested on 2013-01-30.
6325dfc0f6cSIan Lepore 	 */
6335dfc0f6cSIan Lepore 	dst.reserve(128);
6345dfc0f6cSIan Lepore 
6355dfc0f6cSIan Lepore 	if (prepend != NULL)
6365dfc0f6cSIan Lepore 		dst = prepend;
6375dfc0f6cSIan Lepore 
6385dfc0f6cSIan Lepore 	for (;;) {
6395dfc0f6cSIan Lepore 		var_at = strchr(src, '$');
6405dfc0f6cSIan Lepore 		if (var_at == NULL) {
6415dfc0f6cSIan Lepore 			dst.append(src);
6425dfc0f6cSIan Lepore 			break;
6435102ef84SWarner Losh 		}
6445dfc0f6cSIan Lepore 		dst.append(src, var_at - src);
6455dfc0f6cSIan Lepore 		src = var_at;
6465dfc0f6cSIan Lepore 		expand_one(src, dst);
6475dfc0f6cSIan Lepore 	}
6485dfc0f6cSIan Lepore 
6495dfc0f6cSIan Lepore 	if (append != NULL)
6505dfc0f6cSIan Lepore 		dst.append(append);
6515102ef84SWarner Losh 
6526cabd675SWarner Losh 	return (dst);
6533054f218SWarner Losh }
6543054f218SWarner Losh 
6558b823408SWarner Losh bool
65611fd1366SEitan Adler config::chop_var(char *&buffer, char *&lhs, char *&rhs) const
6578b823408SWarner Losh {
6588b823408SWarner Losh 	char *walker;
6598b823408SWarner Losh 
6608b823408SWarner Losh 	if (*buffer == '\0')
6618b823408SWarner Losh 		return (false);
6628b823408SWarner Losh 	walker = lhs = buffer;
6638b823408SWarner Losh 	while (is_id_char(*walker))
6648b823408SWarner Losh 		walker++;
6658b823408SWarner Losh 	if (*walker != '=')
6668b823408SWarner Losh 		return (false);
6678b823408SWarner Losh 	walker++;		// skip =
6688b823408SWarner Losh 	if (*walker == '"') {
6698b823408SWarner Losh 		walker++;	// skip "
6708b823408SWarner Losh 		rhs = walker;
6718b823408SWarner Losh 		while (*walker && *walker != '"')
6728b823408SWarner Losh 			walker++;
6738b823408SWarner Losh 		if (*walker != '"')
6748b823408SWarner Losh 			return (false);
6758b823408SWarner Losh 		rhs[-2] = '\0';
6768b823408SWarner Losh 		*walker++ = '\0';
6778b823408SWarner Losh 	} else {
6788b823408SWarner Losh 		rhs = walker;
6798b823408SWarner Losh 		while (*walker && !isspace(*walker))
6808b823408SWarner Losh 			walker++;
6818b823408SWarner Losh 		if (*walker != '\0')
6828b823408SWarner Losh 			*walker++ = '\0';
6838b823408SWarner Losh 		rhs[-1] = '\0';
6848b823408SWarner Losh 	}
685b1ee04b1SWarner Losh 	while (isspace(*walker))
686b1ee04b1SWarner Losh 		walker++;
6878b823408SWarner Losh 	buffer = walker;
6888b823408SWarner Losh 	return (true);
6898b823408SWarner Losh }
6908b823408SWarner Losh 
6918b823408SWarner Losh 
6928b823408SWarner Losh char *
6938b823408SWarner Losh config::set_vars(char *buffer)
6948b823408SWarner Losh {
6958b823408SWarner Losh 	char *lhs;
6968b823408SWarner Losh 	char *rhs;
6978b823408SWarner Losh 
6988b823408SWarner Losh 	while (1) {
6998b823408SWarner Losh 		if (!chop_var(buffer, lhs, rhs))
7008b823408SWarner Losh 			break;
7018b823408SWarner Losh 		set_variable(lhs, rhs);
7028b823408SWarner Losh 	}
7038b823408SWarner Losh 	return (buffer);
7048b823408SWarner Losh }
7058b823408SWarner Losh 
7068b823408SWarner Losh void
7078b823408SWarner Losh config::find_and_execute(char type)
7088b823408SWarner Losh {
7098b823408SWarner Losh 	vector<event_proc *> *l;
7108b823408SWarner Losh 	vector<event_proc *>::const_iterator i;
71194d2d4ebSBrooks Davis 	const char *s;
7128b823408SWarner Losh 
7138b823408SWarner Losh 	switch (type) {
7148b823408SWarner Losh 	default:
7158b823408SWarner Losh 		return;
716842ccec5SWarner Losh 	case notify:
717842ccec5SWarner Losh 		l = &_notify_list;
718842ccec5SWarner Losh 		s = "notify";
719842ccec5SWarner Losh 		break;
7208b823408SWarner Losh 	case nomatch:
7218b823408SWarner Losh 		l = &_nomatch_list;
7228b823408SWarner Losh 		s = "nomatch";
7238b823408SWarner Losh 		break;
7248b823408SWarner Losh 	case attach:
7258b823408SWarner Losh 		l = &_attach_list;
7268b823408SWarner Losh 		s = "attach";
7278b823408SWarner Losh 		break;
7288b823408SWarner Losh 	case detach:
7298b823408SWarner Losh 		l = &_detach_list;
7308b823408SWarner Losh 		s = "detach";
7318b823408SWarner Losh 		break;
7328b823408SWarner Losh 	}
7335a882d77SWarner Losh 	if (Dflag)
7348b823408SWarner Losh 		fprintf(stderr, "Processing %s event\n", s);
735edee691dSEitan Adler 	for (i = l->begin(); i != l->end(); ++i) {
7368b823408SWarner Losh 		if ((*i)->matches(*this)) {
7378b823408SWarner Losh 			(*i)->run(*this);
7388b823408SWarner Losh 			break;
7398b823408SWarner Losh 		}
7408b823408SWarner Losh 	}
7418b823408SWarner Losh 
7428b823408SWarner Losh }
7438b823408SWarner Losh 
7443054f218SWarner Losh 
7453054f218SWarner Losh static void
7468b823408SWarner Losh process_event(char *buffer)
7473054f218SWarner Losh {
7483054f218SWarner Losh 	char type;
7493054f218SWarner Losh 	char *sp;
7503054f218SWarner Losh 
7518b823408SWarner Losh 	sp = buffer + 1;
7525a882d77SWarner Losh 	if (Dflag)
7538b823408SWarner Losh 		fprintf(stderr, "Processing event '%s'\n", buffer);
7543054f218SWarner Losh 	type = *buffer++;
7558b823408SWarner Losh 	cfg.push_var_table();
7568b823408SWarner Losh 	// No match doesn't have a device, and the format is a little
7578b823408SWarner Losh 	// different, so handle it separately.
758842ccec5SWarner Losh 	switch (type) {
759842ccec5SWarner Losh 	case notify:
760842ccec5SWarner Losh 		sp = cfg.set_vars(sp);
761842ccec5SWarner Losh 		break;
762842ccec5SWarner Losh 	case nomatch:
763528d3f79SWarner Losh 		//? at location pnp-info on bus
764528d3f79SWarner Losh 		sp = strchr(sp, ' ');
765528d3f79SWarner Losh 		if (sp == NULL)
766528d3f79SWarner Losh 			return;	/* Can't happen? */
767528d3f79SWarner Losh 		*sp++ = '\0';
7689b6cb520SWarner Losh 		while (isspace(*sp))
7699b6cb520SWarner Losh 			sp++;
770842ccec5SWarner Losh 		if (strncmp(sp, "at ", 3) == 0)
771842ccec5SWarner Losh 			sp += 3;
772842ccec5SWarner Losh 		sp = cfg.set_vars(sp);
7739b6cb520SWarner Losh 		while (isspace(*sp))
7749b6cb520SWarner Losh 			sp++;
775842ccec5SWarner Losh 		if (strncmp(sp, "on ", 3) == 0)
776842ccec5SWarner Losh 			cfg.set_variable("bus", sp + 3);
777842ccec5SWarner Losh 		break;
778842ccec5SWarner Losh 	case attach:	/*FALLTHROUGH*/
779842ccec5SWarner Losh 	case detach:
7808b823408SWarner Losh 		sp = strchr(sp, ' ');
7813054f218SWarner Losh 		if (sp == NULL)
7823054f218SWarner Losh 			return;	/* Can't happen? */
7838b823408SWarner Losh 		*sp++ = '\0';
7848b823408SWarner Losh 		cfg.set_variable("device-name", buffer);
7859b6cb520SWarner Losh 		while (isspace(*sp))
7869b6cb520SWarner Losh 			sp++;
7878b823408SWarner Losh 		if (strncmp(sp, "at ", 3) == 0)
7888b823408SWarner Losh 			sp += 3;
7898b823408SWarner Losh 		sp = cfg.set_vars(sp);
7909b6cb520SWarner Losh 		while (isspace(*sp))
7919b6cb520SWarner Losh 			sp++;
7928b823408SWarner Losh 		if (strncmp(sp, "on ", 3) == 0)
7938b823408SWarner Losh 			cfg.set_variable("bus", sp + 3);
794842ccec5SWarner Losh 		break;
795b1ee04b1SWarner Losh 	}
796b1ee04b1SWarner Losh 
7978b823408SWarner Losh 	cfg.find_and_execute(type);
7988b823408SWarner Losh 	cfg.pop_var_table();
7993054f218SWarner Losh }
8003054f218SWarner Losh 
801251bedd1SWarner Losh int
802251bedd1SWarner Losh create_socket(const char *name)
803251bedd1SWarner Losh {
804251bedd1SWarner Losh 	int fd, slen;
805251bedd1SWarner Losh 	struct sockaddr_un sun;
806251bedd1SWarner Losh 
807251bedd1SWarner Losh 	if ((fd = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0)
808251bedd1SWarner Losh 		err(1, "socket");
809251bedd1SWarner Losh 	bzero(&sun, sizeof(sun));
810251bedd1SWarner Losh 	sun.sun_family = AF_UNIX;
811251bedd1SWarner Losh 	strlcpy(sun.sun_path, name, sizeof(sun.sun_path));
812251bedd1SWarner Losh 	slen = SUN_LEN(&sun);
813251bedd1SWarner Losh 	unlink(name);
814e60fa014SJoe Marcus Clarke 	if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
815e60fa014SJoe Marcus Clarke 	    	err(1, "fcntl");
8165d586d29SDimitry Andric 	if (::bind(fd, (struct sockaddr *) & sun, slen) < 0)
817251bedd1SWarner Losh 		err(1, "bind");
818251bedd1SWarner Losh 	listen(fd, 4);
81983818929SJoe Marcus Clarke 	chown(name, 0, 0);	/* XXX - root.wheel */
820e60fa014SJoe Marcus Clarke 	chmod(name, 0666);
821251bedd1SWarner Losh 	return (fd);
822251bedd1SWarner Losh }
823251bedd1SWarner Losh 
824e1334f93SIan Lepore unsigned int max_clients = 10;	/* Default, can be overriden on cmdline. */
825e1334f93SIan Lepore unsigned int num_clients;
826251bedd1SWarner Losh list<int> clients;
827251bedd1SWarner Losh 
828251bedd1SWarner Losh void
829251bedd1SWarner Losh notify_clients(const char *data, int len)
830251bedd1SWarner Losh {
831e1334f93SIan Lepore 	list<int>::iterator i;
832251bedd1SWarner Losh 
833e1334f93SIan Lepore 	/*
834e1334f93SIan Lepore 	 * Deliver the data to all clients.  Throw clients overboard at the
835e1334f93SIan Lepore 	 * first sign of trouble.  This reaps clients who've died or closed
836e1334f93SIan Lepore 	 * their sockets, and also clients who are alive but failing to keep up
837e1334f93SIan Lepore 	 * (or who are maliciously not reading, to consume buffer space in
838e1334f93SIan Lepore 	 * kernel memory or tie up the limited number of available connections).
839e1334f93SIan Lepore 	 */
840e1334f93SIan Lepore 	for (i = clients.begin(); i != clients.end(); ) {
841e1334f93SIan Lepore 		if (write(*i, data, len) != len) {
842e1334f93SIan Lepore 			--num_clients;
843251bedd1SWarner Losh 			close(*i);
844e1334f93SIan Lepore 			i = clients.erase(i);
845e1334f93SIan Lepore 		} else
846e1334f93SIan Lepore 			++i;
847251bedd1SWarner Losh 	}
848251bedd1SWarner Losh }
849251bedd1SWarner Losh 
850e1334f93SIan Lepore void
851e1334f93SIan Lepore check_clients(void)
852e1334f93SIan Lepore {
853e1334f93SIan Lepore 	int s;
854e1334f93SIan Lepore 	struct pollfd pfd;
855e1334f93SIan Lepore 	list<int>::iterator i;
856e1334f93SIan Lepore 
857e1334f93SIan Lepore 	/*
858e1334f93SIan Lepore 	 * Check all existing clients to see if any of them have disappeared.
859e1334f93SIan Lepore 	 * Normally we reap clients when we get an error trying to send them an
860e1334f93SIan Lepore 	 * event.  This check eliminates the problem of an ever-growing list of
861e1334f93SIan Lepore 	 * zombie clients because we're never writing to them on a system
862e1334f93SIan Lepore 	 * without frequent device-change activity.
863e1334f93SIan Lepore 	 */
864e1334f93SIan Lepore 	pfd.events = 0;
865e1334f93SIan Lepore 	for (i = clients.begin(); i != clients.end(); ) {
866e1334f93SIan Lepore 		pfd.fd = *i;
867e1334f93SIan Lepore 		s = poll(&pfd, 1, 0);
868e1334f93SIan Lepore 		if ((s < 0 && s != EINTR ) ||
869e1334f93SIan Lepore 		    (s > 0 && (pfd.revents & POLLHUP))) {
870e1334f93SIan Lepore 			--num_clients;
871e1334f93SIan Lepore 			close(*i);
872e1334f93SIan Lepore 			i = clients.erase(i);
873e1334f93SIan Lepore 		} else
874e1334f93SIan Lepore 			++i;
875e1334f93SIan Lepore 	}
876251bedd1SWarner Losh }
877251bedd1SWarner Losh 
878251bedd1SWarner Losh void
879251bedd1SWarner Losh new_client(int fd)
880251bedd1SWarner Losh {
881251bedd1SWarner Losh 	int s;
882251bedd1SWarner Losh 
883e1334f93SIan Lepore 	/*
884e1334f93SIan Lepore 	 * First go reap any zombie clients, then accept the connection, and
885e1334f93SIan Lepore 	 * shut down the read side to stop clients from consuming kernel memory
886e1334f93SIan Lepore 	 * by sending large buffers full of data we'll never read.
887e1334f93SIan Lepore 	 */
888e1334f93SIan Lepore 	check_clients();
889251bedd1SWarner Losh 	s = accept(fd, NULL, NULL);
890e1334f93SIan Lepore 	if (s != -1) {
891e1334f93SIan Lepore 		shutdown(s, SHUT_RD);
892251bedd1SWarner Losh 		clients.push_back(s);
893e1334f93SIan Lepore 		++num_clients;
894e1334f93SIan Lepore 	}
895251bedd1SWarner Losh }
896251bedd1SWarner Losh 
8973054f218SWarner Losh static void
8983054f218SWarner Losh event_loop(void)
8993054f218SWarner Losh {
9003054f218SWarner Losh 	int rv;
9013054f218SWarner Losh 	int fd;
9023054f218SWarner Losh 	char buffer[DEVCTL_MAXBUF];
9035a882d77SWarner Losh 	int once = 0;
904251bedd1SWarner Losh 	int server_fd, max_fd;
905e1334f93SIan Lepore 	int accepting;
9065a882d77SWarner Losh 	timeval tv;
9075a882d77SWarner Losh 	fd_set fds;
9083054f218SWarner Losh 
909901610f4SPawel Jakub Dawidek 	fd = open(PATH_DEVCTL, O_RDONLY | O_CLOEXEC);
9103054f218SWarner Losh 	if (fd == -1)
911251bedd1SWarner Losh 		err(1, "Can't open devctl device %s", PATH_DEVCTL);
912251bedd1SWarner Losh 	server_fd = create_socket(PIPE);
913e1334f93SIan Lepore 	accepting = 1;
914251bedd1SWarner Losh 	max_fd = max(fd, server_fd) + 1;
915*67ae3bf1SEitan Adler 	while (!romeo_must_die) {
9165a882d77SWarner Losh 		if (!once && !dflag && !nflag) {
9175a882d77SWarner Losh 			// Check to see if we have any events pending.
9185a882d77SWarner Losh 			tv.tv_sec = 0;
9195a882d77SWarner Losh 			tv.tv_usec = 0;
9205a882d77SWarner Losh 			FD_ZERO(&fds);
9215a882d77SWarner Losh 			FD_SET(fd, &fds);
9225a882d77SWarner Losh 			rv = select(fd + 1, &fds, &fds, &fds, &tv);
9235a882d77SWarner Losh 			// No events -> we've processed all pending events
924f3059505SWarner Losh 			if (rv == 0) {
9255a882d77SWarner Losh 				if (Dflag)
9265a882d77SWarner Losh 					fprintf(stderr, "Calling daemon\n");
9271a0cc6b1SPawel Jakub Dawidek 				cfg.remove_pidfile();
9281a0cc6b1SPawel Jakub Dawidek 				cfg.open_pidfile();
9295a882d77SWarner Losh 				daemon(0, 0);
9301a0cc6b1SPawel Jakub Dawidek 				cfg.write_pidfile();
9315a882d77SWarner Losh 				once++;
9325a882d77SWarner Losh 			}
9335a882d77SWarner Losh 		}
934e1334f93SIan Lepore 		/*
935e1334f93SIan Lepore 		 * When we've already got the max number of clients, stop
936e1334f93SIan Lepore 		 * accepting new connections (don't put server_fd in the set),
937e1334f93SIan Lepore 		 * shrink the accept() queue to reject connections quickly, and
938e1334f93SIan Lepore 		 * poll the existing clients more often, so that we notice more
939e1334f93SIan Lepore 		 * quickly when any of them disappear to free up client slots.
940e1334f93SIan Lepore 		 */
941251bedd1SWarner Losh 		FD_ZERO(&fds);
942251bedd1SWarner Losh 		FD_SET(fd, &fds);
943e1334f93SIan Lepore 		if (num_clients < max_clients) {
944e1334f93SIan Lepore 			if (!accepting) {
945e1334f93SIan Lepore 				listen(server_fd, max_clients);
946e1334f93SIan Lepore 				accepting = 1;
947e1334f93SIan Lepore 			}
948251bedd1SWarner Losh 			FD_SET(server_fd, &fds);
949e1334f93SIan Lepore 			tv.tv_sec = 60;
950e1334f93SIan Lepore 			tv.tv_usec = 0;
951e1334f93SIan Lepore 		} else {
952e1334f93SIan Lepore 			if (accepting) {
953e1334f93SIan Lepore 				listen(server_fd, 0);
954e1334f93SIan Lepore 				accepting = 0;
955e1334f93SIan Lepore 			}
956e1334f93SIan Lepore 			tv.tv_sec = 2;
957e1334f93SIan Lepore 			tv.tv_usec = 0;
958e1334f93SIan Lepore 		}
959e1334f93SIan Lepore 		rv = select(max_fd, &fds, NULL, NULL, &tv);
960251bedd1SWarner Losh 		if (rv == -1) {
961251bedd1SWarner Losh 			if (errno == EINTR)
962251bedd1SWarner Losh 				continue;
963251bedd1SWarner Losh 			err(1, "select");
964e1334f93SIan Lepore 		} else if (rv == 0)
965e1334f93SIan Lepore 			check_clients();
966251bedd1SWarner Losh 		if (FD_ISSET(fd, &fds)) {
9673054f218SWarner Losh 			rv = read(fd, buffer, sizeof(buffer) - 1);
9683054f218SWarner Losh 			if (rv > 0) {
969251bedd1SWarner Losh 				notify_clients(buffer, rv);
9703054f218SWarner Losh 				buffer[rv] = '\0';
9713054f218SWarner Losh 				while (buffer[--rv] == '\n')
9723054f218SWarner Losh 					buffer[rv] = '\0';
9733054f218SWarner Losh 				process_event(buffer);
9743054f218SWarner Losh 			} else if (rv < 0) {
9753054f218SWarner Losh 				if (errno != EINTR)
9763054f218SWarner Losh 					break;
9773054f218SWarner Losh 			} else {
9783054f218SWarner Losh 				/* EOF */
9793054f218SWarner Losh 				break;
9803054f218SWarner Losh 			}
9813054f218SWarner Losh 		}
982251bedd1SWarner Losh 		if (FD_ISSET(server_fd, &fds))
983251bedd1SWarner Losh 			new_client(server_fd);
984251bedd1SWarner Losh 	}
9853054f218SWarner Losh 	close(fd);
9863054f218SWarner Losh }
9873054f218SWarner Losh 
9883054f218SWarner Losh /*
9893054f218SWarner Losh  * functions that the parser uses.
9903054f218SWarner Losh  */
9913054f218SWarner Losh void
9923054f218SWarner Losh add_attach(int prio, event_proc *p)
9933054f218SWarner Losh {
9943054f218SWarner Losh 	cfg.add_attach(prio, p);
9953054f218SWarner Losh }
9963054f218SWarner Losh 
9973054f218SWarner Losh void
9983054f218SWarner Losh add_detach(int prio, event_proc *p)
9993054f218SWarner Losh {
10003054f218SWarner Losh 	cfg.add_detach(prio, p);
10013054f218SWarner Losh }
10023054f218SWarner Losh 
10033054f218SWarner Losh void
10043054f218SWarner Losh add_directory(const char *dir)
10053054f218SWarner Losh {
10063054f218SWarner Losh 	cfg.add_directory(dir);
10073054f218SWarner Losh 	free(const_cast<char *>(dir));
10083054f218SWarner Losh }
10093054f218SWarner Losh 
10103054f218SWarner Losh void
10113054f218SWarner Losh add_nomatch(int prio, event_proc *p)
10123054f218SWarner Losh {
10133054f218SWarner Losh 	cfg.add_nomatch(prio, p);
10143054f218SWarner Losh }
10153054f218SWarner Losh 
1016842ccec5SWarner Losh void
1017842ccec5SWarner Losh add_notify(int prio, event_proc *p)
1018842ccec5SWarner Losh {
1019842ccec5SWarner Losh 	cfg.add_notify(prio, p);
1020842ccec5SWarner Losh }
1021842ccec5SWarner Losh 
10223054f218SWarner Losh event_proc *
10233054f218SWarner Losh add_to_event_proc(event_proc *ep, eps *eps)
10243054f218SWarner Losh {
10253054f218SWarner Losh 	if (ep == NULL)
10263054f218SWarner Losh 		ep = new event_proc();
10273054f218SWarner Losh 	ep->add(eps);
10283054f218SWarner Losh 	return (ep);
10293054f218SWarner Losh }
10303054f218SWarner Losh 
10313054f218SWarner Losh eps *
10323054f218SWarner Losh new_action(const char *cmd)
10333054f218SWarner Losh {
10343054f218SWarner Losh 	eps *e = new action(cmd);
10353054f218SWarner Losh 	free(const_cast<char *>(cmd));
10363054f218SWarner Losh 	return (e);
10373054f218SWarner Losh }
10383054f218SWarner Losh 
10393054f218SWarner Losh eps *
10403054f218SWarner Losh new_match(const char *var, const char *re)
10413054f218SWarner Losh {
10425102ef84SWarner Losh 	eps *e = new match(cfg, var, re);
10433054f218SWarner Losh 	free(const_cast<char *>(var));
10443054f218SWarner Losh 	free(const_cast<char *>(re));
10453054f218SWarner Losh 	return (e);
10463054f218SWarner Losh }
10473054f218SWarner Losh 
1048cd70782bSWarner Losh eps *
1049cd70782bSWarner Losh new_media(const char *var, const char *re)
1050cd70782bSWarner Losh {
1051cd70782bSWarner Losh 	eps *e = new media(cfg, var, re);
1052cd70782bSWarner Losh 	free(const_cast<char *>(var));
1053cd70782bSWarner Losh 	free(const_cast<char *>(re));
1054cd70782bSWarner Losh 	return (e);
1055cd70782bSWarner Losh }
1056cd70782bSWarner Losh 
10573054f218SWarner Losh void
10583054f218SWarner Losh set_pidfile(const char *name)
10593054f218SWarner Losh {
10603054f218SWarner Losh 	cfg.set_pidfile(name);
10613054f218SWarner Losh 	free(const_cast<char *>(name));
10623054f218SWarner Losh }
10633054f218SWarner Losh 
10643054f218SWarner Losh void
10653054f218SWarner Losh set_variable(const char *var, const char *val)
10663054f218SWarner Losh {
10673054f218SWarner Losh 	cfg.set_variable(var, val);
10683054f218SWarner Losh 	free(const_cast<char *>(var));
10693054f218SWarner Losh 	free(const_cast<char *>(val));
10703054f218SWarner Losh }
10713054f218SWarner Losh 
10723054f218SWarner Losh 
10733054f218SWarner Losh 
10743054f218SWarner Losh static void
10753054f218SWarner Losh gensighand(int)
10763054f218SWarner Losh {
1077fcdcaa88SEitan Adler 	romeo_must_die = 1;
10783054f218SWarner Losh }
10793054f218SWarner Losh 
10803054f218SWarner Losh static void
10813054f218SWarner Losh usage()
10823054f218SWarner Losh {
1083e1334f93SIan Lepore 	fprintf(stderr, "usage: %s [-Ddn] [-l connlimit] [-f file]\n",
1084e1334f93SIan Lepore 	    getprogname());
10853054f218SWarner Losh 	exit(1);
10863054f218SWarner Losh }
10873054f218SWarner Losh 
10889c180898SWarner Losh static void
10899c180898SWarner Losh check_devd_enabled()
10909c180898SWarner Losh {
10919c180898SWarner Losh 	int val = 0;
10929c180898SWarner Losh 	size_t len;
10939c180898SWarner Losh 
10949c180898SWarner Losh 	len = sizeof(val);
109579f92e25SWarner Losh 	if (sysctlbyname(SYSCTL, &val, &len, NULL, 0) != 0)
10969c180898SWarner Losh 		errx(1, "devctl sysctl missing from kernel!");
10979c180898SWarner Losh 	if (val) {
10989c180898SWarner Losh 		warnx("Setting " SYSCTL " to 0");
10999c180898SWarner Losh 		val = 0;
11009c180898SWarner Losh 		sysctlbyname(SYSCTL, NULL, NULL, &val, sizeof(val));
11019c180898SWarner Losh 	}
11029c180898SWarner Losh }
11039c180898SWarner Losh 
11043054f218SWarner Losh /*
11053054f218SWarner Losh  * main
11063054f218SWarner Losh  */
11073054f218SWarner Losh int
11083054f218SWarner Losh main(int argc, char **argv)
11093054f218SWarner Losh {
11103054f218SWarner Losh 	int ch;
11113054f218SWarner Losh 
11129c180898SWarner Losh 	check_devd_enabled();
1113e1334f93SIan Lepore 	while ((ch = getopt(argc, argv, "Ddf:l:n")) != -1) {
11143054f218SWarner Losh 		switch (ch) {
11155a882d77SWarner Losh 		case 'D':
11165a882d77SWarner Losh 			Dflag++;
11175a882d77SWarner Losh 			break;
11183054f218SWarner Losh 		case 'd':
11193054f218SWarner Losh 			dflag++;
11203054f218SWarner Losh 			break;
11218334958aSJoseph Koshy 		case 'f':
11228334958aSJoseph Koshy 			configfile = optarg;
11238334958aSJoseph Koshy 			break;
1124e1334f93SIan Lepore 		case 'l':
1125e1334f93SIan Lepore 			max_clients = MAX(1, strtoul(optarg, NULL, 0));
1126e1334f93SIan Lepore 			break;
11275a882d77SWarner Losh 		case 'n':
11285a882d77SWarner Losh 			nflag++;
11295a882d77SWarner Losh 			break;
11303054f218SWarner Losh 		default:
11313054f218SWarner Losh 			usage();
11323054f218SWarner Losh 		}
11333054f218SWarner Losh 	}
11343054f218SWarner Losh 
11353054f218SWarner Losh 	cfg.parse();
1136fd6a8f23SWarner Losh 	if (!dflag && nflag) {
11371a0cc6b1SPawel Jakub Dawidek 		cfg.open_pidfile();
11383054f218SWarner Losh 		daemon(0, 0);
11391a0cc6b1SPawel Jakub Dawidek 		cfg.write_pidfile();
1140fd6a8f23SWarner Losh 	}
1141f32a7686SWarner Losh 	signal(SIGPIPE, SIG_IGN);
11423054f218SWarner Losh 	signal(SIGHUP, gensighand);
11433054f218SWarner Losh 	signal(SIGINT, gensighand);
11443054f218SWarner Losh 	signal(SIGTERM, gensighand);
11453054f218SWarner Losh 	event_loop();
11463054f218SWarner Losh 	return (0);
11473054f218SWarner Losh }
1148