├── .gitignore ├── .travis.yml ├── CHANGELOG ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── resources ├── circadian.conf.in └── circadian.service └── src └── main.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | **/*.rs.bk 3 | *~ 4 | #*# 5 | .idea -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | language: rust 3 | rust: 4 | - stable 5 | - beta 6 | - nightly 7 | os: 8 | - linux 9 | matrix: 10 | allow_failures: 11 | - rust: nightly 12 | branches: 13 | only: 14 | - "master" 15 | install: 16 | - curl https://static.rust-lang.org/rustup.sh | 17 | sh -s -- --prefix=$HOME/rust 18 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | v0.8.4 [2023-03-18] 2 | 3 | * Always use "C" locale (fixes 'w' parsing issues) 4 | 5 | v0.8.3 [2023-03-18] 6 | 7 | * Switch pulseaudio detection to pactl (pipewire-compatible) 8 | * Significantly more robust X11 idle detection 9 | * Add output verbosity setting 10 | 11 | v0.8.2 [2023-02-19] 12 | 13 | * Add pulseaudio audio detection 14 | 15 | v0.8.1 [2023-01-02] 16 | 17 | * [no changes] 18 | 19 | v0.8.0 (unreleased) 20 | 21 | * Add support for monitoring NFS status 22 | 23 | v0.7.0 [2022-01-08] 24 | 25 | * Add command-line option to test idle state 26 | * Fix 'w' idle detection on non-debian systems 27 | * Fix systemd service install location 28 | 29 | v0.6.0 [2017-11-25] 30 | 31 | * Support a minimum wake time before re-sleeping 32 | * Detect X idle time when no active X session 33 | 34 | v0.5.0 [2017-11-16] 35 | 36 | * Reschedule wake timer any time it is overdue. 37 | * Reschedule wake timer when waking from sleep. 38 | 39 | v0.4.0 [2017-11-16] 40 | 41 | * Reschedule wake time with RTC clock 42 | * Install to /usr/local/bin instead of /usr/bin 43 | * Install systemd service system-wide 44 | 45 | v0.3.0 [2017-11-15] 46 | 47 | * Initial release 48 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "ahash" 7 | version = "0.7.6" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" 10 | dependencies = [ 11 | "getrandom", 12 | "once_cell", 13 | "version_check", 14 | ] 15 | 16 | [[package]] 17 | name = "aho-corasick" 18 | version = "0.7.20" 19 | source = "registry+https://github.com/rust-lang/crates.io-index" 20 | checksum = "cc936419f96fa211c1b9166887b38e5e40b19958e5b895be7c1f93adec7071ac" 21 | dependencies = [ 22 | "memchr", 23 | ] 24 | 25 | [[package]] 26 | name = "autocfg" 27 | version = "1.1.0" 28 | source = "registry+https://github.com/rust-lang/crates.io-index" 29 | checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" 30 | 31 | [[package]] 32 | name = "bitflags" 33 | version = "1.3.2" 34 | source = "registry+https://github.com/rust-lang/crates.io-index" 35 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" 36 | 37 | [[package]] 38 | name = "cc" 39 | version = "1.0.79" 40 | source = "registry+https://github.com/rust-lang/crates.io-index" 41 | checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f" 42 | 43 | [[package]] 44 | name = "cfg-if" 45 | version = "1.0.0" 46 | source = "registry+https://github.com/rust-lang/crates.io-index" 47 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 48 | 49 | [[package]] 50 | name = "circadian" 51 | version = "0.8.4" 52 | dependencies = [ 53 | "clap", 54 | "glob", 55 | "nix", 56 | "regex", 57 | "rust-ini", 58 | "time", 59 | "users", 60 | ] 61 | 62 | [[package]] 63 | name = "clap" 64 | version = "4.1.10" 65 | source = "registry+https://github.com/rust-lang/crates.io-index" 66 | checksum = "ce38afc168d8665cfc75c7b1dd9672e50716a137f433f070991619744a67342a" 67 | dependencies = [ 68 | "bitflags", 69 | "clap_derive", 70 | "clap_lex", 71 | "is-terminal", 72 | "once_cell", 73 | "strsim", 74 | "termcolor", 75 | ] 76 | 77 | [[package]] 78 | name = "clap_derive" 79 | version = "4.1.9" 80 | source = "registry+https://github.com/rust-lang/crates.io-index" 81 | checksum = "fddf67631444a3a3e3e5ac51c36a5e01335302de677bd78759eaa90ab1f46644" 82 | dependencies = [ 83 | "heck", 84 | "proc-macro-error", 85 | "proc-macro2", 86 | "quote", 87 | "syn", 88 | ] 89 | 90 | [[package]] 91 | name = "clap_lex" 92 | version = "0.3.3" 93 | source = "registry+https://github.com/rust-lang/crates.io-index" 94 | checksum = "033f6b7a4acb1f358c742aaca805c939ee73b4c6209ae4318ec7aca81c42e646" 95 | dependencies = [ 96 | "os_str_bytes", 97 | ] 98 | 99 | [[package]] 100 | name = "dlv-list" 101 | version = "0.3.0" 102 | source = "registry+https://github.com/rust-lang/crates.io-index" 103 | checksum = "0688c2a7f92e427f44895cd63841bff7b29f8d7a1648b9e7e07a4a365b2e1257" 104 | 105 | [[package]] 106 | name = "errno" 107 | version = "0.2.8" 108 | source = "registry+https://github.com/rust-lang/crates.io-index" 109 | checksum = "f639046355ee4f37944e44f60642c6f3a7efa3cf6b78c78a0d989a8ce6c396a1" 110 | dependencies = [ 111 | "errno-dragonfly", 112 | "libc", 113 | "winapi", 114 | ] 115 | 116 | [[package]] 117 | name = "errno-dragonfly" 118 | version = "0.1.2" 119 | source = "registry+https://github.com/rust-lang/crates.io-index" 120 | checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf" 121 | dependencies = [ 122 | "cc", 123 | "libc", 124 | ] 125 | 126 | [[package]] 127 | name = "getrandom" 128 | version = "0.2.8" 129 | source = "registry+https://github.com/rust-lang/crates.io-index" 130 | checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31" 131 | dependencies = [ 132 | "cfg-if", 133 | "libc", 134 | "wasi", 135 | ] 136 | 137 | [[package]] 138 | name = "glob" 139 | version = "0.3.1" 140 | source = "registry+https://github.com/rust-lang/crates.io-index" 141 | checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" 142 | 143 | [[package]] 144 | name = "hashbrown" 145 | version = "0.12.3" 146 | source = "registry+https://github.com/rust-lang/crates.io-index" 147 | checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" 148 | dependencies = [ 149 | "ahash", 150 | ] 151 | 152 | [[package]] 153 | name = "heck" 154 | version = "0.4.1" 155 | source = "registry+https://github.com/rust-lang/crates.io-index" 156 | checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" 157 | 158 | [[package]] 159 | name = "hermit-abi" 160 | version = "0.3.1" 161 | source = "registry+https://github.com/rust-lang/crates.io-index" 162 | checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286" 163 | 164 | [[package]] 165 | name = "io-lifetimes" 166 | version = "1.0.7" 167 | source = "registry+https://github.com/rust-lang/crates.io-index" 168 | checksum = "76e86b86ae312accbf05ade23ce76b625e0e47a255712b7414037385a1c05380" 169 | dependencies = [ 170 | "hermit-abi", 171 | "libc", 172 | "windows-sys", 173 | ] 174 | 175 | [[package]] 176 | name = "is-terminal" 177 | version = "0.4.4" 178 | source = "registry+https://github.com/rust-lang/crates.io-index" 179 | checksum = "21b6b32576413a8e69b90e952e4a026476040d81017b80445deda5f2d3921857" 180 | dependencies = [ 181 | "hermit-abi", 182 | "io-lifetimes", 183 | "rustix", 184 | "windows-sys", 185 | ] 186 | 187 | [[package]] 188 | name = "libc" 189 | version = "0.2.139" 190 | source = "registry+https://github.com/rust-lang/crates.io-index" 191 | checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79" 192 | 193 | [[package]] 194 | name = "linux-raw-sys" 195 | version = "0.1.4" 196 | source = "registry+https://github.com/rust-lang/crates.io-index" 197 | checksum = "f051f77a7c8e6957c0696eac88f26b0117e54f52d3fc682ab19397a8812846a4" 198 | 199 | [[package]] 200 | name = "log" 201 | version = "0.4.17" 202 | source = "registry+https://github.com/rust-lang/crates.io-index" 203 | checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" 204 | dependencies = [ 205 | "cfg-if", 206 | ] 207 | 208 | [[package]] 209 | name = "memchr" 210 | version = "2.5.0" 211 | source = "registry+https://github.com/rust-lang/crates.io-index" 212 | checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" 213 | 214 | [[package]] 215 | name = "memoffset" 216 | version = "0.7.1" 217 | source = "registry+https://github.com/rust-lang/crates.io-index" 218 | checksum = "5de893c32cde5f383baa4c04c5d6dbdd735cfd4a794b0debdb2bb1b421da5ff4" 219 | dependencies = [ 220 | "autocfg", 221 | ] 222 | 223 | [[package]] 224 | name = "nix" 225 | version = "0.26.2" 226 | source = "registry+https://github.com/rust-lang/crates.io-index" 227 | checksum = "bfdda3d196821d6af13126e40375cdf7da646a96114af134d5f417a9a1dc8e1a" 228 | dependencies = [ 229 | "bitflags", 230 | "cfg-if", 231 | "libc", 232 | "memoffset", 233 | "pin-utils", 234 | "static_assertions", 235 | ] 236 | 237 | [[package]] 238 | name = "num_threads" 239 | version = "0.1.6" 240 | source = "registry+https://github.com/rust-lang/crates.io-index" 241 | checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44" 242 | dependencies = [ 243 | "libc", 244 | ] 245 | 246 | [[package]] 247 | name = "once_cell" 248 | version = "1.17.1" 249 | source = "registry+https://github.com/rust-lang/crates.io-index" 250 | checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3" 251 | 252 | [[package]] 253 | name = "ordered-multimap" 254 | version = "0.4.3" 255 | source = "registry+https://github.com/rust-lang/crates.io-index" 256 | checksum = "ccd746e37177e1711c20dd619a1620f34f5c8b569c53590a72dedd5344d8924a" 257 | dependencies = [ 258 | "dlv-list", 259 | "hashbrown", 260 | ] 261 | 262 | [[package]] 263 | name = "os_str_bytes" 264 | version = "6.4.1" 265 | source = "registry+https://github.com/rust-lang/crates.io-index" 266 | checksum = "9b7820b9daea5457c9f21c69448905d723fbd21136ccf521748f23fd49e723ee" 267 | 268 | [[package]] 269 | name = "pin-utils" 270 | version = "0.1.0" 271 | source = "registry+https://github.com/rust-lang/crates.io-index" 272 | checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" 273 | 274 | [[package]] 275 | name = "proc-macro-error" 276 | version = "1.0.4" 277 | source = "registry+https://github.com/rust-lang/crates.io-index" 278 | checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" 279 | dependencies = [ 280 | "proc-macro-error-attr", 281 | "proc-macro2", 282 | "quote", 283 | "syn", 284 | "version_check", 285 | ] 286 | 287 | [[package]] 288 | name = "proc-macro-error-attr" 289 | version = "1.0.4" 290 | source = "registry+https://github.com/rust-lang/crates.io-index" 291 | checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" 292 | dependencies = [ 293 | "proc-macro2", 294 | "quote", 295 | "version_check", 296 | ] 297 | 298 | [[package]] 299 | name = "proc-macro2" 300 | version = "1.0.52" 301 | source = "registry+https://github.com/rust-lang/crates.io-index" 302 | checksum = "1d0e1ae9e836cc3beddd63db0df682593d7e2d3d891ae8c9083d2113e1744224" 303 | dependencies = [ 304 | "unicode-ident", 305 | ] 306 | 307 | [[package]] 308 | name = "quote" 309 | version = "1.0.26" 310 | source = "registry+https://github.com/rust-lang/crates.io-index" 311 | checksum = "4424af4bf778aae2051a77b60283332f386554255d722233d09fbfc7e30da2fc" 312 | dependencies = [ 313 | "proc-macro2", 314 | ] 315 | 316 | [[package]] 317 | name = "regex" 318 | version = "1.7.1" 319 | source = "registry+https://github.com/rust-lang/crates.io-index" 320 | checksum = "48aaa5748ba571fb95cd2c85c09f629215d3a6ece942baa100950af03a34f733" 321 | dependencies = [ 322 | "aho-corasick", 323 | "memchr", 324 | "regex-syntax", 325 | ] 326 | 327 | [[package]] 328 | name = "regex-syntax" 329 | version = "0.6.28" 330 | source = "registry+https://github.com/rust-lang/crates.io-index" 331 | checksum = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848" 332 | 333 | [[package]] 334 | name = "rust-ini" 335 | version = "0.18.0" 336 | source = "registry+https://github.com/rust-lang/crates.io-index" 337 | checksum = "f6d5f2436026b4f6e79dc829837d467cc7e9a55ee40e750d716713540715a2df" 338 | dependencies = [ 339 | "cfg-if", 340 | "ordered-multimap", 341 | ] 342 | 343 | [[package]] 344 | name = "rustix" 345 | version = "0.36.9" 346 | source = "registry+https://github.com/rust-lang/crates.io-index" 347 | checksum = "fd5c6ff11fecd55b40746d1995a02f2eb375bf8c00d192d521ee09f42bef37bc" 348 | dependencies = [ 349 | "bitflags", 350 | "errno", 351 | "io-lifetimes", 352 | "libc", 353 | "linux-raw-sys", 354 | "windows-sys", 355 | ] 356 | 357 | [[package]] 358 | name = "serde" 359 | version = "1.0.157" 360 | source = "registry+https://github.com/rust-lang/crates.io-index" 361 | checksum = "707de5fcf5df2b5788fca98dd7eab490bc2fd9b7ef1404defc462833b83f25ca" 362 | 363 | [[package]] 364 | name = "static_assertions" 365 | version = "1.1.0" 366 | source = "registry+https://github.com/rust-lang/crates.io-index" 367 | checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" 368 | 369 | [[package]] 370 | name = "strsim" 371 | version = "0.10.0" 372 | source = "registry+https://github.com/rust-lang/crates.io-index" 373 | checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" 374 | 375 | [[package]] 376 | name = "syn" 377 | version = "1.0.109" 378 | source = "registry+https://github.com/rust-lang/crates.io-index" 379 | checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" 380 | dependencies = [ 381 | "proc-macro2", 382 | "quote", 383 | "unicode-ident", 384 | ] 385 | 386 | [[package]] 387 | name = "termcolor" 388 | version = "1.1.3" 389 | source = "registry+https://github.com/rust-lang/crates.io-index" 390 | checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" 391 | dependencies = [ 392 | "winapi-util", 393 | ] 394 | 395 | [[package]] 396 | name = "time" 397 | version = "0.3.20" 398 | source = "registry+https://github.com/rust-lang/crates.io-index" 399 | checksum = "cd0cbfecb4d19b5ea75bb31ad904eb5b9fa13f21079c3b92017ebdf4999a5890" 400 | dependencies = [ 401 | "libc", 402 | "num_threads", 403 | "serde", 404 | "time-core", 405 | "time-macros", 406 | ] 407 | 408 | [[package]] 409 | name = "time-core" 410 | version = "0.1.0" 411 | source = "registry+https://github.com/rust-lang/crates.io-index" 412 | checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd" 413 | 414 | [[package]] 415 | name = "time-macros" 416 | version = "0.2.8" 417 | source = "registry+https://github.com/rust-lang/crates.io-index" 418 | checksum = "fd80a657e71da814b8e5d60d3374fc6d35045062245d80224748ae522dd76f36" 419 | dependencies = [ 420 | "time-core", 421 | ] 422 | 423 | [[package]] 424 | name = "unicode-ident" 425 | version = "1.0.8" 426 | source = "registry+https://github.com/rust-lang/crates.io-index" 427 | checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4" 428 | 429 | [[package]] 430 | name = "users" 431 | version = "0.11.0" 432 | source = "registry+https://github.com/rust-lang/crates.io-index" 433 | checksum = "24cc0f6d6f267b73e5a2cadf007ba8f9bc39c6a6f9666f8cf25ea809a153b032" 434 | dependencies = [ 435 | "libc", 436 | "log", 437 | ] 438 | 439 | [[package]] 440 | name = "version_check" 441 | version = "0.9.4" 442 | source = "registry+https://github.com/rust-lang/crates.io-index" 443 | checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" 444 | 445 | [[package]] 446 | name = "wasi" 447 | version = "0.11.0+wasi-snapshot-preview1" 448 | source = "registry+https://github.com/rust-lang/crates.io-index" 449 | checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" 450 | 451 | [[package]] 452 | name = "winapi" 453 | version = "0.3.9" 454 | source = "registry+https://github.com/rust-lang/crates.io-index" 455 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 456 | dependencies = [ 457 | "winapi-i686-pc-windows-gnu", 458 | "winapi-x86_64-pc-windows-gnu", 459 | ] 460 | 461 | [[package]] 462 | name = "winapi-i686-pc-windows-gnu" 463 | version = "0.4.0" 464 | source = "registry+https://github.com/rust-lang/crates.io-index" 465 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 466 | 467 | [[package]] 468 | name = "winapi-util" 469 | version = "0.1.5" 470 | source = "registry+https://github.com/rust-lang/crates.io-index" 471 | checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" 472 | dependencies = [ 473 | "winapi", 474 | ] 475 | 476 | [[package]] 477 | name = "winapi-x86_64-pc-windows-gnu" 478 | version = "0.4.0" 479 | source = "registry+https://github.com/rust-lang/crates.io-index" 480 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 481 | 482 | [[package]] 483 | name = "windows-sys" 484 | version = "0.45.0" 485 | source = "registry+https://github.com/rust-lang/crates.io-index" 486 | checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" 487 | dependencies = [ 488 | "windows-targets", 489 | ] 490 | 491 | [[package]] 492 | name = "windows-targets" 493 | version = "0.42.2" 494 | source = "registry+https://github.com/rust-lang/crates.io-index" 495 | checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" 496 | dependencies = [ 497 | "windows_aarch64_gnullvm", 498 | "windows_aarch64_msvc", 499 | "windows_i686_gnu", 500 | "windows_i686_msvc", 501 | "windows_x86_64_gnu", 502 | "windows_x86_64_gnullvm", 503 | "windows_x86_64_msvc", 504 | ] 505 | 506 | [[package]] 507 | name = "windows_aarch64_gnullvm" 508 | version = "0.42.2" 509 | source = "registry+https://github.com/rust-lang/crates.io-index" 510 | checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" 511 | 512 | [[package]] 513 | name = "windows_aarch64_msvc" 514 | version = "0.42.2" 515 | source = "registry+https://github.com/rust-lang/crates.io-index" 516 | checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" 517 | 518 | [[package]] 519 | name = "windows_i686_gnu" 520 | version = "0.42.2" 521 | source = "registry+https://github.com/rust-lang/crates.io-index" 522 | checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" 523 | 524 | [[package]] 525 | name = "windows_i686_msvc" 526 | version = "0.42.2" 527 | source = "registry+https://github.com/rust-lang/crates.io-index" 528 | checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" 529 | 530 | [[package]] 531 | name = "windows_x86_64_gnu" 532 | version = "0.42.2" 533 | source = "registry+https://github.com/rust-lang/crates.io-index" 534 | checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" 535 | 536 | [[package]] 537 | name = "windows_x86_64_gnullvm" 538 | version = "0.42.2" 539 | source = "registry+https://github.com/rust-lang/crates.io-index" 540 | checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" 541 | 542 | [[package]] 543 | name = "windows_x86_64_msvc" 544 | version = "0.42.2" 545 | source = "registry+https://github.com/rust-lang/crates.io-index" 546 | checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" 547 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "circadian" 3 | version = "0.8.4" 4 | authors = ["Trevor Bentley "] 5 | description = "Linux auto-suspend/wake power management daemon" 6 | keywords = ["linux", "power", "suspend", "daemon", "service"] 7 | categories = [] 8 | homepage = "https://github.com/mrmekon/circadian" 9 | repository = "https://github.com/mrmekon/circadian" 10 | documentation = "https://github.com/mrmekon/circadian" 11 | license = "GPL-3.0" 12 | 13 | [package.metadata.deb] 14 | maintainer = "Trevor Bentley " 15 | copyright = "Copyright 2017 Trevor Bentley" 16 | license-file = ["LICENSE"] 17 | extended-description = """\ 18 | Circadian is a power management daemon for automatically suspending machines \ 19 | when they are idle, and optionally waking them back up at set times.""" 20 | depends = "$auto, systemd" 21 | revision = "1" 22 | section = "admin" 23 | priority = "optional" 24 | assets = [ 25 | ["target/release/circadian", "usr/bin/", "755"], 26 | ["resources/circadian.conf.in", "etc/circadian.conf", "644"], 27 | ["resources/circadian.service", "usr/lib/systemd/system/", "644"], 28 | ] 29 | 30 | [package.metadata.release] 31 | sign-commit = false 32 | pre-release-commit-message = "Release {{version}}" 33 | tag-message = "Release {{version}}" 34 | 35 | 36 | [profile.release] 37 | lto = true 38 | 39 | [dependencies] 40 | regex = "1.7.1" 41 | glob = "0.3.1" 42 | rust-ini = "0.18.0" 43 | clap = { version = "4.1.10", features = ["derive"] } 44 | time = { version = "0.3.35", features = ["macros", "parsing", "local-offset"] } 45 | nix = "0.26.2" 46 | users = "0.11.0" 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Circadian 2 | 3 | ## 4 | ### Suspend-On-Idle Daemon for GNU/Linux Power Management 5 | ## 6 | 7 | Circadian is a background daemon/service for triggering suspend/sleep/hibernate automatically when a computer is idle. 8 | 9 | It is primarily for stationary devices with permanent power (i.e. desktops, servers, media centers). 10 | 11 | Circadian uses a suite of 'idle heuristics' to determine when a system is idle. These include: 12 | * User activity in X11 (keyboard, mouse, full-screen playback) 13 | * User activity in terminals (typing in PTY/SSH session) 14 | * Open SSH connections 15 | * Open SMB/Samba connections 16 | * Open NFS connections 17 | * Active audio playback 18 | * CPU usage below specified threshold 19 | * Blacklisted processes 20 | 21 | When all of its heuristics determine that your system has been idle for long enough, Circadian will execute a command. This is typically a simple power suspend, but it can be configured to any desired action. 22 | 23 | Circadian can also schedule an automatic daily wakeup. Simply set a wake time in its configuration file and it will wake up once every day at that time (if not already awake). This allows an easy way to keep a machine updated and backed up, even if it is seldom used. 24 | 25 | It can also execute a command when it detects that the system has woken up from sleep, regardless of why it woke up. 26 | 27 | Circadian exists because modern Linux distros already support suspend-on-idle, but it is apparently a very buggy and unreliable domain. After you've followed your distro's advice of poking a handful of conf files, tweaking a few XML hierarchies, writing a few scripts, wafting the smoke of burning sage across your keyboard, suspending gem stones from your machine, and whatever else may be recommended... perhaps try Circadian. 28 | 29 | ## Example use cases 30 | 31 | * Gaming rig with noisy fans? Auto-sleep when idle! 32 | * Storage/backup machine? Auto-wake, backup, and auto-sleep! 33 | * Seldom used server, but needs to be available? Wake-on-LAN, and auto-sleep when no SSH connections! 34 | * Wake up to your local music library? Auto-wake, play music, and auto-sleep! 35 | * Media center that you only use in evenings? Sleep all day, auto-wake when you get home! 36 | 37 | ## Status 38 | 39 | "Works for me". You try. You give feedback on GitHub, or to . 40 | 41 | ## Installing 42 | 43 | ### Debian x86-64 44 | 45 | * Download the latest [Circadian release](https://github.com/mrmekon/circadian/releases/) 46 | 47 | ``` 48 | $ sudo dpkg -i circadian_0.6.0-1_amd64.deb 49 | ``` 50 | 51 | If desired, install tooling to detect network (`netstat`), X11 (`xssstate` and`xprintidle`), audio activity (`pactl`): 52 | 53 | ``` 54 | $ sudo apt-get install suckless-tools xprintidle net-tools pulseaudio-utils 55 | ``` 56 | 57 | Edit `/etc/circadian.conf` to configure. The default is to suspend with systemd after 2 hours of idle. 58 | 59 | When you are happy with the config, continue: 60 | 61 | ``` 62 | $ sudo systemctl enable --now circadian 63 | ``` 64 | 65 | ### Arch Linux 66 | 67 | * Use your favorite AUR package manager 68 | 69 | ``` 70 | yay -S circadian 71 | ``` 72 | 73 | Consider installing the optional packages of `xprintidle` and `xssstate` for X11 based idle detection and `net-tools` for SSH detection. Both of this options are enabled by default. 74 | 75 | 76 | ### Any other system with systemd 77 | 78 | Install manually. It's easy. 79 | 80 | ``` 81 | $ git clone https://github.com/mrmekon/circadian.git 82 | $ cd circadian 83 | $ cargo build --release 84 | $ sudo cp target/release/circadian /usr/local/bin/ 85 | $ sudo cp resources/circadian.conf.in /etc/circadian.conf 86 | $ sudo cp resources/circadian.service /etc/systemd/system/ 87 | $ sudo systemctl enable circadian 88 | $ sudo systemctl start circadian 89 | ``` 90 | 91 | ### Non-systemd systems 92 | 93 | Follow systemd instructions, and port circadian.service to whatever format you want. 94 | 95 | ## Dependencies 96 | 97 | * Might need to install 98 | * xssstate 99 | * xprintidle 100 | * netstat 101 | * pactl 102 | * rustc + cargo (if building locally) 103 | * Should already have 104 | * grep 105 | * awk 106 | * w 107 | * id 108 | * uptime 109 | * pgrep 110 | * cat 111 | * sh 112 | 113 | Auto-wake requires kernel support for the real-time clock (RTC). You can check for the file `/sys/class/rtc/rtc0/wakealarm`. You probably have it. 114 | 115 | ## Usage 116 | 117 | * Should run as root, ideally from systemd. 118 | * Config is in: /etc/circadian.conf (it is documented) 119 | * `pkill -SIGUSR1 circadian` will dump info to syslog. Use that to see if it's working, or find out why it isn't sleeping. 120 | -------------------------------------------------------------------------------- /resources/circadian.conf.in: -------------------------------------------------------------------------------- 1 | ## 2 | ## Settings 3 | ## 4 | ## Options used to configure Circadian itself. 5 | ## 6 | [settings] 7 | # How verbose the output should be while running, between 0 and 4 8 | # inclusive. '0' is for normal usage, '4' is intended for active 9 | # debugging. 10 | # 11 | # Default: 0 12 | verbosity = 0 13 | 14 | ## 15 | ## Heuristics 16 | ## 17 | ## Options used to detect whether the system is idle. 18 | ## 19 | [heuristics] 20 | # Whether TTY input on *any* TTY blocks idle. This includes X terminals, 21 | # virtual terminals, SSH sessions, etc. Resets whenever a TTY determines 22 | # that it has input, which is typically keypresses. 23 | # 24 | # At least one of tty_input or x11_input must be 'yes'. 25 | # 26 | # Monitors the idle column of the 'w' command. 27 | # 28 | # Default: yes 29 | tty_input = yes 30 | 31 | # Whether X11 idle detection is used, the specifics of which are determined 32 | # by your particular combination of window/display manager. This is normally 33 | # any user input device (keyboard, mouse), but can additionally be reset 34 | # by certain programs. Typically, any program that prevents the screensaver 35 | # from displaying will also reset this. 36 | # 37 | # At least one of tty_input or x11_input must be 'yes'. 38 | # 39 | # Monitors xprintidle and xssstate 40 | # 41 | # Default: yes 42 | x11_input = yes 43 | 44 | # Whether active SSH connections block the system from being idle. Both 45 | # inbound and outbound connections will prevent the system from going idle 46 | # if this is 'yes'. 47 | # 48 | # Monitors netstat 49 | # 50 | # Default: yes 51 | ssh_block = yes 52 | 53 | # Whether active Samba connections block the system from being idle. Note 54 | # that GVfs sometimes makes local loopback connections to a local Samba 55 | # share, which will prevent idle. This is disabled by default because of 56 | # the aggressiveness of SMB browsing clients. 57 | # 58 | # Monitors netstat 59 | # 60 | # Default: no 61 | smb_block = no 62 | 63 | # Whether active NFS connections block the system from being idle. Both 64 | # inbound and outbound connections will prevent the system from going idle 65 | # if this is 'yes'. 66 | # 67 | # Monitors netstat 68 | # 69 | # Default: no 70 | nfs_block = no 71 | 72 | # Whether active audio playback blocks the system from being idle. 73 | # 74 | # Monitors /proc/asound 75 | # 76 | # Default: yes 77 | audio_block = yes 78 | 79 | # Max CPU load for the past minute to be considered idle. This is the 80 | # unscaled load, can go above 1.0 even on non-maxed multi-core systems. 81 | # Set to 999.0 or comment out to disable. 82 | # 83 | # Monitors uptime 84 | # 85 | # Default: 0.5 86 | max_cpu_load = 0.5 87 | 88 | # Specific processes that block the system from being considered idle if 89 | # they are running. Supply as a comma separated list. Basic regex is 90 | # permitted, and the format "^full-process-name$" is recommended. 91 | # 92 | # Monitors pgrep 93 | # 94 | # Example: 95 | # process_block = mplayer,vlc 96 | # 97 | # Default: some common file transfer utils 98 | process_block = ^dd$,^rsync$,^apt-get$,^dpkg$,^cp$,^mv$ 99 | 100 | [actions] 101 | # How long the system must be idle before the idle action is taken. 102 | # 103 | # Empty or 0 is disabled. 104 | # 105 | # NOTE: only the '*_input' heuristics need to be continuously idle without 106 | # interruption. The other heuristics only need to be true instantaneously 107 | # after idle_time has passed. (ex: with an idle_time of 1 hour, the mouse 108 | # must not move at all for 1 hour, but SSH connections can come and go 109 | # during that hour. The on_idle command will run the next time that _at least_ 110 | # 1 hour has gone by without mouse movement, and no SSH connections are 111 | # currently active.) 112 | # 113 | # This is also the minimum amount of time that Circadian must be awake before 114 | # it wll sleep (again). 115 | # 116 | # Suffix: 117 | # - seconds 118 | # m - minutes 119 | # h - hours 120 | # 121 | # Default: 120 minutes 122 | idle_time = 120m 123 | 124 | # Command to execute when the system is determined to have been idle for at 125 | # least idle_time. Typically a suspend or hibernate command. 126 | # 127 | # Common options: 128 | # * pm-suspend 129 | # * pm-hibernate 130 | # * pm-suspend-hybrid 131 | # * systemctl suspend 132 | # * systemctl hibernate 133 | # * dbus-send --system --print-reply --dest="org.freedesktop.UPower" \ 134 | # /org/freedesktop/UPower org.freedesktop.UPower.Suspend 135 | # 136 | # Default: pm-suspend 137 | on_idle = "systemctl suspend" 138 | 139 | # Time of day (in local timezone) to automatically wake the machine if it 140 | # is sleeping. Specify in 24-hour time format with a colon. Leave blank 141 | # or comment out for no wake time. 142 | # 143 | # This depends on the hardware RTC being enabled and supported by your kernel. 144 | # 145 | # Example: 146 | # auto_wake = 16:00 147 | # 148 | # Default: disabled 149 | auto_wake = 150 | 151 | # Command to execute after waking from a sleep. 152 | # 153 | # Default: 154 | on_wake = "" 155 | -------------------------------------------------------------------------------- /resources/circadian.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Circadian power management service 3 | 4 | [Service] 5 | Type=simple 6 | User=root 7 | ExecStart=/usr/local/bin/circadian 8 | Restart=on-failure 9 | 10 | [Install] 11 | WantedBy=multi-user.target 12 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 Trevor Bentley 3 | * 4 | * Author: Trevor Bentley 5 | * Contact: trevor@trevorbentley.com 6 | * Source: https://github.com/mrmekon/circadian 7 | * 8 | * This file is part of Circadian. 9 | * 10 | * Circadian is free software: you can redistribute it and/or modify 11 | * it under the terms of the GNU General Public License as published by 12 | * the Free Software Foundation, either version 3 of the License, or 13 | * (at your option) any later version. 14 | * 15 | * Circadian is distributed in the hope that it will be useful, 16 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | * GNU General Public License for more details. 19 | * 20 | * You should have received a copy of the GNU General Public License 21 | * along with Circadian. If not, see . 22 | */ 23 | extern crate regex; 24 | 25 | use std::collections::HashSet; 26 | use std::io::BufRead; 27 | use std::os::linux::fs::MetadataExt; 28 | use regex::Regex; 29 | 30 | extern crate glob; 31 | use glob::glob; 32 | 33 | extern crate clap; 34 | use clap::Parser; 35 | 36 | extern crate ini; 37 | use ini::Ini; 38 | 39 | extern crate nix; 40 | use nix::sys::signal; 41 | 42 | extern crate time; 43 | use time::macros::*; 44 | 45 | extern crate users; 46 | use users::get_user_by_name; 47 | 48 | use std::io::Write; 49 | use std::path::PathBuf; 50 | use std::process::Stdio; 51 | use std::process::Command; 52 | use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; 53 | 54 | use std::os::unix::process::CommandExt; 55 | 56 | pub static VERBOSITY: AtomicUsize = AtomicUsize::new(0); 57 | pub const MAX_VERBOSITY: usize = 4; 58 | #[allow(unused_macros)] 59 | macro_rules! println_vb1 { 60 | () => { if VERBOSITY.load(Ordering::SeqCst) > 0 { println!() } }; 61 | ($($arg:tt)*) => {{ if VERBOSITY.load(Ordering::SeqCst) > 0 { println!($($arg)*); } }}; 62 | } 63 | #[allow(unused_macros)] 64 | macro_rules! println_vb2 { 65 | () => { if VERBOSITY.load(Ordering::SeqCst) > 1 { println!() } }; 66 | ($($arg:tt)*) => {{ if VERBOSITY.load(Ordering::SeqCst) > 1 { println!($($arg)*); } }}; 67 | } 68 | #[allow(unused_macros)] 69 | macro_rules! println_vb3 { 70 | () => { if VERBOSITY.load(Ordering::SeqCst) > 2 { println!() } }; 71 | ($($arg:tt)*) => {{ if VERBOSITY.load(Ordering::SeqCst) > 2 { println!($($arg)*); } }}; 72 | } 73 | #[allow(unused_macros)] 74 | macro_rules! println_vb4 { 75 | () => { if VERBOSITY.load(Ordering::SeqCst) > 3 { println!() } }; 76 | ($($arg:tt)*) => {{ if VERBOSITY.load(Ordering::SeqCst) > 3 { println!($($arg)*); } }}; 77 | } 78 | 79 | pub struct CircadianError(String); 80 | 81 | impl std::fmt::Display for CircadianError { 82 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 83 | write!(f, "{}", self.0) 84 | } 85 | } 86 | impl std::fmt::Debug for CircadianError { 87 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 88 | write!(f, "{}", self.0) 89 | } 90 | } 91 | impl std::error::Error for CircadianError { 92 | fn description(&self) -> &str { 93 | self.0.as_str() 94 | } 95 | 96 | fn cause(&self) -> Option<&dyn std::error::Error> { 97 | None 98 | } 99 | } 100 | impl <'a> From<&'a str> for CircadianError { 101 | fn from(error: &str) -> Self { 102 | CircadianError(error.to_owned()) 103 | } 104 | } 105 | impl From for CircadianError { 106 | fn from(error: std::io::Error) -> Self { 107 | CircadianError(error.to_string().to_owned()) 108 | } 109 | } 110 | impl From for CircadianError { 111 | fn from(error: regex::Error) -> Self { 112 | CircadianError(error.to_string().to_owned()) 113 | } 114 | } 115 | impl From for CircadianError { 116 | fn from(error: std::num::ParseIntError) -> Self { 117 | CircadianError(error.to_string().to_owned()) 118 | } 119 | } 120 | impl From for CircadianError { 121 | fn from(error: std::string::FromUtf8Error) -> Self { 122 | CircadianError(error.to_string().to_owned()) 123 | } 124 | } 125 | impl From for CircadianError { 126 | fn from(error: glob::PatternError) -> Self { 127 | CircadianError(error.to_string().to_owned()) 128 | } 129 | } 130 | impl From for CircadianError { 131 | fn from(error: ini::Error) -> Self { 132 | CircadianError(error.to_string().to_owned()) 133 | } 134 | } 135 | impl From for CircadianError { 136 | fn from(error: nix::Error) -> Self { 137 | CircadianError(error.to_string().to_owned()) 138 | } 139 | } 140 | impl From for CircadianError { 141 | fn from(error: time::error::Parse) -> Self { 142 | CircadianError(error.to_string().to_owned()) 143 | } 144 | } 145 | impl From for CircadianError { 146 | fn from(error: time::error::ComponentRange) -> Self { 147 | CircadianError(error.to_string().to_owned()) 148 | } 149 | } 150 | 151 | type IdleResult = Result; 152 | type ThreshResult = Result; 153 | type ExistResult = Result; 154 | 155 | #[allow(dead_code)] 156 | enum NetConnection { 157 | SSH, 158 | SMB, 159 | NFS, 160 | } 161 | 162 | #[allow(dead_code)] 163 | enum CpuHistory { 164 | Min1, 165 | Min5, 166 | Min15 167 | } 168 | 169 | #[derive(Clone)] 170 | struct AutoWakeEpoch { 171 | epoch: i64, 172 | is_utc: bool, 173 | } 174 | 175 | #[derive(Debug)] 176 | struct IdleResponse { 177 | w_idle: IdleResult, 178 | w_enabled: bool, 179 | xssstate_idle: IdleResult, 180 | xssstate_enabled: bool, 181 | xprintidle_idle: IdleResult, 182 | xprintidle_enabled: bool, 183 | wake_remain: u32, 184 | tty_idle: u32, 185 | tty_enabled: bool, 186 | x11_idle: u32, 187 | x11_enabled: bool, 188 | min_idle: u32, 189 | idle_target: u64, 190 | idle_remain: u64, 191 | is_idle: bool, 192 | } 193 | impl std::fmt::Display for IdleResponse { 194 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 195 | let result_map = vec![ 196 | (self.w_idle.as_ref(), self.w_enabled, "w"), 197 | (self.xssstate_idle.as_ref(), self.xssstate_enabled, "xssstate"), 198 | (self.xprintidle_idle.as_ref(), self.xprintidle_enabled, "xprintidle"), 199 | ]; 200 | for (var,enabled,name) in result_map { 201 | let s = match var { 202 | Ok(x) => x.to_string(), 203 | Err(e) => e.to_string(), 204 | }; 205 | let enabled = match enabled { 206 | true => "*", 207 | _ => "", 208 | }; 209 | let name = format!("{}{}", name, enabled); 210 | let _ = write!(f, "{:<16}: {}\n", name, s); 211 | } 212 | let _ = write!(f, "{:<16}: {}\n", "Wake block", self.wake_remain); 213 | let int_map = vec![ 214 | (self.tty_idle, self.tty_enabled, "TTY (combined)"), 215 | (self.x11_idle, self.x11_enabled, "X11 (combined)"), 216 | ]; 217 | for (var,enabled,name) in int_map { 218 | let enabled = match enabled { 219 | true => "*", 220 | _ => "", 221 | }; 222 | let name = format!("{}{}", name, enabled); 223 | let _ = write!(f, "{:<16}: {}\n", name, var); 224 | } 225 | let _ = write!(f, "{:<16}: {}\n", "Idle (min)", self.min_idle); 226 | let _ = write!(f, "{:<16}: {}\n", "Idle target", self.idle_target); 227 | let _ = write!(f, "{:<16}: {}\n", "Until idle", self.idle_remain); 228 | let _ = write!(f, "{:<16}: {}\n", "IDLE?", self.is_idle); 229 | Ok(()) 230 | } 231 | } 232 | 233 | #[derive(Debug)] 234 | struct NonIdleResponse { 235 | cpu_load: ThreshResult, 236 | cpu_load_enabled: bool, 237 | ssh: ExistResult, 238 | ssh_enabled: bool, 239 | smb: ExistResult, 240 | smb_enabled: bool, 241 | nfs: ExistResult, 242 | nfs_enabled: bool, 243 | audio: ExistResult, 244 | audio_enabled: bool, 245 | procs: ExistResult, 246 | procs_enabled: bool, 247 | is_blocked: bool, 248 | } 249 | impl std::fmt::Display for NonIdleResponse { 250 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { 251 | let result_map = vec![ 252 | (self.cpu_load.as_ref(), self.cpu_load_enabled, "CPU load"), 253 | (self.ssh.as_ref(), self.ssh_enabled, "SSH"), 254 | (self.smb.as_ref(), self.smb_enabled, "SMB"), 255 | (self.nfs.as_ref(), self.nfs_enabled, "NFS"), 256 | (self.audio.as_ref(), self.audio_enabled, "Audio"), 257 | (self.procs.as_ref(), self.procs_enabled, "Processes"), 258 | ]; 259 | for (var,enabled,name) in result_map { 260 | let s = match var { 261 | Ok(x) => x.to_string(), 262 | Err(e) => e.to_string(), 263 | }; 264 | let enabled = match enabled { 265 | true => "*", 266 | _ => "", 267 | }; 268 | let name = format!("{}{}", name, enabled); 269 | let _ = write!(f, "{:<16}: {}\n", name, s); 270 | } 271 | let _ = write!(f, "{:<16}: {}\n", "BLOCKED?", self.is_blocked); 272 | Ok(()) 273 | } 274 | } 275 | 276 | static SIGUSR_SIGNALED: AtomicBool = AtomicBool::new(false); 277 | 278 | /// Set global flag when SIGUSR1 signal is received 279 | extern fn sigusr1_handler(_: i32) { 280 | SIGUSR_SIGNALED.store(true, Ordering::SeqCst); 281 | } 282 | 283 | /// Register SIGUSR1 signal handler 284 | fn register_sigusr1() -> Result { 285 | let sig_handler = signal::SigHandler::Handler(sigusr1_handler); 286 | let sig_action = signal::SigAction::new(sig_handler, 287 | signal::SaFlags::empty(), 288 | signal::SigSet::empty()); 289 | unsafe { 290 | Ok(signal::sigaction(signal::SIGUSR1, &sig_action)?) 291 | } 292 | } 293 | 294 | fn command_exists(cmd: &str) -> bool { 295 | match Command::new(cmd) 296 | .stdout(Stdio::null()) 297 | .stderr(Stdio::null()) 298 | .status() { 299 | Ok(_) => true, 300 | Err(_) => false, 301 | } 302 | } 303 | 304 | /// Parse idle time strings from 'w' command into seconds 305 | fn parse_w_time(time_str: &str) -> Result { 306 | let mut secs: u32 = 0; 307 | let mut mins: u32 = 0; 308 | let mut hours:u32 = 0; 309 | let re_sec = Regex::new(r"^\d+.\d+s$")?; 310 | let re_min = Regex::new(r"^\d+:\d+$")?; 311 | let re_hour = Regex::new(r"^\d+:\d+m$")?; 312 | if re_sec.is_match(time_str) { 313 | let time_str: &str = time_str.trim_matches('s'); 314 | let parts: Vec = time_str.split(".") 315 | .map(|s| str::parse::(s).unwrap_or(0)) 316 | .collect(); 317 | secs = *parts.get(0).unwrap_or(&0); 318 | } 319 | else if re_min.is_match(time_str) { 320 | let parts: Vec = time_str.split(":") 321 | .map(|s| str::parse::(s).unwrap_or(0)) 322 | .collect(); 323 | mins = *parts.get(0).unwrap_or(&0); 324 | secs = *parts.get(1).unwrap_or(&0); 325 | } 326 | else if re_hour.is_match(time_str) { 327 | let time_str: &str = time_str.trim_matches('m'); 328 | let parts: Vec = time_str.split(":") 329 | .map(|s| str::parse::(s).unwrap_or(0)) 330 | .collect(); 331 | hours = *parts.get(0).unwrap_or(&0); 332 | mins = *parts.get(1).unwrap_or(&0); 333 | } 334 | else { 335 | return Err(CircadianError("Invalid idle format".to_string())); 336 | } 337 | Ok((hours*60*60) + (mins*60) + secs) 338 | } 339 | 340 | // count number of fields in 'w' output 341 | // 342 | // This is a stupid requirement because some linux distros build w 343 | // with the 'FROM' field enabled by default and others with it 344 | // disabled. 'w' has a command-line option to *toggle* the field, but 345 | // no to forcibly enable/disable it. 346 | fn count_w_fields() -> Result { 347 | let w_stdout = Stdio::piped(); 348 | let s_stdout = Stdio::piped(); 349 | let mut w_output = Command::new("w") 350 | .arg("-us") 351 | .stdout(w_stdout).spawn()?; 352 | let _ = w_output.wait()?; 353 | let w_stdout = w_output.stdout 354 | .ok_or(CircadianError("w command has no output".into()))?; 355 | // print just the second row, the header 356 | let mut sed_output = Command::new("sed") 357 | .arg("-n") 358 | .arg("2p") 359 | .stdin(w_stdout) 360 | .stdout(s_stdout) 361 | .spawn()?; 362 | let _ = sed_output.wait()?; 363 | let s_stdout = sed_output.stdout 364 | .ok_or(CircadianError("w/sed command has no output".into()))?; 365 | let awk_output = Command::new("awk") 366 | .arg("{print NF}") 367 | .stdin(s_stdout) 368 | .output()?; 369 | let num_fields: usize = String::from_utf8(awk_output.stdout) 370 | .unwrap_or(String::new()) 371 | .trim() 372 | .parse::()?; 373 | Ok(num_fields) 374 | } 375 | 376 | // Returns tuple containing argument string to provide to `w` to have 377 | // the FROM field included, and the 0-indexed offset of the field. 378 | fn w_from_args() -> Result<(String, usize), CircadianError> { 379 | // Ask for a fake user to get just the header and check if the 380 | // FROM field is enabled. 381 | let w_output = Command::new("w") 382 | .arg("-us") 383 | .arg("CIRCADIAN_FAKEUSER") 384 | .output()?; 385 | let w_fields: Vec = w_output.stdout 386 | .lines() 387 | .nth(1) // second line is the header 388 | .ok_or(CircadianError("w command has no output".into()))?? 389 | .split_whitespace().map(|x| x.to_owned()).collect(); 390 | let from_header = String::from("FROM"); 391 | let (hargs, args) = match w_fields.contains(&from_header) { 392 | true => ("-hus".to_string(), "-us".to_string()), 393 | false => ("-husf".to_string(), "-usf".to_string()), 394 | }; 395 | 396 | // Do it again with FROM field on and find its index. 397 | let w_output = Command::new("w") 398 | .arg(&args) 399 | .arg("CIRCADIAN_FAKEUSER") 400 | .output()?; 401 | let w_fields: Vec = w_output.stdout 402 | .lines() 403 | .nth(1) 404 | .ok_or(CircadianError("w command has no output".into()))?? 405 | .split_whitespace().map(|x| x.to_owned()).collect(); 406 | let idx = w_fields.iter() 407 | .position(|x| x == &from_header) 408 | .ok_or(CircadianError("w command arguments invalid".into()))?; 409 | Ok((hargs, idx)) 410 | } 411 | 412 | fn xauthority_from_cmdline(display: &str) -> Result { 413 | // Look for PIDs of processes with a variety of X11-related names. 414 | let pgrep_out = Command::new("pgrep") 415 | .arg("(X11|Xorg|xinit|Xwayland|Xephyr)") 416 | .output()?; 417 | let pids: Vec = String::from_utf8(pgrep_out.stdout) 418 | .unwrap_or(String::new()) 419 | .split("\n") 420 | .map(|s| s.trim().to_owned()) 421 | .filter(|s| s.len() > 0) 422 | .collect(); 423 | let display = display.to_owned(); 424 | 425 | // Read the command-line arguments out of procfs for all of the 426 | // matching PIDs. 427 | for pid in &pids { 428 | let cmdline_path = PathBuf::from(format!("/proc/{}/cmdline", pid)); 429 | if !cmdline_path.exists() { 430 | continue; 431 | } 432 | let raw_args: String = String::from_utf8(std::fs::read(&cmdline_path)?)?; 433 | let split_args: Vec = raw_args.split("\0").map(|s| s.to_owned()).collect(); 434 | 435 | // Look for processes that have the display name (":0") as an 436 | // argument, and also have a "-auth" argument. The parameter 437 | // after "-auth" should be an xauth file. 438 | let auth_arg = String::from("-auth"); 439 | if split_args.contains(&auth_arg) && split_args.contains(&display) { 440 | // Grab the next argument after "-auth" 441 | let split_args: Vec = split_args.iter().rev().take_while(|s| *s != "-auth").map(|s| s.to_owned()).collect(); 442 | let auth_arg: &str = split_args.iter().map(|x| x.as_str()).rev().next().unwrap_or(""); 443 | let auth_path = PathBuf::from(auth_arg); 444 | // Ensure the file actually exists 445 | if auth_path.exists() { 446 | // return the first match 447 | println_vb4!(" - xauth from cmdline: {}", auth_arg); 448 | return Ok(auth_arg.to_string()); 449 | } 450 | } 451 | } 452 | 453 | Err(CircadianError("No auth file specified on command line.".into())) 454 | } 455 | 456 | fn xauthority_for_uid(uid: u32, display: &str) -> String { 457 | // Default to whatever is currently in the XAUTHORITY environment 458 | // variable, if anything. 459 | let default = std::env::var("XAUTHORITY").unwrap_or("".into()); 460 | 461 | // If root user, try to read the xauth file out of the 462 | // command-line arguments. This one takes highest priority, if it 463 | // exists. 464 | if uid == 0 { 465 | if let Ok(xauth) = xauthority_from_cmdline(display) { 466 | return xauth; 467 | } 468 | } 469 | 470 | // getent displays the row from /etc/passwd for a specific user 471 | let getent_stdout = Stdio::piped(); 472 | let mut getent_output = match Command::new("getent") 473 | .arg("passwd") 474 | .arg(uid.to_string()) 475 | .stdout(getent_stdout).spawn() { 476 | Ok(w) => w, 477 | _ => return default, 478 | }; 479 | let _ = match getent_output.wait() { 480 | Ok(_) => {}, 481 | _ => return default, 482 | }; 483 | let getent_stdout = match getent_output.stdout { 484 | Some(w) => w, 485 | _ => return default, 486 | }; 487 | 488 | // the 6th colon-separated field is the user's home directory 489 | let cut_output = match Command::new("cut") 490 | .arg("-d:") 491 | .arg("-f6") 492 | .stdin(getent_stdout) 493 | .output() { 494 | Ok(o) => o, 495 | _ => return default, 496 | }; 497 | 498 | // look for ~/.Xauthority for the specified user 499 | let homedir = String::from_utf8(cut_output.stdout) 500 | .unwrap_or(default.clone()) 501 | .trim().to_owned(); 502 | let mut homedir = PathBuf::from(homedir); 503 | homedir.push(".Xauthority"); 504 | 505 | // return the path if it exists, otherwise just use whatever the 506 | // current XAUTHORITY environment variable is set to. 507 | match homedir.exists() { 508 | true => homedir.to_str().unwrap_or(&default).to_owned(), 509 | _ => default, 510 | } 511 | } 512 | 513 | /// Call 'w' command and return minimum idle time 514 | fn idle_w() -> IdleResult { 515 | let num_fields = count_w_fields()?; 516 | let w_stdout = Stdio::piped(); 517 | let mut w_output = Command::new("w") 518 | .arg("-hus") 519 | .stdout(w_stdout).spawn()?; 520 | let _ = w_output.wait()?; 521 | let w_stdout = w_output.stdout 522 | .ok_or(CircadianError("w command has no output".into()))?; 523 | // idle field is the second to last 524 | let awk_output = Command::new("awk") 525 | .arg(format!("{{print ${}}}", num_fields - 1)) 526 | .stdin(w_stdout) 527 | .output()?; 528 | let idle_times: Vec = String::from_utf8(awk_output.stdout) 529 | .unwrap_or(String::new()) 530 | .split("\n") 531 | .filter(|t| t.len() > 0) 532 | .map(|t| parse_w_time(t)) 533 | .filter_map(|t| t.ok()) 534 | .collect(); 535 | Ok(idle_times.iter().cloned().fold(std::u32::MAX, std::cmp::min)) 536 | } 537 | 538 | /// Call idle command for each X display 539 | /// 540 | /// 'cmd' should be a unix command that, given args 'args', prints the idle 541 | /// time in milliseconds. It will be run with the DISPLAY env variable set 542 | /// and with the uid of the user that owns the DISPLAY, for every running 543 | /// X display. The minimum of all found idle times is returned. 544 | fn idle_fn(cmd: &str, args: Vec<&str>) -> IdleResult { 545 | let mut display_mins: Vec = Vec::::new(); 546 | let (w_args, from_idx) = w_from_args()?; 547 | println_vb4!("cmd: {} / w args: '{}' / w field: {}", cmd, w_args, from_idx); 548 | for device in glob("/tmp/.X11-unix/X*")? { 549 | println_vb4!(" - socket: {:?}", device); 550 | let device: String = match device { 551 | Ok(p) => p.to_str().unwrap_or("0").to_owned(), 552 | _ => "0".to_owned(), 553 | }; 554 | let display = format!(":{}", device.chars().rev().next().unwrap_or('0')); 555 | println_vb4!(" - display: {}", display); 556 | let mut output = Command::new("w") 557 | .arg(&w_args) 558 | .stdout(Stdio::piped()).spawn()?; 559 | let _ = output.wait()?; 560 | let w_stdout = output.stdout 561 | .ok_or(CircadianError("w command has no output".into()))?; 562 | let awk_arg = format!("{{if (${} ~ /^{}/) print $1}}", from_idx + 1, display); 563 | let output = Command::new("awk") 564 | .arg(awk_arg) 565 | .stdin(w_stdout) 566 | .output()?; 567 | let user_str = String::from_utf8(output.stdout) 568 | .unwrap_or(String::new()); 569 | println_vb4!(" - awk users ({}): {}", user_str.len(), user_str.replace("\n", " / ")); 570 | 571 | // Get a list of all system users with open sessions to this 572 | // X11 display, and de-duplicate by storing in a set. There 573 | // should be one per logged in user if a session manager is in 574 | // use, plus one for each terminal the user has open. 575 | let user_list: HashSet<&str> = user_str.split("\n") 576 | .map(|x| x.trim()) 577 | .filter(|x| x.len() > 0) 578 | .collect(); 579 | // Convert all of the user names to UIDs. 580 | let mut user_list: HashSet = user_list.iter() 581 | .filter_map(|x| match x.trim() { 582 | user if user.len() > 0 => { 583 | match Command::new("id").arg("-u").arg(user).output() { 584 | Ok(output) => { 585 | let mut uid = String::from_utf8(output.stdout) 586 | .unwrap_or(String::new()); 587 | uid.pop(); 588 | let uid = uid.parse::().unwrap_or(0); 589 | Some(uid) 590 | }, 591 | Err(_) => { 592 | None 593 | } 594 | } 595 | }, 596 | _ => { 597 | None 598 | } 599 | }) 600 | .collect(); 601 | // Insert the UID of the socket owner, too. This covers X 602 | // servers spawned without session managers, i.e. those 603 | // spawned with 'startx' or Xephyr. 604 | let owner_uid = std::fs::metadata(&device)?.st_uid(); 605 | user_list.insert(owner_uid); 606 | // Always give it a try as root, too, since root can read 607 | // xauth files from anywhere. 608 | user_list.insert(0); 609 | println_vb4!(" - socket owner: {}", owner_uid); 610 | for uid in user_list { 611 | println_vb4!(" - UID: {}", uid); 612 | let xauth = xauthority_for_uid(uid, &display); 613 | println_vb4!(" - xauthority: {}", xauth); 614 | // allow this command to fail, in case there are several X 615 | // servers running. 616 | match Command::new(cmd) 617 | .args(&args) 618 | .uid(uid) 619 | .env("DISPLAY", &display) 620 | .env("XAUTHORITY", &xauth) 621 | .output() { 622 | Ok(output) => { 623 | let mut idle_str = String::from_utf8(output.stdout) 624 | .unwrap_or(String::new()); 625 | idle_str.pop(); 626 | let idle = idle_str.parse::().unwrap_or(std::u32::MAX)/1000; 627 | println_vb4!(" - idle: {}", idle); 628 | display_mins.push(idle); 629 | }, 630 | Err(e) => { 631 | println!("WARNING: {} failed for socket {} with error: {}", cmd, device, e); 632 | }, 633 | } 634 | } 635 | } 636 | match display_mins.len() { 637 | 0 => Err(CircadianError("No displays found.".to_string())), 638 | _ => Ok(display_mins.iter().fold(std::u32::MAX, |acc, x| std::cmp::min(acc,*x))) 639 | } 640 | } 641 | 642 | /// Call 'xprintidle' command and return idle time 643 | fn idle_xprintidle() -> IdleResult { 644 | idle_fn("xprintidle", vec![]) 645 | } 646 | 647 | /// Call 'xssstate' command and return idle time 648 | fn idle_xssstate() -> IdleResult { 649 | idle_fn("xssstate", vec!["-i"]) 650 | } 651 | 652 | 653 | /// Compare whether 'uptime' 5-min CPU usage compares 654 | /// to the given thresh with the given cmp function. 655 | /// 656 | /// ex: thresh_cpu(CpuHistory::Min1, 0.1, std::cmp::PartialOrd::lt) returns true 657 | /// if the 5-min CPU usage is less than 0.1 for the past minute 658 | /// 659 | fn thresh_cpu(history: CpuHistory, thresh: f64, cmp: C) -> ThreshResult 660 | where C: Fn(&f64, &f64) -> bool { 661 | let output = Command::new("uptime") 662 | .output()?; 663 | let uptime_str = String::from_utf8(output.stdout) 664 | .unwrap_or(String::new()); 665 | let columns: Vec<&str> = uptime_str.split(" ").collect(); 666 | let cpu_usages: Vec = columns.iter() 667 | .rev().take(3).map(|x| *x).collect::>().iter() 668 | .rev() 669 | .map(|x| *x) 670 | .filter(|x| x.len() > 0) 671 | .map(|x| str::parse::(&x[0..x.len()-1].replace(",",".")).unwrap_or(0.0)) 672 | .collect::>(); 673 | let idle: Vec = cpu_usages.iter() 674 | .map(|x| cmp(x, &thresh)) 675 | .collect(); 676 | // idle is bools of [1min, 5min, 15min] CPU usage 677 | let idx = match history { 678 | CpuHistory::Min1 => 0, 679 | CpuHistory::Min5 => 1, 680 | CpuHistory::Min15 => 2, 681 | }; 682 | // false == below threshold, true == above 683 | Ok(!*idle.get(idx).unwrap_or(&false)) 684 | } 685 | 686 | /// Determine whether a process (by name regex) is running. 687 | fn exist_process(prc: &str) -> ExistResult { 688 | let output = Command::new("pgrep") 689 | .arg("-c") 690 | .arg(prc) 691 | .output()?; 692 | let output = &output.stdout[0..output.stdout.len()-1]; 693 | let count: u32 = String::from_utf8(output.to_vec()) 694 | .unwrap_or(String::new()).parse::()?; 695 | Ok(count > 0) 696 | } 697 | 698 | /// Determine whether the given type of network connection is established. 699 | fn exist_net_connection(conn: NetConnection) -> ExistResult { 700 | let mut output = Command::new("netstat") 701 | .arg("-tnpa") 702 | .stderr(Stdio::null()) 703 | .stdout(Stdio::piped()).spawn()?; 704 | let _ = output.wait()?; 705 | let stdout = output.stdout 706 | .ok_or(CircadianError("netstat command has no output".to_string()))?; 707 | let mut output = Command::new("grep") 708 | .arg("ESTABLISHED") 709 | .stdin(stdout) 710 | .stdout(Stdio::piped()).spawn()?; 711 | let _ = output.wait()?; 712 | let stdout = output.stdout 713 | .ok_or(CircadianError("netstat command has no connections".to_string()))?; 714 | let pattern = match conn { 715 | NetConnection::SSH => "[0-9]+/ssh[d]*", 716 | NetConnection::SMB => "[0-9]+/smb[d]*", 717 | NetConnection::NFS => "[0-9]+:2049\\s", 718 | }; 719 | let output = Command::new("grep") 720 | .arg("-E") 721 | .arg(pattern) 722 | .stdin(stdout) 723 | .output()?; 724 | let output = String::from_utf8(output.stdout) 725 | .unwrap_or(String::new()); 726 | let connections: Vec<&str> = output 727 | .split("\n") 728 | .filter(|l| l.len() > 0) 729 | .collect(); 730 | Ok(connections.len() > 0) 731 | } 732 | 733 | /// Determine whether audio is actively playing on any ALSA interface. 734 | fn exist_audio_alsa() -> ExistResult { 735 | let mut count = 0; 736 | for device in glob("/proc/asound/card*/pcm*/sub*/status")? { 737 | if let Ok(path) = device { 738 | let mut cat_output = Command::new("cat") 739 | .arg(path) 740 | .stderr(Stdio::null()) 741 | .stdout(Stdio::piped()).spawn()?; 742 | let _ = cat_output.wait()?; 743 | let stdout = cat_output.stdout 744 | .ok_or(CircadianError("cat /proc/asound/* failed".to_string()))?; 745 | let output = Command::new("grep") 746 | .arg("state:") 747 | .stdin(stdout) 748 | .output()?; 749 | let output_str = String::from_utf8(output.stdout)?; 750 | let lines: Vec<&str> = output_str.split("\n") 751 | .filter(|l| l.len() > 0) 752 | .collect(); 753 | count += lines.len(); 754 | } 755 | } 756 | Ok(count > 0) 757 | } 758 | 759 | /// Determine whether audio is actively playing on any Pulseaudio interface. 760 | fn exist_audio_pulseaudio() -> ExistResult { 761 | let users_output = Command::new("users") 762 | .stderr(Stdio::null()) 763 | .output(); 764 | let users_stdout = users_output 765 | .map_err(| _ | CircadianError("users failed".to_string())); 766 | let users_output_str = String::from_utf8(users_stdout?.stdout)?; 767 | let active_users: HashSet<&str> = users_output_str.split(" ") 768 | .filter(|l| l.len() > 0) 769 | .collect(); 770 | 771 | let mut count = 0; 772 | for active_user in active_users { 773 | match get_user_by_name(&active_user.trim()) { 774 | Some(x) => { 775 | let active_user_id = x.uid(); 776 | let mut pactl_output = Command::new("pactl").uid(active_user_id) 777 | .env("XDG_RUNTIME_DIR", format!("/run/user/{}", active_user_id)) 778 | .args(["list", "sinks", "short"]) 779 | .stderr(Stdio::null()) 780 | .stdout(Stdio::piped()).spawn()?; 781 | let _ = pactl_output.wait()?; 782 | let stdout = pactl_output.stdout 783 | .ok_or(CircadianError("pactl failed".to_string()))?; 784 | let output = Command::new("grep") 785 | .arg("RUNNING") // Does not includes IDLE == Paused audio 786 | .stdin(stdout) 787 | .output()?; 788 | let output_str = String::from_utf8(output.stdout)?; 789 | let lines: Vec<&str> = output_str.split("\n") 790 | .filter(|l| l.len() > 0) 791 | .collect(); 792 | count += lines.len(); 793 | }, 794 | None => continue, 795 | } 796 | 797 | } 798 | Ok(count > 0) 799 | } 800 | 801 | fn exist_audio() -> ExistResult { 802 | let audio_alsa = exist_audio_alsa(); 803 | let audio_pulseaudio = exist_audio_pulseaudio(); 804 | Ok(*audio_alsa.as_ref().unwrap_or(&false) || *audio_pulseaudio.as_ref().unwrap_or(&false)) 805 | } 806 | 807 | #[derive(Parser)] 808 | #[command(author, version, about, long_about)] 809 | #[command(help_template = "\ 810 | {name} v{version}, {author-with-newline} 811 | {about-with-newline} 812 | {usage-heading} {usage} 813 | 814 | {all-args}{after-help} 815 | ")] 816 | struct CircadianLaunchOptions { 817 | #[arg(short = 'f', long = "config", value_name = "FILE", default_value_t = String::from("/etc/circadian.conf"))] 818 | config_file: String, 819 | #[arg(short, long)] 820 | test: bool, 821 | #[arg(short, long = "verbose", action = clap::ArgAction::Count)] 822 | verbosity: u8, 823 | } 824 | 825 | #[derive(Default,Debug)] 826 | struct CircadianConfig { 827 | verbosity: usize, 828 | idle_time: u64, 829 | auto_wake: Option, 830 | on_idle: Option, 831 | on_wake: Option, 832 | tty_input: bool, 833 | x11_input: bool, 834 | ssh_block: bool, 835 | smb_block: bool, 836 | nfs_block: bool, 837 | audio_block: bool, 838 | max_cpu_load: Option, 839 | process_block: Vec, 840 | } 841 | 842 | fn read_config(file_path: &str) -> Result { 843 | println!("Reading config from file: {}", file_path); 844 | let i = Ini::load_from_file(file_path)?; 845 | let mut config: CircadianConfig = Default::default(); 846 | if let Some(section) = i.section(Some("settings".to_owned())) { 847 | let verbosity: usize = section.get("verbosity") 848 | .and_then(|x| match x { 849 | x if x.len() > 0 => { x.parse::().ok() }, 850 | _ => None, 851 | }) 852 | .unwrap_or(0); 853 | let verbosity = std::cmp::min(verbosity, MAX_VERBOSITY); 854 | VERBOSITY.store(verbosity, Ordering::SeqCst); 855 | config.verbosity = verbosity; 856 | } 857 | if let Some(section) = i.section(Some("actions".to_owned())) { 858 | config.idle_time = section.get("idle_time") 859 | .map_or(0, |x| if x.len() > 0 { 860 | let (body,suffix) = x.split_at(x.len()-1); 861 | let num: u64 = match suffix { 862 | "m" => body.parse::().unwrap_or(0) * 60, 863 | "h" => body.parse::().unwrap_or(0) * 60 * 60, 864 | _ => x.parse::().unwrap_or(0), 865 | }; 866 | num 867 | } else {0}); 868 | config.auto_wake = section.get("auto_wake") 869 | .and_then(|x| if x.len() > 0 {Some(x.to_owned())} else {None}); 870 | config.on_idle = section.get("on_idle") 871 | .and_then(|x| if x.len() > 0 {Some(x.to_owned())} else {None}); 872 | config.on_wake = section.get("on_wake") 873 | .and_then(|x| if x.len() > 0 {Some(x.to_owned())} else {None}); 874 | } 875 | fn read_bool(s: &ini::Properties, 876 | key: &str) -> bool { 877 | match s.get(key).unwrap_or(&"no".to_string()).to_lowercase().as_str() { 878 | "yes" | "true" | "1" => true, 879 | _ => false, 880 | } 881 | } 882 | if let Some(section) = i.section(Some("heuristics".to_owned())) { 883 | config.tty_input = read_bool(section, "tty_input"); 884 | config.x11_input = read_bool(section, "x11_input"); 885 | config.ssh_block = read_bool(section, "ssh_block"); 886 | config.smb_block = read_bool(section, "smb_block"); 887 | config.nfs_block = read_bool(section, "nfs_block"); 888 | config.audio_block = read_bool(section, "audio_block"); 889 | config.max_cpu_load = section.get("max_cpu_load") 890 | .and_then(|x| if x.len() > 0 891 | {Some(x.parse::().unwrap_or(999.0))} else {None}); 892 | if let Some(proc_str) = section.get("process_block") { 893 | let proc_list = proc_str.split(","); 894 | config.process_block = proc_list 895 | .map(|x| x.trim().to_owned()).collect(); 896 | } 897 | } 898 | Ok(config) 899 | } 900 | 901 | fn test_idle(config: &CircadianConfig, start: i64) -> IdleResponse { 902 | let now = time::OffsetDateTime::now_utc().unix_timestamp(); 903 | let tty = idle_w(); 904 | let xssstate = idle_xssstate(); 905 | let xprintidle = idle_xprintidle(); 906 | let tty_idle = *tty.as_ref().unwrap_or(&std::u32::MAX); 907 | let x11_idle = std::cmp::min(*xssstate.as_ref().unwrap_or(&std::u32::MAX), 908 | *xprintidle.as_ref().unwrap_or(&std::u32::MAX)); 909 | let wake_remain = std::cmp::max(0, start + (config.idle_time as i64) - now) as u32; 910 | let min_idle: u32 = match (config.tty_input, config.x11_input) { 911 | (true,true) => std::cmp::min(tty_idle, x11_idle) as u32, 912 | (true,false) => tty_idle as u32, 913 | (false,_) => x11_idle as u32, 914 | }; 915 | let idle_remain: u64 = 916 | std::cmp::max(config.idle_time as i64 - min_idle as i64, 0) as u64; 917 | IdleResponse { 918 | w_idle: tty, 919 | w_enabled: config.tty_input, 920 | xssstate_idle: xssstate, 921 | xssstate_enabled: config.x11_input, 922 | xprintidle_idle: xprintidle, 923 | xprintidle_enabled: config.x11_input, 924 | wake_remain: wake_remain, 925 | tty_idle: tty_idle, 926 | tty_enabled: config.tty_input, 927 | x11_idle: x11_idle, 928 | x11_enabled: config.x11_input, 929 | min_idle: min_idle, 930 | idle_target: config.idle_time, 931 | idle_remain: idle_remain, 932 | is_idle: idle_remain == 0 && wake_remain == 0, 933 | } 934 | } 935 | fn test_nonidle(config: &CircadianConfig) -> NonIdleResponse { 936 | let cpu_load = thresh_cpu(CpuHistory::Min1, 937 | config.max_cpu_load.unwrap_or(999.0), 938 | std::cmp::PartialOrd::lt); 939 | let cpu_load_enabled = config.max_cpu_load.is_some() && 940 | config.max_cpu_load.unwrap() < 999.0; 941 | let ssh = exist_net_connection(NetConnection::SSH); 942 | let ssh_enabled = config.ssh_block; 943 | let smb = exist_net_connection(NetConnection::SMB); 944 | let smb_enabled = config.smb_block; 945 | let nfs = exist_net_connection(NetConnection::NFS); 946 | let nfs_enabled = config.nfs_block; 947 | let audio = exist_audio(); 948 | let audio_enabled = config.audio_block; 949 | let procs = config.process_block.iter() 950 | // Run 'exist_process' on each process string 951 | .map(|p| exist_process(p)) 952 | // Flatten into a single result with a Vec of bools 953 | .collect::, CircadianError>>() 954 | // Flatten Vec of bools into a single bool 955 | .map(|x| x.iter().fold(false, |acc,p| acc || *p)); 956 | let procs_enabled = config.process_block.len() > 0; 957 | 958 | let blocked = (cpu_load_enabled && *cpu_load.as_ref().unwrap_or(&true)) || 959 | (ssh_enabled && *ssh.as_ref().unwrap_or(&true)) || 960 | (smb_enabled && *smb.as_ref().unwrap_or(&true)) || 961 | (nfs_enabled && *nfs.as_ref().unwrap_or(&true)) || 962 | (audio_enabled && *audio.as_ref().unwrap_or(&true)) || 963 | (procs_enabled && *procs.as_ref().unwrap_or(&true)); 964 | NonIdleResponse { 965 | cpu_load: cpu_load, 966 | cpu_load_enabled: cpu_load_enabled, 967 | ssh: ssh, 968 | ssh_enabled: ssh_enabled, 969 | smb: smb, 970 | smb_enabled: smb_enabled, 971 | nfs: nfs, 972 | nfs_enabled: nfs_enabled, 973 | audio: audio, 974 | audio_enabled: audio_enabled, 975 | procs: procs, 976 | procs_enabled: procs_enabled, 977 | is_blocked: blocked, 978 | } 979 | } 980 | 981 | fn is_rtc_utc() -> Result { 982 | fn get_rtc_time() -> Result { 983 | let output = Command::new("cat") 984 | .arg("/sys/class/rtc/rtc0/time") 985 | .output()?; 986 | let t = String::from_utf8(output.stdout)?; 987 | Ok(t.split(":").take(2).collect::>().join(":")) 988 | } 989 | let utc_tm = time::OffsetDateTime::now_utc().time(); 990 | let utc_time = format!("{:02}:{:02}", utc_tm.hour(), utc_tm.minute()); 991 | let rtc_time = get_rtc_time()?; 992 | let is_utc = utc_time == rtc_time; 993 | let is_synced = utc_time.split(":").nth(1) == rtc_time.split(":").nth(1); 994 | match is_synced { 995 | true => Ok(is_utc), 996 | _ => Err("RTC clock does not match OS clock. Auto-wake disabled.".into()), 997 | } 998 | } 999 | 1000 | fn auto_wake_to_epoch(auto_wake: &str) -> Result { 1001 | let _ = is_rtc_utc()?; // just to detect RTC sync errors 1002 | let format = format_description!("[hour]:[minute]"); 1003 | let auto_wake_tm = time::Time::parse(auto_wake, &format)?; 1004 | let now_local = match time::OffsetDateTime::now_local() { 1005 | Ok(l) => l, 1006 | _ => time::OffsetDateTime::now_utc(), 1007 | }; 1008 | let target_time_local = now_local.clone(); 1009 | let target_time_local = target_time_local.replace_hour(auto_wake_tm.hour())?; 1010 | let target_time_local = target_time_local.replace_minute(auto_wake_tm.minute())?; 1011 | let target_time_local = target_time_local.replace_second(0)?; 1012 | let target_time_local = match target_time_local < now_local { 1013 | true => target_time_local + time::Duration::days(1), 1014 | false => target_time_local, 1015 | }; 1016 | 1017 | // UNIX timestamps are defined as being in UTC, and Linux's RTC is 1018 | // defined as taking UTC timestamps. 1019 | Ok(AutoWakeEpoch { 1020 | epoch: target_time_local.unix_timestamp(), 1021 | is_utc: true 1022 | }) 1023 | } 1024 | fn set_rtc_wakealarm(timestamp: i64) -> Result<(), CircadianError> { 1025 | { 1026 | let mut f = std::fs::OpenOptions::new() 1027 | .write(true) 1028 | .truncate(true) 1029 | .open("/sys/class/rtc/rtc0/wakealarm")?; 1030 | f.write_all("0\n".as_bytes())?; 1031 | } 1032 | { 1033 | let mut f = std::fs::OpenOptions::new() 1034 | .write(true) 1035 | .truncate(true) 1036 | .open("/sys/class/rtc/rtc0/wakealarm")?; 1037 | f.write_all(format!("{}\n", timestamp).as_bytes())?; 1038 | } 1039 | Ok(()) 1040 | } 1041 | 1042 | fn set_auto_wake(auto_wake: Option<&String>) -> Result { 1043 | if auto_wake.is_none() { 1044 | return Err("Auto-wake not enabled.".into()); 1045 | } 1046 | let time = auto_wake.unwrap(); 1047 | let epoch = auto_wake_to_epoch(time)?; 1048 | let _ = set_rtc_wakealarm(epoch.epoch)?; 1049 | println!("Auto-wake scheduled for {} ({})", time, epoch.epoch); 1050 | Ok(epoch) 1051 | } 1052 | 1053 | fn reschedule_auto_wake(auto_wake: Option<&String>, current_epoch: Option) -> Option { 1054 | let mut new_rtc: Option = current_epoch.clone(); 1055 | if auto_wake.is_none() || current_epoch.is_none() { 1056 | return None; 1057 | } 1058 | let epoch = current_epoch.unwrap(); 1059 | let now = match epoch.is_utc { 1060 | true => time::OffsetDateTime::now_utc().unix_timestamp(), 1061 | false => match time::OffsetDateTime::now_local() { 1062 | Ok(l) => l.unix_timestamp(), 1063 | _ => time::OffsetDateTime::now_utc().unix_timestamp(), 1064 | } 1065 | }; 1066 | if now >= epoch.epoch { 1067 | new_rtc = match set_auto_wake(auto_wake) { 1068 | Ok(epoch) => Some(epoch), 1069 | Err(e) => {println!("Error recheduling auto-wake timer: {}. Disabled.", e); None}, 1070 | }; 1071 | } 1072 | new_rtc 1073 | } 1074 | 1075 | #[allow(dead_code)] 1076 | fn test() { 1077 | println!("Sec: {:?}", parse_w_time("10.45s")); 1078 | println!("Sec: {:?}", parse_w_time("1:11")); 1079 | println!("Sec: {:?}", parse_w_time("0:10m")); 1080 | println!("w min: {:?}", idle_w()); 1081 | println!("xssstate min: {:?}", idle_xssstate()); 1082 | println!("xprintidle min: {:?}", idle_xprintidle()); 1083 | println!("cpu: {:?}", thresh_cpu(CpuHistory::Min5, 0.3, std::cmp::PartialOrd::lt)); 1084 | println!("ssh: {:?}", exist_net_connection(NetConnection::SSH)); 1085 | println!("smb: {:?}", exist_net_connection(NetConnection::SMB)); 1086 | println!("nfs: {:?}", exist_net_connection(NetConnection::NFS)); 1087 | println!("iotop: {:?}", exist_process("^iotop$")); 1088 | println!("audio: {:?}", exist_audio()); 1089 | } 1090 | 1091 | fn main() { 1092 | let launch_opts = CircadianLaunchOptions::parse(); 1093 | let config = read_config(&launch_opts.config_file) 1094 | .unwrap_or_else(|x| { 1095 | println!("{}", x); 1096 | println!("Could not open config file. Exiting."); 1097 | std::process::exit(1); 1098 | }); 1099 | println!("Circadian launching."); 1100 | println!("{:?}", config); 1101 | 1102 | // override config verbosity from command-line 1103 | if launch_opts.verbosity as usize > config.verbosity { 1104 | VERBOSITY.store(launch_opts.verbosity as usize, Ordering::SeqCst); 1105 | } 1106 | 1107 | // override user locale to make all command outputs uniform (e.g. when parsing column headers or dates/times) 1108 | std::env::set_var("LC_ALL", "C"); 1109 | 1110 | if launch_opts.test { 1111 | println!("Got --test: running idle test and exiting."); 1112 | let start = time::OffsetDateTime::now_utc().unix_timestamp(); 1113 | let idle = test_idle(&config, start); 1114 | let tests = test_nonidle(&config); 1115 | println!("Idle Detection Summary:\n{}{}", idle, tests); 1116 | std::process::exit(0); 1117 | } 1118 | 1119 | if !config.tty_input && !config.x11_input { 1120 | println!("tty_input or x11_input must be enabled. Exiting."); 1121 | std::process::exit(1); 1122 | } 1123 | if config.tty_input && !command_exists("w") { 1124 | println!("'w' command required by tty_input failed. Exiting."); 1125 | std::process::exit(1); 1126 | } 1127 | if config.x11_input && 1128 | !command_exists("xssstate") && 1129 | !command_exists("xprintidle") { 1130 | println!("Both 'xssstate' and 'xprintidle' commands required by x11_input failed. Exiting."); 1131 | std::process::exit(1); 1132 | } 1133 | if config.max_cpu_load.is_some() && 1134 | thresh_cpu(CpuHistory::Min1, 0.0, std::cmp::PartialOrd::lt).is_err() { 1135 | println!("'uptime' command required by max_cpu_load failed. Exiting."); 1136 | std::process::exit(1); 1137 | } 1138 | if (config.ssh_block || config.smb_block || config.nfs_block) && 1139 | exist_net_connection(NetConnection::SSH).is_err() { 1140 | println!("'netstat' command required by ssh/smb/nfs_block failed. Exiting."); 1141 | std::process::exit(1); 1142 | } 1143 | if config.audio_block && (exist_audio_alsa().is_err() && exist_audio_pulseaudio().is_err()) { 1144 | println!("'/proc/asound/' and pactl required by audio_block is unreadable. Exiting."); 1145 | std::process::exit(1); 1146 | } 1147 | if config.process_block.len() > 0 && exist_process("").is_err() { 1148 | println!("'pgrep' required by process_block failed. Exiting."); 1149 | std::process::exit(1); 1150 | } 1151 | if config.idle_time == 0 { 1152 | println!("Idle time disabled. Nothing to do. Exiting."); 1153 | std::process::exit(1); 1154 | } 1155 | let mut current_rtc: Option = match set_auto_wake(config.auto_wake.as_ref()) { 1156 | Ok(epoch) => Some(epoch), 1157 | Err(e) => {println!("Error setting auto-wake timer: {}", e); None}, 1158 | }; 1159 | let _ = register_sigusr1().unwrap_or_else(|x| { 1160 | println!("{}", x); 1161 | println!("WARNING: Could not register SIGUSR1 handler."); 1162 | std::process::exit(1); 1163 | }); 1164 | println!("Configuration valid. Idle detection starting."); 1165 | 1166 | let mut idle_triggered = false; 1167 | let mut start = time::OffsetDateTime::now_utc().unix_timestamp(); 1168 | let mut watchdog = time::OffsetDateTime::now_utc().unix_timestamp(); 1169 | loop { 1170 | let idle = test_idle(&config, start); 1171 | // If it's idle, the idle command hasn't already run, and it has been 1172 | // at least |idle_time| since the service started: enter idle state. 1173 | if idle.is_idle && !idle_triggered { 1174 | let tests = test_nonidle(&config); 1175 | if !tests.is_blocked { 1176 | println!("Idle state active:\n{}{}", idle, tests); 1177 | if let Some(ref idle_cmd) = config.on_idle { 1178 | println!("System suspending."); 1179 | let status = Command::new("sh") 1180 | .arg("-c") 1181 | .arg(idle_cmd) 1182 | .status(); 1183 | match status { 1184 | Ok(_) => { println!("Idle command succeeded."); }, 1185 | Err(e) => { println!("Idle command failed: {}", e); }, 1186 | } 1187 | } 1188 | idle_triggered = true; 1189 | } 1190 | } 1191 | else { 1192 | idle_triggered = false; 1193 | } 1194 | 1195 | let sleep_time = std::cmp::max(idle.idle_remain, 5000); 1196 | let sleep_chunk = 500; 1197 | // Sleep for the minimum time needed before the system can possibly 1198 | // be idle, but do it in small chunks so we can periodically check 1199 | // for signals and clock jumps. 1200 | for _ in 0 .. sleep_time / sleep_chunk { 1201 | // Print stats when SIGUSR1 signal received 1202 | let signaled = SIGUSR_SIGNALED.swap(false, Ordering::SeqCst); 1203 | if signaled { 1204 | let idle = test_idle(&config, start); 1205 | let tests = test_nonidle(&config); 1206 | println!("Idle Detection Summary:\n{}{}", idle, tests); 1207 | } 1208 | 1209 | let now = time::OffsetDateTime::now_utc().unix_timestamp(); 1210 | // Look for clock jumps that indicate the system slept 1211 | if watchdog + 30 < now { 1212 | println!("Watchdog missed. Wake from sleep!"); 1213 | start = time::OffsetDateTime::now_utc().unix_timestamp(); 1214 | let idle = test_idle(&config, start); 1215 | let tests = test_nonidle(&config); 1216 | println!("Idle state on wake:\n{}{}", idle, tests); 1217 | if let Some(ref wake_cmd) = config.on_wake { 1218 | println!("System waking."); 1219 | let status = Command::new("sh") 1220 | .arg("-c") 1221 | .arg(wake_cmd) 1222 | .status(); 1223 | match status { 1224 | Ok(_) => { println!("Wake command succeeded."); }, 1225 | Err(e) => { println!("Wake command failed: {}", e); }, 1226 | } 1227 | } 1228 | } 1229 | // Kick watchdog timer frequently, and possibly reschedule auto-wake timer 1230 | if watchdog + 10 < now { 1231 | current_rtc = reschedule_auto_wake(config.auto_wake.as_ref(), current_rtc); 1232 | watchdog = time::OffsetDateTime::now_utc().unix_timestamp(); 1233 | } 1234 | std::thread::sleep(std::time::Duration::from_millis(sleep_chunk)); 1235 | } 1236 | } 1237 | } 1238 | --------------------------------------------------------------------------------