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