]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sbin/devd/devd.cc
MFC r358694:
[FreeBSD/stable/9.git] / sbin / devd / devd.cc
1 /*-
2  * Copyright (c) 2002-2010 M. Warner Losh.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * my_system is a variation on lib/libc/stdlib/system.c:
27  *
28  * Copyright (c) 1988, 1993
29  *      The Regents of the University of California.  All rights reserved.
30  *
31  * Redistribution and use in source and binary forms, with or without
32  * modification, are permitted provided that the following conditions
33  * are met:
34  * 1. Redistributions of source code must retain the above copyright
35  *    notice, this list of conditions and the following disclaimer.
36  * 2. Redistributions in binary form must reproduce the above copyright
37  *    notice, this list of conditions and the following disclaimer in the
38  *    documentation and/or other materials provided with the distribution.
39  * 4. Neither the name of the University nor the names of its contributors
40  *    may be used to endorse or promote products derived from this software
41  *    without specific prior written permission.
42  *
43  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
44  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
47  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
48  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
49  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
51  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
52  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53  * SUCH DAMAGE.
54  */
55
56 /*
57  * DEVD control daemon.
58  */
59
60 // TODO list:
61 //      o devd.conf and devd man pages need a lot of help:
62 //        - devd needs to document the unix domain socket
63 //        - devd.conf needs more details on the supported statements.
64
65 #include <sys/cdefs.h>
66 __FBSDID("$FreeBSD$");
67
68 #include <sys/param.h>
69 #include <sys/socket.h>
70 #include <sys/stat.h>
71 #include <sys/sysctl.h>
72 #include <sys/types.h>
73 #include <sys/wait.h>
74 #include <sys/un.h>
75
76 #include <ctype.h>
77 #include <dirent.h>
78 #include <errno.h>
79 #include <err.h>
80 #include <fcntl.h>
81 #include <libutil.h>
82 #include <paths.h>
83 #include <poll.h>
84 #include <regex.h>
85 #include <signal.h>
86 #include <stdlib.h>
87 #include <stdio.h>
88 #include <string.h>
89 #include <unistd.h>
90
91 #include <algorithm>
92 #include <map>
93 #include <string>
94 #include <list>
95 #include <vector>
96
97 #include "devd.h"               /* C compatible definitions */
98 #include "devd.hh"              /* C++ class definitions */
99
100 #define PIPE "/var/run/devd.pipe"
101 #define CF "/etc/devd.conf"
102 #define SYSCTL "hw.bus.devctl_disable"
103
104 /*
105  * Since the client socket is nonblocking, we must increase its send buffer to
106  * handle brief event storms.  On FreeBSD, AF_UNIX sockets don't have a receive
107  * buffer, so the client can't increate the buffersize by itself.
108  *
109  * For example, when creating a ZFS pool, devd emits one 165 character
110  * resource.fs.zfs.statechange message for each vdev in the pool.  A 64k
111  * buffer has enough space for almost 400 drives, which would be very large but
112  * not impossibly large pool.  A 128k buffer has enough space for 794 drives,
113  * which is more than can fit in a rack with modern technology.
114  */
115 #define CLIENT_BUFSIZE 131072
116
117 using namespace std;
118
119 extern FILE *yyin;
120 extern int lineno;
121
122 static const char notify = '!';
123 static const char nomatch = '?';
124 static const char attach = '+';
125 static const char detach = '-';
126
127 static struct pidfh *pfh;
128
129 int Dflag;
130 int dflag;
131 int nflag;
132 int romeo_must_die = 0;
133
134 static const char *configfile = CF;
135
136 static void event_loop(void);
137 static void usage(void);
138
139 template <class T> void
140 delete_and_clear(vector<T *> &v)
141 {
142         typename vector<T *>::const_iterator i;
143
144         for (i = v.begin(); i != v.end(); ++i)
145                 delete *i;
146         v.clear();
147 }
148
149 config cfg;
150
151 event_proc::event_proc() : _prio(-1)
152 {
153         _epsvec.reserve(4);
154 }
155
156 event_proc::~event_proc()
157 {
158         delete_and_clear(_epsvec);
159 }
160
161 void
162 event_proc::add(eps *eps)
163 {
164         _epsvec.push_back(eps);
165 }
166
167 bool
168 event_proc::matches(config &c) const
169 {
170         vector<eps *>::const_iterator i;
171
172         for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
173                 if (!(*i)->do_match(c))
174                         return (false);
175         return (true);
176 }
177
178 bool
179 event_proc::run(config &c) const
180 {
181         vector<eps *>::const_iterator i;
182                 
183         for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
184                 if (!(*i)->do_action(c))
185                         return (false);
186         return (true);
187 }
188
189 action::action(const char *cmd)
190         : _cmd(cmd) 
191 {
192         // nothing
193 }
194
195 action::~action()
196 {
197         // nothing
198 }
199
200 static int
201 my_system(const char *command)
202 {
203         pid_t pid, savedpid;
204         int pstat;
205         struct sigaction ign, intact, quitact;
206         sigset_t newsigblock, oldsigblock;
207
208         if (!command)           /* just checking... */
209                 return(1);
210
211         /*
212          * Ignore SIGINT and SIGQUIT, block SIGCHLD. Remember to save
213          * existing signal dispositions.
214          */
215         ign.sa_handler = SIG_IGN;
216         ::sigemptyset(&ign.sa_mask);
217         ign.sa_flags = 0;
218         ::sigaction(SIGINT, &ign, &intact);
219         ::sigaction(SIGQUIT, &ign, &quitact);
220         ::sigemptyset(&newsigblock);
221         ::sigaddset(&newsigblock, SIGCHLD);
222         ::sigprocmask(SIG_BLOCK, &newsigblock, &oldsigblock);
223         switch (pid = ::fork()) {
224         case -1:                        /* error */
225                 break;
226         case 0:                         /* child */
227                 /*
228                  * Restore original signal dispositions and exec the command.
229                  */
230                 ::sigaction(SIGINT, &intact, NULL);
231                 ::sigaction(SIGQUIT,  &quitact, NULL);
232                 ::sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
233                 /*
234                  * Close the PID file, and all other open descriptors.
235                  * Inherit std{in,out,err} only.
236                  */
237                 cfg.close_pidfile();
238                 ::closefrom(3);
239                 ::execl(_PATH_BSHELL, "sh", "-c", command, (char *)NULL);
240                 ::_exit(127);
241         default:                        /* parent */
242                 savedpid = pid;
243                 do {
244                         pid = ::wait4(savedpid, &pstat, 0, (struct rusage *)0);
245                 } while (pid == -1 && errno == EINTR);
246                 break;
247         }
248         ::sigaction(SIGINT, &intact, NULL);
249         ::sigaction(SIGQUIT,  &quitact, NULL);
250         ::sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
251         return (pid == -1 ? -1 : pstat);
252 }
253
254 bool
255 action::do_action(config &c)
256 {
257         string s = c.expand_string(_cmd.c_str());
258         if (Dflag)
259                 fprintf(stderr, "Executing '%s'\n", s.c_str());
260         my_system(s.c_str());
261         return (true);
262 }
263
264 match::match(config &c, const char *var, const char *re) :
265         _inv(re[0] == '!'),
266         _var(var),
267         _re(c.expand_string(_inv ? re + 1 : re, "^", "$"))
268 {
269         regcomp(&_regex, _re.c_str(), REG_EXTENDED | REG_NOSUB | REG_ICASE);
270 }
271
272 match::~match()
273 {
274         regfree(&_regex);
275 }
276
277 bool
278 match::do_match(config &c)
279 {
280         const string &value = c.get_variable(_var);
281         bool retval;
282
283         if (Dflag)
284                 fprintf(stderr, "Testing %s=%s against %s, invert=%d\n",
285                     _var.c_str(), value.c_str(), _re.c_str(), _inv);
286
287         retval = (regexec(&_regex, value.c_str(), 0, NULL, 0) == 0);
288         if (_inv == 1)
289                 retval = (retval == 0) ? 1 : 0;
290
291         return retval;
292 }
293
294 #include <sys/sockio.h>
295 #include <net/if.h>
296 #include <net/if_media.h>
297
298 media::media(config &, const char *var, const char *type)
299         : _var(var), _type(-1)
300 {
301         static struct ifmedia_description media_types[] = {
302                 { IFM_ETHER,            "Ethernet" },
303                 { IFM_TOKEN,            "Tokenring" },
304                 { IFM_FDDI,             "FDDI" },
305                 { IFM_IEEE80211,        "802.11" },
306                 { IFM_ATM,              "ATM" },
307                 { IFM_CARP,             "CARP" },
308                 { -1,                   "unknown" },
309                 { 0, NULL },
310         };
311         for (int i = 0; media_types[i].ifmt_string != NULL; ++i)
312                 if (strcasecmp(type, media_types[i].ifmt_string) == 0) {
313                         _type = media_types[i].ifmt_word;
314                         break;
315                 }
316 }
317
318 media::~media()
319 {
320 }
321
322 bool
323 media::do_match(config &c)
324 {
325         string value;
326         struct ifmediareq ifmr;
327         bool retval;
328         int s;
329
330         // Since we can be called from both a device attach/detach
331         // context where device-name is defined and what we want,
332         // as well as from a link status context, where subsystem is
333         // the name of interest, first try device-name and fall back
334         // to subsystem if none exists.
335         value = c.get_variable("device-name");
336         if (value.length() == 0)
337                 value = c.get_variable("subsystem");
338         if (Dflag)
339                 fprintf(stderr, "Testing media type of %s against 0x%x\n",
340                     value.c_str(), _type);
341
342         retval = false;
343
344         s = socket(PF_INET, SOCK_DGRAM, 0);
345         if (s >= 0) {
346                 memset(&ifmr, 0, sizeof(ifmr));
347                 strncpy(ifmr.ifm_name, value.c_str(), sizeof(ifmr.ifm_name));
348
349                 if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0 &&
350                     ifmr.ifm_status & IFM_AVALID) {
351                         if (Dflag)
352                                 fprintf(stderr, "%s has media type 0x%x\n", 
353                                     value.c_str(), IFM_TYPE(ifmr.ifm_active));
354                         retval = (IFM_TYPE(ifmr.ifm_active) == _type);
355                 } else if (_type == -1) {
356                         if (Dflag)
357                                 fprintf(stderr, "%s has unknown media type\n", 
358                                     value.c_str());
359                         retval = true;
360                 }
361                 close(s);
362         }
363
364         return retval;
365 }
366
367 const string var_list::bogus = "_$_$_$_$_B_O_G_U_S_$_$_$_$_";
368 const string var_list::nothing = "";
369
370 const string &
371 var_list::get_variable(const string &var) const
372 {
373         map<string, string>::const_iterator i;
374
375         i = _vars.find(var);
376         if (i == _vars.end())
377                 return (var_list::bogus);
378         return (i->second);
379 }
380
381 bool
382 var_list::is_set(const string &var) const
383 {
384         return (_vars.find(var) != _vars.end());
385 }
386
387 void
388 var_list::set_variable(const string &var, const string &val)
389 {
390         if (Dflag)
391                 fprintf(stderr, "setting %s=%s\n", var.c_str(), val.c_str());
392         _vars[var] = val;
393 }
394
395 void
396 config::reset(void)
397 {
398         _dir_list.clear();
399         delete_and_clear(_var_list_table);
400         delete_and_clear(_attach_list);
401         delete_and_clear(_detach_list);
402         delete_and_clear(_nomatch_list);
403         delete_and_clear(_notify_list);
404 }
405
406 void
407 config::parse_one_file(const char *fn)
408 {
409         if (Dflag)
410                 fprintf(stderr, "Parsing %s\n", fn);
411         yyin = fopen(fn, "r");
412         if (yyin == NULL)
413                 err(1, "Cannot open config file %s", fn);
414         lineno = 1;
415         if (yyparse() != 0)
416                 errx(1, "Cannot parse %s at line %d", fn, lineno);
417         fclose(yyin);
418 }
419
420 void
421 config::parse_files_in_dir(const char *dirname)
422 {
423         DIR *dirp;
424         struct dirent *dp;
425         char path[PATH_MAX];
426
427         if (Dflag)
428                 fprintf(stderr, "Parsing files in %s\n", dirname);
429         dirp = opendir(dirname);
430         if (dirp == NULL)
431                 return;
432         readdir(dirp);          /* Skip . */
433         readdir(dirp);          /* Skip .. */
434         while ((dp = readdir(dirp)) != NULL) {
435                 if (strcmp(dp->d_name + dp->d_namlen - 5, ".conf") == 0) {
436                         snprintf(path, sizeof(path), "%s/%s",
437                             dirname, dp->d_name);
438                         parse_one_file(path);
439                 }
440         }
441         closedir(dirp);
442 }
443
444 class epv_greater {
445 public:
446         int operator()(event_proc *const&l1, event_proc *const&l2) const
447         {
448                 return (l1->get_priority() > l2->get_priority());
449         }
450 };
451
452 void
453 config::sort_vector(vector<event_proc *> &v)
454 {
455         stable_sort(v.begin(), v.end(), epv_greater());
456 }
457
458 void
459 config::parse(void)
460 {
461         vector<string>::const_iterator i;
462
463         parse_one_file(configfile);
464         for (i = _dir_list.begin(); i != _dir_list.end(); ++i)
465                 parse_files_in_dir((*i).c_str());
466         sort_vector(_attach_list);
467         sort_vector(_detach_list);
468         sort_vector(_nomatch_list);
469         sort_vector(_notify_list);
470 }
471
472 void
473 config::open_pidfile()
474 {
475         pid_t otherpid;
476         
477         if (_pidfile == "")
478                 return;
479         pfh = pidfile_open(_pidfile.c_str(), 0600, &otherpid);
480         if (pfh == NULL) {
481                 if (errno == EEXIST)
482                         errx(1, "devd already running, pid: %d", (int)otherpid);
483                 warn("cannot open pid file");
484         }
485 }
486
487 void
488 config::write_pidfile()
489 {
490         
491         pidfile_write(pfh);
492 }
493
494 void
495 config::close_pidfile()
496 {
497         
498         pidfile_close(pfh);
499 }
500
501 void
502 config::remove_pidfile()
503 {
504         
505         pidfile_remove(pfh);
506 }
507
508 void
509 config::add_attach(int prio, event_proc *p)
510 {
511         p->set_priority(prio);
512         _attach_list.push_back(p);
513 }
514
515 void
516 config::add_detach(int prio, event_proc *p)
517 {
518         p->set_priority(prio);
519         _detach_list.push_back(p);
520 }
521
522 void
523 config::add_directory(const char *dir)
524 {
525         _dir_list.push_back(string(dir));
526 }
527
528 void
529 config::add_nomatch(int prio, event_proc *p)
530 {
531         p->set_priority(prio);
532         _nomatch_list.push_back(p);
533 }
534
535 void
536 config::add_notify(int prio, event_proc *p)
537 {
538         p->set_priority(prio);
539         _notify_list.push_back(p);
540 }
541
542 void
543 config::set_pidfile(const char *fn)
544 {
545         _pidfile = string(fn);
546 }
547
548 void
549 config::push_var_table()
550 {
551         var_list *vl;
552         
553         vl = new var_list();
554         _var_list_table.push_back(vl);
555         if (Dflag)
556                 fprintf(stderr, "Pushing table\n");
557 }
558
559 void
560 config::pop_var_table()
561 {
562         delete _var_list_table.back();
563         _var_list_table.pop_back();
564         if (Dflag)
565                 fprintf(stderr, "Popping table\n");
566 }
567
568 void
569 config::set_variable(const char *var, const char *val)
570 {
571         _var_list_table.back()->set_variable(var, val);
572 }
573
574 const string &
575 config::get_variable(const string &var)
576 {
577         vector<var_list *>::reverse_iterator i;
578
579         for (i = _var_list_table.rbegin(); i != _var_list_table.rend(); ++i) {
580                 if ((*i)->is_set(var))
581                         return ((*i)->get_variable(var));
582         }
583         return (var_list::nothing);
584 }
585
586 bool
587 config::is_id_char(char ch) const
588 {
589         return (ch != '\0' && (isalpha(ch) || isdigit(ch) || ch == '_' || 
590             ch == '-'));
591 }
592
593 void
594 config::expand_one(const char *&src, string &dst)
595 {
596         int count;
597         string buffer;
598
599         src++;
600         // $$ -> $
601         if (*src == '$') {
602                 dst.append(src++, 1);
603                 return;
604         }
605                 
606         // $(foo) -> $(foo)
607         // Not sure if I want to support this or not, so for now we just pass
608         // it through.
609         if (*src == '(') {
610                 dst.append("$");
611                 count = 1;
612                 /* If the string ends before ) is matched , return. */
613                 while (count > 0 && *src) {
614                         if (*src == ')')
615                                 count--;
616                         else if (*src == '(')
617                                 count++;
618                         dst.append(src++, 1);
619                 }
620                 return;
621         }
622         
623         // ${^A-Za-z] -> $\1
624         if (!isalpha(*src)) {
625                 dst.append("$");
626                 dst.append(src++, 1);
627                 return;
628         }
629
630         // $var -> replace with value
631         do {
632                 buffer.append(src++, 1);
633         } while (is_id_char(*src));
634         dst.append(get_variable(buffer.c_str()));
635 }
636
637 const string
638 config::expand_string(const char *src, const char *prepend, const char *append)
639 {
640         const char *var_at;
641         string dst;
642
643         /*
644          * 128 bytes is enough for 2427 of 2438 expansions that happen
645          * while parsing config files, as tested on 2013-01-30.
646          */
647         dst.reserve(128);
648
649         if (prepend != NULL)
650                 dst = prepend;
651
652         for (;;) {
653                 var_at = strchr(src, '$');
654                 if (var_at == NULL) {
655                         dst.append(src);
656                         break;
657                 }
658                 dst.append(src, var_at - src);
659                 src = var_at;
660                 expand_one(src, dst);
661         }
662
663         if (append != NULL)
664                 dst.append(append);
665
666         return (dst);
667 }
668
669 bool
670 config::chop_var(char *&buffer, char *&lhs, char *&rhs)
671 {
672         char *walker;
673         
674         if (*buffer == '\0')
675                 return (false);
676         walker = lhs = buffer;
677         while (is_id_char(*walker))
678                 walker++;
679         if (*walker != '=')
680                 return (false);
681         walker++;               // skip =
682         if (*walker == '"') {
683                 walker++;       // skip "
684                 rhs = walker;
685                 while (*walker && *walker != '"')
686                         walker++;
687                 if (*walker != '"')
688                         return (false);
689                 rhs[-2] = '\0';
690                 *walker++ = '\0';
691         } else {
692                 rhs = walker;
693                 while (*walker && !isspace(*walker))
694                         walker++;
695                 if (*walker != '\0')
696                         *walker++ = '\0';
697                 rhs[-1] = '\0';
698         }
699         while (isspace(*walker))
700                 walker++;
701         buffer = walker;
702         return (true);
703 }
704
705
706 char *
707 config::set_vars(char *buffer)
708 {
709         char *lhs;
710         char *rhs;
711
712         while (1) {
713                 if (!chop_var(buffer, lhs, rhs))
714                         break;
715                 set_variable(lhs, rhs);
716         }
717         return (buffer);
718 }
719
720 void
721 config::find_and_execute(char type)
722 {
723         vector<event_proc *> *l;
724         vector<event_proc *>::const_iterator i;
725         const char *s;
726
727         switch (type) {
728         default:
729                 return;
730         case notify:
731                 l = &_notify_list;
732                 s = "notify";
733                 break;
734         case nomatch:
735                 l = &_nomatch_list;
736                 s = "nomatch";
737                 break;
738         case attach:
739                 l = &_attach_list;
740                 s = "attach";
741                 break;
742         case detach:
743                 l = &_detach_list;
744                 s = "detach";
745                 break;
746         }
747         if (Dflag)
748                 fprintf(stderr, "Processing %s event\n", s);
749         for (i = l->begin(); i != l->end(); ++i) {
750                 if ((*i)->matches(*this)) {
751                         (*i)->run(*this);
752                         break;
753                 }
754         }
755
756 }
757
758 \f
759 static void
760 process_event(char *buffer)
761 {
762         char type;
763         char *sp;
764
765         sp = buffer + 1;
766         if (Dflag)
767                 fprintf(stderr, "Processing event '%s'\n", buffer);
768         type = *buffer++;
769         cfg.push_var_table();
770         // No match doesn't have a device, and the format is a little
771         // different, so handle it separately.
772         switch (type) {
773         case notify:
774                 sp = cfg.set_vars(sp);
775                 break;
776         case nomatch:
777                 //? at location pnp-info on bus
778                 sp = strchr(sp, ' ');
779                 if (sp == NULL)
780                         return; /* Can't happen? */
781                 *sp++ = '\0';
782                 while (isspace(*sp))
783                         sp++;
784                 if (strncmp(sp, "at ", 3) == 0)
785                         sp += 3;
786                 sp = cfg.set_vars(sp);
787                 while (isspace(*sp))
788                         sp++;
789                 if (strncmp(sp, "on ", 3) == 0)
790                         cfg.set_variable("bus", sp + 3);
791                 break;
792         case attach:    /*FALLTHROUGH*/
793         case detach:
794                 sp = strchr(sp, ' ');
795                 if (sp == NULL)
796                         return; /* Can't happen? */
797                 *sp++ = '\0';
798                 cfg.set_variable("device-name", buffer);
799                 while (isspace(*sp))
800                         sp++;
801                 if (strncmp(sp, "at ", 3) == 0)
802                         sp += 3;
803                 sp = cfg.set_vars(sp);
804                 while (isspace(*sp))
805                         sp++;
806                 if (strncmp(sp, "on ", 3) == 0)
807                         cfg.set_variable("bus", sp + 3);
808                 break;
809         }
810         
811         cfg.find_and_execute(type);
812         cfg.pop_var_table();
813 }
814
815 int
816 create_socket(const char *name)
817 {
818         int fd, slen;
819         struct sockaddr_un sun;
820
821         if ((fd = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0)
822                 err(1, "socket");
823         bzero(&sun, sizeof(sun));
824         sun.sun_family = AF_UNIX;
825         strlcpy(sun.sun_path, name, sizeof(sun.sun_path));
826         slen = SUN_LEN(&sun);
827         unlink(name);
828         if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
829                 err(1, "fcntl");
830         if (::bind(fd, (struct sockaddr *) & sun, slen) < 0)
831                 err(1, "bind");
832         listen(fd, 4);
833         chown(name, 0, 0);      /* XXX - root.wheel */
834         chmod(name, 0666);
835         return (fd);
836 }
837
838 unsigned int max_clients = 10;  /* Default, can be overriden on cmdline. */
839 unsigned int num_clients;
840 list<int> clients;
841
842 void
843 notify_clients(const char *data, int len)
844 {
845         list<int>::iterator i;
846
847         /*
848          * Deliver the data to all clients.  Throw clients overboard at the
849          * first sign of trouble.  This reaps clients who've died or closed
850          * their sockets, and also clients who are alive but failing to keep up
851          * (or who are maliciously not reading, to consume buffer space in
852          * kernel memory or tie up the limited number of available connections).
853          */
854         for (i = clients.begin(); i != clients.end(); ) {
855                 if (write(*i, data, len) != len) {
856                         --num_clients;
857                         close(*i);
858                         i = clients.erase(i);
859                 } else
860                         ++i;
861         }
862 }
863
864 void
865 check_clients(void)
866 {
867         int s;
868         struct pollfd pfd;
869         list<int>::iterator i;
870
871         /*
872          * Check all existing clients to see if any of them have disappeared.
873          * Normally we reap clients when we get an error trying to send them an
874          * event.  This check eliminates the problem of an ever-growing list of
875          * zombie clients because we're never writing to them on a system
876          * without frequent device-change activity.
877          */
878         pfd.events = 0;
879         for (i = clients.begin(); i != clients.end(); ) {
880                 pfd.fd = *i;
881                 s = poll(&pfd, 1, 0);
882                 if ((s < 0 && s != EINTR ) ||
883                     (s > 0 && (pfd.revents & POLLHUP))) {
884                         --num_clients;
885                         close(*i);
886                         i = clients.erase(i);
887                 } else
888                         ++i;
889         }
890 }
891
892 void
893 new_client(int fd)
894 {
895         int s;
896         int sndbuf_size;
897
898         /*
899          * First go reap any zombie clients, then accept the connection, and
900          * shut down the read side to stop clients from consuming kernel memory
901          * by sending large buffers full of data we'll never read.
902          */
903         check_clients();
904         s = accept(fd, NULL, NULL);
905         if (s != -1) {
906                 sndbuf_size = CLIENT_BUFSIZE;
907                 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &sndbuf_size,
908                     sizeof(sndbuf_size)))
909                         err(1, "setsockopt");
910                 shutdown(s, SHUT_RD);
911                 clients.push_back(s);
912                 ++num_clients;
913         } else
914                 err(1, "accept");
915 }
916
917 static void
918 event_loop(void)
919 {
920         int rv;
921         int fd;
922         char buffer[DEVCTL_MAXBUF];
923         int once = 0;
924         int server_fd, max_fd;
925         int accepting;
926         timeval tv;
927         fd_set fds;
928
929         fd = open(PATH_DEVCTL, O_RDONLY);
930         if (fd == -1)
931                 err(1, "Can't open devctl device %s", PATH_DEVCTL);
932         if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0)
933                 err(1, "Can't set close-on-exec flag on devctl");
934         server_fd = create_socket(PIPE);
935         accepting = 1;
936         max_fd = max(fd, server_fd) + 1;
937         while (1) {
938                 if (romeo_must_die)
939                         break;
940                 if (!once && !dflag && !nflag) {
941                         // Check to see if we have any events pending.
942                         tv.tv_sec = 0;
943                         tv.tv_usec = 0;
944                         FD_ZERO(&fds);
945                         FD_SET(fd, &fds);
946                         rv = select(fd + 1, &fds, &fds, &fds, &tv);
947                         // No events -> we've processed all pending events
948                         if (rv == 0) {
949                                 if (Dflag)
950                                         fprintf(stderr, "Calling daemon\n");
951                                 cfg.remove_pidfile();
952                                 cfg.open_pidfile();
953                                 daemon(0, 0);
954                                 cfg.write_pidfile();
955                                 once++;
956                         }
957                 }
958                 /*
959                  * When we've already got the max number of clients, stop
960                  * accepting new connections (don't put server_fd in the set),
961                  * shrink the accept() queue to reject connections quickly, and
962                  * poll the existing clients more often, so that we notice more
963                  * quickly when any of them disappear to free up client slots.
964                  */
965                 FD_ZERO(&fds);
966                 FD_SET(fd, &fds);
967                 if (num_clients < max_clients) {
968                         if (!accepting) {
969                                 listen(server_fd, max_clients);
970                                 accepting = 1;
971                         }
972                         FD_SET(server_fd, &fds);
973                         tv.tv_sec = 60;
974                         tv.tv_usec = 0;
975                 } else {
976                         if (accepting) {
977                                 listen(server_fd, 0);
978                                 accepting = 0;
979                         }
980                         tv.tv_sec = 2;
981                         tv.tv_usec = 0;
982                 }
983                 rv = select(max_fd, &fds, NULL, NULL, &tv);
984                 if (rv == -1) {
985                         if (errno == EINTR)
986                                 continue;
987                         err(1, "select");
988                 } else if (rv == 0)
989                         check_clients();
990                 if (FD_ISSET(fd, &fds)) {
991                         rv = read(fd, buffer, sizeof(buffer) - 1);
992                         if (rv > 0) {
993                                 notify_clients(buffer, rv);
994                                 buffer[rv] = '\0';
995                                 while (buffer[--rv] == '\n')
996                                         buffer[rv] = '\0';
997                                 process_event(buffer);
998                         } else if (rv < 0) {
999                                 if (errno != EINTR)
1000                                         break;
1001                         } else {
1002                                 /* EOF */
1003                                 break;
1004                         }
1005                 }
1006                 if (FD_ISSET(server_fd, &fds))
1007                         new_client(server_fd);
1008         }
1009         close(fd);
1010 }
1011 \f
1012 /*
1013  * functions that the parser uses.
1014  */
1015 void
1016 add_attach(int prio, event_proc *p)
1017 {
1018         cfg.add_attach(prio, p);
1019 }
1020
1021 void
1022 add_detach(int prio, event_proc *p)
1023 {
1024         cfg.add_detach(prio, p);
1025 }
1026
1027 void
1028 add_directory(const char *dir)
1029 {
1030         cfg.add_directory(dir);
1031         free(const_cast<char *>(dir));
1032 }
1033
1034 void
1035 add_nomatch(int prio, event_proc *p)
1036 {
1037         cfg.add_nomatch(prio, p);
1038 }
1039
1040 void
1041 add_notify(int prio, event_proc *p)
1042 {
1043         cfg.add_notify(prio, p);
1044 }
1045
1046 event_proc *
1047 add_to_event_proc(event_proc *ep, eps *eps)
1048 {
1049         if (ep == NULL)
1050                 ep = new event_proc();
1051         ep->add(eps);
1052         return (ep);
1053 }
1054
1055 eps *
1056 new_action(const char *cmd)
1057 {
1058         eps *e = new action(cmd);
1059         free(const_cast<char *>(cmd));
1060         return (e);
1061 }
1062
1063 eps *
1064 new_match(const char *var, const char *re)
1065 {
1066         eps *e = new match(cfg, var, re);
1067         free(const_cast<char *>(var));
1068         free(const_cast<char *>(re));
1069         return (e);
1070 }
1071
1072 eps *
1073 new_media(const char *var, const char *re)
1074 {
1075         eps *e = new media(cfg, var, re);
1076         free(const_cast<char *>(var));
1077         free(const_cast<char *>(re));
1078         return (e);
1079 }
1080
1081 void
1082 set_pidfile(const char *name)
1083 {
1084         cfg.set_pidfile(name);
1085         free(const_cast<char *>(name));
1086 }
1087
1088 void
1089 set_variable(const char *var, const char *val)
1090 {
1091         cfg.set_variable(var, val);
1092         free(const_cast<char *>(var));
1093         free(const_cast<char *>(val));
1094 }
1095
1096 \f
1097
1098 static void
1099 gensighand(int)
1100 {
1101         romeo_must_die++;
1102         _exit(0);
1103 }
1104
1105 static void
1106 usage()
1107 {
1108         fprintf(stderr, "usage: %s [-Ddn] [-l connlimit] [-f file]\n",
1109             getprogname());
1110         exit(1);
1111 }
1112
1113 static void
1114 check_devd_enabled()
1115 {
1116         int val = 0;
1117         size_t len;
1118
1119         len = sizeof(val);
1120         if (sysctlbyname(SYSCTL, &val, &len, NULL, 0) != 0)
1121                 errx(1, "devctl sysctl missing from kernel!");
1122         if (val) {
1123                 warnx("Setting " SYSCTL " to 0");
1124                 val = 0;
1125                 sysctlbyname(SYSCTL, NULL, NULL, &val, sizeof(val));
1126         }
1127 }
1128
1129 /*
1130  * main
1131  */
1132 int
1133 main(int argc, char **argv)
1134 {
1135         int ch;
1136
1137         check_devd_enabled();
1138         while ((ch = getopt(argc, argv, "Ddf:l:n")) != -1) {
1139                 switch (ch) {
1140                 case 'D':
1141                         Dflag++;
1142                         break;
1143                 case 'd':
1144                         dflag++;
1145                         break;
1146                 case 'f':
1147                         configfile = optarg;
1148                         break;
1149                 case 'l':
1150                         max_clients = MAX(1, strtoul(optarg, NULL, 0));
1151                         break;
1152                 case 'n':
1153                         nflag++;
1154                         break;
1155                 default:
1156                         usage();
1157                 }
1158         }
1159
1160         cfg.parse();
1161         if (!dflag && nflag) {
1162                 cfg.open_pidfile();
1163                 daemon(0, 0);
1164                 cfg.write_pidfile();
1165         }
1166         signal(SIGPIPE, SIG_IGN);
1167         signal(SIGHUP, gensighand);
1168         signal(SIGINT, gensighand);
1169         signal(SIGTERM, gensighand);
1170         event_loop();
1171         return (0);
1172 }