1 /*- 2 * Copyright (c) 2002-2010 M. Warner Losh. 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 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. 13 * 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 24 * SUCH DAMAGE. 25 * 26 * my_system is a variation on lib/libc/stdlib/system.c: 27 * 28 * Copyright (c) 1988, 1993 29 * The Regents of the University of California. All rights reserved. 30 * 31 * Redistribution and use in source and binary forms, with or without 32 * modification, are permitted provided that the following conditions 33 * are met: 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 * 3. 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. 42 * 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 53 * SUCH DAMAGE. 54 */ 55 56 /* 57 * DEVD control daemon. 58 */ 59 60 // TODO list: 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. 64 65 #include <sys/cdefs.h> 66 __FBSDID("$FreeBSD$"); 67 68 #include <sys/param.h> 69 #include <sys/socket.h> 70 #include <sys/stat.h> 71 #include <sys/sysctl.h> 72 #include <sys/types.h> 73 #include <sys/wait.h> 74 #include <sys/un.h> 75 76 #include <cctype> 77 #include <cerrno> 78 #include <cstdlib> 79 #include <cstdio> 80 #include <csignal> 81 #include <cstring> 82 #include <cstdarg> 83 84 #include <dirent.h> 85 #include <err.h> 86 #include <fcntl.h> 87 #include <libutil.h> 88 #include <paths.h> 89 #include <poll.h> 90 #include <regex.h> 91 #include <syslog.h> 92 #include <unistd.h> 93 94 #include <algorithm> 95 #include <map> 96 #include <string> 97 #include <list> 98 #include <stdexcept> 99 #include <vector> 100 101 #include "devd.h" /* C compatible definitions */ 102 #include "devd.hh" /* C++ class definitions */ 103 104 #define STREAMPIPE "/var/run/devd.pipe" 105 #define SEQPACKETPIPE "/var/run/devd.seqpacket.pipe" 106 #define CF "/etc/devd.conf" 107 #define SYSCTL "hw.bus.devctl_queue" 108 109 /* 110 * Since the client socket is nonblocking, we must increase its send buffer to 111 * handle brief event storms. On FreeBSD, AF_UNIX sockets don't have a receive 112 * buffer, so the client can't increase the buffersize by itself. 113 * 114 * For example, when creating a ZFS pool, devd emits one 165 character 115 * resource.fs.zfs.statechange message for each vdev in the pool. The kernel 116 * allocates a 4608B mbuf for each message. Modern technology places a limit of 117 * roughly 450 drives/rack, and it's unlikely that a zpool will ever be larger 118 * than that. 119 * 120 * 450 drives * 165 bytes / drive = 74250B of data in the sockbuf 121 * 450 drives * 4608B / drive = 2073600B of mbufs in the sockbuf 122 * 123 * We can't directly set the sockbuf's mbuf limit, but we can do it indirectly. 124 * The kernel sets it to the minimum of a hard-coded maximum value and sbcc * 125 * kern.ipc.sockbuf_waste_factor, where sbcc is the socket buffer size set by 126 * the user. The default value of kern.ipc.sockbuf_waste_factor is 8. If we 127 * set the bufsize to 256k and use the kern.ipc.sockbuf_waste_factor, then the 128 * kernel will set the mbuf limit to 2MB, which is just large enough for 450 129 * drives. It also happens to be the same as the hardcoded maximum value. 130 */ 131 #define CLIENT_BUFSIZE 262144 132 133 using namespace std; 134 135 typedef struct client { 136 int fd; 137 int socktype; 138 } client_t; 139 140 extern FILE *yyin; 141 extern int lineno; 142 143 static const char notify = '!'; 144 static const char nomatch = '?'; 145 static const char attach = '+'; 146 static const char detach = '-'; 147 148 static struct pidfh *pfh; 149 150 static int no_daemon = 0; 151 static int daemonize_quick = 0; 152 static int quiet_mode = 0; 153 static unsigned total_events = 0; 154 static volatile sig_atomic_t got_siginfo = 0; 155 static volatile sig_atomic_t romeo_must_die = 0; 156 157 static const char *configfile = CF; 158 159 static void devdlog(int priority, const char* message, ...) 160 __printflike(2, 3); 161 static void event_loop(void); 162 static void usage(void); 163 164 template <class T> void 165 delete_and_clear(vector<T *> &v) 166 { 167 typename vector<T *>::const_iterator i; 168 169 for (i = v.begin(); i != v.end(); ++i) 170 delete *i; 171 v.clear(); 172 } 173 174 config cfg; 175 176 event_proc::event_proc() : _prio(-1) 177 { 178 _epsvec.reserve(4); 179 } 180 181 event_proc::~event_proc() 182 { 183 delete_and_clear(_epsvec); 184 } 185 186 void 187 event_proc::add(eps *eps) 188 { 189 _epsvec.push_back(eps); 190 } 191 192 bool 193 event_proc::matches(config &c) const 194 { 195 vector<eps *>::const_iterator i; 196 197 for (i = _epsvec.begin(); i != _epsvec.end(); ++i) 198 if (!(*i)->do_match(c)) 199 return (false); 200 return (true); 201 } 202 203 bool 204 event_proc::run(config &c) const 205 { 206 vector<eps *>::const_iterator i; 207 208 for (i = _epsvec.begin(); i != _epsvec.end(); ++i) 209 if (!(*i)->do_action(c)) 210 return (false); 211 return (true); 212 } 213 214 action::action(const char *cmd) 215 : _cmd(cmd) 216 { 217 // nothing 218 } 219 220 action::~action() 221 { 222 // nothing 223 } 224 225 static int 226 my_system(const char *command) 227 { 228 pid_t pid, savedpid; 229 int pstat; 230 struct sigaction ign, intact, quitact; 231 sigset_t newsigblock, oldsigblock; 232 233 if (!command) /* just checking... */ 234 return (1); 235 236 /* 237 * Ignore SIGINT and SIGQUIT, block SIGCHLD. Remember to save 238 * existing signal dispositions. 239 */ 240 ign.sa_handler = SIG_IGN; 241 ::sigemptyset(&ign.sa_mask); 242 ign.sa_flags = 0; 243 ::sigaction(SIGINT, &ign, &intact); 244 ::sigaction(SIGQUIT, &ign, &quitact); 245 ::sigemptyset(&newsigblock); 246 ::sigaddset(&newsigblock, SIGCHLD); 247 ::sigprocmask(SIG_BLOCK, &newsigblock, &oldsigblock); 248 switch (pid = ::fork()) { 249 case -1: /* error */ 250 break; 251 case 0: /* child */ 252 /* 253 * Restore original signal dispositions and exec the command. 254 */ 255 ::sigaction(SIGINT, &intact, NULL); 256 ::sigaction(SIGQUIT, &quitact, NULL); 257 ::sigprocmask(SIG_SETMASK, &oldsigblock, NULL); 258 /* 259 * Close the PID file, and all other open descriptors. 260 * Inherit std{in,out,err} only. 261 */ 262 cfg.close_pidfile(); 263 ::closefrom(3); 264 ::execl(_PATH_BSHELL, "sh", "-c", command, (char *)NULL); 265 ::_exit(127); 266 default: /* parent */ 267 savedpid = pid; 268 do { 269 pid = ::wait4(savedpid, &pstat, 0, (struct rusage *)0); 270 } while (pid == -1 && errno == EINTR); 271 break; 272 } 273 ::sigaction(SIGINT, &intact, NULL); 274 ::sigaction(SIGQUIT, &quitact, NULL); 275 ::sigprocmask(SIG_SETMASK, &oldsigblock, NULL); 276 return (pid == -1 ? -1 : pstat); 277 } 278 279 bool 280 action::do_action(config &c) 281 { 282 string s = c.expand_string(_cmd.c_str()); 283 devdlog(LOG_INFO, "Executing '%s'\n", s.c_str()); 284 my_system(s.c_str()); 285 return (true); 286 } 287 288 match::match(config &c, const char *var, const char *re) : 289 _inv(re[0] == '!'), 290 _var(var), 291 _re(c.expand_string(_inv ? re + 1 : re, "^", "$")) 292 { 293 regcomp(&_regex, _re.c_str(), REG_EXTENDED | REG_NOSUB | REG_ICASE); 294 } 295 296 match::~match() 297 { 298 regfree(&_regex); 299 } 300 301 bool 302 match::do_match(config &c) 303 { 304 const string &value = c.get_variable(_var); 305 bool retval; 306 307 /* 308 * This function gets called WAY too often to justify calling syslog() 309 * each time, even at LOG_DEBUG. Because if syslogd isn't running, it 310 * can consume excessive amounts of systime inside of connect(). Only 311 * log when we're in -d mode. 312 */ 313 if (no_daemon) { 314 devdlog(LOG_DEBUG, "Testing %s=%s against %s, invert=%d\n", 315 _var.c_str(), value.c_str(), _re.c_str(), _inv); 316 } 317 318 retval = (regexec(&_regex, value.c_str(), 0, NULL, 0) == 0); 319 if (_inv == 1) 320 retval = (retval == 0) ? 1 : 0; 321 322 return (retval); 323 } 324 325 #include <sys/sockio.h> 326 #include <net/if.h> 327 #include <net/if_media.h> 328 329 media::media(config &, const char *var, const char *type) 330 : _var(var), _type(-1) 331 { 332 static struct ifmedia_description media_types[] = { 333 { IFM_ETHER, "Ethernet" }, 334 { IFM_TOKEN, "Tokenring" }, 335 { IFM_FDDI, "FDDI" }, 336 { IFM_IEEE80211, "802.11" }, 337 { IFM_ATM, "ATM" }, 338 { -1, "unknown" }, 339 { 0, NULL }, 340 }; 341 for (int i = 0; media_types[i].ifmt_string != NULL; ++i) 342 if (strcasecmp(type, media_types[i].ifmt_string) == 0) { 343 _type = media_types[i].ifmt_word; 344 break; 345 } 346 } 347 348 media::~media() 349 { 350 } 351 352 bool 353 media::do_match(config &c) 354 { 355 string value; 356 struct ifmediareq ifmr; 357 bool retval; 358 int s; 359 360 // Since we can be called from both a device attach/detach 361 // context where device-name is defined and what we want, 362 // as well as from a link status context, where subsystem is 363 // the name of interest, first try device-name and fall back 364 // to subsystem if none exists. 365 value = c.get_variable("device-name"); 366 if (value.empty()) 367 value = c.get_variable("subsystem"); 368 devdlog(LOG_DEBUG, "Testing media type of %s against 0x%x\n", 369 value.c_str(), _type); 370 371 retval = false; 372 373 s = socket(PF_INET, SOCK_DGRAM, 0); 374 if (s >= 0) { 375 memset(&ifmr, 0, sizeof(ifmr)); 376 strlcpy(ifmr.ifm_name, value.c_str(), sizeof(ifmr.ifm_name)); 377 378 if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0 && 379 ifmr.ifm_status & IFM_AVALID) { 380 devdlog(LOG_DEBUG, "%s has media type 0x%x\n", 381 value.c_str(), IFM_TYPE(ifmr.ifm_active)); 382 retval = (IFM_TYPE(ifmr.ifm_active) == _type); 383 } else if (_type == -1) { 384 devdlog(LOG_DEBUG, "%s has unknown media type\n", 385 value.c_str()); 386 retval = true; 387 } 388 close(s); 389 } 390 391 return (retval); 392 } 393 394 const string var_list::bogus = "_$_$_$_$_B_O_G_U_S_$_$_$_$_"; 395 const string var_list::nothing = ""; 396 397 const string & 398 var_list::get_variable(const string &var) const 399 { 400 map<string, string>::const_iterator i; 401 402 i = _vars.find(var); 403 if (i == _vars.end()) 404 return (var_list::bogus); 405 return (i->second); 406 } 407 408 bool 409 var_list::is_set(const string &var) const 410 { 411 return (_vars.find(var) != _vars.end()); 412 } 413 414 /** fix_value 415 * 416 * Removes quoted characters that have made it this far. \" are 417 * converted to ". For all other characters, both \ and following 418 * character. So the string 'fre\:\"' is translated to 'fred\:"'. 419 */ 420 const std::string & 421 var_list::fix_value(const std::string &val) const 422 { 423 char *tmp, *dst; 424 const char *src; 425 std::string *rv; 426 427 dst = tmp = new char[val.length()]; 428 src = val.c_str(); 429 while (*src) { 430 if (*src == '\\' && src[1] == '"') 431 src++; 432 else 433 *dst++ = *src++; 434 } 435 rv = new string(tmp); 436 delete tmp; 437 return *rv; 438 } 439 440 void 441 var_list::set_variable(const string &var, const string &val) 442 { 443 /* 444 * This function gets called WAY too often to justify calling syslog() 445 * each time, even at LOG_DEBUG. Because if syslogd isn't running, it 446 * can consume excessive amounts of systime inside of connect(). Only 447 * log when we're in -d mode. 448 */ 449 _vars[var] = fix_value(val); 450 if (no_daemon) 451 devdlog(LOG_DEBUG, "setting %s=%s\n", var.c_str(), val.c_str()); 452 } 453 454 void 455 config::reset(void) 456 { 457 _dir_list.clear(); 458 delete_and_clear(_var_list_table); 459 delete_and_clear(_attach_list); 460 delete_and_clear(_detach_list); 461 delete_and_clear(_nomatch_list); 462 delete_and_clear(_notify_list); 463 } 464 465 void 466 config::parse_one_file(const char *fn) 467 { 468 devdlog(LOG_DEBUG, "Parsing %s\n", fn); 469 yyin = fopen(fn, "r"); 470 if (yyin == NULL) 471 err(1, "Cannot open config file %s", fn); 472 lineno = 1; 473 if (yyparse() != 0) 474 errx(1, "Cannot parse %s at line %d", fn, lineno); 475 fclose(yyin); 476 } 477 478 void 479 config::parse_files_in_dir(const char *dirname) 480 { 481 DIR *dirp; 482 struct dirent *dp; 483 char path[PATH_MAX]; 484 485 devdlog(LOG_DEBUG, "Parsing files in %s\n", dirname); 486 dirp = opendir(dirname); 487 if (dirp == NULL) 488 return; 489 readdir(dirp); /* Skip . */ 490 readdir(dirp); /* Skip .. */ 491 while ((dp = readdir(dirp)) != NULL) { 492 if (strcmp(dp->d_name + dp->d_namlen - 5, ".conf") == 0) { 493 snprintf(path, sizeof(path), "%s/%s", 494 dirname, dp->d_name); 495 parse_one_file(path); 496 } 497 } 498 closedir(dirp); 499 } 500 501 class epv_greater { 502 public: 503 int operator()(event_proc *const&l1, event_proc *const&l2) const 504 { 505 return (l1->get_priority() > l2->get_priority()); 506 } 507 }; 508 509 void 510 config::sort_vector(vector<event_proc *> &v) 511 { 512 stable_sort(v.begin(), v.end(), epv_greater()); 513 } 514 515 void 516 config::parse(void) 517 { 518 vector<string>::const_iterator i; 519 520 parse_one_file(configfile); 521 for (i = _dir_list.begin(); i != _dir_list.end(); ++i) 522 parse_files_in_dir((*i).c_str()); 523 sort_vector(_attach_list); 524 sort_vector(_detach_list); 525 sort_vector(_nomatch_list); 526 sort_vector(_notify_list); 527 } 528 529 void 530 config::open_pidfile() 531 { 532 pid_t otherpid; 533 534 if (_pidfile.empty()) 535 return; 536 pfh = pidfile_open(_pidfile.c_str(), 0600, &otherpid); 537 if (pfh == NULL) { 538 if (errno == EEXIST) 539 errx(1, "devd already running, pid: %d", (int)otherpid); 540 warn("cannot open pid file"); 541 } 542 } 543 544 void 545 config::write_pidfile() 546 { 547 548 pidfile_write(pfh); 549 } 550 551 void 552 config::close_pidfile() 553 { 554 555 pidfile_close(pfh); 556 } 557 558 void 559 config::remove_pidfile() 560 { 561 562 pidfile_remove(pfh); 563 } 564 565 void 566 config::add_attach(int prio, event_proc *p) 567 { 568 p->set_priority(prio); 569 _attach_list.push_back(p); 570 } 571 572 void 573 config::add_detach(int prio, event_proc *p) 574 { 575 p->set_priority(prio); 576 _detach_list.push_back(p); 577 } 578 579 void 580 config::add_directory(const char *dir) 581 { 582 _dir_list.push_back(string(dir)); 583 } 584 585 void 586 config::add_nomatch(int prio, event_proc *p) 587 { 588 p->set_priority(prio); 589 _nomatch_list.push_back(p); 590 } 591 592 void 593 config::add_notify(int prio, event_proc *p) 594 { 595 p->set_priority(prio); 596 _notify_list.push_back(p); 597 } 598 599 void 600 config::set_pidfile(const char *fn) 601 { 602 _pidfile = fn; 603 } 604 605 void 606 config::push_var_table() 607 { 608 var_list *vl; 609 610 vl = new var_list(); 611 _var_list_table.push_back(vl); 612 devdlog(LOG_DEBUG, "Pushing table\n"); 613 } 614 615 void 616 config::pop_var_table() 617 { 618 delete _var_list_table.back(); 619 _var_list_table.pop_back(); 620 devdlog(LOG_DEBUG, "Popping table\n"); 621 } 622 623 void 624 config::set_variable(const char *var, const char *val) 625 { 626 _var_list_table.back()->set_variable(var, val); 627 } 628 629 const string & 630 config::get_variable(const string &var) 631 { 632 vector<var_list *>::reverse_iterator i; 633 634 for (i = _var_list_table.rbegin(); i != _var_list_table.rend(); ++i) { 635 if ((*i)->is_set(var)) 636 return ((*i)->get_variable(var)); 637 } 638 return (var_list::nothing); 639 } 640 641 bool 642 config::is_id_char(char ch) const 643 { 644 return (ch != '\0' && (isalpha(ch) || isdigit(ch) || ch == '_' || 645 ch == '-')); 646 } 647 648 void 649 config::expand_one(const char *&src, string &dst) 650 { 651 int count; 652 string buffer; 653 654 src++; 655 // $$ -> $ 656 if (*src == '$') { 657 dst += *src++; 658 return; 659 } 660 661 // $(foo) -> $(foo) 662 // Not sure if I want to support this or not, so for now we just pass 663 // it through. 664 if (*src == '(') { 665 dst += '$'; 666 count = 1; 667 /* If the string ends before ) is matched , return. */ 668 while (count > 0 && *src) { 669 if (*src == ')') 670 count--; 671 else if (*src == '(') 672 count++; 673 dst += *src++; 674 } 675 return; 676 } 677 678 // $[^-A-Za-z_*] -> $\1 679 if (!isalpha(*src) && *src != '_' && *src != '-' && *src != '*') { 680 dst += '$'; 681 dst += *src++; 682 return; 683 } 684 685 // $var -> replace with value 686 do { 687 buffer += *src++; 688 } while (is_id_char(*src)); 689 dst.append(get_variable(buffer)); 690 } 691 692 const string 693 config::expand_string(const char *src, const char *prepend, const char *append) 694 { 695 const char *var_at; 696 string dst; 697 698 /* 699 * 128 bytes is enough for 2427 of 2438 expansions that happen 700 * while parsing config files, as tested on 2013-01-30. 701 */ 702 dst.reserve(128); 703 704 if (prepend != NULL) 705 dst = prepend; 706 707 for (;;) { 708 var_at = strchr(src, '$'); 709 if (var_at == NULL) { 710 dst.append(src); 711 break; 712 } 713 dst.append(src, var_at - src); 714 src = var_at; 715 expand_one(src, dst); 716 } 717 718 if (append != NULL) 719 dst.append(append); 720 721 return (dst); 722 } 723 724 bool 725 config::chop_var(char *&buffer, char *&lhs, char *&rhs) const 726 { 727 char *walker; 728 729 if (*buffer == '\0') 730 return (false); 731 walker = lhs = buffer; 732 while (is_id_char(*walker)) 733 walker++; 734 if (*walker != '=') 735 return (false); 736 walker++; // skip = 737 if (*walker == '"') { 738 walker++; // skip " 739 rhs = walker; 740 while (*walker && *walker != '"') { 741 // Skip \" ... We leave it in the string and strip the \ later. 742 // due to the super simplistic parser that we have here. 743 if (*walker == '\\' && walker[1] == '"') 744 walker++; 745 walker++; 746 } 747 if (*walker != '"') 748 return (false); 749 rhs[-2] = '\0'; 750 *walker++ = '\0'; 751 } else { 752 rhs = walker; 753 while (*walker && !isspace(*walker)) 754 walker++; 755 if (*walker != '\0') 756 *walker++ = '\0'; 757 rhs[-1] = '\0'; 758 } 759 while (isspace(*walker)) 760 walker++; 761 buffer = walker; 762 return (true); 763 } 764 765 766 char * 767 config::set_vars(char *buffer) 768 { 769 char *lhs; 770 char *rhs; 771 772 while (1) { 773 if (!chop_var(buffer, lhs, rhs)) 774 break; 775 set_variable(lhs, rhs); 776 } 777 return (buffer); 778 } 779 780 void 781 config::find_and_execute(char type) 782 { 783 vector<event_proc *> *l; 784 vector<event_proc *>::const_iterator i; 785 const char *s; 786 787 switch (type) { 788 default: 789 return; 790 case notify: 791 l = &_notify_list; 792 s = "notify"; 793 break; 794 case nomatch: 795 l = &_nomatch_list; 796 s = "nomatch"; 797 break; 798 case attach: 799 l = &_attach_list; 800 s = "attach"; 801 break; 802 case detach: 803 l = &_detach_list; 804 s = "detach"; 805 break; 806 } 807 devdlog(LOG_DEBUG, "Processing %s event\n", s); 808 for (i = l->begin(); i != l->end(); ++i) { 809 if ((*i)->matches(*this)) { 810 (*i)->run(*this); 811 break; 812 } 813 } 814 815 } 816 817 818 static void 819 process_event(char *buffer) 820 { 821 char type; 822 char *sp; 823 struct timeval tv; 824 char *timestr; 825 826 sp = buffer + 1; 827 devdlog(LOG_INFO, "Processing event '%s'\n", buffer); 828 type = *buffer++; 829 cfg.push_var_table(); 830 // $* is the entire line 831 cfg.set_variable("*", buffer - 1); 832 // $_ is the entire line without the initial character 833 cfg.set_variable("_", buffer); 834 835 // Save the time this happened (as approximated by when we got 836 // around to processing it). 837 gettimeofday(&tv, NULL); 838 asprintf(×tr, "%jd.%06ld", (uintmax_t)tv.tv_sec, tv.tv_usec); 839 cfg.set_variable("timestamp", timestr); 840 free(timestr); 841 842 // Match doesn't have a device, and the format is a little 843 // different, so handle it separately. 844 switch (type) { 845 case notify: 846 //! (k=v)* 847 sp = cfg.set_vars(sp); 848 break; 849 case nomatch: 850 //? at location pnp-info on bus 851 sp = strchr(sp, ' '); 852 if (sp == NULL) 853 return; /* Can't happen? */ 854 *sp++ = '\0'; 855 while (isspace(*sp)) 856 sp++; 857 if (strncmp(sp, "at ", 3) == 0) 858 sp += 3; 859 sp = cfg.set_vars(sp); 860 while (isspace(*sp)) 861 sp++; 862 if (strncmp(sp, "on ", 3) == 0) 863 cfg.set_variable("bus", sp + 3); 864 break; 865 case attach: /*FALLTHROUGH*/ 866 case detach: 867 sp = strchr(sp, ' '); 868 if (sp == NULL) 869 return; /* Can't happen? */ 870 *sp++ = '\0'; 871 cfg.set_variable("device-name", buffer); 872 while (isspace(*sp)) 873 sp++; 874 if (strncmp(sp, "at ", 3) == 0) 875 sp += 3; 876 sp = cfg.set_vars(sp); 877 while (isspace(*sp)) 878 sp++; 879 if (strncmp(sp, "on ", 3) == 0) 880 cfg.set_variable("bus", sp + 3); 881 break; 882 } 883 884 cfg.find_and_execute(type); 885 cfg.pop_var_table(); 886 } 887 888 int 889 create_socket(const char *name, int socktype) 890 { 891 int fd, slen; 892 struct sockaddr_un sun; 893 894 if ((fd = socket(PF_LOCAL, socktype, 0)) < 0) 895 err(1, "socket"); 896 bzero(&sun, sizeof(sun)); 897 sun.sun_family = AF_UNIX; 898 strlcpy(sun.sun_path, name, sizeof(sun.sun_path)); 899 slen = SUN_LEN(&sun); 900 unlink(name); 901 if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0) 902 err(1, "fcntl"); 903 if (::bind(fd, (struct sockaddr *) & sun, slen) < 0) 904 err(1, "bind"); 905 listen(fd, 4); 906 if (chown(name, 0, 0)) /* XXX - root.wheel */ 907 err(1, "chown"); 908 if (chmod(name, 0666)) 909 err(1, "chmod"); 910 return (fd); 911 } 912 913 unsigned int max_clients = 10; /* Default, can be overridden on cmdline. */ 914 unsigned int num_clients; 915 916 list<client_t> clients; 917 918 void 919 notify_clients(const char *data, int len) 920 { 921 list<client_t>::iterator i; 922 923 /* 924 * Deliver the data to all clients. Throw clients overboard at the 925 * first sign of trouble. This reaps clients who've died or closed 926 * their sockets, and also clients who are alive but failing to keep up 927 * (or who are maliciously not reading, to consume buffer space in 928 * kernel memory or tie up the limited number of available connections). 929 */ 930 for (i = clients.begin(); i != clients.end(); ) { 931 int flags; 932 if (i->socktype == SOCK_SEQPACKET) 933 flags = MSG_EOR; 934 else 935 flags = 0; 936 937 if (send(i->fd, data, len, flags) != len) { 938 --num_clients; 939 close(i->fd); 940 i = clients.erase(i); 941 devdlog(LOG_WARNING, "notify_clients: send() failed; " 942 "dropping unresponsive client\n"); 943 } else 944 ++i; 945 } 946 } 947 948 void 949 check_clients(void) 950 { 951 int s; 952 struct pollfd pfd; 953 list<client_t>::iterator i; 954 955 /* 956 * Check all existing clients to see if any of them have disappeared. 957 * Normally we reap clients when we get an error trying to send them an 958 * event. This check eliminates the problem of an ever-growing list of 959 * zombie clients because we're never writing to them on a system 960 * without frequent device-change activity. 961 */ 962 pfd.events = 0; 963 for (i = clients.begin(); i != clients.end(); ) { 964 pfd.fd = i->fd; 965 s = poll(&pfd, 1, 0); 966 if ((s < 0 && s != EINTR ) || 967 (s > 0 && (pfd.revents & POLLHUP))) { 968 --num_clients; 969 close(i->fd); 970 i = clients.erase(i); 971 devdlog(LOG_NOTICE, "check_clients: " 972 "dropping disconnected client\n"); 973 } else 974 ++i; 975 } 976 } 977 978 void 979 new_client(int fd, int socktype) 980 { 981 client_t s; 982 int sndbuf_size; 983 984 /* 985 * First go reap any zombie clients, then accept the connection, and 986 * shut down the read side to stop clients from consuming kernel memory 987 * by sending large buffers full of data we'll never read. 988 */ 989 check_clients(); 990 s.socktype = socktype; 991 s.fd = accept(fd, NULL, NULL); 992 if (s.fd != -1) { 993 sndbuf_size = CLIENT_BUFSIZE; 994 if (setsockopt(s.fd, SOL_SOCKET, SO_SNDBUF, &sndbuf_size, 995 sizeof(sndbuf_size))) 996 err(1, "setsockopt"); 997 shutdown(s.fd, SHUT_RD); 998 clients.push_back(s); 999 ++num_clients; 1000 } else 1001 err(1, "accept"); 1002 } 1003 1004 static void 1005 event_loop(void) 1006 { 1007 int rv; 1008 int fd; 1009 char buffer[DEVCTL_MAXBUF]; 1010 int once = 0; 1011 int stream_fd, seqpacket_fd, max_fd; 1012 int accepting; 1013 timeval tv; 1014 fd_set fds; 1015 1016 fd = open(PATH_DEVCTL, O_RDONLY | O_CLOEXEC); 1017 if (fd == -1) 1018 err(1, "Can't open devctl device %s", PATH_DEVCTL); 1019 stream_fd = create_socket(STREAMPIPE, SOCK_STREAM); 1020 seqpacket_fd = create_socket(SEQPACKETPIPE, SOCK_SEQPACKET); 1021 accepting = 1; 1022 max_fd = max(fd, max(stream_fd, seqpacket_fd)) + 1; 1023 while (!romeo_must_die) { 1024 if (!once && !no_daemon && !daemonize_quick) { 1025 // Check to see if we have any events pending. 1026 tv.tv_sec = 0; 1027 tv.tv_usec = 0; 1028 FD_ZERO(&fds); 1029 FD_SET(fd, &fds); 1030 rv = select(fd + 1, &fds, &fds, &fds, &tv); 1031 // No events -> we've processed all pending events 1032 if (rv == 0) { 1033 devdlog(LOG_DEBUG, "Calling daemon\n"); 1034 cfg.remove_pidfile(); 1035 cfg.open_pidfile(); 1036 daemon(0, 0); 1037 cfg.write_pidfile(); 1038 once++; 1039 } 1040 } 1041 /* 1042 * When we've already got the max number of clients, stop 1043 * accepting new connections (don't put the listening sockets in 1044 * the set), shrink the accept() queue to reject connections 1045 * quickly, and poll the existing clients more often, so that we 1046 * notice more quickly when any of them disappear to free up 1047 * client slots. 1048 */ 1049 FD_ZERO(&fds); 1050 FD_SET(fd, &fds); 1051 if (num_clients < max_clients) { 1052 if (!accepting) { 1053 listen(stream_fd, max_clients); 1054 listen(seqpacket_fd, max_clients); 1055 accepting = 1; 1056 } 1057 FD_SET(stream_fd, &fds); 1058 FD_SET(seqpacket_fd, &fds); 1059 tv.tv_sec = 60; 1060 tv.tv_usec = 0; 1061 } else { 1062 if (accepting) { 1063 listen(stream_fd, 0); 1064 listen(seqpacket_fd, 0); 1065 accepting = 0; 1066 } 1067 tv.tv_sec = 2; 1068 tv.tv_usec = 0; 1069 } 1070 rv = select(max_fd, &fds, NULL, NULL, &tv); 1071 if (got_siginfo) { 1072 devdlog(LOG_NOTICE, "Events received so far=%u\n", 1073 total_events); 1074 got_siginfo = 0; 1075 } 1076 if (rv == -1) { 1077 if (errno == EINTR) 1078 continue; 1079 err(1, "select"); 1080 } else if (rv == 0) 1081 check_clients(); 1082 if (FD_ISSET(fd, &fds)) { 1083 rv = read(fd, buffer, sizeof(buffer) - 1); 1084 if (rv > 0) { 1085 total_events++; 1086 if (rv == sizeof(buffer) - 1) { 1087 devdlog(LOG_WARNING, "Warning: " 1088 "available event data exceeded " 1089 "buffer space\n"); 1090 } 1091 notify_clients(buffer, rv); 1092 buffer[rv] = '\0'; 1093 while (buffer[--rv] == '\n') 1094 buffer[rv] = '\0'; 1095 try { 1096 process_event(buffer); 1097 } 1098 catch (std::length_error e) { 1099 devdlog(LOG_ERR, "Dropping event %s " 1100 "due to low memory", buffer); 1101 } 1102 } else if (rv < 0) { 1103 if (errno != EINTR) 1104 break; 1105 } else { 1106 /* EOF */ 1107 break; 1108 } 1109 } 1110 if (FD_ISSET(stream_fd, &fds)) 1111 new_client(stream_fd, SOCK_STREAM); 1112 /* 1113 * Aside from the socket type, both sockets use the same 1114 * protocol, so we can process clients the same way. 1115 */ 1116 if (FD_ISSET(seqpacket_fd, &fds)) 1117 new_client(seqpacket_fd, SOCK_SEQPACKET); 1118 } 1119 close(seqpacket_fd); 1120 close(stream_fd); 1121 close(fd); 1122 } 1123 1124 /* 1125 * functions that the parser uses. 1126 */ 1127 void 1128 add_attach(int prio, event_proc *p) 1129 { 1130 cfg.add_attach(prio, p); 1131 } 1132 1133 void 1134 add_detach(int prio, event_proc *p) 1135 { 1136 cfg.add_detach(prio, p); 1137 } 1138 1139 void 1140 add_directory(const char *dir) 1141 { 1142 cfg.add_directory(dir); 1143 free(const_cast<char *>(dir)); 1144 } 1145 1146 void 1147 add_nomatch(int prio, event_proc *p) 1148 { 1149 cfg.add_nomatch(prio, p); 1150 } 1151 1152 void 1153 add_notify(int prio, event_proc *p) 1154 { 1155 cfg.add_notify(prio, p); 1156 } 1157 1158 event_proc * 1159 add_to_event_proc(event_proc *ep, eps *eps) 1160 { 1161 if (ep == NULL) 1162 ep = new event_proc(); 1163 ep->add(eps); 1164 return (ep); 1165 } 1166 1167 eps * 1168 new_action(const char *cmd) 1169 { 1170 eps *e = new action(cmd); 1171 free(const_cast<char *>(cmd)); 1172 return (e); 1173 } 1174 1175 eps * 1176 new_match(const char *var, const char *re) 1177 { 1178 eps *e = new match(cfg, var, re); 1179 free(const_cast<char *>(var)); 1180 free(const_cast<char *>(re)); 1181 return (e); 1182 } 1183 1184 eps * 1185 new_media(const char *var, const char *re) 1186 { 1187 eps *e = new media(cfg, var, re); 1188 free(const_cast<char *>(var)); 1189 free(const_cast<char *>(re)); 1190 return (e); 1191 } 1192 1193 void 1194 set_pidfile(const char *name) 1195 { 1196 cfg.set_pidfile(name); 1197 free(const_cast<char *>(name)); 1198 } 1199 1200 void 1201 set_variable(const char *var, const char *val) 1202 { 1203 cfg.set_variable(var, val); 1204 free(const_cast<char *>(var)); 1205 free(const_cast<char *>(val)); 1206 } 1207 1208 1209 1210 static void 1211 gensighand(int) 1212 { 1213 romeo_must_die = 1; 1214 } 1215 1216 /* 1217 * SIGINFO handler. Will print useful statistics to the syslog or stderr 1218 * as appropriate 1219 */ 1220 static void 1221 siginfohand(int) 1222 { 1223 got_siginfo = 1; 1224 } 1225 1226 /* 1227 * Local logging function. Prints to syslog if we're daemonized; stderr 1228 * otherwise. 1229 */ 1230 static void 1231 devdlog(int priority, const char* fmt, ...) 1232 { 1233 va_list argp; 1234 1235 va_start(argp, fmt); 1236 if (no_daemon) 1237 vfprintf(stderr, fmt, argp); 1238 else if (quiet_mode == 0 || priority <= LOG_WARNING) 1239 vsyslog(priority, fmt, argp); 1240 va_end(argp); 1241 } 1242 1243 static void 1244 usage() 1245 { 1246 fprintf(stderr, "usage: %s [-dnq] [-l connlimit] [-f file]\n", 1247 getprogname()); 1248 exit(1); 1249 } 1250 1251 static void 1252 check_devd_enabled() 1253 { 1254 int val = 0; 1255 size_t len; 1256 1257 len = sizeof(val); 1258 if (sysctlbyname(SYSCTL, &val, &len, NULL, 0) != 0) 1259 errx(1, "devctl sysctl missing from kernel!"); 1260 if (val == 0) { 1261 warnx("Setting " SYSCTL " to 1000"); 1262 val = 1000; 1263 if (sysctlbyname(SYSCTL, NULL, NULL, &val, sizeof(val))) 1264 err(1, "sysctlbyname"); 1265 } 1266 } 1267 1268 /* 1269 * main 1270 */ 1271 int 1272 main(int argc, char **argv) 1273 { 1274 int ch; 1275 1276 check_devd_enabled(); 1277 while ((ch = getopt(argc, argv, "df:l:nq")) != -1) { 1278 switch (ch) { 1279 case 'd': 1280 no_daemon = 1; 1281 break; 1282 case 'f': 1283 configfile = optarg; 1284 break; 1285 case 'l': 1286 max_clients = MAX(1, strtoul(optarg, NULL, 0)); 1287 break; 1288 case 'n': 1289 daemonize_quick = 1; 1290 break; 1291 case 'q': 1292 quiet_mode = 1; 1293 break; 1294 default: 1295 usage(); 1296 } 1297 } 1298 1299 cfg.parse(); 1300 if (!no_daemon && daemonize_quick) { 1301 cfg.open_pidfile(); 1302 daemon(0, 0); 1303 cfg.write_pidfile(); 1304 } 1305 signal(SIGPIPE, SIG_IGN); 1306 signal(SIGHUP, gensighand); 1307 signal(SIGINT, gensighand); 1308 signal(SIGTERM, gensighand); 1309 signal(SIGINFO, siginfohand); 1310 event_loop(); 1311 return (0); 1312 } 1313