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