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>
96 #include "devd.h" /* C compatible definitions */
97 #include "devd.hh" /* C++ class definitions */
99 #define PIPE "/var/run/devd.pipe"
100 #define CF "/etc/devd.conf"
101 #define SYSCTL "hw.bus.devctl_disable"
108 static const char notify = '!';
109 static const char nomatch = '?';
110 static const char attach = '+';
111 static const char detach = '-';
113 static struct pidfh *pfh;
118 int romeo_must_die = 0;
120 static const char *configfile = CF;
122 static void event_loop(void);
123 static void usage(void);
125 template <class T> void
126 delete_and_clear(vector<T *> &v)
128 typename vector<T *>::const_iterator i;
130 for (i = v.begin(); i != v.end(); ++i)
137 event_proc::event_proc() : _prio(-1)
142 event_proc::~event_proc()
144 delete_and_clear(_epsvec);
148 event_proc::add(eps *eps)
150 _epsvec.push_back(eps);
154 event_proc::matches(config &c) const
156 vector<eps *>::const_iterator i;
158 for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
159 if (!(*i)->do_match(c))
165 event_proc::run(config &c) const
167 vector<eps *>::const_iterator i;
169 for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
170 if (!(*i)->do_action(c))
175 action::action(const char *cmd)
187 my_system(const char *command)
191 struct sigaction ign, intact, quitact;
192 sigset_t newsigblock, oldsigblock;
194 if (!command) /* just checking... */
198 * Ignore SIGINT and SIGQUIT, block SIGCHLD. Remember to save
199 * existing signal dispositions.
201 ign.sa_handler = SIG_IGN;
202 ::sigemptyset(&ign.sa_mask);
204 ::sigaction(SIGINT, &ign, &intact);
205 ::sigaction(SIGQUIT, &ign, &quitact);
206 ::sigemptyset(&newsigblock);
207 ::sigaddset(&newsigblock, SIGCHLD);
208 ::sigprocmask(SIG_BLOCK, &newsigblock, &oldsigblock);
209 switch (pid = ::fork()) {
214 * Restore original signal dispositions and exec the command.
216 ::sigaction(SIGINT, &intact, NULL);
217 ::sigaction(SIGQUIT, &quitact, NULL);
218 ::sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
220 * Close the PID file, and all other open descriptors.
221 * Inherit std{in,out,err} only.
225 ::execl(_PATH_BSHELL, "sh", "-c", command, (char *)NULL);
227 default: /* parent */
230 pid = ::wait4(savedpid, &pstat, 0, (struct rusage *)0);
231 } while (pid == -1 && errno == EINTR);
234 ::sigaction(SIGINT, &intact, NULL);
235 ::sigaction(SIGQUIT, &quitact, NULL);
236 ::sigprocmask(SIG_SETMASK, &oldsigblock, NULL);
237 return (pid == -1 ? -1 : pstat);
241 action::do_action(config &c)
243 string s = c.expand_string(_cmd);
245 fprintf(stderr, "Executing '%s'\n", s.c_str());
246 my_system(s.c_str());
250 match::match(config &c, const char *var, const char *re)
251 : _var(var), _re("^")
253 if (!c.expand_string(string(re)).empty() &&
254 c.expand_string(string(re)).at(0) == '!') {
255 _re.append(c.expand_string(string(re)).substr(1));
258 _re.append(c.expand_string(string(re)));
262 regcomp(&_regex, _re.c_str(), REG_EXTENDED | REG_NOSUB | REG_ICASE);
271 match::do_match(config &c)
273 const string &value = c.get_variable(_var);
277 fprintf(stderr, "Testing %s=%s against %s, invert=%d\n",
278 _var.c_str(), value.c_str(), _re.c_str(), _inv);
280 retval = (regexec(&_regex, value.c_str(), 0, NULL, 0) == 0);
282 retval = (retval == 0) ? 1 : 0;
287 #include <sys/sockio.h>
289 #include <net/if_media.h>
291 media::media(config &, const char *var, const char *type)
292 : _var(var), _type(-1)
294 static struct ifmedia_description media_types[] = {
295 { IFM_ETHER, "Ethernet" },
296 { IFM_TOKEN, "Tokenring" },
297 { IFM_FDDI, "FDDI" },
298 { IFM_IEEE80211, "802.11" },
303 for (int i = 0; media_types[i].ifmt_string != NULL; ++i)
304 if (strcasecmp(type, media_types[i].ifmt_string) == 0) {
305 _type = media_types[i].ifmt_word;
315 media::do_match(config &c)
318 struct ifmediareq ifmr;
322 // Since we can be called from both a device attach/detach
323 // context where device-name is defined and what we want,
324 // as well as from a link status context, where subsystem is
325 // the name of interest, first try device-name and fall back
326 // to subsystem if none exists.
327 value = c.get_variable("device-name");
328 if (value.length() == 0)
329 value = c.get_variable("subsystem");
331 fprintf(stderr, "Testing media type of %s against 0x%x\n",
332 value.c_str(), _type);
336 s = socket(PF_INET, SOCK_DGRAM, 0);
338 memset(&ifmr, 0, sizeof(ifmr));
339 strncpy(ifmr.ifm_name, value.c_str(), sizeof(ifmr.ifm_name));
341 if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0 &&
342 ifmr.ifm_status & IFM_AVALID) {
344 fprintf(stderr, "%s has media type 0x%x\n",
345 value.c_str(), IFM_TYPE(ifmr.ifm_active));
346 retval = (IFM_TYPE(ifmr.ifm_active) == _type);
347 } else if (_type == -1) {
349 fprintf(stderr, "%s has unknown media type\n",
359 const string var_list::bogus = "_$_$_$_$_B_O_G_U_S_$_$_$_$_";
360 const string var_list::nothing = "";
363 var_list::get_variable(const string &var) const
365 map<string, string>::const_iterator i;
368 if (i == _vars.end())
369 return (var_list::bogus);
374 var_list::is_set(const string &var) const
376 return (_vars.find(var) != _vars.end());
380 var_list::set_variable(const string &var, const string &val)
383 fprintf(stderr, "setting %s=%s\n", var.c_str(), val.c_str());
391 delete_and_clear(_var_list_table);
392 delete_and_clear(_attach_list);
393 delete_and_clear(_detach_list);
394 delete_and_clear(_nomatch_list);
395 delete_and_clear(_notify_list);
399 config::parse_one_file(const char *fn)
402 fprintf(stderr, "Parsing %s\n", fn);
403 yyin = fopen(fn, "r");
405 err(1, "Cannot open config file %s", fn);
408 errx(1, "Cannot parse %s at line %d", fn, lineno);
413 config::parse_files_in_dir(const char *dirname)
420 fprintf(stderr, "Parsing files in %s\n", dirname);
421 dirp = opendir(dirname);
424 readdir(dirp); /* Skip . */
425 readdir(dirp); /* Skip .. */
426 while ((dp = readdir(dirp)) != NULL) {
427 if (strcmp(dp->d_name + dp->d_namlen - 5, ".conf") == 0) {
428 snprintf(path, sizeof(path), "%s/%s",
429 dirname, dp->d_name);
430 parse_one_file(path);
438 int operator()(event_proc *const&l1, event_proc *const&l2) const
440 return (l1->get_priority() > l2->get_priority());
445 config::sort_vector(vector<event_proc *> &v)
447 stable_sort(v.begin(), v.end(), epv_greater());
453 vector<string>::const_iterator i;
455 parse_one_file(configfile);
456 for (i = _dir_list.begin(); i != _dir_list.end(); ++i)
457 parse_files_in_dir((*i).c_str());
458 sort_vector(_attach_list);
459 sort_vector(_detach_list);
460 sort_vector(_nomatch_list);
461 sort_vector(_notify_list);
465 config::open_pidfile()
471 pfh = pidfile_open(_pidfile.c_str(), 0600, &otherpid);
474 errx(1, "devd already running, pid: %d", (int)otherpid);
475 warn("cannot open pid file");
480 config::write_pidfile()
487 config::close_pidfile()
494 config::remove_pidfile()
501 config::add_attach(int prio, event_proc *p)
503 p->set_priority(prio);
504 _attach_list.push_back(p);
508 config::add_detach(int prio, event_proc *p)
510 p->set_priority(prio);
511 _detach_list.push_back(p);
515 config::add_directory(const char *dir)
517 _dir_list.push_back(string(dir));
521 config::add_nomatch(int prio, event_proc *p)
523 p->set_priority(prio);
524 _nomatch_list.push_back(p);
528 config::add_notify(int prio, event_proc *p)
530 p->set_priority(prio);
531 _notify_list.push_back(p);
535 config::set_pidfile(const char *fn)
537 _pidfile = string(fn);
541 config::push_var_table()
546 _var_list_table.push_back(vl);
548 fprintf(stderr, "Pushing table\n");
552 config::pop_var_table()
554 delete _var_list_table.back();
555 _var_list_table.pop_back();
557 fprintf(stderr, "Popping table\n");
561 config::set_variable(const char *var, const char *val)
563 _var_list_table.back()->set_variable(var, val);
567 config::get_variable(const string &var)
569 vector<var_list *>::reverse_iterator i;
571 for (i = _var_list_table.rbegin(); i != _var_list_table.rend(); ++i) {
572 if ((*i)->is_set(var))
573 return ((*i)->get_variable(var));
575 return (var_list::nothing);
579 config::is_id_char(char ch) const
581 return (ch != '\0' && (isalpha(ch) || isdigit(ch) || ch == '_' ||
586 config::expand_one(const char *&src, string &dst)
594 dst.append(src++, 1);
599 // Not sure if I want to support this or not, so for now we just pass
604 /* If the string ends before ) is matched , return. */
605 while (count > 0 && *src) {
608 else if (*src == '(')
610 dst.append(src++, 1);
616 if (!isalpha(*src)) {
618 dst.append(src++, 1);
622 // $var -> replace with value
624 buffer.append(src++, 1);
625 } while (is_id_char(*src));
626 buffer.append("", 1);
627 dst.append(get_variable(buffer.c_str()));
631 config::expand_string(const string &s)
639 expand_one(src, dst);
641 dst.append(src++, 1);
649 config::chop_var(char *&buffer, char *&lhs, char *&rhs)
655 walker = lhs = buffer;
656 while (is_id_char(*walker))
661 if (*walker == '"') {
664 while (*walker && *walker != '"')
672 while (*walker && !isspace(*walker))
678 while (isspace(*walker))
686 config::set_vars(char *buffer)
692 if (!chop_var(buffer, lhs, rhs))
694 set_variable(lhs, rhs);
700 config::find_and_execute(char type)
702 vector<event_proc *> *l;
703 vector<event_proc *>::const_iterator i;
727 fprintf(stderr, "Processing %s event\n", s);
728 for (i = l->begin(); i != l->end(); ++i) {
729 if ((*i)->matches(*this)) {
739 process_event(char *buffer)
746 fprintf(stderr, "Processing event '%s'\n", buffer);
748 cfg.push_var_table();
749 // No match doesn't have a device, and the format is a little
750 // different, so handle it separately.
753 sp = cfg.set_vars(sp);
756 //? at location pnp-info on bus
757 sp = strchr(sp, ' ');
759 return; /* Can't happen? */
763 if (strncmp(sp, "at ", 3) == 0)
765 sp = cfg.set_vars(sp);
768 if (strncmp(sp, "on ", 3) == 0)
769 cfg.set_variable("bus", sp + 3);
771 case attach: /*FALLTHROUGH*/
773 sp = strchr(sp, ' ');
775 return; /* Can't happen? */
777 cfg.set_variable("device-name", buffer);
780 if (strncmp(sp, "at ", 3) == 0)
782 sp = cfg.set_vars(sp);
785 if (strncmp(sp, "on ", 3) == 0)
786 cfg.set_variable("bus", sp + 3);
790 cfg.find_and_execute(type);
795 create_socket(const char *name)
798 struct sockaddr_un sun;
800 if ((fd = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0)
802 bzero(&sun, sizeof(sun));
803 sun.sun_family = AF_UNIX;
804 strlcpy(sun.sun_path, name, sizeof(sun.sun_path));
805 slen = SUN_LEN(&sun);
807 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
809 if (::bind(fd, (struct sockaddr *) & sun, slen) < 0)
812 chown(name, 0, 0); /* XXX - root.wheel */
820 notify_clients(const char *data, int len)
823 list<int>::const_iterator i;
825 for (i = clients.begin(); i != clients.end(); ++i) {
826 if (write(*i, data, len) <= 0) {
832 for (i = bad.begin(); i != bad.end(); ++i)
833 clients.erase(find(clients.begin(), clients.end(), *i));
841 s = accept(fd, NULL, NULL);
843 clients.push_back(s);
851 char buffer[DEVCTL_MAXBUF];
853 int server_fd, max_fd;
857 fd = open(PATH_DEVCTL, O_RDONLY | O_CLOEXEC);
859 err(1, "Can't open devctl device %s", PATH_DEVCTL);
860 server_fd = create_socket(PIPE);
861 max_fd = max(fd, server_fd) + 1;
865 if (!once && !dflag && !nflag) {
866 // Check to see if we have any events pending.
871 rv = select(fd + 1, &fds, &fds, &fds, &tv);
872 // No events -> we've processed all pending events
875 fprintf(stderr, "Calling daemon\n");
876 cfg.remove_pidfile();
885 FD_SET(server_fd, &fds);
886 rv = select(max_fd, &fds, NULL, NULL, NULL);
892 if (FD_ISSET(fd, &fds)) {
893 rv = read(fd, buffer, sizeof(buffer) - 1);
895 notify_clients(buffer, rv);
897 while (buffer[--rv] == '\n')
899 process_event(buffer);
908 if (FD_ISSET(server_fd, &fds))
909 new_client(server_fd);
915 * functions that the parser uses.
918 add_attach(int prio, event_proc *p)
920 cfg.add_attach(prio, p);
924 add_detach(int prio, event_proc *p)
926 cfg.add_detach(prio, p);
930 add_directory(const char *dir)
932 cfg.add_directory(dir);
933 free(const_cast<char *>(dir));
937 add_nomatch(int prio, event_proc *p)
939 cfg.add_nomatch(prio, p);
943 add_notify(int prio, event_proc *p)
945 cfg.add_notify(prio, p);
949 add_to_event_proc(event_proc *ep, eps *eps)
952 ep = new event_proc();
958 new_action(const char *cmd)
960 eps *e = new action(cmd);
961 free(const_cast<char *>(cmd));
966 new_match(const char *var, const char *re)
968 eps *e = new match(cfg, var, re);
969 free(const_cast<char *>(var));
970 free(const_cast<char *>(re));
975 new_media(const char *var, const char *re)
977 eps *e = new media(cfg, var, re);
978 free(const_cast<char *>(var));
979 free(const_cast<char *>(re));
984 set_pidfile(const char *name)
986 cfg.set_pidfile(name);
987 free(const_cast<char *>(name));
991 set_variable(const char *var, const char *val)
993 cfg.set_variable(var, val);
994 free(const_cast<char *>(var));
995 free(const_cast<char *>(val));
1010 fprintf(stderr, "usage: %s [-Ddn] [-f file]\n", getprogname());
1015 check_devd_enabled()
1021 if (sysctlbyname(SYSCTL, &val, &len, NULL, 0) != 0)
1022 errx(1, "devctl sysctl missing from kernel!");
1024 warnx("Setting " SYSCTL " to 0");
1026 sysctlbyname(SYSCTL, NULL, NULL, &val, sizeof(val));
1034 main(int argc, char **argv)
1038 check_devd_enabled();
1039 while ((ch = getopt(argc, argv, "Ddf:n")) != -1) {
1048 configfile = optarg;
1059 if (!dflag && nflag) {
1062 cfg.write_pidfile();
1064 signal(SIGPIPE, SIG_IGN);
1065 signal(SIGHUP, gensighand);
1066 signal(SIGINT, gensighand);
1067 signal(SIGTERM, gensighand);