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"
109 static const char notify = '!';
110 static const char nomatch = '?';
111 static const char attach = '+';
112 static const char detach = '-';
114 static struct pidfh *pfh;
119 int romeo_must_die = 0;
121 static const char *configfile = CF;
123 static void event_loop(void);
124 static void usage(void);
126 template <class T> void
127 delete_and_clear(vector<T *> &v)
129 typename vector<T *>::const_iterator i;
131 for (i = v.begin(); i != v.end(); ++i)
138 event_proc::event_proc() : _prio(-1)
143 event_proc::~event_proc()
145 delete_and_clear(_epsvec);
149 event_proc::add(eps *eps)
151 _epsvec.push_back(eps);
155 event_proc::matches(config &c) const
157 vector<eps *>::const_iterator i;
159 for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
160 if (!(*i)->do_match(c))
166 event_proc::run(config &c) const
168 vector<eps *>::const_iterator i;
170 for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
171 if (!(*i)->do_action(c))
176 action::action(const char *cmd)
188 my_system(const char *command)
192 struct sigaction ign, intact, quitact;
193 sigset_t newsigblock, oldsigblock;
195 if (!command) /* just checking... */
199 * Ignore SIGINT and SIGQUIT, block SIGCHLD. Remember to save
200 * existing signal dispositions.
202 ign.sa_handler = SIG_IGN;
203 ::sigemptyset(&ign.sa_mask);
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()) {
215 * Restore original signal dispositions and exec the command.
217 ::sigaction(SIGINT, &intact, NULL);
218 ::sigaction(SIGQUIT, &quitact, NULL);
219 ::sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
221 * Close the PID file, and all other open descriptors.
222 * Inherit std{in,out,err} only.
226 ::execl(_PATH_BSHELL, "sh", "-c", command, (char *)NULL);
228 default: /* parent */
231 pid = ::wait4(savedpid, &pstat, 0, (struct rusage *)0);
232 } while (pid == -1 && errno == EINTR);
235 ::sigaction(SIGINT, &intact, NULL);
236 ::sigaction(SIGQUIT, &quitact, NULL);
237 ::sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
238 return (pid == -1 ? -1 : pstat);
242 action::do_action(config &c)
244 string s = c.expand_string(_cmd);
246 fprintf(stderr, "Executing '%s'\n", s.c_str());
247 my_system(s.c_str());
251 match::match(config &c, const char *var, const char *re)
252 : _var(var), _re("^")
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));
259 _re.append(c.expand_string(string(re)));
263 regcomp(&_regex, _re.c_str(), REG_EXTENDED | REG_NOSUB | REG_ICASE);
272 match::do_match(config &c)
274 const string &value = c.get_variable(_var);
278 fprintf(stderr, "Testing %s=%s against %s, invert=%d\n",
279 _var.c_str(), value.c_str(), _re.c_str(), _inv);
281 retval = (regexec(&_regex, value.c_str(), 0, NULL, 0) == 0);
283 retval = (retval == 0) ? 1 : 0;
288 #include <sys/sockio.h>
290 #include <net/if_media.h>
292 media::media(config &, const char *var, const char *type)
293 : _var(var), _type(-1)
295 static struct ifmedia_description media_types[] = {
296 { IFM_ETHER, "Ethernet" },
297 { IFM_TOKEN, "Tokenring" },
298 { IFM_FDDI, "FDDI" },
299 { IFM_IEEE80211, "802.11" },
301 { IFM_CARP, "CARP" },
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;
317 media::do_match(config &c)
320 struct ifmediareq ifmr;
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");
333 fprintf(stderr, "Testing media type of %s against 0x%x\n",
334 value.c_str(), _type);
338 s = socket(PF_INET, SOCK_DGRAM, 0);
340 memset(&ifmr, 0, sizeof(ifmr));
341 strncpy(ifmr.ifm_name, value.c_str(), sizeof(ifmr.ifm_name));
343 if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0 &&
344 ifmr.ifm_status & IFM_AVALID) {
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) {
351 fprintf(stderr, "%s has unknown media type\n",
361 const string var_list::bogus = "_$_$_$_$_B_O_G_U_S_$_$_$_$_";
362 const string var_list::nothing = "";
365 var_list::get_variable(const string &var) const
367 map<string, string>::const_iterator i;
370 if (i == _vars.end())
371 return (var_list::bogus);
376 var_list::is_set(const string &var) const
378 return (_vars.find(var) != _vars.end());
382 var_list::set_variable(const string &var, const string &val)
385 fprintf(stderr, "setting %s=%s\n", var.c_str(), val.c_str());
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);
401 config::parse_one_file(const char *fn)
404 fprintf(stderr, "Parsing %s\n", fn);
405 yyin = fopen(fn, "r");
407 err(1, "Cannot open config file %s", fn);
410 errx(1, "Cannot parse %s at line %d", fn, lineno);
415 config::parse_files_in_dir(const char *dirname)
422 fprintf(stderr, "Parsing files in %s\n", dirname);
423 dirp = opendir(dirname);
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);
440 int operator()(event_proc *const&l1, event_proc *const&l2) const
442 return (l1->get_priority() > l2->get_priority());
447 config::sort_vector(vector<event_proc *> &v)
449 stable_sort(v.begin(), v.end(), epv_greater());
455 vector<string>::const_iterator i;
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);
467 config::open_pidfile()
473 pfh = pidfile_open(_pidfile.c_str(), 0600, &otherpid);
476 errx(1, "devd already running, pid: %d", (int)otherpid);
477 warn("cannot open pid file");
482 config::write_pidfile()
489 config::close_pidfile()
496 config::remove_pidfile()
503 config::add_attach(int prio, event_proc *p)
505 p->set_priority(prio);
506 _attach_list.push_back(p);
510 config::add_detach(int prio, event_proc *p)
512 p->set_priority(prio);
513 _detach_list.push_back(p);
517 config::add_directory(const char *dir)
519 _dir_list.push_back(string(dir));
523 config::add_nomatch(int prio, event_proc *p)
525 p->set_priority(prio);
526 _nomatch_list.push_back(p);
530 config::add_notify(int prio, event_proc *p)
532 p->set_priority(prio);
533 _notify_list.push_back(p);
537 config::set_pidfile(const char *fn)
539 _pidfile = string(fn);
543 config::push_var_table()
548 _var_list_table.push_back(vl);
550 fprintf(stderr, "Pushing table\n");
554 config::pop_var_table()
556 delete _var_list_table.back();
557 _var_list_table.pop_back();
559 fprintf(stderr, "Popping table\n");
563 config::set_variable(const char *var, const char *val)
565 _var_list_table.back()->set_variable(var, val);
569 config::get_variable(const string &var)
571 vector<var_list *>::reverse_iterator i;
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));
577 return (var_list::nothing);
581 config::is_id_char(char ch) const
583 return (ch != '\0' && (isalpha(ch) || isdigit(ch) || ch == '_' ||
588 config::expand_one(const char *&src, string &dst)
596 dst.append(src++, 1);
601 // Not sure if I want to support this or not, so for now we just pass
606 /* If the string ends before ) is matched , return. */
607 while (count > 0 && *src) {
610 else if (*src == '(')
612 dst.append(src++, 1);
618 if (!isalpha(*src)) {
620 dst.append(src++, 1);
624 // $var -> replace with value
626 buffer.append(src++, 1);
627 } while (is_id_char(*src));
628 buffer.append("", 1);
629 dst.append(get_variable(buffer.c_str()));
633 config::expand_string(const string &s)
641 expand_one(src, dst);
643 dst.append(src++, 1);
651 config::chop_var(char *&buffer, char *&lhs, char *&rhs)
657 walker = lhs = buffer;
658 while (is_id_char(*walker))
663 if (*walker == '"') {
666 while (*walker && *walker != '"')
674 while (*walker && !isspace(*walker))
680 while (isspace(*walker))
688 config::set_vars(char *buffer)
694 if (!chop_var(buffer, lhs, rhs))
696 set_variable(lhs, rhs);
702 config::find_and_execute(char type)
704 vector<event_proc *> *l;
705 vector<event_proc *>::const_iterator i;
729 fprintf(stderr, "Processing %s event\n", s);
730 for (i = l->begin(); i != l->end(); ++i) {
731 if ((*i)->matches(*this)) {
741 process_event(char *buffer)
748 fprintf(stderr, "Processing event '%s'\n", 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.
755 sp = cfg.set_vars(sp);
758 //? at location pnp-info on bus
759 sp = strchr(sp, ' ');
761 return; /* Can't happen? */
765 if (strncmp(sp, "at ", 3) == 0)
767 sp = cfg.set_vars(sp);
770 if (strncmp(sp, "on ", 3) == 0)
771 cfg.set_variable("bus", sp + 3);
773 case attach: /*FALLTHROUGH*/
775 sp = strchr(sp, ' ');
777 return; /* Can't happen? */
779 cfg.set_variable("device-name", buffer);
782 if (strncmp(sp, "at ", 3) == 0)
784 sp = cfg.set_vars(sp);
787 if (strncmp(sp, "on ", 3) == 0)
788 cfg.set_variable("bus", sp + 3);
792 cfg.find_and_execute(type);
797 create_socket(const char *name)
800 struct sockaddr_un sun;
802 if ((fd = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0)
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);
809 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
811 if (::bind(fd, (struct sockaddr *) & sun, slen) < 0)
814 chown(name, 0, 0); /* XXX - root.wheel */
819 unsigned int max_clients = 10; /* Default, can be overriden on cmdline. */
820 unsigned int num_clients;
824 notify_clients(const char *data, int len)
826 list<int>::iterator i;
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).
835 for (i = clients.begin(); i != clients.end(); ) {
836 if (write(*i, data, len) != len) {
839 i = clients.erase(i);
850 list<int>::iterator i;
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.
860 for (i = clients.begin(); i != clients.end(); ) {
862 s = poll(&pfd, 1, 0);
863 if ((s < 0 && s != EINTR ) ||
864 (s > 0 && (pfd.revents & POLLHUP))) {
867 i = clients.erase(i);
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.
884 s = accept(fd, NULL, NULL);
886 shutdown(s, SHUT_RD);
887 clients.push_back(s);
897 char buffer[DEVCTL_MAXBUF];
899 int server_fd, max_fd;
904 fd = open(PATH_DEVCTL, O_RDONLY);
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);
911 max_fd = max(fd, server_fd) + 1;
915 if (!once && !dflag && !nflag) {
916 // Check to see if we have any events pending.
921 rv = select(fd + 1, &fds, &fds, &fds, &tv);
922 // No events -> we've processed all pending events
925 fprintf(stderr, "Calling daemon\n");
926 cfg.remove_pidfile();
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.
942 if (num_clients < max_clients) {
944 listen(server_fd, max_clients);
947 FD_SET(server_fd, &fds);
952 listen(server_fd, 0);
958 rv = select(max_fd, &fds, NULL, NULL, &tv);
965 if (FD_ISSET(fd, &fds)) {
966 rv = read(fd, buffer, sizeof(buffer) - 1);
968 notify_clients(buffer, rv);
970 while (buffer[--rv] == '\n')
972 process_event(buffer);
981 if (FD_ISSET(server_fd, &fds))
982 new_client(server_fd);
988 * functions that the parser uses.
991 add_attach(int prio, event_proc *p)
993 cfg.add_attach(prio, p);
997 add_detach(int prio, event_proc *p)
999 cfg.add_detach(prio, p);
1003 add_directory(const char *dir)
1005 cfg.add_directory(dir);
1006 free(const_cast<char *>(dir));
1010 add_nomatch(int prio, event_proc *p)
1012 cfg.add_nomatch(prio, p);
1016 add_notify(int prio, event_proc *p)
1018 cfg.add_notify(prio, p);
1022 add_to_event_proc(event_proc *ep, eps *eps)
1025 ep = new event_proc();
1031 new_action(const char *cmd)
1033 eps *e = new action(cmd);
1034 free(const_cast<char *>(cmd));
1039 new_match(const char *var, const char *re)
1041 eps *e = new match(cfg, var, re);
1042 free(const_cast<char *>(var));
1043 free(const_cast<char *>(re));
1048 new_media(const char *var, const char *re)
1050 eps *e = new media(cfg, var, re);
1051 free(const_cast<char *>(var));
1052 free(const_cast<char *>(re));
1057 set_pidfile(const char *name)
1059 cfg.set_pidfile(name);
1060 free(const_cast<char *>(name));
1064 set_variable(const char *var, const char *val)
1066 cfg.set_variable(var, val);
1067 free(const_cast<char *>(var));
1068 free(const_cast<char *>(val));
1083 fprintf(stderr, "usage: %s [-Ddn] [-l connlimit] [-f file]\n",
1089 check_devd_enabled()
1095 if (sysctlbyname(SYSCTL, &val, &len, NULL, 0) != 0)
1096 errx(1, "devctl sysctl missing from kernel!");
1098 warnx("Setting " SYSCTL " to 0");
1100 sysctlbyname(SYSCTL, NULL, NULL, &val, sizeof(val));
1108 main(int argc, char **argv)
1112 check_devd_enabled();
1113 while ((ch = getopt(argc, argv, "Ddf:l:n")) != -1) {
1122 configfile = optarg;
1125 max_clients = MAX(1, strtoul(optarg, NULL, 0));
1136 if (!dflag && nflag) {
1139 cfg.write_pidfile();
1141 signal(SIGPIPE, SIG_IGN);
1142 signal(SIGHUP, gensighand);
1143 signal(SIGINT, gensighand);
1144 signal(SIGTERM, gensighand);