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"
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.
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.
118 #define CLIENT_BUFSIZE 131072
125 static const char notify = '!';
126 static const char nomatch = '?';
127 static const char attach = '+';
128 static const char detach = '-';
130 static struct pidfh *pfh;
132 static int no_daemon = 0;
133 static int daemonize_quick = 0;
134 static int quiet_mode = 0;
135 static unsigned total_events = 0;
136 static volatile sig_atomic_t got_siginfo = 0;
137 static volatile sig_atomic_t romeo_must_die = 0;
139 static const char *configfile = CF;
141 static void devdlog(int priority, const char* message, ...)
143 static void event_loop(void);
144 static void usage(void);
146 template <class T> void
147 delete_and_clear(vector<T *> &v)
149 typename vector<T *>::const_iterator i;
151 for (i = v.begin(); i != v.end(); ++i)
158 event_proc::event_proc() : _prio(-1)
163 event_proc::~event_proc()
165 delete_and_clear(_epsvec);
169 event_proc::add(eps *eps)
171 _epsvec.push_back(eps);
175 event_proc::matches(config &c) const
177 vector<eps *>::const_iterator i;
179 for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
180 if (!(*i)->do_match(c))
186 event_proc::run(config &c) const
188 vector<eps *>::const_iterator i;
190 for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
191 if (!(*i)->do_action(c))
196 action::action(const char *cmd)
208 my_system(const char *command)
212 struct sigaction ign, intact, quitact;
213 sigset_t newsigblock, oldsigblock;
215 if (!command) /* just checking... */
219 * Ignore SIGINT and SIGQUIT, block SIGCHLD. Remember to save
220 * existing signal dispositions.
222 ign.sa_handler = SIG_IGN;
223 ::sigemptyset(&ign.sa_mask);
225 ::sigaction(SIGINT, &ign, &intact);
226 ::sigaction(SIGQUIT, &ign, &quitact);
227 ::sigemptyset(&newsigblock);
228 ::sigaddset(&newsigblock, SIGCHLD);
229 ::sigprocmask(SIG_BLOCK, &newsigblock, &oldsigblock);
230 switch (pid = ::fork()) {
235 * Restore original signal dispositions and exec the command.
237 ::sigaction(SIGINT, &intact, NULL);
238 ::sigaction(SIGQUIT, &quitact, NULL);
239 ::sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
241 * Close the PID file, and all other open descriptors.
242 * Inherit std{in,out,err} only.
246 ::execl(_PATH_BSHELL, "sh", "-c", command, (char *)NULL);
248 default: /* parent */
251 pid = ::wait4(savedpid, &pstat, 0, (struct rusage *)0);
252 } while (pid == -1 && errno == EINTR);
255 ::sigaction(SIGINT, &intact, NULL);
256 ::sigaction(SIGQUIT, &quitact, NULL);
257 ::sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
258 return (pid == -1 ? -1 : pstat);
262 action::do_action(config &c)
264 string s = c.expand_string(_cmd.c_str());
265 devdlog(LOG_NOTICE, "Executing '%s'\n", s.c_str());
266 my_system(s.c_str());
270 match::match(config &c, const char *var, const char *re) :
273 _re(c.expand_string(_inv ? re + 1 : re, "^", "$"))
275 regcomp(&_regex, _re.c_str(), REG_EXTENDED | REG_NOSUB | REG_ICASE);
284 match::do_match(config &c)
286 const string &value = c.get_variable(_var);
290 * This function gets called WAY too often to justify calling syslog()
291 * each time, even at LOG_DEBUG. Because if syslogd isn't running, it
292 * can consume excessive amounts of systime inside of connect(). Only
293 * log when we're in -d mode.
296 devdlog(LOG_DEBUG, "Testing %s=%s against %s, invert=%d\n",
297 _var.c_str(), value.c_str(), _re.c_str(), _inv);
300 retval = (regexec(&_regex, value.c_str(), 0, NULL, 0) == 0);
302 retval = (retval == 0) ? 1 : 0;
307 #include <sys/sockio.h>
309 #include <net/if_media.h>
311 media::media(config &, const char *var, const char *type)
312 : _var(var), _type(-1)
314 static struct ifmedia_description media_types[] = {
315 { IFM_ETHER, "Ethernet" },
316 { IFM_TOKEN, "Tokenring" },
317 { IFM_FDDI, "FDDI" },
318 { IFM_IEEE80211, "802.11" },
323 for (int i = 0; media_types[i].ifmt_string != NULL; ++i)
324 if (strcasecmp(type, media_types[i].ifmt_string) == 0) {
325 _type = media_types[i].ifmt_word;
335 media::do_match(config &c)
338 struct ifmediareq ifmr;
342 // Since we can be called from both a device attach/detach
343 // context where device-name is defined and what we want,
344 // as well as from a link status context, where subsystem is
345 // the name of interest, first try device-name and fall back
346 // to subsystem if none exists.
347 value = c.get_variable("device-name");
349 value = c.get_variable("subsystem");
350 devdlog(LOG_DEBUG, "Testing media type of %s against 0x%x\n",
351 value.c_str(), _type);
355 s = socket(PF_INET, SOCK_DGRAM, 0);
357 memset(&ifmr, 0, sizeof(ifmr));
358 strncpy(ifmr.ifm_name, value.c_str(), sizeof(ifmr.ifm_name));
360 if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0 &&
361 ifmr.ifm_status & IFM_AVALID) {
362 devdlog(LOG_DEBUG, "%s has media type 0x%x\n",
363 value.c_str(), IFM_TYPE(ifmr.ifm_active));
364 retval = (IFM_TYPE(ifmr.ifm_active) == _type);
365 } else if (_type == -1) {
366 devdlog(LOG_DEBUG, "%s has unknown media type\n",
376 const string var_list::bogus = "_$_$_$_$_B_O_G_U_S_$_$_$_$_";
377 const string var_list::nothing = "";
380 var_list::get_variable(const string &var) const
382 map<string, string>::const_iterator i;
385 if (i == _vars.end())
386 return (var_list::bogus);
391 var_list::is_set(const string &var) const
393 return (_vars.find(var) != _vars.end());
397 var_list::set_variable(const string &var, const string &val)
400 * This function gets called WAY too often to justify calling syslog()
401 * each time, even at LOG_DEBUG. Because if syslogd isn't running, it
402 * can consume excessive amounts of systime inside of connect(). Only
403 * log when we're in -d mode.
406 devdlog(LOG_DEBUG, "setting %s=%s\n", var.c_str(), val.c_str());
414 delete_and_clear(_var_list_table);
415 delete_and_clear(_attach_list);
416 delete_and_clear(_detach_list);
417 delete_and_clear(_nomatch_list);
418 delete_and_clear(_notify_list);
422 config::parse_one_file(const char *fn)
424 devdlog(LOG_DEBUG, "Parsing %s\n", fn);
425 yyin = fopen(fn, "r");
427 err(1, "Cannot open config file %s", fn);
430 errx(1, "Cannot parse %s at line %d", fn, lineno);
435 config::parse_files_in_dir(const char *dirname)
441 devdlog(LOG_DEBUG, "Parsing files in %s\n", dirname);
442 dirp = opendir(dirname);
445 readdir(dirp); /* Skip . */
446 readdir(dirp); /* Skip .. */
447 while ((dp = readdir(dirp)) != NULL) {
448 if (strcmp(dp->d_name + dp->d_namlen - 5, ".conf") == 0) {
449 snprintf(path, sizeof(path), "%s/%s",
450 dirname, dp->d_name);
451 parse_one_file(path);
459 int operator()(event_proc *const&l1, event_proc *const&l2) const
461 return (l1->get_priority() > l2->get_priority());
466 config::sort_vector(vector<event_proc *> &v)
468 stable_sort(v.begin(), v.end(), epv_greater());
474 vector<string>::const_iterator i;
476 parse_one_file(configfile);
477 for (i = _dir_list.begin(); i != _dir_list.end(); ++i)
478 parse_files_in_dir((*i).c_str());
479 sort_vector(_attach_list);
480 sort_vector(_detach_list);
481 sort_vector(_nomatch_list);
482 sort_vector(_notify_list);
486 config::open_pidfile()
490 if (_pidfile.empty())
492 pfh = pidfile_open(_pidfile.c_str(), 0600, &otherpid);
495 errx(1, "devd already running, pid: %d", (int)otherpid);
496 warn("cannot open pid file");
501 config::write_pidfile()
508 config::close_pidfile()
515 config::remove_pidfile()
522 config::add_attach(int prio, event_proc *p)
524 p->set_priority(prio);
525 _attach_list.push_back(p);
529 config::add_detach(int prio, event_proc *p)
531 p->set_priority(prio);
532 _detach_list.push_back(p);
536 config::add_directory(const char *dir)
538 _dir_list.push_back(string(dir));
542 config::add_nomatch(int prio, event_proc *p)
544 p->set_priority(prio);
545 _nomatch_list.push_back(p);
549 config::add_notify(int prio, event_proc *p)
551 p->set_priority(prio);
552 _notify_list.push_back(p);
556 config::set_pidfile(const char *fn)
562 config::push_var_table()
567 _var_list_table.push_back(vl);
568 devdlog(LOG_DEBUG, "Pushing table\n");
572 config::pop_var_table()
574 delete _var_list_table.back();
575 _var_list_table.pop_back();
576 devdlog(LOG_DEBUG, "Popping table\n");
580 config::set_variable(const char *var, const char *val)
582 _var_list_table.back()->set_variable(var, val);
586 config::get_variable(const string &var)
588 vector<var_list *>::reverse_iterator i;
590 for (i = _var_list_table.rbegin(); i != _var_list_table.rend(); ++i) {
591 if ((*i)->is_set(var))
592 return ((*i)->get_variable(var));
594 return (var_list::nothing);
598 config::is_id_char(char ch) const
600 return (ch != '\0' && (isalpha(ch) || isdigit(ch) || ch == '_' ||
605 config::expand_one(const char *&src, string &dst)
618 // Not sure if I want to support this or not, so for now we just pass
623 /* If the string ends before ) is matched , return. */
624 while (count > 0 && *src) {
627 else if (*src == '(')
635 if (!isalpha(*src)) {
641 // $var -> replace with value
644 } while (is_id_char(*src));
645 dst.append(get_variable(buffer));
649 config::expand_string(const char *src, const char *prepend, const char *append)
655 * 128 bytes is enough for 2427 of 2438 expansions that happen
656 * while parsing config files, as tested on 2013-01-30.
664 var_at = strchr(src, '$');
665 if (var_at == NULL) {
669 dst.append(src, var_at - src);
671 expand_one(src, dst);
681 config::chop_var(char *&buffer, char *&lhs, char *&rhs) const
687 walker = lhs = buffer;
688 while (is_id_char(*walker))
693 if (*walker == '"') {
696 while (*walker && *walker != '"')
704 while (*walker && !isspace(*walker))
710 while (isspace(*walker))
718 config::set_vars(char *buffer)
724 if (!chop_var(buffer, lhs, rhs))
726 set_variable(lhs, rhs);
732 config::find_and_execute(char type)
734 vector<event_proc *> *l;
735 vector<event_proc *>::const_iterator i;
758 devdlog(LOG_DEBUG, "Processing %s event\n", s);
759 for (i = l->begin(); i != l->end(); ++i) {
760 if ((*i)->matches(*this)) {
770 process_event(char *buffer)
776 devdlog(LOG_INFO, "Processing event '%s'\n", buffer);
778 cfg.push_var_table();
779 // No match doesn't have a device, and the format is a little
780 // different, so handle it separately.
783 sp = cfg.set_vars(sp);
786 //? at location pnp-info on bus
787 sp = strchr(sp, ' ');
789 return; /* Can't happen? */
793 if (strncmp(sp, "at ", 3) == 0)
795 sp = cfg.set_vars(sp);
798 if (strncmp(sp, "on ", 3) == 0)
799 cfg.set_variable("bus", sp + 3);
801 case attach: /*FALLTHROUGH*/
803 sp = strchr(sp, ' ');
805 return; /* Can't happen? */
807 cfg.set_variable("device-name", buffer);
810 if (strncmp(sp, "at ", 3) == 0)
812 sp = cfg.set_vars(sp);
815 if (strncmp(sp, "on ", 3) == 0)
816 cfg.set_variable("bus", sp + 3);
820 cfg.find_and_execute(type);
825 create_socket(const char *name)
828 struct sockaddr_un sun;
830 if ((fd = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0)
832 bzero(&sun, sizeof(sun));
833 sun.sun_family = AF_UNIX;
834 strlcpy(sun.sun_path, name, sizeof(sun.sun_path));
835 slen = SUN_LEN(&sun);
837 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
839 if (::bind(fd, (struct sockaddr *) & sun, slen) < 0)
842 chown(name, 0, 0); /* XXX - root.wheel */
847 unsigned int max_clients = 10; /* Default, can be overriden on cmdline. */
848 unsigned int num_clients;
852 notify_clients(const char *data, int len)
854 list<int>::iterator i;
857 * Deliver the data to all clients. Throw clients overboard at the
858 * first sign of trouble. This reaps clients who've died or closed
859 * their sockets, and also clients who are alive but failing to keep up
860 * (or who are maliciously not reading, to consume buffer space in
861 * kernel memory or tie up the limited number of available connections).
863 for (i = clients.begin(); i != clients.end(); ) {
864 if (write(*i, data, len) != len) {
867 i = clients.erase(i);
868 devdlog(LOG_WARNING, "notify_clients: write() failed; "
869 "dropping unresponsive client\n");
880 list<int>::iterator i;
883 * Check all existing clients to see if any of them have disappeared.
884 * Normally we reap clients when we get an error trying to send them an
885 * event. This check eliminates the problem of an ever-growing list of
886 * zombie clients because we're never writing to them on a system
887 * without frequent device-change activity.
890 for (i = clients.begin(); i != clients.end(); ) {
892 s = poll(&pfd, 1, 0);
893 if ((s < 0 && s != EINTR ) ||
894 (s > 0 && (pfd.revents & POLLHUP))) {
897 i = clients.erase(i);
898 devdlog(LOG_NOTICE, "check_clients: "
899 "dropping disconnected client\n");
912 * First go reap any zombie clients, then accept the connection, and
913 * shut down the read side to stop clients from consuming kernel memory
914 * by sending large buffers full of data we'll never read.
917 s = accept(fd, NULL, NULL);
919 sndbuf_size = CLIENT_BUFSIZE;
920 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &sndbuf_size,
921 sizeof(sndbuf_size)))
922 err(1, "setsockopt");
923 shutdown(s, SHUT_RD);
924 clients.push_back(s);
935 char buffer[DEVCTL_MAXBUF];
937 int server_fd, max_fd;
942 fd = open(PATH_DEVCTL, O_RDONLY | O_CLOEXEC);
944 err(1, "Can't open devctl device %s", PATH_DEVCTL);
945 server_fd = create_socket(PIPE);
947 max_fd = max(fd, server_fd) + 1;
948 while (!romeo_must_die) {
949 if (!once && !no_daemon && !daemonize_quick) {
950 // Check to see if we have any events pending.
955 rv = select(fd + 1, &fds, &fds, &fds, &tv);
956 // No events -> we've processed all pending events
958 devdlog(LOG_DEBUG, "Calling daemon\n");
959 cfg.remove_pidfile();
967 * When we've already got the max number of clients, stop
968 * accepting new connections (don't put server_fd in the set),
969 * shrink the accept() queue to reject connections quickly, and
970 * poll the existing clients more often, so that we notice more
971 * quickly when any of them disappear to free up client slots.
975 if (num_clients < max_clients) {
977 listen(server_fd, max_clients);
980 FD_SET(server_fd, &fds);
985 listen(server_fd, 0);
991 rv = select(max_fd, &fds, NULL, NULL, &tv);
993 devdlog(LOG_NOTICE, "Events received so far=%u\n",
1003 if (FD_ISSET(fd, &fds)) {
1004 rv = read(fd, buffer, sizeof(buffer) - 1);
1007 if (rv == sizeof(buffer) - 1) {
1008 devdlog(LOG_WARNING, "Warning: "
1009 "available event data exceeded "
1012 notify_clients(buffer, rv);
1014 while (buffer[--rv] == '\n')
1016 process_event(buffer);
1017 } else if (rv < 0) {
1025 if (FD_ISSET(server_fd, &fds))
1026 new_client(server_fd);
1032 * functions that the parser uses.
1035 add_attach(int prio, event_proc *p)
1037 cfg.add_attach(prio, p);
1041 add_detach(int prio, event_proc *p)
1043 cfg.add_detach(prio, p);
1047 add_directory(const char *dir)
1049 cfg.add_directory(dir);
1050 free(const_cast<char *>(dir));
1054 add_nomatch(int prio, event_proc *p)
1056 cfg.add_nomatch(prio, p);
1060 add_notify(int prio, event_proc *p)
1062 cfg.add_notify(prio, p);
1066 add_to_event_proc(event_proc *ep, eps *eps)
1069 ep = new event_proc();
1075 new_action(const char *cmd)
1077 eps *e = new action(cmd);
1078 free(const_cast<char *>(cmd));
1083 new_match(const char *var, const char *re)
1085 eps *e = new match(cfg, var, re);
1086 free(const_cast<char *>(var));
1087 free(const_cast<char *>(re));
1092 new_media(const char *var, const char *re)
1094 eps *e = new media(cfg, var, re);
1095 free(const_cast<char *>(var));
1096 free(const_cast<char *>(re));
1101 set_pidfile(const char *name)
1103 cfg.set_pidfile(name);
1104 free(const_cast<char *>(name));
1108 set_variable(const char *var, const char *val)
1110 cfg.set_variable(var, val);
1111 free(const_cast<char *>(var));
1112 free(const_cast<char *>(val));
1124 * SIGINFO handler. Will print useful statistics to the syslog or stderr
1134 * Local logging function. Prints to syslog if we're daemonized; syslog
1138 devdlog(int priority, const char* fmt, ...)
1142 va_start(argp, fmt);
1144 vfprintf(stderr, fmt, argp);
1145 else if ((! quiet_mode) || (priority <= LOG_WARNING))
1146 vsyslog(priority, fmt, argp);
1153 fprintf(stderr, "usage: %s [-dnq] [-l connlimit] [-f file]\n",
1159 check_devd_enabled()
1165 if (sysctlbyname(SYSCTL, &val, &len, NULL, 0) != 0)
1166 errx(1, "devctl sysctl missing from kernel!");
1168 warnx("Setting " SYSCTL " to 0");
1170 sysctlbyname(SYSCTL, NULL, NULL, &val, sizeof(val));
1178 main(int argc, char **argv)
1182 check_devd_enabled();
1183 while ((ch = getopt(argc, argv, "df:l:nq")) != -1) {
1189 configfile = optarg;
1192 max_clients = MAX(1, strtoul(optarg, NULL, 0));
1195 daemonize_quick = 1;
1206 if (!no_daemon && daemonize_quick) {
1209 cfg.write_pidfile();
1211 signal(SIGPIPE, SIG_IGN);
1212 signal(SIGHUP, gensighand);
1213 signal(SIGINT, gensighand);
1214 signal(SIGTERM, gensighand);
1215 signal(SIGINFO, siginfohand);