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 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
|
/* xscreensaver, Copyright © 1991-2023 Jamie Zawinski <jwz@jwz.org>
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation. No representations are made about the suitability of this
* software for any purpose. It is provided "as is" without express or
* implied warranty.
*
* ==========================================================================
* XScreenSaver Daemon, version 6.
* ==========================================================================
*
* Having started its life in 1991, XScreenSaver acquired a lot of optional
* features to allow it to detect user activity, lock the screen and
* authenticate on systems as varied as VMS, SunOS, HPUX, SGI, and of course
* that young upstart, Linux. In such a heterogeneous environment, many
* features that would have simplified things were not universally available.
* Though I made an effort to follow a principle of minimal library usage in
* the XScreenSaver daemon, as described in my 2004 article "On Toolkits"
* <https://www.jwz.org/xscreensaver/toolkits.html>, there was still quite a
* lot of code in the daemon, more than is strictly necessary when we consider
* only modern, still-maintained operating systems.
*
* This 2021 refactor had one goal: to minimize the amount of code in which a
* crash will cause the screen to unlock. In service of that goal, the process
* which holds the keyboard an mouse grabbed should:
*
* - Be as small as technically possible, for ease of auditing;
*
* - Link against as few libraries as possible, to bring in as little
* third-party code as possible;
*
* - Delegate other tasks to helper programs running in other processes,
* in such a way that if those other processes should crash, the grabs
* remain intact and the screen remains locked.
*
* In the XScreenSaver 6 design, the division of labor is as follows:
*
* A) "xscreensaver" -- This is the main screen saver daemon. If this
* process crashes, the screen unlocks, so this is the one where
* minimizing the attack surface is critical.
*
* - It reads events using the XInput extension version 2, which is
* required. This means that X11R7 is also required, which was
* released in 2009, and is ubiquitous as of 2021.
*
* - It links against only libX11 and libXi.
*
* - It maps no windows and renders no graphics or text. It only
* acquires keyboard and mouse grabs, handles timer logic, and
* launches and manages several sub-processes.
*
* B) "xscreensaver-gfx" -- When the time comes for the screen to blank,
* this process is launched to fade out, black out every monitor on
* the system, launch graphics demos to render on those blanked screens,
* and cycle them from time to time.
*
* - If this program crashes, the screen does not unlock. The keyboard
* and mouse remain grabbed by the "xscreensaver" process, which will
* re-launch this process as necessary.
*
* - If it does crash, the logged in user's desktop may be momentarily
* visible before it re-launches, but it will be impossible to interact
* with it.
*
* - This process must react to hot-swapping of monitors in order to
* keep the screen blanked and the desktop obscured, and manages the
* life cycle of the graphics demos, each running in their own
* sub-process of "xscreensaver-gfx".
*
* C) The graphics demos themselves. Launched by "xscreensaver-gfx" to run
* on the windows provided, there is one of these processes for each
* screen. These can use X11 or OpenGL, and have no impact on security;
* if it breaks, you can keep both pieces.
*
* D) "xscreensaver-auth" -- When the time comes to prompt the user for their
* password to unlock the screen, the "xscreensaver" daemon launches this
* process. If it exits with a "success" error code, the screen unlocks,
* otherwise it does not. This means that if it crashes, the screen
* remains locked.
*
* - It turns out that programs using the XInput 2 extension are able to
* snoop the keyboard even when the keyboard is grabbed by another
* process! So that's how this program reads user input, even while
* the "xscreensaver" process has the keyboard grabbed.
*
* - This program runs PAM, or whatever other authorization mechanisms
* are configured. On some systems, it may need to be setuid in order
* to read /etc/shadow, meaning it must disavow privileges after
* initialization but before connecting to the X server.
*
* - It gets to use libXft, so the fonts don't suck.
*
* - In theory, this program could be implemented using any GUI toolkit,
* and thus take advantage of input methods, on-screen keyboards,
* screen readers, etc. Again, this is permissible because this
* program fails SAFE: if it crashes, the screen remains locked.
*
* E) "xscreensaver-systemd" -- This runs in the background and monitors
* requests on the systemd dbus. This is how closing the laptop lid
* causes the screen to lock, and how video players request that blanking
* be inhibited. This program invokes "xscreensaver-command" as needed
* to pass those requests along to "xscreensaver" via ClientMessages.
*
*
* ==========================================================================
* Ancient History
* ==========================================================================
*
* As mentioned above, XScreenSaver version 6 (released in 2021) requires
* the XInput 2 server extension for idle detection and password input.
* In XScreenSaver 5 and earlier (1991 through 2020), idle-detection was
* far more convoluted. Basically, we selected input events on every window,
* and noticed when new windows were created so that we could track them too.
* Over the decades, there have also been three optional X11 server extensions
* that were applicable to screen saving:
*
* - XIdle
*
* This extension provided a function to poll the user's idle time.
* It was simple and direct and worked great. Therefore, it was
* removed from the X11 distribution in 1994, with the release of
* X11R6. https://bugs.freedesktop.org/show_bug.cgi?id=1419
*
* - SGI SCREEN_SAVER
*
* This extension sent two new events: "user is idle", and "user is no
* longer idle". It was simple and direct and worked great. But as
* the name implies, it only ever worked on Silicon Graphics machines.
* SGI became irrelevant around 1998 and went out of business in 2009.
*
* - MIT-SCREEN-SAVER
*
* This extension still exists, but it is useless to us. Since it still
* exists, people sometimes ask why XScreenSaver no longer makes use of it.
* The MIT-SCREEN-SAVER extension took the following approach:
*
* - When the user is idle, immediately map full screen black windows
* on each screen.
*
* - Inform the screen saver client that the screen is now black.
*
* - When user activity occurs, unmap the windows and then inform the
* screen saver client.
*
* The screen saver client was able to specify a few parameters of that
* window, like visual and depth, but that was all.
*
* The extension was designed with the assumption that a screen saver would
* render onto the provided window. However:
*
* - OpenGL programs may require different visuals than 2D X11 programs,
* and you can't change the visual of a window after it has been
* created.
*
* - The extension mapped one window per X11 "Screen", which, in this
* modern world, tend to span the entire virtual desktop; whereas
* XScreenSaver runs savers full screen on each *monitor* instead.
* In other words, it was incompatible with Xinerama / RANDR.
*
* - Since this extension mapped its own full-screen black windows and
* informed us of that after the fact, it precluded "fade" and "unfade"
* animations from being implemented.
*
* - Since it only told us when the user was idle or non-idle, it
* precluded the "hysteresis" option from being implemented (ignoring
* tiny mouse motions).
*
* In summary, it created its windows too early, removed them too late,
* created windows of the wrong quantity and wrong shape, could not create
* them with the proper visuals, and delivered too little information about
* what caused the user activity.
*
* Also, the MIT-SCREEN-SAVER extension was flaky, and using it at all led
* to frequent server crashes. Worse, those server crashes were highly
* dependent on your particular video driver.
*
* So that's why, even if the server supports the MIT-SCREEN-SAVER
* extension, we don't use it.
*
* Some video players attempt to inhibit blanking during playback by
* calling XResetScreenSaver and/or XScreenSaverSuspend, which affect
* only the X server's *built-in* screen saver, and the window created
* by the MIT-SCREEN-SAVER extension. To rely upon those calls alone
* and then call it a day would betray a willful ignorance of why the
* MIT-SCREEN-SAVER extension is a useless foundation upon which to
* build a screen saver or screen locker.
*
* Fortunately, every modern video player and web browser also makes
* use of systemd / logind / dbus to request blanking inhibition, and
* we receive those requests via our systemd integration in
* xscreensaver-systemd (which see).
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "version.h"
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <stdio.h>
#include <ctype.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <errno.h>
#include <pwd.h> /* for getpwuid() */
#include <grp.h> /* for getgrgid() */
#ifdef HAVE_UNAME
# include <sys/utsname.h> /* for uname() */
#endif /* HAVE_UNAME */
#ifdef HAVE_SYS_WAIT_H
# include <sys/wait.h> /* for waitpid() and associated macros */
#endif
#ifndef HAVE_XINPUT
# error The XInput2 extension is required
#endif
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include <X11/cursorfont.h>
#include <X11/Xos.h>
#include <X11/extensions/XInput2.h>
#include "xmu.h"
#include "blurb.h"
#include "atoms.h"
#include "clientmsg.h"
#include "xinput.h"
#include "prefs.h"
#undef countof
#define countof(x) (sizeof((x))/sizeof((*x)))
#undef ABS
#define ABS(x)((x)<0?-(x):(x))
#undef MAX
#define MAX(x,y)((x)>(y)?(x):(y))
/* Globals used in this file.
*/
Bool debug_p = False;
static Bool splash_p = True;
static const char *version_number = 0;
/* Preferences. */
static Bool lock_p = False;
static Bool locking_disabled_p = False;
static Bool blanking_disabled_p = False;
static unsigned int blank_timeout = 0;
static unsigned int lock_timeout = 0;
static unsigned int pointer_hysteresis = 0;
/* Subprocesses. */
#define SAVER_GFX_PROGRAM "xscreensaver-gfx"
#define SAVER_AUTH_PROGRAM "xscreensaver-auth"
#define SAVER_SYSTEMD_PROGRAM "xscreensaver-systemd"
static pid_t saver_gfx_pid = 0;
static pid_t saver_auth_pid = 0;
static pid_t saver_systemd_pid = 0;
static int sighup_received = 0;
static int sigterm_received = 0;
static int sigchld_received = 0;
static Bool gfx_stopped_p = False;
Window daemon_window = 0;
Cursor blank_cursor = None;
Cursor auth_cursor = None;
/* for the --restart command.
*/
static char **saved_argv;
static void
save_argv (int ac, char **av)
{
saved_argv = (char **) calloc (ac+2, sizeof (char *));
saved_argv [ac] = 0;
while (ac--)
{
int i = strlen (av[ac]) + 1;
saved_argv[ac] = (char *) malloc (i);
memcpy (saved_argv[ac], av[ac], i);
}
}
static void
kill_all_subprocs (void)
{
if (saver_gfx_pid)
{
if (verbose_p)
fprintf (stderr, "%s: pid %lu: killing " SAVER_GFX_PROGRAM "\n",
blurb(), (unsigned long) saver_gfx_pid);
kill (saver_gfx_pid, SIGTERM);
if (gfx_stopped_p) /* SIGCONT to allow SIGTERM to proceed */
{
if (verbose_p)
fprintf (stderr, "%s: pid %lu: sending " SAVER_GFX_PROGRAM
" SIGCONT\n",
blurb(), (unsigned long) saver_gfx_pid);
gfx_stopped_p = False;
kill (-saver_gfx_pid, SIGCONT); /* send to process group */
}
}
if (saver_auth_pid)
{
if (verbose_p)
fprintf (stderr, "%s: pid %lu: killing " SAVER_AUTH_PROGRAM "\n",
blurb(), (unsigned long) saver_auth_pid);
kill (saver_auth_pid, SIGTERM);
}
if (saver_systemd_pid)
{
if (verbose_p)
fprintf (stderr, "%s: pid %lu: killing " SAVER_SYSTEMD_PROGRAM "\n",
blurb(), (unsigned long) saver_systemd_pid);
kill (saver_systemd_pid, SIGTERM);
}
}
static void
saver_exit (int status)
{
kill_all_subprocs();
exit (status);
}
static void
catch_signal (int sig, RETSIGTYPE (*handler) (int))
{
# ifdef HAVE_SIGACTION
struct sigaction a;
a.sa_handler = handler;
sigemptyset (&a.sa_mask);
a.sa_flags = 0;
/* On Linux 2.4.9 (at least) we need to tell the kernel to not mask delivery
of this signal from inside its handler, or else when we execvp() the
process again, it starts up with SIGHUP blocked, meaning that killing
it with -HUP only works *once*. You'd think that execvp() would reset
all the signal masks, but it doesn't.
*/
# if defined(SA_NOMASK)
a.sa_flags |= SA_NOMASK;
# elif defined(SA_NODEFER)
a.sa_flags |= SA_NODEFER;
# endif
if (sigaction (sig, &a, 0) < 0)
# else /* !HAVE_SIGACTION */
if (((long) signal (sig, handler)) == -1L)
# endif /* !HAVE_SIGACTION */
{
char buf [255];
sprintf (buf, "%s: couldn't catch signal %d", blurb(), sig);
perror (buf);
saver_exit (1);
}
}
/* Re-execs the process with the arguments in saved_argv. Does not return.
Do not call this while the screen is locked: user must unlock first.
*/
static void
restart_process (void)
{
kill_all_subprocs();
execvp (saved_argv [0], saved_argv); /* shouldn't return */
{
char buf [512];
sprintf (buf, "%s: could not restart process", blurb());
perror(buf);
fflush(stderr);
abort();
}
}
static RETSIGTYPE saver_sighup_handler (int sig) { sighup_received = sig; }
static RETSIGTYPE saver_sigchld_handler (int sig) { sigchld_received = sig; }
static RETSIGTYPE saver_sigterm_handler (int sig) { sigterm_received = sig; }
static void
handle_signals (void)
{
catch_signal (SIGHUP, saver_sighup_handler);
catch_signal (SIGCHLD, saver_sigchld_handler);
catch_signal (SIGTERM, saver_sigterm_handler); /* kill */
catch_signal (SIGINT, saver_sigterm_handler); /* shell ^C */
catch_signal (SIGQUIT, saver_sigterm_handler); /* shell ^| */
}
static pid_t
fork_and_exec (Display *dpy, int argc, char **argv)
{
char buf [255];
pid_t forked = fork();
switch ((int) forked) {
case -1:
sprintf (buf, "%s: couldn't fork", blurb());
perror (buf);
break;
case 0:
close (ConnectionNumber (dpy)); /* close display fd */
execvp (argv[0], argv); /* shouldn't return. */
sprintf (buf, "%s: pid %lu: couldn't exec %s", blurb(),
(unsigned long) getpid(), argv[0]);
perror (buf);
exit (1); /* exits child fork */
break;
default: /* parent fork */
if (verbose_p)
{
int i;
fprintf (stderr, "%s: pid %lu: launched",
blurb(), (unsigned long) forked);
for (i = 0; i < argc; i++)
fprintf (stderr, " %s", argv[i]);
fprintf (stderr, "\n");
}
/* Put each launched process in its own process group so that
SIGSTOP will affect all of its inferior processes as well.
*/
if (setpgid (forked, 0))
{
char buf [255];
sprintf (buf, "%s: setpgid %d", blurb(), forked);
perror (buf);
}
break;
}
return forked;
}
static int respawn_thrashing_count = 0;
/* Called from the main loop some time after the SIGCHLD signal has fired.
Returns true if:
- the process that died was "xscreensaver-auth", and
- it exited with a "success" status meaning "user is authenticated".
*/
static Bool
handle_sigchld (Display *dpy, Bool blanked_p)
{
Bool authenticated_p = False;
sigchld_received = 0;
if (debug_p)
fprintf (stderr, "%s: SIGCHLD received\n", blurb());
/* Reap every now-dead inferior without blocking. */
while (1)
{
int wait_status = 0;
pid_t kid = waitpid (-1, &wait_status, WNOHANG | WUNTRACED);
char how[100];
/* 0 means no more children to reap.
-1 means error -- except "interrupted system call"
isn't a "real" error, so if we get that, try again.
*/
if (kid == 0 ||
(kid < 0 && errno != EINTR))
break;
/* We get SIGCHLD after sending SIGSTOP, but no action is required. */
if (WIFSTOPPED (wait_status))
{
if (verbose_p)
fprintf (stderr, "%s: pid %lu: %s stopped\n", blurb(),
(unsigned long) kid,
(kid == saver_gfx_pid ? SAVER_GFX_PROGRAM :
kid == saver_auth_pid ? SAVER_AUTH_PROGRAM :
kid == saver_systemd_pid ? SAVER_SYSTEMD_PROGRAM :
"unknown"));
continue;
}
if (WIFSIGNALED (wait_status))
{
if (WTERMSIG (wait_status) == SIGTERM)
strcpy (how, "with SIGTERM");
else
sprintf (how, "with signal %d", WTERMSIG (wait_status));
}
else if (WIFEXITED (wait_status))
{
int exit_status = WEXITSTATUS (wait_status);
/* Treat exit code as a signed 8-bit quantity. */
if (exit_status & 0x80) exit_status |= ~0xFF;
if (exit_status)
sprintf (how, "with status %d", exit_status);
else
strcpy (how, "normally");
}
else
sprintf (how, "for unknown reason %d", wait_status);
if (kid == saver_gfx_pid)
{
saver_gfx_pid = 0;
gfx_stopped_p = False;
if (blanked_p)
{
if (respawn_thrashing_count > 5)
{
/* If we have tried to re-launch this pid N times in a row
without unblanking, give up instead of forking it in a
tight loop. Screen will remain grabbed, but desktop will
be visible.
*/
fprintf (stderr, "%s: pid %lu: " SAVER_GFX_PROGRAM
" won't re-launch!\n",
blurb(), (unsigned long) kid);
}
else
{
char *av[10];
int ac = 0;
av[ac++] = SAVER_GFX_PROGRAM;
av[ac++] = "--emergency";
if (verbose_p) av[ac++] = "--verbose";
if (verbose_p > 1) av[ac++] = "--verbose";
if (verbose_p > 2) av[ac++] = "--verbose";
if (debug_p) av[ac++] = "--debug";
av[ac] = 0;
fprintf (stderr, "%s: pid %lu: " SAVER_GFX_PROGRAM
" exited unexpectedly %s: re-launching\n",
blurb(), (unsigned long) kid, how);
gfx_stopped_p = False;
saver_gfx_pid = fork_and_exec (dpy, ac, av);
respawn_thrashing_count++;
}
}
else
{
/* Should not have been running anyway. */
if (verbose_p)
fprintf (stderr, "%s: pid %lu: " SAVER_GFX_PROGRAM
" exited %s\n", blurb(), (unsigned long) kid, how);
}
}
else if (kid == saver_systemd_pid)
{
/* xscreensaver-systemd might fail if systemd isn't running, or if
xscreensaver-systemd was already running, or if some other
program has bound to our targets. Or if it doesn't exist because
this system doesn't use systemd. So don't re-launch it if it
failed to start, or dies.
*/
saver_systemd_pid = 0;
fprintf (stderr, "%s: pid %lu: " SAVER_SYSTEMD_PROGRAM
" exited unexpectedly %s\n",
blurb(), (unsigned long) kid, how);
}
else if (kid == saver_auth_pid)
{
saver_auth_pid = 0;
/* xscreensaver-auth exits with status 200 to mean "ok to unlock".
Any other exit code, or dying with a signal, means "nope".
*/
if (!WIFSIGNALED (wait_status) &&
WIFEXITED (wait_status))
{
unsigned int status = (unsigned int) WEXITSTATUS (wait_status);
if (status == 200)
{
authenticated_p = True;
strcpy (how, "and authenticated");
}
else if (status == 0 && !blanked_p)
strcpy (how, "normally"); /* This was the splash dialog */
else if (status == 0)
strcpy (how, "and authentication canceled");
else if (status == 255) /* which is -1 */
strcpy (how, "and authentication failed");
}
if (verbose_p)
fprintf (stderr, "%s: pid %lu: " SAVER_AUTH_PROGRAM " exited %s\n",
blurb(), (unsigned long) kid, how);
}
else if (verbose_p)
{
fprintf (stderr, "%s: pid %lu: unknown child"
" exited unexpectedly %s\n",
blurb(), (unsigned long) kid, how);
}
}
return authenticated_p;
}
/* Add DEFAULT_PATH_PREFIX to the front of $PATH.
Typically "/usr/libexec/xscreensaver".
*/
static void
hack_environment (void)
{
static const char *def_path = DEFAULT_PATH_PREFIX;
const char *opath = getenv("PATH");
char *npath;
if (! opath) opath = "/bin:/usr/bin"; /* WTF */
npath = (char *) malloc(strlen(def_path) + strlen(opath) + 20);
strcpy (npath, "PATH=");
strcat (npath, def_path);
strcat (npath, ":");
strcat (npath, opath);
/* Can fail if out of memory, I guess. Ignore errors. */
putenv (npath);
/* don't free (npath) -- some implementations of putenv (BSD 4.4,
glibc 2.0) copy the argument, but some (libc4,5, glibc 2.1.2)
do not. So we must leak it (and/or the previous setting). Yay.
*/
}
static void
print_banner(void)
{
const time_t rel = XSCREENSAVER_RELEASED;
struct tm *tm = localtime (&rel);
char buf[100];
int months = (time ((time_t *) 0) - XSCREENSAVER_RELEASED) / (60*60*24*30);
int years = months / 12.0 + 0.7;
strftime (buf, sizeof(buf), "%b %Y", tm);
if (months > 18)
sprintf (buf + strlen(buf), " -- %d years ago", years);
else if (months > 1)
sprintf (buf + strlen(buf), " -- %d months ago", months);
if (verbose_p || debug_p)
{
fprintf (stderr,
"\tXScreenSaver " XSCREENSAVER_VERSION ", released %s\n"
"\tCopyright \302\251 1991-%d by"
" Jamie Zawinski <jwz@jwz.org>\n\n",
buf, tm->tm_year + 1900);
if (months > 18)
fprintf (stderr,
/* Hey jerks, the only time someone will see this particular
message is if they are running xscreensaver with '-log' in
order to send me a bug report, and they had damned well
better try the latest release before they do that --
even if your perma-out-of-date distro does not make that
easily available to them. */
"\t ###################################################\n"
"\t ### ###\n"
"\t ### THIS VERSION IS VERY OLD! PLEASE UPGRADE! ###\n"
"\t ### Do not report bugs upstream, please use ###\n"
"\t ### your distro (Debian/Ubuntu) bug tracker. ###\n"
"\t ### ###\n"
"\t ###################################################\n"
"\n");
}
if (debug_p)
fprintf (stderr,
"#####################################"
"#####################################\n"
"\n"
"\t\t\t DEBUG MODE IS NOT SECURE\n"
"\n"
"\tThe XScreenSaver window will only cover the left half of\n"
"\tthe screen. Position your terminal window on the right.\n"
"\tWARNING: stderr and the log file will include every\n"
"\tcharacter that you type, including passwords.\n"
"\n"
"#####################################"
"#####################################\n"
"\n");
version_number = XSCREENSAVER_VERSION;
}
static void
fix_fds (void)
{
/* Bad Things Happen if stdin, stdout, and stderr have been closed
(as by the `sh incantation "xscreensaver >&- 2>&-"). When you do
that, the X connection gets allocated to one of these fds, and
then some random library writes to stderr, and random bits get
stuffed down the X pipe, causing "Xlib: sequence lost" errors.
So, we cause the first three file descriptors to be open to
/dev/null if they aren't open to something else already. This
must be done before any other files are opened (or the closing
of that other file will again free up one of the "magic" first
three FDs.)
We do this by opening /dev/null three times, and then closing
those fds, *unless* any of them got allocated as #0, #1, or #2,
in which case we leave them open. Gag.
Really, this crap is technically required of *every* X program,
if you want it to be robust in the face of "2>&-".
*/
int fd0 = open ("/dev/null", O_RDWR);
int fd1 = open ("/dev/null", O_RDWR);
int fd2 = open ("/dev/null", O_RDWR);
if (fd0 > 2) close (fd0);
if (fd1 > 2) close (fd1);
if (fd2 > 2) close (fd2);
}
/* Mostly duplicated in resources.c.
*/
static int
parse_time (const char *string)
{
unsigned int h, m, s;
char c;
if (3 == sscanf (string, " %u : %2u : %2u %c", &h, &m, &s, &c))
;
else if (2 == sscanf (string, " : %2u : %2u %c", &m, &s, &c) ||
2 == sscanf (string, " %u : %2u %c", &m, &s, &c))
h = 0;
else if (1 == sscanf (string, " : %2u %c", &s, &c))
h = m = 0;
else if (1 == sscanf (string, " %u %c", &m, &c))
h = s = 0;
else
{
fprintf (stderr, "%s: unparsable duration \"%s\"\n", blurb(), string);
return -1;
}
if (s >= 60 && (h != 0 || m != 0))
{
fprintf (stderr, "%s: seconds > 59 in \"%s\"\n", blurb(), string);
return -1;
}
if (m >= 60 && h > 0)
{
fprintf (stderr, "%s: minutes > 59 in \"%s\"\n", blurb(), string);
return -1;
}
return ((h * 60 * 60) + (m * 60) + s);
}
/* This program only needs a very few options from the init file, so it
just reads the .ad file and the .xscreensaver file directly rather
than going through Xt and Xrm.
*/
static void init_line_handler (int lineno,
const char *key, const char *val,
void *closure)
{
if (*key == '*' || *key == '.') key++; /* Xrm wildcards */
if (!strcmp (key, "verbose")) verbose_p = !strcasecmp (val, "true");
else if (!strcmp (key, "splash")) splash_p = !strcasecmp (val, "true");
else if (!strcmp (key, "lock")) lock_p = !strcasecmp (val, "true");
else if (!strcmp (key, "mode")) blanking_disabled_p =
!strcasecmp (val, "off");
else if (!strcmp (key, "timeout"))
{
int t = parse_time (val);
if (t > 0) blank_timeout = t;
}
else if (!strcmp (key, "lockTimeout"))
{
int t = parse_time (val);
if (t >= 0) lock_timeout = t;
}
else if (!strcmp (key, "pointerHysteresis"))
{
int i = atoi (val);
if (i >= 0)
pointer_hysteresis = i;
}
}
static void
read_init_file_simple (const char *filename)
{
if (debug_p)
fprintf (stderr, "%s: reading %s\n", blurb(), filename);
parse_init_file (filename, init_line_handler, 0);
}
static time_t init_file_time = 0;
static void
read_init_files (Bool both_p)
{
static const char *home = 0;
char *fn;
struct stat st;
Bool read_p = False;
if (!home)
{
home = getenv("HOME");
if (!home) home = "";
}
if (both_p)
{
read_init_file_simple (AD_DIR "/XScreenSaver");
read_p = True;
}
fn = (char *) malloc (strlen(home) + 40);
sprintf (fn, "%s/.xscreensaver", home);
if (!stat (fn, &st))
{
if (both_p || st.st_mtime != init_file_time)
{
Bool ov = verbose_p;
init_file_time = st.st_mtime;
read_init_file_simple (fn);
read_p = True;
/* Changes to verbose in .xscreenaver after startup are ignored; else
running xscreensaver-settings would turn off cmd line -verbose. */
if (!both_p) verbose_p = ov;
}
}
if (blank_timeout < 5)
blank_timeout = 60 * 60 * 10;
free (fn);
if (read_p && verbose_p)
{
fprintf (stderr, "%s: blank after: %d\n", blurb(), blank_timeout);
if (lock_p)
fprintf (stderr, "%s: lock after: %d\n", blurb(), lock_timeout);
}
}
/* We trap and ignore ALL protocol errors that happen after initialization.
By default, Xlib would exit. Ignoring an X error is less bad than
crashing and unlocking.
*/
static Bool ignore_x11_error_p = False;
static Bool error_handler_hit_p = False;
static Bool print_x11_error_p = True;
static int
error_handler (Display *dpy, XErrorEvent *event)
{
error_handler_hit_p = True;
if (print_x11_error_p)
{
const char *b = blurb();
const char *p = progname;
fprintf (stderr, "\n%s: X ERROR! PLEASE REPORT THIS BUG!\n\n", b);
progname = b;
XmuPrintDefaultErrorMessage (dpy, event, stderr);
progname = p;
# ifdef __GNUC__
__extension__ /* don't warn about "string length is greater than the
length ISO C89 compilers are required to support". */
# endif
fprintf (stderr, "\n"
"#######################################################################\n"
"\n"
" If at all possible, please re-run xscreensaver with the command\n"
" line arguments \"-sync -log log.txt\", and reproduce this bug.\n"
" Please include the complete \"log.txt\" file with your bug report.\n"
"\n"
" https://www.jwz.org/xscreensaver/bugs.html explains how to create\n"
" the most useful bug reports.\n"
"\n"
" The more information you can provide, the better. But please\n"
" report this bug, regardless!\n"
"\n"
"#######################################################################\n"
"\n"
"\n");
fflush (stderr);
if (! ignore_x11_error_p)
abort();
}
return 0;
}
/* Check for other running instances of XScreenSaver, gnome-screensaver, etc.
*/
static void
ensure_no_screensaver_running (Display *dpy)
{
int screen, nscreens = ScreenCount (dpy);
/* Silently ignore BadWindow race conditions. */
Bool op = print_x11_error_p;
print_x11_error_p = False;
for (screen = 0; screen < nscreens; screen++)
{
int i;
Window root = RootWindow (dpy, screen);
Window root2 = 0, parent = 0, *kids = 0;
unsigned int nkids = 0;
if (! XQueryTree (dpy, root, &root2, &parent, &kids, &nkids))
continue;
if (root != root2)
continue;
if (parent)
continue;
for (i = 0; i < nkids; i++)
{
Atom type;
int format;
unsigned long nitems, bytesafter;
unsigned char *version;
if (XGetWindowProperty (dpy, kids[i], XA_SCREENSAVER_VERSION, 0, 1,
False, XA_STRING, &type, &format, &nitems,
&bytesafter, &version)
== Success
&& type != None)
{
unsigned char *id;
if (XGetWindowProperty (dpy, kids[i], XA_SCREENSAVER_ID, 0, 512,
False, XA_STRING, &type, &format,
&nitems, &bytesafter, &id)
!= Success
|| type == None)
id = (unsigned char *) "???";
fprintf (stderr,
"%s: already running on display %s"
" (window 0x%x)\n from process %s\n",
blurb(), DisplayString (dpy), (int) kids [i],
(char *) id);
saver_exit (1);
}
else if (XGetWindowProperty (dpy, kids[i], XA_WM_COMMAND, 0, 128,
False, XA_STRING, &type, &format,
&nitems, &bytesafter, &version)
== Success
&& type != None
&& (!strcmp ((char *) version, "gnome-screensaver") ||
!strcmp ((char *) version, "mate-screensaver") ||
!strcmp ((char *) version, "cinnamon-screensaver") ||
!strcmp ((char *) version, "xfce4-screensaver") ||
!strcmp ((char *) version, "light-locker")))
{
fprintf (stderr,
"%s: \"%s\" is already running on display %s"
" (window 0x%x)\n",
blurb(), (char *) version,
DisplayString (dpy), (int) kids [i]);
saver_exit (1);
}
}
if (kids) XFree ((char *) kids);
}
print_x11_error_p = op;
}
/* Store a property on the root window indicating that xscreensaver is
running, and whether it is blanked or locked. This property is read
by "xscreensaver-command" and by ensure_no_screensaver_running().
This property is also overwritten by "xscreensaver-gfx" to indicate
which screenhacks are running.
*/
static void
store_saver_status (Display *dpy,
Bool blanked_p, Bool locked_p, time_t blank_time)
{
/* The contents of XA_SCREENSAVER_STATUS has LOCK/BLANK/0 in the first slot,
the time at which that state began in the second slot, and the ordinal of
the running hacks on each screen (1-based) in subsequent slots. Since
we don't know the hacks here (or even how many monitors are attached) we
leave whatever was there before unchanged: it will be updated by
"xscreensaver-gfx".
XA_SCREENSAVER_STATUS is stored on the (real) root window of screen 0.
XA_SCREENSAVER_VERSION and XA_SCREENSAVER_ID are stored on the unmapped
window created by the "xscreensaver" process. ClientMessage events are
sent to that window, and the responses are sent via the
XA_SCREENSAVER_RESPONSE property on it.
These properties are not used on the windows created by "xscreensaver-gfx"
for use by the display hacks.
See the different version of this function in windows.c.
*/
Window w = RootWindow (dpy, 0); /* always screen 0 */
Atom type;
unsigned char *dataP = 0;
PROP32 *status = 0;
int format;
unsigned long nitems, bytesafter;
/* Read the old property, so we can change just parts. */
if (XGetWindowProperty (dpy, w,
XA_SCREENSAVER_STATUS,
0, 999, False, XA_INTEGER,
&type, &format, &nitems, &bytesafter,
&dataP)
== Success
&& type == XA_INTEGER
&& nitems >= 3
&& dataP)
status = (PROP32 *) dataP;
if (!status) /* There was no existing property */
{
nitems = 3;
status = (PROP32 *) malloc (nitems * sizeof(*status));
}
status[0] = (PROP32) (locked_p ? XA_LOCK : blanked_p ? XA_BLANK : 0);
status[1] = (PROP32) blank_time; /* Y2038 bug: unsigned 32 bit time_t */
XChangeProperty (dpy, w, XA_SCREENSAVER_STATUS, XA_INTEGER, 32,
PropModeReplace, (unsigned char *) status, nitems);
XSync (dpy, False);
# if 0
if (debug_p && verbose_p)
{
int i;
fprintf (stderr, "%s: wrote status property: 0x%lx: %s", blurb(),
(unsigned long) w,
(status[0] == XA_LOCK ? "LOCK" :
status[0] == XA_BLANK ? "BLANK" :
status[0] == 0 ? "0" : "???"));
for (i = 1; i < nitems; i++)
fprintf (stderr, ", %lu", status[i]);
fprintf (stderr, "\n");
if (system ("xprop -root _SCREENSAVER_STATUS") <= 0)
fprintf (stderr, "%s: xprop exec failed\n", blurb());
}
# endif /* 0 */
if (status != (PROP32 *) dataP)
free (status);
if (dataP)
XFree (dataP);
}
/* This process does not map any windows on the screen. However, it creates
one hidden window on screen 0, which is the rendezvous point for
communication with xscreensaver-command: that window is how it can tell
that XScreenSaver is running, what the version number is, and it is where
bidirectional ClientMessage communication takes place. Since there are
no "blanking" windows around at all when xscreensaver-gfx is not running,
this window is needed. We could have instead re-tooled xscreensaver-command
to do all of its communication through the root window instead, but this
seemed easier.
*/
static void
create_daemon_window (Display *dpy)
{
XClassHint class_hints;
XSetWindowAttributes attrs;
unsigned long attrmask = 0;
const char *name = "???";
const char *host = "???";
char buf[20];
pid_t pid = getpid();
struct passwd *p = getpwuid (getuid ());
time_t now = time ((time_t *) 0);
char *id;
# ifdef HAVE_UNAME
struct utsname uts;
# endif
if (p && p->pw_name && *p->pw_name)
name = p->pw_name;
else if (p)
{
sprintf (buf, "%lu", (unsigned long) p->pw_uid);
name = buf;
}
else
name = "???";
# ifdef HAVE_UNAME
{
if (! uname (&uts))
host = uts.nodename;
}
# endif
class_hints.res_name = (char *) progname; /* not const? */
class_hints.res_class = "XScreenSaver";
id = (char *) malloc (strlen(name) + strlen(host) + 50);
sprintf (id, "%lu (%s@%s)", (unsigned long) pid, name, host);
attrmask = CWOverrideRedirect | CWEventMask;
attrs.override_redirect = True;
attrs.event_mask = PropertyChangeMask;
daemon_window = XCreateWindow (dpy, RootWindow (dpy, 0),
0, 0, 1, 1, 0,
DefaultDepth (dpy, 0), InputOutput,
DefaultVisual (dpy, 0), attrmask, &attrs);
XStoreName (dpy, daemon_window, "XScreenSaver Daemon");
XSetClassHint (dpy, daemon_window, &class_hints);
XChangeProperty (dpy, daemon_window, XA_WM_COMMAND, XA_STRING,
8, PropModeReplace, (unsigned char *) progname,
strlen (progname));
XChangeProperty (dpy, daemon_window, XA_SCREENSAVER_VERSION, XA_STRING,
8, PropModeReplace, (unsigned char *) version_number,
strlen (version_number));
XChangeProperty (dpy, daemon_window, XA_SCREENSAVER_ID, XA_STRING,
8, PropModeReplace, (unsigned char *) id, strlen (id));
store_saver_status (dpy, False, False, now);
free (id);
}
static const char *
grab_string (int status)
{
switch (status) {
case GrabSuccess: return "GrabSuccess";
case AlreadyGrabbed: return "AlreadyGrabbed";
case GrabInvalidTime: return "GrabInvalidTime";
case GrabNotViewable: return "GrabNotViewable";
case GrabFrozen: return "GrabFrozen";
default:
{
static char buf[255];
sprintf(buf, "unknown status: %d", status);
return buf;
}
}
}
static int
grab_kbd (Screen *screen)
{
Display *dpy = DisplayOfScreen (screen);
Window w = RootWindowOfScreen (screen);
int status = XGrabKeyboard (dpy, w, True, GrabModeAsync, GrabModeAsync,
CurrentTime);
if (verbose_p)
fprintf (stderr, "%s: grabbing keyboard on 0x%lx: %s\n",
blurb(), (unsigned long) w, grab_string (status));
return status;
}
static int
grab_mouse (Screen *screen, Cursor cursor)
{
Display *dpy = DisplayOfScreen (screen);
Window w = RootWindowOfScreen (screen);
int status = XGrabPointer (dpy, w, True,
(ButtonPressMask | ButtonReleaseMask |
EnterWindowMask | LeaveWindowMask |
PointerMotionMask | PointerMotionHintMask |
Button1MotionMask | Button2MotionMask |
Button3MotionMask | Button4MotionMask |
Button5MotionMask | ButtonMotionMask),
GrabModeAsync, GrabModeAsync, w,
cursor, CurrentTime);
if (verbose_p)
fprintf (stderr, "%s: grabbing mouse on 0x%lx... %s\n",
blurb(), (unsigned long) w, grab_string (status));
return status;
}
static void
ungrab_kbd (Display *dpy)
{
if (verbose_p)
fprintf (stderr, "%s: ungrabbing keyboard\n", blurb());
XUngrabKeyboard (dpy, CurrentTime);
}
static void
ungrab_mouse (Display *dpy)
{
if (verbose_p)
fprintf (stderr, "%s: ungrabbing mouse\n", blurb());
XUngrabPointer (dpy, CurrentTime);
}
/* Some remote desktop clients (e.g., "rdesktop") hold the keyboard GRABBED the
whole time they have focus! This is idiotic because the whole point of
grabbing is to get events when you do *not* have focus, so grabbing only
*when* you have focus is redundant. Anyway, that prevents us from getting a
keyboard grab. It turns out that for some of these apps, de-focusing them
forces them to release their grab.
So if we fail to grab the keyboard four times in a row, we forcibly set
focus to "None" and try four more times. We don't touch focus unless we're
already having a hard time getting a grab.
*/
static void
nuke_focus (Screen *screen)
{
Display *dpy = DisplayOfScreen (screen);
Window focus = 0;
int rev = 0;
XGetInputFocus (dpy, &focus, &rev);
if (verbose_p)
{
char w[255], r[255];
if (focus == PointerRoot) strcpy (w, "PointerRoot");
else if (focus == None) strcpy (w, "None");
else sprintf (w, "0x%lx", (unsigned long) focus);
if (rev == RevertToParent) strcpy (r, "RevertToParent");
else if (rev == RevertToPointerRoot) strcpy (r, "RevertToPointerRoot");
else if (rev == RevertToNone) strcpy (r, "RevertToNone");
else sprintf (r, "0x%x", rev);
fprintf (stderr, "%s: removing focus from %s / %s\n",
blurb(), w, r);
}
XSetInputFocus (dpy, None, RevertToNone, CurrentTime);
}
static void
ungrab_keyboard_and_mouse (Display *dpy)
{
ungrab_mouse (dpy);
ungrab_kbd (dpy);
}
/* Returns true if it succeeds.
*/
static Bool
grab_keyboard_and_mouse (Screen *screen)
{
Display *dpy = DisplayOfScreen (screen);
Status mstatus = 0, kstatus = 0;
int i;
int retries = 4;
Bool focus_fuckus = False;
AGAIN:
for (i = 0; i < retries; i++)
{
XSync (dpy, False);
kstatus = grab_kbd (screen);
if (kstatus == GrabSuccess)
break;
/* else, wait a second and try to grab again. */
sleep (1);
}
if (kstatus != GrabSuccess)
{
fprintf (stderr, "%s: couldn't grab keyboard: %s\n",
blurb(), grab_string (kstatus));
if (! focus_fuckus)
{
focus_fuckus = True;
nuke_focus (screen);
goto AGAIN;
}
}
for (i = 0; i < retries; i++)
{
XSync (dpy, False);
mstatus = grab_mouse (screen, blank_cursor);
if (mstatus == GrabSuccess)
break;
/* else, wait a second and try to grab again. */
sleep (1);
}
if (mstatus != GrabSuccess)
fprintf (stderr, "%s: couldn't grab pointer: %s\n",
blurb(), grab_string (mstatus));
/* When should we allow blanking to proceed? The current theory
is that a keyboard grab is mandatory; a mouse grab is optional.
- If we don't have a keyboard grab, then we won't be able to
read a password to unlock, so the kbd grab is mandatory.
(We can't conditionalize this on locked_p, because someone
might run "xscreensaver-command -lock" at any time.)
- If we don't have a mouse grab, then we might not see mouse
clicks as a signal to unblank -- but we will still see kbd
activity, so that's not a disaster.
If the mouse grab failed with AlreadyGrabbed, then I *think*
that means that we will still see the mouse events via XInput2.
But if it failed with GrabFrozen, that means that the grabber
used GrabModeSync, and we will only receive those mouse events
as a replay after they release the grab, which doesn't help us.
If the keyboard grab failed with AlreadyGrabbed rather than
GrabFrozen then we may still get those keypresses -- but so will
the program holding the grab, so that's unacceptable for our
purpose of reading passwords.
It has been suggested that we should allow blanking if locking
is disabled, and we have a mouse grab but no keyboard grab.
That would allow screen blanking (but not locking) while the gdm
login screen had the keyboard grabbed, but one would have to use
the mouse to unblank. Keyboard characters would go to the gdm
login field without unblanking. I have not made this change
because I'm not completely convinced it is a safe thing to do.
*/
if (kstatus != GrabSuccess) /* Do not blank without a kbd grab. */
{
/* If we didn't get both grabs, release the one we did get. */
ungrab_keyboard_and_mouse (dpy);
return False;
}
return True; /* Grab is good, go ahead and blank. */
}
/* Which screen is the mouse on?
*/
static Screen *
mouse_screen (Display *dpy)
{
int i, nscreens = ScreenCount (dpy);
if (nscreens > 1)
for (i = 0; i < nscreens; i++)
{
Window pointer_root, pointer_child;
int root_x, root_y, win_x, win_y;
unsigned int mask;
int status = XQueryPointer (dpy, RootWindow (dpy, i),
&pointer_root, &pointer_child,
&root_x, &root_y, &win_x, &win_y, &mask);
if (status != None)
{
if (verbose_p)
fprintf (stderr, "%s: mouse is on screen %d of %d\n",
blurb(), i, nscreens);
return ScreenOfDisplay (dpy, i);
}
}
return ScreenOfDisplay (dpy, 0);
}
static void
maybe_disable_locking (Display *dpy)
{
const char *why = 0;
Bool wayland_p = (getenv ("WAYLAND_DISPLAY") ||
getenv ("WAYLAND_SOCKET"));
# ifdef NO_LOCKING
why = "locking disabled at compile time";
# endif
if (!why)
{
uid_t u = getuid();
if (u == 0 || u == (uid_t) -1 || u == (uid_t) -2)
why = "cannot lock when running as root";
}
if (!why && getenv ("RUNNING_UNDER_GDM"))
/* Launched as GDM's "Background" program */
why = "cannot lock when running under GDM";
/* X11 grabs don't work under Wayland's embedded X11 server. The Wayland
window manager lives at a higher level than the X11 emulation layer. */
if (!why && wayland_p)
why = "cannot lock securely under Wayland";
if (!why)
{
/* Grabs under the macOS XDarwin server only affect other X11 programs:
you can Cmd-Tab to "Terminal". These extensions exist on later
releases XQuartz. */
int op = 0, event = 0, error = 0;
if (XQueryExtension (dpy, "Apple-DRI", &op, &event, &error) ||
XQueryExtension (dpy, "Apple-WM", &op, &event, &error))
why = "cannot lock securely under macOS X11";
}
if (why)
{
if (debug_p)
{
fprintf (stderr, "%s: %s\n", blurb(), why);
fprintf (stderr, "%s: DEBUG MODE: allowing locking anyway!\n",
blurb());
}
else if (wayland_p)
{
const char *s = blurb();
locking_disabled_p = True;
/* Maybe we should just refuse to launch instead? We can operate
properly only if the user uses only X11 programs, and doesn't
want to lock the screen.
*/
fprintf (stderr, "\n"
"%s: WARNING: Wayland is not supported.\n"
"\n"
"%s: Under Wayland, idle-detection fails when non-X11\n"
"%s: programs are selected, meaning the screen may\n"
"%s: blank prematurely. Also, locking is impossible.\n"
"%s: See the manual for instructions on configuring\n"
"%s: your system to use X11 instead of Wayland.\n\n",
s, s, s, s, s, s);
}
else
{
locking_disabled_p = True;
if (lock_p || verbose_p)
fprintf (stderr, "%s: locking disabled: %s\n", blurb(), why);
}
}
}
static void
main_loop (Display *dpy)
{
int xi_opcode;
time_t now = time ((time_t *) 0);
time_t active_at = now;
time_t blanked_at = 0;
time_t ignore_activity_before = now;
time_t last_checked_init_file = now;
Bool authenticated_p = False;
Bool ignore_motion_p = False;
enum { UNBLANKED, BLANKED, LOCKED, AUTH } current_state = UNBLANKED;
struct { time_t time; int x, y; } last_mouse = { 0, 0, 0 };
maybe_disable_locking (dpy);
init_xscreensaver_atoms (dpy);
ensure_no_screensaver_running (dpy);
if (! init_xinput (dpy, &xi_opcode))
saver_exit (1);
/* Disable server built-in screen saver. */
XSetScreenSaver (dpy, 0, 0, 0, 0);
XForceScreenSaver (dpy, ScreenSaverReset);
/* It would be nice to sync the server's DPMS settings here to what is
specified in the .xscreensaver file, but xscreensaver-gfx handles that,
so that won't happen until the first time the screen blanks. */
create_daemon_window (dpy);
handle_signals();
blank_cursor = None; /* Cursor of window under mouse (which is blank). */
auth_cursor = XCreateFontCursor (dpy, XC_top_left_arrow);
if (strchr (version_number, 'a') || strchr (version_number, 'b'))
splash_p = True; /* alpha and beta releases */
/* Launch "xscreensaver-auth" once at startup with either --splash or --init,
The latter to handle the OOM-killer while setuid. */
{
char *av[10];
int ac = 0;
av[ac++] = SAVER_AUTH_PROGRAM;
av[ac++] = (splash_p ? "--splash" : "--init");
if (verbose_p) av[ac++] = "--verbose";
if (verbose_p > 1) av[ac++] = "--verbose";
if (verbose_p > 2) av[ac++] = "--verbose";
if (debug_p) av[ac++] = "--debug";
av[ac] = 0;
saver_auth_pid = fork_and_exec (dpy, ac, av);
}
# if defined(HAVE_LIBSYSTEMD) || defined(HAVE_LIBELOGIND)
/* Launch xscreensaver-systemd at startup. */
{
char *av[10];
int ac = 0;
av[ac++] = SAVER_SYSTEMD_PROGRAM;
if (verbose_p || debug_p)
av[ac++] = "--verbose";
av[ac] = 0;
saver_systemd_pid = fork_and_exec (dpy, ac, av);
}
# endif /* HAVE_LIBSYSTEMD || HAVE_LIBELOGIND */
/* X11 errors during startup initialization were fatal.
Once we enter the main loop, they are printed but ignored.
*/
XSync (dpy, False);
ignore_x11_error_p = True;
/************************************************************************
Main loop
************************************************************************/
while (1)
{
Bool force_blank_p = False;
Bool force_lock_p = False;
Atom blank_mode = 0;
char blank_mode_arg[20] = { 0 };
/* Wait until an event comes in, or a timeout. */
{
int xfd = ConnectionNumber (dpy);
fd_set in_fds;
struct timeval tv;
time_t until;
switch (current_state) {
case UNBLANKED: until = active_at + blank_timeout; break;
case BLANKED: until = blanked_at + lock_timeout; break;
default: until = 0;
}
tv.tv_sec = 0;
tv.tv_usec = 0;
if (until >= now)
tv.tv_sec = until - now;
if (verbose_p > 3)
{
if (!tv.tv_sec)
fprintf (stderr, "%s: block until input\n", blurb());
else
{
struct tm tm;
time_t t = now + tv.tv_sec;
localtime_r (&t, &tm);
fprintf (stderr,
"%s: block for %ld sec until %02d:%02d:%02d\n",
blurb(), tv.tv_sec, tm.tm_hour, tm.tm_min, tm.tm_sec);
}
}
FD_ZERO (&in_fds);
FD_SET (xfd, &in_fds);
select (xfd + 1, &in_fds, NULL, NULL, (tv.tv_sec ? &tv : NULL));
}
now = time ((time_t *) 0);
/********************************************************************
Signal handlers
********************************************************************/
/* If a signal handler fired, it set a flag, and that caused select()
to return. Now that we are back on the program stack, handle
those signals. */
/* SIGHUP is the same as "xscreensaver-command -restart". */
if (sighup_received)
{
sighup_received = 0;
if (current_state == LOCKED)
{
fprintf (stderr,
"%s: SIGHUP received while locked: ignoring\n",
blurb());
}
else
{
fprintf (stderr, "%s: SIGHUP received: restarting\n", blurb());
restart_process(); /* Does not return */
fprintf (stderr, "%s: SIGHUP RESTART FAILED!\n", blurb());
}
}
/* Upon SIGTERM, SIGINT or SIGQUIT we must kill our subprocesses
before exiting.
*/
if (sigterm_received)
{
int sig = sigterm_received; /* Same handler for all 3 signals */
const char *sn = (sig == SIGINT ? "SIGINT" :
sig == SIGQUIT ? "SIGQUIT" : "SIGTERM");
sigterm_received = 0;
fprintf (stderr, "%s: %s received%s: exiting\n", blurb(), sn,
(current_state == LOCKED ? " while locked" : ""));
/* Rather than calling saver_exit(), set our SIGTERM handler back to
the default and re-signal it so that this process actually dies
with a signal. */
signal (sig, SIG_DFL);
kill_all_subprocs();
kill (getpid(), sig);
abort();
}
/* SIGCHLD is fired any time one of our subprocesses dies.
When "xscreensaver-auth" dies, it analyzes its exit code.
*/
if (sigchld_received)
authenticated_p = handle_sigchld (dpy, current_state != UNBLANKED);
/* Now process any outstanding X11 events on the queue: user activity
from XInput, and ClientMessages from xscreensaver-command.
*/
while (XPending (dpy))
{
XEvent xev;
XNextEvent (dpy, &xev);
now = time ((time_t *) 0);
/****************************************************************
Client Messages
Both xscreensaver and xscreensaver-gfx handle these; some are
handled exclusively by one program or another, and some of them
(select, next, prev) are handled by xscreensaver only if
xscreensaver-gfx is not already running.
****************************************************************/
switch (xev.xany.type) {
case ClientMessage:
{
Atom msg = xev.xclient.data.l[0];
/* Re-load the .xscreensaver file before processing the results
of any ClientMessage, in case they just changed the timeouts.
*/
last_checked_init_file = 0;
if (! (xev.xclient.message_type == XA_SCREENSAVER &&
xev.xclient.format == 32 &&
xev.xclient.data.l[0]))
{
goto BAD_CM;
}
else if (msg == XA_ACTIVATE ||
msg == XA_SELECT ||
msg == XA_DEMO ||
msg == XA_NEXT ||
msg == XA_PREV)
{
/* The others are the same as -activate except that they
cause some extra args to be added to the xscreensaver-gfx
command line.
*/
if (msg != XA_ACTIVATE)
blank_mode = msg;
if (msg == XA_SELECT || msg == XA_DEMO)
{ /* see remote.c */
unsigned long n = xev.xclient.data.l[1];
if (n == 5000) n = xev.xclient.data.l[2];
sprintf (blank_mode_arg, "%lu", n);
}
if (msg == XA_DEMO) ignore_motion_p = True;
if (current_state == UNBLANKED)
{
force_blank_p = True;
ignore_activity_before = now + 2;
clientmessage_response (dpy, &xev, True, "blanking");
}
else if (msg == XA_SELECT ||
msg == XA_NEXT ||
msg == XA_PREV)
{
/* When active, these are handled by xscreensaver-gfx
instead of xscreensaver, so silently ignore them,
and allow xscreensaver-gfx to reply instead. */
}
else
clientmessage_response (dpy, &xev, False,
"already active");
}
else if (msg == XA_CYCLE)
{
if (current_state == UNBLANKED)
/* Only allowed when screen already blanked */
clientmessage_response (dpy, &xev, False, "not blanked");
/* else xscreensaver-gfx will respond to this. */
}
else if (msg == XA_DEACTIVATE)
{
if (current_state == UNBLANKED)
{
clientmessage_response (dpy, &xev, True,
"already inactive, resetting activity time");
active_at = now;
ignore_activity_before = now;
}
else
{
/* This behaves just like user input: if state is
LOCKED, it will advance to AUTH. */
active_at = now;
ignore_activity_before = now;
clientmessage_response (dpy, &xev, True, "deactivating");
}
/* DEACTIVATE while inactive also needs to reset the
server's DPMS time, but doing that here would mean
linking with additional libraries, doing additional X
protocol, and also some finicky error handling, since
the DPMS extension is a pain in the ass. So instead,
I made xscreensaver-command:reset_dpms_timer() do that
instead. This somewhat breaks the abstraction of
ClientMessage handling, but it's more robust. */
}
else if (msg == XA_LOCK)
{
if (locking_disabled_p)
clientmessage_response (dpy, &xev, False,
"locking disabled");
else if (current_state == UNBLANKED ||
current_state == BLANKED)
{
force_lock_p = True;
ignore_activity_before = now + 2;
clientmessage_response (dpy, &xev, True, "locking");
}
else
clientmessage_response (dpy, &xev, False,
"already locked");
}
else if (msg == XA_SUSPEND)
{
force_blank_p = True;
if (lock_p) force_lock_p = True;
ignore_activity_before = now + 2;
blank_mode = msg;
clientmessage_response (dpy, &xev, True, "suspending");
}
else if (msg == XA_EXIT)
{
if (current_state == UNBLANKED ||
current_state == BLANKED)
{
clientmessage_response (dpy, &xev, True, "exiting");
XSync (dpy, False);
saver_exit (0);
}
else
clientmessage_response (dpy, &xev, False,
"screen is locked");
}
else if (msg == XA_RESTART)
{
if (current_state == UNBLANKED ||
current_state == BLANKED)
{
clientmessage_response (dpy, &xev, True, "restarting");
XSync (dpy, False);
restart_process(); /* Does not return */
fprintf (stderr, "%s: RESTART FAILED!\n", blurb());
}
else
clientmessage_response (dpy, &xev, False,
"screen is locked");
}
else
{
BAD_CM:
if (verbose_p)
{
Atom type;
char *tstr, *name;
Bool op = print_x11_error_p;
print_x11_error_p = False; /* Ignore BadAtom */
type = xev.xclient.message_type;
tstr = type ? XGetAtomName (dpy, type) : 0;
name = msg ? XGetAtomName (dpy, msg) : 0;
fprintf (stderr,
"%s: unrecognized ClientMessage %s %s\n",
blurb(),
(tstr ? tstr : "???"),
(name ? name : "???"));
if (tstr) XFree (tstr);
if (name) XFree (name);
print_x11_error_p = op;
}
}
continue;
}
/****************************************************************
Normal X11 keyboard and mouse events
****************************************************************/
/* XInput2 "raw" events bypass X11 grabs, but grabs take priority.
If this process has the keyboard and mouse grabbed, it receives
the following events:
- X11 KeyPress, KeyRelease
- X11 ButtonPress, ButtonRelease
- X11 MotionNotify
- XInput XI_RawButtonPress, XI_RawButtonRelease
- XInput XI_RawMotion
Note that button and motion events are doubly reported, but
keyboard events are not.
If this process does *not* have the keyboard and mouse grabbed,
it receives the following events, regardless of the window in
which they occur:
- XInput XI_RawKeyPress, XI_RawKeyRelease
- XInput XI_RawButtonPress, XI_RawButtonRelease
- XInput XI_RawMotion
But here's an irritating kink: though XInput2 generally allows
snooping of everything, it respects GrabModeSync. What this
means is that if some other process has the keyboard grabbed with
"Sync" instead of "Async", then this process will not see any of
the events until that process releases its grab, and then the
events come in late, all at once. Verify this by running:
test-xinput &
Note that keyboard and mouse events are detected.
test-grab --mouse --mouse-async --kbd-async
Same.
test-grab --mouse --mouse-sync --kbd-async
Keyboard events are detected.
No motion or button events until "test-grab" is killed.
test-grab --mouse --mouse-async --kbd-sync
Vice versa.
*/
case KeyPress:
case KeyRelease:
if (current_state != AUTH && /* logged by xscreensaver-auth */
(verbose_p > 1 ||
(verbose_p && now - active_at > 1)))
print_xinput_event (dpy, &xev, "");
active_at = now;
continue;
break;
case ButtonPress:
case ButtonRelease:
active_at = now;
if (verbose_p)
print_xinput_event (dpy, &xev, "");
continue;
break;
case MotionNotify:
/* Since we always get XI_RawMotion, but only get MotionNotify
when grabbed, we can just ignore MotionNotify and let the
XI_RawMotion clause handle hysteresis. */
if (verbose_p > 1)
print_xinput_event (dpy, &xev, "ignored");
continue;
break;
default:
break;
}
/****************************************************************
XInput keyboard and mouse events
****************************************************************/
if (xev.xcookie.type != GenericEvent ||
xev.xcookie.extension != xi_opcode)
continue; /* not an XInput event */
if (!xev.xcookie.data)
XGetEventData (dpy, &xev.xcookie);
if (!xev.xcookie.data)
continue; /* Bogus XInput event */
switch (xev.xcookie.evtype) {
case XI_RawKeyPress:
case XI_RawKeyRelease:
case XI_RawButtonPress:
case XI_RawButtonRelease:
case XI_RawTouchBegin:
case XI_RawTouchEnd:
case XI_RawTouchUpdate:
if (current_state != AUTH && /* logged by xscreensaver-auth */
(verbose_p > 1 ||
(verbose_p && now - active_at > 1)))
print_xinput_event (dpy, &xev, "");
active_at = now;
break;
case XI_RawMotion:
{
/* Mouse wheel scrolling sends Button4 and Button5 events as well
as motion, so we handled those above, in XI_RawButtonPress.
The raw_values in the motion event for a mouse wheel reflect
the position of the wheel sensor.
On a trackpad where two-finger-swipe is a scroll gesture, I
saw behavior identical to a mouse wheel -- it does not send
RawTouch events.
*/
/* Don't poll the mouse position more frequently than once
a second. The motion only counts as activity if it has
moved farther than N pixels per second.
*/
int secs = now - last_mouse.time;
if (secs >= 1)
{
Window root_ret, child_ret;
int root_x, root_y;
int win_x, win_y;
unsigned int mask;
int dist;
Bool ignored_p = False;
XQueryPointer (dpy, DefaultRootWindow (dpy),
&root_ret, &child_ret, &root_x, &root_y,
&win_x, &win_y, &mask);
dist = MAX (ABS (last_mouse.x - root_x),
ABS (last_mouse.y - root_y));
ignored_p = (ignore_motion_p || dist < pointer_hysteresis);
if (! ignored_p)
{
active_at = now;
last_mouse.time = now;
last_mouse.x = root_x;
last_mouse.y = root_y;
}
if (verbose_p > 1 ||
(verbose_p && now - active_at > 5))
print_xinput_event (dpy, &xev,
(ignored_p ? " ignored" : ""));
}
}
break;
default:
if (verbose_p)
print_xinput_event (dpy, &xev, "");
break;
}
XFreeEventData (dpy, &xev.xcookie);
}
/********************************************************************
Advancing the state machine
********************************************************************/
/* If it's time, see if the .xscreensaver file has changed, since that
might change the blank and lock timeouts.
*/
if (now >= last_checked_init_file + 60)
{
last_checked_init_file = now;
if (verbose_p)
fprintf(stderr,"%s: checking init file\n", blurb());
read_init_files (False);
}
/* Now that events have been processed, see if the state should change,
based on any events received and the current time.
*/
switch (current_state) {
case UNBLANKED:
if (!locking_disabled_p &&
(force_lock_p ||
(lock_p &&
now >= active_at + blank_timeout + lock_timeout)))
{
if (verbose_p)
fprintf (stderr, "%s: locking\n", blurb());
if (grab_keyboard_and_mouse (mouse_screen (dpy)))
{
current_state = LOCKED;
blanked_at = now;
authenticated_p = False;
store_saver_status (dpy, True, True, now);
}
else
fprintf (stderr, "%s: unable to grab -- locking aborted!\n",
blurb());
force_lock_p = False; /* Single shot */
}
else if (force_blank_p ||
now >= active_at + blank_timeout)
{
if (blanking_disabled_p && !force_blank_p)
{
if (verbose_p)
fprintf (stderr, "%s: not blanking: disabled\n", blurb());
}
else
{
if (verbose_p)
fprintf (stderr, "%s: blanking\n", blurb());
if (grab_keyboard_and_mouse (mouse_screen (dpy)))
{
current_state = BLANKED;
blanked_at = now;
store_saver_status (dpy, True, False, now);
}
else
fprintf (stderr, "%s: unable to grab -- blanking aborted!\n",
blurb());
}
}
if (current_state == BLANKED || current_state == LOCKED)
{
/* Grab succeeded and state changed: launch graphics. */
if (! saver_gfx_pid)
{
static Bool first_time_p = True;
char *av[20];
int ac = 0;
av[ac++] = SAVER_GFX_PROGRAM;
if (first_time_p) av[ac++] = "--init";
if (verbose_p) av[ac++] = "--verbose";
if (verbose_p > 1) av[ac++] = "--verbose";
if (verbose_p > 2) av[ac++] = "--verbose";
if (debug_p) av[ac++] = "--debug";
if (blank_mode == XA_NEXT)
av[ac++] = "--next";
else if (blank_mode == XA_PREV)
av[ac++] = "--prev";
else if (blank_mode == XA_SELECT)
av[ac++] = "--select";
else if (blank_mode == XA_DEMO)
av[ac++] = "--demo";
else if (blank_mode == XA_SUSPEND)
av[ac++] = "--emergency";
if (blank_mode == XA_SELECT || blank_mode == XA_DEMO)
av[ac++] = blank_mode_arg;
av[ac] = 0;
gfx_stopped_p = False;
saver_gfx_pid = fork_and_exec (dpy, ac, av);
respawn_thrashing_count = 0;
first_time_p = False;
}
}
break;
case BLANKED:
if (!locking_disabled_p &&
(force_lock_p ||
(lock_p &&
now >= blanked_at + lock_timeout)))
{
if (verbose_p)
fprintf (stderr, "%s: locking%s\n", blurb(),
(force_lock_p ? "" : " after timeout"));
current_state = LOCKED;
authenticated_p = False;
store_saver_status (dpy, True, True, now);
force_lock_p = False; /* Single shot */
}
else if (active_at >= now &&
active_at >= ignore_activity_before)
{
UNBLANK:
if (verbose_p)
fprintf (stderr, "%s: unblanking\n", blurb());
current_state = UNBLANKED;
ignore_motion_p = False;
store_saver_status (dpy, False, False, now);
if (saver_gfx_pid)
{
if (verbose_p)
fprintf (stderr,
"%s: pid %lu: killing " SAVER_GFX_PROGRAM "\n",
blurb(), (unsigned long) saver_gfx_pid);
kill (saver_gfx_pid, SIGTERM);
respawn_thrashing_count = 0;
if (gfx_stopped_p) /* SIGCONT to allow SIGTERM to proceed */
{
if (verbose_p)
fprintf (stderr, "%s: pid %lu: sending "
SAVER_GFX_PROGRAM " SIGCONT\n",
blurb(), (unsigned long) saver_gfx_pid);
gfx_stopped_p = False;
kill (-saver_gfx_pid, SIGCONT); /* send to process group */
}
}
ungrab_keyboard_and_mouse (dpy);
}
break;
case LOCKED:
if (active_at >= now &&
active_at >= ignore_activity_before)
{
char *av[10];
int ac = 0;
if (saver_gfx_pid)
{
/* To suspend or not suspend? If we don't suspend, then a
misbehaving or heavily-loaded screenhack might make it more
difficult to type in the password. Though that seems pretty
unlikely.
But if we do suspend, then attaching a new monitor while
the unlock dialog is up will cause a new desktop to be
visible, since "xscreensaver-gfx" is the process that
handles RANDR. You can't interact with that new desktop,
but you can see it, possibly including (depending on the
window manager) the names of file icons on the desktop, or
other things. */
# if 0
if (verbose_p)
fprintf (stderr, "%s: pid %lu: sending " SAVER_GFX_PROGRAM
" SIGSTOP\n", blurb(),
(unsigned long) saver_gfx_pid);
gfx_stopped_p = True;
kill (-saver_gfx_pid, SIGSTOP); /* send to process group */
# endif
}
if (verbose_p)
fprintf (stderr, "%s: authorizing\n", blurb());
current_state = AUTH;
/* We already hold the mouse grab, but try to re-grab it with
a different mouse pointer, so that the pointer shows up while
the auth dialog is raised. We can ignore failures here. */
grab_mouse (mouse_screen (dpy), auth_cursor);
av[ac++] = SAVER_AUTH_PROGRAM;
if (verbose_p) av[ac++] = "--verbose";
if (verbose_p > 1) av[ac++] = "--verbose";
if (verbose_p > 2) av[ac++] = "--verbose";
if (debug_p) av[ac++] = "--debug";
av[ac] = 0;
saver_auth_pid = fork_and_exec (dpy, ac, av);
}
break;
case AUTH:
if (saver_auth_pid)
{
/* xscreensaver-auth still running -- wait for it to exit. */
}
else if (authenticated_p)
{
/* xscreensaver-auth exited with "success" status */
if (verbose_p)
fprintf (stderr, "%s: unlocking\n", blurb());
authenticated_p = False;
goto UNBLANK;
}
else
{
/* xscreensaver-auth exited with non-success, or with signal. */
if (verbose_p)
fprintf (stderr, "%s: authorization failed\n", blurb());
current_state = LOCKED;
authenticated_p = False;
/* We already hold the mouse grab, but try to re-grab it with
a different mouse pointer, to hide the pointer again now that
the auth dialog is gone. We can ignore failures here. */
grab_mouse (mouse_screen (dpy), blank_cursor);
/* When the unlock dialog is dismissed, ignore any input for a
second to give the user time to take their hands off of the
keyboard and mouse, so that it doesn't pop up again
immediately. */
ignore_activity_before = now + 1;
if (gfx_stopped_p) /* SIGCONT to resume savers */
{
if (verbose_p)
fprintf (stderr, "%s: pid %lu: sending " SAVER_GFX_PROGRAM
" SIGCONT\n",
blurb(), (unsigned long) saver_gfx_pid);
gfx_stopped_p = False;
kill (-saver_gfx_pid, SIGCONT); /* send to process group */
}
}
break;
default:
/* abort(); */
break;
}
}
}
/* There is no good reason for this executable to be setuid, but in case
it is, turn that off.
*/
static const char *
disavow_privileges (void)
{
static char msg[255];
uid_t euid = geteuid();
gid_t egid = getegid();
uid_t uid = getuid();
gid_t gid = getgid();
if (uid == euid && gid == egid)
return 0;
/* Without setgroups(), the process will retain any supplementary groups
associated with the uid, e.g. the default groups of the "root" user.
But setgroups() can only be called by root, and returns EPERM for other
users even if the call would be a no-op. So ignore its error status.
*/
setgroups (1, &gid);
if (gid != egid && setgid (gid) != 0)
{
fprintf (stderr, "%s: setgid %d -> %d failed\n", blurb(), egid, gid);
exit (1);
}
if (uid != euid && setgid (gid) != 0)
{
fprintf (stderr, "%s: setuid %d -> %d failed\n", blurb(), euid, uid);
exit (1);
}
/* Return the message since this is before verbose_p is set or log opened. */
sprintf (msg, "setuid %d:%d -> %d:%d", euid, egid, uid, gid);
return msg;
}
int
main (int argc, char **argv)
{
Display *dpy = 0;
char *dpy_str = getenv ("DISPLAY");
char *logfile = 0;
Bool sync_p = False;
Bool cmdline_verbose_val = False, cmdline_verbose_p = False;
Bool cmdline_splash_val = False, cmdline_splash_p = False;
const char *s;
const char *pmsg;
int i;
progname = argv[0];
s = strrchr (progname, '/');
if (s) progname = s+1;
pmsg = disavow_privileges();
fclose (stdin);
fix_fds();
for (i = 1; i < argc; i++)
{
const char *oa = argv[i];
/* XScreenSaver predates the "--arg" convention. */
if (argv[i][0] == '-' && argv[i][1] == '-')
argv[i]++;
if (!strcmp (argv[i], "-debug"))
debug_p = True;
else if (!strcmp (argv[i], "-v") || !strcmp (argv[i], "-verbose"))
{
verbose_p++;
cmdline_verbose_p = True, cmdline_verbose_val = verbose_p;
}
else if (!strcmp (argv[i], "-vv"))
{
verbose_p += 2;
cmdline_verbose_p = True, cmdline_verbose_val = verbose_p;
}
else if (!strcmp (argv[i], "-vvv"))
{
verbose_p += 3;
cmdline_verbose_p = True, cmdline_verbose_val = verbose_p;
}
else if (!strcmp (argv[i], "-vvvv"))
{
verbose_p += 4;
cmdline_verbose_p = True, cmdline_verbose_val = verbose_p;
}
else if (!strcmp (argv[i], "-q") || !strcmp (argv[i], "-quiet"))
{
verbose_p = 0;
cmdline_verbose_p = True, cmdline_verbose_val = verbose_p;
}
else if (!strcmp (argv[i], "-splash"))
{
splash_p = True;
cmdline_splash_p = True, cmdline_splash_val = splash_p;
}
else if (!strcmp (argv[i], "-no-splash") ||
!strcmp (argv[i], "-nosplash"))
{
splash_p = False;
cmdline_splash_p = True, cmdline_splash_val = splash_p;
}
else if (!strcmp (argv[i], "-log"))
{
logfile = argv[++i];
if (!logfile) goto HELP;
if (! verbose_p) /* might already be -vv */
verbose_p = cmdline_verbose_p = cmdline_verbose_val = True;
}
else if (!strcmp (argv[i], "-ver") ||
!strcmp (argv[i], "-vers") ||
!strcmp (argv[i], "-version"))
{
fprintf (stderr, "%s\n", screensaver_id+4);
exit (1);
}
else if (!strcmp (argv[i], "-d") ||
!strcmp (argv[i], "-dpy") ||
!strcmp (argv[i], "-disp") ||
!strcmp (argv[i], "-display"))
{
dpy_str = argv[++i];
if (!dpy_str) goto HELP;
}
else if (!strcmp (argv[i], "-sync") ||
!strcmp (argv[i], "-synch") ||
!strcmp (argv[i], "-synchronize") ||
!strcmp (argv[i], "-synchronise"))
sync_p = True;
else if (!strcmp (argv[i], "-h") || !strcmp (argv[i], "-help"))
{
HELP:
print_banner();
fprintf (stderr,
"\t\thttps://www.jwz.org/xscreensaver/\n"
"\n"
"\tOptions:\n\n"
"\t\t--dpy host:display.screen\n"
"\t\t--verbose\n"
"\t\t--no-splash\n"
"\t\t--log logfile\n"
"\t\t--version\n"
"\n"
"\tRun 'xscreensaver-settings' to configure.\n"
"\n");
saver_exit (1);
}
else
{
fprintf (stderr, "\n%s: unknown option: %s\n\n", blurb(), oa);
goto HELP;
}
}
if (logfile)
{
int stdout_fd = 1;
int stderr_fd = 2;
int fd = open (logfile, O_WRONLY | O_APPEND | O_CREAT, 0666);
if (fd < 0)
{
char buf[255];
FAIL:
sprintf (buf, "%.100s: %.100s", blurb(), logfile);
perror (buf);
fflush (stderr);
fflush (stdout);
saver_exit (1);
}
fprintf (stderr, "%s: logging to file %s\n", blurb(), logfile);
if (dup2 (fd, stdout_fd) < 0) goto FAIL;
if (dup2 (fd, stderr_fd) < 0) goto FAIL;
fprintf (stderr, "\n\n"
"#####################################"
"#####################################\n"
"%s: logging to \"%s\"\n"
"#####################################"
"#####################################\n"
"\n",
blurb(), logfile);
if (!verbose_p)
verbose_p = True;
cmdline_verbose_val = verbose_p;
}
save_argv (argc, argv);
hack_environment();
print_banner();
read_init_files (True);
/* Command line overrides init file */
if (cmdline_verbose_p) verbose_p = cmdline_verbose_val;
if (cmdline_splash_p) splash_p = cmdline_splash_val;
if (verbose_p)
fprintf (stderr, "%s: running in process %lu\n", blurb(),
(unsigned long) getpid());
if (verbose_p && pmsg)
fprintf (stderr, "%s: %s\n", blurb(), pmsg);
if (! dpy_str)
{
dpy_str = ":0.0";
fprintf (stderr,
"%s: warning: $DISPLAY is not set: defaulting to \"%s\"\n",
blurb(), dpy_str);
}
/* Copy the -dpy arg to $DISPLAY for subprocesses. */
{
char *s = (char *) malloc (strlen(dpy_str) + 20);
sprintf (s, "DISPLAY=%s", dpy_str);
putenv (s);
/* free (s); */ /* some versions of putenv do not copy */
}
dpy = XOpenDisplay (dpy_str);
if (!dpy) saver_exit (1);
if (sync_p)
{
XSynchronize (dpy, True);
XSync (dpy, False);
}
XSetErrorHandler (error_handler);
main_loop (dpy);
saver_exit (0);
return (1);
}
|