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