xref: /dragonfly/sbin/devd/devd.cc (revision 9f7604d7)
1 /*-
2  * Copyright (c) 2002-2010 M. Warner Losh.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sbin/devd/devd.cc,v 1.33 2006/09/17 22:49:26 ru Exp $
27  * $DragonFly: src/sbin/devd/devd.cc,v 1.1 2008/10/03 00:26:21 hasso Exp $
28  */
29 
30 /*
31  * DEVD control daemon.
32  */
33 
34 // TODO list:
35 //	o devd.conf and devd man pages need a lot of help:
36 //	  - devd needs to document the unix domain socket
37 //	  - devd.conf needs more details on the supported statements.
38 
39 #include <sys/param.h>
40 #include <sys/socket.h>
41 #include <sys/stat.h>
42 #include <sys/sysctl.h>
43 #include <sys/types.h>
44 #include <sys/un.h>
45 
46 #include <cctype>
47 #include <cerrno>
48 #include <csignal>
49 #include <cstdlib>
50 #include <cstdio>
51 #include <cstring>
52 
53 #include <dirent.h>
54 #include <err.h>
55 #include <fcntl.h>
56 #include <libutil.h>
57 #include <regex.h>
58 #include <unistd.h>
59 
60 #include <algorithm>
61 #include <map>
62 #include <string>
63 #include <list>
64 #include <vector>
65 
66 #include "devd.h"		/* C compatible definitions */
67 #include "devd.hh"		/* C++ class definitions */
68 
69 #define PIPE "/var/run/devd.pipe"
70 #define CF "/etc/devd.conf"
71 #define SYSCTL "hw.bus.devctl_disable"
72 
73 using namespace std;
74 
75 extern FILE *yyin;
76 extern int lineno;
77 
78 static const char notify = '!';
79 static const char nomatch = '?';
80 static const char attach = '+';
81 static const char detach = '-';
82 
83 int Dflag;
84 int dflag;
85 int nflag;
86 static volatile sig_atomic_t romeo_must_die = 0;
87 
88 static const char *configfile = CF;
89 
90 static void event_loop(void);
91 static void usage(void);
92 
93 template <class T> void
94 delete_and_clear(vector<T *> &v)
95 {
96 	typename vector<T *>::const_iterator i;
97 
98 	for (i = v.begin(); i != v.end(); ++i)
99 		delete *i;
100 	v.clear();
101 }
102 
103 config cfg;
104 
105 event_proc::event_proc() : _prio(-1)
106 {
107 	// nothing
108 }
109 
110 event_proc::~event_proc()
111 {
112 	delete_and_clear(_epsvec);
113 }
114 
115 void
116 event_proc::add(eps *eps)
117 {
118 	_epsvec.push_back(eps);
119 }
120 
121 bool
122 event_proc::matches(config &c) const
123 {
124 	vector<eps *>::const_iterator i;
125 
126 	for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
127 		if (!(*i)->do_match(c))
128 			return (false);
129 	return (true);
130 }
131 
132 bool
133 event_proc::run(config &c) const
134 {
135 	vector<eps *>::const_iterator i;
136 
137 	for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
138 		if (!(*i)->do_action(c))
139 			return (false);
140 	return (true);
141 }
142 
143 action::action(const char *cmd)
144 	: _cmd(cmd)
145 {
146 	// nothing
147 }
148 
149 action::~action()
150 {
151 	// nothing
152 }
153 
154 bool
155 action::do_action(config &c)
156 {
157 	string s = c.expand_string(_cmd);
158 	if (Dflag)
159 		fprintf(stderr, "Executing '%s'\n", s.c_str());
160 	::system(s.c_str());
161 	return (true);
162 }
163 
164 match::match(config &c, const char *var, const char *re)
165 	: _var(var), _re("^")
166 {
167 	_re.append(c.expand_string(string(re)));
168 	_re.append("$");
169 	regcomp(&_regex, _re.c_str(), REG_EXTENDED | REG_NOSUB | REG_ICASE);
170 }
171 
172 match::~match()
173 {
174 	regfree(&_regex);
175 }
176 
177 bool
178 match::do_match(config &c)
179 {
180 	const string &value = c.get_variable(_var);
181 	bool retval;
182 
183 	if (Dflag)
184 		fprintf(stderr, "Testing %s=%s against %s\n", _var.c_str(),
185 		    value.c_str(), _re.c_str());
186 
187 	retval = (regexec(&_regex, value.c_str(), 0, NULL, 0) == 0);
188 	return retval;
189 }
190 
191 #include <sys/sockio.h>
192 #include <net/if.h>
193 #include <net/if_media.h>
194 
195 media::media(config &, const char *var, const char *type)
196 	: _var(var), _type(-1)
197 {
198 	static struct ifmedia_description media_types[] = {
199 		{ IFM_ETHER,		"Ethernet" },
200 		{ IFM_IEEE80211,	"802.11" },
201 		{ IFM_ATM,		"ATM" },
202 		{ IFM_CARP,		"CARP" },
203 		{ -1,			"unknown" },
204 		{ 0, NULL },
205 	};
206 	for (int i = 0; media_types[i].ifmt_string != NULL; ++i)
207 		if (strcasecmp(type, media_types[i].ifmt_string) == 0) {
208 			_type = media_types[i].ifmt_word;
209 			break;
210 		}
211 }
212 
213 media::~media()
214 {
215 }
216 
217 bool
218 media::do_match(config &c)
219 {
220 	string value;
221 	struct ifmediareq ifmr;
222 	bool retval;
223 	int s;
224 
225 	// Since we can be called from both a device attach/detach
226 	// context where device-name is defined and what we want,
227 	// as well as from a link status context, where subsystem is
228 	// the name of interest, first try device-name and fall back
229 	// to subsystem if none exists.
230 	value = c.get_variable("device-name");
231 	if (value.empty())
232 		value = c.get_variable("subsystem");
233 	if (Dflag)
234 		fprintf(stderr, "Testing media type of %s against 0x%x\n",
235 		    value.c_str(), _type);
236 
237 	retval = false;
238 
239 	s = socket(PF_INET, SOCK_DGRAM, 0);
240 	if (s >= 0) {
241 		memset(&ifmr, 0, sizeof(ifmr));
242 		strncpy(ifmr.ifm_name, value.c_str(), sizeof(ifmr.ifm_name));
243 
244 		if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0 &&
245 		    ifmr.ifm_status & IFM_AVALID) {
246 			if (Dflag)
247 				fprintf(stderr, "%s has media type 0x%x\n",
248 				    value.c_str(), IFM_TYPE(ifmr.ifm_active));
249 			retval = (IFM_TYPE(ifmr.ifm_active) == _type);
250 		} else if (_type == -1) {
251 			if (Dflag)
252 				fprintf(stderr, "%s has unknown media type\n",
253 				    value.c_str());
254 			retval = true;
255 		}
256 		close(s);
257 	}
258 
259 	return retval;
260 }
261 
262 const string var_list::bogus = "_$_$_$_$_B_O_G_U_S_$_$_$_$_";
263 const string var_list::nothing = "";
264 
265 const string &
266 var_list::get_variable(const string &var) const
267 {
268 	map<string, string>::const_iterator i;
269 
270 	i = _vars.find(var);
271 	if (i == _vars.end())
272 		return (var_list::bogus);
273 	return (i->second);
274 }
275 
276 bool
277 var_list::is_set(const string &var) const
278 {
279 	return (_vars.find(var) != _vars.end());
280 }
281 
282 void
283 var_list::set_variable(const string &var, const string &val)
284 {
285 	if (Dflag)
286 		fprintf(stderr, "setting %s=%s\n", var.c_str(), val.c_str());
287 	_vars[var] = val;
288 }
289 
290 void
291 config::reset(void)
292 {
293 	_dir_list.clear();
294 	delete_and_clear(_var_list_table);
295 	delete_and_clear(_attach_list);
296 	delete_and_clear(_detach_list);
297 	delete_and_clear(_nomatch_list);
298 	delete_and_clear(_notify_list);
299 }
300 
301 void
302 config::parse_one_file(const char *fn)
303 {
304 	if (Dflag)
305 		fprintf(stderr, "Parsing %s\n", fn);
306 	yyin = fopen(fn, "r");
307 	if (yyin == NULL)
308 		err(1, "Cannot open config file %s", fn);
309 	lineno = 1;
310 	if (yyparse() != 0)
311 		errx(1, "Cannot parse %s at line %d", fn, lineno);
312 	fclose(yyin);
313 }
314 
315 void
316 config::parse_files_in_dir(const char *dirname)
317 {
318 	DIR *dirp;
319 	struct dirent *dp;
320 	char path[PATH_MAX];
321 
322 	if (Dflag)
323 		fprintf(stderr, "Parsing files in %s\n", dirname);
324 	dirp = opendir(dirname);
325 	if (dirp == NULL)
326 		return;
327 	readdir(dirp);		/* Skip . */
328 	readdir(dirp);		/* Skip .. */
329 	while ((dp = readdir(dirp)) != NULL) {
330 		if (strcmp(dp->d_name + dp->d_namlen - 5, ".conf") == 0) {
331 			snprintf(path, sizeof(path), "%s/%s",
332 			    dirname, dp->d_name);
333 			parse_one_file(path);
334 		}
335 	}
336 }
337 
338 class epv_greater {
339 public:
340 	int operator()(event_proc *const&l1, event_proc *const&l2) const
341 	{
342 		return (l1->get_priority() > l2->get_priority());
343 	}
344 };
345 
346 void
347 config::sort_vector(vector<event_proc *> &v)
348 {
349 	sort(v.begin(), v.end(), epv_greater());
350 }
351 
352 void
353 config::parse(void)
354 {
355 	vector<string>::const_iterator i;
356 
357 	parse_one_file(configfile);
358 	for (i = _dir_list.begin(); i != _dir_list.end(); ++i)
359 		parse_files_in_dir((*i).c_str());
360 	sort_vector(_attach_list);
361 	sort_vector(_detach_list);
362 	sort_vector(_nomatch_list);
363 	sort_vector(_notify_list);
364 }
365 
366 void
367 config::open_pidfile()
368 {
369 	if (pidfile(NULL))
370 		errx(1, "devd already running");
371 }
372 
373 void
374 config::add_attach(int prio, event_proc *p)
375 {
376 	p->set_priority(prio);
377 	_attach_list.push_back(p);
378 }
379 
380 void
381 config::add_detach(int prio, event_proc *p)
382 {
383 	p->set_priority(prio);
384 	_detach_list.push_back(p);
385 }
386 
387 void
388 config::add_directory(const char *dir)
389 {
390 	_dir_list.push_back(string(dir));
391 }
392 
393 void
394 config::add_nomatch(int prio, event_proc *p)
395 {
396 	p->set_priority(prio);
397 	_nomatch_list.push_back(p);
398 }
399 
400 void
401 config::add_notify(int prio, event_proc *p)
402 {
403 	p->set_priority(prio);
404 	_notify_list.push_back(p);
405 }
406 
407 void
408 config::set_pidfile(const char *fn)
409 {
410 	_pidfile = fn;
411 }
412 
413 void
414 config::push_var_table()
415 {
416 	var_list *vl;
417 
418 	vl = new var_list();
419 	_var_list_table.push_back(vl);
420 	if (Dflag)
421 		fprintf(stderr, "Pushing table\n");
422 }
423 
424 void
425 config::pop_var_table()
426 {
427 	delete _var_list_table.back();
428 	_var_list_table.pop_back();
429 	if (Dflag)
430 		fprintf(stderr, "Popping table\n");
431 }
432 
433 void
434 config::set_variable(const char *var, const char *val)
435 {
436 	_var_list_table.back()->set_variable(var, val);
437 }
438 
439 const string &
440 config::get_variable(const string &var)
441 {
442 	vector<var_list *>::reverse_iterator i;
443 
444 	for (i = _var_list_table.rbegin(); i != _var_list_table.rend(); ++i) {
445 		if ((*i)->is_set(var))
446 			return ((*i)->get_variable(var));
447 	}
448 	return (var_list::nothing);
449 }
450 
451 bool
452 config::is_id_char(char ch) const
453 {
454 	return (ch != '\0' && (isalpha(ch) || isdigit(ch) || ch == '_' ||
455 	    ch == '-'));
456 }
457 
458 void
459 config::expand_one(const char *&src, string &dst)
460 {
461 	int count;
462 	string buffer, varstr;
463 
464 	src++;
465 	// $$ -> $
466 	if (*src == '$') {
467 		dst += *src++;
468 		return;
469 	}
470 
471 	// $(foo) -> $(foo)
472 	// Not sure if I want to support this or not, so for now we just pass
473 	// it through.
474 	if (*src == '(') {
475 		dst += '$';
476 		count = 1;
477 		/* If the string ends before ) is matched , return. */
478 		while (count > 0 && *src) {
479 			if (*src == ')')
480 				count--;
481 			else if (*src == '(')
482 				count++;
483 			dst += *src++;
484 		}
485 		return;
486 	}
487 
488 	// $[^A-Za-z] -> $\1
489 	if (!isalpha(*src)) {
490 		dst += '$';
491 		dst += *src++;
492 		return;
493 	}
494 
495 	// $var -> replace with value
496 	do {
497 		buffer += *src++;
498 	} while (is_id_char(*src));
499 	buffer.append("", 1);
500 	varstr = get_variable(buffer.c_str());
501 	dst.append(varstr);
502 }
503 
504 const string
505 config::expand_string(const string &s)
506 {
507 	const char *src;
508 	string dst;
509 
510 	src = s.c_str();
511 	while (*src) {
512 		if (*src == '$')
513 			expand_one(src, dst);
514 		else
515 			dst.append(src++, 1);
516 	}
517 	dst.append("", 1);
518 
519 	return (dst);
520 }
521 
522 bool
523 config::chop_var(char *&buffer, char *&lhs, char *&rhs) const
524 {
525 	char *walker;
526 
527 	if (*buffer == '\0')
528 		return (false);
529 	walker = lhs = buffer;
530 	while (is_id_char(*walker))
531 		walker++;
532 	if (*walker != '=')
533 		return (false);
534 	walker++;		// skip =
535 	if (*walker == '"') {
536 		walker++;	// skip "
537 		rhs = walker;
538 		while (*walker && *walker != '"')
539 			walker++;
540 		if (*walker != '"')
541 			return (false);
542 		rhs[-2] = '\0';
543 		*walker++ = '\0';
544 	} else {
545 		rhs = walker;
546 		while (*walker && !isspace(*walker))
547 			walker++;
548 		if (*walker != '\0')
549 			*walker++ = '\0';
550 		rhs[-1] = '\0';
551 	}
552 	while (isspace(*walker))
553 		walker++;
554 	buffer = walker;
555 	return (true);
556 }
557 
558 
559 char *
560 config::set_vars(char *buffer)
561 {
562 	char *lhs;
563 	char *rhs;
564 
565 	while (1) {
566 		if (!chop_var(buffer, lhs, rhs))
567 			break;
568 		set_variable(lhs, rhs);
569 	}
570 	return (buffer);
571 }
572 
573 void
574 config::find_and_execute(char type)
575 {
576 	vector<event_proc *> *l;
577 	vector<event_proc *>::const_iterator i;
578 	const char *s;
579 
580 	switch (type) {
581 	default:
582 		return;
583 	case notify:
584 		l = &_notify_list;
585 		s = "notify";
586 		break;
587 	case nomatch:
588 		l = &_nomatch_list;
589 		s = "nomatch";
590 		break;
591 	case attach:
592 		l = &_attach_list;
593 		s = "attach";
594 		break;
595 	case detach:
596 		l = &_detach_list;
597 		s = "detach";
598 		break;
599 	}
600 	if (Dflag)
601 		fprintf(stderr, "Processing %s event\n", s);
602 	for (i = l->begin(); i != l->end(); ++i) {
603 		if ((*i)->matches(*this)) {
604 			(*i)->run(*this);
605 			break;
606 		}
607 	}
608 
609 }
610 
611 
612 static void
613 process_event(char *buffer)
614 {
615 	char type;
616 	char *sp;
617 
618 	sp = buffer + 1;
619 	if (Dflag)
620 		fprintf(stderr, "Processing event '%s'\n", buffer);
621 	type = *buffer++;
622 	cfg.push_var_table();
623 	// No match doesn't have a device, and the format is a little
624 	// different, so handle it separately.
625 	switch (type) {
626 	case notify:
627 		sp = cfg.set_vars(sp);
628 		break;
629 	case nomatch:
630 		//? at location pnp-info on bus
631 		sp = strchr(sp, ' ');
632 		if (sp == NULL)
633 			return;	/* Can't happen? */
634 		*sp++ = '\0';
635 		if (strncmp(sp, "at ", 3) == 0)
636 			sp += 3;
637 		sp = cfg.set_vars(sp);
638 		if (strncmp(sp, "on ", 3) == 0)
639 			cfg.set_variable("bus", sp + 3);
640 		break;
641 	case attach:	/*FALLTHROUGH*/
642 	case detach:
643 		sp = strchr(sp, ' ');
644 		if (sp == NULL)
645 			return;	/* Can't happen? */
646 		*sp++ = '\0';
647 		cfg.set_variable("device-name", buffer);
648 		if (strncmp(sp, "at ", 3) == 0)
649 			sp += 3;
650 		sp = cfg.set_vars(sp);
651 		if (strncmp(sp, "on ", 3) == 0)
652 			cfg.set_variable("bus", sp + 3);
653 		break;
654 	}
655 
656 	cfg.find_and_execute(type);
657 	cfg.pop_var_table();
658 }
659 
660 int
661 create_socket(const char *name)
662 {
663 	int fd, slen;
664 	struct sockaddr_un sun;
665 
666 	if ((fd = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0)
667 		err(1, "socket");
668 	bzero(&sun, sizeof(sun));
669 	sun.sun_family = AF_UNIX;
670 	strlcpy(sun.sun_path, name, sizeof(sun.sun_path));
671 	slen = SUN_LEN(&sun);
672 	unlink(name);
673 	if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
674 	    	err(1, "fcntl");
675 	if (::bind(fd, (struct sockaddr *) & sun, slen) < 0)
676 		err(1, "bind");
677 	listen(fd, 4);
678 	chown(name, 0, 0);	/* XXX - root.wheel */
679 	chmod(name, 0666);
680 	return (fd);
681 }
682 
683 list<int> clients;
684 
685 void
686 notify_clients(const char *data, int len)
687 {
688 	list<int> bad;
689 	list<int>::const_iterator i;
690 
691 	for (i = clients.begin(); i != clients.end(); ++i) {
692 		if (write(*i, data, len) <= 0) {
693 			bad.push_back(*i);
694 			close(*i);
695 		}
696 	}
697 
698 	for (i = bad.begin(); i != bad.end(); ++i)
699 		clients.erase(find(clients.begin(), clients.end(), *i));
700 }
701 
702 void
703 new_client(int fd)
704 {
705 	int s;
706 
707 	s = accept(fd, NULL, NULL);
708 	if (s != -1)
709 		clients.push_back(s);
710 }
711 
712 static void
713 event_loop(void)
714 {
715 	int rv;
716 	int fd;
717 	char buffer[DEVCTL_MAXBUF];
718 	int once = 0;
719 	int server_fd, max_fd;
720 	timeval tv;
721 	fd_set fds;
722 
723 	fd = open(PATH_DEVCTL, O_RDONLY);
724 	if (fd == -1)
725 		err(1, "Can't open devctl device %s", PATH_DEVCTL);
726 	if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0)
727 		err(1, "Can't set close-on-exec flag on devctl");
728 	server_fd = create_socket(PIPE);
729 	max_fd = max(fd, server_fd) + 1;
730 	while (!romeo_must_die) {
731 		if (!once && !dflag && !nflag) {
732 			// Check to see if we have any events pending.
733 			tv.tv_sec = 0;
734 			tv.tv_usec = 0;
735 			FD_ZERO(&fds);
736 			FD_SET(fd, &fds);
737 			rv = select(fd + 1, &fds, NULL, NULL, &tv);
738 			// No events -> we've processed all pending events
739 			if (rv == 0) {
740 				if (Dflag)
741 					fprintf(stderr, "Calling daemon\n");
742 				daemon(0, 0);
743 				cfg.open_pidfile();
744 				once++;
745 			}
746 		}
747 		FD_ZERO(&fds);
748 		FD_SET(fd, &fds);
749 		FD_SET(server_fd, &fds);
750 		rv = select(max_fd, &fds, NULL, NULL, NULL);
751 		if (rv == -1) {
752 			if (errno == EINTR)
753 				continue;
754 			err(1, "select");
755 		}
756 		if (FD_ISSET(fd, &fds)) {
757 			rv = read(fd, buffer, sizeof(buffer) - 1);
758 			if (rv > 0) {
759 				notify_clients(buffer, rv);
760 				buffer[rv] = '\0';
761 				while (buffer[--rv] == '\n')
762 					buffer[rv] = '\0';
763 				process_event(buffer);
764 			} else if (rv < 0) {
765 				if (errno != EINTR)
766 					break;
767 			} else {
768 				/* EOF */
769 				break;
770 			}
771 		}
772 		if (FD_ISSET(server_fd, &fds))
773 			new_client(server_fd);
774 	}
775 	close(fd);
776 }
777 
778 /*
779  * functions that the parser uses.
780  */
781 void
782 add_attach(int prio, event_proc *p)
783 {
784 	cfg.add_attach(prio, p);
785 }
786 
787 void
788 add_detach(int prio, event_proc *p)
789 {
790 	cfg.add_detach(prio, p);
791 }
792 
793 void
794 add_directory(const char *dir)
795 {
796 	cfg.add_directory(dir);
797 	free(const_cast<char *>(dir));
798 }
799 
800 void
801 add_nomatch(int prio, event_proc *p)
802 {
803 	cfg.add_nomatch(prio, p);
804 }
805 
806 void
807 add_notify(int prio, event_proc *p)
808 {
809 	cfg.add_notify(prio, p);
810 }
811 
812 event_proc *
813 add_to_event_proc(event_proc *ep, eps *eps)
814 {
815 	if (ep == NULL)
816 		ep = new event_proc();
817 	ep->add(eps);
818 	return (ep);
819 }
820 
821 eps *
822 new_action(const char *cmd)
823 {
824 	eps *e = new action(cmd);
825 	free(const_cast<char *>(cmd));
826 	return (e);
827 }
828 
829 eps *
830 new_match(const char *var, const char *re)
831 {
832 	eps *e = new match(cfg, var, re);
833 	free(const_cast<char *>(var));
834 	free(const_cast<char *>(re));
835 	return (e);
836 }
837 
838 eps *
839 new_media(const char *var, const char *re)
840 {
841 	eps *e = new media(cfg, var, re);
842 	free(const_cast<char *>(var));
843 	free(const_cast<char *>(re));
844 	return (e);
845 }
846 
847 void
848 set_pidfile(const char *name)
849 {
850 	cfg.set_pidfile(name);
851 	free(const_cast<char *>(name));
852 }
853 
854 void
855 set_variable(const char *var, const char *val)
856 {
857 	cfg.set_variable(var, val);
858 	free(const_cast<char *>(var));
859 	free(const_cast<char *>(val));
860 }
861 
862 
863 
864 static void
865 gensighand(int)
866 {
867 	romeo_must_die = 1;
868 	unlink("/var/run/devd.pid");	/* XXX */
869 }
870 
871 static void
872 usage()
873 {
874 	fprintf(stderr, "usage: %s [-Ddn] [-f file]\n", getprogname());
875 	exit(1);
876 }
877 
878 static void
879 check_devd_enabled()
880 {
881 	int val = 0;
882 	size_t len;
883 
884 	len = sizeof(val);
885 	if (sysctlbyname(SYSCTL, &val, &len, NULL, 0) != 0)
886 		errx(1, "devctl sysctl missing from kernel!");
887 	if (val) {
888 		warnx("Setting " SYSCTL " to 0");
889 		val = 0;
890 		sysctlbyname(SYSCTL, NULL, NULL, &val, sizeof(val));
891 	}
892 }
893 
894 /*
895  * main
896  */
897 int
898 main(int argc, char **argv)
899 {
900 	int ch;
901 
902 	check_devd_enabled();
903 	while ((ch = getopt(argc, argv, "Ddf:n")) != -1) {
904 		switch (ch) {
905 		case 'D':
906 			Dflag++;
907 			break;
908 		case 'd':
909 			dflag++;
910 			break;
911 		case 'f':
912 			configfile = optarg;
913 			break;
914 		case 'n':
915 			nflag++;
916 			break;
917 		default:
918 			usage();
919 		}
920 	}
921 
922 	cfg.parse();
923 	if (!dflag && nflag) {
924 		if (Dflag)
925 			fprintf(stderr, "Calling daemon\n");
926 		daemon(0, 0);
927 		cfg.open_pidfile();
928 	}
929 	signal(SIGPIPE, SIG_IGN);
930 	signal(SIGHUP, gensighand);
931 	signal(SIGINT, gensighand);
932 	signal(SIGTERM, gensighand);
933 	event_loop();
934 	return (0);
935 }
936