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