smartmontools SVN Rev 5659
Utility to control and monitor storage systems with "S.M.A.R.T."
smartd.cpp
Go to the documentation of this file.
1/*
2 * Home page of code is: https://www.smartmontools.org
3 *
4 * Copyright (C) 2002-11 Bruce Allen
5 * Copyright (C) 2008-25 Christian Franke
6 * Copyright (C) 2000 Michael Cornwell <cornwell@acm.org>
7 * Copyright (C) 2008 Oliver Bock <brevilo@users.sourceforge.net>
8 *
9 * SPDX-License-Identifier: GPL-2.0-or-later
10 */
11
12#include "config.h"
13#define __STDC_FORMAT_MACROS 1 // enable PRI* for C++
14
15// unconditionally included files
16#include <inttypes.h>
17#include <stdio.h>
18#include <sys/types.h>
19#include <sys/stat.h> // umask
20#include <signal.h>
21#include <fcntl.h>
22#include <string.h>
23#include <syslog.h>
24#include <stdarg.h>
25#include <stdlib.h>
26#include <errno.h>
27#include <time.h>
28#include <limits.h>
29#include <getopt.h>
30
31#include <algorithm> // std::replace()
32#include <map>
33#include <stdexcept>
34#include <string>
35#include <vector>
36
37// conditionally included files
38#ifndef _WIN32
39#include <sys/wait.h>
40#endif
41#ifdef HAVE_UNISTD_H
42#include <unistd.h>
43#endif
44
45#ifdef _WIN32
46#include "os_win32/popen.h" // popen_as_rstr_user(), pclose()
47#ifdef _MSC_VER
48#pragma warning(disable:4761) // "conversion supplied"
49typedef unsigned short mode_t;
50typedef int pid_t;
51#endif
52#include <io.h> // umask()
53#include <process.h> // getpid()
54#endif // _WIN32
55
56#ifdef __CYGWIN__
57#include <io.h> // setmode()
58#endif // __CYGWIN__
59
60#ifdef HAVE_LIBCAP_NG
61#include <cap-ng.h>
62#endif // LIBCAP_NG
63
64#ifdef HAVE_LIBSYSTEMD
65#include <systemd/sd-daemon.h>
66#endif // HAVE_LIBSYSTEMD
67
68// locally included files
69#include "atacmds.h"
70#include "dev_interface.h"
71#include "knowndrives.h"
72#include "scsicmds.h"
73#include "nvmecmds.h"
74#include "utility.h"
75#include "sg_unaligned.h"
76
77#ifdef HAVE_POSIX_API
78#include "popen_as_ugid.h"
79#endif
80
81#ifdef _WIN32
82// fork()/signal()/initd simulation for native Windows
83#include "os_win32/daemon_win32.h" // daemon_main/detach/signal()
84#define strsignal daemon_strsignal
85#define sleep daemon_sleep
86// SIGQUIT does not exist, CONTROL-Break signals SIGBREAK.
87#define SIGQUIT SIGBREAK
88#define SIGQUIT_KEYNAME "CONTROL-Break"
89#else // _WIN32
90#define SIGQUIT_KEYNAME "CONTROL-\\"
91#endif // _WIN32
92
93const char * smartd_cpp_cvsid = "$Id: smartd.cpp 5657 2025-02-02 15:37:48Z chrfranke $"
94 CONFIG_H_CVSID;
95
96extern "C" {
97 typedef void (*signal_handler_type)(int);
98}
99
101{
102#if defined(_WIN32)
103 // signal() emulation
104 daemon_signal(sig, handler);
105
106#else
107 // SVr4, POSIX.1-2001, ..., POSIX.1-2024
108 struct sigaction sa;
109 sa.sa_handler = SIG_DFL;
110 sigaction(sig, (struct sigaction *)0, &sa);
111 if (sa.sa_handler == SIG_IGN)
112 return;
113
114 sa = {};
115 sa.sa_handler = handler;
116 sa.sa_flags = SA_RESTART; // BSD signal() semantics
117 sigaction(sig, &sa, (struct sigaction *)0);
118#endif
119}
120
121using namespace smartmontools;
122
123static const int scsiLogRespLen = 252;
124
125// smartd exit codes
126#define EXIT_BADCMD 1 // command line did not parse
127#define EXIT_BADCONF 2 // syntax error in config file
128#define EXIT_STARTUP 3 // problem forking daemon
129#define EXIT_PID 4 // problem creating pid file
130#define EXIT_NOCONF 5 // config file does not exist
131#define EXIT_READCONF 6 // config file exists but cannot be read
132
133#define EXIT_NOMEM 8 // out of memory
134#define EXIT_BADCODE 10 // internal error - should NEVER happen
135
136#define EXIT_BADDEV 16 // we can't monitor this device
137#define EXIT_NODEV 17 // no devices to monitor
138
139#define EXIT_SIGNAL 254 // abort on signal
140
141
142// command-line: 1=debug mode, 2=print presets
143static unsigned char debugmode = 0;
144
145// command-line: how long to sleep between checks
146static constexpr int default_checktime = 1800;
148static int checktime_min = 0; // Minimum individual check time, 0 if none
149
150// command-line: name of PID file (empty for no pid file)
151static std::string pid_file;
152
153// command-line: path prefix of persistent state file, empty if no persistence.
154static std::string state_path_prefix
155#ifdef SMARTMONTOOLS_SAVESTATES
156 = SMARTMONTOOLS_SAVESTATES
157#endif
158 ;
159
160// command-line: path prefix of attribute log file, empty if no logs.
161static std::string attrlog_path_prefix
162#ifdef SMARTMONTOOLS_ATTRIBUTELOG
163 = SMARTMONTOOLS_ATTRIBUTELOG
164#endif
165 ;
166
167// configuration file name
168static const char * configfile;
169// configuration file "name" if read from stdin
170static const char * const configfile_stdin = "<stdin>";
171// path of alternate configuration file
172static std::string configfile_alt;
173
174// warning script file
175static std::string warning_script;
176
177#ifdef HAVE_POSIX_API
178// run warning script as non-privileged user
179static bool warn_as_user;
180static uid_t warn_uid;
181static gid_t warn_gid;
182static std::string warn_uname, warn_gname;
183#elif defined(_WIN32)
184// run warning script as restricted user
185static bool warn_as_restr_user;
186#endif
187
188// command-line: when should we exit?
189enum quit_t {
194static bool quit_nodev0 = false;
195
196// command-line; this is the default syslog(3) log facility to use.
197static int facility=LOG_DAEMON;
198
199#ifndef _WIN32
200// command-line: fork into background?
201static bool do_fork=true;
202#endif
203
204// TODO: This smartctl only variable is also used in some os_*.cpp
205unsigned char failuretest_permissive = 0;
206
207// set to one if we catch a USR1 (check devices now)
208static volatile int caughtsigUSR1=0;
209
210#ifdef _WIN32
211// set to one if we catch a USR2 (toggle debug mode)
212static volatile int caughtsigUSR2=0;
213#endif
214
215// set to one if we catch a HUP (reload config file). In debug mode,
216// set to two, if we catch INT (also reload config file).
217static volatile int caughtsigHUP=0;
218
219// set to signal value if we catch INT, QUIT, or TERM
220static volatile int caughtsigEXIT=0;
221
222// This function prints either to stdout or to the syslog as needed.
223static void PrintOut(int priority, const char *fmt, ...)
225
226#ifdef HAVE_LIBSYSTEMD
227// systemd notify support
228
229static bool notify_enabled = false;
230static bool notify_ready = false;
231
232static inline void notify_init()
233{
234 if (!getenv("NOTIFY_SOCKET"))
235 return;
236 notify_enabled = true;
237}
238
239static inline bool notify_post_init()
240{
241 if (!notify_enabled)
242 return true;
243 if (do_fork) {
244 PrintOut(LOG_CRIT, "Option -n (--no-fork) is required if 'Type=notify' is set.\n");
245 return false;
246 }
247 return true;
248}
249
250static inline void notify_extend_timeout()
251{
252 if (!notify_enabled)
253 return;
254 if (notify_ready)
255 return;
256 const char * notify = "EXTEND_TIMEOUT_USEC=20000000"; // typical drive spinup time is 20s tops
257 if (debugmode) {
258 pout("sd_notify(0, \"%s\")\n", notify);
259 return;
260 }
261 sd_notify(0, notify);
262}
263
264static void notify_msg(const char * msg, bool ready = false)
265{
266 if (!notify_enabled)
267 return;
268 if (debugmode) {
269 pout("sd_notify(0, \"%sSTATUS=%s\")\n", (ready ? "READY=1\\n" : ""), msg);
270 return;
271 }
272 sd_notifyf(0, "%sSTATUS=%s", (ready ? "READY=1\n" : ""), msg);
273}
274
275static void notify_check(int numdev)
276{
277 if (!notify_enabled)
278 return;
279 char msg[32];
280 snprintf(msg, sizeof(msg), "Checking %d device%s ...",
281 numdev, (numdev != 1 ? "s" : ""));
282 notify_msg(msg);
283}
284
285static void notify_wait(time_t wakeuptime, int numdev)
286{
287 if (!notify_enabled)
288 return;
289 char ts[16] = ""; struct tm tmbuf;
290 strftime(ts, sizeof(ts), "%H:%M:%S", time_to_tm_local(&tmbuf, wakeuptime));
291 char msg[64];
292 snprintf(msg, sizeof(msg), "Next check of %d device%s will start at %s",
293 numdev, (numdev != 1 ? "s" : ""), ts);
294 notify_msg(msg, !notify_ready); // first call notifies READY=1
295 notify_ready = true;
296}
297
298static void notify_exit(int status)
299{
300 if (!notify_enabled)
301 return;
302 const char * msg;
303 switch (status) {
304 case 0: msg = "Exiting ..."; break;
305 case EXIT_BADCMD: msg = "Error in command line (see SYSLOG)"; break;
306 case EXIT_BADCONF: case EXIT_NOCONF:
307 case EXIT_READCONF: msg = "Error in config file (see SYSLOG)"; break;
308 case EXIT_BADDEV: msg = "Unable to register a device (see SYSLOG)"; break;
309 case EXIT_NODEV: msg = "No devices to monitor"; break;
310 default: msg = "Error (see SYSLOG)"; break;
311 }
312 // Ensure that READY=1 is notified before 'exit(0)' because otherwise
313 // systemd will report a service (protocol) failure
314 notify_msg(msg, (!status && !notify_ready));
315}
316
317#else // HAVE_LIBSYSTEMD
318// No systemd notify support
319
320static inline bool notify_post_init()
321{
322#ifdef __linux__
323 if (getenv("NOTIFY_SOCKET")) {
324 PrintOut(LOG_CRIT, "This version of smartd was build without 'Type=notify' support.\n");
325 return false;
326 }
327#endif
328 return true;
329}
330
331static inline void notify_init() { }
332static inline void notify_extend_timeout() { }
333static inline void notify_msg(const char *) { }
334static inline void notify_check(int) { }
335static inline void notify_wait(time_t, int) { }
336static inline void notify_exit(int) { }
337
338#endif // HAVE_LIBSYSTEMD
339
340// Email frequencies
341enum class emailfreqs : unsigned char {
343};
344
345// Attribute monitoring flags.
346// See monitor_attr_flags below.
347enum {
354};
355
356// Array of flags for each attribute.
358{
359public:
360 bool is_set(int id, unsigned char flag) const
361 { return (0 < id && id < (int)sizeof(m_flags) && (m_flags[id] & flag)); }
362
363 void set(int id, unsigned char flags)
364 {
365 if (0 < id && id < (int)sizeof(m_flags))
366 m_flags[id] |= flags;
367 }
368
369private:
370 unsigned char m_flags[256]{};
371};
372
373
374/// Configuration data for a device. Read from smartd.conf.
375/// Supports copy & assignment and is compatible with STL containers.
377{
378 int lineno{}; // Line number of entry in file
379 std::string name; // Device name (with optional extra info)
380 std::string dev_name; // Device name (plain, for SMARTD_DEVICE variable)
381 std::string dev_type; // Device type argument from -d directive, empty if none
382 std::string dev_idinfo; // Device identify info for warning emails and duplicate check
383 std::string dev_idinfo_bc; // Same without namespace id for duplicate check
384 std::string state_file; // Path of the persistent state file, empty if none
385 std::string attrlog_file; // Path of the persistent attrlog file, empty if none
386 int checktime{}; // Individual check interval, 0 if none
387 bool ignore{}; // Ignore this entry
388 bool id_is_unique{}; // True if dev_idinfo is unique (includes S/N or WWN)
389 bool smartcheck{}; // Check SMART status
390 bool usagefailed{}; // Check for failed Usage Attributes
391 bool prefail{}; // Track changes in Prefail Attributes
392 bool usage{}; // Track changes in Usage Attributes
393 bool selftest{}; // Monitor number of selftest errors
394 bool errorlog{}; // Monitor number of ATA errors
395 bool xerrorlog{}; // Monitor number of ATA errors (Extended Comprehensive error log)
396 bool offlinests{}; // Monitor changes in offline data collection status
397 bool offlinests_ns{}; // Disable auto standby if in progress
398 bool selfteststs{}; // Monitor changes in self-test execution status
399 bool selfteststs_ns{}; // Disable auto standby if in progress
400 bool permissive{}; // Ignore failed SMART commands
401 char autosave{}; // 1=disable, 2=enable Autosave Attributes
402 char autoofflinetest{}; // 1=disable, 2=enable Auto Offline Test
403 firmwarebug_defs firmwarebugs; // -F directives from drivedb or smartd.conf
404 bool ignorepresets{}; // Ignore database of -v options
405 bool showpresets{}; // Show database entry for this device
406 bool removable{}; // Device may disappear (not be present)
407 char powermode{}; // skip check, if disk in idle or standby mode
408 bool powerquiet{}; // skip powermode 'skipping checks' message
409 int powerskipmax{}; // how many times can be check skipped
410 unsigned char tempdiff{}; // Track Temperature changes >= this limit
411 unsigned char tempinfo{}, tempcrit{}; // Track Temperatures >= these limits as LOG_INFO, LOG_CRIT+mail
412 regular_expression test_regex; // Regex for scheduled testing
413 unsigned test_offset_factor{}; // Factor for staggering of scheduled tests
414
415 // Configuration of email warning messages
416 std::string emailcmdline; // script to execute, empty if no messages
417 std::string emailaddress; // email address, or empty
418 emailfreqs emailfreq{}; // Send emails once, daily, diminishing
419 bool emailtest{}; // Send test email?
420
421 // ATA ONLY
422 int dev_rpm{}; // rotation rate, 0 = unknown, 1 = SSD, >1 = HDD
423 int set_aam{}; // disable(-1), enable(1..255->0..254) Automatic Acoustic Management
424 int set_apm{}; // disable(-1), enable(2..255->1..254) Advanced Power Management
425 int set_lookahead{}; // disable(-1), enable(1) read look-ahead
426 int set_standby{}; // set(1..255->0..254) standby timer
427 bool set_security_freeze{}; // Freeze ATA security
428 int set_wcache{}; // disable(-1), enable(1) write cache
429 int set_dsn{}; // disable(0x2), enable(0x1) DSN
430
431 bool sct_erc_set{}; // set SCT ERC to:
432 unsigned short sct_erc_readtime{}; // ERC read time (deciseconds)
433 unsigned short sct_erc_writetime{}; // ERC write time (deciseconds)
434
435 unsigned char curr_pending_id{}; // ID of current pending sector count, 0 if none
436 unsigned char offl_pending_id{}; // ID of offline uncorrectable sector count, 0 if none
437 bool curr_pending_incr{}, offl_pending_incr{}; // True if current/offline pending values increase
438 bool curr_pending_set{}, offl_pending_set{}; // True if '-C', '-U' set in smartd.conf
439
440 attribute_flags monitor_attr_flags; // MONITOR_* flags for each attribute
441
443
444 // NVMe only
445 unsigned nvme_err_log_max_entries{}; // size of error log
446};
447
448// Number of allowed mail message types
449static const int SMARTD_NMAIL = 13;
450// Type for '-M test' mails (state not persistent)
451static const int MAILTYPE_TEST = 0;
452// TODO: Add const or enum for all mail types.
453
454struct mailinfo {
455 int logged{}; // number of times an email has been sent
456 time_t firstsent{}; // time first email was sent, as defined by time(2)
457 time_t lastsent{}; // time last email was sent, as defined by time(2)
458};
459
460/// Persistent state data for a device.
462{
463 unsigned char tempmin{}, tempmax{}; // Min/Max Temperatures
464
465 unsigned char selflogcount{}; // total number of self-test errors
466 uint64_t selfloghour{}; // lifetime hours of last self-test error
467 // (NVMe self-test log uses a 64 bit value)
468
469 time_t scheduled_test_next_check{}; // Time of next check for scheduled self-tests
470
471 uint64_t selective_test_last_start{}; // Start LBA of last scheduled selective self-test
472 uint64_t selective_test_last_end{}; // End LBA of last scheduled selective self-test
473
474 mailinfo maillog[SMARTD_NMAIL]; // log info on when mail sent
475
476 // ATA ONLY
477 int ataerrorcount{}; // Total number of ATA errors
478
479 // Persistent part of ata_smart_values:
481 unsigned char id{};
482 unsigned char val{};
483 unsigned char worst{}; // Byte needed for 'raw64' attribute only.
484 uint64_t raw{};
485 unsigned char resvd{};
486 };
488
489 // SCSI ONLY
490
493 unsigned char found{};
494 };
496
499 unsigned char found{};
500 };
502
503 // NVMe only
505};
506
507/// Non-persistent state data for a device.
509{
510 bool must_write{}; // true if persistent part should be written
511
512 bool skip{}; // skip during next check cycle
513 time_t wakeuptime{}; // next wakeup time, 0 if unknown or global
514
515 bool not_cap_offline{}; // true == not capable of offline testing
520
521 unsigned char temperature{}; // last recorded Temperature (in Celsius)
522 time_t tempmin_delay{}; // time where Min Temperature tracking will start
523
524 bool removed{}; // true if open() failed for removable device
525
526 bool powermodefail{}; // true if power mode check failed
527 int powerskipcnt{}; // Number of checks skipped due to idle or standby mode
528 int lastpowermodeskipped{}; // the last power mode that was skipped
529
530 bool attrlog_dirty{}; // true if persistent part has new attr values that
531 // need to be written to attrlog
532
533 // SCSI ONLY
534 // TODO: change to bool
535 unsigned char SmartPageSupported{}; // has log sense IE page (0x2f)
536 unsigned char TempPageSupported{}; // has log sense temperature page (0xd)
541 unsigned char SuppressReport{}; // minimize nuisance reports
542 unsigned char modese_len{}; // mode sense/select cmd len: 0 (don't
543 // know yet) 6 or 10
544 // ATA ONLY
545 uint64_t num_sectors{}; // Number of sectors
546 ata_smart_values smartval{}; // SMART data
548 bool offline_started{}; // true if offline data collection was started
549
550 // ATA and NVMe
551 bool selftest_started{}; // true if self-test was started
552
553 // NVMe only
554 uint8_t selftest_op{}; // last self-test operation
555 uint8_t selftest_compl{}; // last self-test completion
556};
557
558/// Runtime state data for a device.
560: public persistent_dev_state,
561 public temp_dev_state
562{
564 void update_temp_state();
565};
566
567/// Container for configuration info for each device.
568typedef std::vector<dev_config> dev_config_vector;
569
570/// Container for state info for each device.
571typedef std::vector<dev_state> dev_state_vector;
572
573// Copy ATA attributes to persistent state.
575{
576 for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
579 pa.id = ta.id;
580 if (ta.id == 0) {
581 pa.val = pa.worst = 0; pa.raw = 0;
582 continue;
583 }
584 pa.val = ta.current;
585 pa.worst = ta.worst;
586 pa.raw = ta.raw[0]
587 | ( ta.raw[1] << 8)
588 | ( ta.raw[2] << 16)
589 | ((uint64_t)ta.raw[3] << 24)
590 | ((uint64_t)ta.raw[4] << 32)
591 | ((uint64_t)ta.raw[5] << 40);
592 pa.resvd = ta.reserv;
593 }
594}
595
596// Copy ATA from persistent to temp state.
598{
599 for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
600 const ata_attribute & pa = ata_attributes[i];
602 ta.id = pa.id;
603 if (pa.id == 0) {
604 ta.current = ta.worst = 0;
605 memset(ta.raw, 0, sizeof(ta.raw));
606 continue;
607 }
608 ta.current = pa.val;
609 ta.worst = pa.worst;
610 ta.raw[0] = (unsigned char) pa.raw;
611 ta.raw[1] = (unsigned char)(pa.raw >> 8);
612 ta.raw[2] = (unsigned char)(pa.raw >> 16);
613 ta.raw[3] = (unsigned char)(pa.raw >> 24);
614 ta.raw[4] = (unsigned char)(pa.raw >> 32);
615 ta.raw[5] = (unsigned char)(pa.raw >> 40);
616 ta.reserv = pa.resvd;
617 }
618}
619
620// Parse a line from a state file.
621static bool parse_dev_state_line(const char * line, persistent_dev_state & state)
622{
623 static const regular_expression regex(
624 "^ *"
625 "((temperature-min)" // (1 (2)
626 "|(temperature-max)" // (3)
627 "|(self-test-errors)" // (4)
628 "|(self-test-last-err-hour)" // (5)
629 "|(scheduled-test-next-check)" // (6)
630 "|(selective-test-last-start)" // (7)
631 "|(selective-test-last-end)" // (8)
632 "|(ata-error-count)" // (9)
633 "|(mail\\.([0-9]+)\\." // (10 (11)
634 "((count)" // (12 (13)
635 "|(first-sent-time)" // (14)
636 "|(last-sent-time)" // (15)
637 ")" // 12)
638 ")" // 10)
639 "|(ata-smart-attribute\\.([0-9]+)\\." // (16 (17)
640 "((id)" // (18 (19)
641 "|(val)" // (20)
642 "|(worst)" // (21)
643 "|(raw)" // (22)
644 "|(resvd)" // (23)
645 ")" // 18)
646 ")" // 16)
647 "|(nvme-err-log-entries)" // (24)
648 ")" // 1)
649 " *= *([0-9]+)[ \n]*$" // (25)
650 );
651
652 const int nmatch = 1+25;
654 if (!regex.execute(line, nmatch, match))
655 return false;
656 if (match[nmatch-1].rm_so < 0)
657 return false;
658
659 uint64_t val = strtoull(line + match[nmatch-1].rm_so, (char **)0, 10);
660
661 int m = 1;
662 if (match[++m].rm_so >= 0)
663 state.tempmin = (unsigned char)val;
664 else if (match[++m].rm_so >= 0)
665 state.tempmax = (unsigned char)val;
666 else if (match[++m].rm_so >= 0)
667 state.selflogcount = (unsigned char)val;
668 else if (match[++m].rm_so >= 0)
669 state.selfloghour = val;
670 else if (match[++m].rm_so >= 0)
671 state.scheduled_test_next_check = (time_t)val;
672 else if (match[++m].rm_so >= 0)
673 state.selective_test_last_start = val;
674 else if (match[++m].rm_so >= 0)
675 state.selective_test_last_end = val;
676 else if (match[++m].rm_so >= 0)
677 state.ataerrorcount = (int)val;
678 else if (match[m+=2].rm_so >= 0) {
679 int i = atoi(line+match[m].rm_so);
680 if (!(0 <= i && i < SMARTD_NMAIL))
681 return false;
682 if (i == MAILTYPE_TEST) // Don't suppress test mails
683 return true;
684 if (match[m+=2].rm_so >= 0)
685 state.maillog[i].logged = (int)val;
686 else if (match[++m].rm_so >= 0)
687 state.maillog[i].firstsent = (time_t)val;
688 else if (match[++m].rm_so >= 0)
689 state.maillog[i].lastsent = (time_t)val;
690 else
691 return false;
692 }
693 else if (match[m+=5+1].rm_so >= 0) {
694 int i = atoi(line+match[m].rm_so);
695 if (!(0 <= i && i < NUMBER_ATA_SMART_ATTRIBUTES))
696 return false;
697 if (match[m+=2].rm_so >= 0)
698 state.ata_attributes[i].id = (unsigned char)val;
699 else if (match[++m].rm_so >= 0)
700 state.ata_attributes[i].val = (unsigned char)val;
701 else if (match[++m].rm_so >= 0)
702 state.ata_attributes[i].worst = (unsigned char)val;
703 else if (match[++m].rm_so >= 0)
704 state.ata_attributes[i].raw = val;
705 else if (match[++m].rm_so >= 0)
706 state.ata_attributes[i].resvd = (unsigned char)val;
707 else
708 return false;
709 }
710 else if (match[m+7].rm_so >= 0)
711 state.nvme_err_log_entries = val;
712 else
713 return false;
714 return true;
715}
716
717// Read a state file.
718static bool read_dev_state(const char * path, persistent_dev_state & state)
719{
720 stdio_file f(path, "r");
721 if (!f) {
722 if (errno != ENOENT)
723 pout("Cannot read state file \"%s\"\n", path);
724 return false;
725 }
726#ifdef __CYGWIN__
727 setmode(fileno(f), O_TEXT); // Allow files with \r\n
728#endif
729
730 persistent_dev_state new_state;
731 int good = 0, bad = 0;
732 char line[256];
733 while (fgets(line, sizeof(line), f)) {
734 const char * s = line + strspn(line, " \t");
735 if (!*s || *s == '#')
736 continue;
737 if (!parse_dev_state_line(line, new_state))
738 bad++;
739 else
740 good++;
741 }
742
743 if (bad) {
744 if (!good) {
745 pout("%s: format error\n", path);
746 return false;
747 }
748 pout("%s: %d invalid line(s) ignored\n", path, bad);
749 }
750
751 // This sets the values missing in the file to 0.
752 state = new_state;
753 return true;
754}
755
756static void write_dev_state_line(FILE * f, const char * name, uint64_t val)
757{
758 if (val)
759 fprintf(f, "%s = %" PRIu64 "\n", name, val);
760}
761
762static void write_dev_state_line(FILE * f, const char * name1, int id, const char * name2, uint64_t val)
763{
764 if (val)
765 fprintf(f, "%s.%d.%s = %" PRIu64 "\n", name1, id, name2, val);
766}
767
768// Write a state file
769static bool write_dev_state(const char * path, const persistent_dev_state & state)
770{
771 // Rename old "file" to "file~"
772 std::string pathbak = path; pathbak += '~';
773 unlink(pathbak.c_str());
774 rename(path, pathbak.c_str());
775
776 stdio_file f(path, "w");
777 if (!f) {
778 pout("Cannot create state file \"%s\"\n", path);
779 return false;
780 }
781
782 fprintf(f, "# smartd state file\n");
783 write_dev_state_line(f, "temperature-min", state.tempmin);
784 write_dev_state_line(f, "temperature-max", state.tempmax);
785 write_dev_state_line(f, "self-test-errors", state.selflogcount);
786 write_dev_state_line(f, "self-test-last-err-hour", state.selfloghour);
787 write_dev_state_line(f, "scheduled-test-next-check", state.scheduled_test_next_check);
788 write_dev_state_line(f, "selective-test-last-start", state.selective_test_last_start);
789 write_dev_state_line(f, "selective-test-last-end", state.selective_test_last_end);
790
791 for (int i = 0; i < SMARTD_NMAIL; i++) {
792 if (i == MAILTYPE_TEST) // Don't suppress test mails
793 continue;
794 const mailinfo & mi = state.maillog[i];
795 if (!mi.logged)
796 continue;
797 write_dev_state_line(f, "mail", i, "count", mi.logged);
798 write_dev_state_line(f, "mail", i, "first-sent-time", mi.firstsent);
799 write_dev_state_line(f, "mail", i, "last-sent-time", mi.lastsent);
800 }
801
802 // ATA ONLY
803 write_dev_state_line(f, "ata-error-count", state.ataerrorcount);
804
805 for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
806 const auto & pa = state.ata_attributes[i];
807 if (!pa.id)
808 continue;
809 write_dev_state_line(f, "ata-smart-attribute", i, "id", pa.id);
810 write_dev_state_line(f, "ata-smart-attribute", i, "val", pa.val);
811 write_dev_state_line(f, "ata-smart-attribute", i, "worst", pa.worst);
812 write_dev_state_line(f, "ata-smart-attribute", i, "raw", pa.raw);
813 write_dev_state_line(f, "ata-smart-attribute", i, "resvd", pa.resvd);
814 }
815
816 // NVMe only
817 write_dev_state_line(f, "nvme-err-log-entries", state.nvme_err_log_entries);
818
819 return true;
820}
821
822// Write to the attrlog file
823static bool write_dev_attrlog(const char * path, const dev_state & state)
824{
825 stdio_file f(path, "a");
826 if (!f) {
827 pout("Cannot create attribute log file \"%s\"\n", path);
828 return false;
829 }
830
831
832 time_t now = time(nullptr);
833 struct tm tmbuf, * tms = time_to_tm_local(&tmbuf, now);
834 fprintf(f, "%d-%02d-%02d %02d:%02d:%02d;",
835 1900+tms->tm_year, 1+tms->tm_mon, tms->tm_mday,
836 tms->tm_hour, tms->tm_min, tms->tm_sec);
837 // ATA ONLY
838 for (const auto & pa : state.ata_attributes) {
839 if (!pa.id)
840 continue;
841 fprintf(f, "\t%d;%d;%" PRIu64 ";", pa.id, pa.val, pa.raw);
842 }
843 // SCSI ONLY
844 const struct scsiErrorCounter * ecp;
845 const char * pageNames[3] = {"read", "write", "verify"};
846 for (int k = 0; k < 3; ++k) {
847 if ( !state.scsi_error_counters[k].found ) continue;
848 ecp = &state.scsi_error_counters[k].errCounter;
849 fprintf(f, "\t%s-corr-by-ecc-fast;%" PRIu64 ";"
850 "\t%s-corr-by-ecc-delayed;%" PRIu64 ";"
851 "\t%s-corr-by-retry;%" PRIu64 ";"
852 "\t%s-total-err-corrected;%" PRIu64 ";"
853 "\t%s-corr-algorithm-invocations;%" PRIu64 ";"
854 "\t%s-gb-processed;%.3f;"
855 "\t%s-total-unc-errors;%" PRIu64 ";",
856 pageNames[k], ecp->counter[0],
857 pageNames[k], ecp->counter[1],
858 pageNames[k], ecp->counter[2],
859 pageNames[k], ecp->counter[3],
860 pageNames[k], ecp->counter[4],
861 pageNames[k], (ecp->counter[5] / 1000000000.0),
862 pageNames[k], ecp->counter[6]);
863 }
864 if(state.scsi_nonmedium_error.found && state.scsi_nonmedium_error.nme.gotPC0) {
865 fprintf(f, "\tnon-medium-errors;%" PRIu64 ";", state.scsi_nonmedium_error.nme.counterPC0);
866 }
867 // write SCSI current temperature if it is monitored
868 if (state.temperature)
869 fprintf(f, "\ttemperature;%d;", state.temperature);
870 // end of line
871 fprintf(f, "\n");
872 return true;
873}
874
875// Write all state files. If write_always is false, don't write
876// unless must_write is set.
877static void write_all_dev_states(const dev_config_vector & configs,
878 dev_state_vector & states,
879 bool write_always = true)
880{
881 for (unsigned i = 0; i < states.size(); i++) {
882 const dev_config & cfg = configs.at(i);
883 if (cfg.state_file.empty())
884 continue;
885 dev_state & state = states[i];
886 if (!write_always && !state.must_write)
887 continue;
888 if (!write_dev_state(cfg.state_file.c_str(), state))
889 continue;
890 state.must_write = false;
891 if (write_always || debugmode)
892 PrintOut(LOG_INFO, "Device: %s, state written to %s\n",
893 cfg.name.c_str(), cfg.state_file.c_str());
894 }
895}
896
897// Write to all attrlog files
898static void write_all_dev_attrlogs(const dev_config_vector & configs,
899 dev_state_vector & states)
900{
901 for (unsigned i = 0; i < states.size(); i++) {
902 const dev_config & cfg = configs.at(i);
903 if (cfg.attrlog_file.empty())
904 continue;
905 dev_state & state = states[i];
906 if (state.attrlog_dirty) {
907 write_dev_attrlog(cfg.attrlog_file.c_str(), state);
908 state.attrlog_dirty = false;
909 }
910 }
911}
912
913extern "C" { // signal handlers require C-linkage
914
915// Note if we catch a SIGUSR1
916static void USR1handler(int sig)
917{
918 if (SIGUSR1==sig)
920 return;
921}
922
923#ifdef _WIN32
924// Note if we catch a SIGUSR2
925static void USR2handler(int sig)
926{
927 if (SIGUSR2==sig)
928 caughtsigUSR2=1;
929 return;
930}
931#endif
932
933// Note if we catch a HUP (or INT in debug mode)
934static void HUPhandler(int sig)
935{
936 if (sig==SIGHUP)
937 caughtsigHUP=1;
938 else
939 caughtsigHUP=2;
940 return;
941}
942
943// signal handler for TERM, QUIT, and INT (if not in debug mode)
944static void sighandler(int sig)
945{
946 if (!caughtsigEXIT)
947 caughtsigEXIT=sig;
948 return;
949}
950
951} // extern "C"
952
953#ifdef HAVE_LIBCAP_NG
954// capabilities(7) support
955
956static int capabilities_mode /* = 0 */; // 1=enabled, 2=mail
957
958static void capabilities_drop_now()
959{
960 if (!capabilities_mode)
961 return;
962 capng_clear(CAPNG_SELECT_BOTH);
963 capng_updatev(CAPNG_ADD, (capng_type_t)(CAPNG_EFFECTIVE|CAPNG_PERMITTED),
964 CAP_SYS_ADMIN, CAP_MKNOD, CAP_SYS_RAWIO, -1);
965 if (warn_as_user && (warn_uid || warn_gid)) {
966 // For popen_as_ugid()
967 capng_updatev(CAPNG_ADD, (capng_type_t)(CAPNG_EFFECTIVE|CAPNG_PERMITTED),
968 CAP_SETGID, CAP_SETUID, -1);
969 }
970 if (capabilities_mode > 1) {
971 // For exim MTA
972 capng_updatev(CAPNG_ADD, CAPNG_BOUNDING_SET,
973 CAP_SETGID, CAP_SETUID, CAP_CHOWN, CAP_FOWNER, CAP_DAC_OVERRIDE, -1);
974 }
975 capng_apply(CAPNG_SELECT_BOTH);
976}
977
978static void capabilities_log_error_hint()
979{
980 if (!capabilities_mode)
981 return;
982 PrintOut(LOG_INFO, "If mail notification does not work with '--capabilities%s\n",
983 (capabilities_mode == 1 ? "', try '--capabilities=mail'"
984 : "=mail', please inform " PACKAGE_BUGREPORT));
985}
986
987#else // HAVE_LIBCAP_NG
988// No capabilities(7) support
989
990static inline void capabilities_drop_now() { }
991static inline void capabilities_log_error_hint() { }
992
993#endif // HAVE_LIBCAP_NG
994
995// a replacement for setenv() which is not available on all platforms.
996// Note that the string passed to putenv must not be freed or made
997// invalid, since a pointer to it is kept by putenv(). This means that
998// it must either be a static buffer or allocated off the heap. The
999// string can be freed if the environment variable is redefined via
1000// another call to putenv(). There is no portable way to unset a variable
1001// with putenv(). So we manage the buffer in a static object.
1002// Using setenv() if available is not considered because some
1003// implementations may produce memory leaks.
1004
1006{
1007public:
1008 env_buffer() = default;
1009 env_buffer(const env_buffer &) = delete;
1010 void operator=(const env_buffer &) = delete;
1011
1012 void set(const char * name, const char * value);
1013private:
1014 char * m_buf = nullptr;
1015};
1016
1017void env_buffer::set(const char * name, const char * value)
1018{
1019 int size = strlen(name) + 1 + strlen(value) + 1;
1020 char * newbuf = new char[size];
1021 snprintf(newbuf, size, "%s=%s", name, value);
1022
1023 if (putenv(newbuf))
1024 throw std::runtime_error("putenv() failed");
1025
1026 // This assumes that the same NAME is passed on each call
1027 delete [] m_buf;
1028 m_buf = newbuf;
1029}
1030
1031#define EBUFLEN 1024
1032
1033static void MailWarning(const dev_config & cfg, dev_state & state, int which, const char *fmt, ...)
1035
1036// If either address or executable path is non-null then send and log
1037// a warning email, or execute executable
1038static void MailWarning(const dev_config & cfg, dev_state & state, int which, const char *fmt, ...)
1039{
1040 // See if user wants us to send mail
1041 if (cfg.emailaddress.empty() && cfg.emailcmdline.empty())
1042 return;
1043
1044 // Which type of mail are we sending?
1045 static const char * const whichfail[] = {
1046 "EmailTest", // 0
1047 "Health", // 1
1048 "Usage", // 2
1049 "SelfTest", // 3
1050 "ErrorCount", // 4
1051 "FailedHealthCheck", // 5
1052 "FailedReadSmartData", // 6
1053 "FailedReadSmartErrorLog", // 7
1054 "FailedReadSmartSelfTestLog", // 8
1055 "FailedOpenDevice", // 9
1056 "CurrentPendingSector", // 10
1057 "OfflineUncorrectableSector", // 11
1058 "Temperature" // 12
1059 };
1060 STATIC_ASSERT(sizeof(whichfail) == SMARTD_NMAIL * sizeof(whichfail[0]));
1061
1062 if (!(0 <= which && which < SMARTD_NMAIL)) {
1063 PrintOut(LOG_CRIT, "Internal error in MailWarning(): which=%d\n", which);
1064 return;
1065 }
1066 mailinfo * mail = state.maillog + which;
1067
1068 // Calc current and next interval for warning reminder emails
1069 int days, nextdays;
1070 if (which == 0)
1071 days = nextdays = -1; // EmailTest
1072 else switch (cfg.emailfreq) {
1073 case emailfreqs::once:
1074 days = nextdays = -1; break;
1075 case emailfreqs::always:
1076 days = nextdays = 0; break;
1077 case emailfreqs::daily:
1078 days = nextdays = 1; break;
1080 // 0, 1, 2, 3, 4, 5, 6, 7, ... => 1, 2, 4, 8, 16, 32, 32, 32, ...
1081 nextdays = 1 << ((unsigned)mail->logged <= 5 ? mail->logged : 5);
1082 // 0, 1, 2, 3, 4, 5, 6, 7, ... => 0, 1, 2, 4, 8, 16, 32, 32, ... (0 not used below)
1083 days = ((unsigned)mail->logged <= 5 ? nextdays >> 1 : nextdays);
1084 break;
1085 default:
1086 PrintOut(LOG_CRIT, "Internal error in MailWarning(): cfg.emailfreq=%d\n", (int)cfg.emailfreq);
1087 return;
1088 }
1089
1090 time_t now = time(nullptr);
1091 if (mail->logged) {
1092 // Return if no warning reminder email needs to be sent (now)
1093 if (days < 0)
1094 return; // '-M once' or EmailTest
1095 if (days > 0 && now < mail->lastsent + days * 24 * 3600)
1096 return; // '-M daily/diminishing' and too early
1097 }
1098 else {
1099 // Record the time of this first email message
1100 mail->firstsent = now;
1101 }
1102
1103 // Record the time of this email message
1104 mail->lastsent = now;
1105
1106 // print warning string into message
1107 // Note: Message length may reach ~300 characters as device names may be
1108 // very long on certain platforms (macOS ~230 characters).
1109 // Message length must not exceed email line length limit, see RFC 5322:
1110 // "... MUST be no more than 998 characters, ... excluding the CRLF."
1111 char message[512];
1112 va_list ap;
1113 va_start(ap, fmt);
1114 vsnprintf(message, sizeof(message), fmt, ap);
1115 va_end(ap);
1116
1117 // replace commas by spaces to separate recipients
1118 std::string address = cfg.emailaddress;
1119 std::replace(address.begin(), address.end(), ',', ' ');
1120
1121 // Export information in environment variables that will be useful
1122 // for user scripts
1123 const char * executable = cfg.emailcmdline.c_str();
1124 static env_buffer env[13];
1125 env[0].set("SMARTD_MAILER", executable);
1126 env[1].set("SMARTD_MESSAGE", message);
1127 char dates[DATEANDEPOCHLEN];
1128 snprintf(dates, sizeof(dates), "%d", mail->logged);
1129 env[2].set("SMARTD_PREVCNT", dates);
1130 dateandtimezoneepoch(dates, mail->firstsent);
1131 env[3].set("SMARTD_TFIRST", dates);
1132 snprintf(dates, DATEANDEPOCHLEN,"%d", (int)mail->firstsent);
1133 env[4].set("SMARTD_TFIRSTEPOCH", dates);
1134 env[5].set("SMARTD_FAILTYPE", whichfail[which]);
1135 env[6].set("SMARTD_ADDRESS", address.c_str());
1136 env[7].set("SMARTD_DEVICESTRING", cfg.name.c_str());
1137
1138 // Allow 'smartctl ... -d $SMARTD_DEVICETYPE $SMARTD_DEVICE'
1139 env[8].set("SMARTD_DEVICETYPE",
1140 (!cfg.dev_type.empty() ? cfg.dev_type.c_str() : "auto"));
1141 env[9].set("SMARTD_DEVICE", cfg.dev_name.c_str());
1142
1143 env[10].set("SMARTD_DEVICEINFO", cfg.dev_idinfo.c_str());
1144 dates[0] = 0;
1145 if (nextdays >= 0)
1146 snprintf(dates, sizeof(dates), "%d", nextdays);
1147 env[11].set("SMARTD_NEXTDAYS", dates);
1148 // Avoid false positive recursion detection by smartd_warning.{sh,cmd}
1149 env[12].set("SMARTD_SUBJECT", "");
1150
1151 // now construct a command to send this as EMAIL
1152 if (!*executable)
1153 executable = "<mail>";
1154 const char * newadd = (!address.empty()? address.c_str() : "<nomailer>");
1155 const char * newwarn = (which? "Warning via" : "Test of");
1156
1157 char command[256];
1158#ifdef _WIN32
1159 // Path may contain spaces
1160 snprintf(command, sizeof(command), "\"%s\" 2>&1", warning_script.c_str());
1161#else
1162 snprintf(command, sizeof(command), "%s 2>&1", warning_script.c_str());
1163#endif
1164
1165 // tell SYSLOG what we are about to do...
1166 PrintOut(LOG_INFO,"%s %s to %s%s ...\n",
1167 (which ? "Sending warning via" : "Executing test of"), executable, newadd,
1168 (
1169#ifdef HAVE_POSIX_API
1170 warn_as_user ?
1171 strprintf(" (uid=%u(%s) gid=%u(%s))",
1172 (unsigned)warn_uid, warn_uname.c_str(),
1173 (unsigned)warn_gid, warn_gname.c_str() ).c_str() :
1174#elif defined(_WIN32)
1175 warn_as_restr_user ? " (restricted user)" :
1176#endif
1177 ""
1178 )
1179 );
1180
1181 // issue the command to send mail or to run the user's executable
1182 errno=0;
1183 FILE * pfp;
1184
1185#ifdef HAVE_POSIX_API
1186 if (warn_as_user) {
1187 pfp = popen_as_ugid(command, "r", warn_uid, warn_gid);
1188 } else
1189#endif
1190 {
1191#ifdef _WIN32
1192 pfp = popen_as_restr_user(command, "r", warn_as_restr_user);
1193#else
1194 pfp = popen(command, "r");
1195#endif
1196 }
1197
1198 if (!pfp)
1199 // failed to popen() mail process
1200 PrintOut(LOG_CRIT,"%s %s to %s: failed (fork or pipe failed, or no memory) %s\n",
1201 newwarn, executable, newadd, errno?strerror(errno):"");
1202 else {
1203 // pipe succeeded!
1204 int len;
1205 char buffer[EBUFLEN];
1206
1207 // if unexpected output on stdout/stderr, null terminate, print, and flush
1208 if ((len=fread(buffer, 1, EBUFLEN, pfp))) {
1209 int count=0;
1210 int newlen = len<EBUFLEN ? len : EBUFLEN-1;
1211 buffer[newlen]='\0';
1212 PrintOut(LOG_CRIT,"%s %s to %s produced unexpected output (%s%d bytes) to STDOUT/STDERR: \n%s\n",
1213 newwarn, executable, newadd, len!=newlen?"here truncated to ":"", newlen, buffer);
1214
1215 // flush pipe if needed
1216 while (fread(buffer, 1, EBUFLEN, pfp) && count<EBUFLEN)
1217 count++;
1218
1219 // tell user that pipe was flushed, or that something is really wrong
1220 if (count && count<EBUFLEN)
1221 PrintOut(LOG_CRIT,"%s %s to %s: flushed remaining STDOUT/STDERR\n",
1222 newwarn, executable, newadd);
1223 else if (count)
1224 PrintOut(LOG_CRIT,"%s %s to %s: more than 1 MB STDOUT/STDERR flushed, breaking pipe\n",
1225 newwarn, executable, newadd);
1226 }
1227
1228 // if something went wrong with mail process, print warning
1229 errno=0;
1230 int status;
1231
1232#ifdef HAVE_POSIX_API
1233 if (warn_as_user) {
1234 status = pclose_as_ugid(pfp);
1235 } else
1236#endif
1237 {
1238 status = pclose(pfp);
1239 }
1240
1241 if (status == -1)
1242 PrintOut(LOG_CRIT,"%s %s to %s: pclose(3) failed %s\n", newwarn, executable, newadd,
1243 errno?strerror(errno):"");
1244 else {
1245 // mail process apparently succeeded. Check and report exit status
1246 if (WIFEXITED(status)) {
1247 // exited 'normally' (but perhaps with nonzero status)
1248 int status8 = WEXITSTATUS(status);
1249 if (status8>128)
1250 PrintOut(LOG_CRIT,"%s %s to %s: failed (32-bit/8-bit exit status: %d/%d) perhaps caught signal %d [%s]\n",
1251 newwarn, executable, newadd, status, status8, status8-128, strsignal(status8-128));
1252 else if (status8) {
1253 PrintOut(LOG_CRIT,"%s %s to %s: failed (32-bit/8-bit exit status: %d/%d)\n",
1254 newwarn, executable, newadd, status, status8);
1256 }
1257 else
1258 PrintOut(LOG_INFO,"%s %s to %s: successful\n", newwarn, executable, newadd);
1259 }
1260
1261 if (WIFSIGNALED(status))
1262 PrintOut(LOG_INFO,"%s %s to %s: exited because of uncaught signal %d [%s]\n",
1263 newwarn, executable, newadd, WTERMSIG(status), strsignal(WTERMSIG(status)));
1264
1265 // this branch is probably not possible. If subprocess is
1266 // stopped then pclose() should not return.
1267 if (WIFSTOPPED(status))
1268 PrintOut(LOG_CRIT,"%s %s to %s: process STOPPED because it caught signal %d [%s]\n",
1269 newwarn, executable, newadd, WSTOPSIG(status), strsignal(WSTOPSIG(status)));
1270
1271 }
1272 }
1273
1274 // increment mail sent counter
1275 mail->logged++;
1276}
1277
1278static void reset_warning_mail(const dev_config & cfg, dev_state & state, int which, const char *fmt, ...)
1280
1281static void reset_warning_mail(const dev_config & cfg, dev_state & state, int which, const char *fmt, ...)
1282{
1283 if (!(0 <= which && which < SMARTD_NMAIL))
1284 return;
1285
1286 // Return if no mail sent yet
1287 mailinfo & mi = state.maillog[which];
1288 if (!mi.logged)
1289 return;
1290
1291 // Format & print message
1292 char msg[256];
1293 va_list ap;
1294 va_start(ap, fmt);
1295 vsnprintf(msg, sizeof(msg), fmt, ap);
1296 va_end(ap);
1297
1298 PrintOut(LOG_INFO, "Device: %s, %s, warning condition reset after %d email%s\n", cfg.name.c_str(),
1299 msg, mi.logged, (mi.logged==1 ? "" : "s"));
1300
1301 // Clear mail counter and timestamps
1302 mi = mailinfo();
1303 state.must_write = true;
1304}
1305
1306#ifndef _WIN32
1307
1308// Output multiple lines via separate syslog(3) calls.
1310static void vsyslog_lines(int priority, const char * fmt, va_list ap)
1311{
1312 char buf[512+EBUFLEN]; // enough space for exec cmd output in MailWarning()
1313 vsnprintf(buf, sizeof(buf), fmt, ap);
1314
1315 for (char * p = buf, * q; p && *p; p = q) {
1316 if ((q = strchr(p, '\n')))
1317 *q++ = 0;
1318 if (*p)
1319 syslog(priority, "%s\n", p);
1320 }
1321}
1322
1323#else // _WIN32
1324// os_win32/syslog_win32.cpp supports multiple lines.
1325#define vsyslog_lines vsyslog
1326#endif // _WIN32
1327
1328// Printing function for watching ataprint commands, or losing them
1329// [From GLIBC Manual: Since the prototype doesn't specify types for
1330// optional arguments, in a call to a variadic function the default
1331// argument promotions are performed on the optional argument
1332// values. This means the objects of type char or short int (whether
1333// signed or not) are promoted to either int or unsigned int, as
1334// appropriate.]
1335void pout(const char *fmt, ...){
1336 va_list ap;
1337
1338 // get the correct time in syslog()
1340 // initialize variable argument list
1341 va_start(ap,fmt);
1342 // in debugmode==1 mode we will print the output from the ataprint.o functions!
1343 if (debugmode && debugmode != 2) {
1344 FILE * f = stdout;
1345#ifdef _WIN32
1346 if (facility == LOG_LOCAL1) // logging to stdout
1347 f = stderr;
1348#endif
1349 vfprintf(f, fmt, ap);
1350 fflush(f);
1351 }
1352 // in debugmode==2 mode we print output from knowndrives.o functions
1353 else if (debugmode==2 || ata_debugmode || scsi_debugmode) {
1354 openlog("smartd", LOG_PID, facility);
1355 vsyslog_lines(LOG_INFO, fmt, ap);
1356 closelog();
1357 }
1358 va_end(ap);
1359 return;
1360}
1361
1362// This function prints either to stdout or to the syslog as needed.
1363static void PrintOut(int priority, const char *fmt, ...){
1364 va_list ap;
1365
1366 // get the correct time in syslog()
1368 // initialize variable argument list
1369 va_start(ap,fmt);
1370 if (debugmode) {
1371 FILE * f = stdout;
1372#ifdef _WIN32
1373 if (facility == LOG_LOCAL1) // logging to stdout
1374 f = stderr;
1375#endif
1376 vfprintf(f, fmt, ap);
1377 fflush(f);
1378 }
1379 else {
1380 openlog("smartd", LOG_PID, facility);
1381 vsyslog_lines(priority, fmt, ap);
1382 closelog();
1383 }
1384 va_end(ap);
1385 return;
1386}
1387
1388// Used to warn users about invalid checksums. Called from atacmds.cpp.
1389void checksumwarning(const char * string)
1390{
1391 pout("Warning! %s error: invalid SMART checksum.\n", string);
1392}
1393
1394#ifndef _WIN32
1395
1396// Wait for the pid file to show up, this makes sure a calling program knows
1397// that the daemon is really up and running and has a pid to kill it
1398static bool WaitForPidFile()
1399{
1400 int waited, max_wait = 10;
1401 struct stat stat_buf;
1402
1403 if (pid_file.empty() || debugmode)
1404 return true;
1405
1406 for(waited = 0; waited < max_wait; ++waited) {
1407 if (!stat(pid_file.c_str(), &stat_buf)) {
1408 return true;
1409 } else
1410 sleep(1);
1411 }
1412 return false;
1413}
1414
1415#endif // _WIN32
1416
1417// Forks new process if needed, closes ALL file descriptors,
1418// redirects stdin, stdout, and stderr. Not quite daemon().
1419// See https://www.linuxjournal.com/article/2335
1420// for a good description of why we do things this way.
1421static int daemon_init()
1422{
1423#ifndef _WIN32
1424
1425 // flush all buffered streams. Else we might get two copies of open
1426 // streams since both parent and child get copies of the buffers.
1427 fflush(nullptr);
1428
1429 if (do_fork) {
1430 pid_t pid;
1431 if ((pid=fork()) < 0) {
1432 // unable to fork!
1433 PrintOut(LOG_CRIT,"smartd unable to fork daemon process!\n");
1434 return EXIT_STARTUP;
1435 }
1436 if (pid) {
1437 // we are the parent process, wait for pid file, then exit cleanly
1438 if(!WaitForPidFile()) {
1439 PrintOut(LOG_CRIT,"PID file %s didn't show up!\n", pid_file.c_str());
1440 return EXIT_STARTUP;
1441 }
1442 return 0;
1443 }
1444
1445 // from here on, we are the child process.
1446 setsid();
1447
1448 // Fork one more time to avoid any possibility of having terminals
1449 if ((pid=fork()) < 0) {
1450 // unable to fork!
1451 PrintOut(LOG_CRIT,"smartd unable to fork daemon process!\n");
1452 return EXIT_STARTUP;
1453 }
1454 if (pid)
1455 // we are the parent process -- exit cleanly
1456 return 0;
1457
1458 // Now we are the child's child...
1459 }
1460
1461 // close any open file descriptors
1462 int open_max = sysconf(_SC_OPEN_MAX);
1463#ifdef HAVE_CLOSE_RANGE
1464 if (close_range(0, open_max - 1, 0))
1465#endif
1466 {
1467 // Limit number of unneeded close() calls under the assumption that
1468 // there are no large gaps between open FDs
1469 for (int i = 0, failed = 0; i < open_max && failed < 1024; i++)
1470 failed = (!close(i) ? 0 : failed + 1);
1471 }
1472
1473 // redirect any IO attempts to /dev/null and change to root directory
1474 int fd = open("/dev/null", O_RDWR);
1475 if (!(fd == 0 && dup(fd) == 1 && dup(fd) == 2 && !chdir("/"))) {
1476 PrintOut(LOG_CRIT, "smartd unable to redirect to /dev/null or to chdir to root!\n");
1477 return EXIT_STARTUP;
1478 }
1479 umask(0022);
1480
1481 if (do_fork)
1482 PrintOut(LOG_INFO, "smartd has fork()ed into background mode. New PID=%d.\n", (int)getpid());
1483
1484#else // _WIN32
1485
1486 // No fork() on native Win32
1487 // Detach this process from console
1488 fflush(nullptr);
1489 if (daemon_detach("smartd")) {
1490 PrintOut(LOG_CRIT,"smartd unable to detach from console!\n");
1491 return EXIT_STARTUP;
1492 }
1493 // stdin/out/err now closed if not redirected
1494
1495#endif // _WIN32
1496
1497 // No error, continue in main_worker()
1498 return -1;
1499}
1500
1501// create a PID file containing the current process id
1502static bool write_pid_file()
1503{
1504 if (!pid_file.empty()) {
1505 pid_t pid = getpid();
1506 mode_t old_umask;
1507#ifndef __CYGWIN__
1508 old_umask = umask(0077); // rwx------
1509#else
1510 // Cygwin: smartd service runs on system account, ensure PID file can be read by admins
1511 old_umask = umask(0033); // rwxr--r--
1512#endif
1513
1514 stdio_file f(pid_file.c_str(), "w");
1515 umask(old_umask);
1516 if (!(f && fprintf(f, "%d\n", (int)pid) > 0 && f.close())) {
1517 PrintOut(LOG_CRIT, "unable to write PID file %s - exiting.\n", pid_file.c_str());
1518 return false;
1519 }
1520 PrintOut(LOG_INFO, "file %s written containing PID %d\n", pid_file.c_str(), (int)pid);
1521 }
1522 return true;
1523}
1524
1525// Prints header identifying version of code and home
1526static void PrintHead()
1527{
1528 PrintOut(LOG_INFO, "%s\n", format_version_info("smartd").c_str());
1529}
1530
1531// prints help info for configuration file Directives
1532static void Directives()
1533{
1534 PrintOut(LOG_INFO,
1535 "Configuration file (%s) Directives (after device name):\n"
1536 " -d TYPE Set the device type: auto, ignore, removable,\n"
1537 " %s\n"
1538 " -T TYPE Set the tolerance to one of: normal, permissive\n"
1539 " -o VAL Enable/disable automatic offline tests (on/off)\n"
1540 " -S VAL Enable/disable attribute autosave (on/off)\n"
1541 " -n MODE No check if: never, sleep[,N][,q], standby[,N][,q], idle[,N][,q]\n"
1542 " -H Monitor SMART Health Status, report if failed\n"
1543 " -s REG Do Self-Test at time(s) given by regular expression REG\n"
1544 " -l TYPE Monitor SMART log or self-test status:\n"
1545 " error, selftest, xerror, offlinests[,ns], selfteststs[,ns]\n"
1546 " -l scterc,R,W Set SCT Error Recovery Control\n"
1547 " -e Change device setting: aam,[N|off], apm,[N|off], dsn,[on|off],\n"
1548 " lookahead,[on|off], security-freeze, standby,[N|off], wcache,[on|off]\n"
1549 " -f Monitor 'Usage' Attributes, report failures\n"
1550 " -m ADD Send email warning to address ADD\n"
1551 " -M TYPE Modify email warning behavior (see man page)\n"
1552 " -p Report changes in 'Prefailure' Attributes\n"
1553 " -u Report changes in 'Usage' Attributes\n"
1554 " -t Equivalent to -p and -u Directives\n"
1555 " -r ID Also report Raw values of Attribute ID with -p, -u or -t\n"
1556 " -R ID Track changes in Attribute ID Raw value with -p, -u or -t\n"
1557 " -i ID Ignore Attribute ID for -f Directive\n"
1558 " -I ID Ignore Attribute ID for -p, -u or -t Directive\n"
1559 " -C ID[+] Monitor [increases of] Current Pending Sectors in Attribute ID\n"
1560 " -U ID[+] Monitor [increases of] Offline Uncorrectable Sectors in Attribute ID\n"
1561 " -W D,I,C Monitor Temperature D)ifference, I)nformal limit, C)ritical limit\n"
1562 " -v N,ST Modifies labeling of Attribute N (see man page) \n"
1563 " -P TYPE Drive-specific presets: use, ignore, show, showall\n"
1564 " -a Default: -H -f -t -l error -l selftest -l selfteststs -C 197 -U 198\n"
1565 " -F TYPE Use firmware bug workaround:\n"
1566 " %s\n"
1567 " -c i=N Set interval between disk checks to N seconds\n"
1568 " # Comment: text after a hash sign is ignored\n"
1569 " \\ Line continuation character\n"
1570 "Attribute ID is a decimal integer 1 <= ID <= 255\n"
1571 "Use ID = 0 to turn off -C and/or -U Directives\n"
1572 "Example: /dev/sda -a\n",
1573 configfile,
1574 smi()->get_valid_dev_types_str().c_str(),
1576}
1577
1578/* Returns a pointer to a static string containing a formatted list of the valid
1579 arguments to the option opt or nullptr on failure. */
1580static const char *GetValidArgList(char opt)
1581{
1582 switch (opt) {
1583 case 'A':
1584 case 's':
1585 return "<PATH_PREFIX>, -";
1586 case 'B':
1587 return "[+]<FILE_NAME>";
1588 case 'c':
1589 return "<FILE_NAME>, -";
1590 case 'l':
1591 return "daemon, local0, local1, local2, local3, local4, local5, local6, local7";
1592 case 'q':
1593 return "nodev[0], errors[,nodev0], nodev[0]startup, never, onecheck, showtests";
1594 case 'r':
1595 return "ioctl[,N], ataioctl[,N], scsiioctl[,N], nvmeioctl[,N]";
1596 case 'p':
1597 case 'w':
1598 return "<FILE_NAME>";
1599 case 'i':
1600 return "<INTEGER_SECONDS>";
1601#ifdef HAVE_POSIX_API
1602 case 'u':
1603 return "<USER>[:<GROUP>], -";
1604#elif defined(_WIN32)
1605 case 'u':
1606 return "restricted, unchanged";
1607#endif
1608#ifdef HAVE_LIBCAP_NG
1609 case 'C':
1610 return "mail, <no_argument>";
1611#endif
1612 default:
1613 return nullptr;
1614 }
1615}
1616
1617/* prints help information for command syntax */
1618static void Usage()
1619{
1620 PrintOut(LOG_INFO,"Usage: smartd [options]\n\n");
1621#ifdef SMARTMONTOOLS_ATTRIBUTELOG
1622 PrintOut(LOG_INFO," -A PREFIX|-, --attributelog=PREFIX|-\n");
1623#else
1624 PrintOut(LOG_INFO," -A PREFIX, --attributelog=PREFIX\n");
1625#endif
1626 PrintOut(LOG_INFO," Log attribute information to {PREFIX}MODEL-SERIAL.TYPE.csv\n");
1627#ifdef SMARTMONTOOLS_ATTRIBUTELOG
1628 PrintOut(LOG_INFO," [default is " SMARTMONTOOLS_ATTRIBUTELOG "MODEL-SERIAL.TYPE.csv]\n");
1629#endif
1630 PrintOut(LOG_INFO,"\n");
1631 PrintOut(LOG_INFO," -B [+]FILE, --drivedb=[+]FILE\n");
1632 PrintOut(LOG_INFO," Read and replace [add] drive database from FILE\n");
1633 PrintOut(LOG_INFO," [default is +%s", get_drivedb_path_add());
1634#ifdef SMARTMONTOOLS_DRIVEDBDIR
1635 PrintOut(LOG_INFO,"\n");
1636 PrintOut(LOG_INFO," and then %s", get_drivedb_path_default());
1637#endif
1638 PrintOut(LOG_INFO,"]\n\n");
1639 PrintOut(LOG_INFO," -c NAME|-, --configfile=NAME|-\n");
1640 PrintOut(LOG_INFO," Read configuration file NAME or stdin\n");
1641 PrintOut(LOG_INFO," [default is %s]\n\n", configfile);
1642#ifdef HAVE_LIBCAP_NG
1643 PrintOut(LOG_INFO," -C, --capabilities[=mail]\n");
1644 PrintOut(LOG_INFO," Drop unneeded Linux process capabilities.\n"
1645 " Warning: Mail notification may not work when used.\n\n");
1646#endif
1647 PrintOut(LOG_INFO," -d, --debug\n");
1648 PrintOut(LOG_INFO," Start smartd in debug mode\n\n");
1649 PrintOut(LOG_INFO," -D, --showdirectives\n");
1650 PrintOut(LOG_INFO," Print the configuration file Directives and exit\n\n");
1651 PrintOut(LOG_INFO," -h, --help, --usage\n");
1652 PrintOut(LOG_INFO," Display this help and exit\n\n");
1653 PrintOut(LOG_INFO," -i N, --interval=N\n");
1654 PrintOut(LOG_INFO," Set interval between disk checks to N seconds, where N >= 10\n\n");
1655 PrintOut(LOG_INFO," -l local[0-7], --logfacility=local[0-7]\n");
1656#ifndef _WIN32
1657 PrintOut(LOG_INFO," Use syslog facility local0 - local7 or daemon [default]\n\n");
1658#else
1659 PrintOut(LOG_INFO," Log to \"./smartd.log\", stdout, stderr [default is event log]\n\n");
1660#endif
1661#ifndef _WIN32
1662 PrintOut(LOG_INFO," -n, --no-fork\n");
1663 PrintOut(LOG_INFO," Do not fork into background\n");
1664#ifdef HAVE_LIBSYSTEMD
1665 PrintOut(LOG_INFO," (systemd 'Type=notify' is assumed if $NOTIFY_SOCKET is set)\n");
1666#endif // HAVE_LIBSYSTEMD
1667 PrintOut(LOG_INFO,"\n");
1668#endif // WIN32
1669 PrintOut(LOG_INFO," -p NAME, --pidfile=NAME\n");
1670 PrintOut(LOG_INFO," Write PID file NAME\n\n");
1671 PrintOut(LOG_INFO," -q WHEN, --quit=WHEN\n");
1672 PrintOut(LOG_INFO," Quit on one of: %s\n\n", GetValidArgList('q'));
1673 PrintOut(LOG_INFO," -r, --report=TYPE\n");
1674 PrintOut(LOG_INFO," Report transactions for one of: %s\n\n", GetValidArgList('r'));
1675#ifdef SMARTMONTOOLS_SAVESTATES
1676 PrintOut(LOG_INFO," -s PREFIX|-, --savestates=PREFIX|-\n");
1677#else
1678 PrintOut(LOG_INFO," -s PREFIX, --savestates=PREFIX\n");
1679#endif
1680 PrintOut(LOG_INFO," Save disk states to {PREFIX}MODEL-SERIAL.TYPE.state\n");
1681#ifdef SMARTMONTOOLS_SAVESTATES
1682 PrintOut(LOG_INFO," [default is " SMARTMONTOOLS_SAVESTATES "MODEL-SERIAL.TYPE.state]\n");
1683#endif
1684 PrintOut(LOG_INFO,"\n");
1685 PrintOut(LOG_INFO," -w NAME, --warnexec=NAME\n");
1686 PrintOut(LOG_INFO," Run executable NAME on warnings\n");
1687#ifndef _WIN32
1688 PrintOut(LOG_INFO," [default is " SMARTMONTOOLS_SMARTDSCRIPTDIR "/smartd_warning.sh]\n\n");
1689#else
1690 PrintOut(LOG_INFO," [default is %s/smartd_warning.cmd]\n\n", get_exe_dir().c_str());
1691#endif
1692#ifdef HAVE_POSIX_API
1693 PrintOut(LOG_INFO," -u USER[:GROUP], --warn-as-user=USER[:GROUP]\n");
1694 PrintOut(LOG_INFO," Run warning script as non-privileged USER\n\n");
1695#elif defined(_WIN32)
1696 PrintOut(LOG_INFO," -u MODE, --warn-as-user=MODE\n");
1697 PrintOut(LOG_INFO," Run warning script with modified access token: %s\n\n", GetValidArgList('u'));
1698#endif
1699#ifdef _WIN32
1700 PrintOut(LOG_INFO," --service\n");
1701 PrintOut(LOG_INFO," Running as windows service (see man page), install with:\n");
1702 PrintOut(LOG_INFO," smartd install [options]\n");
1703 PrintOut(LOG_INFO," Remove service with:\n");
1704 PrintOut(LOG_INFO," smartd remove\n\n");
1705#endif // _WIN32
1706 PrintOut(LOG_INFO," -V, --version, --license, --copyright\n");
1707 PrintOut(LOG_INFO," Print License, Copyright, and version information\n");
1708}
1709
1710static int CloseDevice(smart_device * device, const char * name)
1711{
1712 if (!device->close()){
1713 PrintOut(LOG_INFO,"Device: %s, %s, close() failed\n", name, device->get_errmsg());
1714 return 1;
1715 }
1716 // device successfully closed
1717 return 0;
1718}
1719
1720// Replace invalid characters in cfg.dev_idinfo
1721static bool sanitize_dev_idinfo(std::string & s)
1722{
1723 bool changed = false;
1724 for (unsigned i = 0; i < s.size(); i++) {
1725 char c = s[i];
1726 STATIC_ASSERT(' ' == 0x20 && '~' == 0x07e); // Assume ASCII
1727 // Don't pass possible command escapes ('~! COMMAND') to the 'mail' command.
1728 if ((' ' <= c && c <= '~') && !(i == 0 && c == '~'))
1729 continue;
1730 s[i] = '?';
1731 changed = true;
1732 }
1733 return changed;
1734}
1735
1736// return true if a char is not allowed in a state file name
1737static bool not_allowed_in_filename(char c)
1738{
1739 return !( ('0' <= c && c <= '9')
1740 || ('A' <= c && c <= 'Z')
1741 || ('a' <= c && c <= 'z'));
1742}
1743
1744// Read error count from Summary or Extended Comprehensive SMART error log
1745// Return -1 on error
1746static int read_ata_error_count(ata_device * device, const char * name,
1747 firmwarebug_defs firmwarebugs, bool extended)
1748{
1749 if (!extended) {
1751 if (ataReadErrorLog(device, &log, firmwarebugs)){
1752 PrintOut(LOG_INFO,"Device: %s, Read Summary SMART Error Log failed\n",name);
1753 return -1;
1754 }
1755 return (log.error_log_pointer ? log.ata_error_count : 0);
1756 }
1757 else {
1759 if (!ataReadExtErrorLog(device, &logx, 0, 1 /*first sector only*/, firmwarebugs)) {
1760 PrintOut(LOG_INFO,"Device: %s, Read Extended Comprehensive SMART Error Log failed\n",name);
1761 return -1;
1762 }
1763 // Some disks use the reserved byte as index, see ataprint.cpp.
1764 return (logx.error_log_index || logx.reserved1 ? logx.device_error_count : 0);
1765 }
1766}
1767
1768// Count error entries in ATA self-test log, set HOUR to power on hours of most
1769// recent error. Return error count or -1 on failure.
1770static int check_ata_self_test_log(ata_device * device, const char * name,
1771 firmwarebug_defs firmwarebugs,
1772 unsigned & hour)
1773{
1774 struct ata_smart_selftestlog log;
1775
1776 hour = 0;
1777 if (ataReadSelfTestLog(device, &log, firmwarebugs)){
1778 PrintOut(LOG_INFO,"Device: %s, Read SMART Self Test Log Failed\n",name);
1779 return -1;
1780 }
1781
1782 if (!log.mostrecenttest)
1783 // No tests logged
1784 return 0;
1785
1786 // Count failed self-tests
1787 int errcnt = 0;
1788 for (int i = 20; i >= 0; i--) {
1789 int j = (i + log.mostrecenttest) % 21;
1791 if (!nonempty(&entry, sizeof(entry)))
1792 continue;
1793
1794 int status = entry.selfteststatus >> 4;
1795 if (status == 0x0 && (entry.selftestnumber & 0x7f) == 0x02)
1796 // First successful extended self-test, stop count
1797 break;
1798
1799 if (0x3 <= status && status <= 0x8) {
1800 // Self-test showed an error
1801 errcnt++;
1802 // Keep track of time of most recent error
1803 if (!hour)
1804 hour = entry.timestamp;
1805 }
1806 }
1807
1808 return errcnt;
1809}
1810
1811// Check offline data collection status
1812static inline bool is_offl_coll_in_progress(unsigned char status)
1813{
1814 return ((status & 0x7f) == 0x03);
1815}
1816
1817// Check self-test execution status
1818static inline bool is_self_test_in_progress(unsigned char status)
1819{
1820 return ((status >> 4) == 0xf);
1821}
1822
1823// Log offline data collection status
1824static void log_offline_data_coll_status(const char * name, unsigned char status)
1825{
1826 const char * msg;
1827 switch (status & 0x7f) {
1828 case 0x00: msg = "was never started"; break;
1829 case 0x02: msg = "was completed without error"; break;
1830 case 0x03: msg = "is in progress"; break;
1831 case 0x04: msg = "was suspended by an interrupting command from host"; break;
1832 case 0x05: msg = "was aborted by an interrupting command from host"; break;
1833 case 0x06: msg = "was aborted by the device with a fatal error"; break;
1834 default: msg = nullptr;
1835 }
1836
1837 if (msg)
1838 PrintOut(((status & 0x7f) == 0x06 ? LOG_CRIT : LOG_INFO),
1839 "Device: %s, offline data collection %s%s\n", name, msg,
1840 ((status & 0x80) ? " (auto:on)" : ""));
1841 else
1842 PrintOut(LOG_INFO, "Device: %s, unknown offline data collection status 0x%02x\n",
1843 name, status);
1844}
1845
1846// Log self-test execution status
1847static void log_self_test_exec_status(const char * name, unsigned char status)
1848{
1849 const char * msg;
1850 switch (status >> 4) {
1851 case 0x0: msg = "completed without error"; break;
1852 case 0x1: msg = "was aborted by the host"; break;
1853 case 0x2: msg = "was interrupted by the host with a reset"; break;
1854 case 0x3: msg = "could not complete due to a fatal or unknown error"; break;
1855 case 0x4: msg = "completed with error (unknown test element)"; break;
1856 case 0x5: msg = "completed with error (electrical test element)"; break;
1857 case 0x6: msg = "completed with error (servo/seek test element)"; break;
1858 case 0x7: msg = "completed with error (read test element)"; break;
1859 case 0x8: msg = "completed with error (handling damage?)"; break;
1860 default: msg = nullptr;
1861 }
1862
1863 if (msg)
1864 PrintOut(((status >> 4) >= 0x4 ? LOG_CRIT : LOG_INFO),
1865 "Device: %s, previous self-test %s\n", name, msg);
1866 else if ((status >> 4) == 0xf)
1867 PrintOut(LOG_INFO, "Device: %s, self-test in progress, %u0%% remaining\n",
1868 name, status & 0x0f);
1869 else
1870 PrintOut(LOG_INFO, "Device: %s, unknown self-test status 0x%02x\n",
1871 name, status);
1872}
1873
1874// Check pending sector count id (-C, -U directives).
1875static bool check_pending_id(const dev_config & cfg, const dev_state & state,
1876 unsigned char id, const char * msg)
1877{
1878 // Check attribute index
1879 int i = ata_find_attr_index(id, state.smartval);
1880 if (i < 0) {
1881 PrintOut(LOG_INFO, "Device: %s, can't monitor %s count - no Attribute %d\n",
1882 cfg.name.c_str(), msg, id);
1883 return false;
1884 }
1885
1886 // Check value
1887 uint64_t rawval = ata_get_attr_raw_value(state.smartval.vendor_attributes[i],
1888 cfg.attribute_defs);
1889 if (rawval >= (state.num_sectors ? state.num_sectors : 0xffffffffULL)) {
1890 PrintOut(LOG_INFO, "Device: %s, ignoring %s count - bogus Attribute %d value %" PRIu64 " (0x%" PRIx64 ")\n",
1891 cfg.name.c_str(), msg, id, rawval, rawval);
1892 return false;
1893 }
1894
1895 return true;
1896}
1897
1898// Called by ATA/SCSI/NVMeDeviceScan() after successful device check
1899static void finish_device_scan(dev_config & cfg, dev_state & state)
1900{
1901 // Set cfg.emailfreq if user hasn't set it
1902 if ((!cfg.emailaddress.empty() || !cfg.emailcmdline.empty()) && cfg.emailfreq == emailfreqs::unknown) {
1903 // Avoid that emails are suppressed forever due to state persistence
1904 if (cfg.state_file.empty())
1906 else
1908 }
1909
1910 // Start self-test regex check now if time was not read from state file
1911 if (!cfg.test_regex.empty() && !state.scheduled_test_next_check)
1912 state.scheduled_test_next_check = time(nullptr);
1913}
1914
1915// Common function to format result message for ATA setting
1916static void format_set_result_msg(std::string & msg, const char * name, bool ok,
1917 int set_option = 0, bool has_value = false)
1918{
1919 if (!msg.empty())
1920 msg += ", ";
1921 msg += name;
1922 if (!ok)
1923 msg += ":--";
1924 else if (set_option < 0)
1925 msg += ":off";
1926 else if (has_value)
1927 msg += strprintf(":%d", set_option-1);
1928 else if (set_option > 0)
1929 msg += ":on";
1930}
1931
1932// Return true and print message if CFG.dev_idinfo is already in PREV_CFGS
1933static bool is_duplicate_dev_idinfo(const dev_config & cfg, const dev_config_vector & prev_cfgs)
1934{
1935 if (!cfg.id_is_unique)
1936 return false;
1937
1938 for (const auto & prev_cfg : prev_cfgs) {
1939 if (!prev_cfg.id_is_unique)
1940 continue;
1941 if (!( cfg.dev_idinfo == prev_cfg.dev_idinfo
1942 // Also check identity without NSID if device does not support multiple namespaces
1943 || (!cfg.dev_idinfo_bc.empty() && cfg.dev_idinfo_bc == prev_cfg.dev_idinfo)
1944 || (!prev_cfg.dev_idinfo_bc.empty() && cfg.dev_idinfo == prev_cfg.dev_idinfo_bc)))
1945 continue;
1946
1947 PrintOut(LOG_INFO, "Device: %s, same identity as %s, ignored\n",
1948 cfg.dev_name.c_str(), prev_cfg.dev_name.c_str());
1949 return true;
1950 }
1951
1952 return false;
1953}
1954
1955// TODO: Add '-F swapid' directive
1956const bool fix_swapped_id = false;
1957
1958// scan to see what ata devices there are, and if they support SMART
1959static int ATADeviceScan(dev_config & cfg, dev_state & state, ata_device * atadev,
1960 const dev_config_vector * prev_cfgs)
1961{
1962 int supported=0;
1963 struct ata_identify_device drive;
1964 const char *name = cfg.name.c_str();
1965 int retid;
1966
1967 // Device must be open
1968
1969 // Get drive identity structure
1970 if ((retid = ata_read_identity(atadev, &drive, fix_swapped_id))) {
1971 if (retid<0)
1972 // Unable to read Identity structure
1973 PrintOut(LOG_INFO,"Device: %s, not ATA, no IDENTIFY DEVICE Structure\n",name);
1974 else
1975 PrintOut(LOG_INFO,"Device: %s, packet devices [this device %s] not SMART capable\n",
1976 name, packetdevicetype(retid-1));
1977 CloseDevice(atadev, name);
1978 return 2;
1979 }
1980
1981 // Get drive identity, size and rotation rate (HDD/SSD)
1982 char model[40+1], serial[20+1], firmware[8+1];
1983 ata_format_id_string(model, drive.model, sizeof(model)-1);
1984 ata_format_id_string(serial, drive.serial_no, sizeof(serial)-1);
1985 ata_format_id_string(firmware, drive.fw_rev, sizeof(firmware)-1);
1986
1987 ata_size_info sizes;
1988 ata_get_size_info(&drive, sizes);
1989 state.num_sectors = sizes.sectors;
1990 cfg.dev_rpm = ata_get_rotation_rate(&drive);
1991
1992 char wwn[64]; wwn[0] = 0;
1993 unsigned oui = 0; uint64_t unique_id = 0;
1994 int naa = ata_get_wwn(&drive, oui, unique_id);
1995 if (naa >= 0)
1996 snprintf(wwn, sizeof(wwn), "WWN:%x-%06x-%09" PRIx64 ", ", naa, oui, unique_id);
1997
1998 // Format device id string for warning emails
1999 char cap[32];
2000 cfg.dev_idinfo = strprintf("%s, S/N:%s, %sFW:%s, %s", model, serial, wwn, firmware,
2001 format_capacity(cap, sizeof(cap), sizes.capacity, "."));
2002 cfg.id_is_unique = true; // TODO: Check serial?
2004 cfg.id_is_unique = false;
2005
2006 PrintOut(LOG_INFO, "Device: %s, %s\n", name, cfg.dev_idinfo.c_str());
2007
2008 // Check for duplicates
2009 if (prev_cfgs && is_duplicate_dev_idinfo(cfg, *prev_cfgs)) {
2010 CloseDevice(atadev, name);
2011 return 1;
2012 }
2013
2014 // Show if device in database, and use preset vendor attribute
2015 // options unless user has requested otherwise.
2016 if (cfg.ignorepresets)
2017 PrintOut(LOG_INFO, "Device: %s, smartd database not searched (Directive: -P ignore).\n", name);
2018 else {
2019 // Apply vendor specific presets, print warning if present
2020 std::string dbversion;
2022 &drive, cfg.attribute_defs, cfg.firmwarebugs, dbversion);
2023 if (!dbentry)
2024 PrintOut(LOG_INFO, "Device: %s, not found in smartd database%s%s.\n", name,
2025 (!dbversion.empty() ? " " : ""), (!dbversion.empty() ? dbversion.c_str() : ""));
2026 else {
2027 PrintOut(LOG_INFO, "Device: %s, found in smartd database%s%s%s%s\n",
2028 name, (!dbversion.empty() ? " " : ""), (!dbversion.empty() ? dbversion.c_str() : ""),
2029 (*dbentry->modelfamily ? ": " : "."), (*dbentry->modelfamily ? dbentry->modelfamily : ""));
2030 if (*dbentry->warningmsg)
2031 PrintOut(LOG_CRIT, "Device: %s, WARNING: %s\n", name, dbentry->warningmsg);
2032 }
2033 }
2034
2035 // Check for ATA Security LOCK
2036 unsigned short word128 = drive.words088_255[128-88];
2037 bool locked = ((word128 & 0x0007) == 0x0007); // LOCKED|ENABLED|SUPPORTED
2038 if (locked)
2039 PrintOut(LOG_INFO, "Device: %s, ATA Security is **LOCKED**\n", name);
2040
2041 // Set default '-C 197[+]' if no '-C ID' is specified.
2042 if (!cfg.curr_pending_set)
2044 // Set default '-U 198[+]' if no '-U ID' is specified.
2045 if (!cfg.offl_pending_set)
2047
2048 // If requested, show which presets would be used for this drive
2049 if (cfg.showpresets) {
2050 int savedebugmode=debugmode;
2051 PrintOut(LOG_INFO, "Device %s: presets are:\n", name);
2052 if (!debugmode)
2053 debugmode=2;
2054 show_presets(&drive);
2055 debugmode=savedebugmode;
2056 }
2057
2058 // see if drive supports SMART
2059 supported=ataSmartSupport(&drive);
2060 if (supported!=1) {
2061 if (supported==0)
2062 // drive does NOT support SMART
2063 PrintOut(LOG_INFO,"Device: %s, lacks SMART capability\n",name);
2064 else
2065 // can't tell if drive supports SMART
2066 PrintOut(LOG_INFO,"Device: %s, ATA IDENTIFY DEVICE words 82-83 don't specify if SMART capable.\n",name);
2067
2068 // should we proceed anyway?
2069 if (cfg.permissive) {
2070 PrintOut(LOG_INFO,"Device: %s, proceeding since '-T permissive' Directive given.\n",name);
2071 }
2072 else {
2073 PrintOut(LOG_INFO,"Device: %s, to proceed anyway, use '-T permissive' Directive.\n",name);
2074 CloseDevice(atadev, name);
2075 return 2;
2076 }
2077 }
2078
2079 if (ataEnableSmart(atadev)) {
2080 // Enable SMART command has failed
2081 PrintOut(LOG_INFO,"Device: %s, could not enable SMART capability\n",name);
2082
2083 if (ataIsSmartEnabled(&drive) <= 0) {
2084 if (!cfg.permissive) {
2085 PrintOut(LOG_INFO, "Device: %s, to proceed anyway, use '-T permissive' Directive.\n", name);
2086 CloseDevice(atadev, name);
2087 return 2;
2088 }
2089 PrintOut(LOG_INFO, "Device: %s, proceeding since '-T permissive' Directive given.\n", name);
2090 }
2091 else {
2092 PrintOut(LOG_INFO, "Device: %s, proceeding since SMART is already enabled\n", name);
2093 }
2094 }
2095
2096 // disable device attribute autosave...
2097 if (cfg.autosave==1) {
2098 if (ataDisableAutoSave(atadev))
2099 PrintOut(LOG_INFO,"Device: %s, could not disable SMART Attribute Autosave.\n",name);
2100 else
2101 PrintOut(LOG_INFO,"Device: %s, disabled SMART Attribute Autosave.\n",name);
2102 }
2103
2104 // or enable device attribute autosave
2105 if (cfg.autosave==2) {
2106 if (ataEnableAutoSave(atadev))
2107 PrintOut(LOG_INFO,"Device: %s, could not enable SMART Attribute Autosave.\n",name);
2108 else
2109 PrintOut(LOG_INFO,"Device: %s, enabled SMART Attribute Autosave.\n",name);
2110 }
2111
2112 // capability check: SMART status
2113 if (cfg.smartcheck && ataSmartStatus2(atadev) == -1) {
2114 PrintOut(LOG_INFO,"Device: %s, not capable of SMART Health Status check\n",name);
2115 cfg.smartcheck = false;
2116 }
2117
2118 // capability check: Read smart values and thresholds. Note that
2119 // smart values are ALSO needed even if we ONLY want to know if the
2120 // device is self-test log or error-log capable! After ATA-5, this
2121 // information was ALSO reproduced in the IDENTIFY DEVICE response,
2122 // but sadly not for ATA-5. Sigh.
2123
2124 // do we need to get SMART data?
2125 bool smart_val_ok = false;
2126 if ( cfg.autoofflinetest || cfg.selftest
2127 || cfg.errorlog || cfg.xerrorlog
2128 || cfg.offlinests || cfg.selfteststs
2129 || cfg.usagefailed || cfg.prefail || cfg.usage
2130 || cfg.tempdiff || cfg.tempinfo || cfg.tempcrit
2131 || cfg.curr_pending_id || cfg.offl_pending_id ) {
2132
2133 if (ataReadSmartValues(atadev, &state.smartval)) {
2134 PrintOut(LOG_INFO, "Device: %s, Read SMART Values failed\n", name);
2135 cfg.usagefailed = cfg.prefail = cfg.usage = false;
2136 cfg.tempdiff = cfg.tempinfo = cfg.tempcrit = 0;
2137 cfg.curr_pending_id = cfg.offl_pending_id = 0;
2138 }
2139 else {
2140 smart_val_ok = true;
2141 if (ataReadSmartThresholds(atadev, &state.smartthres)) {
2142 PrintOut(LOG_INFO, "Device: %s, Read SMART Thresholds failed%s\n",
2143 name, (cfg.usagefailed ? ", ignoring -f Directive" : ""));
2144 cfg.usagefailed = false;
2145 // Let ata_get_attr_state() return ATTRSTATE_NO_THRESHOLD:
2146 memset(&state.smartthres, 0, sizeof(state.smartthres));
2147 }
2148 }
2149
2150 // see if the necessary Attribute is there to monitor offline or
2151 // current pending sectors or temperature
2152 if ( cfg.curr_pending_id
2153 && !check_pending_id(cfg, state, cfg.curr_pending_id,
2154 "Current_Pending_Sector"))
2155 cfg.curr_pending_id = 0;
2156
2157 if ( cfg.offl_pending_id
2158 && !check_pending_id(cfg, state, cfg.offl_pending_id,
2159 "Offline_Uncorrectable"))
2160 cfg.offl_pending_id = 0;
2161
2162 if ( (cfg.tempdiff || cfg.tempinfo || cfg.tempcrit)
2164 PrintOut(LOG_INFO, "Device: %s, can't monitor Temperature, ignoring -W %d,%d,%d\n",
2165 name, cfg.tempdiff, cfg.tempinfo, cfg.tempcrit);
2166 cfg.tempdiff = cfg.tempinfo = cfg.tempcrit = 0;
2167 }
2168
2169 // Report ignored '-r' or '-R' directives
2170 for (int id = 1; id <= 255; id++) {
2172 char opt = (!cfg.monitor_attr_flags.is_set(id, MONITOR_RAW) ? 'r' : 'R');
2173 const char * excl = (cfg.monitor_attr_flags.is_set(id,
2174 (opt == 'r' ? MONITOR_AS_CRIT : MONITOR_RAW_AS_CRIT)) ? "!" : "");
2175
2176 int idx = ata_find_attr_index(id, state.smartval);
2177 if (idx < 0)
2178 PrintOut(LOG_INFO,"Device: %s, no Attribute %d, ignoring -%c %d%s\n", name, id, opt, id, excl);
2179 else {
2180 bool prefail = !!ATTRIBUTE_FLAGS_PREFAILURE(state.smartval.vendor_attributes[idx].flags);
2181 if (!((prefail && cfg.prefail) || (!prefail && cfg.usage)))
2182 PrintOut(LOG_INFO,"Device: %s, not monitoring %s Attributes, ignoring -%c %d%s\n", name,
2183 (prefail ? "Prefailure" : "Usage"), opt, id, excl);
2184 }
2185 }
2186 }
2187 }
2188
2189 // enable/disable automatic on-line testing
2190 if (cfg.autoofflinetest) {
2191 // is this an enable or disable request?
2192 const char *what=(cfg.autoofflinetest==1)?"disable":"enable";
2193 if (!smart_val_ok)
2194 PrintOut(LOG_INFO,"Device: %s, could not %s SMART Automatic Offline Testing.\n",name, what);
2195 else {
2196 // if command appears unsupported, issue a warning...
2197 if (!isSupportAutomaticTimer(&state.smartval))
2198 PrintOut(LOG_INFO,"Device: %s, SMART Automatic Offline Testing unsupported...\n",name);
2199 // ... but then try anyway
2200 if ((cfg.autoofflinetest==1)?ataDisableAutoOffline(atadev):ataEnableAutoOffline(atadev))
2201 PrintOut(LOG_INFO,"Device: %s, %s SMART Automatic Offline Testing failed.\n", name, what);
2202 else
2203 PrintOut(LOG_INFO,"Device: %s, %sd SMART Automatic Offline Testing.\n", name, what);
2204 }
2205 }
2206
2207 // Read log directories if required for capability check
2208 ata_smart_log_directory smart_logdir, gp_logdir;
2209 bool smart_logdir_ok = false, gp_logdir_ok = false;
2210
2212 && (cfg.errorlog || cfg.selftest)
2213 && !cfg.firmwarebugs.is_set(BUG_NOLOGDIR)) {
2214 if (!ataReadLogDirectory(atadev, &smart_logdir, false))
2215 smart_logdir_ok = true;
2216 }
2217
2218 if (cfg.xerrorlog && !cfg.firmwarebugs.is_set(BUG_NOLOGDIR)) {
2219 if (!ataReadLogDirectory(atadev, &gp_logdir, true))
2220 gp_logdir_ok = true;
2221 }
2222
2223 // capability check: self-test-log
2224 state.selflogcount = 0; state.selfloghour = 0;
2225 if (cfg.selftest) {
2226 int errcnt = 0; unsigned hour = 0;
2227 if (!( cfg.permissive
2228 || ( smart_logdir_ok && smart_logdir.entry[0x06-1].numsectors)
2229 || (!smart_logdir_ok && smart_val_ok && isSmartTestLogCapable(&state.smartval, &drive)))) {
2230 PrintOut(LOG_INFO, "Device: %s, no SMART Self-test Log, ignoring -l selftest (override with -T permissive)\n", name);
2231 cfg.selftest = false;
2232 }
2233 else if ((errcnt = check_ata_self_test_log(atadev, name, cfg.firmwarebugs, hour)) < 0) {
2234 PrintOut(LOG_INFO, "Device: %s, no SMART Self-test Log, ignoring -l selftest\n", name);
2235 cfg.selftest = false;
2236 }
2237 else {
2238 state.selflogcount = (unsigned char)errcnt;
2239 state.selfloghour = hour;
2240 }
2241 }
2242
2243 // capability check: ATA error log
2244 state.ataerrorcount = 0;
2245 if (cfg.errorlog) {
2246 int errcnt1;
2247 if (!( cfg.permissive
2248 || ( smart_logdir_ok && smart_logdir.entry[0x01-1].numsectors)
2249 || (!smart_logdir_ok && smart_val_ok && isSmartErrorLogCapable(&state.smartval, &drive)))) {
2250 PrintOut(LOG_INFO, "Device: %s, no SMART Error Log, ignoring -l error (override with -T permissive)\n", name);
2251 cfg.errorlog = false;
2252 }
2253 else if ((errcnt1 = read_ata_error_count(atadev, name, cfg.firmwarebugs, false)) < 0) {
2254 PrintOut(LOG_INFO, "Device: %s, no SMART Error Log, ignoring -l error\n", name);
2255 cfg.errorlog = false;
2256 }
2257 else
2258 state.ataerrorcount = errcnt1;
2259 }
2260
2261 if (cfg.xerrorlog) {
2262 int errcnt2;
2263 if (!( cfg.permissive || cfg.firmwarebugs.is_set(BUG_NOLOGDIR)
2264 || (gp_logdir_ok && gp_logdir.entry[0x03-1].numsectors) )) {
2265 PrintOut(LOG_INFO, "Device: %s, no Extended Comprehensive SMART Error Log, ignoring -l xerror (override with -T permissive)\n",
2266 name);
2267 cfg.xerrorlog = false;
2268 }
2269 else if ((errcnt2 = read_ata_error_count(atadev, name, cfg.firmwarebugs, true)) < 0) {
2270 PrintOut(LOG_INFO, "Device: %s, no Extended Comprehensive SMART Error Log, ignoring -l xerror\n", name);
2271 cfg.xerrorlog = false;
2272 }
2273 else if (cfg.errorlog && state.ataerrorcount != errcnt2) {
2274 PrintOut(LOG_INFO, "Device: %s, SMART Error Logs report different error counts: %d != %d\n",
2275 name, state.ataerrorcount, errcnt2);
2276 // Record max error count
2277 if (errcnt2 > state.ataerrorcount)
2278 state.ataerrorcount = errcnt2;
2279 }
2280 else
2281 state.ataerrorcount = errcnt2;
2282 }
2283
2284 // capability check: self-test and offline data collection status
2285 if (cfg.offlinests || cfg.selfteststs) {
2286 if (!(cfg.permissive || (smart_val_ok && state.smartval.offline_data_collection_capability))) {
2287 if (cfg.offlinests)
2288 PrintOut(LOG_INFO, "Device: %s, no SMART Offline Data Collection capability, ignoring -l offlinests (override with -T permissive)\n", name);
2289 if (cfg.selfteststs)
2290 PrintOut(LOG_INFO, "Device: %s, no SMART Self-test capability, ignoring -l selfteststs (override with -T permissive)\n", name);
2291 cfg.offlinests = cfg.selfteststs = false;
2292 }
2293 }
2294
2295 // capabilities check -- does it support powermode?
2296 if (cfg.powermode) {
2297 int powermode = ataCheckPowerMode(atadev);
2298
2299 if (-1 == powermode) {
2300 PrintOut(LOG_CRIT, "Device: %s, no ATA CHECK POWER STATUS support, ignoring -n Directive\n", name);
2301 cfg.powermode=0;
2302 }
2303 else if (powermode!=0x00 && powermode!=0x01
2304 && powermode!=0x40 && powermode!=0x41
2305 && powermode!=0x80 && powermode!=0x81 && powermode!=0x82 && powermode!=0x83
2306 && powermode!=0xff) {
2307 PrintOut(LOG_CRIT, "Device: %s, CHECK POWER STATUS returned %d, not ATA compliant, ignoring -n Directive\n",
2308 name, powermode);
2309 cfg.powermode=0;
2310 }
2311 }
2312
2313 // Apply ATA settings
2314 std::string msg;
2315
2316 if (cfg.set_aam)
2317 format_set_result_msg(msg, "AAM", (cfg.set_aam > 0 ?
2318 ata_set_features(atadev, ATA_ENABLE_AAM, cfg.set_aam-1) :
2319 ata_set_features(atadev, ATA_DISABLE_AAM)), cfg.set_aam, true);
2320
2321 if (cfg.set_apm)
2322 format_set_result_msg(msg, "APM", (cfg.set_apm > 0 ?
2323 ata_set_features(atadev, ATA_ENABLE_APM, cfg.set_apm-1) :
2324 ata_set_features(atadev, ATA_DISABLE_APM)), cfg.set_apm, true);
2325
2326 if (cfg.set_lookahead)
2327 format_set_result_msg(msg, "Rd-ahead", ata_set_features(atadev,
2329 cfg.set_lookahead);
2330
2331 if (cfg.set_wcache)
2332 format_set_result_msg(msg, "Wr-cache", ata_set_features(atadev,
2334
2335 if (cfg.set_dsn)
2336 format_set_result_msg(msg, "DSN", ata_set_features(atadev,
2337 ATA_ENABLE_DISABLE_DSN, (cfg.set_dsn > 0 ? 0x1 : 0x2)));
2338
2339 if (cfg.set_security_freeze)
2340 format_set_result_msg(msg, "Security freeze",
2342
2343 if (cfg.set_standby)
2344 format_set_result_msg(msg, "Standby",
2345 ata_nodata_command(atadev, ATA_IDLE, cfg.set_standby-1), cfg.set_standby, true);
2346
2347 // Report as one log entry
2348 if (!msg.empty())
2349 PrintOut(LOG_INFO, "Device: %s, ATA settings applied: %s\n", name, msg.c_str());
2350
2351 // set SCT Error Recovery Control if requested
2352 if (cfg.sct_erc_set) {
2354 PrintOut(LOG_INFO, "Device: %s, no SCT Error Recovery Control support, ignoring -l scterc\n",
2355 name);
2356 else if (locked)
2357 PrintOut(LOG_INFO, "Device: %s, no SCT support if ATA Security is LOCKED, ignoring -l scterc\n",
2358 name);
2359 else if ( ataSetSCTErrorRecoveryControltime(atadev, 1, cfg.sct_erc_readtime, false, false )
2360 || ataSetSCTErrorRecoveryControltime(atadev, 2, cfg.sct_erc_writetime, false, false))
2361 PrintOut(LOG_INFO, "Device: %s, set of SCT Error Recovery Control failed\n", name);
2362 else
2363 PrintOut(LOG_INFO, "Device: %s, SCT Error Recovery Control set to: Read: %u, Write: %u\n",
2364 name, cfg.sct_erc_readtime, cfg.sct_erc_writetime);
2365 }
2366
2367 // If no tests available or selected, return
2368 if (!( cfg.smartcheck || cfg.selftest
2369 || cfg.errorlog || cfg.xerrorlog
2370 || cfg.offlinests || cfg.selfteststs
2371 || cfg.usagefailed || cfg.prefail || cfg.usage
2372 || cfg.tempdiff || cfg.tempinfo || cfg.tempcrit)) {
2373 CloseDevice(atadev, name);
2374 return 3;
2375 }
2376
2377 // tell user we are registering device
2378 PrintOut(LOG_INFO,"Device: %s, is SMART capable. Adding to \"monitor\" list.\n",name);
2379
2380 // close file descriptor
2381 CloseDevice(atadev, name);
2382
2383 if (!state_path_prefix.empty() || !attrlog_path_prefix.empty()) {
2384 // Build file name for state file
2385 std::replace_if(model, model+strlen(model), not_allowed_in_filename, '_');
2386 std::replace_if(serial, serial+strlen(serial), not_allowed_in_filename, '_');
2387 if (!state_path_prefix.empty()) {
2388 cfg.state_file = strprintf("%s%s-%s.ata.state", state_path_prefix.c_str(), model, serial);
2389 // Read previous state
2390 if (read_dev_state(cfg.state_file.c_str(), state)) {
2391 PrintOut(LOG_INFO, "Device: %s, state read from %s\n", name, cfg.state_file.c_str());
2392 // Copy ATA attribute values to temp state
2393 state.update_temp_state();
2394 }
2395 }
2396 if (!attrlog_path_prefix.empty())
2397 cfg.attrlog_file = strprintf("%s%s-%s.ata.csv", attrlog_path_prefix.c_str(), model, serial);
2398 }
2399
2400 finish_device_scan(cfg, state);
2401
2402 return 0;
2403}
2404
2405// on success, return 0. On failure, return >0. Never return <0,
2406// please.
2407static int SCSIDeviceScan(dev_config & cfg, dev_state & state, scsi_device * scsidev,
2408 const dev_config_vector * prev_cfgs)
2409{
2410 int err, req_len, avail_len, version, len;
2411 const char *device = cfg.name.c_str();
2412 struct scsi_iec_mode_page iec;
2413 uint8_t tBuf[64];
2414 uint8_t inqBuf[96];
2415 uint8_t vpdBuf[252];
2416 char lu_id[64], serial[256], vendor[40], model[40];
2417
2418 // Device must be open
2419 memset(inqBuf, 0, 96);
2420 req_len = 36;
2421 if ((err = scsiStdInquiry(scsidev, inqBuf, req_len))) {
2422 /* Marvell controllers fail on a 36 bytes StdInquiry, but 64 suffices */
2423 req_len = 64;
2424 int err64;
2425 if ((err64 = scsiStdInquiry(scsidev, inqBuf, req_len))) {
2426 PrintOut(LOG_INFO, "Device: %s, Both 36 and 64 byte INQUIRY failed; "
2427 "skip device [err=%d, %d]\n", device, err, err64);
2428 return 2;
2429 }
2430 }
2431 version = (inqBuf[2] & 0x7f); /* Accept old ISO/IEC 9316:1995 variants */
2432
2433 avail_len = inqBuf[4] + 5;
2434 len = (avail_len < req_len) ? avail_len : req_len;
2435 if (len < 36) {
2436 PrintOut(LOG_INFO, "Device: %s, INQUIRY response less than 36 bytes; "
2437 "skip device\n", device);
2438 return 2;
2439 }
2440
2441 int pdt = inqBuf[0] & 0x1f;
2442
2443 switch (pdt) {
2445 case SCSI_PT_WO:
2446 case SCSI_PT_CDROM:
2447 case SCSI_PT_OPTICAL:
2448 case SCSI_PT_RBC: /* Reduced Block commands */
2449 case SCSI_PT_HOST_MANAGED: /* Zoned disk */
2450 break;
2451 default:
2452 PrintOut(LOG_INFO, "Device: %s, not a disk like device [PDT=0x%x], "
2453 "skip\n", device, pdt);
2454 return 2;
2455 }
2456
2458 delete supported_vpd_pages_p;
2459 supported_vpd_pages_p = nullptr;
2460 }
2462
2463 lu_id[0] = '\0';
2464 if (version >= 0x3) {
2465 /* SPC to SPC-5, assume SPC-6 is version==8 or higher */
2467 vpdBuf, sizeof(vpdBuf))) {
2468 len = vpdBuf[3];
2469 scsi_decode_lu_dev_id(vpdBuf + 4, len, lu_id, sizeof(lu_id), nullptr);
2470 }
2471 }
2472 serial[0] = '\0';
2474 vpdBuf, sizeof(vpdBuf))) {
2475 len = vpdBuf[3];
2476 vpdBuf[4 + len] = '\0';
2477 scsi_format_id_string(serial, &vpdBuf[4], len);
2478 }
2479
2480 char si_str[64];
2481 struct scsi_readcap_resp srr;
2482 uint64_t capacity = scsiGetSize(scsidev, scsidev->use_rcap16(), &srr);
2483
2484 if (capacity)
2485 format_capacity(si_str, sizeof(si_str), capacity, ".");
2486 else
2487 si_str[0] = '\0';
2488
2489 // Format device id string for warning emails
2490 cfg.dev_idinfo = strprintf("[%.8s %.16s %.4s]%s%s%s%s%s%s",
2491 (char *)&inqBuf[8], (char *)&inqBuf[16], (char *)&inqBuf[32],
2492 (lu_id[0] ? ", lu id: " : ""), (lu_id[0] ? lu_id : ""),
2493 (serial[0] ? ", S/N: " : ""), (serial[0] ? serial : ""),
2494 (si_str[0] ? ", " : ""), (si_str[0] ? si_str : ""));
2495 cfg.id_is_unique = (lu_id[0] || serial[0]);
2497 cfg.id_is_unique = false;
2498
2499 // format "model" string
2500 scsi_format_id_string(vendor, &inqBuf[8], 8);
2501 scsi_format_id_string(model, &inqBuf[16], 16);
2502 PrintOut(LOG_INFO, "Device: %s, %s\n", device, cfg.dev_idinfo.c_str());
2503
2504 // Check for duplicates
2505 if (prev_cfgs && is_duplicate_dev_idinfo(cfg, *prev_cfgs)) {
2506 CloseDevice(scsidev, device);
2507 return 1;
2508 }
2509
2510 // check that device is ready for commands. IE stores its stuff on
2511 // the media.
2512 if ((err = scsiTestUnitReady(scsidev))) {
2513 if (SIMPLE_ERR_NOT_READY == err)
2514 PrintOut(LOG_INFO, "Device: %s, NOT READY (e.g. spun down); skip device\n", device);
2515 else if (SIMPLE_ERR_NO_MEDIUM == err)
2516 PrintOut(LOG_INFO, "Device: %s, NO MEDIUM present; skip device\n", device);
2517 else if (SIMPLE_ERR_BECOMING_READY == err)
2518 PrintOut(LOG_INFO, "Device: %s, BECOMING (but not yet) READY; skip device\n", device);
2519 else
2520 PrintOut(LOG_CRIT, "Device: %s, failed Test Unit Ready [err=%d]\n", device, err);
2521 CloseDevice(scsidev, device);
2522 return 2;
2523 }
2524
2525 // Badly-conforming USB storage devices may fail this check.
2526 // The response to the following IE mode page fetch (current and
2527 // changeable values) is carefully examined. It has been found
2528 // that various USB devices that malform the response will lock up
2529 // if asked for a log page (e.g. temperature) so it is best to
2530 // bail out now.
2531 if (!(err = scsiFetchIECmpage(scsidev, &iec, state.modese_len)))
2532 state.modese_len = iec.modese_len;
2533 else if (SIMPLE_ERR_BAD_FIELD == err)
2534 ; /* continue since it is reasonable not to support IE mpage */
2535 else { /* any other error (including malformed response) unreasonable */
2536 PrintOut(LOG_INFO,
2537 "Device: %s, Bad IEC (SMART) mode page, err=%d, skip device\n",
2538 device, err);
2539 CloseDevice(scsidev, device);
2540 return 3;
2541 }
2542
2543 // N.B. The following is passive (i.e. it doesn't attempt to turn on
2544 // smart if it is off). This may change to be the same as the ATA side.
2545 if (!scsi_IsExceptionControlEnabled(&iec)) {
2546 PrintOut(LOG_INFO, "Device: %s, IE (SMART) not enabled, skip device\n"
2547 "Try 'smartctl -s on %s' to turn on SMART features\n",
2548 device, device);
2549 CloseDevice(scsidev, device);
2550 return 3;
2551 }
2552
2553 // Flag that certain log pages are supported (information may be
2554 // available from other sources).
2555 if (0 == scsiLogSense(scsidev, SUPPORTED_LPAGES, 0, tBuf, sizeof(tBuf), 0) ||
2556 0 == scsiLogSense(scsidev, SUPPORTED_LPAGES, 0, tBuf, sizeof(tBuf), 68))
2557 /* workaround for the bug #678 on ST8000NM0075/E001. Up to 64 pages + 4b header */
2558 {
2559 for (int k = 4; k < tBuf[3] + LOGPAGEHDRSIZE; ++k) {
2560 switch (tBuf[k]) {
2561 case TEMPERATURE_LPAGE:
2562 state.TempPageSupported = 1;
2563 break;
2564 case IE_LPAGE:
2565 state.SmartPageSupported = 1;
2566 break;
2568 state.ReadECounterPageSupported = 1;
2569 break;
2572 break;
2575 break;
2578 break;
2579 default:
2580 break;
2581 }
2582 }
2583 }
2584
2585 // Check if scsiCheckIE() is going to work
2586 {
2587 uint8_t asc = 0;
2588 uint8_t ascq = 0;
2589 uint8_t currenttemp = 0;
2590 uint8_t triptemp = 0;
2591
2592 if (scsiCheckIE(scsidev, state.SmartPageSupported, state.TempPageSupported,
2593 &asc, &ascq, &currenttemp, &triptemp)) {
2594 PrintOut(LOG_INFO, "Device: %s, unexpectedly failed to read SMART values\n", device);
2595 state.SuppressReport = 1;
2596 }
2597 if ( (state.SuppressReport || !currenttemp)
2598 && (cfg.tempdiff || cfg.tempinfo || cfg.tempcrit)) {
2599 PrintOut(LOG_INFO, "Device: %s, can't monitor Temperature, ignoring -W %d,%d,%d\n",
2600 device, cfg.tempdiff, cfg.tempinfo, cfg.tempcrit);
2601 cfg.tempdiff = cfg.tempinfo = cfg.tempcrit = 0;
2602 }
2603 }
2604
2605 // capability check: self-test-log
2606 if (cfg.selftest){
2607 int retval = scsiCountFailedSelfTests(scsidev, 0);
2608 if (retval<0) {
2609 // no self-test log, turn off monitoring
2610 PrintOut(LOG_INFO, "Device: %s, does not support SMART Self-Test Log.\n", device);
2611 cfg.selftest = false;
2612 state.selflogcount = 0;
2613 state.selfloghour = 0;
2614 }
2615 else {
2616 // register starting values to watch for changes
2617 state.selflogcount = retval & 0xff;
2618 state.selfloghour = (retval >> 8) & 0xffff;
2619 }
2620 }
2621
2622 // disable autosave (set GLTSD bit)
2623 if (cfg.autosave==1){
2624 if (scsiSetControlGLTSD(scsidev, 1, state.modese_len))
2625 PrintOut(LOG_INFO,"Device: %s, could not disable autosave (set GLTSD bit).\n",device);
2626 else
2627 PrintOut(LOG_INFO,"Device: %s, disabled autosave (set GLTSD bit).\n",device);
2628 }
2629
2630 // or enable autosave (clear GLTSD bit)
2631 if (cfg.autosave==2){
2632 if (scsiSetControlGLTSD(scsidev, 0, state.modese_len))
2633 PrintOut(LOG_INFO,"Device: %s, could not enable autosave (clear GLTSD bit).\n",device);
2634 else
2635 PrintOut(LOG_INFO,"Device: %s, enabled autosave (cleared GLTSD bit).\n",device);
2636 }
2637
2638 // tell user we are registering device
2639 PrintOut(LOG_INFO, "Device: %s, is SMART capable. Adding to \"monitor\" list.\n", device);
2640
2641 // Disable ATA specific self-tests
2642 state.not_cap_conveyance = state.not_cap_offline = state.not_cap_selective = true;
2643
2644 // Make sure that init_standby_check() ignores SCSI devices
2645 cfg.offlinests_ns = cfg.selfteststs_ns = false;
2646
2647 // close file descriptor
2648 CloseDevice(scsidev, device);
2649
2650 if (!state_path_prefix.empty() || !attrlog_path_prefix.empty()) {
2651 // Build file name for state file
2652 std::replace_if(model, model+strlen(model), not_allowed_in_filename, '_');
2653 std::replace_if(serial, serial+strlen(serial), not_allowed_in_filename, '_');
2654 if (!state_path_prefix.empty()) {
2655 cfg.state_file = strprintf("%s%s-%s-%s.scsi.state", state_path_prefix.c_str(), vendor, model, serial);
2656 // Read previous state
2657 if (read_dev_state(cfg.state_file.c_str(), state)) {
2658 PrintOut(LOG_INFO, "Device: %s, state read from %s\n", device, cfg.state_file.c_str());
2659 // Copy ATA attribute values to temp state
2660 state.update_temp_state();
2661 }
2662 }
2663 if (!attrlog_path_prefix.empty())
2664 cfg.attrlog_file = strprintf("%s%s-%s-%s.scsi.csv", attrlog_path_prefix.c_str(), vendor, model, serial);
2665 }
2666
2667 finish_device_scan(cfg, state);
2668
2669 return 0;
2670}
2671
2672// Convert 128 bit LE integer to uint64_t or its max value on overflow.
2673static uint64_t le128_to_uint64(const unsigned char (& val)[16])
2674{
2675 for (int i = 8; i < 16; i++) {
2676 if (val[i])
2677 return ~(uint64_t)0;
2678 }
2679 uint64_t lo = val[7];
2680 for (int i = 7-1; i >= 0; i--) {
2681 lo <<= 8; lo += val[i];
2682 }
2683 return lo;
2684}
2685
2686// Check the NVMe Error Information log for device related errors.
2687static bool check_nvme_error_log(const dev_config & cfg, dev_state & state, nvme_device * nvmedev,
2688 uint64_t newcnt = 0)
2689{
2690 // Limit transfer size to one page (64 entries) to avoid problems with
2691 // limits of NVMe pass-through layer or too low MDTS values.
2692 unsigned want_entries = 64;
2693 if (want_entries > cfg.nvme_err_log_max_entries)
2694 want_entries = cfg.nvme_err_log_max_entries;
2695 raw_buffer error_log_buf(want_entries * sizeof(nvme_error_log_page));
2696 nvme_error_log_page * error_log =
2697 reinterpret_cast<nvme_error_log_page *>(error_log_buf.data());
2698 unsigned read_entries = nvme_read_error_log(nvmedev, error_log, want_entries, false /*!lpo_sup*/);
2699 if (!read_entries) {
2700 PrintOut(LOG_INFO, "Device: %s, Read %u entries from Error Information Log failed\n",
2701 cfg.name.c_str(), want_entries);
2702 return false;
2703 }
2704
2705 if (!newcnt)
2706 return true; // Support check only
2707
2708 // Scan log, find device related errors
2709 uint64_t oldcnt = state.nvme_err_log_entries, mincnt = newcnt;
2710 int err = 0, ign = 0;
2711 for (unsigned i = 0; i < read_entries; i++) {
2712 const nvme_error_log_page & e = error_log[i];
2713 if (!e.error_count)
2714 continue; // unused
2715 if (e.error_count <= oldcnt)
2716 break; // stop on first old entry
2717 if (e.error_count < mincnt)
2718 mincnt = e.error_count; // min known error
2719 if (e.error_count > newcnt)
2720 newcnt = e.error_count; // adjust maximum
2721 uint16_t status = e.status_field >> 1;
2722 if (!nvme_status_is_error(status) || nvme_status_to_errno(status) == EINVAL) {
2723 ign++; // Not a device related error
2724 continue;
2725 }
2726
2727 // Log the most recent 8 errors
2728 if (++err > 8)
2729 continue;
2730 char buf[64];
2731 PrintOut(LOG_INFO, "Device: %s, NVMe error [%u], count %" PRIu64 ", status 0x%04x: %s\n",
2732 cfg.name.c_str(), i, e.error_count, e.status_field,
2734 }
2735
2736 std::string msg = strprintf("Device: %s, NVMe error count increased from %" PRIu64 " to %" PRIu64
2737 " (%d new, %d ignored, %" PRIu64 " unknown)",
2738 cfg.name.c_str(), oldcnt, newcnt, err, ign,
2739 (mincnt > oldcnt + 1 ? mincnt - oldcnt - 1 : 0));
2740 // LOG_CRIT only if device related errors are found
2741 if (!err) {
2742 PrintOut(LOG_INFO, "%s\n", msg.c_str());
2743 }
2744 else {
2745 PrintOut(LOG_CRIT, "%s\n", msg.c_str());
2746 MailWarning(cfg, state, 4, "%s", msg.c_str());
2747 }
2748
2749 state.nvme_err_log_entries = newcnt;
2750 state.must_write = true;
2751 return true;
2752}
2753
2754static int NVMeDeviceScan(dev_config & cfg, dev_state & state, nvme_device * nvmedev,
2755 const dev_config_vector * prev_cfgs)
2756{
2757 const char *name = cfg.name.c_str();
2758
2759 // Device must be open
2760
2761 // Get ID Controller
2762 nvme_id_ctrl id_ctrl;
2763 if (!nvme_read_id_ctrl(nvmedev, id_ctrl)) {
2764 PrintOut(LOG_INFO, "Device: %s, NVMe Identify Controller failed\n", name);
2765 CloseDevice(nvmedev, name);
2766 return 2;
2767 }
2768
2769 // Get drive identity
2770 char model[40+1], serial[20+1], firmware[8+1];
2771 format_char_array(model, id_ctrl.mn);
2772 format_char_array(serial, id_ctrl.sn);
2773 format_char_array(firmware, id_ctrl.fr);
2774
2775 // Format device id string for warning emails
2776 char nsstr[32] = "", capstr[32] = "";
2777 unsigned nsid = nvmedev->get_nsid();
2779 snprintf(nsstr, sizeof(nsstr), ", NSID:%u", nsid);
2780 uint64_t capacity = le128_to_uint64(id_ctrl.tnvmcap);
2781 if (capacity)
2782 format_capacity(capstr, sizeof(capstr), capacity, ".");
2783
2784 auto idinfo = &dev_config::dev_idinfo;
2785 for (;;) {
2786 cfg.*idinfo = strprintf("%s, S/N:%s, FW:%s%s%s%s", model, serial, firmware,
2787 nsstr, (capstr[0] ? ", " : ""), capstr);
2788 if (!(nsstr[0] && id_ctrl.nn == 1))
2789 break; // No namespace id or device supports multiple namespaces
2790 // Keep version without namespace id for 'is_duplicate_dev_idinfo()'
2791 nsstr[0] = 0;
2792 idinfo = &dev_config::dev_idinfo_bc;
2793 }
2794
2795 cfg.id_is_unique = true; // TODO: Check serial?
2797 cfg.id_is_unique = false;
2798
2799 PrintOut(LOG_INFO, "Device: %s, %s\n", name, cfg.dev_idinfo.c_str());
2800
2801 // Check for duplicates
2802 if (prev_cfgs && is_duplicate_dev_idinfo(cfg, *prev_cfgs)) {
2803 CloseDevice(nvmedev, name);
2804 return 1;
2805 }
2806
2807 // Read SMART/Health log
2808 // TODO: Support per namespace SMART/Health log
2809 nvme_smart_log smart_log;
2810 if (!nvme_read_smart_log(nvmedev, nvme_broadcast_nsid, smart_log)) {
2811 PrintOut(LOG_INFO, "Device: %s, failed to read NVMe SMART/Health Information\n", name);
2812 CloseDevice(nvmedev, name);
2813 return 2;
2814 }
2815
2816 // Check temperature sensor support
2817 if (cfg.tempdiff || cfg.tempinfo || cfg.tempcrit) {
2818 if (!sg_get_unaligned_le16(smart_log.temperature)) {
2819 PrintOut(LOG_INFO, "Device: %s, no Temperature sensors, ignoring -W %d,%d,%d\n",
2820 name, cfg.tempdiff, cfg.tempinfo, cfg.tempcrit);
2821 cfg.tempdiff = cfg.tempinfo = cfg.tempcrit = 0;
2822 }
2823 }
2824
2825 // Init total error count
2826 cfg.nvme_err_log_max_entries = id_ctrl.elpe + 1; // 0's based value
2827 if (cfg.errorlog || cfg.xerrorlog) {
2828 if (!check_nvme_error_log(cfg, state, nvmedev)) {
2829 PrintOut(LOG_INFO, "Device: %s, Error Information unavailable, ignoring -l [x]error\n", name);
2830 cfg.errorlog = cfg.xerrorlog = false;
2831 }
2832 else
2834 }
2835
2836 // Check for self-test support
2837 state.not_cap_short = state.not_cap_long = !(id_ctrl.oacs & 0x0010);
2838 state.selflogcount = 0; state.selfloghour = 0;
2839 if (cfg.selftest || cfg.selfteststs || !cfg.test_regex.empty()) {
2840 nvme_self_test_log self_test_log;
2841 if ( !state.not_cap_short
2842 && !nvme_read_self_test_log(nvmedev, nvme_broadcast_nsid, self_test_log)) {
2843 PrintOut(LOG_INFO, "Device: %s, Read NVMe Self-test Log failed: %s\n", name,
2844 nvmedev->get_errmsg());
2845 state.not_cap_short = state.not_cap_long = true;
2846 }
2847 if (state.not_cap_short) {
2848 PrintOut(LOG_INFO, "Device: %s, does not support NVMe Self-tests, ignoring%s%s%s%s\n", name,
2849 (cfg.selftest ? " -l selftest" : ""),
2850 (cfg.selfteststs ? " -l selfteststs" : ""),
2851 (!cfg.test_regex.empty() ? " -s " : ""), cfg.test_regex.get_pattern());
2852 cfg.selftest = cfg.selfteststs = false; cfg.test_regex = {};
2853 }
2854 }
2855
2856 // If no supported tests selected, return
2857 if (!( cfg.smartcheck || cfg.errorlog || cfg.xerrorlog
2858 || cfg.selftest || cfg.selfteststs || !cfg.test_regex.empty()
2859 || cfg.tempdiff || cfg.tempinfo || cfg.tempcrit ) ) {
2860 CloseDevice(nvmedev, name);
2861 return 3;
2862 }
2863
2864 // Tell user we are registering device
2865 PrintOut(LOG_INFO,"Device: %s, is SMART capable. Adding to \"monitor\" list.\n", name);
2866
2867 // Disable ATA specific self-tests
2868 state.not_cap_conveyance = state.not_cap_offline = state.not_cap_selective = true;
2869
2870 // Make sure that init_standby_check() ignores NVMe devices
2871 // TODO: Implement '-l selfteststs,ns' for NVMe
2872 cfg.offlinests_ns = cfg.selfteststs_ns = false;
2873
2874 CloseDevice(nvmedev, name);
2875
2876 if (!state_path_prefix.empty()) {
2877 // Build file name for state file
2878 std::replace_if(model, model+strlen(model), not_allowed_in_filename, '_');
2879 std::replace_if(serial, serial+strlen(serial), not_allowed_in_filename, '_');
2880 nsstr[0] = 0;
2882 snprintf(nsstr, sizeof(nsstr), "-n%u", nsid);
2883 cfg.state_file = strprintf("%s%s-%s%s.nvme.state", state_path_prefix.c_str(), model, serial, nsstr);
2884 // Read previous state
2885 if (read_dev_state(cfg.state_file.c_str(), state))
2886 PrintOut(LOG_INFO, "Device: %s, state read from %s\n", name, cfg.state_file.c_str());
2887 }
2888
2889 finish_device_scan(cfg, state);
2890
2891 return 0;
2892}
2893
2894// Open device for next check, return false on error
2895static bool open_device(const dev_config & cfg, dev_state & state, smart_device * device,
2896 const char * type)
2897{
2898 const char * name = cfg.name.c_str();
2899
2900 // If user has asked, test the email warning system
2901 if (cfg.emailtest)
2902 MailWarning(cfg, state, 0, "TEST EMAIL from smartd for device: %s", name);
2903
2904 // User may have requested (with the -n Directive) to leave the disk
2905 // alone if it is in idle or standby mode. In this case check the
2906 // power mode first before opening the device for full access,
2907 // and exit without check if disk is reported in standby.
2908 if (device->is_ata() && cfg.powermode && !state.powermodefail && !state.removed) {
2909 // Note that 'is_powered_down()' handles opening the device itself, and
2910 // can be used before calling 'open()' (that's the whole point of 'is_powered_down()'!).
2911 if (device->is_powered_down())
2912 {
2913 // skip at most powerskipmax checks
2914 if (!cfg.powerskipmax || state.powerskipcnt<cfg.powerskipmax) {
2915 // report first only except if state has changed, avoid waking up system disk
2916 if ((!state.powerskipcnt || state.lastpowermodeskipped != -1) && !cfg.powerquiet) {
2917 PrintOut(LOG_INFO, "Device: %s, is in %s mode, suspending checks\n", name, "STANDBY (OS)");
2918 state.lastpowermodeskipped = -1;
2919 }
2920 state.powerskipcnt++;
2921 return false;
2922 }
2923 }
2924 }
2925
2926 // if we can't open device, fail gracefully rather than hard --
2927 // perhaps the next time around we'll be able to open it
2928 if (!device->open()) {
2929 // For removable devices, print error message only once and suppress email
2930 if (!cfg.removable) {
2931 PrintOut(LOG_INFO, "Device: %s, open() of %s device failed: %s\n", name, type, device->get_errmsg());
2932 MailWarning(cfg, state, 9, "Device: %s, unable to open %s device", name, type);
2933 }
2934 else if (!state.removed) {
2935 PrintOut(LOG_INFO, "Device: %s, removed %s device: %s\n", name, type, device->get_errmsg());
2936 state.removed = true;
2937 }
2938 else if (debugmode)
2939 PrintOut(LOG_INFO, "Device: %s, %s device still removed: %s\n", name, type, device->get_errmsg());
2940 return false;
2941 }
2942
2943 if (debugmode)
2944 PrintOut(LOG_INFO,"Device: %s, opened %s device\n", name, type);
2945
2946 if (!cfg.removable)
2947 reset_warning_mail(cfg, state, 9, "open of %s device worked again", type);
2948 else if (state.removed) {
2949 PrintOut(LOG_INFO, "Device: %s, reconnected %s device\n", name, type);
2950 state.removed = false;
2951 }
2952
2953 return true;
2954}
2955
2956// If the self-test log has got more self-test errors (or more recent
2957// self-test errors) recorded, then notify user.
2958static void report_self_test_log_changes(const dev_config & cfg, dev_state & state,
2959 int errcnt, uint64_t hour)
2960{
2961 const char * name = cfg.name.c_str();
2962
2963 if (errcnt < 0)
2964 // command failed
2965 // TODO: Move this to ATA/SCSICheckDevice()
2966 MailWarning(cfg, state, 8, "Device: %s, Read SMART Self-Test Log Failed", name);
2967 else {
2968 reset_warning_mail(cfg, state, 8, "Read SMART Self-Test Log worked again");
2969
2970 if (state.selflogcount < errcnt) {
2971 // increase in error count
2972 PrintOut(LOG_CRIT, "Device: %s, Self-Test Log error count increased from %d to %d\n",
2973 name, state.selflogcount, errcnt);
2974 MailWarning(cfg, state, 3, "Device: %s, Self-Test Log error count increased from %d to %d",
2975 name, state.selflogcount, errcnt);
2976 state.must_write = true;
2977 }
2978 else if (errcnt > 0 && state.selfloghour != hour) {
2979 // more recent error
2980 // ATA: a 'more recent' error might actually be a smaller hour number,
2981 // if the hour number has wrapped.
2982 // There's still a bug here. You might just happen to run a new test
2983 // exactly 32768 hours after the previous failure, and have run exactly
2984 // 20 tests between the two, in which case smartd will miss the
2985 // new failure.
2986 PrintOut(LOG_CRIT, "Device: %s, new Self-Test Log error at hour timestamp %" PRIu64 "\n",
2987 name, hour);
2988 MailWarning(cfg, state, 3, "Device: %s, new Self-Test Log error at hour timestamp %" PRIu64 "\n",
2989 name, hour);
2990 state.must_write = true;
2991 }
2992
2993 // Print info if error entries have disappeared
2994 // or newer successful extended self-test exists
2995 if (state.selflogcount > errcnt) {
2996 PrintOut(LOG_INFO, "Device: %s, Self-Test Log error count decreased from %d to %d\n",
2997 name, state.selflogcount, errcnt);
2998 if (errcnt == 0)
2999 reset_warning_mail(cfg, state, 3, "Self-Test Log does no longer report errors");
3000 }
3001
3002 state.selflogcount = errcnt;
3003 state.selfloghour = hour;
3004 }
3005 return;
3006}
3007
3008// Test types, ordered by priority.
3009static const char test_type_chars[] = "LncrSCO";
3010static const unsigned num_test_types = sizeof(test_type_chars)-1;
3011
3012// returns test type if time to do test of type testtype,
3013// 0 if not time to do test.
3014static char next_scheduled_test(const dev_config & cfg, dev_state & state, time_t usetime = 0)
3015{
3016 // check that self-testing has been requested
3017 if (cfg.test_regex.empty())
3018 return 0;
3019
3020 // Exit if drive not capable of any test
3021 if ( state.not_cap_long && state.not_cap_short
3022 && state.not_cap_conveyance && state.not_cap_offline && state.not_cap_selective)
3023 return 0;
3024
3025 // since we are about to call localtime(), be sure glibc is informed
3026 // of any timezone changes we make.
3027 if (!usetime)
3029
3030 // Is it time for next check?
3031 time_t now = (!usetime ? time(nullptr) : usetime);
3032 if (now < state.scheduled_test_next_check) {
3033 if (state.scheduled_test_next_check <= now + 3600)
3034 return 0; // Next check within one hour
3035 // More than one hour, assume system clock time adjusted to the past
3036 state.scheduled_test_next_check = now;
3037 }
3038 else if (state.scheduled_test_next_check + (3600L*24*90) < now) {
3039 // Limit time check interval to 90 days
3040 state.scheduled_test_next_check = now - (3600L*24*90);
3041 }
3042
3043 // Find ':NNN[-LLL]' in regex for possible offsets and limits
3044 const unsigned max_offsets = 1 + num_test_types;
3045 unsigned offsets[max_offsets] = {0, }, limits[max_offsets] = {0, };
3046 unsigned num_offsets = 1; // offsets/limits[0] == 0 always
3047 for (const char * p = cfg.test_regex.get_pattern(); num_offsets < max_offsets; ) {
3048 const char * q = strchr(p, ':');
3049 if (!q)
3050 break;
3051 p = q + 1;
3052 unsigned offset = 0, limit = 0; int n1 = -1, n2 = -1, n3 = -1;
3053 sscanf(p, "%u%n-%n%u%n", &offset, &n1, &n2, &limit, &n3);
3054 if (!(n1 == 3 && (n2 < 0 || (n3 == 3+1+3 && limit > 0))))
3055 continue;
3056 offsets[num_offsets] = offset; limits[num_offsets] = limit;
3057 num_offsets++;
3058 p += (n3 > 0 ? n3 : n1);
3059 }
3060
3061 // Check interval [state.scheduled_test_next_check, now] for scheduled tests
3062 char testtype = 0;
3063 time_t testtime = 0;
3064 int maxtest = num_test_types-1;
3065
3066 for (time_t t = state.scheduled_test_next_check; ; ) {
3067 // Check offset 0 and then all offsets for ':NNN' found above
3068 for (unsigned i = 0; i < num_offsets; i++) {
3069 unsigned offset = offsets[i], limit = limits[i];
3070 unsigned delay = cfg.test_offset_factor * offset;
3071 if (0 < limit && limit < delay)
3072 delay %= limit + 1;
3073 struct tm tmbuf, * tms = time_to_tm_local(&tmbuf, t - (delay * 3600));
3074
3075 // tm_wday is 0 (Sunday) to 6 (Saturday). We use 1 (Monday) to 7 (Sunday).
3076 int weekday = (tms->tm_wday ? tms->tm_wday : 7);
3077 for (int j = 0; j <= maxtest; j++) {
3078 // Skip if drive not capable of this test
3079 switch (test_type_chars[j]) {
3080 case 'L': if (state.not_cap_long) continue; break;
3081 case 'S': if (state.not_cap_short) continue; break;
3082 case 'C': if (state.not_cap_conveyance) continue; break;
3083 case 'O': if (state.not_cap_offline) continue; break;
3084 case 'c': case 'n':
3085 case 'r': if (state.not_cap_selective) continue; break;
3086 default: continue;
3087 }
3088 // Try match of "T/MM/DD/d/HH[:NNN]"
3089 char pattern[64];
3090 snprintf(pattern, sizeof(pattern), "%c/%02d/%02d/%1d/%02d",
3091 test_type_chars[j], tms->tm_mon+1, tms->tm_mday, weekday, tms->tm_hour);
3092 if (i > 0) {
3093 const unsigned len = sizeof("S/01/01/1/01") - 1;
3094 snprintf(pattern + len, sizeof(pattern) - len, ":%03u", offset);
3095 if (limit > 0)
3096 snprintf(pattern + len + 4, sizeof(pattern) - len - 4, "-%03u", limit);
3097 }
3098 if (cfg.test_regex.full_match(pattern)) {
3099 // Test found
3100 testtype = pattern[0];
3101 testtime = t;
3102 // Limit further matches to higher priority self-tests
3103 maxtest = j-1;
3104 break;
3105 }
3106 }
3107 }
3108
3109 // Exit if no tests left or current time reached
3110 if (maxtest < 0)
3111 break;
3112 if (t >= now)
3113 break;
3114 // Check next hour
3115 if ((t += 3600) > now)
3116 t = now;
3117 }
3118
3119 // Do next check not before next hour.
3120 struct tm tmbuf, * tmnow = time_to_tm_local(&tmbuf, now);
3121 state.scheduled_test_next_check = now + (3600 - tmnow->tm_min*60 - tmnow->tm_sec);
3122
3123 if (testtype) {
3124 state.must_write = true;
3125 // Tell user if an old test was found.
3126 if (!usetime && (testtime / 3600) < (now / 3600)) {
3127 char datebuf[DATEANDEPOCHLEN]; dateandtimezoneepoch(datebuf, testtime);
3128 PrintOut(LOG_INFO, "Device: %s, old test of type %c not run at %s, starting now.\n",
3129 cfg.name.c_str(), testtype, datebuf);
3130 }
3131 }
3132
3133 return testtype;
3134}
3135
3136// Print a list of future tests.
3138{
3139 unsigned numdev = configs.size();
3140 if (!numdev)
3141 return;
3142 std::vector<int> testcnts(numdev * num_test_types, 0);
3143
3144 PrintOut(LOG_INFO, "\nNext scheduled self tests (at most 5 of each type per device):\n");
3145
3146 // FixGlibcTimeZoneBug(); // done in PrintOut()
3147 time_t now = time(nullptr);
3148 char datenow[DATEANDEPOCHLEN], date[DATEANDEPOCHLEN];
3149 dateandtimezoneepoch(datenow, now);
3150
3151 long seconds;
3152 for (seconds=checktime; seconds<3600L*24*90; seconds+=checktime) {
3153 // Check for each device whether a test will be run
3154 time_t testtime = now + seconds;
3155 for (unsigned i = 0; i < numdev; i++) {
3156 const dev_config & cfg = configs.at(i);
3157 dev_state & state = states.at(i);
3158 const char * p;
3159 char testtype = next_scheduled_test(cfg, state, testtime);
3160 if (testtype && (p = strchr(test_type_chars, testtype))) {
3161 unsigned t = (p - test_type_chars);
3162 // Report at most 5 tests of each type
3163 if (++testcnts[i*num_test_types + t] <= 5) {
3164 dateandtimezoneepoch(date, testtime);
3165 PrintOut(LOG_INFO, "Device: %s, will do test %d of type %c at %s\n", cfg.name.c_str(),
3166 testcnts[i*num_test_types + t], testtype, date);
3167 }
3168 }
3169 }
3170 }
3171
3172 // Report totals
3173 dateandtimezoneepoch(date, now+seconds);
3174 PrintOut(LOG_INFO, "\nTotals [%s - %s]:\n", datenow, date);
3175 for (unsigned i = 0; i < numdev; i++) {
3176 const dev_config & cfg = configs.at(i);
3177 bool ata = devices.at(i)->is_ata();
3178 for (unsigned t = 0; t < num_test_types; t++) {
3179 int cnt = testcnts[i*num_test_types + t];
3180 if (cnt == 0 && !strchr((ata ? "LSCO" : "LS"), test_type_chars[t]))
3181 continue;
3182 PrintOut(LOG_INFO, "Device: %s, will do %3d test%s of type %c\n", cfg.name.c_str(),
3183 cnt, (cnt==1?"":"s"), test_type_chars[t]);
3184 }
3185 }
3186
3187}
3188
3189// Return zero on success, nonzero on failure. Perform offline (background)
3190// short or long (extended) self test on given scsi device.
3191static int DoSCSISelfTest(const dev_config & cfg, dev_state & state, scsi_device * device, char testtype)
3192{
3193 int retval = 0;
3194 const char *testname = nullptr;
3195 const char *name = cfg.name.c_str();
3196 int inProgress;
3197
3198 if (scsiSelfTestInProgress(device, &inProgress)) {
3199 PrintOut(LOG_CRIT, "Device: %s, does not support Self-Tests\n", name);
3200 state.not_cap_short = state.not_cap_long = true;
3201 return 1;
3202 }
3203
3204 if (1 == inProgress) {
3205 PrintOut(LOG_INFO, "Device: %s, skip since Self-Test already in "
3206 "progress.\n", name);
3207 return 1;
3208 }
3209
3210 switch (testtype) {
3211 case 'S':
3212 testname = "Short Self";
3213 retval = scsiSmartShortSelfTest(device);
3214 break;
3215 case 'L':
3216 testname = "Long Self";
3217 retval = scsiSmartExtendSelfTest(device);
3218 break;
3219 }
3220 // If we can't do the test, exit
3221 if (!testname) {
3222 PrintOut(LOG_CRIT, "Device: %s, not capable of %c Self-Test\n", name,
3223 testtype);
3224 return 1;
3225 }
3226 if (retval) {
3227 if ((SIMPLE_ERR_BAD_OPCODE == retval) ||
3228 (SIMPLE_ERR_BAD_FIELD == retval)) {
3229 PrintOut(LOG_CRIT, "Device: %s, not capable of %s-Test\n", name,
3230 testname);
3231 if ('L'==testtype)
3232 state.not_cap_long = true;
3233 else
3234 state.not_cap_short = true;
3235
3236 return 1;
3237 }
3238 PrintOut(LOG_CRIT, "Device: %s, execute %s-Test failed (err: %d)\n", name,
3239 testname, retval);
3240 return 1;
3241 }
3242
3243 PrintOut(LOG_INFO, "Device: %s, starting scheduled %s-Test.\n", name, testname);
3244
3245 return 0;
3246}
3247
3248// Do an offline immediate or self-test. Return zero on success,
3249// nonzero on failure.
3250static int DoATASelfTest(const dev_config & cfg, dev_state & state, ata_device * device, char testtype)
3251{
3252 const char *name = cfg.name.c_str();
3253
3254 // Read current smart data and check status/capability
3255 // TODO: Reuse smart data already read in ATACheckDevice()
3256 struct ata_smart_values data;
3257 if (ataReadSmartValues(device, &data) || !(data.offline_data_collection_capability)) {
3258 PrintOut(LOG_CRIT, "Device: %s, not capable of Offline or Self-Testing.\n", name);
3259 return 1;
3260 }
3261
3262 // Check for capability to do the test
3263 int dotest = -1, mode = 0;
3264 const char *testname = nullptr;
3265 switch (testtype) {
3266 case 'O':
3267 testname="Offline Immediate ";
3269 dotest=OFFLINE_FULL_SCAN;
3270 else
3271 state.not_cap_offline = true;
3272 break;
3273 case 'C':
3274 testname="Conveyance Self-";
3276 dotest=CONVEYANCE_SELF_TEST;
3277 else
3278 state.not_cap_conveyance = true;
3279 break;
3280 case 'S':
3281 testname="Short Self-";
3282 if (isSupportSelfTest(&data))
3283 dotest=SHORT_SELF_TEST;
3284 else
3285 state.not_cap_short = true;
3286 break;
3287 case 'L':
3288 testname="Long Self-";
3289 if (isSupportSelfTest(&data))
3290 dotest=EXTEND_SELF_TEST;
3291 else
3292 state.not_cap_long = true;
3293 break;
3294
3295 case 'c': case 'n': case 'r':
3296 testname = "Selective Self-";
3298 dotest = SELECTIVE_SELF_TEST;
3299 switch (testtype) {
3300 case 'c': mode = SEL_CONT; break;
3301 case 'n': mode = SEL_NEXT; break;
3302 case 'r': mode = SEL_REDO; break;
3303 }
3304 }
3305 else
3306 state.not_cap_selective = true;
3307 break;
3308 }
3309
3310 // If we can't do the test, exit
3311 if (dotest<0) {
3312 PrintOut(LOG_CRIT, "Device: %s, not capable of %sTest\n", name, testname);
3313 return 1;
3314 }
3315
3316 // If currently running a self-test, do not interrupt it to start another.
3317 if (15==(data.self_test_exec_status >> 4)) {
3318 if (cfg.firmwarebugs.is_set(BUG_SAMSUNG3) && data.self_test_exec_status == 0xf0) {
3319 PrintOut(LOG_INFO, "Device: %s, will not skip scheduled %sTest "
3320 "despite unclear Self-Test byte (SAMSUNG Firmware bug).\n", name, testname);
3321 } else {
3322 PrintOut(LOG_INFO, "Device: %s, skip scheduled %sTest; %1d0%% remaining of current Self-Test.\n",
3323 name, testname, (int)(data.self_test_exec_status & 0x0f));
3324 return 1;
3325 }
3326 }
3327
3328 if (dotest == SELECTIVE_SELF_TEST) {
3329 // Set test span
3330 ata_selective_selftest_args selargs, prev_args;
3331 selargs.num_spans = 1;
3332 selargs.span[0].mode = mode;
3333 prev_args.num_spans = 1;
3334 prev_args.span[0].start = state.selective_test_last_start;
3335 prev_args.span[0].end = state.selective_test_last_end;
3336 if (ataWriteSelectiveSelfTestLog(device, selargs, &data, state.num_sectors, &prev_args)) {
3337 PrintOut(LOG_CRIT, "Device: %s, prepare %sTest failed\n", name, testname);
3338 return 1;
3339 }
3340 uint64_t start = selargs.span[0].start, end = selargs.span[0].end;
3341 PrintOut(LOG_INFO, "Device: %s, %s test span at LBA %" PRIu64 " - %" PRIu64 " (%" PRIu64 " sectors, %u%% - %u%% of disk).\n",
3342 name, (selargs.span[0].mode == SEL_NEXT ? "next" : "redo"),
3343 start, end, end - start + 1,
3344 (unsigned)((100 * start + state.num_sectors/2) / state.num_sectors),
3345 (unsigned)((100 * end + state.num_sectors/2) / state.num_sectors));
3346 state.selective_test_last_start = start;
3347 state.selective_test_last_end = end;
3348 }
3349
3350 // execute the test, and return status
3351 int retval = smartcommandhandler(device, IMMEDIATE_OFFLINE, dotest, nullptr);
3352 if (retval) {
3353 PrintOut(LOG_CRIT, "Device: %s, execute %sTest failed.\n", name, testname);
3354 return retval;
3355 }
3356
3357 // Report recent test start to do_disable_standby_check()
3358 // and force log of next test status
3359 if (testtype == 'O')
3360 state.offline_started = true;
3361 else
3362 state.selftest_started = true;
3363
3364 PrintOut(LOG_INFO, "Device: %s, starting scheduled %sTest.\n", name, testname);
3365 return 0;
3366}
3367
3368// Check pending sector count attribute values (-C, -U directives).
3369static void check_pending(const dev_config & cfg, dev_state & state,
3370 unsigned char id, bool increase_only,
3371 const ata_smart_values & smartval,
3372 int mailtype, const char * msg)
3373{
3374 // Find attribute index
3375 int i = ata_find_attr_index(id, smartval);
3376 if (!(i >= 0 && ata_find_attr_index(id, state.smartval) == i))
3377 return;
3378
3379 // No report if no sectors pending.
3380 uint64_t rawval = ata_get_attr_raw_value(smartval.vendor_attributes[i], cfg.attribute_defs);
3381 if (rawval == 0) {
3382 reset_warning_mail(cfg, state, mailtype, "No more %s", msg);
3383 return;
3384 }
3385
3386 // If attribute is not reset, report only sector count increases.
3387 uint64_t prev_rawval = ata_get_attr_raw_value(state.smartval.vendor_attributes[i], cfg.attribute_defs);
3388 if (!(!increase_only || prev_rawval < rawval))
3389 return;
3390
3391 // Format message.
3392 std::string s = strprintf("Device: %s, %" PRId64 " %s", cfg.name.c_str(), rawval, msg);
3393 if (prev_rawval > 0 && rawval != prev_rawval)
3394 s += strprintf(" (changed %+" PRId64 ")", rawval - prev_rawval);
3395
3396 PrintOut(LOG_CRIT, "%s\n", s.c_str());
3397 MailWarning(cfg, state, mailtype, "%s", s.c_str());
3398 state.must_write = true;
3399}
3400
3401// Format Temperature value
3402static const char * fmt_temp(unsigned char x, char (& buf)[20])
3403{
3404 if (!x) // unset
3405 return "??";
3406 snprintf(buf, sizeof(buf), "%u", x);
3407 return buf;
3408}
3409
3410// Check Temperature limits
3411static void CheckTemperature(const dev_config & cfg, dev_state & state, unsigned char currtemp, unsigned char triptemp)
3412{
3413 if (!(0 < currtemp && currtemp < 255)) {
3414 PrintOut(LOG_INFO, "Device: %s, failed to read Temperature\n", cfg.name.c_str());
3415 return;
3416 }
3417
3418 // Update Max Temperature
3419 const char * minchg = "", * maxchg = "";
3420 if (currtemp > state.tempmax) {
3421 if (state.tempmax)
3422 maxchg = "!";
3423 state.tempmax = currtemp;
3424 state.must_write = true;
3425 }
3426
3427 char buf[20];
3428 if (!state.temperature) {
3429 // First check
3430 if (!state.tempmin || currtemp < state.tempmin)
3431 // Delay Min Temperature update by ~ 30 minutes.
3432 state.tempmin_delay = time(nullptr) + default_checktime - 60;
3433 PrintOut(LOG_INFO, "Device: %s, initial Temperature is %d Celsius (Min/Max %s/%u%s)\n",
3434 cfg.name.c_str(), (int)currtemp, fmt_temp(state.tempmin, buf), state.tempmax, maxchg);
3435 if (triptemp)
3436 PrintOut(LOG_INFO, " [trip Temperature is %d Celsius]\n", (int)triptemp);
3437 state.temperature = currtemp;
3438 }
3439 else {
3440 if (state.tempmin_delay) {
3441 // End Min Temperature update delay if ...
3442 if ( (state.tempmin && currtemp > state.tempmin) // current temp exceeds recorded min,
3443 || (state.tempmin_delay <= time(nullptr))) { // or delay time is over.
3444 state.tempmin_delay = 0;
3445 if (!state.tempmin)
3446 state.tempmin = 255;
3447 }
3448 }
3449
3450 // Update Min Temperature
3451 if (!state.tempmin_delay && currtemp < state.tempmin) {
3452 state.tempmin = currtemp;
3453 state.must_write = true;
3454 if (currtemp != state.temperature)
3455 minchg = "!";
3456 }
3457
3458 // Track changes
3459 if (cfg.tempdiff && (*minchg || *maxchg || abs((int)currtemp - (int)state.temperature) >= cfg.tempdiff)) {
3460 PrintOut(LOG_INFO, "Device: %s, Temperature changed %+d Celsius to %u Celsius (Min/Max %s%s/%u%s)\n",
3461 cfg.name.c_str(), (int)currtemp-(int)state.temperature, currtemp, fmt_temp(state.tempmin, buf), minchg, state.tempmax, maxchg);
3462 state.temperature = currtemp;
3463 }
3464 }
3465
3466 // Check limits
3467 if (cfg.tempcrit && currtemp >= cfg.tempcrit) {
3468 PrintOut(LOG_CRIT, "Device: %s, Temperature %u Celsius reached critical limit of %u Celsius (Min/Max %s%s/%u%s)\n",
3469 cfg.name.c_str(), currtemp, cfg.tempcrit, fmt_temp(state.tempmin, buf), minchg, state.tempmax, maxchg);
3470 MailWarning(cfg, state, 12, "Device: %s, Temperature %d Celsius reached critical limit of %u Celsius (Min/Max %s%s/%u%s)",
3471 cfg.name.c_str(), currtemp, cfg.tempcrit, fmt_temp(state.tempmin, buf), minchg, state.tempmax, maxchg);
3472 }
3473 else if (cfg.tempinfo && currtemp >= cfg.tempinfo) {
3474 PrintOut(LOG_INFO, "Device: %s, Temperature %u Celsius reached limit of %u Celsius (Min/Max %s%s/%u%s)\n",
3475 cfg.name.c_str(), currtemp, cfg.tempinfo, fmt_temp(state.tempmin, buf), minchg, state.tempmax, maxchg);
3476 }
3477 else if (cfg.tempcrit) {
3478 unsigned char limit = (cfg.tempinfo ? cfg.tempinfo : cfg.tempcrit-5);
3479 if (currtemp < limit)
3480 reset_warning_mail(cfg, state, 12, "Temperature %u Celsius dropped below %u Celsius", currtemp, limit);
3481 }
3482}
3483
3484// Check normalized and raw attribute values.
3485static void check_attribute(const dev_config & cfg, dev_state & state,
3486 const ata_smart_attribute & attr,
3487 const ata_smart_attribute & prev,
3488 int attridx,
3489 const ata_smart_threshold_entry * thresholds)
3490{
3491 // Check attribute and threshold
3492 ata_attr_state attrstate = ata_get_attr_state(attr, attridx, thresholds, cfg.attribute_defs);
3493 if (attrstate == ATTRSTATE_NON_EXISTING)
3494 return;
3495
3496 // If requested, check for usage attributes that have failed.
3497 if ( cfg.usagefailed && attrstate == ATTRSTATE_FAILED_NOW
3499 std::string attrname = ata_get_smart_attr_name(attr.id, cfg.attribute_defs, cfg.dev_rpm);
3500 PrintOut(LOG_CRIT, "Device: %s, Failed SMART usage Attribute: %d %s.\n", cfg.name.c_str(), attr.id, attrname.c_str());
3501 MailWarning(cfg, state, 2, "Device: %s, Failed SMART usage Attribute: %d %s.", cfg.name.c_str(), attr.id, attrname.c_str());
3502 state.must_write = true;
3503 }
3504
3505 // Return if we're not tracking this type of attribute
3506 bool prefail = !!ATTRIBUTE_FLAGS_PREFAILURE(attr.flags);
3507 if (!( ( prefail && cfg.prefail)
3508 || (!prefail && cfg.usage )))
3509 return;
3510
3511 // Return if '-I ID' was specified
3513 return;
3514
3515 // Issue warning if they don't have the same ID in all structures.
3516 if (attr.id != prev.id) {
3517 PrintOut(LOG_INFO,"Device: %s, same Attribute has different ID numbers: %d = %d\n",
3518 cfg.name.c_str(), attr.id, prev.id);
3519 return;
3520 }
3521
3522 // Compare normalized values if valid.
3523 bool valchanged = false;
3524 if (attrstate > ATTRSTATE_NO_NORMVAL) {
3525 if (attr.current != prev.current)
3526 valchanged = true;
3527 }
3528
3529 // Compare raw values if requested.
3530 bool rawchanged = false;
3531 if (cfg.monitor_attr_flags.is_set(attr.id, MONITOR_RAW)) {
3534 rawchanged = true;
3535 }
3536
3537 // Return if no change
3538 if (!(valchanged || rawchanged))
3539 return;
3540
3541 // Format value strings
3542 std::string currstr, prevstr;
3543 if (attrstate == ATTRSTATE_NO_NORMVAL) {
3544 // Print raw values only
3545 currstr = strprintf("%s (Raw)",
3546 ata_format_attr_raw_value(attr, cfg.attribute_defs).c_str());
3547 prevstr = strprintf("%s (Raw)",
3548 ata_format_attr_raw_value(prev, cfg.attribute_defs).c_str());
3549 }
3550 else if (cfg.monitor_attr_flags.is_set(attr.id, MONITOR_RAW_PRINT)) {
3551 // Print normalized and raw values
3552 currstr = strprintf("%d [Raw %s]", attr.current,
3553 ata_format_attr_raw_value(attr, cfg.attribute_defs).c_str());
3554 prevstr = strprintf("%d [Raw %s]", prev.current,
3555 ata_format_attr_raw_value(prev, cfg.attribute_defs).c_str());
3556 }
3557 else {
3558 // Print normalized values only
3559 currstr = strprintf("%d", attr.current);
3560 prevstr = strprintf("%d", prev.current);
3561 }
3562
3563 // Format message
3564 std::string msg = strprintf("Device: %s, SMART %s Attribute: %d %s changed from %s to %s",
3565 cfg.name.c_str(), (prefail ? "Prefailure" : "Usage"), attr.id,
3566 ata_get_smart_attr_name(attr.id, cfg.attribute_defs, cfg.dev_rpm).c_str(),
3567 prevstr.c_str(), currstr.c_str());
3568
3569 // Report this change as critical ?
3570 if ( (valchanged && cfg.monitor_attr_flags.is_set(attr.id, MONITOR_AS_CRIT))
3571 || (rawchanged && cfg.monitor_attr_flags.is_set(attr.id, MONITOR_RAW_AS_CRIT))) {
3572 PrintOut(LOG_CRIT, "%s\n", msg.c_str());
3573 MailWarning(cfg, state, 2, "%s", msg.c_str());
3574 }
3575 else {
3576 PrintOut(LOG_INFO, "%s\n", msg.c_str());
3577 }
3578 state.must_write = true;
3579}
3580
3581
3582static int ATACheckDevice(const dev_config & cfg, dev_state & state, ata_device * atadev,
3583 bool firstpass, bool allow_selftests)
3584{
3585 if (!open_device(cfg, state, atadev, "ATA"))
3586 return 1;
3587
3588 const char * name = cfg.name.c_str();
3589
3590 // user may have requested (with the -n Directive) to leave the disk
3591 // alone if it is in idle or sleeping mode. In this case check the
3592 // power mode and exit without check if needed
3593 if (cfg.powermode && !state.powermodefail) {
3594 int dontcheck=0, powermode=ataCheckPowerMode(atadev);
3595 const char * mode = 0;
3596 if (0 <= powermode && powermode < 0xff) {
3597 // wait for possible spin up and check again
3598 int powermode2;
3599 sleep(5);
3600 powermode2 = ataCheckPowerMode(atadev);
3601 if (powermode2 > powermode)
3602 PrintOut(LOG_INFO, "Device: %s, CHECK POWER STATUS spins up disk (0x%02x -> 0x%02x)\n", name, powermode, powermode2);
3603 powermode = powermode2;
3604 }
3605
3606 switch (powermode){
3607 case -1:
3608 // SLEEP
3609 mode="SLEEP";
3610 if (cfg.powermode>=1)
3611 dontcheck=1;
3612 break;
3613 case 0x00:
3614 // STANDBY
3615 mode="STANDBY";
3616 if (cfg.powermode>=2)
3617 dontcheck=1;
3618 break;
3619 case 0x01:
3620 // STANDBY_Y
3621 mode="STANDBY_Y";
3622 if (cfg.powermode>=2)
3623 dontcheck=1;
3624 break;
3625 case 0x80:
3626 // IDLE
3627 mode="IDLE";
3628 if (cfg.powermode>=3)
3629 dontcheck=1;
3630 break;
3631 case 0x81:
3632 // IDLE_A
3633 mode="IDLE_A";
3634 if (cfg.powermode>=3)
3635 dontcheck=1;
3636 break;
3637 case 0x82:
3638 // IDLE_B
3639 mode="IDLE_B";
3640 if (cfg.powermode>=3)
3641 dontcheck=1;
3642 break;
3643 case 0x83:
3644 // IDLE_C
3645 mode="IDLE_C";
3646 if (cfg.powermode>=3)
3647 dontcheck=1;
3648 break;
3649 case 0xff:
3650 // ACTIVE/IDLE
3651 case 0x40:
3652 // ACTIVE
3653 case 0x41:
3654 // ACTIVE
3655 mode="ACTIVE or IDLE";
3656 break;
3657 default:
3658 // UNKNOWN
3659 PrintOut(LOG_CRIT, "Device: %s, CHECK POWER STATUS returned %d, not ATA compliant, ignoring -n Directive\n",
3660 name, powermode);
3661 state.powermodefail = true;
3662 break;
3663 }
3664
3665 // if we are going to skip a check, return now
3666 if (dontcheck){
3667 // skip at most powerskipmax checks
3668 if (!cfg.powerskipmax || state.powerskipcnt<cfg.powerskipmax) {
3669 CloseDevice(atadev, name);
3670 // report first only except if state has changed, avoid waking up system disk
3671 if ((!state.powerskipcnt || state.lastpowermodeskipped != powermode) && !cfg.powerquiet) {
3672 PrintOut(LOG_INFO, "Device: %s, is in %s mode, suspending checks\n", name, mode);
3673 state.lastpowermodeskipped = powermode;
3674 }
3675 state.powerskipcnt++;
3676 return 0;
3677 }
3678 else {
3679 PrintOut(LOG_INFO, "Device: %s, %s mode ignored due to reached limit of skipped checks (%d check%s skipped)\n",
3680 name, mode, state.powerskipcnt, (state.powerskipcnt==1?"":"s"));
3681 }
3682 state.powerskipcnt = 0;
3683 state.tempmin_delay = time(nullptr) + default_checktime - 60; // Delay Min Temperature update
3684 }
3685 else if (state.powerskipcnt) {
3686 PrintOut(LOG_INFO, "Device: %s, is back in %s mode, resuming checks (%d check%s skipped)\n",
3687 name, mode, state.powerskipcnt, (state.powerskipcnt==1?"":"s"));
3688 state.powerskipcnt = 0;
3689 state.tempmin_delay = time(nullptr) + default_checktime - 60; // Delay Min Temperature update
3690 }
3691 }
3692
3693 // check smart status
3694 if (cfg.smartcheck) {
3695 int status=ataSmartStatus2(atadev);
3696 if (status==-1){
3697 PrintOut(LOG_INFO,"Device: %s, not capable of SMART self-check\n",name);
3698 MailWarning(cfg, state, 5, "Device: %s, not capable of SMART self-check", name);
3699 state.must_write = true;
3700 }
3701 else if (status==1){
3702 PrintOut(LOG_CRIT, "Device: %s, FAILED SMART self-check. BACK UP DATA NOW!\n", name);
3703 MailWarning(cfg, state, 1, "Device: %s, FAILED SMART self-check. BACK UP DATA NOW!", name);
3704 state.must_write = true;
3705 }
3706 }
3707
3708 // Check everything that depends upon SMART Data (eg, Attribute values)
3709 if ( cfg.usagefailed || cfg.prefail || cfg.usage
3710 || cfg.curr_pending_id || cfg.offl_pending_id
3711 || cfg.tempdiff || cfg.tempinfo || cfg.tempcrit
3712 || cfg.selftest || cfg.offlinests || cfg.selfteststs) {
3713
3714 // Read current attribute values.
3715 ata_smart_values curval;
3716 if (ataReadSmartValues(atadev, &curval)){
3717 PrintOut(LOG_CRIT, "Device: %s, failed to read SMART Attribute Data\n", name);
3718 MailWarning(cfg, state, 6, "Device: %s, failed to read SMART Attribute Data", name);
3719 state.must_write = true;
3720 }
3721 else {
3722 reset_warning_mail(cfg, state, 6, "read SMART Attribute Data worked again");
3723
3724 // look for current or offline pending sectors
3725 if (cfg.curr_pending_id)
3726 check_pending(cfg, state, cfg.curr_pending_id, cfg.curr_pending_incr, curval, 10,
3727 (!cfg.curr_pending_incr ? "Currently unreadable (pending) sectors"
3728 : "Total unreadable (pending) sectors" ));
3729
3730 if (cfg.offl_pending_id)
3731 check_pending(cfg, state, cfg.offl_pending_id, cfg.offl_pending_incr, curval, 11,
3732 (!cfg.offl_pending_incr ? "Offline uncorrectable sectors"
3733 : "Total offline uncorrectable sectors"));
3734
3735 // check temperature limits
3736 if (cfg.tempdiff || cfg.tempinfo || cfg.tempcrit)
3737 CheckTemperature(cfg, state, ata_return_temperature_value(&curval, cfg.attribute_defs), 0);
3738
3739 // look for failed usage attributes, or track usage or prefail attributes
3740 if (cfg.usagefailed || cfg.prefail || cfg.usage) {
3741 for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
3742 check_attribute(cfg, state,
3743 curval.vendor_attributes[i],
3744 state.smartval.vendor_attributes[i],
3745 i, state.smartthres.thres_entries);
3746 }
3747 }
3748
3749 // Log changes of offline data collection status
3750 if (cfg.offlinests) {
3753 || state.offline_started // test was started in previous call
3754 || (firstpass && (debugmode || (curval.offline_data_collection_status & 0x7d))))
3756 }
3757
3758 // Log changes of self-test execution status
3759 if (cfg.selfteststs) {
3761 || state.selftest_started // test was started in previous call
3762 || (firstpass && (debugmode || (curval.self_test_exec_status & 0xf0))))
3764 }
3765
3766 // Save the new values for the next time around
3767 state.smartval = curval;
3769 state.attrlog_dirty = true;
3770 }
3771 }
3772 state.offline_started = state.selftest_started = false;
3773
3774 // check if number of selftest errors has increased (note: may also DECREASE)
3775 if (cfg.selftest) {
3776 unsigned hour = 0;
3777 int errcnt = check_ata_self_test_log(atadev, name, cfg.firmwarebugs, hour);
3778 report_self_test_log_changes(cfg, state, errcnt, hour);
3779 }
3780
3781 // check if number of ATA errors has increased
3782 if (cfg.errorlog || cfg.xerrorlog) {
3783
3784 int errcnt1 = -1, errcnt2 = -1;
3785 if (cfg.errorlog)
3786 errcnt1 = read_ata_error_count(atadev, name, cfg.firmwarebugs, false);
3787 if (cfg.xerrorlog)
3788 errcnt2 = read_ata_error_count(atadev, name, cfg.firmwarebugs, true);
3789
3790 // new number of errors is max of both logs
3791 int newc = (errcnt1 >= errcnt2 ? errcnt1 : errcnt2);
3792
3793 // did command fail?
3794 if (newc<0)
3795 // lack of PrintOut here is INTENTIONAL
3796 MailWarning(cfg, state, 7, "Device: %s, Read SMART Error Log Failed", name);
3797
3798 // has error count increased?
3799 int oldc = state.ataerrorcount;
3800 if (newc>oldc){
3801 PrintOut(LOG_CRIT, "Device: %s, ATA error count increased from %d to %d\n",
3802 name, oldc, newc);
3803 MailWarning(cfg, state, 4, "Device: %s, ATA error count increased from %d to %d",
3804 name, oldc, newc);
3805 state.must_write = true;
3806 }
3807
3808 if (newc>=0)
3809 state.ataerrorcount=newc;
3810 }
3811
3812 // if the user has asked, and device is capable (or we're not yet
3813 // sure) check whether a self test should be done now.
3814 if (allow_selftests && !cfg.test_regex.empty()) {
3815 char testtype = next_scheduled_test(cfg, state, false/*!scsi*/);
3816 if (testtype)
3817 DoATASelfTest(cfg, state, atadev, testtype);
3818 }
3819
3820 // Don't leave device open -- the OS/user may want to access it
3821 // before the next smartd cycle!
3822 CloseDevice(atadev, name);
3823 return 0;
3824}
3825
3826static int SCSICheckDevice(const dev_config & cfg, dev_state & state, scsi_device * scsidev, bool allow_selftests)
3827{
3828 if (!open_device(cfg, state, scsidev, "SCSI"))
3829 return 1;
3830
3831 const char * name = cfg.name.c_str();
3832
3833 uint8_t asc = 0, ascq = 0;
3834 uint8_t currenttemp = 0, triptemp = 0;
3835 if (!state.SuppressReport) {
3836 if (scsiCheckIE(scsidev, state.SmartPageSupported, state.TempPageSupported,
3837 &asc, &ascq, &currenttemp, &triptemp)) {
3838 PrintOut(LOG_INFO, "Device: %s, failed to read SMART values\n",
3839 name);
3840 MailWarning(cfg, state, 6, "Device: %s, failed to read SMART values", name);
3841 state.SuppressReport = 1;
3842 }
3843 }
3844 if (asc > 0) {
3845 char b[128];
3846 const char * cp = scsiGetIEString(asc, ascq, b, sizeof(b));
3847
3848 if (cp) {
3849 PrintOut(LOG_CRIT, "Device: %s, SMART Failure: %s\n", name, cp);
3850 MailWarning(cfg, state, 1,"Device: %s, SMART Failure: %s", name, cp);
3851 } else if (asc == 4 && ascq == 9) {
3852 PrintOut(LOG_INFO,"Device: %s, self-test in progress\n", name);
3853 } else if (debugmode)
3854 PrintOut(LOG_INFO,"Device: %s, non-SMART asc,ascq: %d,%d\n",
3855 name, (int)asc, (int)ascq);
3856 } else if (debugmode)
3857 PrintOut(LOG_INFO,"Device: %s, SMART health: passed\n", name);
3858
3859 // check temperature limits
3860 if (cfg.tempdiff || cfg.tempinfo || cfg.tempcrit)
3861 CheckTemperature(cfg, state, currenttemp, triptemp);
3862
3863 // check if number of selftest errors has increased (note: may also DECREASE)
3864 if (cfg.selftest) {
3865 int retval = scsiCountFailedSelfTests(scsidev, 0);
3866 report_self_test_log_changes(cfg, state, (retval >= 0 ? (retval & 0xff) : -1), retval >> 8);
3867 }
3868
3869 if (allow_selftests && !cfg.test_regex.empty()) {
3870 char testtype = next_scheduled_test(cfg, state);
3871 if (testtype)
3872 DoSCSISelfTest(cfg, state, scsidev, testtype);
3873 }
3874 if (!cfg.attrlog_file.empty()){
3875 // saving error counters to state
3876 uint8_t tBuf[252];
3877 if (state.ReadECounterPageSupported && (0 == scsiLogSense(scsidev,
3878 READ_ERROR_COUNTER_LPAGE, 0, tBuf, sizeof(tBuf), 0))) {
3881 state.scsi_error_counters[0].found=1;
3882 }
3883 if (state.WriteECounterPageSupported && (0 == scsiLogSense(scsidev,
3884 WRITE_ERROR_COUNTER_LPAGE, 0, tBuf, sizeof(tBuf), 0))) {
3887 state.scsi_error_counters[1].found=1;
3888 }
3889 if (state.VerifyECounterPageSupported && (0 == scsiLogSense(scsidev,
3890 VERIFY_ERROR_COUNTER_LPAGE, 0, tBuf, sizeof(tBuf), 0))) {
3893 state.scsi_error_counters[2].found=1;
3894 }
3895 if (state.NonMediumErrorPageSupported && (0 == scsiLogSense(scsidev,
3896 NON_MEDIUM_ERROR_LPAGE, 0, tBuf, sizeof(tBuf), 0))) {
3900 }
3901 // store temperature if not done by CheckTemperature() above
3902 if (!(cfg.tempdiff || cfg.tempinfo || cfg.tempcrit))
3903 state.temperature = currenttemp;
3904 }
3905 CloseDevice(scsidev, name);
3906 state.attrlog_dirty = true;
3907 return 0;
3908}
3909
3910// Log NVMe self-test execution status changes
3911static void log_nvme_self_test_exec_status(const char * name, dev_state & state, bool firstpass,
3912 const nvme_self_test_log & self_test_log)
3913{
3914 uint8_t curr_op = self_test_log.current_operation & 0xf;
3915 uint8_t curr_compl = self_test_log.current_completion & 0x7f;
3916
3917 // Return if no changes and log not forced
3918 if (!( curr_op != state.selftest_op
3919 || curr_compl != state.selftest_compl
3920 || state.selftest_started // test was started in previous call
3921 || (firstpass && (debugmode || curr_op))))
3922 return;
3923
3924 state.selftest_op = curr_op;
3925 state.selftest_compl = curr_compl;
3926
3927 const nvme_self_test_result & r = self_test_log.results[0];
3928 uint8_t op0 = r.self_test_status >> 4, res0 = r.self_test_status & 0xf;
3929
3930 uint8_t op = (curr_op ? curr_op : op0);
3931 const char * t; char tb[32];
3932 switch (op) {
3933 case 0x0: t = ""; break;
3934 case 0x1: t = "short"; break;
3935 case 0x2: t = "extended"; break;
3936 case 0xe: t = "vendor specific"; break;
3937 default: snprintf(tb, sizeof(tb), "unknown (0x%x)", op);
3938 t = tb; break;
3939 }
3940
3941 if (curr_op) {
3942 PrintOut(LOG_INFO, "Device %s, %s self-test in progress, %d%% remaining\n",
3943 name, t, 100 - curr_compl);
3944 }
3945 else if (!op0 || res0 == 0xf) { // First entry unused
3946 PrintOut(LOG_INFO, "Device %s, no self-test has ever been run\n", name);
3947 }
3948 else {
3949 // Report last test result from first log entry
3950 const char * m; char mb[48];
3951 switch (res0) {
3952 case 0x0: m = "completed without error"; break;
3953 case 0x1: m = "was aborted by a self-test command"; break;
3954 case 0x2: m = "was aborted by a controller reset"; break;
3955 case 0x3: m = "was aborted due to a namespace removal"; break;
3956 case 0x4: m = "was aborted by a format NVM command"; break;
3957 case 0x5: m = "completed with error (fatal or unknown error)"; break;
3958 case 0x6: m = "completed with error (unknown failed segment)"; break;
3959 case 0x7: m = "completed with error (failed segments)"; break;
3960 case 0x8: m = "was aborted (unknown reason)"; break;
3961 case 0x9: m = "was aborted due to a sanitize operation"; break;
3962 default: snprintf(mb, sizeof(mb), "returned an unknown result (0x%x)", res0);
3963 m = mb; break;
3964 }
3965
3966 char ns[32] = "";
3967 if (r.valid & 0x01)
3968 snprintf(ns, sizeof(ns), " of NSID 0x%x", r.nsid);
3969
3970 PrintOut((0x5 <= res0 && res0 <= 0x7 ? LOG_CRIT : LOG_INFO),
3971 "Device %s, previous %s self-test%s %s\n", name, t, ns, m);
3972 }
3973}
3974
3975// Count error entries in NVMe self-test log, set HOUR to power on hours of most
3976// recent error. Return the error count.
3977static int check_nvme_self_test_log(uint32_t nsid, const nvme_self_test_log & self_test_log,
3978 uint64_t & hour)
3979{
3980 hour = 0;
3981 int errcnt = 0;
3982
3983 for (unsigned i = 0; i < 20; i++) {
3984 const nvme_self_test_result & r = self_test_log.results[i];
3985 uint8_t op = r.self_test_status >> 4;
3986 uint8_t res = r.self_test_status & 0xf;
3987 if (!op || res == 0xf)
3988 continue; // Unused entry
3989
3990 if (!( nsid == nvme_broadcast_nsid
3991 || !(r.valid & 0x01) /* No NSID */
3992 || r.nsid == nvme_broadcast_nsid || r.nsid == nsid))
3993 continue; // Different individual namespace
3994
3995 if (op == 0x2 /* Extended */ && !res /* Completed without error */)
3996 break; // Stop count at first successful extended test
3997
3998 if (!(0x5 <= res && res <= 0x7))
3999 continue; // No error or aborted
4000
4001 // Error found
4002 if (++errcnt != 1)
4003 continue; // Not most recent error
4004
4005 // Keep track of time of most recent error
4007 }
4008
4009 return errcnt;
4010}
4011
4012static int start_nvme_self_test(const dev_config & cfg, dev_state & state, nvme_device * device,
4013 char testtype, const nvme_self_test_log & self_test_log)
4014{
4015 const char *name = cfg.name.c_str();
4016 unsigned nsid = device->get_nsid();
4017
4018 const char *testname; uint8_t stc;
4019 switch (testtype) {
4020 case 'S': testname = "Short"; stc = 1; break;
4021 case 'L': testname = "Extended"; stc = 2; break;
4022 default: // Should not happen
4023 PrintOut(LOG_INFO, "Device: %s, not capable of %c Self-Test\n", name, testtype);
4024 return 1;
4025 }
4026
4027 // If currently running a self-test, do not try to start another.
4028 if (self_test_log.current_operation & 0xf) {
4029 PrintOut(LOG_INFO, "Device: %s, skip scheduled %s Self-Test (NSID 0x%x); %d%% remaining of current Self-Test.\n",
4030 name, testname, nsid, 100 - (self_test_log.current_completion & 0x7f));
4031 return 1;
4032 }
4033
4034 if (!nvme_self_test(device, stc, nsid)) {
4035 PrintOut(LOG_CRIT, "Device: %s, execute %s Self-Test failed (NSID 0x%x): %s.\n",
4036 name, testname, nsid, device->get_errmsg());
4037 return 1;
4038 }
4039
4040 // Report recent test start to do_disable_standby_check()
4041 // and force log of next test status
4042 // TODO: Add NVMe support to do_disable_standby_check()
4043 state.selftest_started = true;
4044
4045 PrintOut(LOG_INFO, "Device: %s, starting scheduled %s Self-Test (NSID 0x%x).\n",
4046 name, testname, nsid);
4047 return 0;
4048}
4049
4050static int NVMeCheckDevice(const dev_config & cfg, dev_state & state, nvme_device * nvmedev, bool firstpass, bool allow_selftests)
4051{
4052 if (!open_device(cfg, state, nvmedev, "NVMe"))
4053 return 1;
4054
4055 const char * name = cfg.name.c_str();
4056
4057 // Read SMART/Health log
4058 // TODO: Support per namespace SMART/Health log
4059 nvme_smart_log smart_log;
4060 if (!nvme_read_smart_log(nvmedev, nvme_broadcast_nsid, smart_log)) {
4061 CloseDevice(nvmedev, name);
4062 PrintOut(LOG_INFO, "Device: %s, failed to read NVMe SMART/Health Information\n", name);
4063 MailWarning(cfg, state, 6, "Device: %s, failed to read NVMe SMART/Health Information", name);
4064 state.must_write = true;
4065 return 0;
4066 }
4067
4068 // Check Critical Warning bits
4069 if (cfg.smartcheck && smart_log.critical_warning) {
4070 unsigned char w = smart_log.critical_warning;
4071 std::string msg;
4072 static const char * const wnames[] =
4073 {"LowSpare", "Temperature", "Reliability", "R/O", "VolMemBackup"};
4074
4075 for (unsigned b = 0, cnt = 0; b < 8 ; b++) {
4076 if (!(w & (1 << b)))
4077 continue;
4078 if (cnt)
4079 msg += ", ";
4080 if (++cnt > 3) {
4081 msg += "..."; break;
4082 }
4083 if (b >= sizeof(wnames)/sizeof(wnames[0])) {
4084 msg += "*Unknown*"; break;
4085 }
4086 msg += wnames[b];
4087 }
4088
4089 PrintOut(LOG_CRIT, "Device: %s, Critical Warning (0x%02x): %s\n", name, w, msg.c_str());
4090 MailWarning(cfg, state, 1, "Device: %s, Critical Warning (0x%02x): %s", name, w, msg.c_str());
4091 state.must_write = true;
4092 }
4093
4094 // Check temperature limits
4095 if (cfg.tempdiff || cfg.tempinfo || cfg.tempcrit) {
4096 uint16_t k = sg_get_unaligned_le16(smart_log.temperature);
4097 // Convert Kelvin to positive Celsius (TODO: Allow negative temperatures)
4098 int c = (int)k - 273;
4099 if (c < 1)
4100 c = 1;
4101 else if (c > 0xff)
4102 c = 0xff;
4103 CheckTemperature(cfg, state, c, 0);
4104 }
4105
4106 // Check for test schedule
4107 char testtype = (allow_selftests && !cfg.test_regex.empty()
4108 ? next_scheduled_test(cfg, state) : 0);
4109
4110 // Read the self-test log if required
4111 nvme_self_test_log self_test_log{};
4112 if (testtype || cfg.selftest || cfg.selfteststs) {
4113 if (!nvme_read_self_test_log(nvmedev, nvme_broadcast_nsid, self_test_log)) {
4114 PrintOut(LOG_CRIT, "Device: %s, Read Self-test Log failed: %s\n",
4115 name, nvmedev->get_errmsg());
4116 MailWarning(cfg, state, 8, "Device: %s, Read Self-test Log failed: %s\n",
4117 name, nvmedev->get_errmsg());
4118 testtype = 0;
4119 }
4120 else {
4121 reset_warning_mail(cfg, state, 8, "Read Self-Test Log worked again");
4122
4123 // Log changes of self-test execution status
4124 if (cfg.selfteststs)
4125 log_nvme_self_test_exec_status(name, state, firstpass, self_test_log);
4126
4127 // Check if number of selftest errors has increased (note: may also DECREASE)
4128 if (cfg.selftest) {
4129 uint64_t hour = 0;
4130 int errcnt = check_nvme_self_test_log(nvmedev->get_nsid(), self_test_log, hour);
4131 report_self_test_log_changes(cfg, state, errcnt, hour);
4132 }
4133 }
4134 }
4135 state.selftest_started = false;
4136
4137 // Check if number of errors has increased
4138 if (cfg.errorlog || cfg.xerrorlog) {
4139 uint64_t newcnt = le128_to_uint64(smart_log.num_err_log_entries);
4140 if (newcnt > state.nvme_err_log_entries) {
4141 // Warn only if device related errors are found
4142 check_nvme_error_log(cfg, state, nvmedev, newcnt);
4143 }
4144 // else // TODO: Handle decrease of count?
4145 }
4146
4147 // Start self-test if scheduled
4148 if (testtype)
4149 start_nvme_self_test(cfg, state, nvmedev, testtype, self_test_log);
4150
4151 CloseDevice(nvmedev, name);
4152 state.attrlog_dirty = true;
4153 return 0;
4154}
4155
4156// 0=not used, 1=not disabled, 2=disable rejected by OS, 3=disabled
4158
4160{
4161 // Check for '-l offlinests,ns' or '-l selfteststs,ns' directives
4162 bool sts1 = false, sts2 = false;
4163 for (const auto & cfg : configs) {
4164 if (cfg.offlinests_ns)
4165 sts1 = true;
4166 if (cfg.selfteststs_ns)
4167 sts2 = true;
4168 }
4169
4170 // Check for support of disable auto standby
4171 // Reenable standby if smartd.conf was reread
4172 if (sts1 || sts2 || standby_disable_state == 3) {
4173 if (!smi()->disable_system_auto_standby(false)) {
4174 if (standby_disable_state == 3)
4175 PrintOut(LOG_CRIT, "System auto standby enable failed: %s\n", smi()->get_errmsg());
4176 if (sts1 || sts2) {
4177 PrintOut(LOG_INFO, "Disable auto standby not supported, ignoring ',ns' from %s%s%s\n",
4178 (sts1 ? "-l offlinests,ns" : ""), (sts1 && sts2 ? " and " : ""), (sts2 ? "-l selfteststs,ns" : ""));
4179 sts1 = sts2 = false;
4180 }
4181 }
4182 }
4183
4184 standby_disable_state = (sts1 || sts2 ? 1 : 0);
4185}
4186
4187static void do_disable_standby_check(const dev_config_vector & configs, const dev_state_vector & states)
4188{
4190 return;
4191
4192 // Check for just started or still running self-tests
4193 bool running = false;
4194 for (unsigned i = 0; i < configs.size() && !running; i++) {
4195 const dev_config & cfg = configs.at(i); const dev_state & state = states.at(i);
4196
4197 if ( ( cfg.offlinests_ns
4198 && (state.offline_started ||
4200 || ( cfg.selfteststs_ns
4201 && (state.selftest_started ||
4203 running = true;
4204 // state.offline/selftest_started will be reset after next logging of test status
4205 }
4206
4207 // Disable/enable auto standby and log state changes
4208 if (!running) {
4209 if (standby_disable_state != 1) {
4210 if (!smi()->disable_system_auto_standby(false))
4211 PrintOut(LOG_CRIT, "Self-test(s) completed, system auto standby enable failed: %s\n",
4212 smi()->get_errmsg());
4213 else
4214 PrintOut(LOG_INFO, "Self-test(s) completed, system auto standby enabled\n");
4216 }
4217 }
4218 else if (!smi()->disable_system_auto_standby(true)) {
4219 if (standby_disable_state != 2) {
4220 PrintOut(LOG_INFO, "Self-test(s) in progress, system auto standby disable rejected: %s\n",
4221 smi()->get_errmsg());
4223 }
4224 }
4225 else {
4226 if (standby_disable_state != 3) {
4227 PrintOut(LOG_INFO, "Self-test(s) in progress, system auto standby disabled\n");
4229 }
4230 }
4231}
4232
4233// Checks the SMART status of all ATA and SCSI devices
4234static void CheckDevicesOnce(const dev_config_vector & configs, dev_state_vector & states,
4235 smart_device_list & devices, bool firstpass, bool allow_selftests)
4236{
4237 for (unsigned i = 0; i < configs.size(); i++) {
4238 const dev_config & cfg = configs.at(i);
4239 dev_state & state = states.at(i);
4240 if (state.skip) {
4241 if (debugmode)
4242 PrintOut(LOG_INFO, "Device: %s, skipped (interval=%d)\n", cfg.name.c_str(),
4243 (cfg.checktime ? cfg.checktime : checktime));
4244 continue;
4245 }
4246
4247 smart_device * dev = devices.at(i);
4248 if (dev->is_ata())
4249 ATACheckDevice(cfg, state, dev->to_ata(), firstpass, allow_selftests);
4250 else if (dev->is_scsi())
4251 SCSICheckDevice(cfg, state, dev->to_scsi(), allow_selftests);
4252 else if (dev->is_nvme())
4253 NVMeCheckDevice(cfg, state, dev->to_nvme(), firstpass, allow_selftests);
4254
4255 // Prevent systemd unit startup timeout when checking many devices on startup
4257 }
4258
4259 do_disable_standby_check(configs, states);
4260}
4261
4262// Install all signal handlers
4264{
4265 // normal and abnormal exit
4268
4269 // in debug mode, <CONTROL-C> ==> HUP
4271
4272 // Catch HUP and USR1
4275#ifdef _WIN32
4276 set_signal_if_not_ignored(SIGUSR2, USR2handler);
4277#endif
4278}
4279
4280#ifdef _WIN32
4281// Toggle debug mode implemented for native windows only
4282// (there is no easy way to reopen tty on *nix)
4283static void ToggleDebugMode()
4284{
4285 if (!debugmode) {
4286 PrintOut(LOG_INFO,"Signal USR2 - enabling debug mode\n");
4287 if (!daemon_enable_console("smartd [Debug]")) {
4288 debugmode = 1;
4289 daemon_signal(SIGINT, HUPhandler);
4290 PrintOut(LOG_INFO,"smartd debug mode enabled, PID=%d\n", getpid());
4291 }
4292 else
4293 PrintOut(LOG_INFO,"enable console failed\n");
4294 }
4295 else if (debugmode == 1) {
4296 daemon_disable_console();
4297 debugmode = 0;
4298 daemon_signal(SIGINT, sighandler);
4299 PrintOut(LOG_INFO,"Signal USR2 - debug mode disabled\n");
4300 }
4301 else
4302 PrintOut(LOG_INFO,"Signal USR2 - debug mode %d not changed\n", debugmode);
4303}
4304#endif
4305
4306time_t calc_next_wakeuptime(time_t wakeuptime, time_t timenow, int ct)
4307{
4308 if (timenow < wakeuptime)
4309 return wakeuptime;
4310 return timenow + ct - (timenow - wakeuptime) % ct;
4311}
4312
4313static time_t dosleep(time_t wakeuptime, const dev_config_vector & configs,
4314 dev_state_vector & states, bool & sigwakeup)
4315{
4316 // If past wake-up-time, compute next wake-up-time
4317 time_t timenow = time(nullptr);
4318 unsigned n = configs.size();
4319 int ct;
4320 if (!checktime_min) {
4321 // Same for all devices
4322 wakeuptime = calc_next_wakeuptime(wakeuptime, timenow, checktime);
4323 ct = checktime;
4324 }
4325 else {
4326 // Determine wakeuptime of next device(s)
4327 wakeuptime = 0;
4328 for (unsigned i = 0; i < n; i++) {
4329 const dev_config & cfg = configs.at(i);
4330 dev_state & state = states.at(i);
4331 if (!state.skip)
4332 state.wakeuptime = calc_next_wakeuptime((state.wakeuptime ? state.wakeuptime : timenow),
4333 timenow, (cfg.checktime ? cfg.checktime : checktime));
4334 if (!wakeuptime || state.wakeuptime < wakeuptime)
4335 wakeuptime = state.wakeuptime;
4336 }
4337 ct = checktime_min;
4338 }
4339
4340 notify_wait(wakeuptime, n);
4341
4342 // Sleep until we catch a signal or have completed sleeping
4343 bool no_skip = false;
4344 int addtime = 0;
4345 while (timenow < wakeuptime+addtime && !caughtsigUSR1 && !caughtsigHUP && !caughtsigEXIT) {
4346 // Restart if system clock has been adjusted to the past
4347 if (wakeuptime > timenow + ct) {
4348 PrintOut(LOG_INFO, "System clock time adjusted to the past. Resetting next wakeup time.\n");
4349 wakeuptime = timenow + ct;
4350 for (auto & state : states)
4351 state.wakeuptime = 0;
4352 no_skip = true;
4353 }
4354
4355 // Exit sleep when time interval has expired or a signal is received
4356 sleep(wakeuptime+addtime-timenow);
4357
4358#ifdef _WIN32
4359 // toggle debug mode?
4360 if (caughtsigUSR2) {
4361 ToggleDebugMode();
4362 caughtsigUSR2 = 0;
4363 }
4364#endif
4365
4366 timenow = time(nullptr);
4367
4368 // Actual sleep time too long?
4369 if (!addtime && timenow > wakeuptime+60) {
4370 if (debugmode)
4371 PrintOut(LOG_INFO, "Sleep time was %d seconds too long, assuming wakeup from standby mode.\n",
4372 (int)(timenow-wakeuptime));
4373 // Wait another 20 seconds to avoid I/O errors during disk spin-up
4374 addtime = timenow-wakeuptime+20;
4375 // Use next wake-up-time if close
4376 int nextcheck = ct - addtime % ct;
4377 if (nextcheck <= 20)
4378 addtime += nextcheck;
4379 }
4380 }
4381
4382 // if we caught a SIGUSR1 then print message and clear signal
4383 if (caughtsigUSR1){
4384 PrintOut(LOG_INFO,"Signal USR1 - checking devices now rather than in %d seconds.\n",
4385 wakeuptime-timenow>0?(int)(wakeuptime-timenow):0);
4386 caughtsigUSR1=0;
4387 sigwakeup = no_skip = true;
4388 }
4389
4390 // Check which devices must be skipped in this cycle
4391 if (checktime_min) {
4392 for (auto & state : states)
4393 state.skip = (!no_skip && timenow < state.wakeuptime);
4394 }
4395
4396 // return adjusted wakeuptime
4397 return wakeuptime;
4398}
4399
4400// Print out a list of valid arguments for the Directive d
4401static void printoutvaliddirectiveargs(int priority, char d)
4402{
4403 switch (d) {
4404 case 'n':
4405 PrintOut(priority, "never[,N][,q], sleep[,N][,q], standby[,N][,q], idle[,N][,q]");
4406 break;
4407 case 's':
4408 PrintOut(priority, "valid_regular_expression");
4409 break;
4410 case 'd':
4411 PrintOut(priority, "%s", smi()->get_valid_dev_types_str().c_str());
4412 break;
4413 case 'T':
4414 PrintOut(priority, "normal, permissive");
4415 break;
4416 case 'o':
4417 case 'S':
4418 PrintOut(priority, "on, off");
4419 break;
4420 case 'l':
4421 PrintOut(priority, "error, selftest");
4422 break;
4423 case 'M':
4424 PrintOut(priority, "\"once\", \"always\", \"daily\", \"diminishing\", \"test\", \"exec\"");
4425 break;
4426 case 'v':
4427 PrintOut(priority, "\n%s\n", create_vendor_attribute_arg_list().c_str());
4428 break;
4429 case 'P':
4430 PrintOut(priority, "use, ignore, show, showall");
4431 break;
4432 case 'F':
4433 PrintOut(priority, "%s", get_valid_firmwarebug_args());
4434 break;
4435 case 'e':
4436 PrintOut(priority, "aam,[N|off], apm,[N|off], lookahead,[on|off], dsn,[on|off] "
4437 "security-freeze, standby,[N|off], wcache,[on|off]");
4438 break;
4439 case 'c':
4440 PrintOut(priority, "i=N, interval=N");
4441 break;
4442 }
4443}
4444
4445// exits with an error message, or returns integer value of token
4446static int GetInteger(const char *arg, const char *name, const char *token, int lineno, const char *cfgfile,
4447 int min, int max, char * suffix = 0)
4448{
4449 // make sure argument is there
4450 if (!arg) {
4451 PrintOut(LOG_CRIT,"File %s line %d (drive %s): Directive: %s takes integer argument from %d to %d.\n",
4452 cfgfile, lineno, name, token, min, max);
4453 return -1;
4454 }
4455
4456 // get argument value (base 10), check that it's integer, and in-range
4457 char *endptr;
4458 int val = strtol(arg,&endptr,10);
4459
4460 // optional suffix present?
4461 if (suffix) {
4462 if (!strcmp(endptr, suffix))
4463 endptr += strlen(suffix);
4464 else
4465 *suffix = 0;
4466 }
4467
4468 if (!(!*endptr && min <= val && val <= max)) {
4469 PrintOut(LOG_CRIT,"File %s line %d (drive %s): Directive: %s has argument: %s; needs integer from %d to %d.\n",
4470 cfgfile, lineno, name, token, arg, min, max);
4471 return -1;
4472 }
4473
4474 // all is well; return value
4475 return val;
4476}
4477
4478
4479// Get 1-3 small integer(s) for '-W' directive
4480static int Get3Integers(const char *arg, const char *name, const char *token, int lineno, const char *cfgfile,
4481 unsigned char *val1, unsigned char *val2, unsigned char *val3)
4482{
4483 unsigned v1 = 0, v2 = 0, v3 = 0;
4484 int n1 = -1, n2 = -1, n3 = -1, len;
4485 if (!arg) {
4486 PrintOut(LOG_CRIT,"File %s line %d (drive %s): Directive: %s takes 1-3 integer argument(s) from 0 to 255.\n",
4487 cfgfile, lineno, name, token);
4488 return -1;
4489 }
4490
4491 len = strlen(arg);
4492 if (!( sscanf(arg, "%u%n,%u%n,%u%n", &v1, &n1, &v2, &n2, &v3, &n3) >= 1
4493 && (n1 == len || n2 == len || n3 == len) && v1 <= 255 && v2 <= 255 && v3 <= 255)) {
4494 PrintOut(LOG_CRIT,"File %s line %d (drive %s): Directive: %s has argument: %s; needs 1-3 integer(s) from 0 to 255.\n",
4495 cfgfile, lineno, name, token, arg);
4496 return -1;
4497 }
4498 *val1 = (unsigned char)v1; *val2 = (unsigned char)v2; *val3 = (unsigned char)v3;
4499 return 0;
4500}
4501
4502
4503#ifdef _WIN32
4504
4505// Concatenate strtok() results if quoted with "..."
4506static const char * strtok_dequote(const char * delimiters)
4507{
4508 const char * t = strtok(nullptr, delimiters);
4509 if (!t || t[0] != '"')
4510 return t;
4511
4512 static std::string token;
4513 token = t+1;
4514 for (;;) {
4515 t = strtok(nullptr, delimiters);
4516 if (!t || !*t)
4517 return "\"";
4518 token += ' ';
4519 int len = strlen(t);
4520 if (t[len-1] == '"') {
4521 token += std::string(t, len-1);
4522 break;
4523 }
4524 token += t;
4525 }
4526 return token.c_str();
4527}
4528
4529#endif // _WIN32
4530
4531
4532// This function returns 1 if it has correctly parsed one token (and
4533// any arguments), else zero if no tokens remain. It returns -1 if an
4534// error was encountered.
4535static int ParseToken(char * token, dev_config & cfg, smart_devtype_list & scan_types)
4536{
4537 char sym;
4538 const char * name = cfg.name.c_str();
4539 int lineno=cfg.lineno;
4540 const char *delim = " \n\t";
4541 int badarg = 0;
4542 int missingarg = 0;
4543 const char *arg = 0;
4544
4545 // is the rest of the line a comment
4546 if (*token=='#')
4547 return 1;
4548
4549 // is the token not recognized?
4550 if (*token!='-' || strlen(token)!=2) {
4551 PrintOut(LOG_CRIT,"File %s line %d (drive %s): unknown Directive: %s\n",
4552 configfile, lineno, name, token);
4553 PrintOut(LOG_CRIT, "Run smartd -D to print a list of valid Directives.\n");
4554 return -1;
4555 }
4556
4557 // token we will be parsing:
4558 sym=token[1];
4559
4560 // parse the token and swallow its argument
4561 int val;
4562 char plus[] = "+", excl[] = "!";
4563
4564 switch (sym) {
4565 case 'C':
4566 // monitor current pending sector count (default 197)
4567 if ((val = GetInteger((arg = strtok(nullptr, delim)), name, token, lineno, configfile, 0, 255, plus)) < 0)
4568 return -1;
4569 cfg.curr_pending_id = (unsigned char)val;
4570 cfg.curr_pending_incr = (*plus == '+');
4571 cfg.curr_pending_set = true;
4572 break;
4573 case 'U':
4574 // monitor offline uncorrectable sectors (default 198)
4575 if ((val = GetInteger((arg = strtok(nullptr, delim)), name, token, lineno, configfile, 0, 255, plus)) < 0)
4576 return -1;
4577 cfg.offl_pending_id = (unsigned char)val;
4578 cfg.offl_pending_incr = (*plus == '+');
4579 cfg.offl_pending_set = true;
4580 break;
4581 case 'T':
4582 // Set tolerance level for SMART command failures
4583 if (!(arg = strtok(nullptr, delim))) {
4584 missingarg = 1;
4585 } else if (!strcmp(arg, "normal")) {
4586 // Normal mode: exit on failure of a mandatory S.M.A.R.T. command, but
4587 // not on failure of an optional S.M.A.R.T. command.
4588 // This is the default so we don't need to actually do anything here.
4589 cfg.permissive = false;
4590 } else if (!strcmp(arg, "permissive")) {
4591 // Permissive mode; ignore errors from Mandatory SMART commands
4592 cfg.permissive = true;
4593 } else {
4594 badarg = 1;
4595 }
4596 break;
4597 case 'd':
4598 // specify the device type
4599 if (!(arg = strtok(nullptr, delim))) {
4600 missingarg = 1;
4601 } else if (!strcmp(arg, "ignore")) {
4602 cfg.ignore = true;
4603 } else if (!strcmp(arg, "removable")) {
4604 cfg.removable = true;
4605 } else if (!strcmp(arg, "auto")) {
4606 cfg.dev_type = "";
4607 scan_types.clear();
4608 } else {
4609 cfg.dev_type = arg;
4610 scan_types.push_back(arg);
4611 }
4612 break;
4613 case 'F':
4614 // fix firmware bug
4615 if (!(arg = strtok(nullptr, delim)))
4616 missingarg = 1;
4617 else if (!parse_firmwarebug_def(arg, cfg.firmwarebugs))
4618 badarg = 1;
4619 break;
4620 case 'H':
4621 // check SMART status
4622 cfg.smartcheck = true;
4623 break;
4624 case 'f':
4625 // check for failure of usage attributes
4626 cfg.usagefailed = true;
4627 break;
4628 case 't':
4629 // track changes in all vendor attributes
4630 cfg.prefail = true;
4631 cfg.usage = true;
4632 break;
4633 case 'p':
4634 // track changes in prefail vendor attributes
4635 cfg.prefail = true;
4636 break;
4637 case 'u':
4638 // track changes in usage vendor attributes
4639 cfg.usage = true;
4640 break;
4641 case 'l':
4642 // track changes in SMART logs
4643 if (!(arg = strtok(nullptr, delim))) {
4644 missingarg = 1;
4645 } else if (!strcmp(arg, "selftest")) {
4646 // track changes in self-test log
4647 cfg.selftest = true;
4648 } else if (!strcmp(arg, "error")) {
4649 // track changes in ATA error log
4650 cfg.errorlog = true;
4651 } else if (!strcmp(arg, "xerror")) {
4652 // track changes in Extended Comprehensive SMART error log
4653 cfg.xerrorlog = true;
4654 } else if (!strcmp(arg, "offlinests")) {
4655 // track changes in offline data collection status
4656 cfg.offlinests = true;
4657 } else if (!strcmp(arg, "offlinests,ns")) {
4658 // track changes in offline data collection status, disable auto standby
4659 cfg.offlinests = cfg.offlinests_ns = true;
4660 } else if (!strcmp(arg, "selfteststs")) {
4661 // track changes in self-test execution status
4662 cfg.selfteststs = true;
4663 } else if (!strcmp(arg, "selfteststs,ns")) {
4664 // track changes in self-test execution status, disable auto standby
4665 cfg.selfteststs = cfg.selfteststs_ns = true;
4666 } else if (!strncmp(arg, "scterc,", sizeof("scterc,")-1)) {
4667 // set SCT Error Recovery Control
4668 unsigned rt = ~0, wt = ~0; int nc = -1;
4669 sscanf(arg,"scterc,%u,%u%n", &rt, &wt, &nc);
4670 if (nc == (int)strlen(arg) && rt <= 999 && wt <= 999) {
4671 cfg.sct_erc_set = true;
4672 cfg.sct_erc_readtime = rt;
4673 cfg.sct_erc_writetime = wt;
4674 }
4675 else
4676 badarg = 1;
4677 } else {
4678 badarg = 1;
4679 }
4680 break;
4681 case 'a':
4682 // monitor everything
4683 cfg.smartcheck = true;
4684 cfg.prefail = true;
4685 cfg.usagefailed = true;
4686 cfg.usage = true;
4687 cfg.selftest = true;
4688 cfg.errorlog = true;
4689 cfg.selfteststs = true;
4690 break;
4691 case 'o':
4692 // automatic offline testing enable/disable
4693 if (!(arg = strtok(nullptr, delim))) {
4694 missingarg = 1;
4695 } else if (!strcmp(arg, "on")) {
4696 cfg.autoofflinetest = 2;
4697 } else if (!strcmp(arg, "off")) {
4698 cfg.autoofflinetest = 1;
4699 } else {
4700 badarg = 1;
4701 }
4702 break;
4703 case 'n':
4704 // skip disk check if in idle or standby mode
4705 if (!(arg = strtok(nullptr, delim)))
4706 missingarg = 1;
4707 else {
4708 char *endptr = nullptr;
4709 char *next = strchr(const_cast<char*>(arg), ',');
4710
4711 cfg.powerquiet = false;
4712 cfg.powerskipmax = 0;
4713
4714 if (next)
4715 *next = '\0';
4716 if (!strcmp(arg, "never"))
4717 cfg.powermode = 0;
4718 else if (!strcmp(arg, "sleep"))
4719 cfg.powermode = 1;
4720 else if (!strcmp(arg, "standby"))
4721 cfg.powermode = 2;
4722 else if (!strcmp(arg, "idle"))
4723 cfg.powermode = 3;
4724 else
4725 badarg = 1;
4726
4727 // if optional arguments are present
4728 if (!badarg && next) {
4729 next++;
4730 cfg.powerskipmax = strtol(next, &endptr, 10);
4731 if (endptr == next)
4732 cfg.powerskipmax = 0;
4733 else {
4734 next = endptr + (*endptr != '\0');
4735 if (cfg.powerskipmax <= 0)
4736 badarg = 1;
4737 }
4738 if (*next != '\0') {
4739 if (!strcmp("q", next))
4740 cfg.powerquiet = true;
4741 else {
4742 badarg = 1;
4743 }
4744 }
4745 }
4746 }
4747 break;
4748 case 'S':
4749 // automatic attribute autosave enable/disable
4750 if (!(arg = strtok(nullptr, delim))) {
4751 missingarg = 1;
4752 } else if (!strcmp(arg, "on")) {
4753 cfg.autosave = 2;
4754 } else if (!strcmp(arg, "off")) {
4755 cfg.autosave = 1;
4756 } else {
4757 badarg = 1;
4758 }
4759 break;
4760 case 's':
4761 // warn user, and delete any previously given -s REGEXP Directives
4762 if (!cfg.test_regex.empty()){
4763 PrintOut(LOG_INFO, "File %s line %d (drive %s): ignoring previous Test Directive -s %s\n",
4764 configfile, lineno, name, cfg.test_regex.get_pattern());
4766 }
4767 // check for missing argument
4768 if (!(arg = strtok(nullptr, delim))) {
4769 missingarg = 1;
4770 }
4771 // Compile regex
4772 else {
4773 if (!cfg.test_regex.compile(arg)) {
4774 // not a valid regular expression!
4775 PrintOut(LOG_CRIT, "File %s line %d (drive %s): -s argument \"%s\" is INVALID extended regular expression. %s.\n",
4776 configfile, lineno, name, arg, cfg.test_regex.get_errmsg());
4777 return -1;
4778 }
4779 // Do a bit of sanity checking and warn user if we think that
4780 // their regexp is "strange". User probably confused about shell
4781 // glob(3) syntax versus regular expression syntax regexp(7).
4782 // Check also for possible invalid number of digits in ':NNN[-LLL]' suffix.
4783 static const regular_expression syntax_check(
4784 "[^]$()*+./:?^[|0-9LSCOncr-]+|"
4785 ":[0-9]{0,2}($|[^0-9])|:[0-9]{4,}|"
4786 ":[0-9]{3}-(000|[0-9]{0,2}($|[^0-9])|[0-9]{4,})"
4787 );
4789 if (syntax_check.execute(arg, 1, &range) && 0 <= range.rm_so && range.rm_so < range.rm_eo)
4790 PrintOut(LOG_INFO, "File %s line %d (drive %s): warning, \"%.*s\" looks odd in "
4791 "extended regular expression \"%s\"\n",
4792 configfile, lineno, name, (int)(range.rm_eo - range.rm_so), arg + range.rm_so, arg);
4793 }
4794 break;
4795 case 'm':
4796 // send email to address that follows
4797 if (!(arg = strtok(nullptr, delim)))
4798 missingarg = 1;
4799 else {
4800 if (!cfg.emailaddress.empty())
4801 PrintOut(LOG_INFO, "File %s line %d (drive %s): ignoring previous Address Directive -m %s\n",
4802 configfile, lineno, name, cfg.emailaddress.c_str());
4803 cfg.emailaddress = arg;
4804 }
4805 break;
4806 case 'M':
4807 // email warning options
4808 if (!(arg = strtok(nullptr, delim)))
4809 missingarg = 1;
4810 else if (!strcmp(arg, "once"))
4812 else if (!strcmp(arg, "always"))
4814 else if (!strcmp(arg, "daily"))
4816 else if (!strcmp(arg, "diminishing"))
4818 else if (!strcmp(arg, "test"))
4819 cfg.emailtest = true;
4820 else if (!strcmp(arg, "exec")) {
4821 // Get the next argument (the command line)
4822#ifdef _WIN32
4823 // Allow "/path name/with spaces/..." on Windows
4824 arg = strtok_dequote(delim);
4825 if (arg && arg[0] == '"') {
4826 PrintOut(LOG_CRIT, "File %s line %d (drive %s): Directive %s 'exec' argument: missing closing quote\n",
4827 configfile, lineno, name, token);
4828 return -1;
4829 }
4830#else
4831 arg = strtok(nullptr, delim);
4832#endif
4833 if (!arg) {
4834 PrintOut(LOG_CRIT, "File %s line %d (drive %s): Directive %s 'exec' argument must be followed by executable path.\n",
4835 configfile, lineno, name, token);
4836 return -1;
4837 }
4838 // Free the last cmd line given if any, and copy new one
4839 if (!cfg.emailcmdline.empty())
4840 PrintOut(LOG_INFO, "File %s line %d (drive %s): ignoring previous mail Directive -M exec %s\n",
4841 configfile, lineno, name, cfg.emailcmdline.c_str());
4842 cfg.emailcmdline = arg;
4843 }
4844 else
4845 badarg = 1;
4846 break;
4847 case 'i':
4848 // ignore failure of usage attribute
4849 if ((val = GetInteger((arg = strtok(nullptr, delim)), name, token, lineno, configfile, 1, 255)) < 0)
4850 return -1;
4852 break;
4853 case 'I':
4854 // ignore attribute for tracking purposes
4855 if ((val = GetInteger((arg = strtok(nullptr, delim)), name, token, lineno, configfile, 1, 255)) < 0)
4856 return -1;
4858 break;
4859 case 'r':
4860 // print raw value when tracking
4861 if ((val = GetInteger((arg = strtok(nullptr, delim)), name, token, lineno, configfile, 1, 255, excl)) < 0)
4862 return -1;
4864 if (*excl == '!') // attribute change is critical
4866 break;
4867 case 'R':
4868 // track changes in raw value (forces printing of raw value)
4869 if ((val = GetInteger((arg = strtok(nullptr, delim)), name, token, lineno, configfile, 1, 255, excl)) < 0)
4870 return -1;
4872 if (*excl == '!') // raw value change is critical
4874 break;
4875 case 'W':
4876 // track Temperature
4877 if (Get3Integers((arg = strtok(nullptr, delim)), name, token, lineno, configfile,
4878 &cfg.tempdiff, &cfg.tempinfo, &cfg.tempcrit) < 0)
4879 return -1;
4880 break;
4881 case 'v':
4882 // non-default vendor-specific attribute meaning
4883 if (!(arg = strtok(nullptr, delim))) {
4884 missingarg = 1;
4885 } else if (!parse_attribute_def(arg, cfg.attribute_defs, PRIOR_USER)) {
4886 badarg = 1;
4887 }
4888 break;
4889 case 'P':
4890 // Define use of drive-specific presets.
4891 if (!(arg = strtok(nullptr, delim))) {
4892 missingarg = 1;
4893 } else if (!strcmp(arg, "use")) {
4894 cfg.ignorepresets = false;
4895 } else if (!strcmp(arg, "ignore")) {
4896 cfg.ignorepresets = true;
4897 } else if (!strcmp(arg, "show")) {
4898 cfg.showpresets = true;
4899 } else if (!strcmp(arg, "showall")) {
4901 } else {
4902 badarg = 1;
4903 }
4904 break;
4905
4906 case 'e':
4907 // Various ATA settings
4908 if (!(arg = strtok(nullptr, delim))) {
4909 missingarg = true;
4910 }
4911 else {
4912 char arg2[16+1]; unsigned uval;
4913 int n1 = -1, n2 = -1, n3 = -1, len = strlen(arg);
4914 if (sscanf(arg, "%16[^,=]%n%*[,=]%n%u%n", arg2, &n1, &n2, &uval, &n3) >= 1
4915 && (n1 == len || n2 > 0)) {
4916 bool on = (n2 > 0 && !strcmp(arg+n2, "on"));
4917 bool off = (n2 > 0 && !strcmp(arg+n2, "off"));
4918 if (n3 != len)
4919 uval = ~0U;
4920
4921 if (!strcmp(arg2, "aam")) {
4922 if (off)
4923 cfg.set_aam = -1;
4924 else if (uval <= 254)
4925 cfg.set_aam = uval + 1;
4926 else
4927 badarg = true;
4928 }
4929 else if (!strcmp(arg2, "apm")) {
4930 if (off)
4931 cfg.set_apm = -1;
4932 else if (1 <= uval && uval <= 254)
4933 cfg.set_apm = uval + 1;
4934 else
4935 badarg = true;
4936 }
4937 else if (!strcmp(arg2, "lookahead")) {
4938 if (off)
4939 cfg.set_lookahead = -1;
4940 else if (on)
4941 cfg.set_lookahead = 1;
4942 else
4943 badarg = true;
4944 }
4945 else if (!strcmp(arg, "security-freeze")) {
4946 cfg.set_security_freeze = true;
4947 }
4948 else if (!strcmp(arg2, "standby")) {
4949 if (off)
4950 cfg.set_standby = 0 + 1;
4951 else if (uval <= 255)
4952 cfg.set_standby = uval + 1;
4953 else
4954 badarg = true;
4955 }
4956 else if (!strcmp(arg2, "wcache")) {
4957 if (off)
4958 cfg.set_wcache = -1;
4959 else if (on)
4960 cfg.set_wcache = 1;
4961 else
4962 badarg = true;
4963 }
4964 else if (!strcmp(arg2, "dsn")) {
4965 if (off)
4966 cfg.set_dsn = -1;
4967 else if (on)
4968 cfg.set_dsn = 1;
4969 else
4970 badarg = true;
4971 }
4972 else
4973 badarg = true;
4974 }
4975 else
4976 badarg = true;
4977 }
4978 break;
4979
4980 case 'c':
4981 // Override command line options
4982 {
4983 if (!(arg = strtok(nullptr, delim))) {
4984 missingarg = true;
4985 break;
4986 }
4987 int n = 0, nc = -1, len = strlen(arg);
4988 if ( ( sscanf(arg, "i=%d%n", &n, &nc) == 1
4989 || sscanf(arg, "interval=%d%n", &n, &nc) == 1)
4990 && nc == len && n >= 10)
4991 cfg.checktime = n;
4992 else
4993 badarg = true;
4994 }
4995 break;
4996
4997 default:
4998 // Directive not recognized
4999 PrintOut(LOG_CRIT,"File %s line %d (drive %s): unknown Directive: %s\n",
5000 configfile, lineno, name, token);
5001 PrintOut(LOG_CRIT, "Run smartd -D to print a list of valid Directives.\n");
5002 return -1;
5003 }
5004 if (missingarg) {
5005 PrintOut(LOG_CRIT, "File %s line %d (drive %s): Missing argument to %s Directive\n",
5006 configfile, lineno, name, token);
5007 }
5008 if (badarg) {
5009 PrintOut(LOG_CRIT, "File %s line %d (drive %s): Invalid argument to %s Directive: %s\n",
5010 configfile, lineno, name, token, arg);
5011 }
5012 if (missingarg || badarg) {
5013 PrintOut(LOG_CRIT, "Valid arguments to %s Directive are: ", token);
5014 printoutvaliddirectiveargs(LOG_CRIT, sym);
5015 PrintOut(LOG_CRIT, "\n");
5016 return -1;
5017 }
5018
5019 return 1;
5020}
5021
5022// Scan directive for configuration file
5023#define SCANDIRECTIVE "DEVICESCAN"
5024
5025// This is the routine that adds things to the conf_entries list.
5026//
5027// Return values are:
5028// 1: parsed a normal line
5029// 0: found DEFAULT setting or comment or blank line
5030// -1: found SCANDIRECTIVE line
5031// -2: found an error
5032//
5033// Note: this routine modifies *line from the caller!
5034static int ParseConfigLine(dev_config_vector & conf_entries, dev_config & default_conf,
5035 smart_devtype_list & scan_types, int lineno, /*const*/ char * line)
5036{
5037 const char *delim = " \n\t";
5038
5039 // get first token: device name. If a comment, skip line
5040 const char * name = strtok(line, delim);
5041 if (!name || *name == '#')
5042 return 0;
5043
5044 // Check device name for DEFAULT or DEVICESCAN
5045 int retval;
5046 if (!strcmp("DEFAULT", name)) {
5047 retval = 0;
5048 // Restart with empty defaults
5049 default_conf = dev_config();
5050 }
5051 else {
5052 retval = (!strcmp(SCANDIRECTIVE, name) ? -1 : 1);
5053 // Init new entry with current defaults
5054 conf_entries.push_back(default_conf);
5055 }
5056 dev_config & cfg = (retval ? conf_entries.back() : default_conf);
5057
5058 cfg.name = name; // Later replaced by dev->get_info().info_name
5059 cfg.dev_name = name; // If DEVICESCAN later replaced by get->dev_info().dev_name
5060 cfg.lineno = lineno;
5061
5062 // parse tokens one at a time from the file.
5063 while (char * token = strtok(nullptr, delim)) {
5064 int rc = ParseToken(token, cfg, scan_types);
5065 if (rc < 0)
5066 // error found on the line
5067 return -2;
5068
5069 if (rc == 0)
5070 // No tokens left
5071 break;
5072
5073 // PrintOut(LOG_INFO,"Parsed token %s\n",token);
5074 }
5075
5076 // Check for multiple -d TYPE directives
5077 if (retval != -1 && scan_types.size() > 1) {
5078 PrintOut(LOG_CRIT, "Drive: %s, invalid multiple -d TYPE Directives on line %d of file %s\n",
5079 cfg.name.c_str(), cfg.lineno, configfile);
5080 return -2;
5081 }
5082
5083 // Don't perform checks below for DEFAULT entries
5084 if (retval == 0)
5085 return retval;
5086
5087 // If NO monitoring directives are set, then set all of them.
5088 if (!( cfg.smartcheck || cfg.selftest
5089 || cfg.errorlog || cfg.xerrorlog
5090 || cfg.offlinests || cfg.selfteststs
5091 || cfg.usagefailed || cfg.prefail || cfg.usage
5092 || cfg.tempdiff || cfg.tempinfo || cfg.tempcrit)) {
5093
5094 PrintOut(LOG_INFO,"Drive: %s, implied '-a' Directive on line %d of file %s\n",
5095 cfg.name.c_str(), cfg.lineno, configfile);
5096
5097 cfg.smartcheck = true;
5098 cfg.usagefailed = true;
5099 cfg.prefail = true;
5100 cfg.usage = true;
5101 cfg.selftest = true;
5102 cfg.errorlog = true;
5103 cfg.selfteststs = true;
5104 }
5105
5106 // additional sanity check. Has user set -M options without -m?
5107 if ( cfg.emailaddress.empty()
5108 && (!cfg.emailcmdline.empty() || cfg.emailfreq != emailfreqs::unknown || cfg.emailtest)) {
5109 PrintOut(LOG_CRIT,"Drive: %s, -M Directive(s) on line %d of file %s need -m ADDRESS Directive\n",
5110 cfg.name.c_str(), cfg.lineno, configfile);
5111 return -2;
5112 }
5113
5114 // has the user has set <nomailer>?
5115 if (cfg.emailaddress == "<nomailer>") {
5116 // check that -M exec is also set
5117 if (cfg.emailcmdline.empty()){
5118 PrintOut(LOG_CRIT,"Drive: %s, -m <nomailer> Directive on line %d of file %s needs -M exec Directive\n",
5119 cfg.name.c_str(), cfg.lineno, configfile);
5120 return -2;
5121 }
5122 // From here on the sign of <nomailer> is cfg.emailaddress.empty() and !cfg.emailcmdline.empty()
5123 cfg.emailaddress.clear();
5124 }
5125
5126 return retval;
5127}
5128
5129// Parses a configuration file. Return values are:
5130// N=>0: found N entries
5131// -1: syntax error in config file
5132// -2: config file does not exist
5133// -3: config file exists but cannot be read
5134//
5135// In the case where the return value is 0, there are three
5136// possibilities:
5137// Empty configuration file ==> conf_entries.empty()
5138// No configuration file ==> conf_entries[0].lineno == 0
5139// SCANDIRECTIVE found ==> conf_entries.back().lineno != 0 (size >= 1)
5140static int ParseConfigFile(dev_config_vector & conf_entries, smart_devtype_list & scan_types)
5141{
5142 // maximum line length in configuration file
5143 const int MAXLINELEN = 256;
5144 // maximum length of a continued line in configuration file
5145 const int MAXCONTLINE = 1023;
5146
5147 stdio_file f;
5148 // Open config file, if it exists and is not <stdin>
5149 if (!(configfile == configfile_stdin)) { // pointer comparison ok here
5150 if (!f.open(configfile,"r") && (errno!=ENOENT || !configfile_alt.empty())) {
5151 // file exists but we can't read it or it should exist due to '-c' option
5152 int ret = (errno!=ENOENT ? -3 : -2);
5153 PrintOut(LOG_CRIT,"%s: Unable to open configuration file %s\n",
5154 strerror(errno),configfile);
5155 return ret;
5156 }
5157 }
5158 else // read from stdin ('-c -' option)
5159 f.open(stdin);
5160
5161 // Start with empty defaults
5162 dev_config default_conf;
5163
5164 // No configuration file found -- use fake one
5165 int entry = 0;
5166 if (!f) {
5167 char fakeconfig[] = SCANDIRECTIVE " -a"; // TODO: Remove this hack, build cfg_entry.
5168
5169 if (ParseConfigLine(conf_entries, default_conf, scan_types, 0, fakeconfig) != -1)
5170 throw std::logic_error("Internal error parsing " SCANDIRECTIVE);
5171 return 0;
5172 }
5173
5174#ifdef __CYGWIN__
5175 setmode(fileno(f), O_TEXT); // Allow files with \r\n
5176#endif
5177
5178 // configuration file exists
5179 PrintOut(LOG_INFO,"Opened configuration file %s\n",configfile);
5180
5181 // parse config file line by line
5182 int lineno = 1, cont = 0, contlineno = 0;
5183 char line[MAXLINELEN+2];
5184 char fullline[MAXCONTLINE+1];
5185
5186 for (;;) {
5187 int len=0,scandevice;
5188 char *lastslash;
5189 char *comment;
5190 char *code;
5191
5192 // make debugging simpler
5193 memset(line,0,sizeof(line));
5194
5195 // get a line
5196 code=fgets(line, MAXLINELEN+2, f);
5197
5198 // are we at the end of the file?
5199 if (!code){
5200 if (cont) {
5201 scandevice = ParseConfigLine(conf_entries, default_conf, scan_types, contlineno, fullline);
5202 // See if we found a SCANDIRECTIVE directive
5203 if (scandevice==-1)
5204 return 0;
5205 // did we find a syntax error
5206 if (scandevice==-2)
5207 return -1;
5208 // the final line is part of a continuation line
5209 entry+=scandevice;
5210 }
5211 break;
5212 }
5213
5214 // input file line number
5215 contlineno++;
5216
5217 // See if line is too long
5218 len=strlen(line);
5219 if (len>MAXLINELEN){
5220 const char *warn;
5221 if (line[len-1]=='\n')
5222 warn="(including newline!) ";
5223 else
5224 warn="";
5225 PrintOut(LOG_CRIT,"Error: line %d of file %s %sis more than MAXLINELEN=%d characters.\n",
5226 (int)contlineno,configfile,warn,(int)MAXLINELEN);
5227 return -1;
5228 }
5229
5230 // Ignore anything after comment symbol
5231 if ((comment=strchr(line,'#'))){
5232 *comment='\0';
5233 len=strlen(line);
5234 }
5235
5236 // is the total line (made of all continuation lines) too long?
5237 if (cont+len>MAXCONTLINE){
5238 PrintOut(LOG_CRIT,"Error: continued line %d (actual line %d) of file %s is more than MAXCONTLINE=%d characters.\n",
5239 lineno, (int)contlineno, configfile, (int)MAXCONTLINE);
5240 return -1;
5241 }
5242
5243 // copy string so far into fullline, and increment length
5244 snprintf(fullline+cont, sizeof(fullline)-cont, "%s" ,line);
5245 cont+=len;
5246
5247 // is this a continuation line. If so, replace \ by space and look at next line
5248 if ( (lastslash=strrchr(line,'\\')) && !strtok(lastslash+1," \n\t")){
5249 *(fullline+(cont-len)+(lastslash-line))=' ';
5250 continue;
5251 }
5252
5253 // Not a continuation line. Parse it
5254 scan_types.clear();
5255 scandevice = ParseConfigLine(conf_entries, default_conf, scan_types, contlineno, fullline);
5256
5257 // did we find a scandevice directive?
5258 if (scandevice==-1)
5259 return 0;
5260 // did we find a syntax error
5261 if (scandevice==-2)
5262 return -1;
5263
5264 entry+=scandevice;
5265 lineno++;
5266 cont=0;
5267 }
5268
5269 // note -- may be zero if syntax of file OK, but no valid entries!
5270 return entry;
5271}
5272
5273/* Prints the message "=======> VALID ARGUMENTS ARE: <LIST> <=======\n", where
5274 <LIST> is the list of valid arguments for option opt. */
5275static void PrintValidArgs(char opt)
5276{
5277 const char *s;
5278
5279 PrintOut(LOG_CRIT, "=======> VALID ARGUMENTS ARE: ");
5280 if (!(s = GetValidArgList(opt)))
5281 PrintOut(LOG_CRIT, "Error constructing argument list for option %c", opt);
5282 else
5283 PrintOut(LOG_CRIT, "%s", (char *)s);
5284 PrintOut(LOG_CRIT, " <=======\n");
5285}
5286
5287#ifndef _WIN32
5288// Report error and return false if specified path is not absolute.
5289static bool check_abs_path(char option, const std::string & path)
5290{
5291 if (path.empty() || path[0] == '/')
5292 return true;
5293
5294 debugmode = 1;
5295 PrintHead();
5296 PrintOut(LOG_CRIT, "=======> INVALID ARGUMENT TO -%c: %s <=======\n\n", option, path.c_str());
5297 PrintOut(LOG_CRIT, "Error: relative path names are not allowed\n\n");
5298 return false;
5299}
5300#endif // !_WIN32
5301
5302// Parses input line, prints usage message and
5303// version/license/copyright messages
5304static int parse_options(int argc, char **argv)
5305{
5306 // Init default path names
5307#ifndef _WIN32
5308 configfile = SMARTMONTOOLS_SYSCONFDIR "/smartd.conf";
5309 warning_script = SMARTMONTOOLS_SMARTDSCRIPTDIR "/smartd_warning.sh";
5310#else
5311 std::string exedir = get_exe_dir();
5312 static std::string configfile_str = exedir + "/smartd.conf";
5313 configfile = configfile_str.c_str();
5314 warning_script = exedir + "/smartd_warning.cmd";
5315#endif
5316
5317 // Please update GetValidArgList() if you edit shortopts
5318 static const char shortopts[] = "c:l:q:dDni:p:r:s:A:B:w:Vh?"
5319#if defined(HAVE_POSIX_API) || defined(_WIN32)
5320 "u:"
5321#endif
5322#ifdef HAVE_LIBCAP_NG
5323 "C"
5324#endif
5325 ;
5326 // Please update GetValidArgList() if you edit longopts
5327 struct option longopts[] = {
5328 { "configfile", required_argument, 0, 'c' },
5329 { "logfacility", required_argument, 0, 'l' },
5330 { "quit", required_argument, 0, 'q' },
5331 { "debug", no_argument, 0, 'd' },
5332 { "showdirectives", no_argument, 0, 'D' },
5333 { "interval", required_argument, 0, 'i' },
5334#ifndef _WIN32
5335 { "no-fork", no_argument, 0, 'n' },
5336#else
5337 { "service", no_argument, 0, 'n' },
5338#endif
5339 { "pidfile", required_argument, 0, 'p' },
5340 { "report", required_argument, 0, 'r' },
5341 { "savestates", required_argument, 0, 's' },
5342 { "attributelog", required_argument, 0, 'A' },
5343 { "drivedb", required_argument, 0, 'B' },
5344 { "warnexec", required_argument, 0, 'w' },
5345 { "version", no_argument, 0, 'V' },
5346 { "license", no_argument, 0, 'V' },
5347 { "copyright", no_argument, 0, 'V' },
5348 { "help", no_argument, 0, 'h' },
5349 { "usage", no_argument, 0, 'h' },
5350#if defined(HAVE_POSIX_API) || defined(_WIN32)
5351 { "warn-as-user", required_argument, 0, 'u' },
5352#endif
5353#ifdef HAVE_LIBCAP_NG
5354 { "capabilities", optional_argument, 0, 'C' },
5355#endif
5356 { 0, 0, 0, 0 }
5357 };
5358
5359 opterr=optopt=0;
5360 bool badarg = false;
5361 const char * badarg_msg = nullptr;
5362 bool use_default_db = true; // set false on '-B FILE'
5363
5364 // Parse input options.
5365 int optchar;
5366 while ((optchar = getopt_long(argc, argv, shortopts, longopts, nullptr)) != -1) {
5367 char *arg;
5368 char *tailptr;
5369 long lchecktime;
5370
5371 switch(optchar) {
5372 case 'q':
5373 // when to quit
5374 quit_nodev0 = false;
5375 if (!strcmp(optarg, "nodev"))
5376 quit = QUIT_NODEV;
5377 else if (!strcmp(optarg, "nodev0")) {
5378 quit = QUIT_NODEV;
5379 quit_nodev0 = true;
5380 }
5381 else if (!strcmp(optarg, "nodevstartup"))
5383 else if (!strcmp(optarg, "nodev0startup")) {
5385 quit_nodev0 = true;
5386 }
5387 else if (!strcmp(optarg, "errors"))
5388 quit = QUIT_ERRORS;
5389 else if (!strcmp(optarg, "errors,nodev0")) {
5390 quit = QUIT_ERRORS;
5391 quit_nodev0 = true;
5392 }
5393 else if (!strcmp(optarg, "never"))
5394 quit = QUIT_NEVER;
5395 else if (!strcmp(optarg, "onecheck")) {
5397 debugmode = 1;
5398 }
5399 else if (!strcmp(optarg, "showtests")) {
5401 debugmode = 1;
5402 }
5403 else
5404 badarg = true;
5405 break;
5406 case 'l':
5407 // set the log facility level
5408 if (!strcmp(optarg, "daemon"))
5409 facility=LOG_DAEMON;
5410 else if (!strcmp(optarg, "local0"))
5411 facility=LOG_LOCAL0;
5412 else if (!strcmp(optarg, "local1"))
5413 facility=LOG_LOCAL1;
5414 else if (!strcmp(optarg, "local2"))
5415 facility=LOG_LOCAL2;
5416 else if (!strcmp(optarg, "local3"))
5417 facility=LOG_LOCAL3;
5418 else if (!strcmp(optarg, "local4"))
5419 facility=LOG_LOCAL4;
5420 else if (!strcmp(optarg, "local5"))
5421 facility=LOG_LOCAL5;
5422 else if (!strcmp(optarg, "local6"))
5423 facility=LOG_LOCAL6;
5424 else if (!strcmp(optarg, "local7"))
5425 facility=LOG_LOCAL7;
5426 else
5427 badarg = true;
5428 break;
5429 case 'd':
5430 // enable debug mode
5431 debugmode = 1;
5432 break;
5433 case 'n':
5434 // don't fork()
5435#ifndef _WIN32 // On Windows, --service is already handled by daemon_main()
5436 do_fork = false;
5437#endif
5438 break;
5439 case 'D':
5440 // print summary of all valid directives
5441 debugmode = 1;
5442 Directives();
5443 return 0;
5444 case 'i':
5445 // Period (time interval) for checking
5446 // strtol will set errno in the event of overflow, so we'll check it.
5447 errno = 0;
5448 lchecktime = strtol(optarg, &tailptr, 10);
5449 if (*tailptr != '\0' || lchecktime < 10 || lchecktime > INT_MAX || errno) {
5450 debugmode=1;
5451 PrintHead();
5452 PrintOut(LOG_CRIT, "======> INVALID INTERVAL: %s <=======\n", optarg);
5453 PrintOut(LOG_CRIT, "======> INTERVAL MUST BE INTEGER BETWEEN %d AND %d <=======\n", 10, INT_MAX);
5454 PrintOut(LOG_CRIT, "\nUse smartd -h to get a usage summary\n\n");
5455 return EXIT_BADCMD;
5456 }
5457 checktime = (int)lchecktime;
5458 break;
5459 case 'r':
5460 // report IOCTL transactions
5461 {
5462 int n1 = -1, n2 = -1, len = strlen(optarg);
5463 char s[9+1]; unsigned i = 1;
5464 sscanf(optarg, "%9[a-z]%n,%u%n", s, &n1, &i, &n2);
5465 if (!((n1 == len || n2 == len) && 1 <= i && i <= 4)) {
5466 badarg = true;
5467 } else if (!strcmp(s,"ioctl")) {
5469 } else if (!strcmp(s,"ataioctl")) {
5470 ata_debugmode = i;
5471 } else if (!strcmp(s,"scsiioctl")) {
5472 scsi_debugmode = i;
5473 } else if (!strcmp(s,"nvmeioctl")) {
5474 nvme_debugmode = i;
5475 } else {
5476 badarg = true;
5477 }
5478 }
5479 break;
5480 case 'c':
5481 // alternate configuration file
5482 if (strcmp(optarg,"-"))
5483 configfile = (configfile_alt = optarg).c_str();
5484 else // read from stdin
5486 break;
5487 case 'p':
5488 // output file with PID number
5489 pid_file = optarg;
5490 break;
5491 case 's':
5492 // path prefix of persistent state file
5493 state_path_prefix = (strcmp(optarg, "-") ? optarg : "");
5494 break;
5495 case 'A':
5496 // path prefix of attribute log file
5497 attrlog_path_prefix = (strcmp(optarg, "-") ? optarg : "");
5498 break;
5499 case 'B':
5500 {
5501 const char * path = optarg;
5502 if (*path == '+' && path[1])
5503 path++;
5504 else
5505 use_default_db = false;
5506 unsigned char savedebug = debugmode; debugmode = 1;
5507 if (!read_drive_database(path))
5508 return EXIT_BADCMD;
5509 debugmode = savedebug;
5510 }
5511 break;
5512 case 'w':
5513 warning_script = optarg;
5514 break;
5515#ifdef HAVE_POSIX_API
5516 case 'u':
5517 warn_as_user = false;
5518 if (strcmp(optarg, "-")) {
5519 warn_uname = warn_gname = "unknown";
5520 badarg_msg = parse_ugid(optarg, warn_uid, warn_gid,
5521 warn_uname, warn_gname );
5522 if (badarg_msg)
5523 break;
5524 warn_as_user = true;
5525 }
5526 break;
5527#elif defined(_WIN32)
5528 case 'u':
5529 if (!strcmp(optarg, "restricted"))
5530 warn_as_restr_user = true;
5531 else if (!strcmp(optarg, "unchanged"))
5532 warn_as_restr_user = false;
5533 else
5534 badarg = true;
5535 break;
5536#endif // HAVE_POSIX_API ||_WIN32
5537 case 'V':
5538 // print version and CVS info
5539 debugmode = 1;
5540 PrintOut(LOG_INFO, "%s", format_version_info("smartd", 3 /*full*/).c_str());
5541 return 0;
5542#ifdef HAVE_LIBCAP_NG
5543 case 'C':
5544 // enable capabilities
5545 if (!optarg)
5546 capabilities_mode = 1;
5547 else if (!strcmp(optarg, "mail"))
5548 capabilities_mode = 2;
5549 else
5550 badarg = true;
5551 break;
5552#endif
5553 case 'h':
5554 // help: print summary of command-line options
5555 debugmode=1;
5556 PrintHead();
5557 Usage();
5558 return 0;
5559 case '?':
5560 default:
5561 // unrecognized option
5562 debugmode=1;
5563 PrintHead();
5564 // Point arg to the argument in which this option was found.
5565 // Note: getopt_long() may set optind > argc (e.g. musl libc)
5566 arg = argv[optind <= argc ? optind - 1 : argc - 1];
5567 // Check whether the option is a long option that doesn't map to -h.
5568 if (arg[1] == '-' && optchar != 'h') {
5569 // Iff optopt holds a valid option then argument must be missing.
5570 if (optopt && strchr(shortopts, optopt)) {
5571 PrintOut(LOG_CRIT, "=======> ARGUMENT REQUIRED FOR OPTION: %s <=======\n",arg+2);
5572 PrintValidArgs(optopt);
5573 } else {
5574 PrintOut(LOG_CRIT, "=======> UNRECOGNIZED OPTION: %s <=======\n\n",arg+2);
5575 }
5576 PrintOut(LOG_CRIT, "\nUse smartd --help to get a usage summary\n\n");
5577 return EXIT_BADCMD;
5578 }
5579 if (optopt) {
5580 // Iff optopt holds a valid option then argument must be missing.
5581 if (strchr(shortopts, optopt)){
5582 PrintOut(LOG_CRIT, "=======> ARGUMENT REQUIRED FOR OPTION: %c <=======\n",optopt);
5583 PrintValidArgs(optopt);
5584 } else {
5585 PrintOut(LOG_CRIT, "=======> UNRECOGNIZED OPTION: %c <=======\n\n",optopt);
5586 }
5587 PrintOut(LOG_CRIT, "\nUse smartd -h to get a usage summary\n\n");
5588 return EXIT_BADCMD;
5589 }
5590 Usage();
5591 return 0;
5592 }
5593
5594 // Check to see if option had an unrecognized or incorrect argument.
5595 if (badarg || badarg_msg) {
5596 debugmode=1;
5597 PrintHead();
5598 // It would be nice to print the actual option name given by the user
5599 // here, but we just print the short form. Please fix this if you know
5600 // a clean way to do it.
5601 PrintOut(LOG_CRIT, "=======> INVALID ARGUMENT TO -%c: %s <======= \n", optchar, optarg);
5602 if (badarg_msg)
5603 PrintOut(LOG_CRIT, "%s\n", badarg_msg);
5604 else
5605 PrintValidArgs(optchar);
5606 PrintOut(LOG_CRIT, "\nUse smartd -h to get a usage summary\n\n");
5607 return EXIT_BADCMD;
5608 }
5609 }
5610
5611 // non-option arguments are not allowed
5612 if (argc > optind) {
5613 debugmode=1;
5614 PrintHead();
5615 PrintOut(LOG_CRIT, "=======> UNRECOGNIZED ARGUMENT: %s <=======\n\n", argv[optind]);
5616 PrintOut(LOG_CRIT, "\nUse smartd -h to get a usage summary\n\n");
5617 return EXIT_BADCMD;
5618 }
5619
5620 // no pidfile in debug mode
5621 if (debugmode && !pid_file.empty()) {
5622 debugmode=1;
5623 PrintHead();
5624 PrintOut(LOG_CRIT, "=======> INVALID CHOICE OF OPTIONS: -d and -p <======= \n\n");
5625 PrintOut(LOG_CRIT, "Error: pid file %s not written in debug (-d) mode\n\n", pid_file.c_str());
5626 return EXIT_BADCMD;
5627 }
5628
5629#ifndef _WIN32
5630 if (!debugmode) {
5631 // absolute path names are required due to chdir('/') in daemon_init()
5632 if (!( check_abs_path('p', pid_file)
5635 return EXIT_BADCMD;
5636 }
5637#endif
5638
5639#ifdef _WIN32
5640 if (warn_as_restr_user && !popen_as_restr_check()) {
5641 // debugmode=1 // would suppress messages to eventlog or log file
5642 PrintHead();
5643 PrintOut(LOG_CRIT, "Option '--warn-as-user=restricted' is not effective if the current user\n");
5644 PrintOut(LOG_CRIT, "is the local 'SYSTEM' or 'Administrator' account\n\n");
5645 return EXIT_BADCMD;
5646 }
5647#endif
5648
5649 // Read or init drive database
5650 {
5651 unsigned char savedebug = debugmode; debugmode = 1;
5652 if (!init_drive_database(use_default_db))
5653 return EXIT_BADCMD;
5654 debugmode = savedebug;
5655 }
5656
5657 // Check option compatibility of notify support
5658 // cppcheck-suppress knownConditionTrueFalse
5659 if (!notify_post_init())
5660 return EXIT_BADCMD;
5661
5662 // print header, don't write Copyright line to syslog
5663 PrintOut(LOG_INFO, "%s\n", format_version_info("smartd", (debugmode ? 2 : 1)).c_str());
5664
5665 // No error, continue in main_worker()
5666 return -1;
5667}
5668
5669// Function we call if no configuration file was found or if the
5670// SCANDIRECTIVE Directive was found. It makes entries for device
5671// names returned by scan_smart_devices() in os_OSNAME.cpp
5672static int MakeConfigEntries(const dev_config & base_cfg,
5673 dev_config_vector & conf_entries, smart_device_list & scanned_devs,
5674 const smart_devtype_list & types)
5675{
5676 // make list of devices
5677 smart_device_list devlist;
5678 if (!smi()->scan_smart_devices(devlist, types)) {
5679 PrintOut(LOG_CRIT, "DEVICESCAN failed: %s\n", smi()->get_errmsg());
5680 return 0;
5681 }
5682
5683 // if no devices, return
5684 if (devlist.size() == 0)
5685 return 0;
5686
5687 // add empty device slots for existing config entries
5688 while (scanned_devs.size() < conf_entries.size())
5689 scanned_devs.push_back((smart_device *)0);
5690
5691 // loop over entries to create
5692 for (unsigned i = 0; i < devlist.size(); i++) {
5693 // Move device pointer
5694 smart_device * dev = devlist.release(i);
5695 scanned_devs.push_back(dev);
5696
5697 // Append configuration and update names
5698 conf_entries.push_back(base_cfg);
5699 dev_config & cfg = conf_entries.back();
5700 cfg.name = dev->get_info().info_name;
5701 cfg.dev_name = dev->get_info().dev_name;
5702
5703 // Set type only if scanning is limited to specific types
5704 // This is later used to set SMARTD_DEVICETYPE environment variable
5705 if (!types.empty())
5706 cfg.dev_type = dev->get_info().dev_type;
5707 else // SMARTD_DEVICETYPE=auto
5708 cfg.dev_type.clear();
5709 }
5710
5711 return devlist.size();
5712}
5713
5714// Returns negative value (see ParseConfigFile()) if config file
5715// had errors, else number of entries which may be zero or positive.
5716static int ReadOrMakeConfigEntries(dev_config_vector & conf_entries, smart_device_list & scanned_devs)
5717{
5718 // parse configuration file configfile (normally /etc/smartd.conf)
5719 smart_devtype_list scan_types;
5720 int entries = ParseConfigFile(conf_entries, scan_types);
5721
5722 if (entries < 0) {
5723 // There was an error reading the configuration file.
5724 conf_entries.clear();
5725 if (entries == -1)
5726 PrintOut(LOG_CRIT, "Configuration file %s has fatal syntax errors.\n", configfile);
5727 return entries;
5728 }
5729
5730 // no error parsing config file.
5731 if (entries) {
5732 // we did not find a SCANDIRECTIVE and did find valid entries
5733 PrintOut(LOG_INFO, "Configuration file %s parsed.\n", configfile);
5734 }
5735 else if (!conf_entries.empty()) {
5736 // we found a SCANDIRECTIVE or there was no configuration file so
5737 // scan. Configuration file's last entry contains all options
5738 // that were set
5739 dev_config first = conf_entries.back();
5740 conf_entries.pop_back();
5741
5742 if (first.lineno)
5743 PrintOut(LOG_INFO,"Configuration file %s was parsed, found %s, scanning devices\n", configfile, SCANDIRECTIVE);
5744 else
5745 PrintOut(LOG_INFO,"No configuration file %s found, scanning devices\n", configfile);
5746
5747 // make config list of devices to search for
5748 MakeConfigEntries(first, conf_entries, scanned_devs, scan_types);
5749
5750 // warn user if scan table found no devices
5751 if (conf_entries.empty())
5752 PrintOut(LOG_CRIT,"In the system's table of devices NO devices found to scan\n");
5753 }
5754 else
5755 PrintOut(LOG_CRIT, "Configuration file %s parsed but has no entries\n", configfile);
5756
5757 return conf_entries.size();
5758}
5759
5760// Register one device, return false on error
5762 const dev_config_vector * prev_cfgs)
5763{
5764 bool scanning;
5765 if (!dev) {
5766 // Get device of appropriate type
5767 dev = smi()->get_smart_device(cfg.name.c_str(), cfg.dev_type.c_str());
5768 if (!dev) {
5769 if (cfg.dev_type.empty())
5770 PrintOut(LOG_INFO, "Device: %s, unable to autodetect device type\n", cfg.name.c_str());
5771 else
5772 PrintOut(LOG_INFO, "Device: %s, unsupported device type '%s'\n", cfg.name.c_str(), cfg.dev_type.c_str());
5773 return false;
5774 }
5775 scanning = false;
5776 }
5777 else {
5778 // Use device from device scan
5779 scanning = true;
5780 }
5781
5782 // Save old info
5783 smart_device::device_info oldinfo = dev->get_info();
5784
5785 // Open with autodetect support, may return 'better' device
5786 dev.replace( dev->autodetect_open() );
5787
5788 // Report if type has changed
5789 if (oldinfo.dev_type != dev->get_dev_type())
5790 PrintOut(LOG_INFO, "Device: %s, type changed from '%s' to '%s'\n",
5791 cfg.name.c_str(), oldinfo.dev_type.c_str(), dev->get_dev_type());
5792
5793 // Return if autodetect_open() failed
5794 if (!dev->is_open()) {
5795 if (debugmode || !scanning)
5796 PrintOut(LOG_INFO, "Device: %s, open() failed: %s\n", dev->get_info_name(), dev->get_errmsg());
5797 return false;
5798 }
5799
5800 // Update informal name
5801 cfg.name = dev->get_info().info_name;
5802 PrintOut(LOG_INFO, "Device: %s, opened\n", cfg.name.c_str());
5803
5804 int status;
5805 const char * typemsg;
5806 // register ATA device
5807 if (dev->is_ata()){
5808 typemsg = "ATA";
5809 status = ATADeviceScan(cfg, state, dev->to_ata(), prev_cfgs);
5810 }
5811 // or register SCSI device
5812 else if (dev->is_scsi()){
5813 typemsg = "SCSI";
5814 status = SCSIDeviceScan(cfg, state, dev->to_scsi(), prev_cfgs);
5815 }
5816 // or register NVMe device
5817 else if (dev->is_nvme()) {
5818 typemsg = "NVMe";
5819 status = NVMeDeviceScan(cfg, state, dev->to_nvme(), prev_cfgs);
5820 }
5821 else {
5822 PrintOut(LOG_INFO, "Device: %s, neither ATA, SCSI nor NVMe device\n", cfg.name.c_str());
5823 return false;
5824 }
5825
5826 if (status) {
5827 if (!scanning || debugmode) {
5828 if (cfg.lineno)
5829 PrintOut(scanning ? LOG_INFO : LOG_CRIT,
5830 "Unable to register %s device %s at line %d of file %s\n",
5831 typemsg, cfg.name.c_str(), cfg.lineno, configfile);
5832 else
5833 PrintOut(LOG_INFO, "Unable to register %s device %s\n",
5834 typemsg, cfg.name.c_str());
5835 }
5836
5837 return false;
5838 }
5839
5840 return true;
5841}
5842
5843// This function tries devices from conf_entries. Each one that can be
5844// registered is moved onto the [ata|scsi]devices lists and removed
5845// from the conf_entries list.
5846static bool register_devices(const dev_config_vector & conf_entries, smart_device_list & scanned_devs,
5848{
5849 // start by clearing lists/memory of ALL existing devices
5850 configs.clear();
5851 devices.clear();
5852 states.clear();
5853
5854 // Map of already seen non-DEVICESCAN devices (unique_name -> cfg.name)
5855 typedef std::map<std::string, std::string> prev_unique_names_map;
5856 prev_unique_names_map prev_unique_names;
5857
5858 // Register entries
5859 for (unsigned i = 0; i < conf_entries.size(); i++) {
5860 dev_config cfg = conf_entries[i];
5861
5862 // Get unique device "name [type]" (with symlinks resolved) for duplicate detection
5863 std::string unique_name = smi()->get_unique_dev_name(cfg.dev_name.c_str(), cfg.dev_type.c_str());
5864 if (debugmode && unique_name != cfg.dev_name) {
5865 pout("Device: %s%s%s%s, unique name: %s\n", cfg.name.c_str(),
5866 (!cfg.dev_type.empty() ? " [" : ""), cfg.dev_type.c_str(),
5867 (!cfg.dev_type.empty() ? "]" : ""), unique_name.c_str());
5868 }
5869
5870 if (cfg.ignore) {
5871 // Store for duplicate detection and ignore
5872 PrintOut(LOG_INFO, "Device: %s%s%s%s, ignored\n", cfg.name.c_str(),
5873 (!cfg.dev_type.empty() ? " [" : ""), cfg.dev_type.c_str(),
5874 (!cfg.dev_type.empty() ? "]" : ""));
5875 prev_unique_names[unique_name] = cfg.name;
5876 continue;
5877 }
5878
5880
5881 // Device may already be detected during devicescan
5882 bool scanning = false;
5883 if (i < scanned_devs.size()) {
5884 dev = scanned_devs.release(i);
5885 if (dev) {
5886 // Check for a preceding non-DEVICESCAN entry for the same device
5887 prev_unique_names_map::iterator ui = prev_unique_names.find(unique_name);
5888 if (ui != prev_unique_names.end()) {
5889 bool ne = (ui->second != cfg.name);
5890 PrintOut(LOG_INFO, "Device: %s, %s%s, ignored\n", dev->get_info_name(),
5891 (ne ? "same as " : "duplicate"), (ne ? ui->second.c_str() : ""));
5892 continue;
5893 }
5894 scanning = true;
5895 }
5896 }
5897
5898 // Prevent systemd unit startup timeout when registering many devices
5900
5901 // Register device
5902 // If scanning, pass dev_idinfo of previous devices for duplicate check
5903 dev_state state;
5904 if (!register_device(cfg, state, dev, (scanning ? &configs : 0))) {
5905 // if device is explicitly listed and we can't register it, then
5906 // exit unless the user has specified that the device is removable
5907 if (!scanning) {
5908 if (!(cfg.removable || quit == QUIT_NEVER)) {
5909 PrintOut(LOG_CRIT, "Unable to register device %s (no Directive -d removable). Exiting.\n",
5910 cfg.name.c_str());
5911 return false;
5912 }
5913 PrintOut(LOG_INFO, "Device: %s, not available\n", cfg.name.c_str());
5914 // Prevent retry of registration
5915 prev_unique_names[unique_name] = cfg.name;
5916 }
5917 continue;
5918 }
5919
5920 // move onto the list of devices
5921 configs.push_back(cfg);
5922 states.push_back(state);
5923 devices.push_back(dev);
5924 if (!scanning)
5925 // Store for duplicate detection
5926 prev_unique_names[unique_name] = cfg.name;
5927 }
5928
5929 // Set minimum check time and factors for staggered tests
5930 checktime_min = 0;
5931 unsigned factor = 0;
5932 for (auto & cfg : configs) {
5933 if (cfg.checktime && (!checktime_min || checktime_min > cfg.checktime))
5934 checktime_min = cfg.checktime;
5935 if (!cfg.test_regex.empty())
5936 cfg.test_offset_factor = factor++;
5937 }
5940
5942 return true;
5943}
5944
5945
5946// Main program without exception handling
5947static int main_worker(int argc, char **argv)
5948{
5949 // Initialize interface
5951 if (!smi())
5952 return 1;
5953
5954 // Check whether systemd notify is supported and enabled
5955 notify_init();
5956
5957 // parse input and print header and usage info if needed
5958 int status = parse_options(argc,argv);
5959 if (status >= 0)
5960 return status;
5961
5962 // Configuration for each device
5963 dev_config_vector configs;
5964 // Device states
5965 dev_state_vector states;
5966 // Devices to monitor
5968
5969 // Drop capabilities if supported and enabled
5971
5972 notify_msg("Initializing ...");
5973
5974 // the main loop of the code
5975 bool firstpass = true, write_states_always = true;
5976 time_t wakeuptime = 0;
5977 // assert(status < 0);
5978 do {
5979 // Should we (re)read the config file?
5980 if (firstpass || caughtsigHUP){
5981 if (!firstpass) {
5982 // Write state files
5983 if (!state_path_prefix.empty())
5984 write_all_dev_states(configs, states);
5985
5986 PrintOut(LOG_INFO,
5987 caughtsigHUP==1?
5988 "Signal HUP - rereading configuration file %s\n":
5989 "\a\nSignal INT - rereading configuration file %s (" SIGQUIT_KEYNAME " quits)\n\n",
5990 configfile);
5991 notify_msg("Reloading ...");
5992 }
5993
5994 {
5995 dev_config_vector conf_entries; // Entries read from smartd.conf
5996 smart_device_list scanned_devs; // Devices found during scan
5997 // (re)reads config file, makes >=0 entries
5998 int entries = ReadOrMakeConfigEntries(conf_entries, scanned_devs);
5999
6000 if (entries>=0) {
6001 // checks devices, then moves onto ata/scsi list or deallocates.
6002 if (!register_devices(conf_entries, scanned_devs, configs, states, devices)) {
6003 status = EXIT_BADDEV;
6004 break;
6005 }
6006 if (!(configs.size() == devices.size() && configs.size() == states.size()))
6007 throw std::logic_error("Invalid result from RegisterDevices");
6008 }
6009 else if ( quit == QUIT_NEVER
6010 || ((quit == QUIT_NODEV || quit == QUIT_NODEVSTARTUP) && !firstpass)) {
6011 // user has asked to continue on error in configuration file
6012 if (!firstpass)
6013 PrintOut(LOG_INFO,"Reusing previous configuration\n");
6014 }
6015 else {
6016 // exit with configuration file error status
6017 status = (entries == -3 ? EXIT_READCONF : entries == -2 ? EXIT_NOCONF : EXIT_BADCONF);
6018 break;
6019 }
6020 }
6021
6022 if (!( devices.size() > 0 || quit == QUIT_NEVER
6023 || (quit == QUIT_NODEVSTARTUP && !firstpass))) {
6024 status = (!quit_nodev0 ? EXIT_NODEV : 0);
6025 PrintOut((status ? LOG_CRIT : LOG_INFO),
6026 "Unable to monitor any SMART enabled devices. Exiting.\n");
6027 break;
6028 }
6029
6030 // Log number of devices we are monitoring...
6031 int numata = 0, numscsi = 0;
6032 for (unsigned i = 0; i < devices.size(); i++) {
6033 const smart_device * dev = devices.at(i);
6034 if (dev->is_ata())
6035 numata++;
6036 else if (dev->is_scsi())
6037 numscsi++;
6038 }
6039 PrintOut(LOG_INFO, "Monitoring %d ATA/SATA, %d SCSI/SAS and %d NVMe devices\n",
6040 numata, numscsi, (int)devices.size() - numata - numscsi);
6041
6042 if (quit == QUIT_SHOWTESTS) {
6043 // user has asked to print test schedule
6044 PrintTestSchedule(configs, states, devices);
6045 // assert(firstpass);
6046 return 0;
6047 }
6048
6049 // reset signal
6050 caughtsigHUP=0;
6051
6052 // Always write state files after (re)configuration
6053 write_states_always = true;
6054 }
6055
6056 // check all devices once,
6057 // self tests are not started in first pass unless '-q onecheck' is specified
6058 notify_check((int)devices.size());
6059 CheckDevicesOnce(configs, states, devices, firstpass, (!firstpass || quit == QUIT_ONECHECK));
6060
6061 // Write state files
6062 if (!state_path_prefix.empty())
6063 write_all_dev_states(configs, states, write_states_always);
6064 write_states_always = false;
6065
6066 // Write attribute logs
6067 if (!attrlog_path_prefix.empty())
6068 write_all_dev_attrlogs(configs, states);
6069
6070 // user has asked us to exit after first check
6071 if (quit == QUIT_ONECHECK) {
6072 PrintOut(LOG_INFO,"Started with '-q onecheck' option. All devices successfully checked once.\n"
6073 "smartd is exiting (exit status 0)\n");
6074 // assert(firstpass);
6075 return 0;
6076 }
6077
6078 if (firstpass) {
6079 if (!debugmode) {
6080 // fork() into background if needed, close ALL file descriptors,
6081 // redirect stdin, stdout, and stderr, chdir to "/".
6082 status = daemon_init();
6083 if (status >= 0)
6084 return status;
6085
6086 // Write PID file if configured
6087 if (!write_pid_file())
6088 return EXIT_PID;
6089 }
6090
6091 // Set exit and signal handlers
6093
6094 // Initialize wakeup time to CURRENT time
6095 wakeuptime = time(nullptr);
6096
6097 firstpass = false;
6098 }
6099
6100 // sleep until next check time, or a signal arrives
6101 wakeuptime = dosleep(wakeuptime, configs, states, write_states_always);
6102
6103 } while (!caughtsigEXIT);
6104
6105 if (caughtsigEXIT && status < 0) {
6106 // Loop exited on signal
6107 if (caughtsigEXIT == SIGTERM || (debugmode && caughtsigEXIT == SIGQUIT)) {
6108 PrintOut(LOG_INFO, "smartd received signal %d: %s\n",
6109 caughtsigEXIT, strsignal(caughtsigEXIT));
6110 }
6111 else {
6112 // Unexpected SIGINT or SIGQUIT
6113 PrintOut(LOG_CRIT, "smartd received unexpected signal %d: %s\n",
6114 caughtsigEXIT, strsignal(caughtsigEXIT));
6115 status = EXIT_SIGNAL;
6116 }
6117 }
6118
6119 // Status unset above implies success
6120 if (status < 0)
6121 status = 0;
6122
6123 if (!firstpass) {
6124 // Loop exited after daemon_init() and write_pid_file()
6125
6126 // Write state files only on normal exit
6127 if (!status && !state_path_prefix.empty())
6128 write_all_dev_states(configs, states);
6129
6130 // Delete PID file, if one was created
6131 if (!pid_file.empty() && unlink(pid_file.c_str()))
6132 PrintOut(LOG_CRIT,"Can't unlink PID file %s (%s).\n",
6133 pid_file.c_str(), strerror(errno));
6134 }
6135
6136 PrintOut((status ? LOG_CRIT : LOG_INFO), "smartd is exiting (exit status %d)\n", status);
6137 return status;
6138}
6139
6140
6141#ifndef _WIN32
6142// Main program
6143int main(int argc, char **argv)
6144#else
6145// Windows: internal main function started direct or by service control manager
6146static int smartd_main(int argc, char **argv)
6147#endif
6148{
6149 int status;
6150 try {
6151 // Do the real work ...
6152 status = main_worker(argc, argv);
6153 }
6154 catch (const std::bad_alloc & /*ex*/) {
6155 // Memory allocation failed (also thrown by std::operator new)
6156 PrintOut(LOG_CRIT, "Smartd: Out of memory\n");
6157 status = EXIT_NOMEM;
6158 }
6159 catch (const std::exception & ex) {
6160 // Other fatal errors
6161 PrintOut(LOG_CRIT, "Smartd: Exception: %s\n", ex.what());
6162 status = EXIT_BADCODE;
6163 }
6164
6165 // Check for remaining device objects
6166 if (smart_device::get_num_objects() != 0) {
6167 PrintOut(LOG_CRIT, "Smartd: Internal Error: %d device object(s) left at exit.\n",
6169 status = EXIT_BADCODE;
6170 }
6171
6172 if (status == EXIT_BADCODE)
6173 PrintOut(LOG_CRIT, "Please inform " PACKAGE_BUGREPORT ", including output of smartd -V.\n");
6174
6175 notify_exit(status);
6176#ifdef _WIN32
6177 daemon_winsvc_exitcode = status;
6178#endif
6179 return status;
6180}
6181
6182
6183#ifdef _WIN32
6184// Main function for Windows
6185int main(int argc, char **argv){
6186 // Options for smartd windows service
6187 static const daemon_winsvc_options svc_opts = {
6188 "--service", // cmd_opt
6189 "smartd", "SmartD Service", // servicename, displayname
6190 // description
6191 "Controls and monitors storage devices using the Self-Monitoring, "
6192 "Analysis and Reporting Technology System (SMART) built into "
6193 "ATA/SATA and SCSI/SAS hard drives and solid-state drives. "
6194 "www.smartmontools.org"
6195 };
6196 // daemon_main() handles daemon and service specific commands
6197 // and starts smartd_main() direct, from a new process,
6198 // or via service control manager
6199 return daemon_main("smartd", &svc_opts , smartd_main, argc, argv);
6200}
6201#endif
bool ata_nodata_command(ata_device *device, unsigned char command, int sector_count)
Definition: atacmds.cpp:787
int ataDisableAutoOffline(ata_device *device)
Definition: atacmds.cpp:1581
unsigned char ata_return_temperature_value(const ata_smart_values *data, const ata_vendor_attr_defs &defs)
Definition: atacmds.cpp:2159
bool isSmartErrorLogCapable(const ata_smart_values *data, const ata_identify_device *identity)
Definition: atacmds.cpp:1731
int ata_get_wwn(const ata_identify_device *id, unsigned &oui, uint64_t &unique_id)
Definition: atacmds.cpp:900
int ataEnableAutoOffline(ata_device *device)
Definition: atacmds.cpp:1570
int ataSmartStatus2(ata_device *device)
Definition: atacmds.cpp:1604
int ataSmartSupport(const ata_identify_device *drive)
Definition: atacmds.cpp:936
int ataDisableAutoSave(ata_device *device)
Definition: atacmds.cpp:1558
int ata_get_rotation_rate(const ata_identify_device *id)
Definition: atacmds.cpp:920
unsigned char get_unc_attr_id(bool offline, const ata_vendor_attr_defs &defs, bool &increase)
Definition: atacmds.cpp:53
bool parse_attribute_def(const char *opt, ata_vendor_attr_defs &defs, ata_vendor_def_prior priority)
Definition: atacmds.cpp:149
int ataEnableAutoSave(ata_device *device)
Definition: atacmds.cpp:1551
int ataReadSelfTestLog(ata_device *device, ata_smart_selftestlog *data, firmwarebug_defs firmwarebugs)
Definition: atacmds.cpp:1013
std::string ata_format_attr_raw_value(const ata_smart_attribute &attr, const ata_vendor_attr_defs &defs)
Definition: atacmds.cpp:1920
int ata_find_attr_index(unsigned char id, const ata_smart_values &smartval)
Definition: atacmds.cpp:2146
int ataReadErrorLog(ata_device *device, ata_smart_errorlog *data, firmwarebug_defs firmwarebugs)
Definition: atacmds.cpp:1424
void ata_get_size_info(const ata_identify_device *id, ata_size_info &sizes)
Definition: atacmds.cpp:658
int ata_read_identity(ata_device *device, ata_identify_device *buf, bool fix_swapped_id, unsigned char *raw_buf)
Definition: atacmds.cpp:817
int ataEnableSmart(ata_device *device)
Definition: atacmds.cpp:1536
int smartcommandhandler(ata_device *device, smart_command_set command, int select, char *data)
Definition: atacmds.cpp:431
bool isGeneralPurposeLoggingCapable(const ata_identify_device *identity)
Definition: atacmds.cpp:1769
int ataCheckPowerMode(ata_device *device)
Definition: atacmds.cpp:777
std::string create_vendor_attribute_arg_list()
Definition: atacmds.cpp:262
bool isSmartTestLogCapable(const ata_smart_values *data, const ata_identify_device *identity)
Definition: atacmds.cpp:1750
int ataReadSmartValues(ata_device *device, struct ata_smart_values *data)
Definition: atacmds.cpp:967
bool parse_firmwarebug_def(const char *opt, firmwarebug_defs &firmwarebugs)
Definition: atacmds.cpp:277
int ataSetSCTErrorRecoveryControltime(ata_device *device, unsigned type, unsigned short time_limit, bool power_on, bool mfg_default)
Definition: atacmds.cpp:2516
unsigned char ata_debugmode
Definition: atacmds.cpp:33
const char * get_valid_firmwarebug_args()
Definition: atacmds.cpp:297
uint64_t ata_get_attr_raw_value(const ata_smart_attribute &attr, const ata_vendor_attr_defs &defs)
Definition: atacmds.cpp:1846
bool ataReadExtErrorLog(ata_device *device, ata_smart_exterrlog *log, unsigned page, unsigned nsectors, firmwarebug_defs firmwarebugs)
Definition: atacmds.cpp:1491
int ataWriteSelectiveSelfTestLog(ata_device *device, ata_selective_selftest_args &args, const ata_smart_values *sv, uint64_t num_sectors, const ata_selective_selftest_args *prev_args)
Definition: atacmds.cpp:1213
std::string ata_get_smart_attr_name(unsigned char id, const ata_vendor_attr_defs &defs, int rpm)
Definition: atacmds.cpp:2127
int ataReadSmartThresholds(ata_device *device, struct ata_smart_thresholds_pvt *data)
Definition: atacmds.cpp:1518
int ataIsSmartEnabled(const ata_identify_device *drive)
Definition: atacmds.cpp:951
void ata_format_id_string(char *out, const unsigned char *in, int n)
Definition: atacmds.cpp:762
int ataReadLogDirectory(ata_device *device, ata_smart_log_directory *data, bool gpl)
Definition: atacmds.cpp:1164
bool ata_set_features(ata_device *device, unsigned char features, int sector_count)
Definition: atacmds.cpp:799
ata_attr_state ata_get_attr_state(const ata_smart_attribute &attr, int attridx, const ata_smart_threshold_entry *thresholds, const ata_vendor_attr_defs &defs, unsigned char *threshval)
Definition: atacmds.cpp:1796
#define ATA_ENABLE_READ_LOOK_AHEAD
Definition: atacmds.h:72
#define ATA_DISABLE_WRITE_CACHE
Definition: atacmds.h:67
bool isSupportSelfTest(const ata_smart_values *data)
Definition: atacmds.h:877
#define SELECTIVE_SELF_TEST
Definition: atacmds.h:101
bool isSCTErrorRecoveryControlCapable(const ata_identify_device *drive)
Definition: atacmds.h:889
#define ATA_ENABLE_APM
Definition: atacmds.h:70
#define ATA_DISABLE_AAM
Definition: atacmds.h:65
#define OFFLINE_FULL_SCAN
Definition: atacmds.h:97
#define SHORT_SELF_TEST
Definition: atacmds.h:98
bool isSupportConveyanceSelfTest(const ata_smart_values *data)
Definition: atacmds.h:880
#define ATA_ENABLE_DISABLE_DSN
Definition: atacmds.h:73
#define ATA_IDLE
Definition: atacmds.h:55
bool isSupportAutomaticTimer(const ata_smart_values *data)
Definition: atacmds.h:868
#define EXTEND_SELF_TEST
Definition: atacmds.h:99
#define ATA_ENABLE_WRITE_CACHE
Definition: atacmds.h:71
bool isSupportSelectiveSelfTest(const ata_smart_values *data)
Definition: atacmds.h:883
#define ATA_DISABLE_READ_LOOK_AHEAD
Definition: atacmds.h:68
#define ATTRIBUTE_FLAGS_PREFAILURE(x)
Definition: atacmds.h:164
@ PRIOR_USER
Definition: atacmds.h:644
#define ATA_ENABLE_AAM
Definition: atacmds.h:69
bool isSupportExecuteOfflineImmediate(const ata_smart_values *data)
Definition: atacmds.h:862
@ IMMEDIATE_OFFLINE
Definition: atacmds.h:34
#define CONVEYANCE_SELF_TEST
Definition: atacmds.h:100
@ BUG_SAMSUNG3
Definition: atacmds.h:717
@ BUG_NOLOGDIR
Definition: atacmds.h:714
#define ATA_SECURITY_FREEZE_LOCK
Definition: atacmds.h:57
@ SEL_REDO
Definition: atacmds.h:607
@ SEL_NEXT
Definition: atacmds.h:608
@ SEL_CONT
Definition: atacmds.h:609
#define ATA_DISABLE_APM
Definition: atacmds.h:66
#define NUMBER_ATA_SMART_ATTRIBUTES
Definition: atacmds.h:110
ata_attr_state
Definition: atacmds.h:902
@ ATTRSTATE_FAILED_NOW
Definition: atacmds.h:908
@ ATTRSTATE_NON_EXISTING
Definition: atacmds.h:903
@ ATTRSTATE_NO_NORMVAL
Definition: atacmds.h:904
Smart pointer class for device pointers.
void replace(device_type *dev)
Replace the pointer.
ATA device access.
unsigned char m_flags[256]
Definition: smartd.cpp:370
bool is_set(int id, unsigned char flag) const
Definition: smartd.cpp:360
void set(int id, unsigned char flags)
Definition: smartd.cpp:363
env_buffer()=default
env_buffer(const env_buffer &)=delete
char * m_buf
Definition: smartd.cpp:1014
void set(const char *name, const char *value)
Definition: smartd.cpp:1017
void operator=(const env_buffer &)=delete
bool is_set(firmwarebug_t bug) const
Definition: atacmds.h:728
NVMe device access.
unsigned get_nsid() const
Get namespace id.
unsigned char * data()
Definition: utility.h:148
Wrapper class for POSIX regex(3) or std::regex Supports copy & assignment and is compatible with STL ...
Definition: utility.h:222
bool full_match(const char *str) const
Return true if full string matches pattern.
Definition: utility.cpp:593
regmatch_t match_range
Definition: utility.h:262
const char * get_errmsg() const
Get error message from last compile().
Definition: utility.h:249
bool empty() const
Definition: utility.h:253
const char * get_pattern() const
Definition: utility.h:245
bool compile(const char *pattern)
Set and compile new pattern, return false on error.
Definition: utility.cpp:547
bool execute(const char *str, unsigned nmatch, match_range *pmatch) const
Return true if substring matches pattern, fill match_range array.
Definition: utility.cpp:604
SCSI device access.
bool use_rcap16() const
List of devices for DEVICESCAN.
unsigned size() const
void push_back(smart_device *dev)
smart_device * release(unsigned i)
Base class for all devices.
Definition: dev_interface.h:33
bool is_scsi() const
Return true if SCSI device.
Definition: dev_interface.h:89
virtual bool is_powered_down()
Early test if device is powered up or down.
bool is_nvme() const
Return true if NVMe device.
Definition: dev_interface.h:92
const device_info & get_info() const
Get device info struct.
const char * get_errmsg() const
Get last error message.
virtual bool close()=0
Close device, return false on error.
nvme_device * to_nvme()
Downcast to NVMe device.
ata_device * to_ata()
Downcast to ATA device.
Definition: dev_interface.h:96
scsi_device * to_scsi()
Downcast to SCSI device.
static int get_num_objects()
Get current number of allocated 'smart_device' objects.
bool is_ata() const
Return true if ATA device.
Definition: dev_interface.h:86
virtual bool open()=0
Open device, return false on error.
virtual std::string get_unique_dev_name(const char *name, const char *type) const
Return unique device name which is (only) suitable for duplicate detection.
virtual smart_device * get_smart_device(const char *name, const char *type)
Return device object for device 'name' with some 'type'.
static void init()
Initialize platform interface and register with smi().
Definition: dev_legacy.cpp:334
Wrapper class for FILE *.
Definition: utility.h:163
bool close()
Definition: utility.h:194
bool open(const char *name, const char *mode)
Definition: utility.h:177
std::vector< std::string > smart_devtype_list
List of types for DEVICESCAN.
smart_interface * smi()
Global access to the (usually singleton) smart_interface.
const drive_settings * lookup_drive_apply_presets(const ata_identify_device *drive, ata_vendor_attr_defs &defs, firmwarebug_defs &firmwarebugs, std::string &dbversion)
bool init_drive_database(bool use_default_db)
const char * get_drivedb_path_add()
static bool match(const char *pattern, const char *str)
void show_presets(const ata_identify_device *drive)
bool read_drive_database(const char *path)
int showallpresets()
u16 flags
Definition: megaraid.h:14
u32 count
Definition: megaraid.h:1
u32 w[3]
Definition: megaraid.h:19
u8 b[12]
Definition: megaraid.h:17
ptr_t buffer
Definition: megaraid.h:3
u16 s[6]
Definition: megaraid.h:18
ptr_t data
Definition: megaraid.h:15
u32 size
Definition: megaraid.h:0
uint8_t id
uint32_t nsid
union @43 entry
bool nvme_read_self_test_log(nvme_device *device, uint32_t nsid, smartmontools::nvme_self_test_log &self_test_log)
Definition: nvmecmds.cpp:270
int nvme_status_to_errno(uint16_t status)
Definition: nvmecmds.cpp:472
bool nvme_read_id_ctrl(nvme_device *device, nvme_id_ctrl &id_ctrl)
Definition: nvmecmds.cpp:132
unsigned char nvme_debugmode
Definition: nvmecmds.cpp:27
bool nvme_self_test(nvme_device *device, uint8_t stc, uint32_t nsid)
Definition: nvmecmds.cpp:285
unsigned nvme_read_error_log(nvme_device *device, nvme_error_log_page *error_log, unsigned num_entries, bool lpo_sup)
Definition: nvmecmds.cpp:231
bool nvme_read_smart_log(nvme_device *device, uint32_t nsid, nvme_smart_log &smart_log)
Definition: nvmecmds.cpp:254
const char * nvme_status_to_info_str(char *buf, size_t bufsize, uint16_t status)
Definition: nvmecmds.cpp:490
constexpr bool nvme_status_is_error(uint16_t status)
Definition: nvmecmds.h:288
constexpr uint32_t nvme_broadcast_nsid
Definition: nvmecmds.h:257
static struct @44 devices[20]
std::string get_exe_dir()
Definition: os_win32.cpp:4844
#define _WIN32
Definition: os_win32.cpp:54
FILE * popen_as_ugid(const char *cmd, const char *mode, uid_t uid, gid_t gid)
int pclose_as_ugid(FILE *f)
const char * parse_ugid(const char *s, uid_t &uid, gid_t &gid, std::string &uname, std::string &gname)
void scsiDecodeErrCounterPage(unsigned char *resp, struct scsiErrorCounter *ecp, int allocLen)
Definition: scsicmds.cpp:2609
int scsiFetchIECmpage(scsi_device *device, struct scsi_iec_mode_page *iecp, int modese_len)
Definition: scsicmds.cpp:1838
int scsi_decode_lu_dev_id(const unsigned char *b, int blen, char *s, int slen, int *transport)
Definition: scsicmds.cpp:747
int scsiTestUnitReady(scsi_device *device)
Definition: scsicmds.cpp:1456
int scsiInquiryVpd(scsi_device *device, int vpd_page, uint8_t *pBuf, int bufLen)
Definition: scsicmds.cpp:1210
int scsiSmartExtendSelfTest(scsi_device *device)
Definition: scsicmds.cpp:2509
void scsiDecodeNonMediumErrPage(unsigned char *resp, struct scsiNonMediumError *nmep, int allocLen)
Definition: scsicmds.cpp:2654
int scsiCheckIE(scsi_device *device, int hasIELogPage, int hasTempLogPage, uint8_t *asc, uint8_t *ascq, uint8_t *currenttemp, uint8_t *triptemp)
Definition: scsicmds.cpp:2028
uint64_t scsiGetSize(scsi_device *device, bool avoid_rcap16, struct scsi_readcap_resp *srrp)
Definition: scsicmds.cpp:1713
int scsiSelfTestInProgress(scsi_device *fd, int *inProgress)
Definition: scsicmds.cpp:2773
char * scsiGetIEString(uint8_t asc, uint8_t ascq, char *b, int blen)
Definition: scsicmds.cpp:3198
supported_vpd_pages * supported_vpd_pages_p
Definition: scsicmds.cpp:47
void scsi_format_id_string(char *out, const uint8_t *in, int n)
Definition: scsicmds.cpp:3117
int scsiStdInquiry(scsi_device *device, uint8_t *pBuf, int bufLen)
Definition: scsicmds.cpp:1163
int scsiCountFailedSelfTests(scsi_device *fd, int noisy)
Definition: scsicmds.cpp:2722
int scsiSetControlGLTSD(scsi_device *device, int enabled, int modese_len)
Definition: scsicmds.cpp:2987
int scsi_IsExceptionControlEnabled(const struct scsi_iec_mode_page *iecp)
Definition: scsicmds.cpp:1885
int scsiSmartShortSelfTest(scsi_device *device)
Definition: scsicmds.cpp:2498
int scsiLogSense(scsi_device *device, int pagenum, int subpagenum, uint8_t *pBuf, int bufLen, int known_resp_len)
Definition: scsicmds.cpp:873
unsigned char scsi_debugmode
Definition: scsicmds.cpp:45
#define SIMPLE_ERR_BECOMING_READY
Definition: scsicmds.h:354
#define SIMPLE_ERR_BAD_FIELD
Definition: scsicmds.h:350
#define LOGPAGEHDRSIZE
Definition: scsicmds.h:385
#define SIMPLE_ERR_NOT_READY
Definition: scsicmds.h:348
#define SCSI_VPD_DEVICE_IDENTIFICATION
Definition: scsicmds.h:309
#define SIMPLE_ERR_NO_MEDIUM
Definition: scsicmds.h:353
#define SCSI_PT_CDROM
Definition: scsicmds.h:194
#define VERIFY_ERROR_COUNTER_LPAGE
Definition: scsicmds.h:223
#define SUPPORTED_LPAGES
Definition: scsicmds.h:218
#define SIMPLE_ERR_BAD_OPCODE
Definition: scsicmds.h:349
#define NON_MEDIUM_ERROR_LPAGE
Definition: scsicmds.h:224
#define SCSI_VPD_UNIT_SERIAL_NUMBER
Definition: scsicmds.h:308
#define SCSI_PT_HOST_MANAGED
Definition: scsicmds.h:199
#define SCSI_PT_WO
Definition: scsicmds.h:193
#define SCSI_PT_RBC
Definition: scsicmds.h:198
#define TEMPERATURE_LPAGE
Definition: scsicmds.h:229
#define WRITE_ERROR_COUNTER_LPAGE
Definition: scsicmds.h:220
#define SCSI_PT_DIRECT_ACCESS
Definition: scsicmds.h:191
#define READ_ERROR_COUNTER_LPAGE
Definition: scsicmds.h:221
#define IE_LPAGE
Definition: scsicmds.h:241
#define SCSI_PT_OPTICAL
Definition: scsicmds.h:195
static uint64_t sg_get_unaligned_le64(const void *p)
Definition: sg_unaligned.h:303
static uint16_t sg_get_unaligned_le16(const void *p)
Definition: sg_unaligned.h:292
#define EXIT_BADCONF
Definition: smartd.cpp:127
static int CloseDevice(smart_device *device, const char *name)
Definition: smartd.cpp:1710
#define EXIT_SIGNAL
Definition: smartd.cpp:139
static bool is_duplicate_dev_idinfo(const dev_config &cfg, const dev_config_vector &prev_cfgs)
Definition: smartd.cpp:1933
static void reset_warning_mail(const dev_config &cfg, dev_state &state, int which, const char *fmt,...) __attribute_format_printf(4
Definition: smartd.cpp:1281
unsigned char failuretest_permissive
Definition: smartd.cpp:205
#define SIGQUIT_KEYNAME
Definition: smartd.cpp:90
const bool fix_swapped_id
Definition: smartd.cpp:1956
static std::string state_path_prefix
Definition: smartd.cpp:158
static bool write_dev_state(const char *path, const persistent_dev_state &state)
Definition: smartd.cpp:769
static int NVMeDeviceScan(dev_config &cfg, dev_state &state, nvme_device *nvmedev, const dev_config_vector *prev_cfgs)
Definition: smartd.cpp:2754
static int ParseToken(char *token, dev_config &cfg, smart_devtype_list &scan_types)
Definition: smartd.cpp:4535
static std::string configfile_alt
Definition: smartd.cpp:172
static int Get3Integers(const char *arg, const char *name, const char *token, int lineno, const char *cfgfile, unsigned char *val1, unsigned char *val2, unsigned char *val3)
Definition: smartd.cpp:4480
static int facility
Definition: smartd.cpp:197
#define EXIT_BADDEV
Definition: smartd.cpp:136
#define EXIT_NODEV
Definition: smartd.cpp:137
static void sighandler(int sig)
Definition: smartd.cpp:944
static int check_ata_self_test_log(ata_device *device, const char *name, firmwarebug_defs firmwarebugs, unsigned &hour)
Definition: smartd.cpp:1770
static const int MAILTYPE_TEST
Definition: smartd.cpp:451
static void do_disable_standby_check(const dev_config_vector &configs, const dev_state_vector &states)
Definition: smartd.cpp:4187
static void log_self_test_exec_status(const char *name, unsigned char status)
Definition: smartd.cpp:1847
const char * fmt
Definition: smartd.cpp:1310
static void check_attribute(const dev_config &cfg, dev_state &state, const ata_smart_attribute &attr, const ata_smart_attribute &prev, int attridx, const ata_smart_threshold_entry *thresholds)
Definition: smartd.cpp:3485
static void log_offline_data_coll_status(const char *name, unsigned char status)
Definition: smartd.cpp:1824
static void notify_exit(int)
Definition: smartd.cpp:336
static void write_all_dev_attrlogs(const dev_config_vector &configs, dev_state_vector &states)
Definition: smartd.cpp:898
int main(int argc, char **argv)
Definition: smartd.cpp:6143
static int ReadOrMakeConfigEntries(dev_config_vector &conf_entries, smart_device_list &scanned_devs)
Definition: smartd.cpp:5716
static void report_self_test_log_changes(const dev_config &cfg, dev_state &state, int errcnt, uint64_t hour)
Definition: smartd.cpp:2958
static quit_t quit
Definition: smartd.cpp:193
static void write_dev_state_line(FILE *f, const char *name, uint64_t val)
Definition: smartd.cpp:756
static time_t dosleep(time_t wakeuptime, const dev_config_vector &configs, dev_state_vector &states, bool &sigwakeup)
Definition: smartd.cpp:4313
static void notify_extend_timeout()
Definition: smartd.cpp:332
static void check_pending(const dev_config &cfg, dev_state &state, unsigned char id, bool increase_only, const ata_smart_values &smartval, int mailtype, const char *msg)
Definition: smartd.cpp:3369
static void PrintTestSchedule(const dev_config_vector &configs, dev_state_vector &states, const smart_device_list &devices)
Definition: smartd.cpp:3137
static bool check_abs_path(char option, const std::string &path)
Definition: smartd.cpp:5289
static bool register_device(dev_config &cfg, dev_state &state, smart_device_auto_ptr &dev, const dev_config_vector *prev_cfgs)
Definition: smartd.cpp:5761
static void MailWarning(const dev_config &cfg, dev_state &state, int which, const char *fmt,...) __attribute_format_printf(4
Definition: smartd.cpp:1038
static void init_disable_standby_check(const dev_config_vector &configs)
Definition: smartd.cpp:4159
static void notify_init()
Definition: smartd.cpp:331
static void install_signal_handlers()
Definition: smartd.cpp:4263
static void capabilities_drop_now()
Definition: smartd.cpp:990
static void PrintValidArgs(char opt)
Definition: smartd.cpp:5275
#define EXIT_BADCMD
Definition: smartd.cpp:126
#define EXIT_NOCONF
Definition: smartd.cpp:130
const char * smartd_cpp_cvsid
Definition: smartd.cpp:93
static int NVMeCheckDevice(const dev_config &cfg, dev_state &state, nvme_device *nvmedev, bool firstpass, bool allow_selftests)
Definition: smartd.cpp:4050
static void notify_check(int)
Definition: smartd.cpp:334
#define SCANDIRECTIVE
Definition: smartd.cpp:5023
static std::string attrlog_path_prefix
Definition: smartd.cpp:165
static bool WaitForPidFile()
Definition: smartd.cpp:1398
static void notify_wait(time_t, int)
Definition: smartd.cpp:335
void checksumwarning(const char *string)
Definition: smartd.cpp:1389
static volatile int caughtsigEXIT
Definition: smartd.cpp:220
static int ParseConfigFile(dev_config_vector &conf_entries, smart_devtype_list &scan_types)
Definition: smartd.cpp:5140
static uint64_t le128_to_uint64(const unsigned char(&val)[16])
Definition: smartd.cpp:2673
void(* signal_handler_type)(int)
Definition: smartd.cpp:97
#define EXIT_PID
Definition: smartd.cpp:129
vsnprintf(buf, sizeof(buf), fmt, ap)
static int standby_disable_state
Definition: smartd.cpp:4157
static void notify_msg(const char *)
Definition: smartd.cpp:333
static int checktime
Definition: smartd.cpp:147
static int SCSICheckDevice(const dev_config &cfg, dev_state &state, scsi_device *scsidev, bool allow_selftests)
Definition: smartd.cpp:3826
static int ParseConfigLine(dev_config_vector &conf_entries, dev_config &default_conf, smart_devtype_list &scan_types, int lineno, char *line)
Definition: smartd.cpp:5034
static const char * GetValidArgList(char opt)
Definition: smartd.cpp:1580
static const char test_type_chars[]
Definition: smartd.cpp:3009
static bool write_dev_attrlog(const char *path, const dev_state &state)
Definition: smartd.cpp:823
static void CheckDevicesOnce(const dev_config_vector &configs, dev_state_vector &states, smart_device_list &devices, bool firstpass, bool allow_selftests)
Definition: smartd.cpp:4234
static const char * configfile
Definition: smartd.cpp:168
static const char *const configfile_stdin
Definition: smartd.cpp:170
static const char * fmt_temp(unsigned char x, char(&buf)[20])
Definition: smartd.cpp:3402
static void write_all_dev_states(const dev_config_vector &configs, dev_state_vector &states, bool write_always=true)
Definition: smartd.cpp:877
static void static bool notify_post_init()
Definition: smartd.cpp:320
static bool check_pending_id(const dev_config &cfg, const dev_state &state, unsigned char id, const char *msg)
Definition: smartd.cpp:1875
quit_t
Definition: smartd.cpp:189
@ QUIT_NODEVSTARTUP
Definition: smartd.cpp:190
@ QUIT_NEVER
Definition: smartd.cpp:190
@ QUIT_ERRORS
Definition: smartd.cpp:191
@ QUIT_ONECHECK
Definition: smartd.cpp:190
@ QUIT_SHOWTESTS
Definition: smartd.cpp:191
@ QUIT_NODEV
Definition: smartd.cpp:190
static bool not_allowed_in_filename(char c)
Definition: smartd.cpp:1737
static int SCSIDeviceScan(dev_config &cfg, dev_state &state, scsi_device *scsidev, const dev_config_vector *prev_cfgs)
Definition: smartd.cpp:2407
static bool do_fork
Definition: smartd.cpp:201
static void capabilities_log_error_hint()
Definition: smartd.cpp:991
static void PrintHead()
Definition: smartd.cpp:1526
static char next_scheduled_test(const dev_config &cfg, dev_state &state, time_t usetime=0)
Definition: smartd.cpp:3014
static void CheckTemperature(const dev_config &cfg, dev_state &state, unsigned char currtemp, unsigned char triptemp)
Definition: smartd.cpp:3411
static int parse_options(int argc, char **argv)
Definition: smartd.cpp:5304
static unsigned char debugmode
Definition: smartd.cpp:143
static bool read_dev_state(const char *path, persistent_dev_state &state)
Definition: smartd.cpp:718
static int DoATASelfTest(const dev_config &cfg, dev_state &state, ata_device *device, char testtype)
Definition: smartd.cpp:3250
static void printoutvaliddirectiveargs(int priority, char d)
Definition: smartd.cpp:4401
static bool write_pid_file()
Definition: smartd.cpp:1502
#define EXIT_BADCODE
Definition: smartd.cpp:134
static std::string pid_file
Definition: smartd.cpp:151
static int daemon_init()
Definition: smartd.cpp:1421
static bool is_offl_coll_in_progress(unsigned char status)
Definition: smartd.cpp:1812
static void USR1handler(int sig)
Definition: smartd.cpp:916
static bool open_device(const dev_config &cfg, dev_state &state, smart_device *device, const char *type)
Definition: smartd.cpp:2895
static int ATACheckDevice(const dev_config &cfg, dev_state &state, ata_device *atadev, bool firstpass, bool allow_selftests)
Definition: smartd.cpp:3582
const char va_list ap
Definition: smartd.cpp:1311
static int check_nvme_self_test_log(uint32_t nsid, const nvme_self_test_log &self_test_log, uint64_t &hour)
Definition: smartd.cpp:3977
static int main_worker(int argc, char **argv)
Definition: smartd.cpp:5947
static bool quit_nodev0
Definition: smartd.cpp:194
static void Directives()
Definition: smartd.cpp:1532
static bool register_devices(const dev_config_vector &conf_entries, smart_device_list &scanned_devs, dev_config_vector &configs, dev_state_vector &states, smart_device_list &devices)
Definition: smartd.cpp:5846
std::vector< dev_config > dev_config_vector
Container for configuration info for each device.
Definition: smartd.cpp:568
static void HUPhandler(int sig)
Definition: smartd.cpp:934
static int read_ata_error_count(ata_device *device, const char *name, firmwarebug_defs firmwarebugs, bool extended)
Definition: smartd.cpp:1746
static constexpr int default_checktime
Definition: smartd.cpp:146
static int GetInteger(const char *arg, const char *name, const char *token, int lineno, const char *cfgfile, int min, int max, char *suffix=0)
Definition: smartd.cpp:4446
static const int SMARTD_NMAIL
Definition: smartd.cpp:449
#define EXIT_READCONF
Definition: smartd.cpp:131
static void PrintOut(int priority, const char *fmt,...) __attribute_format_printf(2
Definition: smartd.cpp:1363
static void log_nvme_self_test_exec_status(const char *name, dev_state &state, bool firstpass, const nvme_self_test_log &self_test_log)
Definition: smartd.cpp:3911
emailfreqs
Definition: smartd.cpp:341
static const unsigned num_test_types
Definition: smartd.cpp:3010
static void Usage()
Definition: smartd.cpp:1618
static void format_set_result_msg(std::string &msg, const char *name, bool ok, int set_option=0, bool has_value=false)
Definition: smartd.cpp:1916
static int checktime_min
Definition: smartd.cpp:148
static int DoSCSISelfTest(const dev_config &cfg, dev_state &state, scsi_device *device, char testtype)
Definition: smartd.cpp:3191
static void set_signal_if_not_ignored(int sig, signal_handler_type handler)
Definition: smartd.cpp:100
@ MONITOR_RAW
Definition: smartd.cpp:351
@ MONITOR_RAW_PRINT
Definition: smartd.cpp:350
@ MONITOR_RAW_AS_CRIT
Definition: smartd.cpp:353
@ MONITOR_IGN_FAILUSE
Definition: smartd.cpp:348
@ MONITOR_IGNORE
Definition: smartd.cpp:349
@ MONITOR_AS_CRIT
Definition: smartd.cpp:352
time_t calc_next_wakeuptime(time_t wakeuptime, time_t timenow, int ct)
Definition: smartd.cpp:4306
static int ATADeviceScan(dev_config &cfg, dev_state &state, ata_device *atadev, const dev_config_vector *prev_cfgs)
Definition: smartd.cpp:1959
std::vector< dev_state > dev_state_vector
Container for state info for each device.
Definition: smartd.cpp:571
void pout(const char *fmt,...)
Definition: smartd.cpp:1335
static bool is_self_test_in_progress(unsigned char status)
Definition: smartd.cpp:1818
#define EXIT_NOMEM
Definition: smartd.cpp:133
static void finish_device_scan(dev_config &cfg, dev_state &state)
Definition: smartd.cpp:1899
#define EBUFLEN
Definition: smartd.cpp:1031
static bool check_nvme_error_log(const dev_config &cfg, dev_state &state, nvme_device *nvmedev, uint64_t newcnt=0)
Definition: smartd.cpp:2687
static bool parse_dev_state_line(const char *line, persistent_dev_state &state)
Definition: smartd.cpp:621
static const int scsiLogRespLen
Definition: smartd.cpp:123
static std::string warning_script
Definition: smartd.cpp:175
#define EXIT_STARTUP
Definition: smartd.cpp:128
static volatile int caughtsigUSR1
Definition: smartd.cpp:208
static int MakeConfigEntries(const dev_config &base_cfg, dev_config_vector &conf_entries, smart_device_list &scanned_devs, const smart_devtype_list &types)
Definition: smartd.cpp:5672
static int start_nvme_self_test(const dev_config &cfg, dev_state &state, nvme_device *device, char testtype, const nvme_self_test_log &self_test_log)
Definition: smartd.cpp:4012
static bool sanitize_dev_idinfo(std::string &s)
Definition: smartd.cpp:1721
static volatile int caughtsigHUP
Definition: smartd.cpp:217
#define STATIC_ASSERT(x)
Definition: static_assert.h:24
unsigned char model[40]
Definition: atacmds.h:120
unsigned short words088_255[168]
Definition: atacmds.h:130
unsigned char fw_rev[8]
Definition: atacmds.h:119
unsigned char serial_no[20]
Definition: atacmds.h:117
uint64_t capacity
Definition: atacmds.h:986
uint64_t sectors
Definition: atacmds.h:985
unsigned char id
Definition: atacmds.h:138
unsigned char current
Definition: atacmds.h:142
unsigned short flags
Definition: atacmds.h:141
unsigned char reserv
Definition: atacmds.h:145
unsigned char worst
Definition: atacmds.h:143
unsigned char raw[6]
Definition: atacmds.h:144
unsigned short int ata_error_count
Definition: atacmds.h:302
unsigned char error_log_pointer
Definition: atacmds.h:300
unsigned short error_log_index
Definition: atacmds.h:383
unsigned char reserved1
Definition: atacmds.h:382
unsigned short device_error_count
Definition: atacmds.h:385
struct ata_smart_log_entry entry[255]
Definition: atacmds.h:467
unsigned char numsectors
Definition: atacmds.h:458
unsigned char mostrecenttest
Definition: atacmds.h:412
struct ata_smart_selftestlog_struct selftest_struct[21]
Definition: atacmds.h:410
Definition: atacmds.h:231
struct ata_smart_threshold_entry thres_entries[NUMBER_ATA_SMART_ATTRIBUTES]
Definition: atacmds.h:244
unsigned char self_test_exec_status
Definition: atacmds.h:202
unsigned char offline_data_collection_capability
Definition: atacmds.h:205
unsigned char offline_data_collection_status
Definition: atacmds.h:201
struct ata_smart_attribute vendor_attributes[NUMBER_ATA_SMART_ATTRIBUTES]
Definition: atacmds.h:200
Configuration data for a device.
Definition: smartd.cpp:377
bool ignorepresets
Definition: smartd.cpp:404
std::string emailcmdline
Definition: smartd.cpp:416
bool offlinests
Definition: smartd.cpp:396
char powermode
Definition: smartd.cpp:407
bool ignore
Definition: smartd.cpp:387
ata_vendor_attr_defs attribute_defs
Definition: smartd.cpp:442
bool smartcheck
Definition: smartd.cpp:389
int set_wcache
Definition: smartd.cpp:428
int powerskipmax
Definition: smartd.cpp:409
char autoofflinetest
Definition: smartd.cpp:402
unsigned char tempdiff
Definition: smartd.cpp:410
int set_standby
Definition: smartd.cpp:426
int dev_rpm
Definition: smartd.cpp:422
unsigned short sct_erc_readtime
Definition: smartd.cpp:432
std::string state_file
Definition: smartd.cpp:384
int set_dsn
Definition: smartd.cpp:429
bool errorlog
Definition: smartd.cpp:394
std::string dev_idinfo_bc
Definition: smartd.cpp:383
std::string dev_idinfo
Definition: smartd.cpp:382
bool powerquiet
Definition: smartd.cpp:408
attribute_flags monitor_attr_flags
Definition: smartd.cpp:440
unsigned nvme_err_log_max_entries
Definition: smartd.cpp:445
unsigned test_offset_factor
Definition: smartd.cpp:413
firmwarebug_defs firmwarebugs
Definition: smartd.cpp:403
bool showpresets
Definition: smartd.cpp:405
bool removable
Definition: smartd.cpp:406
unsigned char offl_pending_id
Definition: smartd.cpp:436
unsigned char tempcrit
Definition: smartd.cpp:411
bool offlinests_ns
Definition: smartd.cpp:397
bool curr_pending_set
Definition: smartd.cpp:438
unsigned short sct_erc_writetime
Definition: smartd.cpp:433
bool sct_erc_set
Definition: smartd.cpp:431
int set_aam
Definition: smartd.cpp:423
bool selfteststs
Definition: smartd.cpp:398
unsigned char curr_pending_id
Definition: smartd.cpp:435
bool selftest
Definition: smartd.cpp:393
bool id_is_unique
Definition: smartd.cpp:388
std::string name
Definition: smartd.cpp:379
std::string emailaddress
Definition: smartd.cpp:417
bool offl_pending_incr
Definition: smartd.cpp:437
int lineno
Definition: smartd.cpp:378
int checktime
Definition: smartd.cpp:386
bool prefail
Definition: smartd.cpp:391
bool xerrorlog
Definition: smartd.cpp:395
int set_lookahead
Definition: smartd.cpp:425
bool usage
Definition: smartd.cpp:392
std::string attrlog_file
Definition: smartd.cpp:385
regular_expression test_regex
Definition: smartd.cpp:412
bool emailtest
Definition: smartd.cpp:419
bool set_security_freeze
Definition: smartd.cpp:427
bool usagefailed
Definition: smartd.cpp:390
std::string dev_name
Definition: smartd.cpp:380
emailfreqs emailfreq
Definition: smartd.cpp:418
bool selfteststs_ns
Definition: smartd.cpp:399
unsigned char tempinfo
Definition: smartd.cpp:411
bool permissive
Definition: smartd.cpp:400
char autosave
Definition: smartd.cpp:401
int set_apm
Definition: smartd.cpp:424
bool offl_pending_set
Definition: smartd.cpp:438
std::string dev_type
Definition: smartd.cpp:381
bool curr_pending_incr
Definition: smartd.cpp:437
Runtime state data for a device.
Definition: smartd.cpp:562
void update_temp_state()
Definition: smartd.cpp:597
void update_persistent_state()
Definition: smartd.cpp:574
const char * modelfamily
Definition: knowndrives.h:19
const char * warningmsg
Definition: knowndrives.h:22
time_t lastsent
Definition: smartd.cpp:457
int logged
Definition: smartd.cpp:455
time_t firstsent
Definition: smartd.cpp:456
Persistent state data for a device.
Definition: smartd.cpp:462
scsi_nonmedium_error_t scsi_nonmedium_error
Definition: smartd.cpp:501
unsigned char selflogcount
Definition: smartd.cpp:465
uint64_t selfloghour
Definition: smartd.cpp:466
unsigned char tempmax
Definition: smartd.cpp:463
uint64_t nvme_err_log_entries
Definition: smartd.cpp:504
uint64_t selective_test_last_end
Definition: smartd.cpp:472
ata_attribute ata_attributes[NUMBER_ATA_SMART_ATTRIBUTES]
Definition: smartd.cpp:487
uint64_t selective_test_last_start
Definition: smartd.cpp:471
unsigned char tempmin
Definition: smartd.cpp:463
mailinfo maillog[SMARTD_NMAIL]
Definition: smartd.cpp:474
time_t scheduled_test_next_check
Definition: smartd.cpp:469
scsi_error_counter_t scsi_error_counters[3]
Definition: smartd.cpp:495
uint64_t counter[8]
Definition: scsicmds.h:158
uint8_t modese_len
Definition: scsicmds.h:149
Device info strings.
Definition: dev_interface.h:37
std::string info_name
Informal name.
Definition: dev_interface.h:46
std::string dev_type
Actual device type.
Definition: dev_interface.h:47
std::string dev_name
Device (path)name.
Definition: dev_interface.h:45
unsigned char tnvmcap[16]
Definition: nvmecmds.h:97
unsigned short oacs
Definition: nvmecmds.h:83
nvme_self_test_result results[20]
Definition: nvmecmds.h:248
unsigned char critical_warning
Definition: nvmecmds.h:177
unsigned char temperature[2]
Definition: nvmecmds.h:178
unsigned char num_err_log_entries[16]
Definition: nvmecmds.h:192
Non-persistent state data for a device.
Definition: smartd.cpp:509
bool attrlog_dirty
Definition: smartd.cpp:530
bool not_cap_selective
Definition: smartd.cpp:519
bool not_cap_long
Definition: smartd.cpp:518
ata_smart_values smartval
Definition: smartd.cpp:546
bool not_cap_conveyance
Definition: smartd.cpp:516
unsigned char NonMediumErrorPageSupported
Definition: smartd.cpp:540
bool offline_started
Definition: smartd.cpp:548
unsigned char WriteECounterPageSupported
Definition: smartd.cpp:538
bool powermodefail
Definition: smartd.cpp:526
unsigned char temperature
Definition: smartd.cpp:521
ata_smart_thresholds_pvt smartthres
Definition: smartd.cpp:547
bool not_cap_short
Definition: smartd.cpp:517
bool not_cap_offline
Definition: smartd.cpp:515
uint64_t num_sectors
Definition: smartd.cpp:545
time_t tempmin_delay
Definition: smartd.cpp:522
time_t wakeuptime
Definition: smartd.cpp:513
unsigned char SuppressReport
Definition: smartd.cpp:541
unsigned char VerifyECounterPageSupported
Definition: smartd.cpp:539
bool selftest_started
Definition: smartd.cpp:551
unsigned char modese_len
Definition: smartd.cpp:542
bool must_write
Definition: smartd.cpp:510
unsigned char ReadECounterPageSupported
Definition: smartd.cpp:537
uint8_t selftest_op
Definition: smartd.cpp:554
unsigned char TempPageSupported
Definition: smartd.cpp:536
int lastpowermodeskipped
Definition: smartd.cpp:528
uint8_t selftest_compl
Definition: smartd.cpp:555
unsigned char SmartPageSupported
Definition: smartd.cpp:535
int powerskipcnt
Definition: smartd.cpp:527
void FixGlibcTimeZoneBug()
Definition: utility.cpp:214
const char * format_char_array(char *str, int strsize, const char *chr, int chrsize)
Definition: utility.cpp:692
std::string format_version_info(const char *prog_name, int lines)
Definition: utility.cpp:87
void dateandtimezoneepoch(char(&buffer)[DATEANDEPOCHLEN], time_t tval)
Definition: utility.cpp:349
const char * format_capacity(char *str, int strsize, uint64_t val, const char *decimal_point)
Definition: utility.cpp:748
std::string strprintf(const char *fmt,...)
Definition: utility.cpp:799
bool nonempty(const void *data, int size)
Definition: utility.cpp:682
const char * packetdevicetype(int type)
Definition: utility.cpp:315
struct tm * time_to_tm_local(struct tm *tp, time_t t)
Definition: utility.cpp:326
#define DATEANDEPOCHLEN
Definition: utility.h:64
#define __attribute_format_printf(x, y)
Definition: utility.h:34