1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172
|
/*
* Copyright (C) 2005-2007 Red Hat, Inc. All rights reserved.
*
* This file is part of the device-mapper userspace tools.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License v.2.1.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* dmeventd - dm event daemon to monitor active mapped devices
*/
#define _GNU_SOURCE
#define _FILE_OFFSET_BITS 64
#include "configure.h"
#include "libdevmapper.h"
#include "libdevmapper-event.h"
#include "dmeventd.h"
//#include "libmultilog.h"
#include "dm-logging.h"
#include <stdarg.h>
#include <dlfcn.h>
#include <errno.h>
#include <pthread.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
#include <signal.h>
#include <arpa/inet.h> /* for htonl, ntohl */
#include <fcntl.h> /* for musl libc */
#ifdef __linux__
/*
* Kernel version 2.6.36 and higher has
* new OOM killer adjustment interface.
*/
# define OOM_ADJ_FILE_OLD "/proc/self/oom_adj"
# define OOM_ADJ_FILE "/proc/self/oom_score_adj"
/* From linux/oom.h */
/* Old interface */
# define OOM_DISABLE (-17)
# define OOM_ADJUST_MIN (-16)
/* New interface */
# define OOM_SCORE_ADJ_MIN (-1000)
/* Systemd on-demand activation support */
# define SD_RUNTIME_UNIT_FILE_DIR DEFAULT_DM_RUN_DIR "/systemd/system/"
# define SD_ACTIVATION_ENV_VAR_NAME "SD_ACTIVATION"
# define SD_LISTEN_PID_ENV_VAR_NAME "LISTEN_PID"
# define SD_LISTEN_FDS_ENV_VAR_NAME "LISTEN_FDS"
# define SD_LISTEN_FDS_START 3
# define SD_FD_FIFO_SERVER SD_LISTEN_FDS_START
# define SD_FD_FIFO_CLIENT (SD_LISTEN_FDS_START + 1)
#endif
/* FIXME We use syslog for now, because multilog is not yet implemented */
#include <syslog.h>
static volatile sig_atomic_t _exit_now = 0; /* set to '1' when signal is given to exit */
/* List (un)link macros. */
#define LINK(x, head) dm_list_add(head, &(x)->list)
#define LINK_DSO(dso) LINK(dso, &_dso_registry)
#define LINK_THREAD(thread) LINK(thread, &_thread_registry)
#define UNLINK(x) dm_list_del(&(x)->list)
#define UNLINK_DSO(x) UNLINK(x)
#define UNLINK_THREAD(x) UNLINK(x)
#define DAEMON_NAME "dmeventd"
/*
Global mutex for thread list access. Has to be held when:
- iterating thread list
- adding or removing elements from thread list
- changing or reading thread_status's fields:
processing, status, events
Use _lock_mutex() and _unlock_mutex() to hold/release it
*/
static pthread_mutex_t _global_mutex;
/*
There are three states a thread can attain (see struct
thread_status, field int status):
- DM_THREAD_RUNNING: thread has started up and is either working or
waiting for events... transitions to either SHUTDOWN or DONE
- DM_THREAD_SHUTDOWN: thread is still doing something, but it is
supposed to terminate (and transition to DONE) as soon as it
finishes whatever it was doing at the point of flipping state to
SHUTDOWN... the thread is still on the thread list
- DM_THREAD_DONE: thread has terminated and has been moved over to
unused thread list, cleanup pending
*/
#define DM_THREAD_RUNNING 0
#define DM_THREAD_SHUTDOWN 1
#define DM_THREAD_DONE 2
#define THREAD_STACK_SIZE (300*1024)
int dmeventd_debug = 0;
static int _systemd_activation = 0;
static int _foreground = 0;
static int _restart = 0;
static char **_initial_registrations = 0;
/* Data kept about a DSO. */
struct dso_data {
struct dm_list list;
char *dso_name; /* DSO name (eg, "evms", "dmraid", "lvm2"). */
void *dso_handle; /* Opaque handle as returned from dlopen(). */
unsigned int ref_count; /* Library reference count. */
/*
* Event processing.
*
* The DSO can do whatever appropriate steps if an event
* happens such as changing the mapping in case a mirror
* fails, update the application metadata etc.
*
* This function gets a dm_task that is a result of
* DM_DEVICE_WAITEVENT ioctl (results equivalent to
* DM_DEVICE_STATUS). It should not destroy it.
* The caller must dispose of the task.
*/
void (*process_event)(struct dm_task *dmt, enum dm_event_mask event, void **user);
/*
* Device registration.
*
* When an application registers a device for an event, the DSO
* can carry out appropriate steps so that a later call to
* the process_event() function is sane (eg, read metadata
* and activate a mapping).
*/
int (*register_device)(const char *device, const char *uuid, int major,
int minor, void **user);
/*
* Device unregistration.
*
* In case all devices of a mapping (eg, RAID10) are unregistered
* for events, the DSO can recognize this and carry out appropriate
* steps (eg, deactivate mapping, metadata update).
*/
int (*unregister_device)(const char *device, const char *uuid,
int major, int minor, void **user);
};
static DM_LIST_INIT(_dso_registry);
/* Structure to keep parsed register variables from client message. */
struct message_data {
char *id;
char *dso_name; /* Name of DSO. */
char *device_uuid; /* Mapped device path. */
char *events_str; /* Events string as fetched from message. */
enum dm_event_mask events_field; /* Events bitfield. */
char *timeout_str;
uint32_t timeout_secs;
struct dm_event_daemon_message *msg; /* Pointer to message buffer. */
};
/*
* Housekeeping of thread+device states.
*
* One thread per mapped device which can block on it until an event
* occurs and the event processing function of the DSO gets called.
*/
struct thread_status {
struct dm_list list;
pthread_t thread;
struct dso_data *dso_data; /* DSO this thread accesses. */
struct {
char *uuid;
char *name;
int major, minor;
} device;
uint32_t event_nr; /* event number */
int processing; /* Set when event is being processed */
int status; /* see DM_THREAD_{RUNNING,SHUTDOWN,DONE}
constants above */
enum dm_event_mask events; /* bitfield for event filter. */
enum dm_event_mask current_events; /* bitfield for occured events. */
struct dm_task *current_task;
time_t next_time;
uint32_t timeout;
struct dm_list timeout_list;
void *dso_private; /* dso per-thread status variable */
};
static DM_LIST_INIT(_thread_registry);
static DM_LIST_INIT(_thread_registry_unused);
static int _timeout_running;
static DM_LIST_INIT(_timeout_registry);
static pthread_mutex_t _timeout_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t _timeout_cond = PTHREAD_COND_INITIALIZER;
/* Allocate/free the status structure for a monitoring thread. */
static struct thread_status *_alloc_thread_status(const struct message_data *data,
struct dso_data *dso_data)
{
struct thread_status *ret;
if (!(ret = dm_zalloc(sizeof(*ret))))
return NULL;
if (!(ret->device.uuid = dm_strdup(data->device_uuid))) {
dm_free(ret);
return NULL;
}
ret->dso_data = dso_data;
ret->events = data->events_field;
ret->timeout = data->timeout_secs;
dm_list_init(&ret->timeout_list);
return ret;
}
static void _lib_put(struct dso_data *data);
static void _free_thread_status(struct thread_status *thread)
{
_lib_put(thread->dso_data);
if (thread->current_task)
dm_task_destroy(thread->current_task);
dm_free(thread->device.uuid);
dm_free(thread->device.name);
dm_free(thread);
}
/* Allocate/free DSO data. */
static struct dso_data *_alloc_dso_data(struct message_data *data)
{
struct dso_data *ret = (typeof(ret)) dm_zalloc(sizeof(*ret));
if (!ret)
return NULL;
if (!(ret->dso_name = dm_strdup(data->dso_name))) {
dm_free(ret);
return NULL;
}
return ret;
}
/*
* Create a device monitoring thread.
* N.B. Error codes returned are positive.
*/
static int _pthread_create_smallstack(pthread_t *t, void *(*fun)(void *), void *arg)
{
int r;
pthread_t tmp;
pthread_attr_t attr;
/*
* From pthread_attr_init man page:
* POSIX.1-2001 documents an ENOMEM error for pthread_attr_init(); on
* Linux these functions always succeed (but portable and future-proof
* applications should nevertheless handle a possible error return).
*/
if ((r = pthread_attr_init(&attr)) != 0)
return r;
/*
* We use a smaller stack since it gets preallocated in its entirety
*/
pthread_attr_setstacksize(&attr, THREAD_STACK_SIZE);
/*
* If no-one will be waiting, we need to detach.
*/
if (!t) {
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
t = &tmp;
}
r = pthread_create(t, &attr, fun, arg);
pthread_attr_destroy(&attr);
return r;
}
static void _free_dso_data(struct dso_data *data)
{
dm_free(data->dso_name);
dm_free(data);
}
/*
* Fetch a string off src and duplicate it into *ptr.
* Pay attention to zero-length strings.
*/
/* FIXME? move to libdevmapper to share with the client lib (need to
make delimiter a parameter then) */
static int _fetch_string(char **ptr, char **src, const int delimiter)
{
int ret = 0;
char *p;
size_t len;
if ((p = strchr(*src, delimiter)))
*p = 0;
if ((*ptr = dm_strdup(*src))) {
if ((len = strlen(*ptr)))
*src += len;
else {
dm_free(*ptr);
*ptr = NULL;
}
(*src)++;
ret = 1;
}
if (p)
*p = delimiter;
return ret;
}
/* Free message memory. */
static void _free_message(struct message_data *message_data)
{
dm_free(message_data->id);
dm_free(message_data->dso_name);
dm_free(message_data->device_uuid);
dm_free(message_data->events_str);
dm_free(message_data->timeout_str);
}
/* Parse a register message from the client. */
static int _parse_message(struct message_data *message_data)
{
int ret = 0;
struct dm_event_daemon_message *msg = message_data->msg;
char *p = msg->data;
if (!msg->data)
return 0;
/*
* Retrieve application identifier, mapped device
* path and events # string from message.
*/
if (_fetch_string(&message_data->id, &p, ' ') &&
_fetch_string(&message_data->dso_name, &p, ' ') &&
_fetch_string(&message_data->device_uuid, &p, ' ') &&
_fetch_string(&message_data->events_str, &p, ' ') &&
_fetch_string(&message_data->timeout_str, &p, ' ')) {
if (message_data->events_str)
message_data->events_field =
atoi(message_data->events_str);
if (message_data->timeout_str)
message_data->timeout_secs =
atoi(message_data->timeout_str)
? : DM_EVENT_DEFAULT_TIMEOUT;
ret = 1;
}
dm_free(msg->data);
msg->data = NULL;
return ret;
}
/* Global mutex to lock access to lists et al. See _global_mutex
above. */
static int _lock_mutex(void)
{
return pthread_mutex_lock(&_global_mutex);
}
static int _unlock_mutex(void)
{
return pthread_mutex_unlock(&_global_mutex);
}
/* Check, if a device exists. */
static int _fill_device_data(struct thread_status *ts)
{
struct dm_task *dmt;
struct dm_info dmi;
int ret = 0;
if (!ts->device.uuid)
return 0;
if (!(dmt = dm_task_create(DM_DEVICE_INFO)))
return 0;
if (!dm_task_set_uuid(dmt, ts->device.uuid))
goto fail;
if (!dm_task_run(dmt))
goto fail;
dm_free(ts->device.name);
if (!(ts->device.name = dm_strdup(dm_task_get_name(dmt))))
goto fail;
if (!dm_task_get_info(dmt, &dmi))
goto fail;
ts->device.major = dmi.major;
ts->device.minor = dmi.minor;
ret = 1;
fail:
dm_task_destroy(dmt);
return ret;
}
/*
* Find an existing thread for a device.
*
* Mutex must be held when calling this.
*/
static struct thread_status *_lookup_thread_status(struct message_data *data)
{
struct thread_status *thread;
dm_list_iterate_items(thread, &_thread_registry)
if (!strcmp(data->device_uuid, thread->device.uuid))
return thread;
return NULL;
}
static int _get_status(struct message_data *message_data)
{
struct dm_event_daemon_message *msg = message_data->msg;
struct thread_status *thread;
int i = 0, j;
int ret = -ENOMEM;
int count;
int size = 0, current;
size_t len;
char **buffers;
char *message;
_lock_mutex();
count = dm_list_size(&_thread_registry);
buffers = alloca(sizeof(char*) * count);
dm_list_iterate_items(thread, &_thread_registry) {
if ((current = dm_asprintf(buffers + i, "0:%d %s %s %u %" PRIu32 ";",
i, thread->dso_data->dso_name,
thread->device.uuid, thread->events,
thread->timeout)) < 0) {
_unlock_mutex();
goto out;
}
++i;
size += current; /* count with trailing '\0' */
}
_unlock_mutex();
len = strlen(message_data->id);
msg->size = size + len + 1;
dm_free(msg->data);
if (!(msg->data = dm_malloc(msg->size)))
goto out;
memcpy(msg->data, message_data->id, len);
message = msg->data + len;
*message++ = ' ';
for (j = 0; j < i; ++j) {
len = strlen(buffers[j]);
memcpy(message, buffers[j], len);
message += len;
}
ret = 0;
out:
for (j = 0; j < i; ++j)
dm_free(buffers[j]);
return ret;
}
static int _get_parameters(struct message_data *message_data) {
struct dm_event_daemon_message *msg = message_data->msg;
int size;
dm_free(msg->data);
if ((size = dm_asprintf(&msg->data, "%s pid=%d daemon=%s exec_method=%s",
message_data->id, getpid(),
_foreground ? "no" : "yes",
_systemd_activation ? "systemd" : "direct")) < 0) {
stack;
return -ENOMEM;
}
msg->size = (uint32_t) size;
return 0;
}
/* Cleanup at exit. */
static void _exit_dm_lib(void)
{
dm_lib_release();
dm_lib_exit();
}
static void _exit_timeout(void *unused __attribute__((unused)))
{
_timeout_running = 0;
pthread_mutex_unlock(&_timeout_mutex);
}
/* Wake up monitor threads every so often. */
static void *_timeout_thread(void *unused __attribute__((unused)))
{
struct thread_status *thread;
struct timespec timeout;
time_t curr_time;
timeout.tv_nsec = 0;
pthread_cleanup_push(_exit_timeout, NULL);
pthread_mutex_lock(&_timeout_mutex);
while (!dm_list_empty(&_timeout_registry)) {
timeout.tv_sec = 0;
curr_time = time(NULL);
dm_list_iterate_items_gen(thread, &_timeout_registry, timeout_list) {
if (thread->next_time <= curr_time) {
thread->next_time = curr_time + thread->timeout;
pthread_kill(thread->thread, SIGALRM);
}
if (thread->next_time < timeout.tv_sec || !timeout.tv_sec)
timeout.tv_sec = thread->next_time;
}
pthread_cond_timedwait(&_timeout_cond, &_timeout_mutex,
&timeout);
}
pthread_cleanup_pop(1);
return NULL;
}
static int _register_for_timeout(struct thread_status *thread)
{
int ret = 0;
pthread_mutex_lock(&_timeout_mutex);
if (dm_list_empty(&thread->timeout_list)) {
thread->next_time = time(NULL) + thread->timeout;
dm_list_add(&_timeout_registry, &thread->timeout_list);
if (_timeout_running)
pthread_cond_signal(&_timeout_cond);
}
if (!_timeout_running &&
!(ret = _pthread_create_smallstack(NULL, _timeout_thread, NULL)))
_timeout_running = 1;
pthread_mutex_unlock(&_timeout_mutex);
return ret;
}
static void _unregister_for_timeout(struct thread_status *thread)
{
pthread_mutex_lock(&_timeout_mutex);
if (!dm_list_empty(&thread->timeout_list)) {
dm_list_del(&thread->timeout_list);
dm_list_init(&thread->timeout_list);
if (dm_list_empty(&_timeout_registry))
/* No more work -> wakeup to finish quickly */
pthread_cond_signal(&_timeout_cond);
}
pthread_mutex_unlock(&_timeout_mutex);
}
__attribute__((format(printf, 4, 5)))
static void _no_intr_log(int level, const char *file, int line,
const char *f, ...)
{
va_list ap;
if (errno == EINTR)
return;
if (level > _LOG_WARN)
return;
va_start(ap, f);
vfprintf((level < _LOG_WARN) ? stderr : stdout, f, ap);
va_end(ap);
fputc('\n', (level < _LOG_WARN) ? stderr : stdout);
}
static sigset_t _unblock_sigalrm(void)
{
sigset_t set, old;
sigemptyset(&set);
sigaddset(&set, SIGALRM);
pthread_sigmask(SIG_UNBLOCK, &set, &old);
return old;
}
#define DM_WAIT_RETRY 0
#define DM_WAIT_INTR 1
#define DM_WAIT_FATAL 2
/* Wait on a device until an event occurs. */
static int _event_wait(struct thread_status *thread, struct dm_task **task)
{
static unsigned _in_event_counter = 0;
sigset_t set;
int ret = DM_WAIT_RETRY;
struct dm_task *dmt;
struct dm_info info;
*task = 0;
if (!(dmt = dm_task_create(DM_DEVICE_WAITEVENT)))
return DM_WAIT_RETRY;
thread->current_task = dmt;
if (!dm_task_set_uuid(dmt, thread->device.uuid) ||
!dm_task_set_event_nr(dmt, thread->event_nr))
goto out;
_lock_mutex();
/*
* Check if there are already some waiting events,
* in this case the logging is unmodified.
* TODO: audit libdm thread usage
*/
if (!_in_event_counter++)
dm_log_init(_no_intr_log);
_unlock_mutex();
/*
* This is so that you can break out of waiting on an event,
* either for a timeout event, or to cancel the thread.
*/
set = _unblock_sigalrm();
errno = 0;
if (dm_task_run(dmt)) {
thread->current_events |= DM_EVENT_DEVICE_ERROR;
ret = DM_WAIT_INTR;
if ((ret = dm_task_get_info(dmt, &info)))
thread->event_nr = info.event_nr;
} else if (thread->events & DM_EVENT_TIMEOUT && errno == EINTR) {
thread->current_events |= DM_EVENT_TIMEOUT;
ret = DM_WAIT_INTR;
} else if (thread->status == DM_THREAD_SHUTDOWN && errno == EINTR) {
ret = DM_WAIT_FATAL;
} else {
syslog(LOG_NOTICE, "dm_task_run failed, errno = %d, %s",
errno, strerror(errno));
if (errno == ENXIO) {
syslog(LOG_ERR, "%s disappeared, detaching",
thread->device.name);
ret = DM_WAIT_FATAL;
}
}
pthread_sigmask(SIG_SETMASK, &set, NULL);
_lock_mutex();
if (--_in_event_counter == 0)
dm_log_init(NULL);
_unlock_mutex();
out:
if (ret == DM_WAIT_FATAL || ret == DM_WAIT_RETRY) {
dm_task_destroy(dmt);
thread->current_task = NULL;
} else
*task = dmt;
return ret;
}
/* Register a device with the DSO. */
static int _do_register_device(struct thread_status *thread)
{
return thread->dso_data->register_device(thread->device.name,
thread->device.uuid,
thread->device.major,
thread->device.minor,
&(thread->dso_private));
}
/* Unregister a device with the DSO. */
static int _do_unregister_device(struct thread_status *thread)
{
return thread->dso_data->unregister_device(thread->device.name,
thread->device.uuid,
thread->device.major,
thread->device.minor,
&(thread->dso_private));
}
/* Process an event in the DSO. */
static void _do_process_event(struct thread_status *thread, struct dm_task *task)
{
thread->dso_data->process_event(task, thread->current_events, &(thread->dso_private));
}
/* Thread cleanup handler to unregister device. */
static void _monitor_unregister(void *arg)
{
struct thread_status *thread = arg, *thread_iter;
if (!_do_unregister_device(thread))
syslog(LOG_ERR, "%s: %s unregister failed\n", __func__,
thread->device.name);
if (thread->current_task) {
dm_task_destroy(thread->current_task);
thread->current_task = NULL;
}
_lock_mutex();
if (thread->events & DM_EVENT_TIMEOUT) {
/* _unregister_for_timeout locks another mutex, we
don't want to deadlock so we release our mutex for
a bit */
_unlock_mutex();
_unregister_for_timeout(thread);
_lock_mutex();
}
/* we may have been relinked to unused registry since we were
called, so check that */
dm_list_iterate_items(thread_iter, &_thread_registry_unused)
if (thread_iter == thread) {
thread->status = DM_THREAD_DONE;
_unlock_mutex();
return;
}
thread->status = DM_THREAD_DONE;
UNLINK_THREAD(thread);
LINK(thread, &_thread_registry_unused);
_unlock_mutex();
}
static struct dm_task *_get_device_status(struct thread_status *ts)
{
struct dm_task *dmt = dm_task_create(DM_DEVICE_STATUS);
if (!dmt)
return NULL;
if (!dm_task_set_uuid(dmt, ts->device.uuid)) {
dm_task_destroy(dmt);
return NULL;
}
if (!dm_task_run(dmt)) {
dm_task_destroy(dmt);
return NULL;
}
return dmt;
}
/* Device monitoring thread. */
static void *_monitor_thread(void *arg)
{
struct thread_status *thread = arg;
int wait_error;
struct dm_task *task;
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
pthread_cleanup_push(_monitor_unregister, thread);
/* Wait for do_process_request() to finish its task. */
_lock_mutex();
thread->status = DM_THREAD_RUNNING;
_unlock_mutex();
/* Loop forever awaiting/analyzing device events. */
while (1) {
thread->current_events = 0;
wait_error = _event_wait(thread, &task);
if (wait_error == DM_WAIT_RETRY) {
usleep(100); /* avoid busy loop */
continue;
}
if (wait_error == DM_WAIT_FATAL)
break;
/* Timeout occurred, task is not filled properly.
* We get device status here for processing it in DSO.
*/
if (wait_error == DM_WAIT_INTR &&
thread->current_events & DM_EVENT_TIMEOUT) {
dm_task_destroy(task);
task = _get_device_status(thread);
/* FIXME: syslog fail here ? */
if (!(thread->current_task = task))
continue;
}
/*
* We know that wait succeeded and stored a
* pointer to dm_task with device status into task.
*/
/*
* Check against filter.
*
* If there's current events delivered from _event_wait() AND
* the device got registered for those events AND
* those events haven't been processed yet, call
* the DSO's process_event() handler.
*/
_lock_mutex();
if (thread->status == DM_THREAD_SHUTDOWN) {
_unlock_mutex();
break;
}
if (thread->events & thread->current_events) {
thread->processing = 1;
_unlock_mutex();
_do_process_event(thread, task);
dm_task_destroy(task);
thread->current_task = NULL;
_lock_mutex();
thread->processing = 0;
_unlock_mutex();
} else {
_unlock_mutex();
dm_task_destroy(task);
thread->current_task = NULL;
}
}
pthread_cleanup_pop(1);
return NULL;
}
/* Create a device monitoring thread. */
static int _create_thread(struct thread_status *thread)
{
return _pthread_create_smallstack(&thread->thread, _monitor_thread, thread);
}
static int _terminate_thread(struct thread_status *thread)
{
return pthread_kill(thread->thread, SIGALRM);
}
/* DSO reference counting. Call with _global_mutex locked! */
static void _lib_get(struct dso_data *data)
{
data->ref_count++;
}
static void _lib_put(struct dso_data *data)
{
if (!--data->ref_count) {
dlclose(data->dso_handle);
UNLINK_DSO(data);
_free_dso_data(data);
}
}
/* Find DSO data. */
static struct dso_data *_lookup_dso(struct message_data *data)
{
struct dso_data *dso_data, *ret = NULL;
dm_list_iterate_items(dso_data, &_dso_registry)
if (!strcmp(data->dso_name, dso_data->dso_name)) {
_lib_get(dso_data);
ret = dso_data;
break;
}
return ret;
}
/* Lookup DSO symbols we need. */
static int _lookup_symbol(void *dl, void **symbol, const char *name)
{
if ((*symbol = dlsym(dl, name)))
return 1;
return 0;
}
static int lookup_symbols(void *dl, struct dso_data *data)
{
return _lookup_symbol(dl, (void *) &data->process_event,
"process_event") &&
_lookup_symbol(dl, (void *) &data->register_device,
"register_device") &&
_lookup_symbol(dl, (void *) &data->unregister_device,
"unregister_device");
}
/* Load an application specific DSO. */
static struct dso_data *_load_dso(struct message_data *data)
{
void *dl;
struct dso_data *ret;
char dso_name[PATH_MAX];
if (strchr(data->dso_name, '/') == NULL) {
strcpy(dso_name, PLUGIN_PATH);
strncat(dso_name, data->dso_name, sizeof(dso_name));
} else {
strncpy(dso_name, data->dso_name, sizeof(dso_name));
}
dso_name[sizeof(dso_name) - 1] = 0;
if (!(dl = dlopen(dso_name, RTLD_NOW))) {
const char *dlerr = dlerror();
syslog(LOG_ERR, "dmeventd %s dlopen failed: %s", data->dso_name,
dlerr);
data->msg->size =
dm_asprintf(&(data->msg->data), "%s %s dlopen failed: %s",
data->id, data->dso_name, dlerr);
return NULL;
}
if (!(ret = _alloc_dso_data(data))) {
dlclose(dl);
return NULL;
}
if (!(lookup_symbols(dl, ret))) {
_free_dso_data(ret);
dlclose(dl);
return NULL;
}
/*
* Keep handle to close the library once
* we've got no references to it any more.
*/
ret->dso_handle = dl;
_lib_get(ret);
_lock_mutex();
LINK_DSO(ret);
_unlock_mutex();
return ret;
}
/* Return success on daemon active check. */
static int _active(struct message_data *message_data)
{
return 0;
}
/*
* Register for an event.
*
* Only one caller at a time here, because we use
* a FIFO and lock it against multiple accesses.
*/
static int _register_for_event(struct message_data *message_data)
{
int ret = 0;
struct thread_status *thread, *thread_new = NULL;
struct dso_data *dso_data;
if (!(dso_data = _lookup_dso(message_data)) &&
!(dso_data = _load_dso(message_data))) {
stack;
#ifdef ELIBACC
ret = -ELIBACC;
#else
ret = -ENODEV;
#endif
goto out;
}
/* Preallocate thread status struct to avoid deadlock. */
if (!(thread_new = _alloc_thread_status(message_data, dso_data))) {
stack;
ret = -ENOMEM;
goto out;
}
if (!_fill_device_data(thread_new)) {
stack;
ret = -ENODEV;
goto out;
}
/* If creation of timeout thread fails (as it may), we fail
here completely. The client is responsible for either
retrying later or trying to register without timeout
events. However, if timeout thread cannot be started, it
usually means we are so starved on resources that we are
almost as good as dead already... */
if ((thread_new->events & DM_EVENT_TIMEOUT) &&
(ret = -_register_for_timeout(thread_new)))
goto out;
_lock_mutex();
if (!(thread = _lookup_thread_status(message_data))) {
_unlock_mutex();
if (!(ret = _do_register_device(thread_new)))
goto out;
thread = thread_new;
thread_new = NULL;
/* Try to create the monitoring thread for this device. */
_lock_mutex();
if ((ret = -_create_thread(thread))) {
_unlock_mutex();
_do_unregister_device(thread);
_free_thread_status(thread);
goto out;
}
LINK_THREAD(thread);
}
/* Or event # into events bitfield. */
thread->events |= message_data->events_field;
_unlock_mutex();
out:
/*
* Deallocate thread status after releasing
* the lock in case we haven't used it.
*/
if (thread_new)
_free_thread_status(thread_new);
return ret;
}
/*
* Unregister for an event.
*
* Only one caller at a time here as with register_for_event().
*/
static int _unregister_for_event(struct message_data *message_data)
{
int ret = 0;
struct thread_status *thread;
/*
* Clear event in bitfield and deactivate
* monitoring thread in case bitfield is 0.
*/
_lock_mutex();
if (!(thread = _lookup_thread_status(message_data))) {
_unlock_mutex();
ret = -ENODEV;
goto out;
}
if (thread->status == DM_THREAD_DONE) {
/* the thread has terminated while we were not
watching */
_unlock_mutex();
return 0;
}
thread->events &= ~message_data->events_field;
if (!(thread->events & DM_EVENT_TIMEOUT)) {
_unlock_mutex();
_unregister_for_timeout(thread);
_lock_mutex();
}
/*
* In case there's no events to monitor on this device ->
* unlink and terminate its monitoring thread.
*/
if (!thread->events) {
UNLINK_THREAD(thread);
LINK(thread, &_thread_registry_unused);
}
_unlock_mutex();
out:
return ret;
}
/*
* Get registered device.
*
* Only one caller at a time here as with register_for_event().
*/
static int _registered_device(struct message_data *message_data,
struct thread_status *thread)
{
int r;
struct dm_event_daemon_message *msg = message_data->msg;
unsigned events = ((thread->status == DM_THREAD_RUNNING) &&
thread->events) ? thread->events :
thread->events | DM_EVENT_REGISTRATION_PENDING;
dm_free(msg->data);
if ((r = dm_asprintf(&(msg->data), "%s %s %s %u",
message_data->id,
thread->dso_data->dso_name,
thread->device.uuid, events)) < 0)
return -ENOMEM;
msg->size = (uint32_t) r;
return 0;
}
static int _want_registered_device(char *dso_name, char *device_uuid,
struct thread_status *thread)
{
/* If DSO names and device paths are equal. */
if (dso_name && device_uuid)
return !strcmp(dso_name, thread->dso_data->dso_name) &&
!strcmp(device_uuid, thread->device.uuid) &&
(thread->status == DM_THREAD_RUNNING ||
(thread->events & DM_EVENT_REGISTRATION_PENDING));
/* If DSO names are equal. */
if (dso_name)
return !strcmp(dso_name, thread->dso_data->dso_name) &&
(thread->status == DM_THREAD_RUNNING ||
(thread->events & DM_EVENT_REGISTRATION_PENDING));
/* If device paths are equal. */
if (device_uuid)
return !strcmp(device_uuid, thread->device.uuid) &&
(thread->status == DM_THREAD_RUNNING ||
(thread->events & DM_EVENT_REGISTRATION_PENDING));
return 1;
}
static int _get_registered_dev(struct message_data *message_data, int next)
{
struct thread_status *thread, *hit = NULL;
int ret = -ENOENT;
_lock_mutex();
/* Iterate list of threads checking if we want a particular one. */
dm_list_iterate_items(thread, &_thread_registry)
if (_want_registered_device(message_data->dso_name,
message_data->device_uuid,
thread)) {
hit = thread;
break;
}
/*
* If we got a registered device and want the next one ->
* fetch next conforming element off the list.
*/
if (hit && !next)
goto reg;
if (!hit)
goto out;
while (1) {
if (dm_list_end(&_thread_registry, &thread->list))
goto out;
thread = dm_list_item(thread->list.n, struct thread_status);
if (_want_registered_device(message_data->dso_name, NULL, thread)) {
hit = thread;
break;
}
}
reg:
ret = _registered_device(message_data, hit);
out:
_unlock_mutex();
return ret;
}
static int _get_registered_device(struct message_data *message_data)
{
return _get_registered_dev(message_data, 0);
}
static int _get_next_registered_device(struct message_data *message_data)
{
return _get_registered_dev(message_data, 1);
}
static int _set_timeout(struct message_data *message_data)
{
struct thread_status *thread;
_lock_mutex();
if ((thread = _lookup_thread_status(message_data)))
thread->timeout = message_data->timeout_secs;
_unlock_mutex();
return thread ? 0 : -ENODEV;
}
static int _get_timeout(struct message_data *message_data)
{
struct thread_status *thread;
struct dm_event_daemon_message *msg = message_data->msg;
dm_free(msg->data);
_lock_mutex();
if ((thread = _lookup_thread_status(message_data))) {
msg->size = dm_asprintf(&(msg->data), "%s %" PRIu32,
message_data->id, thread->timeout);
} else
msg->data = NULL;
_unlock_mutex();
return thread ? 0 : -ENODEV;
}
/* Open fifos used for client communication. */
static int _open_fifos(struct dm_event_fifos *fifos)
{
struct stat st;
/* Create client fifo. */
(void) dm_prepare_selinux_context(fifos->client_path, S_IFIFO);
if ((mkfifo(fifos->client_path, 0600) == -1) && errno != EEXIST) {
syslog(LOG_ERR, "%s: Failed to create client fifo %s: %m.\n",
__func__, fifos->client_path);
(void) dm_prepare_selinux_context(NULL, 0);
goto fail;
}
/* Create server fifo. */
(void) dm_prepare_selinux_context(fifos->server_path, S_IFIFO);
if ((mkfifo(fifos->server_path, 0600) == -1) && errno != EEXIST) {
syslog(LOG_ERR, "%s: Failed to create server fifo %s: %m.\n",
__func__, fifos->server_path);
(void) dm_prepare_selinux_context(NULL, 0);
goto fail;
}
(void) dm_prepare_selinux_context(NULL, 0);
/* Warn about wrong permissions if applicable */
if ((!stat(fifos->client_path, &st)) && (st.st_mode & 0777) != 0600)
syslog(LOG_WARNING, "Fixing wrong permissions on %s: %m.\n",
fifos->client_path);
if ((!stat(fifos->server_path, &st)) && (st.st_mode & 0777) != 0600)
syslog(LOG_WARNING, "Fixing wrong permissions on %s: %m.\n",
fifos->server_path);
/* If they were already there, make sure permissions are ok. */
if (chmod(fifos->client_path, 0600)) {
syslog(LOG_ERR, "Unable to set correct file permissions on %s: %m.\n",
fifos->client_path);
goto fail;
}
if (chmod(fifos->server_path, 0600)) {
syslog(LOG_ERR, "Unable to set correct file permissions on %s: %m.\n",
fifos->server_path);
goto fail;
}
/* Need to open read+write or we will block or fail */
if ((fifos->server = open(fifos->server_path, O_RDWR)) < 0) {
syslog(LOG_ERR, "Failed to open fifo server %s: %m.\n",
fifos->server_path);
goto fail;
}
if (fcntl(fifos->server, F_SETFD, FD_CLOEXEC) < 0) {
syslog(LOG_ERR, "Failed to set FD_CLOEXEC for fifo server %s: %m.\n",
fifos->server_path);
goto fail;
}
/* Need to open read+write for select() to work. */
if ((fifos->client = open(fifos->client_path, O_RDWR)) < 0) {
syslog(LOG_ERR, "Failed to open fifo client %s: %m", fifos->client_path);
goto fail;
}
if (fcntl(fifos->client, F_SETFD, FD_CLOEXEC) < 0) {
syslog(LOG_ERR, "Failed to set FD_CLOEXEC for fifo client %s: %m.\n",
fifos->client_path);
goto fail;
}
return 1;
fail:
if (fifos->server >= 0 && close(fifos->server))
syslog(LOG_ERR, "Failed to close fifo server %s: %m", fifos->server_path);
if (fifos->client >= 0 && close(fifos->client))
syslog(LOG_ERR, "Failed to close fifo client %s: %m", fifos->client_path);
return 0;
}
/*
* Read message from client making sure that data is available
* and a complete message is read. Must not block indefinitely.
*/
static int _client_read(struct dm_event_fifos *fifos,
struct dm_event_daemon_message *msg)
{
struct timeval t;
unsigned bytes = 0;
int ret = 0;
fd_set fds;
size_t size = 2 * sizeof(uint32_t); /* status + size */
uint32_t *header = alloca(size);
char *buf = (char *)header;
msg->data = NULL;
errno = 0;
while (bytes < size && errno != EOF) {
/* Watch client read FIFO for input. */
FD_ZERO(&fds);
FD_SET(fifos->client, &fds);
t.tv_sec = 1;
t.tv_usec = 0;
ret = select(fifos->client + 1, &fds, NULL, NULL, &t);
if (!ret && !bytes) /* nothing to read */
return 0;
if (!ret) /* trying to finish read */
continue;
if (ret < 0) /* error */
return 0;
ret = read(fifos->client, buf + bytes, size - bytes);
bytes += ret > 0 ? ret : 0;
if (header && (bytes == 2 * sizeof(uint32_t))) {
msg->cmd = ntohl(header[0]);
msg->size = ntohl(header[1]);
buf = msg->data = dm_malloc(msg->size);
size = msg->size;
bytes = 0;
header = 0;
}
}
if (bytes != size) {
dm_free(msg->data);
msg->data = NULL;
return 0;
}
return 1;
}
/*
* Write a message to the client making sure that it is ready to write.
*/
static int _client_write(struct dm_event_fifos *fifos,
struct dm_event_daemon_message *msg)
{
uint32_t temp[2];
unsigned bytes = 0;
int ret = 0;
fd_set fds;
size_t size = 2 * sizeof(uint32_t) + ((msg->data) ? msg->size : 0);
uint32_t *header = dm_malloc(size);
char *buf = (char *)header;
if (!header) {
/* Reply with ENOMEM message */
header = temp;
size = sizeof(temp);
header[0] = htonl(-ENOMEM);
header[1] = 0;
} else {
header[0] = htonl(msg->cmd);
header[1] = htonl((msg->data) ? msg->size : 0);
if (msg->data)
memcpy(buf + 2 * sizeof(uint32_t), msg->data, msg->size);
}
while (bytes < size) {
do {
/* Watch client write FIFO to be ready for output. */
FD_ZERO(&fds);
FD_SET(fifos->server, &fds);
} while (select(fifos->server + 1, NULL, &fds, NULL, NULL) != 1);
if ((ret = write(fifos->server, buf + bytes, size - bytes)) > 0)
bytes += ret;
else if (errno == EIO)
break;
}
if (header != temp)
dm_free(header);
return (bytes == size);
}
/*
* Handle a client request.
*
* We put the request handling functions into
* a list because of the growing number.
*/
static int _handle_request(struct dm_event_daemon_message *msg,
struct message_data *message_data)
{
switch (msg->cmd) {
case DM_EVENT_CMD_REGISTER_FOR_EVENT:
return _register_for_event(message_data);
case DM_EVENT_CMD_UNREGISTER_FOR_EVENT:
return _unregister_for_event(message_data);
case DM_EVENT_CMD_GET_REGISTERED_DEVICE:
return _get_registered_device(message_data);
case DM_EVENT_CMD_GET_NEXT_REGISTERED_DEVICE:
return _get_next_registered_device(message_data);
case DM_EVENT_CMD_SET_TIMEOUT:
return _set_timeout(message_data);
case DM_EVENT_CMD_GET_TIMEOUT:
return _get_timeout(message_data);
case DM_EVENT_CMD_ACTIVE:
return _active(message_data);
case DM_EVENT_CMD_GET_STATUS:
return _get_status(message_data);
/* dmeventd parameters of running dmeventd,
* returns 'pid=<pid> daemon=<no/yes> exec_method=<direct/systemd>'
* pid - pidfile of running dmeventd
* daemon - running as a daemon or not (foreground)?
* exec_method - "direct" if executed directly or
* "systemd" if executed via systemd
*/
case DM_EVENT_CMD_GET_PARAMETERS:
return _get_parameters(message_data);
default:
return -EINVAL;
}
}
/* Process a request passed from the communication thread. */
static int _do_process_request(struct dm_event_daemon_message *msg)
{
int ret;
char *answer;
struct message_data message_data = { .msg = msg };
/* Parse the message. */
if (msg->cmd == DM_EVENT_CMD_HELLO || msg->cmd == DM_EVENT_CMD_DIE) {
ret = 0;
answer = msg->data;
if (answer) {
msg->size = dm_asprintf(&(msg->data), "%s %s %d", answer,
(msg->cmd == DM_EVENT_CMD_DIE) ? "DYING" : "HELLO",
DM_EVENT_PROTOCOL_VERSION);
dm_free(answer);
}
} else if (msg->cmd != DM_EVENT_CMD_ACTIVE && !_parse_message(&message_data)) {
stack;
ret = -EINVAL;
} else
ret = _handle_request(msg, &message_data);
msg->cmd = ret;
if (!msg->data)
msg->size = dm_asprintf(&(msg->data), "%s %s", message_data.id, strerror(-ret));
_free_message(&message_data);
return ret;
}
/* Only one caller at a time. */
static void _process_request(struct dm_event_fifos *fifos)
{
int die;
struct dm_event_daemon_message msg = { 0 };
/*
* Read the request from the client (client_read, client_write
* give true on success and false on failure).
*/
if (!_client_read(fifos, &msg))
return;
die = (msg.cmd == DM_EVENT_CMD_DIE) ? 1 : 0;
/* _do_process_request fills in msg (if memory allows for
data, otherwise just cmd and size = 0) */
_do_process_request(&msg);
if (!_client_write(fifos, &msg))
stack;
dm_free(msg.data);
if (die) {
if (unlink(DMEVENTD_PIDFILE))
perror(DMEVENTD_PIDFILE ": unlink failed");
_exit(0);
}
}
static void _process_initial_registrations(void)
{
int i;
char *reg;
struct dm_event_daemon_message msg = { 0 };
for (i = 0; (reg = _initial_registrations[i]); ++i) {
msg.cmd = DM_EVENT_CMD_REGISTER_FOR_EVENT;
if ((msg.size = strlen(reg))) {
msg.data = reg;
_do_process_request(&msg);
}
}
}
static void _cleanup_unused_threads(void)
{
int ret;
struct dm_list *l;
struct thread_status *thread;
int join_ret = 0;
_lock_mutex();
while ((l = dm_list_first(&_thread_registry_unused))) {
thread = dm_list_item(l, struct thread_status);
if (thread->processing)
break; /* cleanup on the next round */
if (thread->status == DM_THREAD_RUNNING) {
thread->status = DM_THREAD_SHUTDOWN;
break;
}
if (thread->status == DM_THREAD_SHUTDOWN) {
if (!thread->events) {
/* turn codes negative -- should we be returning this? */
ret = _terminate_thread(thread);
if (ret == ESRCH) {
thread->status = DM_THREAD_DONE;
} else if (ret) {
syslog(LOG_ERR,
"Unable to terminate thread: %s\n",
strerror(-ret));
stack;
}
break;
}
dm_list_del(l);
syslog(LOG_ERR,
"thread can't be on unused list unless !thread->events");
thread->status = DM_THREAD_RUNNING;
LINK_THREAD(thread);
continue;
}
if (thread->status == DM_THREAD_DONE) {
dm_list_del(l);
_unlock_mutex();
join_ret = pthread_join(thread->thread, NULL);
_free_thread_status(thread);
_lock_mutex();
}
}
_unlock_mutex();
if (join_ret)
syslog(LOG_ERR, "Failed pthread_join: %s\n", strerror(join_ret));
}
static void _sig_alarm(int signum __attribute__((unused)))
{
pthread_testcancel();
}
/* Init thread signal handling. */
static void _init_thread_signals(void)
{
sigset_t my_sigset;
struct sigaction act = { .sa_handler = _sig_alarm };
sigaction(SIGALRM, &act, NULL);
sigfillset(&my_sigset);
/* These are used for exiting */
sigdelset(&my_sigset, SIGTERM);
sigdelset(&my_sigset, SIGINT);
sigdelset(&my_sigset, SIGHUP);
sigdelset(&my_sigset, SIGQUIT);
pthread_sigmask(SIG_BLOCK, &my_sigset, NULL);
}
/*
* exit_handler
* @sig
*
* Set the global variable which the process should
* be watching to determine when to exit.
*/
static void _exit_handler(int sig __attribute__((unused)))
{
_exit_now = 1;
}
#ifdef __linux__
static int _set_oom_adj(const char *oom_adj_path, int val)
{
FILE *fp;
if (!(fp = fopen(oom_adj_path, "w"))) {
perror("oom_adj: fopen failed");
return 0;
}
fprintf(fp, "%i", val);
if (dm_fclose(fp))
perror("oom_adj: fclose failed");
return 1;
}
/*
* Protection against OOM killer if kernel supports it
*/
static int _protect_against_oom_killer(void)
{
struct stat st;
if (stat(OOM_ADJ_FILE, &st) == -1) {
if (errno != ENOENT)
perror(OOM_ADJ_FILE ": stat failed");
/* Try old oom_adj interface as a fallback */
if (stat(OOM_ADJ_FILE_OLD, &st) == -1) {
if (errno == ENOENT)
perror(OOM_ADJ_FILE_OLD " not found");
else
perror(OOM_ADJ_FILE_OLD ": stat failed");
return 1;
}
return _set_oom_adj(OOM_ADJ_FILE_OLD, OOM_DISABLE) ||
_set_oom_adj(OOM_ADJ_FILE_OLD, OOM_ADJUST_MIN);
}
return _set_oom_adj(OOM_ADJ_FILE, OOM_SCORE_ADJ_MIN);
}
static int _handle_preloaded_fifo(int fd, const char *path)
{
struct stat st_fd, st_path;
int flags;
if ((flags = fcntl(fd, F_GETFD)) < 0)
return 0;
if (flags & FD_CLOEXEC)
return 0;
if (fstat(fd, &st_fd) < 0 || !S_ISFIFO(st_fd.st_mode))
return 0;
if (stat(path, &st_path) < 0 ||
st_path.st_dev != st_fd.st_dev ||
st_path.st_ino != st_fd.st_ino)
return 0;
if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) < 0)
return 0;
return 1;
}
static int _systemd_handover(struct dm_event_fifos *fifos)
{
const char *e;
char *p;
unsigned long env_pid, env_listen_fds;
int r = 0;
/* SD_ACTIVATION must be set! */
if (!(e = getenv(SD_ACTIVATION_ENV_VAR_NAME)) || strcmp(e, "1"))
goto out;
/* LISTEN_PID must be equal to our PID! */
if (!(e = getenv(SD_LISTEN_PID_ENV_VAR_NAME)))
goto out;
errno = 0;
env_pid = strtoul(e, &p, 10);
if (errno || !p || *p || env_pid <= 0 ||
getpid() != (pid_t) env_pid)
goto out;
/* LISTEN_FDS must be 2 and the fds must be FIFOSs! */
if (!(e = getenv(SD_LISTEN_FDS_ENV_VAR_NAME)))
goto out;
errno = 0;
env_listen_fds = strtoul(e, &p, 10);
if (errno || !p || *p || env_listen_fds != 2)
goto out;
/* Check and handle the FIFOs passed in */
r = (_handle_preloaded_fifo(SD_FD_FIFO_SERVER, DM_EVENT_FIFO_SERVER) &&
_handle_preloaded_fifo(SD_FD_FIFO_CLIENT, DM_EVENT_FIFO_CLIENT));
if (r) {
fifos->server = SD_FD_FIFO_SERVER;
fifos->server_path = DM_EVENT_FIFO_SERVER;
fifos->client = SD_FD_FIFO_CLIENT;
fifos->client_path = DM_EVENT_FIFO_CLIENT;
}
out:
unsetenv(SD_ACTIVATION_ENV_VAR_NAME);
unsetenv(SD_LISTEN_PID_ENV_VAR_NAME);
unsetenv(SD_LISTEN_FDS_ENV_VAR_NAME);
return r;
}
#endif
static void _remove_files_on_exit(void)
{
if (unlink(DMEVENTD_PIDFILE))
perror(DMEVENTD_PIDFILE ": unlink failed");
if (!_systemd_activation) {
if (unlink(DM_EVENT_FIFO_CLIENT))
perror(DM_EVENT_FIFO_CLIENT " : unlink failed");
if (unlink(DM_EVENT_FIFO_SERVER))
perror(DM_EVENT_FIFO_SERVER " : unlink failed");
}
}
static void _daemonize(void)
{
int child_status;
int fd;
pid_t pid;
struct rlimit rlim;
struct timeval tval;
sigset_t my_sigset;
sigemptyset(&my_sigset);
if (sigprocmask(SIG_SETMASK, &my_sigset, NULL) < 0) {
fprintf(stderr, "Unable to restore signals.\n");
exit(EXIT_FAILURE);
}
signal(SIGTERM, &_exit_handler);
switch (pid = fork()) {
case -1:
perror("fork failed:");
exit(EXIT_FAILURE);
case 0: /* Child */
break;
default:
/* Wait for response from child */
while (!waitpid(pid, &child_status, WNOHANG) && !_exit_now) {
tval.tv_sec = 0;
tval.tv_usec = 250000; /* .25 sec */
select(0, NULL, NULL, NULL, &tval);
}
if (_exit_now) /* Child has signaled it is ok - we can exit now */
exit(EXIT_SUCCESS);
/* Problem with child. Determine what it is by exit code */
switch (WEXITSTATUS(child_status)) {
case EXIT_DESC_CLOSE_FAILURE:
case EXIT_DESC_OPEN_FAILURE:
case EXIT_FIFO_FAILURE:
case EXIT_CHDIR_FAILURE:
default:
fprintf(stderr, "Child exited with code %d\n", WEXITSTATUS(child_status));
break;
}
exit(WEXITSTATUS(child_status));
}
if (chdir("/"))
exit(EXIT_CHDIR_FAILURE);
if (getrlimit(RLIMIT_NOFILE, &rlim) < 0)
fd = 256; /* just have to guess */
else
fd = rlim.rlim_cur;
for (--fd; fd >= 0; fd--) {
#ifdef __linux__
/* Do not close fds preloaded by systemd! */
if (_systemd_activation &&
(fd == SD_FD_FIFO_SERVER || fd == SD_FD_FIFO_CLIENT))
continue;
#endif
(void) close(fd);
}
if ((open("/dev/null", O_RDONLY) < 0) ||
(open("/dev/null", O_WRONLY) < 0) ||
(open("/dev/null", O_WRONLY) < 0))
exit(EXIT_DESC_OPEN_FAILURE);
setsid();
}
static int _reinstate_registrations(struct dm_event_fifos *fifos)
{
static const char _failed_parsing_msg[] = "Failed to parse existing event registration.\n";
static const char *_delim = " ";
struct dm_event_daemon_message msg = { 0 };
char *endp, *dso_name, *dev_name, *mask, *timeout;
unsigned long mask_value, timeout_value;
int i, ret;
ret = daemon_talk(fifos, &msg, DM_EVENT_CMD_HELLO, NULL, NULL, 0, 0);
dm_free(msg.data);
msg.data = NULL;
if (ret) {
fprintf(stderr, "Failed to communicate with new instance of dmeventd.\n");
return 0;
}
for (i = 0; _initial_registrations[i]; ++i) {
if (!(strtok(_initial_registrations[i], _delim)) ||
!(dso_name = strtok(NULL, _delim)) ||
!(dev_name = strtok(NULL, _delim)) ||
!(mask = strtok(NULL, _delim)) ||
!(timeout = strtok(NULL, _delim))) {
fprintf(stderr, _failed_parsing_msg);
continue;
}
errno = 0;
mask_value = strtoul(mask, &endp, 10);
if (errno || !endp || *endp) {
fprintf(stderr, _failed_parsing_msg);
continue;
}
errno = 0;
timeout_value = strtoul(timeout, &endp, 10);
if (errno || !endp || *endp) {
fprintf(stderr, _failed_parsing_msg);
continue;
}
if (daemon_talk(fifos, &msg, DM_EVENT_CMD_REGISTER_FOR_EVENT,
dso_name,
dev_name,
(enum dm_event_mask) mask_value,
timeout_value))
fprintf(stderr, "Failed to reinstate monitoring for device %s.\n", dev_name);
}
return 1;
}
static void restart(void)
{
struct dm_event_fifos fifos = {
.server = -1,
.client = -1,
/* FIXME Make these either configurable or depend directly on dmeventd_path */
.client_path = DM_EVENT_FIFO_CLIENT,
.server_path = DM_EVENT_FIFO_SERVER
};
struct dm_event_daemon_message msg = { 0 };
int i, count = 0;
char *message;
int version;
const char *e;
/* Get the list of registrations from the running daemon. */
if (!init_fifos(&fifos)) {
fprintf(stderr, "WARNING: Could not initiate communication with existing dmeventd.\n");
exit(EXIT_FAILURE);
}
if (!dm_event_get_version(&fifos, &version)) {
fprintf(stderr, "WARNING: Could not communicate with existing dmeventd.\n");
goto bad;
}
if (version < 1) {
fprintf(stderr, "WARNING: The running dmeventd instance is too old.\n"
"Protocol version %d (required: 1). Action cancelled.\n",
version);
goto bad;
}
if (daemon_talk(&fifos, &msg, DM_EVENT_CMD_GET_STATUS, "-", "-", 0, 0))
goto bad;
message = strchr(msg.data, ' ') + 1;
for (i = 0; msg.data[i]; ++i)
if (msg.data[i] == ';') {
msg.data[i] = 0;
++count;
}
if (!(_initial_registrations = dm_malloc(sizeof(char*) * (count + 1)))) {
fprintf(stderr, "Memory allocation registration failed.\n");
goto bad;
}
for (i = 0; i < count; ++i) {
if (!(_initial_registrations[i] = dm_strdup(message))) {
fprintf(stderr, "Memory allocation for message failed.\n");
goto bad;
}
message += strlen(message) + 1;
}
_initial_registrations[count] = NULL;
if (version >= 2) {
if (daemon_talk(&fifos, &msg, DM_EVENT_CMD_GET_PARAMETERS, "-", "-", 0, 0)) {
fprintf(stderr, "Failed to acquire parameters from old dmeventd.\n");
goto bad;
}
if (strstr(msg.data, "exec_method=systemd"))
_systemd_activation = 1;
}
#ifdef __linux__
/*
* If the protocol version is old, just assume that if systemd is running,
* the dmeventd is also run as a systemd service via fifo activation.
*/
if (version < 2) {
/* This check is copied from sd-daemon.c. */
struct stat st;
if (!lstat(SD_RUNTIME_UNIT_FILE_DIR, &st) && !!S_ISDIR(st.st_mode))
_systemd_activation = 1;
}
#endif
if (daemon_talk(&fifos, &msg, DM_EVENT_CMD_DIE, "-", "-", 0, 0)) {
fprintf(stderr, "Old dmeventd refused to die.\n");
goto bad;
}
if (!_systemd_activation &&
((e = getenv(SD_ACTIVATION_ENV_VAR_NAME)) && strcmp(e, "1")))
_systemd_activation = 1;
for (i = 0; i < 10; ++i) {
if ((access(DMEVENTD_PIDFILE, F_OK) == -1) && (errno == ENOENT))
break;
usleep(10);
}
if (!_systemd_activation) {
fini_fifos(&fifos);
return;
}
/* Reopen fifos. */
fini_fifos(&fifos);
if (!init_fifos(&fifos)) {
fprintf(stderr, "Could not initiate communication with new instance of dmeventd.\n");
exit(EXIT_FAILURE);
}
if (!_reinstate_registrations(&fifos)) {
fprintf(stderr, "Failed to reinstate monitoring with new instance of dmeventd.\n");
goto bad;
}
fini_fifos(&fifos);
exit(EXIT_SUCCESS);
bad:
fini_fifos(&fifos);
exit(EXIT_FAILURE);
}
static void usage(char *prog, FILE *file)
{
fprintf(file, "Usage:\n"
"%s [-d [-d [-d]]] [-f] [-h] [-R] [-V] [-?]\n\n"
" -d Log debug messages to syslog (-d, -dd, -ddd)\n"
" -f Don't fork, run in the foreground\n"
" -h -? Show this help information\n"
" -R Restart dmeventd\n"
" -V Show version of dmeventd\n\n", prog);
}
int main(int argc, char *argv[])
{
signed char opt;
struct dm_event_fifos fifos = {
.client = -1,
.server = -1,
.client_path = DM_EVENT_FIFO_CLIENT,
.server_path = DM_EVENT_FIFO_SERVER
};
int nothreads;
//struct sys_log logdata = {DAEMON_NAME, LOG_DAEMON};
opterr = 0;
optind = 0;
while ((opt = getopt(argc, argv, "?fhVdR")) != EOF) {
switch (opt) {
case 'h':
usage(argv[0], stdout);
exit(EXIT_SUCCESS);
case '?':
usage(argv[0], stderr);
exit(EXIT_SUCCESS);
case 'R':
_restart++;
break;
case 'f':
_foreground++;
break;
case 'd':
dmeventd_debug++;
break;
case 'V':
printf("dmeventd version: %s\n", DM_LIB_VERSION);
exit(EXIT_SUCCESS);
}
}
/*
* Switch to C locale to avoid reading large locale-archive file
* used by some glibc (on some distributions it takes over 100MB).
* Daemon currently needs to use mlockall().
*/
if (setenv("LC_ALL", "C", 1))
perror("Cannot set LC_ALL to C");
if (_restart)
restart();
#ifdef __linux__
_systemd_activation = _systemd_handover(&fifos);
#endif
if (!_foreground)
_daemonize();
openlog("dmeventd", LOG_PID, LOG_DAEMON);
(void) dm_prepare_selinux_context(DMEVENTD_PIDFILE, S_IFREG);
if (dm_create_lockfile(DMEVENTD_PIDFILE) == 0)
exit(EXIT_FAILURE);
atexit(_remove_files_on_exit);
(void) dm_prepare_selinux_context(NULL, 0);
/* Set the rest of the signals to cause '_exit_now' to be set */
signal(SIGTERM, &_exit_handler);
signal(SIGINT, &_exit_handler);
signal(SIGHUP, &_exit_handler);
signal(SIGQUIT, &_exit_handler);
#ifdef __linux__
/* Systemd has adjusted oom killer for us already */
if (!_systemd_activation && !_protect_against_oom_killer())
syslog(LOG_ERR, "Failed to protect against OOM killer");
#endif
_init_thread_signals();
//multilog_clear_logging();
//multilog_add_type(std_syslog, &logdata);
//multilog_init_verbose(std_syslog, _LOG_DEBUG);
//multilog_async(1);
pthread_mutex_init(&_global_mutex, NULL);
if (!_systemd_activation && !_open_fifos(&fifos))
exit(EXIT_FIFO_FAILURE);
/* Signal parent, letting them know we are ready to go. */
if (!_foreground)
kill(getppid(), SIGTERM);
syslog(LOG_NOTICE, "dmeventd ready for processing.");
if (_initial_registrations)
_process_initial_registrations();
for (;;) {
if (_exit_now) {
_exit_now = 0;
/*
* When '_exit_now' is set, signal has been received,
* but can not simply exit unless all
* threads are done processing.
*/
_lock_mutex();
nothreads = (dm_list_empty(&_thread_registry) &&
dm_list_empty(&_thread_registry_unused));
_unlock_mutex();
if (nothreads)
break;
syslog(LOG_ERR, "There are still devices being monitored.");
syslog(LOG_ERR, "Refusing to exit.");
}
_process_request(&fifos);
_cleanup_unused_threads();
}
_exit_dm_lib();
pthread_mutex_destroy(&_global_mutex);
syslog(LOG_NOTICE, "dmeventd shutting down.");
closelog();
exit(EXIT_SUCCESS);
}
|