2 * Copyright (c) 2002-2003 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
28 * DEVD control daemon.
32 // o devd.conf and devd man pages need a lot of help:
33 // - devd needs to document the unix domain socket
34 // - devd.conf needs more details on the supported statements.
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
39 #include <sys/param.h>
40 #include <sys/socket.h>
42 #include <sys/sysctl.h>
43 #include <sys/types.h>
65 #include "devd.h" /* C compatible definitions */
66 #include "devd.hh" /* C++ class definitions */
68 #define PIPE "/var/run/devd.pipe"
69 #define CF "/etc/devd.conf"
70 #define SYSCTL "hw.bus.devctl_disable"
77 static const char notify = '!';
78 static const char nomatch = '?';
79 static const char attach = '+';
80 static const char detach = '-';
82 static struct pidfh *pfh;
87 int romeo_must_die = 0;
89 static const char *configfile = CF;
91 static void event_loop(void);
92 static void usage(void);
94 template <class T> void
95 delete_and_clear(vector<T *> &v)
97 typename vector<T *>::const_iterator i;
99 for (i = v.begin(); i != v.end(); ++i)
106 event_proc::event_proc() : _prio(-1)
111 event_proc::~event_proc()
113 delete_and_clear(_epsvec);
117 event_proc::add(eps *eps)
119 _epsvec.push_back(eps);
123 event_proc::matches(config &c) const
125 vector<eps *>::const_iterator i;
127 for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
128 if (!(*i)->do_match(c))
134 event_proc::run(config &c) const
136 vector<eps *>::const_iterator i;
138 for (i = _epsvec.begin(); i != _epsvec.end(); ++i)
139 if (!(*i)->do_action(c))
144 action::action(const char *cmd)
156 action::do_action(config &c)
158 string s = c.expand_string(_cmd);
160 fprintf(stderr, "Executing '%s'\n", s.c_str());
165 match::match(config &c, const char *var, const char *re)
170 if (!c.expand_string(string(re)).empty() &&
171 c.expand_string(string(re)).at(0) == '!') {
172 _re.append(c.expand_string(string(re)).substr(1));
175 _re.append(c.expand_string(string(re)));
179 regcomp(&_regex, _re.c_str(), REG_EXTENDED | REG_NOSUB | REG_ICASE);
188 match::do_match(config &c)
190 string value = c.get_variable(_var);
194 fprintf(stderr, "Testing %s=%s against %s, invert=%d\n",
195 _var.c_str(), value.c_str(), _re.c_str(), _inv);
197 retval = (regexec(&_regex, value.c_str(), 0, NULL, 0) == 0);
199 retval = (retval == 0) ? 1 : 0;
204 #include <sys/sockio.h>
206 #include <net/if_media.h>
208 media::media(config &, const char *var, const char *type)
209 : _var(var), _type(-1)
211 static struct ifmedia_description media_types[] = {
212 { IFM_ETHER, "Ethernet" },
213 { IFM_TOKEN, "Tokenring" },
214 { IFM_FDDI, "FDDI" },
215 { IFM_IEEE80211, "802.11" },
217 { IFM_CARP, "CARP" },
221 for (int i = 0; media_types[i].ifmt_string != NULL; ++i)
222 if (strcasecmp(type, media_types[i].ifmt_string) == 0) {
223 _type = media_types[i].ifmt_word;
233 media::do_match(config &c)
236 struct ifmediareq ifmr;
240 // Since we can be called from both a device attach/detach
241 // context where device-name is defined and what we want,
242 // as well as from a link status context, where subsystem is
243 // the name of interest, first try device-name and fall back
244 // to subsystem if none exists.
245 value = c.get_variable("device-name");
246 if (value.length() == 0)
247 value = c.get_variable("subsystem");
249 fprintf(stderr, "Testing media type of %s against 0x%x\n",
250 value.c_str(), _type);
254 s = socket(PF_INET, SOCK_DGRAM, 0);
256 memset(&ifmr, 0, sizeof(ifmr));
257 strncpy(ifmr.ifm_name, value.c_str(), sizeof(ifmr.ifm_name));
259 if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0 &&
260 ifmr.ifm_status & IFM_AVALID) {
262 fprintf(stderr, "%s has media type 0x%x\n",
263 value.c_str(), IFM_TYPE(ifmr.ifm_active));
264 retval = (IFM_TYPE(ifmr.ifm_active) == _type);
265 } else if (_type == -1) {
267 fprintf(stderr, "%s has unknown media type\n",
277 const string var_list::bogus = "_$_$_$_$_B_O_G_U_S_$_$_$_$_";
278 const string var_list::nothing = "";
281 var_list::get_variable(const string &var) const
283 map<string, string>::const_iterator i;
286 if (i == _vars.end())
287 return (var_list::bogus);
292 var_list::is_set(const string &var) const
294 return (_vars.find(var) != _vars.end());
298 var_list::set_variable(const string &var, const string &val)
301 fprintf(stderr, "setting %s=%s\n", var.c_str(), val.c_str());
309 delete_and_clear(_var_list_table);
310 delete_and_clear(_attach_list);
311 delete_and_clear(_detach_list);
312 delete_and_clear(_nomatch_list);
313 delete_and_clear(_notify_list);
317 config::parse_one_file(const char *fn)
320 fprintf(stderr, "Parsing %s\n", fn);
321 yyin = fopen(fn, "r");
323 err(1, "Cannot open config file %s", fn);
326 errx(1, "Cannot parse %s at line %d", fn, lineno);
331 config::parse_files_in_dir(const char *dirname)
338 fprintf(stderr, "Parsing files in %s\n", dirname);
339 dirp = opendir(dirname);
342 readdir(dirp); /* Skip . */
343 readdir(dirp); /* Skip .. */
344 while ((dp = readdir(dirp)) != NULL) {
345 if (strcmp(dp->d_name + dp->d_namlen - 5, ".conf") == 0) {
346 snprintf(path, sizeof(path), "%s/%s",
347 dirname, dp->d_name);
348 parse_one_file(path);
356 int operator()(event_proc *const&l1, event_proc *const&l2) const
358 return (l1->get_priority() > l2->get_priority());
363 config::sort_vector(vector<event_proc *> &v)
365 stable_sort(v.begin(), v.end(), epv_greater());
371 vector<string>::const_iterator i;
373 parse_one_file(configfile);
374 for (i = _dir_list.begin(); i != _dir_list.end(); ++i)
375 parse_files_in_dir((*i).c_str());
376 sort_vector(_attach_list);
377 sort_vector(_detach_list);
378 sort_vector(_nomatch_list);
379 sort_vector(_notify_list);
383 config::open_pidfile()
389 pfh = pidfile_open(_pidfile.c_str(), 0600, &otherpid);
392 errx(1, "devd already running, pid: %d", (int)otherpid);
393 warn("cannot open pid file");
398 config::write_pidfile()
405 config::remove_pidfile()
412 config::add_attach(int prio, event_proc *p)
414 p->set_priority(prio);
415 _attach_list.push_back(p);
419 config::add_detach(int prio, event_proc *p)
421 p->set_priority(prio);
422 _detach_list.push_back(p);
426 config::add_directory(const char *dir)
428 _dir_list.push_back(string(dir));
432 config::add_nomatch(int prio, event_proc *p)
434 p->set_priority(prio);
435 _nomatch_list.push_back(p);
439 config::add_notify(int prio, event_proc *p)
441 p->set_priority(prio);
442 _notify_list.push_back(p);
446 config::set_pidfile(const char *fn)
448 _pidfile = string(fn);
452 config::push_var_table()
457 _var_list_table.push_back(vl);
459 fprintf(stderr, "Pushing table\n");
463 config::pop_var_table()
465 delete _var_list_table.back();
466 _var_list_table.pop_back();
468 fprintf(stderr, "Popping table\n");
472 config::set_variable(const char *var, const char *val)
474 _var_list_table.back()->set_variable(var, val);
478 config::get_variable(const string &var)
480 vector<var_list *>::reverse_iterator i;
482 for (i = _var_list_table.rbegin(); i != _var_list_table.rend(); ++i) {
483 if ((*i)->is_set(var))
484 return ((*i)->get_variable(var));
486 return (var_list::nothing);
490 config::is_id_char(char ch) const
492 return (ch != '\0' && (isalpha(ch) || isdigit(ch) || ch == '_' ||
497 config::expand_one(const char *&src, string &dst)
500 string buffer, varstr;
505 dst.append(src++, 1);
510 // Not sure if I want to support this or not, so for now we just pass
515 /* If the string ends before ) is matched , return. */
516 while (count > 0 && *src) {
519 else if (*src == '(')
521 dst.append(src++, 1);
527 if (!isalpha(*src)) {
529 dst.append(src++, 1);
533 // $var -> replace with value
535 buffer.append(src++, 1);
536 } while (is_id_char(*src));
537 buffer.append("", 1);
538 varstr = get_variable(buffer.c_str());
543 config::expand_string(const string &s)
551 expand_one(src, dst);
553 dst.append(src++, 1);
561 config::chop_var(char *&buffer, char *&lhs, char *&rhs)
567 walker = lhs = buffer;
568 while (is_id_char(*walker))
573 if (*walker == '"') {
576 while (*walker && *walker != '"')
584 while (*walker && !isspace(*walker))
590 while (isspace(*walker))
598 config::set_vars(char *buffer)
604 if (!chop_var(buffer, lhs, rhs))
606 set_variable(lhs, rhs);
612 config::find_and_execute(char type)
614 vector<event_proc *> *l;
615 vector<event_proc *>::const_iterator i;
639 fprintf(stderr, "Processing %s event\n", s);
640 for (i = l->begin(); i != l->end(); ++i) {
641 if ((*i)->matches(*this)) {
651 process_event(char *buffer)
658 fprintf(stderr, "Processing event '%s'\n", buffer);
660 cfg.push_var_table();
661 // No match doesn't have a device, and the format is a little
662 // different, so handle it separately.
665 sp = cfg.set_vars(sp);
668 //? at location pnp-info on bus
669 sp = strchr(sp, ' ');
671 return; /* Can't happen? */
673 if (strncmp(sp, "at ", 3) == 0)
675 sp = cfg.set_vars(sp);
676 if (strncmp(sp, "on ", 3) == 0)
677 cfg.set_variable("bus", sp + 3);
679 case attach: /*FALLTHROUGH*/
681 sp = strchr(sp, ' ');
683 return; /* Can't happen? */
685 cfg.set_variable("device-name", buffer);
686 if (strncmp(sp, "at ", 3) == 0)
688 sp = cfg.set_vars(sp);
689 if (strncmp(sp, "on ", 3) == 0)
690 cfg.set_variable("bus", sp + 3);
694 cfg.find_and_execute(type);
699 create_socket(const char *name)
702 struct sockaddr_un sun;
704 if ((fd = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0)
706 bzero(&sun, sizeof(sun));
707 sun.sun_family = AF_UNIX;
708 strlcpy(sun.sun_path, name, sizeof(sun.sun_path));
709 slen = SUN_LEN(&sun);
711 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
713 if (bind(fd, (struct sockaddr *) & sun, slen) < 0)
716 chown(name, 0, 0); /* XXX - root.wheel */
724 notify_clients(const char *data, int len)
727 list<int>::const_iterator i;
729 for (i = clients.begin(); i != clients.end(); ++i) {
730 if (write(*i, data, len) <= 0) {
736 for (i = bad.begin(); i != bad.end(); ++i)
737 clients.erase(find(clients.begin(), clients.end(), *i));
745 s = accept(fd, NULL, NULL);
747 clients.push_back(s);
755 char buffer[DEVCTL_MAXBUF];
757 int server_fd, max_fd;
761 fd = open(PATH_DEVCTL, O_RDONLY);
763 err(1, "Can't open devctl device %s", PATH_DEVCTL);
764 if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0)
765 err(1, "Can't set close-on-exec flag on devctl");
766 server_fd = create_socket(PIPE);
767 max_fd = max(fd, server_fd) + 1;
771 if (!once && !dflag && !nflag) {
772 // Check to see if we have any events pending.
777 rv = select(fd + 1, &fds, &fds, &fds, &tv);
778 // No events -> we've processed all pending events
781 fprintf(stderr, "Calling daemon\n");
782 cfg.remove_pidfile();
791 FD_SET(server_fd, &fds);
792 rv = select(max_fd, &fds, NULL, NULL, NULL);
798 if (FD_ISSET(fd, &fds)) {
799 rv = read(fd, buffer, sizeof(buffer) - 1);
801 notify_clients(buffer, rv);
803 while (buffer[--rv] == '\n')
805 process_event(buffer);
814 if (FD_ISSET(server_fd, &fds))
815 new_client(server_fd);
821 * functions that the parser uses.
824 add_attach(int prio, event_proc *p)
826 cfg.add_attach(prio, p);
830 add_detach(int prio, event_proc *p)
832 cfg.add_detach(prio, p);
836 add_directory(const char *dir)
838 cfg.add_directory(dir);
839 free(const_cast<char *>(dir));
843 add_nomatch(int prio, event_proc *p)
845 cfg.add_nomatch(prio, p);
849 add_notify(int prio, event_proc *p)
851 cfg.add_notify(prio, p);
855 add_to_event_proc(event_proc *ep, eps *eps)
858 ep = new event_proc();
864 new_action(const char *cmd)
866 eps *e = new action(cmd);
867 free(const_cast<char *>(cmd));
872 new_match(const char *var, const char *re)
874 eps *e = new match(cfg, var, re);
875 free(const_cast<char *>(var));
876 free(const_cast<char *>(re));
881 new_media(const char *var, const char *re)
883 eps *e = new media(cfg, var, re);
884 free(const_cast<char *>(var));
885 free(const_cast<char *>(re));
890 set_pidfile(const char *name)
892 cfg.set_pidfile(name);
893 free(const_cast<char *>(name));
897 set_variable(const char *var, const char *val)
899 cfg.set_variable(var, val);
900 free(const_cast<char *>(var));
901 free(const_cast<char *>(val));
916 fprintf(stderr, "usage: %s [-Ddn] [-f file]\n", getprogname());
927 if (sysctlbyname(SYSCTL, &val, &len, NULL, 0) != 0)
928 errx(1, "devctl sysctl missing from kernel!");
930 warnx("Setting " SYSCTL " to 0");
932 sysctlbyname(SYSCTL, NULL, NULL, &val, sizeof(val));
940 main(int argc, char **argv)
944 check_devd_enabled();
945 while ((ch = getopt(argc, argv, "Ddf:n")) != -1) {
965 if (!dflag && nflag) {
970 signal(SIGPIPE, SIG_IGN);
971 signal(SIGHUP, gensighand);
972 signal(SIGINT, gensighand);
973 signal(SIGTERM, gensighand);