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)
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)
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 _re.append(c.expand_string(string(re)));
255 regcomp(&_regex, _re.c_str(), REG_EXTENDED | REG_NOSUB | REG_ICASE);
264 match::do_match(config &c)
266 const string &value = c.get_variable(_var);
270 fprintf(stderr, "Testing %s=%s against %s\n", _var.c_str(),
271 value.c_str(), _re.c_str());
273 retval = (regexec(&_regex, value.c_str(), 0, NULL, 0) == 0);
277 #include <sys/sockio.h>
279 #include <net/if_media.h>
281 media::media(config &, const char *var, const char *type)
282 : _var(var), _type(-1)
284 static struct ifmedia_description media_types[] = {
285 { IFM_ETHER, "Ethernet" },
286 { IFM_TOKEN, "Tokenring" },
287 { IFM_FDDI, "FDDI" },
288 { IFM_IEEE80211, "802.11" },
290 { IFM_CARP, "CARP" },
294 for (int i = 0; media_types[i].ifmt_string != NULL; ++i)
295 if (strcasecmp(type, media_types[i].ifmt_string) == 0) {
296 _type = media_types[i].ifmt_word;
306 media::do_match(config &c)
309 struct ifmediareq ifmr;
313 // Since we can be called from both a device attach/detach
314 // context where device-name is defined and what we want,
315 // as well as from a link status context, where subsystem is
316 // the name of interest, first try device-name and fall back
317 // to subsystem if none exists.
318 value = c.get_variable("device-name");
319 if (value.length() == 0)
320 value = c.get_variable("subsystem");
322 fprintf(stderr, "Testing media type of %s against 0x%x\n",
323 value.c_str(), _type);
327 s = socket(PF_INET, SOCK_DGRAM, 0);
329 memset(&ifmr, 0, sizeof(ifmr));
330 strncpy(ifmr.ifm_name, value.c_str(), sizeof(ifmr.ifm_name));
332 if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0 &&
333 ifmr.ifm_status & IFM_AVALID) {
335 fprintf(stderr, "%s has media type 0x%x\n",
336 value.c_str(), IFM_TYPE(ifmr.ifm_active));
337 retval = (IFM_TYPE(ifmr.ifm_active) == _type);
338 } else if (_type == -1) {
340 fprintf(stderr, "%s has unknown media type\n",
350 const string var_list::bogus = "_$_$_$_$_B_O_G_U_S_$_$_$_$_";
351 const string var_list::nothing = "";
354 var_list::get_variable(const string &var) const
356 map<string, string>::const_iterator i;
359 if (i == _vars.end())
360 return (var_list::bogus);
365 var_list::is_set(const string &var) const
367 return (_vars.find(var) != _vars.end());
371 var_list::set_variable(const string &var, const string &val)
374 fprintf(stderr, "setting %s=%s\n", var.c_str(), val.c_str());
382 delete_and_clear(_var_list_table);
383 delete_and_clear(_attach_list);
384 delete_and_clear(_detach_list);
385 delete_and_clear(_nomatch_list);
386 delete_and_clear(_notify_list);
390 config::parse_one_file(const char *fn)
393 fprintf(stderr, "Parsing %s\n", fn);
394 yyin = fopen(fn, "r");
396 err(1, "Cannot open config file %s", fn);
399 errx(1, "Cannot parse %s at line %d", fn, lineno);
404 config::parse_files_in_dir(const char *dirname)
411 fprintf(stderr, "Parsing files in %s\n", dirname);
412 dirp = opendir(dirname);
415 readdir(dirp); /* Skip . */
416 readdir(dirp); /* Skip .. */
417 while ((dp = readdir(dirp)) != NULL) {
418 if (strcmp(dp->d_name + dp->d_namlen - 5, ".conf") == 0) {
419 snprintf(path, sizeof(path), "%s/%s",
420 dirname, dp->d_name);
421 parse_one_file(path);
429 int operator()(event_proc *const&l1, event_proc *const&l2)
431 return (l1->get_priority() > l2->get_priority());
436 config::sort_vector(vector<event_proc *> &v)
438 stable_sort(v.begin(), v.end(), epv_greater());
444 vector<string>::const_iterator i;
446 parse_one_file(configfile);
447 for (i = _dir_list.begin(); i != _dir_list.end(); ++i)
448 parse_files_in_dir((*i).c_str());
449 sort_vector(_attach_list);
450 sort_vector(_detach_list);
451 sort_vector(_nomatch_list);
452 sort_vector(_notify_list);
456 config::open_pidfile()
462 pfh = pidfile_open(_pidfile.c_str(), 0600, &otherpid);
465 errx(1, "devd already running, pid: %d", (int)otherpid);
466 warn("cannot open pid file");
471 config::write_pidfile()
478 config::close_pidfile()
485 config::remove_pidfile()
492 config::add_attach(int prio, event_proc *p)
494 p->set_priority(prio);
495 _attach_list.push_back(p);
499 config::add_detach(int prio, event_proc *p)
501 p->set_priority(prio);
502 _detach_list.push_back(p);
506 config::add_directory(const char *dir)
508 _dir_list.push_back(string(dir));
512 config::add_nomatch(int prio, event_proc *p)
514 p->set_priority(prio);
515 _nomatch_list.push_back(p);
519 config::add_notify(int prio, event_proc *p)
521 p->set_priority(prio);
522 _notify_list.push_back(p);
526 config::set_pidfile(const char *fn)
528 _pidfile = string(fn);
532 config::push_var_table()
537 _var_list_table.push_back(vl);
539 fprintf(stderr, "Pushing table\n");
543 config::pop_var_table()
545 delete _var_list_table.back();
546 _var_list_table.pop_back();
548 fprintf(stderr, "Popping table\n");
552 config::set_variable(const char *var, const char *val)
554 _var_list_table.back()->set_variable(var, val);
558 config::get_variable(const string &var)
560 vector<var_list *>::reverse_iterator i;
562 for (i = _var_list_table.rbegin(); i != _var_list_table.rend(); ++i) {
563 if ((*i)->is_set(var))
564 return ((*i)->get_variable(var));
566 return (var_list::nothing);
570 config::is_id_char(char ch)
572 return (ch != '\0' && (isalpha(ch) || isdigit(ch) || ch == '_' ||
577 config::expand_one(const char *&src, string &dst)
585 dst.append(src++, 1);
590 // Not sure if I want to support this or not, so for now we just pass
595 /* If the string ends before ) is matched , return. */
596 while (count > 0 && *src) {
599 else if (*src == '(')
601 dst.append(src++, 1);
607 if (!isalpha(*src)) {
609 dst.append(src++, 1);
613 // $var -> replace with value
615 buffer.append(src++, 1);
616 } while (is_id_char(*src));
617 buffer.append("", 1);
618 dst.append(get_variable(buffer.c_str()));
622 config::expand_string(const string &s)
630 expand_one(src, dst);
632 dst.append(src++, 1);
640 config::chop_var(char *&buffer, char *&lhs, char *&rhs)
646 walker = lhs = buffer;
647 while (is_id_char(*walker))
652 if (*walker == '"') {
655 while (*walker && *walker != '"')
663 while (*walker && !isspace(*walker))
669 while (isspace(*walker))
677 config::set_vars(char *buffer)
683 if (!chop_var(buffer, lhs, rhs))
685 set_variable(lhs, rhs);
691 config::find_and_execute(char type)
693 vector<event_proc *> *l;
694 vector<event_proc *>::const_iterator i;
718 fprintf(stderr, "Processing %s event\n", s);
719 for (i = l->begin(); i != l->end(); ++i) {
720 if ((*i)->matches(*this)) {
730 process_event(char *buffer)
737 fprintf(stderr, "Processing event '%s'\n", buffer);
739 cfg.push_var_table();
740 // No match doesn't have a device, and the format is a little
741 // different, so handle it separately.
744 sp = cfg.set_vars(sp);
747 //? at location pnp-info on bus
748 sp = strchr(sp, ' ');
750 return; /* Can't happen? */
754 if (strncmp(sp, "at ", 3) == 0)
756 sp = cfg.set_vars(sp);
759 if (strncmp(sp, "on ", 3) == 0)
760 cfg.set_variable("bus", sp + 3);
762 case attach: /*FALLTHROUGH*/
764 sp = strchr(sp, ' ');
766 return; /* Can't happen? */
768 cfg.set_variable("device-name", buffer);
771 if (strncmp(sp, "at ", 3) == 0)
773 sp = cfg.set_vars(sp);
776 if (strncmp(sp, "on ", 3) == 0)
777 cfg.set_variable("bus", sp + 3);
781 cfg.find_and_execute(type);
786 create_socket(const char *name)
789 struct sockaddr_un sun;
791 if ((fd = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0)
793 bzero(&sun, sizeof(sun));
794 sun.sun_family = AF_UNIX;
795 strlcpy(sun.sun_path, name, sizeof(sun.sun_path));
796 slen = SUN_LEN(&sun);
798 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
800 if (::bind(fd, (struct sockaddr *) & sun, slen) < 0)
803 chown(name, 0, 0); /* XXX - root.wheel */
811 notify_clients(const char *data, int len)
814 list<int>::const_iterator i;
816 for (i = clients.begin(); i != clients.end(); ++i) {
817 if (write(*i, data, len) <= 0) {
823 for (i = bad.begin(); i != bad.end(); ++i)
824 clients.erase(find(clients.begin(), clients.end(), *i));
832 s = accept(fd, NULL, NULL);
834 clients.push_back(s);
842 char buffer[DEVCTL_MAXBUF];
844 int server_fd, max_fd;
848 fd = open(PATH_DEVCTL, O_RDONLY);
850 err(1, "Can't open devctl device %s", PATH_DEVCTL);
851 if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0)
852 err(1, "Can't set close-on-exec flag on devctl");
853 server_fd = create_socket(PIPE);
854 max_fd = max(fd, server_fd) + 1;
858 if (!once && !dflag && !nflag) {
859 // Check to see if we have any events pending.
864 rv = select(fd + 1, &fds, &fds, &fds, &tv);
865 // No events -> we've processed all pending events
868 fprintf(stderr, "Calling daemon\n");
869 cfg.remove_pidfile();
878 FD_SET(server_fd, &fds);
879 rv = select(max_fd, &fds, NULL, NULL, NULL);
885 if (FD_ISSET(fd, &fds)) {
886 rv = read(fd, buffer, sizeof(buffer) - 1);
888 notify_clients(buffer, rv);
890 while (buffer[--rv] == '\n')
892 process_event(buffer);
901 if (FD_ISSET(server_fd, &fds))
902 new_client(server_fd);
908 * functions that the parser uses.
911 add_attach(int prio, event_proc *p)
913 cfg.add_attach(prio, p);
917 add_detach(int prio, event_proc *p)
919 cfg.add_detach(prio, p);
923 add_directory(const char *dir)
925 cfg.add_directory(dir);
926 free(const_cast<char *>(dir));
930 add_nomatch(int prio, event_proc *p)
932 cfg.add_nomatch(prio, p);
936 add_notify(int prio, event_proc *p)
938 cfg.add_notify(prio, p);
942 add_to_event_proc(event_proc *ep, eps *eps)
945 ep = new event_proc();
951 new_action(const char *cmd)
953 eps *e = new action(cmd);
954 free(const_cast<char *>(cmd));
959 new_match(const char *var, const char *re)
961 eps *e = new match(cfg, var, re);
962 free(const_cast<char *>(var));
963 free(const_cast<char *>(re));
968 new_media(const char *var, const char *re)
970 eps *e = new media(cfg, var, re);
971 free(const_cast<char *>(var));
972 free(const_cast<char *>(re));
977 set_pidfile(const char *name)
979 cfg.set_pidfile(name);
980 free(const_cast<char *>(name));
984 set_variable(const char *var, const char *val)
986 cfg.set_variable(var, val);
987 free(const_cast<char *>(var));
988 free(const_cast<char *>(val));
1003 fprintf(stderr, "usage: %s [-Ddn] [-f file]\n", getprogname());
1008 check_devd_enabled()
1014 if (sysctlbyname(SYSCTL, &val, &len, NULL, 0) != 0)
1015 errx(1, "devctl sysctl missing from kernel!");
1017 warnx("Setting " SYSCTL " to 0");
1019 sysctlbyname(SYSCTL, NULL, NULL, &val, sizeof(val));
1027 main(int argc, char **argv)
1031 check_devd_enabled();
1032 while ((ch = getopt(argc, argv, "Ddf:n")) != -1) {
1041 configfile = optarg;
1052 if (!dflag && nflag) {
1055 cfg.write_pidfile();
1057 signal(SIGPIPE, SIG_IGN);
1058 signal(SIGHUP, gensighand);
1059 signal(SIGINT, gensighand);
1060 signal(SIGTERM, gensighand);