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>
97 #include "devd.h" /* C compatible definitions */
98 #include "devd.hh" /* C++ class definitions */
100 #define PIPE "/var/run/devd.pipe"
101 #define CF "/etc/devd.conf"
102 #define SYSCTL "hw.bus.devctl_disable"
105 * Since the client socket is nonblocking, we must increase its send buffer to
106 * handle brief event storms. On FreeBSD, AF_UNIX sockets don't have a receive
107 * buffer, so the client can't increate the buffersize by itself.
109 * For example, when creating a ZFS pool, devd emits one 165 character
110 * resource.fs.zfs.statechange message for each vdev in the pool. A 64k
111 * buffer has enough space for almost 400 drives, which would be very large but
112 * not impossibly large pool. A 128k buffer has enough space for 794 drives,
113 * which is more than can fit in a rack with modern technology.
115 #define CLIENT_BUFSIZE 131072
122 static const char notify = '!';
123 static const char nomatch = '?';
124 static const char attach = '+';
125 static const char detach = '-';
127 static struct pidfh *pfh;
132 int romeo_must_die = 0;
134 static const char *configfile = CF;
136 static void event_loop(void);
137 static void usage(void);
139 template <class T> void
140 delete_and_clear(vector<T *> &v)
142 typename vector<T *>::const_iterator i;
144 for (i = v.begin(); i != v.end(); ++i)
151 event_proc::event_proc() : _prio(-1)
156 event_proc::~event_proc()
158 delete_and_clear(_epsvec);
162 event_proc::add(eps *eps)
164 _epsvec.push_back(eps);
168 event_proc::matches(config &c) const
170 vector<eps *>::const_iterator i;
172 for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
173 if (!(*i)->do_match(c))
179 event_proc::run(config &c) const
181 vector<eps *>::const_iterator i;
183 for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
184 if (!(*i)->do_action(c))
189 action::action(const char *cmd)
201 my_system(const char *command)
205 struct sigaction ign, intact, quitact;
206 sigset_t newsigblock, oldsigblock;
208 if (!command) /* just checking... */
212 * Ignore SIGINT and SIGQUIT, block SIGCHLD. Remember to save
213 * existing signal dispositions.
215 ign.sa_handler = SIG_IGN;
216 ::sigemptyset(&ign.sa_mask);
218 ::sigaction(SIGINT, &ign, &intact);
219 ::sigaction(SIGQUIT, &ign, &quitact);
220 ::sigemptyset(&newsigblock);
221 ::sigaddset(&newsigblock, SIGCHLD);
222 ::sigprocmask(SIG_BLOCK, &newsigblock, &oldsigblock);
223 switch (pid = ::fork()) {
228 * Restore original signal dispositions and exec the command.
230 ::sigaction(SIGINT, &intact, NULL);
231 ::sigaction(SIGQUIT, &quitact, NULL);
232 ::sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
234 * Close the PID file, and all other open descriptors.
235 * Inherit std{in,out,err} only.
239 ::execl(_PATH_BSHELL, "sh", "-c", command, (char *)NULL);
241 default: /* parent */
244 pid = ::wait4(savedpid, &pstat, 0, (struct rusage *)0);
245 } while (pid == -1 && errno == EINTR);
248 ::sigaction(SIGINT, &intact, NULL);
249 ::sigaction(SIGQUIT, &quitact, NULL);
250 ::sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
251 return (pid == -1 ? -1 : pstat);
255 action::do_action(config &c)
257 string s = c.expand_string(_cmd.c_str());
259 fprintf(stderr, "Executing '%s'\n", s.c_str());
260 my_system(s.c_str());
264 match::match(config &c, const char *var, const char *re) :
267 _re(c.expand_string(_inv ? re + 1 : re, "^", "$"))
269 regcomp(&_regex, _re.c_str(), REG_EXTENDED | REG_NOSUB | REG_ICASE);
278 match::do_match(config &c)
280 const string &value = c.get_variable(_var);
284 fprintf(stderr, "Testing %s=%s against %s, invert=%d\n",
285 _var.c_str(), value.c_str(), _re.c_str(), _inv);
287 retval = (regexec(&_regex, value.c_str(), 0, NULL, 0) == 0);
289 retval = (retval == 0) ? 1 : 0;
294 #include <sys/sockio.h>
296 #include <net/if_media.h>
298 media::media(config &, const char *var, const char *type)
299 : _var(var), _type(-1)
301 static struct ifmedia_description media_types[] = {
302 { IFM_ETHER, "Ethernet" },
303 { IFM_TOKEN, "Tokenring" },
304 { IFM_FDDI, "FDDI" },
305 { IFM_IEEE80211, "802.11" },
307 { IFM_CARP, "CARP" },
311 for (int i = 0; media_types[i].ifmt_string != NULL; ++i)
312 if (strcasecmp(type, media_types[i].ifmt_string) == 0) {
313 _type = media_types[i].ifmt_word;
323 media::do_match(config &c)
326 struct ifmediareq ifmr;
330 // Since we can be called from both a device attach/detach
331 // context where device-name is defined and what we want,
332 // as well as from a link status context, where subsystem is
333 // the name of interest, first try device-name and fall back
334 // to subsystem if none exists.
335 value = c.get_variable("device-name");
336 if (value.length() == 0)
337 value = c.get_variable("subsystem");
339 fprintf(stderr, "Testing media type of %s against 0x%x\n",
340 value.c_str(), _type);
344 s = socket(PF_INET, SOCK_DGRAM, 0);
346 memset(&ifmr, 0, sizeof(ifmr));
347 strncpy(ifmr.ifm_name, value.c_str(), sizeof(ifmr.ifm_name));
349 if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0 &&
350 ifmr.ifm_status & IFM_AVALID) {
352 fprintf(stderr, "%s has media type 0x%x\n",
353 value.c_str(), IFM_TYPE(ifmr.ifm_active));
354 retval = (IFM_TYPE(ifmr.ifm_active) == _type);
355 } else if (_type == -1) {
357 fprintf(stderr, "%s has unknown media type\n",
367 const string var_list::bogus = "_$_$_$_$_B_O_G_U_S_$_$_$_$_";
368 const string var_list::nothing = "";
371 var_list::get_variable(const string &var) const
373 map<string, string>::const_iterator i;
376 if (i == _vars.end())
377 return (var_list::bogus);
382 var_list::is_set(const string &var) const
384 return (_vars.find(var) != _vars.end());
388 var_list::set_variable(const string &var, const string &val)
391 fprintf(stderr, "setting %s=%s\n", var.c_str(), val.c_str());
399 delete_and_clear(_var_list_table);
400 delete_and_clear(_attach_list);
401 delete_and_clear(_detach_list);
402 delete_and_clear(_nomatch_list);
403 delete_and_clear(_notify_list);
407 config::parse_one_file(const char *fn)
410 fprintf(stderr, "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)
428 fprintf(stderr, "Parsing files in %s\n", dirname);
429 dirp = opendir(dirname);
432 readdir(dirp); /* Skip . */
433 readdir(dirp); /* Skip .. */
434 while ((dp = readdir(dirp)) != NULL) {
435 if (strcmp(dp->d_name + dp->d_namlen - 5, ".conf") == 0) {
436 snprintf(path, sizeof(path), "%s/%s",
437 dirname, dp->d_name);
438 parse_one_file(path);
446 int operator()(event_proc *const&l1, event_proc *const&l2) const
448 return (l1->get_priority() > l2->get_priority());
453 config::sort_vector(vector<event_proc *> &v)
455 stable_sort(v.begin(), v.end(), epv_greater());
461 vector<string>::const_iterator i;
463 parse_one_file(configfile);
464 for (i = _dir_list.begin(); i != _dir_list.end(); ++i)
465 parse_files_in_dir((*i).c_str());
466 sort_vector(_attach_list);
467 sort_vector(_detach_list);
468 sort_vector(_nomatch_list);
469 sort_vector(_notify_list);
473 config::open_pidfile()
479 pfh = pidfile_open(_pidfile.c_str(), 0600, &otherpid);
482 errx(1, "devd already running, pid: %d", (int)otherpid);
483 warn("cannot open pid file");
488 config::write_pidfile()
495 config::close_pidfile()
502 config::remove_pidfile()
509 config::add_attach(int prio, event_proc *p)
511 p->set_priority(prio);
512 _attach_list.push_back(p);
516 config::add_detach(int prio, event_proc *p)
518 p->set_priority(prio);
519 _detach_list.push_back(p);
523 config::add_directory(const char *dir)
525 _dir_list.push_back(string(dir));
529 config::add_nomatch(int prio, event_proc *p)
531 p->set_priority(prio);
532 _nomatch_list.push_back(p);
536 config::add_notify(int prio, event_proc *p)
538 p->set_priority(prio);
539 _notify_list.push_back(p);
543 config::set_pidfile(const char *fn)
545 _pidfile = string(fn);
549 config::push_var_table()
554 _var_list_table.push_back(vl);
556 fprintf(stderr, "Pushing table\n");
560 config::pop_var_table()
562 delete _var_list_table.back();
563 _var_list_table.pop_back();
565 fprintf(stderr, "Popping table\n");
569 config::set_variable(const char *var, const char *val)
571 _var_list_table.back()->set_variable(var, val);
575 config::get_variable(const string &var)
577 vector<var_list *>::reverse_iterator i;
579 for (i = _var_list_table.rbegin(); i != _var_list_table.rend(); ++i) {
580 if ((*i)->is_set(var))
581 return ((*i)->get_variable(var));
583 return (var_list::nothing);
587 config::is_id_char(char ch) const
589 return (ch != '\0' && (isalpha(ch) || isdigit(ch) || ch == '_' ||
594 config::expand_one(const char *&src, string &dst)
602 dst.append(src++, 1);
607 // Not sure if I want to support this or not, so for now we just pass
612 /* If the string ends before ) is matched , return. */
613 while (count > 0 && *src) {
616 else if (*src == '(')
618 dst.append(src++, 1);
624 if (!isalpha(*src)) {
626 dst.append(src++, 1);
630 // $var -> replace with value
632 buffer.append(src++, 1);
633 } while (is_id_char(*src));
634 dst.append(get_variable(buffer.c_str()));
638 config::expand_string(const char *src, const char *prepend, const char *append)
644 * 128 bytes is enough for 2427 of 2438 expansions that happen
645 * while parsing config files, as tested on 2013-01-30.
653 var_at = strchr(src, '$');
654 if (var_at == NULL) {
658 dst.append(src, var_at - src);
660 expand_one(src, dst);
670 config::chop_var(char *&buffer, char *&lhs, char *&rhs)
676 walker = lhs = buffer;
677 while (is_id_char(*walker))
682 if (*walker == '"') {
685 while (*walker && *walker != '"')
693 while (*walker && !isspace(*walker))
699 while (isspace(*walker))
707 config::set_vars(char *buffer)
713 if (!chop_var(buffer, lhs, rhs))
715 set_variable(lhs, rhs);
721 config::find_and_execute(char type)
723 vector<event_proc *> *l;
724 vector<event_proc *>::const_iterator i;
748 fprintf(stderr, "Processing %s event\n", s);
749 for (i = l->begin(); i != l->end(); ++i) {
750 if ((*i)->matches(*this)) {
760 process_event(char *buffer)
767 fprintf(stderr, "Processing event '%s'\n", buffer);
769 cfg.push_var_table();
770 // No match doesn't have a device, and the format is a little
771 // different, so handle it separately.
774 sp = cfg.set_vars(sp);
777 //? at location pnp-info on bus
778 sp = strchr(sp, ' ');
780 return; /* Can't happen? */
784 if (strncmp(sp, "at ", 3) == 0)
786 sp = cfg.set_vars(sp);
789 if (strncmp(sp, "on ", 3) == 0)
790 cfg.set_variable("bus", sp + 3);
792 case attach: /*FALLTHROUGH*/
794 sp = strchr(sp, ' ');
796 return; /* Can't happen? */
798 cfg.set_variable("device-name", buffer);
801 if (strncmp(sp, "at ", 3) == 0)
803 sp = cfg.set_vars(sp);
806 if (strncmp(sp, "on ", 3) == 0)
807 cfg.set_variable("bus", sp + 3);
811 cfg.find_and_execute(type);
816 create_socket(const char *name)
819 struct sockaddr_un sun;
821 if ((fd = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0)
823 bzero(&sun, sizeof(sun));
824 sun.sun_family = AF_UNIX;
825 strlcpy(sun.sun_path, name, sizeof(sun.sun_path));
826 slen = SUN_LEN(&sun);
828 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
830 if (::bind(fd, (struct sockaddr *) & sun, slen) < 0)
833 chown(name, 0, 0); /* XXX - root.wheel */
838 unsigned int max_clients = 10; /* Default, can be overriden on cmdline. */
839 unsigned int num_clients;
843 notify_clients(const char *data, int len)
845 list<int>::iterator i;
848 * Deliver the data to all clients. Throw clients overboard at the
849 * first sign of trouble. This reaps clients who've died or closed
850 * their sockets, and also clients who are alive but failing to keep up
851 * (or who are maliciously not reading, to consume buffer space in
852 * kernel memory or tie up the limited number of available connections).
854 for (i = clients.begin(); i != clients.end(); ) {
855 if (write(*i, data, len) != len) {
858 i = clients.erase(i);
869 list<int>::iterator i;
872 * Check all existing clients to see if any of them have disappeared.
873 * Normally we reap clients when we get an error trying to send them an
874 * event. This check eliminates the problem of an ever-growing list of
875 * zombie clients because we're never writing to them on a system
876 * without frequent device-change activity.
879 for (i = clients.begin(); i != clients.end(); ) {
881 s = poll(&pfd, 1, 0);
882 if ((s < 0 && s != EINTR ) ||
883 (s > 0 && (pfd.revents & POLLHUP))) {
886 i = clients.erase(i);
899 * First go reap any zombie clients, then accept the connection, and
900 * shut down the read side to stop clients from consuming kernel memory
901 * by sending large buffers full of data we'll never read.
904 s = accept(fd, NULL, NULL);
906 sndbuf_size = CLIENT_BUFSIZE;
907 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &sndbuf_size,
908 sizeof(sndbuf_size)))
909 err(1, "setsockopt");
910 shutdown(s, SHUT_RD);
911 clients.push_back(s);
922 char buffer[DEVCTL_MAXBUF];
924 int server_fd, max_fd;
929 fd = open(PATH_DEVCTL, O_RDONLY);
931 err(1, "Can't open devctl device %s", PATH_DEVCTL);
932 if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0)
933 err(1, "Can't set close-on-exec flag on devctl");
934 server_fd = create_socket(PIPE);
936 max_fd = max(fd, server_fd) + 1;
940 if (!once && !dflag && !nflag) {
941 // Check to see if we have any events pending.
946 rv = select(fd + 1, &fds, &fds, &fds, &tv);
947 // No events -> we've processed all pending events
950 fprintf(stderr, "Calling daemon\n");
951 cfg.remove_pidfile();
959 * When we've already got the max number of clients, stop
960 * accepting new connections (don't put server_fd in the set),
961 * shrink the accept() queue to reject connections quickly, and
962 * poll the existing clients more often, so that we notice more
963 * quickly when any of them disappear to free up client slots.
967 if (num_clients < max_clients) {
969 listen(server_fd, max_clients);
972 FD_SET(server_fd, &fds);
977 listen(server_fd, 0);
983 rv = select(max_fd, &fds, NULL, NULL, &tv);
990 if (FD_ISSET(fd, &fds)) {
991 rv = read(fd, buffer, sizeof(buffer) - 1);
993 notify_clients(buffer, rv);
995 while (buffer[--rv] == '\n')
997 process_event(buffer);
1006 if (FD_ISSET(server_fd, &fds))
1007 new_client(server_fd);
1013 * functions that the parser uses.
1016 add_attach(int prio, event_proc *p)
1018 cfg.add_attach(prio, p);
1022 add_detach(int prio, event_proc *p)
1024 cfg.add_detach(prio, p);
1028 add_directory(const char *dir)
1030 cfg.add_directory(dir);
1031 free(const_cast<char *>(dir));
1035 add_nomatch(int prio, event_proc *p)
1037 cfg.add_nomatch(prio, p);
1041 add_notify(int prio, event_proc *p)
1043 cfg.add_notify(prio, p);
1047 add_to_event_proc(event_proc *ep, eps *eps)
1050 ep = new event_proc();
1056 new_action(const char *cmd)
1058 eps *e = new action(cmd);
1059 free(const_cast<char *>(cmd));
1064 new_match(const char *var, const char *re)
1066 eps *e = new match(cfg, var, re);
1067 free(const_cast<char *>(var));
1068 free(const_cast<char *>(re));
1073 new_media(const char *var, const char *re)
1075 eps *e = new media(cfg, var, re);
1076 free(const_cast<char *>(var));
1077 free(const_cast<char *>(re));
1082 set_pidfile(const char *name)
1084 cfg.set_pidfile(name);
1085 free(const_cast<char *>(name));
1089 set_variable(const char *var, const char *val)
1091 cfg.set_variable(var, val);
1092 free(const_cast<char *>(var));
1093 free(const_cast<char *>(val));
1108 fprintf(stderr, "usage: %s [-Ddn] [-l connlimit] [-f file]\n",
1114 check_devd_enabled()
1120 if (sysctlbyname(SYSCTL, &val, &len, NULL, 0) != 0)
1121 errx(1, "devctl sysctl missing from kernel!");
1123 warnx("Setting " SYSCTL " to 0");
1125 sysctlbyname(SYSCTL, NULL, NULL, &val, sizeof(val));
1133 main(int argc, char **argv)
1137 check_devd_enabled();
1138 while ((ch = getopt(argc, argv, "Ddf:l:n")) != -1) {
1147 configfile = optarg;
1150 max_clients = MAX(1, strtoul(optarg, NULL, 0));
1161 if (!dflag && nflag) {
1164 cfg.write_pidfile();
1166 signal(SIGPIPE, SIG_IGN);
1167 signal(SIGHUP, gensighand);
1168 signal(SIGINT, gensighand);
1169 signal(SIGTERM, gensighand);