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)
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)
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 _re.append(c.expand_string(string(re)));
172 regcomp(&_regex, _re.c_str(), REG_EXTENDED | REG_NOSUB | REG_ICASE);
181 match::do_match(config &c)
183 string value = c.get_variable(_var);
187 fprintf(stderr, "Testing %s=%s against %s\n", _var.c_str(),
188 value.c_str(), _re.c_str());
190 retval = (regexec(&_regex, value.c_str(), 0, NULL, 0) == 0);
194 #include <sys/sockio.h>
196 #include <net/if_media.h>
198 media::media(config &, const char *var, const char *type)
199 : _var(var), _type(-1)
201 static struct ifmedia_description media_types[] = {
202 { IFM_ETHER, "Ethernet" },
203 { IFM_TOKEN, "Tokenring" },
204 { IFM_FDDI, "FDDI" },
205 { IFM_IEEE80211, "802.11" },
207 { IFM_CARP, "CARP" },
211 for (int i = 0; media_types[i].ifmt_string != NULL; i++)
212 if (strcasecmp(type, media_types[i].ifmt_string) == 0) {
213 _type = media_types[i].ifmt_word;
223 media::do_match(config &c)
226 struct ifmediareq ifmr;
230 // Since we can be called from both a device attach/detach
231 // context where device-name is defined and what we want,
232 // as well as from a link status context, where subsystem is
233 // the name of interest, first try device-name and fall back
234 // to subsystem if none exists.
235 value = c.get_variable("device-name");
236 if (value.length() == 0)
237 value = c.get_variable("subsystem");
239 fprintf(stderr, "Testing media type of %s against 0x%x\n",
240 value.c_str(), _type);
244 s = socket(PF_INET, SOCK_DGRAM, 0);
246 memset(&ifmr, 0, sizeof(ifmr));
247 strncpy(ifmr.ifm_name, value.c_str(), sizeof(ifmr.ifm_name));
249 if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0 &&
250 ifmr.ifm_status & IFM_AVALID) {
252 fprintf(stderr, "%s has media type 0x%x\n",
253 value.c_str(), IFM_TYPE(ifmr.ifm_active));
254 retval = (IFM_TYPE(ifmr.ifm_active) == _type);
255 } else if (_type == -1) {
257 fprintf(stderr, "%s has unknown media type\n",
267 const string var_list::bogus = "_$_$_$_$_B_O_G_U_S_$_$_$_$_";
268 const string var_list::nothing = "";
271 var_list::get_variable(const string &var) const
273 map<string, string>::const_iterator i;
276 if (i == _vars.end())
277 return (var_list::bogus);
282 var_list::is_set(const string &var) const
284 return (_vars.find(var) != _vars.end());
288 var_list::set_variable(const string &var, const string &val)
291 fprintf(stderr, "setting %s=%s\n", var.c_str(), val.c_str());
299 delete_and_clear(_var_list_table);
300 delete_and_clear(_attach_list);
301 delete_and_clear(_detach_list);
302 delete_and_clear(_nomatch_list);
303 delete_and_clear(_notify_list);
307 config::parse_one_file(const char *fn)
310 fprintf(stderr, "Parsing %s\n", fn);
311 yyin = fopen(fn, "r");
313 err(1, "Cannot open config file %s", fn);
316 errx(1, "Cannot parse %s at line %d", fn, lineno);
321 config::parse_files_in_dir(const char *dirname)
328 fprintf(stderr, "Parsing files in %s\n", dirname);
329 dirp = opendir(dirname);
332 readdir(dirp); /* Skip . */
333 readdir(dirp); /* Skip .. */
334 while ((dp = readdir(dirp)) != NULL) {
335 if (strcmp(dp->d_name + dp->d_namlen - 5, ".conf") == 0) {
336 snprintf(path, sizeof(path), "%s/%s",
337 dirname, dp->d_name);
338 parse_one_file(path);
346 int operator()(event_proc *const&l1, event_proc *const&l2)
348 return (l1->get_priority() > l2->get_priority());
353 config::sort_vector(vector<event_proc *> &v)
355 sort(v.begin(), v.end(), epv_greater());
361 vector<string>::const_iterator i;
363 parse_one_file(configfile);
364 for (i = _dir_list.begin(); i != _dir_list.end(); i++)
365 parse_files_in_dir((*i).c_str());
366 sort_vector(_attach_list);
367 sort_vector(_detach_list);
368 sort_vector(_nomatch_list);
369 sort_vector(_notify_list);
373 config::open_pidfile()
379 pfh = pidfile_open(_pidfile.c_str(), 0600, &otherpid);
382 errx(1, "devd already running, pid: %d", (int)otherpid);
383 warn("cannot open pid file");
388 config::write_pidfile()
395 config::remove_pidfile()
402 config::add_attach(int prio, event_proc *p)
404 p->set_priority(prio);
405 _attach_list.push_back(p);
409 config::add_detach(int prio, event_proc *p)
411 p->set_priority(prio);
412 _detach_list.push_back(p);
416 config::add_directory(const char *dir)
418 _dir_list.push_back(string(dir));
422 config::add_nomatch(int prio, event_proc *p)
424 p->set_priority(prio);
425 _nomatch_list.push_back(p);
429 config::add_notify(int prio, event_proc *p)
431 p->set_priority(prio);
432 _notify_list.push_back(p);
436 config::set_pidfile(const char *fn)
438 _pidfile = string(fn);
442 config::push_var_table()
447 _var_list_table.push_back(vl);
449 fprintf(stderr, "Pushing table\n");
453 config::pop_var_table()
455 delete _var_list_table.back();
456 _var_list_table.pop_back();
458 fprintf(stderr, "Popping table\n");
462 config::set_variable(const char *var, const char *val)
464 _var_list_table.back()->set_variable(var, val);
468 config::get_variable(const string &var)
470 vector<var_list *>::reverse_iterator i;
472 for (i = _var_list_table.rbegin(); i != _var_list_table.rend(); i++) {
473 if ((*i)->is_set(var))
474 return ((*i)->get_variable(var));
476 return (var_list::nothing);
480 config::is_id_char(char ch)
482 return (ch != '\0' && (isalpha(ch) || isdigit(ch) || ch == '_' ||
487 config::expand_one(const char *&src, string &dst)
490 string buffer, varstr;
495 dst.append(src++, 1);
500 // Not sure if I want to support this or not, so for now we just pass
505 /* If the string ends before ) is matched , return. */
506 while (count > 0 && *src) {
509 else if (*src == '(')
511 dst.append(src++, 1);
517 if (!isalpha(*src)) {
519 dst.append(src++, 1);
523 // $var -> replace with value
525 buffer.append(src++, 1);
526 } while (is_id_char(*src));
527 buffer.append("", 1);
528 varstr = get_variable(buffer.c_str());
533 config::expand_string(const string &s)
541 expand_one(src, dst);
543 dst.append(src++, 1);
551 config::chop_var(char *&buffer, char *&lhs, char *&rhs)
557 walker = lhs = buffer;
558 while (is_id_char(*walker))
563 if (*walker == '"') {
566 while (*walker && *walker != '"')
574 while (*walker && !isspace(*walker))
580 while (isspace(*walker))
588 config::set_vars(char *buffer)
594 if (!chop_var(buffer, lhs, rhs))
596 set_variable(lhs, rhs);
602 config::find_and_execute(char type)
604 vector<event_proc *> *l;
605 vector<event_proc *>::const_iterator i;
629 fprintf(stderr, "Processing %s event\n", s);
630 for (i = l->begin(); i != l->end(); i++) {
631 if ((*i)->matches(*this)) {
641 process_event(char *buffer)
648 fprintf(stderr, "Processing event '%s'\n", buffer);
650 cfg.push_var_table();
651 // No match doesn't have a device, and the format is a little
652 // different, so handle it separately.
655 sp = cfg.set_vars(sp);
658 //? at location pnp-info on bus
659 sp = strchr(sp, ' ');
661 return; /* Can't happen? */
663 if (strncmp(sp, "at ", 3) == 0)
665 sp = cfg.set_vars(sp);
666 if (strncmp(sp, "on ", 3) == 0)
667 cfg.set_variable("bus", sp + 3);
669 case attach: /*FALLTHROUGH*/
671 sp = strchr(sp, ' ');
673 return; /* Can't happen? */
675 cfg.set_variable("device-name", buffer);
676 if (strncmp(sp, "at ", 3) == 0)
678 sp = cfg.set_vars(sp);
679 if (strncmp(sp, "on ", 3) == 0)
680 cfg.set_variable("bus", sp + 3);
684 cfg.find_and_execute(type);
689 create_socket(const char *name)
692 struct sockaddr_un sun;
694 if ((fd = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0)
696 bzero(&sun, sizeof(sun));
697 sun.sun_family = AF_UNIX;
698 strlcpy(sun.sun_path, name, sizeof(sun.sun_path));
699 slen = SUN_LEN(&sun);
701 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
703 if (bind(fd, (struct sockaddr *) & sun, slen) < 0)
706 chown(name, 0, 0); /* XXX - root.wheel */
714 notify_clients(const char *data, int len)
717 list<int>::const_iterator i;
719 for (i = clients.begin(); i != clients.end(); i++) {
720 if (write(*i, data, len) <= 0) {
726 for (i = bad.begin(); i != bad.end(); i++)
727 clients.erase(find(clients.begin(), clients.end(), *i));
735 s = accept(fd, NULL, NULL);
737 clients.push_back(s);
745 char buffer[DEVCTL_MAXBUF];
747 int server_fd, max_fd;
751 fd = open(PATH_DEVCTL, O_RDONLY);
753 err(1, "Can't open devctl device %s", PATH_DEVCTL);
754 if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0)
755 err(1, "Can't set close-on-exec flag on devctl");
756 server_fd = create_socket(PIPE);
757 max_fd = max(fd, server_fd) + 1;
761 if (!once && !dflag && !nflag) {
762 // Check to see if we have any events pending.
767 rv = select(fd + 1, &fds, &fds, &fds, &tv);
768 // No events -> we've processed all pending events
771 fprintf(stderr, "Calling daemon\n");
772 cfg.remove_pidfile();
781 FD_SET(server_fd, &fds);
782 rv = select(max_fd, &fds, NULL, NULL, NULL);
788 if (FD_ISSET(fd, &fds)) {
789 rv = read(fd, buffer, sizeof(buffer) - 1);
791 notify_clients(buffer, rv);
793 while (buffer[--rv] == '\n')
795 process_event(buffer);
804 if (FD_ISSET(server_fd, &fds))
805 new_client(server_fd);
811 * functions that the parser uses.
814 add_attach(int prio, event_proc *p)
816 cfg.add_attach(prio, p);
820 add_detach(int prio, event_proc *p)
822 cfg.add_detach(prio, p);
826 add_directory(const char *dir)
828 cfg.add_directory(dir);
829 free(const_cast<char *>(dir));
833 add_nomatch(int prio, event_proc *p)
835 cfg.add_nomatch(prio, p);
839 add_notify(int prio, event_proc *p)
841 cfg.add_notify(prio, p);
845 add_to_event_proc(event_proc *ep, eps *eps)
848 ep = new event_proc();
854 new_action(const char *cmd)
856 eps *e = new action(cmd);
857 free(const_cast<char *>(cmd));
862 new_match(const char *var, const char *re)
864 eps *e = new match(cfg, var, re);
865 free(const_cast<char *>(var));
866 free(const_cast<char *>(re));
871 new_media(const char *var, const char *re)
873 eps *e = new media(cfg, var, re);
874 free(const_cast<char *>(var));
875 free(const_cast<char *>(re));
880 set_pidfile(const char *name)
882 cfg.set_pidfile(name);
883 free(const_cast<char *>(name));
887 set_variable(const char *var, const char *val)
889 cfg.set_variable(var, val);
890 free(const_cast<char *>(var));
891 free(const_cast<char *>(val));
906 fprintf(stderr, "usage: %s [-Ddn] [-f file]\n", getprogname());
917 if (sysctlbyname(SYSCTL, &val, &len, NULL, 0) != 0)
918 errx(1, "devctl sysctl missing from kernel!");
920 warnx("Setting " SYSCTL " to 0");
922 sysctlbyname(SYSCTL, NULL, NULL, &val, sizeof(val));
930 main(int argc, char **argv)
934 check_devd_enabled();
935 while ((ch = getopt(argc, argv, "Ddf:n")) != -1) {
955 if (!dflag && nflag) {
960 signal(SIGPIPE, SIG_IGN);
961 signal(SIGHUP, gensighand);
962 signal(SIGINT, gensighand);
963 signal(SIGTERM, gensighand);