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