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