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
26 * $FreeBSD: src/sbin/devd/devd.cc,v 1.33 2006/09/17 22:49:26 ru Exp $
27 * $DragonFly: src/sbin/devd/devd.cc,v 1.1 2008/10/03 00:26:21 hasso Exp $
31 * DEVD control daemon.
35 // o devd.conf and devd man pages need a lot of help:
36 // - devd needs to document the unix domain socket
37 // - devd.conf needs more details on the supported statements.
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 = '-';
85 int romeo_must_die = 0;
87 static const char *configfile = CF;
89 static void event_loop(void);
90 static void usage(void);
92 template <class T> void
93 delete_and_clear(vector<T *> &v)
95 typename vector<T *>::const_iterator i;
97 for (i = v.begin(); i != v.end(); i++)
104 event_proc::event_proc() : _prio(-1)
109 event_proc::~event_proc()
111 delete_and_clear(_epsvec);
115 event_proc::add(eps *eps)
117 _epsvec.push_back(eps);
121 event_proc::matches(config &c)
123 vector<eps *>::const_iterator i;
125 for (i = _epsvec.begin(); i != _epsvec.end(); i++)
126 if (!(*i)->do_match(c))
132 event_proc::run(config &c)
134 vector<eps *>::const_iterator i;
136 for (i = _epsvec.begin(); i != _epsvec.end(); i++)
137 if (!(*i)->do_action(c))
142 action::action(const char *cmd)
154 action::do_action(config &c)
156 string s = c.expand_string(_cmd);
158 fprintf(stderr, "Executing '%s'\n", s.c_str());
163 match::match(config &c, const char *var, const char *re)
168 _re.append(c.expand_string(string(re)));
170 regcomp(&_regex, _re.c_str(), REG_EXTENDED | REG_NOSUB | REG_ICASE);
179 match::do_match(config &c)
181 string value = c.get_variable(_var);
185 fprintf(stderr, "Testing %s=%s against %s\n", _var.c_str(),
186 value.c_str(), _re.c_str());
188 retval = (regexec(&_regex, value.c_str(), 0, NULL, 0) == 0);
192 #include <sys/sockio.h>
194 #include <net/if_media.h>
196 media::media(config &, const char *var, const char *type)
197 : _var(var), _type(-1)
199 static struct ifmedia_description media_types[] = {
200 { IFM_ETHER, "Ethernet" },
201 { IFM_IEEE80211, "802.11" },
203 { IFM_CARP, "CARP" },
207 for (int i = 0; media_types[i].ifmt_string != NULL; i++)
208 if (strcasecmp(type, media_types[i].ifmt_string) == 0) {
209 _type = media_types[i].ifmt_word;
219 media::do_match(config &c)
222 struct ifmediareq ifmr;
226 // Since we can be called from both a device attach/detach
227 // context where device-name is defined and what we want,
228 // as well as from a link status context, where subsystem is
229 // the name of interest, first try device-name and fall back
230 // to subsystem if none exists.
231 value = c.get_variable("device-name");
232 if (value.length() == 0)
233 value = c.get_variable("subsystem");
235 fprintf(stderr, "Testing media type of %s against 0x%x\n",
236 value.c_str(), _type);
240 s = socket(PF_INET, SOCK_DGRAM, 0);
242 memset(&ifmr, 0, sizeof(ifmr));
243 strncpy(ifmr.ifm_name, value.c_str(), sizeof(ifmr.ifm_name));
245 if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0 &&
246 ifmr.ifm_status & IFM_AVALID) {
248 fprintf(stderr, "%s has media type 0x%x\n",
249 value.c_str(), IFM_TYPE(ifmr.ifm_active));
250 retval = (IFM_TYPE(ifmr.ifm_active) == _type);
251 } else if (_type == -1) {
253 fprintf(stderr, "%s has unknown media type\n",
263 const string var_list::bogus = "_$_$_$_$_B_O_G_U_S_$_$_$_$_";
264 const string var_list::nothing = "";
267 var_list::get_variable(const string &var) const
269 map<string, string>::const_iterator i;
272 if (i == _vars.end())
273 return (var_list::bogus);
278 var_list::is_set(const string &var) const
280 return (_vars.find(var) != _vars.end());
284 var_list::set_variable(const string &var, const string &val)
287 fprintf(stderr, "setting %s=%s\n", var.c_str(), val.c_str());
295 delete_and_clear(_var_list_table);
296 delete_and_clear(_attach_list);
297 delete_and_clear(_detach_list);
298 delete_and_clear(_nomatch_list);
299 delete_and_clear(_notify_list);
303 config::parse_one_file(const char *fn)
306 printf("Parsing %s\n", fn);
307 yyin = fopen(fn, "r");
309 err(1, "Cannot open config file %s", fn);
312 errx(1, "Cannot parse %s at line %d", fn, lineno);
317 config::parse_files_in_dir(const char *dirname)
324 printf("Parsing files in %s\n", dirname);
325 dirp = opendir(dirname);
328 readdir(dirp); /* Skip . */
329 readdir(dirp); /* Skip .. */
330 while ((dp = readdir(dirp)) != NULL) {
331 if (strcmp(dp->d_name + dp->d_namlen - 5, ".conf") == 0) {
332 snprintf(path, sizeof(path), "%s/%s",
333 dirname, dp->d_name);
334 parse_one_file(path);
341 int operator()(event_proc *const&l1, event_proc *const&l2)
343 return (l1->get_priority() > l2->get_priority());
348 config::sort_vector(vector<event_proc *> &v)
350 sort(v.begin(), v.end(), epv_greater());
356 vector<string>::const_iterator i;
358 parse_one_file(configfile);
359 for (i = _dir_list.begin(); i != _dir_list.end(); i++)
360 parse_files_in_dir((*i).c_str());
361 sort_vector(_attach_list);
362 sort_vector(_detach_list);
363 sort_vector(_nomatch_list);
364 sort_vector(_notify_list);
368 config::open_pidfile()
371 errx(1, "devd already running");
375 config::add_attach(int prio, event_proc *p)
377 p->set_priority(prio);
378 _attach_list.push_back(p);
382 config::add_detach(int prio, event_proc *p)
384 p->set_priority(prio);
385 _detach_list.push_back(p);
389 config::add_directory(const char *dir)
391 _dir_list.push_back(string(dir));
395 config::add_nomatch(int prio, event_proc *p)
397 p->set_priority(prio);
398 _nomatch_list.push_back(p);
402 config::add_notify(int prio, event_proc *p)
404 p->set_priority(prio);
405 _notify_list.push_back(p);
409 config::set_pidfile(const char *fn)
411 _pidfile = string(fn);
415 config::push_var_table()
420 _var_list_table.push_back(vl);
422 fprintf(stderr, "Pushing table\n");
426 config::pop_var_table()
428 delete _var_list_table.back();
429 _var_list_table.pop_back();
431 fprintf(stderr, "Popping table\n");
435 config::set_variable(const char *var, const char *val)
437 _var_list_table.back()->set_variable(var, val);
441 config::get_variable(const string &var)
443 vector<var_list *>::reverse_iterator i;
445 for (i = _var_list_table.rbegin(); i != _var_list_table.rend(); i++) {
446 if ((*i)->is_set(var))
447 return ((*i)->get_variable(var));
449 return (var_list::nothing);
453 config::is_id_char(char ch)
455 return (ch != '\0' && (isalpha(ch) || isdigit(ch) || ch == '_' ||
460 config::expand_one(const char *&src, string &dst)
463 string buffer, varstr;
468 dst.append(src++, 1);
473 // Not sure if I want to support this or not, so for now we just pass
478 /* If the string ends before ) is matched , return. */
479 while (count > 0 && *src) {
482 else if (*src == '(')
484 dst.append(src++, 1);
490 if (!isalpha(*src)) {
492 dst.append(src++, 1);
496 // $var -> replace with value
498 buffer.append(src++, 1);
499 } while (is_id_char(*src));
500 buffer.append("", 1);
501 varstr = get_variable(buffer.c_str());
506 config::expand_string(const string &s)
514 expand_one(src, dst);
516 dst.append(src++, 1);
524 config::chop_var(char *&buffer, char *&lhs, char *&rhs)
530 walker = lhs = buffer;
531 while (is_id_char(*walker))
536 if (*walker == '"') {
539 while (*walker && *walker != '"')
547 while (*walker && !isspace(*walker))
553 while (isspace(*walker))
561 config::set_vars(char *buffer)
567 if (!chop_var(buffer, lhs, rhs))
569 set_variable(lhs, rhs);
575 config::find_and_execute(char type)
577 vector<event_proc *> *l;
578 vector<event_proc *>::const_iterator i;
602 fprintf(stderr, "Processing %s event\n", s);
603 for (i = l->begin(); i != l->end(); i++) {
604 if ((*i)->matches(*this)) {
614 process_event(char *buffer)
621 fprintf(stderr, "Processing event '%s'\n", buffer);
623 cfg.push_var_table();
624 // No match doesn't have a device, and the format is a little
625 // different, so handle it separately.
628 sp = cfg.set_vars(sp);
631 //? at location pnp-info on bus
632 sp = strchr(sp, ' ');
634 return; /* Can't happen? */
636 if (strncmp(sp, "at ", 3) == 0)
638 sp = cfg.set_vars(sp);
639 if (strncmp(sp, "on ", 3) == 0)
640 cfg.set_variable("bus", sp + 3);
642 case attach: /*FALLTHROUGH*/
644 sp = strchr(sp, ' ');
646 return; /* Can't happen? */
648 cfg.set_variable("device-name", buffer);
649 if (strncmp(sp, "at ", 3) == 0)
651 sp = cfg.set_vars(sp);
652 if (strncmp(sp, "on ", 3) == 0)
653 cfg.set_variable("bus", sp + 3);
657 cfg.find_and_execute(type);
662 create_socket(const char *name)
665 struct sockaddr_un sun;
667 if ((fd = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0)
669 bzero(&sun, sizeof(sun));
670 sun.sun_family = AF_UNIX;
671 strlcpy(sun.sun_path, name, sizeof(sun.sun_path));
672 slen = SUN_LEN(&sun);
674 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
676 if (bind(fd, (struct sockaddr *) & sun, slen) < 0)
679 chown(name, 0, 0); /* XXX - root.wheel */
687 notify_clients(const char *data, int len)
690 list<int>::const_iterator i;
692 for (i = clients.begin(); i != clients.end(); i++) {
693 if (write(*i, data, len) <= 0) {
699 for (i = bad.begin(); i != bad.end(); i++)
700 clients.erase(find(clients.begin(), clients.end(), *i));
708 s = accept(fd, NULL, NULL);
710 clients.push_back(s);
718 char buffer[DEVCTL_MAXBUF];
720 int server_fd, max_fd;
724 fd = open(PATH_DEVCTL, O_RDONLY);
726 err(1, "Can't open devctl device %s", PATH_DEVCTL);
727 if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0)
728 err(1, "Can't set close-on-exec flag on devctl");
729 server_fd = create_socket(PIPE);
730 max_fd = max(fd, server_fd) + 1;
734 if (!once && !dflag && !nflag) {
735 // Check to see if we have any events pending.
740 rv = select(fd + 1, &fds, NULL, NULL, &tv);
741 // No events -> we've processed all pending events
744 fprintf(stderr, "Calling daemon\n");
752 FD_SET(server_fd, &fds);
753 rv = select(max_fd, &fds, NULL, NULL, NULL);
759 if (FD_ISSET(fd, &fds)) {
760 rv = read(fd, buffer, sizeof(buffer) - 1);
762 notify_clients(buffer, rv);
764 while (buffer[--rv] == '\n')
766 process_event(buffer);
775 if (FD_ISSET(server_fd, &fds))
776 new_client(server_fd);
782 * functions that the parser uses.
785 add_attach(int prio, event_proc *p)
787 cfg.add_attach(prio, p);
791 add_detach(int prio, event_proc *p)
793 cfg.add_detach(prio, p);
797 add_directory(const char *dir)
799 cfg.add_directory(dir);
800 free(const_cast<char *>(dir));
804 add_nomatch(int prio, event_proc *p)
806 cfg.add_nomatch(prio, p);
810 add_notify(int prio, event_proc *p)
812 cfg.add_notify(prio, p);
816 add_to_event_proc(event_proc *ep, eps *eps)
819 ep = new event_proc();
825 new_action(const char *cmd)
827 eps *e = new action(cmd);
828 free(const_cast<char *>(cmd));
833 new_match(const char *var, const char *re)
835 eps *e = new match(cfg, var, re);
836 free(const_cast<char *>(var));
837 free(const_cast<char *>(re));
842 new_media(const char *var, const char *re)
844 eps *e = new media(cfg, var, re);
845 free(const_cast<char *>(var));
846 free(const_cast<char *>(re));
851 set_pidfile(const char *name)
853 cfg.set_pidfile(name);
854 free(const_cast<char *>(name));
858 set_variable(const char *var, const char *val)
860 cfg.set_variable(var, val);
861 free(const_cast<char *>(var));
862 free(const_cast<char *>(val));
871 unlink("/var/run/devd.pid"); /* XXX */
878 fprintf(stderr, "usage: %s [-Ddn] [-f file]\n", getprogname());
889 if (sysctlbyname(SYSCTL, &val, &len, NULL, 0) != 0)
890 errx(1, "devctl sysctl missing from kernel!");
892 warnx("Setting " SYSCTL " to 0");
894 sysctlbyname(SYSCTL, NULL, NULL, &val, sizeof(val));
902 main(int argc, char **argv)
906 check_devd_enabled();
907 while ((ch = getopt(argc, argv, "Ddf:n")) != -1) {
927 if (!dflag && nflag) {
929 fprintf(stderr, "Calling daemon\n");
933 signal(SIGPIPE, SIG_IGN);
934 signal(SIGHUP, gensighand);
935 signal(SIGINT, gensighand);
936 signal(SIGTERM, gensighand);