2 * Copyright (c) 2002-2010 M. Warner Losh.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
26 * my_system is a variation on lib/libc/stdlib/system.c:
28 * Copyright (c) 1988, 1993
29 * The Regents of the University of California. All rights reserved.
31 * Redistribution and use in source and binary forms, with or without
32 * modification, are permitted provided that the following conditions
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.
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
57 * DEVD control daemon.
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.
65 #include <sys/cdefs.h>
66 __FBSDID("$FreeBSD$");
68 #include <sys/param.h>
69 #include <sys/socket.h>
71 #include <sys/sysctl.h>
72 #include <sys/types.h>
100 #include "devd.h" /* C compatible definitions */
101 #include "devd.hh" /* C++ class definitions */
103 #define PIPE "/var/run/devd.pipe"
104 #define CF "/etc/devd.conf"
105 #define SYSCTL "hw.bus.devctl_disable"
112 static const char notify = '!';
113 static const char nomatch = '?';
114 static const char attach = '+';
115 static const char detach = '-';
117 static struct pidfh *pfh;
121 static unsigned total_events = 0;
122 static volatile sig_atomic_t got_siginfo = 0;
123 static volatile sig_atomic_t romeo_must_die = 0;
125 static const char *configfile = CF;
127 static void devdlog(int priority, const char* message, ...)
129 static void event_loop(void);
130 static void usage(void);
132 template <class T> void
133 delete_and_clear(vector<T *> &v)
135 typename vector<T *>::const_iterator i;
137 for (i = v.begin(); i != v.end(); ++i)
144 event_proc::event_proc() : _prio(-1)
149 event_proc::~event_proc()
151 delete_and_clear(_epsvec);
155 event_proc::add(eps *eps)
157 _epsvec.push_back(eps);
161 event_proc::matches(config &c) const
163 vector<eps *>::const_iterator i;
165 for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
166 if (!(*i)->do_match(c))
172 event_proc::run(config &c) const
174 vector<eps *>::const_iterator i;
176 for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
177 if (!(*i)->do_action(c))
182 action::action(const char *cmd)
194 my_system(const char *command)
198 struct sigaction ign, intact, quitact;
199 sigset_t newsigblock, oldsigblock;
201 if (!command) /* just checking... */
205 * Ignore SIGINT and SIGQUIT, block SIGCHLD. Remember to save
206 * existing signal dispositions.
208 ign.sa_handler = SIG_IGN;
209 ::sigemptyset(&ign.sa_mask);
211 ::sigaction(SIGINT, &ign, &intact);
212 ::sigaction(SIGQUIT, &ign, &quitact);
213 ::sigemptyset(&newsigblock);
214 ::sigaddset(&newsigblock, SIGCHLD);
215 ::sigprocmask(SIG_BLOCK, &newsigblock, &oldsigblock);
216 switch (pid = ::fork()) {
221 * Restore original signal dispositions and exec the command.
223 ::sigaction(SIGINT, &intact, NULL);
224 ::sigaction(SIGQUIT, &quitact, NULL);
225 ::sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
227 * Close the PID file, and all other open descriptors.
228 * Inherit std{in,out,err} only.
232 ::execl(_PATH_BSHELL, "sh", "-c", command, (char *)NULL);
234 default: /* parent */
237 pid = ::wait4(savedpid, &pstat, 0, (struct rusage *)0);
238 } while (pid == -1 && errno == EINTR);
241 ::sigaction(SIGINT, &intact, NULL);
242 ::sigaction(SIGQUIT, &quitact, NULL);
243 ::sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
244 return (pid == -1 ? -1 : pstat);
248 action::do_action(config &c)
250 string s = c.expand_string(_cmd.c_str());
251 devdlog(LOG_NOTICE, "Executing '%s'\n", s.c_str());
252 my_system(s.c_str());
256 match::match(config &c, const char *var, const char *re) :
259 _re(c.expand_string(_inv ? re + 1 : re, "^", "$"))
261 regcomp(&_regex, _re.c_str(), REG_EXTENDED | REG_NOSUB | REG_ICASE);
270 match::do_match(config &c)
272 const string &value = c.get_variable(_var);
276 * This function gets called WAY too often to justify calling syslog()
277 * each time, even at LOG_DEBUG. Because if syslogd isn't running, it
278 * can consume excessive amounts of systime inside of connect(). Only
279 * log when we're in -d mode.
282 devdlog(LOG_DEBUG, "Testing %s=%s against %s, invert=%d\n",
283 _var.c_str(), value.c_str(), _re.c_str(), _inv);
286 retval = (regexec(&_regex, value.c_str(), 0, NULL, 0) == 0);
288 retval = (retval == 0) ? 1 : 0;
293 #include <sys/sockio.h>
295 #include <net/if_media.h>
297 media::media(config &, const char *var, const char *type)
298 : _var(var), _type(-1)
300 static struct ifmedia_description media_types[] = {
301 { IFM_ETHER, "Ethernet" },
302 { IFM_TOKEN, "Tokenring" },
303 { IFM_FDDI, "FDDI" },
304 { IFM_IEEE80211, "802.11" },
309 for (int i = 0; media_types[i].ifmt_string != NULL; ++i)
310 if (strcasecmp(type, media_types[i].ifmt_string) == 0) {
311 _type = media_types[i].ifmt_word;
321 media::do_match(config &c)
324 struct ifmediareq ifmr;
328 // Since we can be called from both a device attach/detach
329 // context where device-name is defined and what we want,
330 // as well as from a link status context, where subsystem is
331 // the name of interest, first try device-name and fall back
332 // to subsystem if none exists.
333 value = c.get_variable("device-name");
335 value = c.get_variable("subsystem");
336 devdlog(LOG_DEBUG, "Testing media type of %s against 0x%x\n",
337 value.c_str(), _type);
341 s = socket(PF_INET, SOCK_DGRAM, 0);
343 memset(&ifmr, 0, sizeof(ifmr));
344 strncpy(ifmr.ifm_name, value.c_str(), sizeof(ifmr.ifm_name));
346 if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0 &&
347 ifmr.ifm_status & IFM_AVALID) {
348 devdlog(LOG_DEBUG, "%s has media type 0x%x\n",
349 value.c_str(), IFM_TYPE(ifmr.ifm_active));
350 retval = (IFM_TYPE(ifmr.ifm_active) == _type);
351 } else if (_type == -1) {
352 devdlog(LOG_DEBUG, "%s has unknown media type\n",
362 const string var_list::bogus = "_$_$_$_$_B_O_G_U_S_$_$_$_$_";
363 const string var_list::nothing = "";
366 var_list::get_variable(const string &var) const
368 map<string, string>::const_iterator i;
371 if (i == _vars.end())
372 return (var_list::bogus);
377 var_list::is_set(const string &var) const
379 return (_vars.find(var) != _vars.end());
383 var_list::set_variable(const string &var, const string &val)
386 * This function gets called WAY too often to justify calling syslog()
387 * each time, even at LOG_DEBUG. Because if syslogd isn't running, it
388 * can consume excessive amounts of systime inside of connect(). Only
389 * log when we're in -d mode.
392 devdlog(LOG_DEBUG, "setting %s=%s\n", var.c_str(), val.c_str());
400 delete_and_clear(_var_list_table);
401 delete_and_clear(_attach_list);
402 delete_and_clear(_detach_list);
403 delete_and_clear(_nomatch_list);
404 delete_and_clear(_notify_list);
408 config::parse_one_file(const char *fn)
410 devdlog(LOG_DEBUG, "Parsing %s\n", fn);
411 yyin = fopen(fn, "r");
413 err(1, "Cannot open config file %s", fn);
416 errx(1, "Cannot parse %s at line %d", fn, lineno);
421 config::parse_files_in_dir(const char *dirname)
427 devdlog(LOG_DEBUG, "Parsing files in %s\n", dirname);
428 dirp = opendir(dirname);
431 readdir(dirp); /* Skip . */
432 readdir(dirp); /* Skip .. */
433 while ((dp = readdir(dirp)) != NULL) {
434 if (strcmp(dp->d_name + dp->d_namlen - 5, ".conf") == 0) {
435 snprintf(path, sizeof(path), "%s/%s",
436 dirname, dp->d_name);
437 parse_one_file(path);
445 int operator()(event_proc *const&l1, event_proc *const&l2) const
447 return (l1->get_priority() > l2->get_priority());
452 config::sort_vector(vector<event_proc *> &v)
454 stable_sort(v.begin(), v.end(), epv_greater());
460 vector<string>::const_iterator i;
462 parse_one_file(configfile);
463 for (i = _dir_list.begin(); i != _dir_list.end(); ++i)
464 parse_files_in_dir((*i).c_str());
465 sort_vector(_attach_list);
466 sort_vector(_detach_list);
467 sort_vector(_nomatch_list);
468 sort_vector(_notify_list);
472 config::open_pidfile()
476 if (_pidfile.empty())
478 pfh = pidfile_open(_pidfile.c_str(), 0600, &otherpid);
481 errx(1, "devd already running, pid: %d", (int)otherpid);
482 warn("cannot open pid file");
487 config::write_pidfile()
494 config::close_pidfile()
501 config::remove_pidfile()
508 config::add_attach(int prio, event_proc *p)
510 p->set_priority(prio);
511 _attach_list.push_back(p);
515 config::add_detach(int prio, event_proc *p)
517 p->set_priority(prio);
518 _detach_list.push_back(p);
522 config::add_directory(const char *dir)
524 _dir_list.push_back(string(dir));
528 config::add_nomatch(int prio, event_proc *p)
530 p->set_priority(prio);
531 _nomatch_list.push_back(p);
535 config::add_notify(int prio, event_proc *p)
537 p->set_priority(prio);
538 _notify_list.push_back(p);
542 config::set_pidfile(const char *fn)
548 config::push_var_table()
553 _var_list_table.push_back(vl);
554 devdlog(LOG_DEBUG, "Pushing table\n");
558 config::pop_var_table()
560 delete _var_list_table.back();
561 _var_list_table.pop_back();
562 devdlog(LOG_DEBUG, "Popping table\n");
566 config::set_variable(const char *var, const char *val)
568 _var_list_table.back()->set_variable(var, val);
572 config::get_variable(const string &var)
574 vector<var_list *>::reverse_iterator i;
576 for (i = _var_list_table.rbegin(); i != _var_list_table.rend(); ++i) {
577 if ((*i)->is_set(var))
578 return ((*i)->get_variable(var));
580 return (var_list::nothing);
584 config::is_id_char(char ch) const
586 return (ch != '\0' && (isalpha(ch) || isdigit(ch) || ch == '_' ||
591 config::expand_one(const char *&src, string &dst)
604 // Not sure if I want to support this or not, so for now we just pass
609 /* If the string ends before ) is matched , return. */
610 while (count > 0 && *src) {
613 else if (*src == '(')
621 if (!isalpha(*src)) {
627 // $var -> replace with value
630 } while (is_id_char(*src));
631 dst.append(get_variable(buffer));
635 config::expand_string(const char *src, const char *prepend, const char *append)
641 * 128 bytes is enough for 2427 of 2438 expansions that happen
642 * while parsing config files, as tested on 2013-01-30.
650 var_at = strchr(src, '$');
651 if (var_at == NULL) {
655 dst.append(src, var_at - src);
657 expand_one(src, dst);
667 config::chop_var(char *&buffer, char *&lhs, char *&rhs) const
673 walker = lhs = buffer;
674 while (is_id_char(*walker))
679 if (*walker == '"') {
682 while (*walker && *walker != '"')
690 while (*walker && !isspace(*walker))
696 while (isspace(*walker))
704 config::set_vars(char *buffer)
710 if (!chop_var(buffer, lhs, rhs))
712 set_variable(lhs, rhs);
718 config::find_and_execute(char type)
720 vector<event_proc *> *l;
721 vector<event_proc *>::const_iterator i;
744 devdlog(LOG_DEBUG, "Processing %s event\n", s);
745 for (i = l->begin(); i != l->end(); ++i) {
746 if ((*i)->matches(*this)) {
756 process_event(char *buffer)
762 devdlog(LOG_DEBUG, "Processing event '%s'\n", buffer);
764 cfg.push_var_table();
765 // No match doesn't have a device, and the format is a little
766 // different, so handle it separately.
769 sp = cfg.set_vars(sp);
772 //? at location pnp-info on bus
773 sp = strchr(sp, ' ');
775 return; /* Can't happen? */
779 if (strncmp(sp, "at ", 3) == 0)
781 sp = cfg.set_vars(sp);
784 if (strncmp(sp, "on ", 3) == 0)
785 cfg.set_variable("bus", sp + 3);
787 case attach: /*FALLTHROUGH*/
789 sp = strchr(sp, ' ');
791 return; /* Can't happen? */
793 cfg.set_variable("device-name", buffer);
796 if (strncmp(sp, "at ", 3) == 0)
798 sp = cfg.set_vars(sp);
801 if (strncmp(sp, "on ", 3) == 0)
802 cfg.set_variable("bus", sp + 3);
806 cfg.find_and_execute(type);
811 create_socket(const char *name)
814 struct sockaddr_un sun;
816 if ((fd = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0)
818 bzero(&sun, sizeof(sun));
819 sun.sun_family = AF_UNIX;
820 strlcpy(sun.sun_path, name, sizeof(sun.sun_path));
821 slen = SUN_LEN(&sun);
823 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
825 if (::bind(fd, (struct sockaddr *) & sun, slen) < 0)
828 chown(name, 0, 0); /* XXX - root.wheel */
833 unsigned int max_clients = 10; /* Default, can be overriden on cmdline. */
834 unsigned int num_clients;
838 notify_clients(const char *data, int len)
840 list<int>::iterator i;
843 * Deliver the data to all clients. Throw clients overboard at the
844 * first sign of trouble. This reaps clients who've died or closed
845 * their sockets, and also clients who are alive but failing to keep up
846 * (or who are maliciously not reading, to consume buffer space in
847 * kernel memory or tie up the limited number of available connections).
849 for (i = clients.begin(); i != clients.end(); ) {
850 if (write(*i, data, len) != len) {
853 i = clients.erase(i);
854 devdlog(LOG_WARNING, "notify_clients: write() failed; "
855 "dropping unresponsive client\n");
866 list<int>::iterator i;
869 * Check all existing clients to see if any of them have disappeared.
870 * Normally we reap clients when we get an error trying to send them an
871 * event. This check eliminates the problem of an ever-growing list of
872 * zombie clients because we're never writing to them on a system
873 * without frequent device-change activity.
876 for (i = clients.begin(); i != clients.end(); ) {
878 s = poll(&pfd, 1, 0);
879 if ((s < 0 && s != EINTR ) ||
880 (s > 0 && (pfd.revents & POLLHUP))) {
883 i = clients.erase(i);
884 devdlog(LOG_NOTICE, "check_clients: "
885 "dropping disconnected client\n");
897 * First go reap any zombie clients, then accept the connection, and
898 * shut down the read side to stop clients from consuming kernel memory
899 * by sending large buffers full of data we'll never read.
902 s = accept(fd, NULL, NULL);
904 shutdown(s, SHUT_RD);
905 clients.push_back(s);
915 char buffer[DEVCTL_MAXBUF];
917 int server_fd, max_fd;
922 fd = open(PATH_DEVCTL, O_RDONLY | O_CLOEXEC);
924 err(1, "Can't open devctl device %s", PATH_DEVCTL);
925 server_fd = create_socket(PIPE);
927 max_fd = max(fd, server_fd) + 1;
928 while (!romeo_must_die) {
929 if (!once && !dflag && !nflag) {
930 // Check to see if we have any events pending.
935 rv = select(fd + 1, &fds, &fds, &fds, &tv);
936 // No events -> we've processed all pending events
938 devdlog(LOG_DEBUG, "Calling daemon\n");
939 cfg.remove_pidfile();
947 * When we've already got the max number of clients, stop
948 * accepting new connections (don't put server_fd in the set),
949 * shrink the accept() queue to reject connections quickly, and
950 * poll the existing clients more often, so that we notice more
951 * quickly when any of them disappear to free up client slots.
955 if (num_clients < max_clients) {
957 listen(server_fd, max_clients);
960 FD_SET(server_fd, &fds);
965 listen(server_fd, 0);
971 rv = select(max_fd, &fds, NULL, NULL, &tv);
973 devdlog(LOG_INFO, "Events received so far=%u\n",
983 if (FD_ISSET(fd, &fds)) {
984 rv = read(fd, buffer, sizeof(buffer) - 1);
987 if (rv == sizeof(buffer) - 1) {
988 devdlog(LOG_WARNING, "Warning: "
989 "available event data exceeded "
992 notify_clients(buffer, rv);
994 while (buffer[--rv] == '\n')
996 process_event(buffer);
1005 if (FD_ISSET(server_fd, &fds))
1006 new_client(server_fd);
1012 * functions that the parser uses.
1015 add_attach(int prio, event_proc *p)
1017 cfg.add_attach(prio, p);
1021 add_detach(int prio, event_proc *p)
1023 cfg.add_detach(prio, p);
1027 add_directory(const char *dir)
1029 cfg.add_directory(dir);
1030 free(const_cast<char *>(dir));
1034 add_nomatch(int prio, event_proc *p)
1036 cfg.add_nomatch(prio, p);
1040 add_notify(int prio, event_proc *p)
1042 cfg.add_notify(prio, p);
1046 add_to_event_proc(event_proc *ep, eps *eps)
1049 ep = new event_proc();
1055 new_action(const char *cmd)
1057 eps *e = new action(cmd);
1058 free(const_cast<char *>(cmd));
1063 new_match(const char *var, const char *re)
1065 eps *e = new match(cfg, var, re);
1066 free(const_cast<char *>(var));
1067 free(const_cast<char *>(re));
1072 new_media(const char *var, const char *re)
1074 eps *e = new media(cfg, var, re);
1075 free(const_cast<char *>(var));
1076 free(const_cast<char *>(re));
1081 set_pidfile(const char *name)
1083 cfg.set_pidfile(name);
1084 free(const_cast<char *>(name));
1088 set_variable(const char *var, const char *val)
1090 cfg.set_variable(var, val);
1091 free(const_cast<char *>(var));
1092 free(const_cast<char *>(val));
1104 * SIGINFO handler. Will print useful statistics to the syslog or stderr
1114 * Local logging function. Prints to syslog if we're daemonized; syslog
1118 devdlog(int priority, const char* fmt, ...)
1122 va_start(argp, fmt);
1124 vfprintf(stderr, fmt, argp);
1126 vsyslog(priority, fmt, argp);
1133 fprintf(stderr, "usage: %s [-dn] [-l connlimit] [-f file]\n",
1139 check_devd_enabled()
1145 if (sysctlbyname(SYSCTL, &val, &len, NULL, 0) != 0)
1146 errx(1, "devctl sysctl missing from kernel!");
1148 warnx("Setting " SYSCTL " to 0");
1150 sysctlbyname(SYSCTL, NULL, NULL, &val, sizeof(val));
1158 main(int argc, char **argv)
1162 check_devd_enabled();
1163 while ((ch = getopt(argc, argv, "df:l:n")) != -1) {
1169 configfile = optarg;
1172 max_clients = MAX(1, strtoul(optarg, NULL, 0));
1183 if (!dflag && nflag) {
1186 cfg.write_pidfile();
1188 signal(SIGPIPE, SIG_IGN);
1189 signal(SIGHUP, gensighand);
1190 signal(SIGINT, gensighand);
1191 signal(SIGTERM, gensighand);
1192 signal(SIGINFO, siginfohand);