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