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