* Home page of code is: https://www.smartmontools.org
*
* Copyright (C) 2002-11 Bruce Allen
* Copyright (C) 2008-23 Christian Franke
* Copyright (C) 2000 Michael Cornwell <cornwell@acm.org>
* Copyright (C) 2008 Oliver Bock <brevilo@users.sourceforge.net>
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "config.h"
#define __STDC_FORMAT_MACROS 1
#include <inttypes.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <fcntl.h>
#include <string.h>
#include <syslog.h>
#include <stdarg.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include <limits.h>
#include <getopt.h>
#include <algorithm>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
#ifndef _WIN32
#include <sys/wait.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef _WIN32
#include "os_win32/popen.h"
#ifdef _MSC_VER
#pragma warning(disable:4761)
typedef unsigned short mode_t;
typedef int pid_t;
#endif
#include <io.h>
#include <process.h>
#endif
#ifdef __CYGWIN__
#include <io.h>
#endif
#ifdef HAVE_LIBCAP_NG
#include <cap-ng.h>
#endif
#ifdef HAVE_LIBSYSTEMD
#include <systemd/sd-daemon.h>
#endif
#include "atacmds.h"
#include "dev_interface.h"
#include "knowndrives.h"
#include "scsicmds.h"
#include "nvmecmds.h"
#include "utility.h"
#ifdef HAVE_POSIX_API
#include "popen_as_ugid.h"
#endif
#ifdef _WIN32
#include "os_win32/daemon_win32.h"
#define strsignal daemon_strsignal
#define sleep daemon_sleep
#define SIGQUIT SIGBREAK
#define SIGQUIT_KEYNAME "CONTROL-Break"
#else
#define SIGQUIT_KEYNAME "CONTROL-\\"
#endif
const char * smartd_cpp_cvsid = "$Id: smartd.cpp 5519 2023-07-24 15:57:54Z chrfranke $"
CONFIG_H_CVSID;
extern "C" {
typedef void (*signal_handler_type)(int);
}
static void set_signal_if_not_ignored(int sig, signal_handler_type handler)
{
#if defined(_WIN32)
daemon_signal(sig, handler);
#elif defined(HAVE_SIGACTION)
struct sigaction sa;
sa.sa_handler = SIG_DFL;
sigaction(sig, (struct sigaction *)0, &sa);
if (sa.sa_handler == SIG_IGN)
return;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = handler;
sa.sa_flags = SA_RESTART;
sigaction(sig, &sa, (struct sigaction *)0);
#elif defined(HAVE_SIGSET)
if (sigset(sig, handler) == SIG_IGN)
sigset(sig, SIG_IGN);
#else
if (signal(sig, handler) == SIG_IGN)
signal(sig, SIG_IGN);
#endif
}
using namespace smartmontools;
static const int scsiLogRespLen = 252;
#define EXIT_BADCMD 1
#define EXIT_BADCONF 2
#define EXIT_STARTUP 3
#define EXIT_PID 4
#define EXIT_NOCONF 5
#define EXIT_READCONF 6
#define EXIT_NOMEM 8
#define EXIT_BADCODE 10
#define EXIT_BADDEV 16
#define EXIT_NODEV 17
#define EXIT_SIGNAL 254
static unsigned char debugmode = 0;
static constexpr int default_checktime = 1800;
static int checktime = default_checktime;
static int checktime_min = 0;
static std::string pid_file;
static std::string state_path_prefix
#ifdef SMARTMONTOOLS_SAVESTATES
= SMARTMONTOOLS_SAVESTATES
#endif
;
static std::string attrlog_path_prefix
#ifdef SMARTMONTOOLS_ATTRIBUTELOG
= SMARTMONTOOLS_ATTRIBUTELOG
#endif
;
static const char * configfile;
static const char * const configfile_stdin = "<stdin>";
static std::string configfile_alt;
static std::string warning_script;
#ifdef HAVE_POSIX_API
static bool warn_as_user;
static uid_t warn_uid;
static gid_t warn_gid;
static std::string warn_uname, warn_gname;
#elif defined(_WIN32)
static bool warn_as_restr_user;
#endif
enum quit_t {
QUIT_NODEV, QUIT_NODEVSTARTUP, QUIT_NEVER, QUIT_ONECHECK,
QUIT_SHOWTESTS, QUIT_ERRORS
};
static quit_t quit = QUIT_NODEV;
static bool quit_nodev0 = false;
static int facility=LOG_DAEMON;
#ifndef _WIN32
static bool do_fork=true;
#endif
unsigned char failuretest_permissive = 0;
static volatile int caughtsigUSR1=0;
#ifdef _WIN32
static volatile int caughtsigUSR2=0;
#endif
static volatile int caughtsigHUP=0;
static volatile int caughtsigEXIT=0;
static void PrintOut(int priority, const char *fmt, ...)
__attribute_format_printf(2, 3);
#ifdef HAVE_LIBSYSTEMD
static bool notify_enabled = false;
static bool notify_ready = false;
static inline void notify_init()
{
if (!getenv("NOTIFY_SOCKET"))
return;
notify_enabled = true;
}
static inline bool notify_post_init()
{
if (!notify_enabled)
return true;
if (do_fork) {
PrintOut(LOG_CRIT, "Option -n (--no-fork) is required if 'Type=notify' is set.\n");
return false;
}
return true;
}
static inline void notify_extend_timeout()
{
if (!notify_enabled)
return;
if (notify_ready)
return;
const char * notify = "EXTEND_TIMEOUT_USEC=20000000";
if (debugmode) {
pout("sd_notify(0, \"%s\")\n", notify);
return;
}
sd_notify(0, notify);
}
static void notify_msg(const char * msg, bool ready = false)
{
if (!notify_enabled)
return;
if (debugmode) {
pout("sd_notify(0, \"%sSTATUS=%s\")\n", (ready ? "READY=1\\n" : ""), msg);
return;
}
sd_notifyf(0, "%sSTATUS=%s", (ready ? "READY=1\n" : ""), msg);
}
static void notify_check(int numdev)
{
if (!notify_enabled)
return;
char msg[32];
snprintf(msg, sizeof(msg), "Checking %d device%s ...",
numdev, (numdev != 1 ? "s" : ""));
notify_msg(msg);
}
static void notify_wait(time_t wakeuptime, int numdev)
{
if (!notify_enabled)
return;
char ts[16] = ""; struct tm tmbuf;
strftime(ts, sizeof(ts), "%H:%M:%S", time_to_tm_local(&tmbuf, wakeuptime));
char msg[64];
snprintf(msg, sizeof(msg), "Next check of %d device%s will start at %s",
numdev, (numdev != 1 ? "s" : ""), ts);
notify_msg(msg, !notify_ready);
notify_ready = true;
}
static void notify_exit(int status)
{
if (!notify_enabled)
return;
const char * msg;
switch (status) {
case 0: msg = "Exiting ..."; break;
case EXIT_BADCMD: msg = "Error in command line (see SYSLOG)"; break;
case EXIT_BADCONF: case EXIT_NOCONF:
case EXIT_READCONF: msg = "Error in config file (see SYSLOG)"; break;
case EXIT_BADDEV: msg = "Unable to register a device (see SYSLOG)"; break;
case EXIT_NODEV: msg = "No devices to monitor"; break;
default: msg = "Error (see SYSLOG)"; break;
}
notify_msg(msg, (!status && !notify_ready));
}
#else
static inline bool notify_post_init()
{
#ifdef __linux__
if (getenv("NOTIFY_SOCKET")) {
PrintOut(LOG_CRIT, "This version of smartd was build without 'Type=notify' support.\n");
return false;
}
#endif
return true;
}
static inline void notify_init() { }
static inline void notify_extend_timeout() { }
static inline void notify_msg(const char *) { }
static inline void notify_check(int) { }
static inline void notify_wait(time_t, int) { }
static inline void notify_exit(int) { }
#endif
enum class emailfreqs : unsigned char {
unknown, once, always, daily, diminishing
};
enum {
MONITOR_IGN_FAILUSE = 0x01,
MONITOR_IGNORE = 0x02,
MONITOR_RAW_PRINT = 0x04,
MONITOR_RAW = 0x08,
MONITOR_AS_CRIT = 0x10,
MONITOR_RAW_AS_CRIT = 0x20,
};
class attribute_flags
{
public:
bool is_set(int id, unsigned char flag) const
{ return (0 < id && id < (int)sizeof(m_flags) && (m_flags[id] & flag)); }
void set(int id, unsigned char flags)
{
if (0 < id && id < (int)sizeof(m_flags))
m_flags[id] |= flags;
}
private:
unsigned char m_flags[256]{};
};
struct dev_config
{
int lineno{};
std::string name;
std::string dev_name;
std::string dev_type;
std::string dev_idinfo;
std::string state_file;
std::string attrlog_file;
int checktime{};
bool ignore{};
bool id_is_unique{};
bool smartcheck{};
bool usagefailed{};
bool prefail{};
bool usage{};
bool selftest{};
bool errorlog{};
bool xerrorlog{};
bool offlinests{};
bool offlinests_ns{};
bool selfteststs{};
bool selfteststs_ns{};
bool permissive{};
char autosave{};
char autoofflinetest{};
firmwarebug_defs firmwarebugs;
bool ignorepresets{};
bool showpresets{};
bool removable{};
char powermode{};
bool powerquiet{};
int powerskipmax{};
unsigned char tempdiff{};
unsigned char tempinfo{}, tempcrit{};
regular_expression test_regex;
unsigned test_offset_factor{};
std::string emailcmdline;
std::string emailaddress;
emailfreqs emailfreq{};
bool emailtest{};
int dev_rpm{};
int set_aam{};
int set_apm{};
int set_lookahead{};
int set_standby{};
bool set_security_freeze{};
int set_wcache{};
int set_dsn{};
bool sct_erc_set{};
unsigned short sct_erc_readtime{};
unsigned short sct_erc_writetime{};
unsigned char curr_pending_id{};
unsigned char offl_pending_id{};
bool curr_pending_incr{}, offl_pending_incr{};
bool curr_pending_set{}, offl_pending_set{};
attribute_flags monitor_attr_flags;
ata_vendor_attr_defs attribute_defs;
unsigned nvme_err_log_max_entries{};
};
static const int SMARTD_NMAIL = 13;
static const int MAILTYPE_TEST = 0;
struct mailinfo {
int logged{};
time_t firstsent{};
time_t lastsent{};
};
struct persistent_dev_state
{
unsigned char tempmin{}, tempmax{};
unsigned char selflogcount{};
unsigned short selfloghour{};
time_t scheduled_test_next_check{};
uint64_t selective_test_last_start{};
uint64_t selective_test_last_end{};
mailinfo maillog[SMARTD_NMAIL];
int ataerrorcount{};
struct ata_attribute {
unsigned char id{};
unsigned char val{};
unsigned char worst{};
uint64_t raw{};
unsigned char resvd{};
};
ata_attribute ata_attributes[NUMBER_ATA_SMART_ATTRIBUTES];
struct scsi_error_counter_t {
struct scsiErrorCounter errCounter{};
unsigned char found{};
};
scsi_error_counter_t scsi_error_counters[3];
struct scsi_nonmedium_error_t {
struct scsiNonMediumError nme{};
unsigned char found{};
};
scsi_nonmedium_error_t scsi_nonmedium_error;
uint64_t nvme_err_log_entries{};
};
struct temp_dev_state
{
bool must_write{};
bool skip{};
time_t wakeuptime{};
bool not_cap_offline{};
bool not_cap_conveyance{};
bool not_cap_short{};
bool not_cap_long{};
bool not_cap_selective{};
unsigned char temperature{};
time_t tempmin_delay{};
bool removed{};
bool powermodefail{};
int powerskipcnt{};
int lastpowermodeskipped{};
bool attrlog_dirty{};
unsigned char SmartPageSupported{};
unsigned char TempPageSupported{};
unsigned char ReadECounterPageSupported{};
unsigned char WriteECounterPageSupported{};
unsigned char VerifyECounterPageSupported{};
unsigned char NonMediumErrorPageSupported{};
unsigned char SuppressReport{};
unsigned char modese_len{};
uint64_t num_sectors{};
ata_smart_values smartval{};
ata_smart_thresholds_pvt smartthres{};
bool offline_started{};
bool selftest_started{};
};
struct dev_state
: public persistent_dev_state,
public temp_dev_state
{
void update_persistent_state();
void update_temp_state();
};
typedef std::vector<dev_config> dev_config_vector;
typedef std::vector<dev_state> dev_state_vector;
void dev_state::update_persistent_state()
{
for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
const ata_smart_attribute & ta = smartval.vendor_attributes[i];
ata_attribute & pa = ata_attributes[i];
pa.id = ta.id;
if (ta.id == 0) {
pa.val = pa.worst = 0; pa.raw = 0;
continue;
}
pa.val = ta.current;
pa.worst = ta.worst;
pa.raw = ta.raw[0]
| ( ta.raw[1] << 8)
| ( ta.raw[2] << 16)
| ((uint64_t)ta.raw[3] << 24)
| ((uint64_t)ta.raw[4] << 32)
| ((uint64_t)ta.raw[5] << 40);
pa.resvd = ta.reserv;
}
}
void dev_state::update_temp_state()
{
for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
const ata_attribute & pa = ata_attributes[i];
ata_smart_attribute & ta = smartval.vendor_attributes[i];
ta.id = pa.id;
if (pa.id == 0) {
ta.current = ta.worst = 0;
memset(ta.raw, 0, sizeof(ta.raw));
continue;
}
ta.current = pa.val;
ta.worst = pa.worst;
ta.raw[0] = (unsigned char) pa.raw;
ta.raw[1] = (unsigned char)(pa.raw >> 8);
ta.raw[2] = (unsigned char)(pa.raw >> 16);
ta.raw[3] = (unsigned char)(pa.raw >> 24);
ta.raw[4] = (unsigned char)(pa.raw >> 32);
ta.raw[5] = (unsigned char)(pa.raw >> 40);
ta.reserv = pa.resvd;
}
}
static bool parse_dev_state_line(const char * line, persistent_dev_state & state)
{
static const regular_expression regex(
"^ *"
"((temperature-min)"
"|(temperature-max)"
"|(self-test-errors)"
"|(self-test-last-err-hour)"
"|(scheduled-test-next-check)"
"|(selective-test-last-start)"
"|(selective-test-last-end)"
"|(ata-error-count)"
"|(mail\\.([0-9]+)\\."
"((count)"
"|(first-sent-time)"
"|(last-sent-time)"
")"
")"
"|(ata-smart-attribute\\.([0-9]+)\\."
"((id)"
"|(val)"
"|(worst)"
"|(raw)"
"|(resvd)"
")"
")"
"|(nvme-err-log-entries)"
")"
" *= *([0-9]+)[ \n]*$"
);
const int nmatch = 1+25;
regular_expression::match_range match[nmatch];
if (!regex.execute(line, nmatch, match))
return false;
if (match[nmatch-1].rm_so < 0)
return false;
uint64_t val = strtoull(line + match[nmatch-1].rm_so, (char **)0, 10);
int m = 1;
if (match[++m].rm_so >= 0)
state.tempmin = (unsigned char)val;
else if (match[++m].rm_so >= 0)
state.tempmax = (unsigned char)val;
else if (match[++m].rm_so >= 0)
state.selflogcount = (unsigned char)val;
else if (match[++m].rm_so >= 0)
state.selfloghour = (unsigned short)val;
else if (match[++m].rm_so >= 0)
state.scheduled_test_next_check = (time_t)val;
else if (match[++m].rm_so >= 0)
state.selective_test_last_start = val;
else if (match[++m].rm_so >= 0)
state.selective_test_last_end = val;
else if (match[++m].rm_so >= 0)
state.ataerrorcount = (int)val;
else if (match[m+=2].rm_so >= 0) {
int i = atoi(line+match[m].rm_so);
if (!(0 <= i && i < SMARTD_NMAIL))
return false;
if (i == MAILTYPE_TEST)
return true;
if (match[m+=2].rm_so >= 0)
state.maillog[i].logged = (int)val;
else if (match[++m].rm_so >= 0)
state.maillog[i].firstsent = (time_t)val;
else if (match[++m].rm_so >= 0)
state.maillog[i].lastsent = (time_t)val;
else
return false;
}
else if (match[m+=5+1].rm_so >= 0) {
int i = atoi(line+match[m].rm_so);
if (!(0 <= i && i < NUMBER_ATA_SMART_ATTRIBUTES))
return false;
if (match[m+=2].rm_so >= 0)
state.ata_attributes[i].id = (unsigned char)val;
else if (match[++m].rm_so >= 0)
state.ata_attributes[i].val = (unsigned char)val;
else if (match[++m].rm_so >= 0)
state.ata_attributes[i].worst = (unsigned char)val;
else if (match[++m].rm_so >= 0)
state.ata_attributes[i].raw = val;
else if (match[++m].rm_so >= 0)
state.ata_attributes[i].resvd = (unsigned char)val;
else
return false;
}
else if (match[m+7].rm_so >= 0)
state.nvme_err_log_entries = val;
else
return false;
return true;
}
static bool read_dev_state(const char * path, persistent_dev_state & state)
{
stdio_file f(path, "r");
if (!f) {
if (errno != ENOENT)
pout("Cannot read state file \"%s\"\n", path);
return false;
}
#ifdef __CYGWIN__
setmode(fileno(f), O_TEXT);
#endif
persistent_dev_state new_state;
int good = 0, bad = 0;
char line[256];
while (fgets(line, sizeof(line), f)) {
const char * s = line + strspn(line, " \t");
if (!*s || *s == '#')
continue;
if (!parse_dev_state_line(line, new_state))
bad++;
else
good++;
}
if (bad) {
if (!good) {
pout("%s: format error\n", path);
return false;
}
pout("%s: %d invalid line(s) ignored\n", path, bad);
}
state = new_state;
return true;
}
static void write_dev_state_line(FILE * f, const char * name, uint64_t val)
{
if (val)
fprintf(f, "%s = %" PRIu64 "\n", name, val);
}
static void write_dev_state_line(FILE * f, const char * name1, int id, const char * name2, uint64_t val)
{
if (val)
fprintf(f, "%s.%d.%s = %" PRIu64 "\n", name1, id, name2, val);
}
static bool write_dev_state(const char * path, const persistent_dev_state & state)
{
std::string pathbak = path; pathbak += '~';
unlink(pathbak.c_str());
rename(path, pathbak.c_str());
stdio_file f(path, "w");
if (!f) {
pout("Cannot create state file \"%s\"\n", path);
return false;
}
fprintf(f, "# smartd state file\n");
write_dev_state_line(f, "temperature-min", state.tempmin);
write_dev_state_line(f, "temperature-max", state.tempmax);
write_dev_state_line(f, "self-test-errors", state.selflogcount);
write_dev_state_line(f, "self-test-last-err-hour", state.selfloghour);
write_dev_state_line(f, "scheduled-test-next-check", state.scheduled_test_next_check);
write_dev_state_line(f, "selective-test-last-start", state.selective_test_last_start);
write_dev_state_line(f, "selective-test-last-end", state.selective_test_last_end);
for (int i = 0; i < SMARTD_NMAIL; i++) {
if (i == MAILTYPE_TEST)
continue;
const mailinfo & mi = state.maillog[i];
if (!mi.logged)
continue;
write_dev_state_line(f, "mail", i, "count", mi.logged);
write_dev_state_line(f, "mail", i, "first-sent-time", mi.firstsent);
write_dev_state_line(f, "mail", i, "last-sent-time", mi.lastsent);
}
write_dev_state_line(f, "ata-error-count", state.ataerrorcount);
for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
const auto & pa = state.ata_attributes[i];
if (!pa.id)
continue;
write_dev_state_line(f, "ata-smart-attribute", i, "id", pa.id);
write_dev_state_line(f, "ata-smart-attribute", i, "val", pa.val);
write_dev_state_line(f, "ata-smart-attribute", i, "worst", pa.worst);
write_dev_state_line(f, "ata-smart-attribute", i, "raw", pa.raw);
write_dev_state_line(f, "ata-smart-attribute", i, "resvd", pa.resvd);
}
write_dev_state_line(f, "nvme-err-log-entries", state.nvme_err_log_entries);
return true;
}
static bool write_dev_attrlog(const char * path, const dev_state & state)
{
stdio_file f(path, "a");
if (!f) {
pout("Cannot create attribute log file \"%s\"\n", path);
return false;
}
time_t now = time(nullptr);
struct tm tmbuf, * tms = time_to_tm_local(&tmbuf, now);
fprintf(f, "%d-%02d-%02d %02d:%02d:%02d;",
1900+tms->tm_year, 1+tms->tm_mon, tms->tm_mday,
tms->tm_hour, tms->tm_min, tms->tm_sec);
for (const auto & pa : state.ata_attributes) {
if (!pa.id)
continue;
fprintf(f, "\t%d;%d;%" PRIu64 ";", pa.id, pa.val, pa.raw);
}
const struct scsiErrorCounter * ecp;
const char * pageNames[3] = {"read", "write", "verify"};
for (int k = 0; k < 3; ++k) {
if ( !state.scsi_error_counters[k].found ) continue;
ecp = &state.scsi_error_counters[k].errCounter;
fprintf(f, "\t%s-corr-by-ecc-fast;%" PRIu64 ";"
"\t%s-corr-by-ecc-delayed;%" PRIu64 ";"
"\t%s-corr-by-retry;%" PRIu64 ";"
"\t%s-total-err-corrected;%" PRIu64 ";"
"\t%s-corr-algorithm-invocations;%" PRIu64 ";"
"\t%s-gb-processed;%.3f;"
"\t%s-total-unc-errors;%" PRIu64 ";",
pageNames[k], ecp->counter[0],
pageNames[k], ecp->counter[1],
pageNames[k], ecp->counter[2],
pageNames[k], ecp->counter[3],
pageNames[k], ecp->counter[4],
pageNames[k], (ecp->counter[5] / 1000000000.0),
pageNames[k], ecp->counter[6]);
}
if(state.scsi_nonmedium_error.found && state.scsi_nonmedium_error.nme.gotPC0) {
fprintf(f, "\tnon-medium-errors;%" PRIu64 ";", state.scsi_nonmedium_error.nme.counterPC0);
}
if (state.temperature)
fprintf(f, "\ttemperature;%d;", state.temperature);
fprintf(f, "\n");
return true;
}
static void write_all_dev_states(const dev_config_vector & configs,
dev_state_vector & states,
bool write_always = true)
{
for (unsigned i = 0; i < states.size(); i++) {
const dev_config & cfg = configs.at(i);
if (cfg.state_file.empty())
continue;
dev_state & state = states[i];
if (!write_always && !state.must_write)
continue;
if (!write_dev_state(cfg.state_file.c_str(), state))
continue;
state.must_write = false;
if (write_always || debugmode)
PrintOut(LOG_INFO, "Device: %s, state written to %s\n",
cfg.name.c_str(), cfg.state_file.c_str());
}
}
static void write_all_dev_attrlogs(const dev_config_vector & configs,
dev_state_vector & states)
{
for (unsigned i = 0; i < states.size(); i++) {
const dev_config & cfg = configs.at(i);
if (cfg.attrlog_file.empty())
continue;
dev_state & state = states[i];
if (state.attrlog_dirty) {
write_dev_attrlog(cfg.attrlog_file.c_str(), state);
state.attrlog_dirty = false;
}
}
}
extern "C" {
static void USR1handler(int sig)
{
if (SIGUSR1==sig)
caughtsigUSR1=1;
return;
}
#ifdef _WIN32
static void USR2handler(int sig)
{
if (SIGUSR2==sig)
caughtsigUSR2=1;
return;
}
#endif
static void HUPhandler(int sig)
{
if (sig==SIGHUP)
caughtsigHUP=1;
else
caughtsigHUP=2;
return;
}
static void sighandler(int sig)
{
if (!caughtsigEXIT)
caughtsigEXIT=sig;
return;
}
}
#ifdef HAVE_LIBCAP_NG
static int capabilities_mode ;
static void capabilities_drop_now()
{
if (!capabilities_mode)
return;
capng_clear(CAPNG_SELECT_BOTH);
capng_updatev(CAPNG_ADD, (capng_type_t)(CAPNG_EFFECTIVE|CAPNG_PERMITTED),
CAP_SYS_ADMIN, CAP_MKNOD, CAP_SYS_RAWIO, -1);
if (warn_as_user && (warn_uid || warn_gid)) {
capng_updatev(CAPNG_ADD, (capng_type_t)(CAPNG_EFFECTIVE|CAPNG_PERMITTED),
CAP_SETGID, CAP_SETUID, -1);
}
if (capabilities_mode > 1) {
capng_updatev(CAPNG_ADD, CAPNG_BOUNDING_SET,
CAP_SETGID, CAP_SETUID, CAP_CHOWN, CAP_FOWNER, CAP_DAC_OVERRIDE, -1);
}
capng_apply(CAPNG_SELECT_BOTH);
}
static void capabilities_log_error_hint()
{
if (!capabilities_mode)
return;
PrintOut(LOG_INFO, "If mail notification does not work with '--capabilities%s\n",
(capabilities_mode == 1 ? "', try '--capabilities=mail'"
: "=mail', please inform " PACKAGE_BUGREPORT));
}
#else
static inline void capabilities_drop_now() { }
static inline void capabilities_log_error_hint() { }
#endif
class env_buffer
{
public:
env_buffer() = default;
env_buffer(const env_buffer &) = delete;
void operator=(const env_buffer &) = delete;
void set(const char * name, const char * value);
private:
char * m_buf = nullptr;
};
void env_buffer::set(const char * name, const char * value)
{
int size = strlen(name) + 1 + strlen(value) + 1;
char * newbuf = new char[size];
snprintf(newbuf, size, "%s=%s", name, value);
if (putenv(newbuf))
throw std::runtime_error("putenv() failed");
delete [] m_buf;
m_buf = newbuf;
}
#define EBUFLEN 1024
static void MailWarning(const dev_config & cfg, dev_state & state, int which, const char *fmt, ...)
__attribute_format_printf(4, 5);
static void MailWarning(const dev_config & cfg, dev_state & state, int which, const char *fmt, ...)
{
if (cfg.emailaddress.empty() && cfg.emailcmdline.empty())
return;
static const char * const whichfail[] = {
"EmailTest",
"Health",
"Usage",
"SelfTest",
"ErrorCount",
"FailedHealthCheck",
"FailedReadSmartData",
"FailedReadSmartErrorLog",
"FailedReadSmartSelfTestLog",
"FailedOpenDevice",
"CurrentPendingSector",
"OfflineUncorrectableSector",
"Temperature"
};
STATIC_ASSERT(sizeof(whichfail) == SMARTD_NMAIL * sizeof(whichfail[0]));
if (!(0 <= which && which < SMARTD_NMAIL)) {
PrintOut(LOG_CRIT, "Internal error in MailWarning(): which=%d\n", which);
return;
}
mailinfo * mail = state.maillog + which;
int days, nextdays;
if (which == 0)
days = nextdays = -1;
else switch (cfg.emailfreq) {
case emailfreqs::once:
days = nextdays = -1; break;
case emailfreqs::always:
days = nextdays = 0; break;
case emailfreqs::daily:
days = nextdays = 1; break;
case emailfreqs::diminishing:
nextdays = 1 << ((unsigned)mail->logged <= 5 ? mail->logged : 5);
days = ((unsigned)mail->logged <= 5 ? nextdays >> 1 : nextdays);
break;
default:
PrintOut(LOG_CRIT, "Internal error in MailWarning(): cfg.emailfreq=%d\n", (int)cfg.emailfreq);
return;
}
time_t now = time(nullptr);
if (mail->logged) {
if (days < 0)
return;
if (days > 0 && now < mail->lastsent + days * 24 * 3600)
return;
}
else {
mail->firstsent = now;
}
mail->lastsent = now;
char message[512];
va_list ap;
va_start(ap, fmt);
vsnprintf(message, sizeof(message), fmt, ap);
va_end(ap);
std::string address = cfg.emailaddress;
std::replace(address.begin(), address.end(), ',', ' ');
const char * executable = cfg.emailcmdline.c_str();
static env_buffer env[13];
env[0].set("SMARTD_MAILER", executable);
env[1].set("SMARTD_MESSAGE", message);
char dates[DATEANDEPOCHLEN];
snprintf(dates, sizeof(dates), "%d", mail->logged);
env[2].set("SMARTD_PREVCNT", dates);
dateandtimezoneepoch(dates, mail->firstsent);
env[3].set("SMARTD_TFIRST", dates);
snprintf(dates, DATEANDEPOCHLEN,"%d", (int)mail->firstsent);
env[4].set("SMARTD_TFIRSTEPOCH", dates);
env[5].set("SMARTD_FAILTYPE", whichfail[which]);
env[6].set("SMARTD_ADDRESS", address.c_str());
env[7].set("SMARTD_DEVICESTRING", cfg.name.c_str());
env[8].set("SMARTD_DEVICETYPE",
(!cfg.dev_type.empty() ? cfg.dev_type.c_str() : "auto"));
env[9].set("SMARTD_DEVICE", cfg.dev_name.c_str());
env[10].set("SMARTD_DEVICEINFO", cfg.dev_idinfo.c_str());
dates[0] = 0;
if (nextdays >= 0)
snprintf(dates, sizeof(dates), "%d", nextdays);
env[11].set("SMARTD_NEXTDAYS", dates);
env[12].set("SMARTD_SUBJECT", "");
if (!*executable)
executable = "<mail>";
const char * newadd = (!address.empty()? address.c_str() : "<nomailer>");
const char * newwarn = (which? "Warning via" : "Test of");
char command[256];
#ifdef _WIN32
snprintf(command, sizeof(command), "\"%s\" 2>&1", warning_script.c_str());
#else
snprintf(command, sizeof(command), "%s 2>&1", warning_script.c_str());
#endif
PrintOut(LOG_INFO,"%s %s to %s%s ...\n",
(which ? "Sending warning via" : "Executing test of"), executable, newadd,
(
#ifdef HAVE_POSIX_API
warn_as_user ?
strprintf(" (uid=%u(%s) gid=%u(%s))",
(unsigned)warn_uid, warn_uname.c_str(),
(unsigned)warn_gid, warn_gname.c_str() ).c_str() :
#elif defined(_WIN32)
warn_as_restr_user ? " (restricted user)" :
#endif
""
)
);
errno=0;
FILE * pfp;
#ifdef HAVE_POSIX_API
if (warn_as_user) {
pfp = popen_as_ugid(command, "r", warn_uid, warn_gid);
} else
#endif
{
#ifdef _WIN32
pfp = popen_as_restr_user(command, "r", warn_as_restr_user);
#else
pfp = popen(command, "r");
#endif
}
if (!pfp)
PrintOut(LOG_CRIT,"%s %s to %s: failed (fork or pipe failed, or no memory) %s\n",
newwarn, executable, newadd, errno?strerror(errno):"");
else {
int len;
char buffer[EBUFLEN];
if ((len=fread(buffer, 1, EBUFLEN, pfp))) {
int count=0;
int newlen = len<EBUFLEN ? len : EBUFLEN-1;
buffer[newlen]='\0';
PrintOut(LOG_CRIT,"%s %s to %s produced unexpected output (%s%d bytes) to STDOUT/STDERR: \n%s\n",
newwarn, executable, newadd, len!=newlen?"here truncated to ":"", newlen, buffer);
while (fread(buffer, 1, EBUFLEN, pfp) && count<EBUFLEN)
count++;
if (count && count<EBUFLEN)
PrintOut(LOG_CRIT,"%s %s to %s: flushed remaining STDOUT/STDERR\n",
newwarn, executable, newadd);
else if (count)
PrintOut(LOG_CRIT,"%s %s to %s: more than 1 MB STDOUT/STDERR flushed, breaking pipe\n",
newwarn, executable, newadd);
}
errno=0;
int status;
#ifdef HAVE_POSIX_API
if (warn_as_user) {
status = pclose_as_ugid(pfp);
} else
#endif
{
status = pclose(pfp);
}
if (status == -1)
PrintOut(LOG_CRIT,"%s %s to %s: pclose(3) failed %s\n", newwarn, executable, newadd,
errno?strerror(errno):"");
else {
if (WIFEXITED(status)) {
int status8 = WEXITSTATUS(status);
if (status8>128)
PrintOut(LOG_CRIT,"%s %s to %s: failed (32-bit/8-bit exit status: %d/%d) perhaps caught signal %d [%s]\n",
newwarn, executable, newadd, status, status8, status8-128, strsignal(status8-128));
else if (status8) {
PrintOut(LOG_CRIT,"%s %s to %s: failed (32-bit/8-bit exit status: %d/%d)\n",
newwarn, executable, newadd, status, status8);
capabilities_log_error_hint();
}
else
PrintOut(LOG_INFO,"%s %s to %s: successful\n", newwarn, executable, newadd);
}
if (WIFSIGNALED(status))
PrintOut(LOG_INFO,"%s %s to %s: exited because of uncaught signal %d [%s]\n",
newwarn, executable, newadd, WTERMSIG(status), strsignal(WTERMSIG(status)));
if (WIFSTOPPED(status))
PrintOut(LOG_CRIT,"%s %s to %s: process STOPPED because it caught signal %d [%s]\n",
newwarn, executable, newadd, WSTOPSIG(status), strsignal(WSTOPSIG(status)));
}
}
mail->logged++;
}
static void reset_warning_mail(const dev_config & cfg, dev_state & state, int which, const char *fmt, ...)
__attribute_format_printf(4, 5);
static void reset_warning_mail(const dev_config & cfg, dev_state & state, int which, const char *fmt, ...)
{
if (!(0 <= which && which < SMARTD_NMAIL))
return;
mailinfo & mi = state.maillog[which];
if (!mi.logged)
return;
char msg[256];
va_list ap;
va_start(ap, fmt);
vsnprintf(msg, sizeof(msg), fmt, ap);
va_end(ap);
PrintOut(LOG_INFO, "Device: %s, %s, warning condition reset after %d email%s\n", cfg.name.c_str(),
msg, mi.logged, (mi.logged==1 ? "" : "s"));
mi = mailinfo();
state.must_write = true;
}
#ifndef _WIN32
__attribute_format_printf(2, 0)
static void vsyslog_lines(int priority, const char * fmt, va_list ap)
{
char buf[512+EBUFLEN];
vsnprintf(buf, sizeof(buf), fmt, ap);
for (char * p = buf, * q; p && *p; p = q) {
if ((q = strchr(p, '\n')))
*q++ = 0;
if (*p)
syslog(priority, "%s\n", p);
}
}
#else
#define vsyslog_lines vsyslog
#endif
void pout(const char *fmt, ...){
va_list ap;
FixGlibcTimeZoneBug();
va_start(ap,fmt);
if (debugmode && debugmode != 2) {
FILE * f = stdout;
#ifdef _WIN32
if (facility == LOG_LOCAL1)
f = stderr;
#endif
vfprintf(f, fmt, ap);
fflush(f);
}
else if (debugmode==2 || ata_debugmode || scsi_debugmode) {
openlog("smartd", LOG_PID, facility);
vsyslog_lines(LOG_INFO, fmt, ap);
closelog();
}
va_end(ap);
return;
}
static void PrintOut(int priority, const char *fmt, ...){
va_list ap;
FixGlibcTimeZoneBug();
va_start(ap,fmt);
if (debugmode) {
FILE * f = stdout;
#ifdef _WIN32
if (facility == LOG_LOCAL1)
f = stderr;
#endif
vfprintf(f, fmt, ap);
fflush(f);
}
else {
openlog("smartd", LOG_PID, facility);
vsyslog_lines(priority, fmt, ap);
closelog();
}
va_end(ap);
return;
}
void checksumwarning(const char * string)
{
pout("Warning! %s error: invalid SMART checksum.\n", string);
}
#ifndef _WIN32
static bool WaitForPidFile()
{
int waited, max_wait = 10;
struct stat stat_buf;
if (pid_file.empty() || debugmode)
return true;
for(waited = 0; waited < max_wait; ++waited) {
if (!stat(pid_file.c_str(), &stat_buf)) {
return true;
} else
sleep(1);
}
return false;
}
#endif
static int daemon_init()
{
#ifndef _WIN32
fflush(nullptr);
if (do_fork) {
pid_t pid;
if ((pid=fork()) < 0) {
PrintOut(LOG_CRIT,"smartd unable to fork daemon process!\n");
return EXIT_STARTUP;
}
if (pid) {
if(!WaitForPidFile()) {
PrintOut(LOG_CRIT,"PID file %s didn't show up!\n", pid_file.c_str());
return EXIT_STARTUP;
}
return 0;
}
setsid();
if ((pid=fork()) < 0) {
PrintOut(LOG_CRIT,"smartd unable to fork daemon process!\n");
return EXIT_STARTUP;
}
if (pid)
return 0;
}
for (int i = sysconf(_SC_OPEN_MAX); --i >= 0; )
close(i);
int fd = open("/dev/null", O_RDWR);
if (!(fd == 0 && dup(fd) == 1 && dup(fd) == 2 && !chdir("/"))) {
PrintOut(LOG_CRIT, "smartd unable to redirect to /dev/null or to chdir to root!\n");
return EXIT_STARTUP;
}
umask(0022);
if (do_fork)
PrintOut(LOG_INFO, "smartd has fork()ed into background mode. New PID=%d.\n", (int)getpid());
#else
fflush(nullptr);
if (daemon_detach("smartd")) {
PrintOut(LOG_CRIT,"smartd unable to detach from console!\n");
return EXIT_STARTUP;
}
#endif
return -1;
}
static bool write_pid_file()
{
if (!pid_file.empty()) {
pid_t pid = getpid();
mode_t old_umask;
#ifndef __CYGWIN__
old_umask = umask(0077);
#else
old_umask = umask(0033);
#endif
stdio_file f(pid_file.c_str(), "w");
umask(old_umask);
if (!(f && fprintf(f, "%d\n", (int)pid) > 0 && f.close())) {
PrintOut(LOG_CRIT, "unable to write PID file %s - exiting.\n", pid_file.c_str());
return false;
}
PrintOut(LOG_INFO, "file %s written containing PID %d\n", pid_file.c_str(), (int)pid);
}
return true;
}
static void PrintHead()
{
PrintOut(LOG_INFO, "%s\n", format_version_info("smartd").c_str());
}
static void Directives()
{
PrintOut(LOG_INFO,
"Configuration file (%s) Directives (after device name):\n"
" -d TYPE Set the device type: auto, ignore, removable,\n"
" %s\n"
" -T TYPE Set the tolerance to one of: normal, permissive\n"
" -o VAL Enable/disable automatic offline tests (on/off)\n"
" -S VAL Enable/disable attribute autosave (on/off)\n"
" -n MODE No check if: never, sleep[,N][,q], standby[,N][,q], idle[,N][,q]\n"
" -H Monitor SMART Health Status, report if failed\n"
" -s REG Do Self-Test at time(s) given by regular expression REG\n"
" -l TYPE Monitor SMART log or self-test status:\n"
" error, selftest, xerror, offlinests[,ns], selfteststs[,ns]\n"
" -l scterc,R,W Set SCT Error Recovery Control\n"
" -e Change device setting: aam,[N|off], apm,[N|off], dsn,[on|off],\n"
" lookahead,[on|off], security-freeze, standby,[N|off], wcache,[on|off]\n"
" -f Monitor 'Usage' Attributes, report failures\n"
" -m ADD Send email warning to address ADD\n"
" -M TYPE Modify email warning behavior (see man page)\n"
" -p Report changes in 'Prefailure' Attributes\n"
" -u Report changes in 'Usage' Attributes\n"
" -t Equivalent to -p and -u Directives\n"
" -r ID Also report Raw values of Attribute ID with -p, -u or -t\n"
" -R ID Track changes in Attribute ID Raw value with -p, -u or -t\n"
" -i ID Ignore Attribute ID for -f Directive\n"
" -I ID Ignore Attribute ID for -p, -u or -t Directive\n"
" -C ID[+] Monitor [increases of] Current Pending Sectors in Attribute ID\n"
" -U ID[+] Monitor [increases of] Offline Uncorrectable Sectors in Attribute ID\n"
" -W D,I,C Monitor Temperature D)ifference, I)nformal limit, C)ritical limit\n"
" -v N,ST Modifies labeling of Attribute N (see man page) \n"
" -P TYPE Drive-specific presets: use, ignore, show, showall\n"
" -a Default: -H -f -t -l error -l selftest -l selfteststs -C 197 -U 198\n"
" -F TYPE Use firmware bug workaround:\n"
" %s\n"
" -c i=N Set interval between disk checks to N seconds\n"
" # Comment: text after a hash sign is ignored\n"
" \\ Line continuation character\n"
"Attribute ID is a decimal integer 1 <= ID <= 255\n"
"Use ID = 0 to turn off -C and/or -U Directives\n"
"Example: /dev/sda -a\n",
configfile,
smi()->get_valid_dev_types_str().c_str(),
get_valid_firmwarebug_args());
}
arguments to the option opt or nullptr on failure. */
static const char *GetValidArgList(char opt)
{
switch (opt) {
case 'A':
case 's':
return "<PATH_PREFIX>, -";
case 'B':
return "[+]<FILE_NAME>";
case 'c':
return "<FILE_NAME>, -";
case 'l':
return "daemon, local0, local1, local2, local3, local4, local5, local6, local7";
case 'q':
return "nodev[0], errors[,nodev0], nodev[0]startup, never, onecheck, showtests";
case 'r':
return "ioctl[,N], ataioctl[,N], scsiioctl[,N], nvmeioctl[,N]";
case 'p':
case 'w':
return "<FILE_NAME>";
case 'i':
return "<INTEGER_SECONDS>";
#ifdef HAVE_POSIX_API
case 'u':
return "<USER>[:<GROUP>], -";
#elif defined(_WIN32)
case 'u':
return "restricted, unchanged";
#endif
#ifdef HAVE_LIBCAP_NG
case 'C':
return "mail, <no_argument>";
#endif
default:
return nullptr;
}
}
static void Usage()
{
PrintOut(LOG_INFO,"Usage: smartd [options]\n\n");
#ifdef SMARTMONTOOLS_ATTRIBUTELOG
PrintOut(LOG_INFO," -A PREFIX|-, --attributelog=PREFIX|-\n");
#else
PrintOut(LOG_INFO," -A PREFIX, --attributelog=PREFIX\n");
#endif
PrintOut(LOG_INFO," Log attribute information to {PREFIX}MODEL-SERIAL.TYPE.csv\n");
#ifdef SMARTMONTOOLS_ATTRIBUTELOG
PrintOut(LOG_INFO," [default is " SMARTMONTOOLS_ATTRIBUTELOG "MODEL-SERIAL.TYPE.csv]\n");
#endif
PrintOut(LOG_INFO,"\n");
PrintOut(LOG_INFO," -B [+]FILE, --drivedb=[+]FILE\n");
PrintOut(LOG_INFO," Read and replace [add] drive database from FILE\n");
PrintOut(LOG_INFO," [default is +%s", get_drivedb_path_add());
#ifdef SMARTMONTOOLS_DRIVEDBDIR
PrintOut(LOG_INFO,"\n");
PrintOut(LOG_INFO," and then %s", get_drivedb_path_default());
#endif
PrintOut(LOG_INFO,"]\n\n");
PrintOut(LOG_INFO," -c NAME|-, --configfile=NAME|-\n");
PrintOut(LOG_INFO," Read configuration file NAME or stdin\n");
PrintOut(LOG_INFO," [default is %s]\n\n", configfile);
#ifdef HAVE_LIBCAP_NG
PrintOut(LOG_INFO," -C, --capabilities[=mail]\n");
PrintOut(LOG_INFO," Drop unneeded Linux process capabilities.\n"
" Warning: Mail notification may not work when used.\n\n");
#endif
PrintOut(LOG_INFO," -d, --debug\n");
PrintOut(LOG_INFO," Start smartd in debug mode\n\n");
PrintOut(LOG_INFO," -D, --showdirectives\n");
PrintOut(LOG_INFO," Print the configuration file Directives and exit\n\n");
PrintOut(LOG_INFO," -h, --help, --usage\n");
PrintOut(LOG_INFO," Display this help and exit\n\n");
PrintOut(LOG_INFO," -i N, --interval=N\n");
PrintOut(LOG_INFO," Set interval between disk checks to N seconds, where N >= 10\n\n");
PrintOut(LOG_INFO," -l local[0-7], --logfacility=local[0-7]\n");
#ifndef _WIN32
PrintOut(LOG_INFO," Use syslog facility local0 - local7 or daemon [default]\n\n");
#else
PrintOut(LOG_INFO," Log to \"./smartd.log\", stdout, stderr [default is event log]\n\n");
#endif
#ifndef _WIN32
PrintOut(LOG_INFO," -n, --no-fork\n");
PrintOut(LOG_INFO," Do not fork into background\n");
#ifdef HAVE_LIBSYSTEMD
PrintOut(LOG_INFO," (systemd 'Type=notify' is assumed if $NOTIFY_SOCKET is set)\n");
#endif
PrintOut(LOG_INFO,"\n");
#endif
PrintOut(LOG_INFO," -p NAME, --pidfile=NAME\n");
PrintOut(LOG_INFO," Write PID file NAME\n\n");
PrintOut(LOG_INFO," -q WHEN, --quit=WHEN\n");
PrintOut(LOG_INFO," Quit on one of: %s\n\n", GetValidArgList('q'));
PrintOut(LOG_INFO," -r, --report=TYPE\n");
PrintOut(LOG_INFO," Report transactions for one of: %s\n\n", GetValidArgList('r'));
#ifdef SMARTMONTOOLS_SAVESTATES
PrintOut(LOG_INFO," -s PREFIX|-, --savestates=PREFIX|-\n");
#else
PrintOut(LOG_INFO," -s PREFIX, --savestates=PREFIX\n");
#endif
PrintOut(LOG_INFO," Save disk states to {PREFIX}MODEL-SERIAL.TYPE.state\n");
#ifdef SMARTMONTOOLS_SAVESTATES
PrintOut(LOG_INFO," [default is " SMARTMONTOOLS_SAVESTATES "MODEL-SERIAL.TYPE.state]\n");
#endif
PrintOut(LOG_INFO,"\n");
PrintOut(LOG_INFO," -w NAME, --warnexec=NAME\n");
PrintOut(LOG_INFO," Run executable NAME on warnings\n");
#ifndef _WIN32
PrintOut(LOG_INFO," [default is " SMARTMONTOOLS_SMARTDSCRIPTDIR "/smartd_warning.sh]\n\n");
#else
PrintOut(LOG_INFO," [default is %s/smartd_warning.cmd]\n\n", get_exe_dir().c_str());
#endif
#ifdef HAVE_POSIX_API
PrintOut(LOG_INFO," -u USER[:GROUP], --warn-as-user=USER[:GROUP]\n");
PrintOut(LOG_INFO," Run warning script as non-privileged USER\n\n");
#elif defined(_WIN32)
PrintOut(LOG_INFO," -u MODE, --warn-as-user=MODE\n");
PrintOut(LOG_INFO," Run warning script with modified access token: %s\n\n", GetValidArgList('u'));
#endif
#ifdef _WIN32
PrintOut(LOG_INFO," --service\n");
PrintOut(LOG_INFO," Running as windows service (see man page), install with:\n");
PrintOut(LOG_INFO," smartd install [options]\n");
PrintOut(LOG_INFO," Remove service with:\n");
PrintOut(LOG_INFO," smartd remove\n\n");
#endif
PrintOut(LOG_INFO," -V, --version, --license, --copyright\n");
PrintOut(LOG_INFO," Print License, Copyright, and version information\n");
}
static int CloseDevice(smart_device * device, const char * name)
{
if (!device->close()){
PrintOut(LOG_INFO,"Device: %s, %s, close() failed\n", name, device->get_errmsg());
return 1;
}
return 0;
}
static bool sanitize_dev_idinfo(std::string & s)
{
bool changed = false;
for (unsigned i = 0; i < s.size(); i++) {
char c = s[i];
STATIC_ASSERT(' ' == 0x20 && '~' == 0x07e);
if ((' ' <= c && c <= '~') && !(i == 0 && c == '~'))
continue;
s[i] = '?';
changed = true;
}
return changed;
}
static bool not_allowed_in_filename(char c)
{
return !( ('0' <= c && c <= '9')
|| ('A' <= c && c <= 'Z')
|| ('a' <= c && c <= 'z'));
}
static int read_ata_error_count(ata_device * device, const char * name,
firmwarebug_defs firmwarebugs, bool extended)
{
if (!extended) {
ata_smart_errorlog log;
if (ataReadErrorLog(device, &log, firmwarebugs)){
PrintOut(LOG_INFO,"Device: %s, Read Summary SMART Error Log failed\n",name);
return -1;
}
return (log.error_log_pointer ? log.ata_error_count : 0);
}
else {
ata_smart_exterrlog logx;
if (!ataReadExtErrorLog(device, &logx, 0, 1 , firmwarebugs)) {
PrintOut(LOG_INFO,"Device: %s, Read Extended Comprehensive SMART Error Log failed\n",name);
return -1;
}
return (logx.error_log_index || logx.reserved1 ? logx.device_error_count : 0);
}
}
static int SelfTestErrorCount(ata_device * device, const char * name,
firmwarebug_defs firmwarebugs)
{
struct ata_smart_selftestlog log;
if (ataReadSelfTestLog(device, &log, firmwarebugs)){
PrintOut(LOG_INFO,"Device: %s, Read SMART Self Test Log Failed\n",name);
return -1;
}
if (!log.mostrecenttest)
return 0;
int errcnt = 0, hours = 0;
for (int i = 20; i >= 0; i--) {
int j = (i + log.mostrecenttest) % 21;
const ata_smart_selftestlog_struct & entry = log.selftest_struct[j];
if (!nonempty(&entry, sizeof(entry)))
continue;
int status = entry.selfteststatus >> 4;
if (status == 0x0 && (entry.selftestnumber & 0x7f) == 0x02)
break;
if (0x3 <= status && status <= 0x8) {
errcnt++;
if (!hours)
hours = entry.timestamp;
}
}
return ((hours << 8) | errcnt);
}
#define SELFTEST_ERRORCOUNT(x) (x & 0xff)
#define SELFTEST_ERRORHOURS(x) ((x >> 8) & 0xffff)
static inline bool is_offl_coll_in_progress(unsigned char status)
{
return ((status & 0x7f) == 0x03);
}
static inline bool is_self_test_in_progress(unsigned char status)
{
return ((status >> 4) == 0xf);
}
static void log_offline_data_coll_status(const char * name, unsigned char status)
{
const char * msg;
switch (status & 0x7f) {
case 0x00: msg = "was never started"; break;
case 0x02: msg = "was completed without error"; break;
case 0x03: msg = "is in progress"; break;
case 0x04: msg = "was suspended by an interrupting command from host"; break;
case 0x05: msg = "was aborted by an interrupting command from host"; break;
case 0x06: msg = "was aborted by the device with a fatal error"; break;
default: msg = nullptr;
}
if (msg)
PrintOut(((status & 0x7f) == 0x06 ? LOG_CRIT : LOG_INFO),
"Device: %s, offline data collection %s%s\n", name, msg,
((status & 0x80) ? " (auto:on)" : ""));
else
PrintOut(LOG_INFO, "Device: %s, unknown offline data collection status 0x%02x\n",
name, status);
}
static void log_self_test_exec_status(const char * name, unsigned char status)
{
const char * msg;
switch (status >> 4) {
case 0x0: msg = "completed without error"; break;
case 0x1: msg = "was aborted by the host"; break;
case 0x2: msg = "was interrupted by the host with a reset"; break;
case 0x3: msg = "could not complete due to a fatal or unknown error"; break;
case 0x4: msg = "completed with error (unknown test element)"; break;
case 0x5: msg = "completed with error (electrical test element)"; break;
case 0x6: msg = "completed with error (servo/seek test element)"; break;
case 0x7: msg = "completed with error (read test element)"; break;
case 0x8: msg = "completed with error (handling damage?)"; break;
default: msg = nullptr;
}
if (msg)
PrintOut(((status >> 4) >= 0x4 ? LOG_CRIT : LOG_INFO),
"Device: %s, previous self-test %s\n", name, msg);
else if ((status >> 4) == 0xf)
PrintOut(LOG_INFO, "Device: %s, self-test in progress, %u0%% remaining\n",
name, status & 0x0f);
else
PrintOut(LOG_INFO, "Device: %s, unknown self-test status 0x%02x\n",
name, status);
}
static bool check_pending_id(const dev_config & cfg, const dev_state & state,
unsigned char id, const char * msg)
{
int i = ata_find_attr_index(id, state.smartval);
if (i < 0) {
PrintOut(LOG_INFO, "Device: %s, can't monitor %s count - no Attribute %d\n",
cfg.name.c_str(), msg, id);
return false;
}
uint64_t rawval = ata_get_attr_raw_value(state.smartval.vendor_attributes[i],
cfg.attribute_defs);
if (rawval >= (state.num_sectors ? state.num_sectors : 0xffffffffULL)) {
PrintOut(LOG_INFO, "Device: %s, ignoring %s count - bogus Attribute %d value %" PRIu64 " (0x%" PRIx64 ")\n",
cfg.name.c_str(), msg, id, rawval, rawval);
return false;
}
return true;
}
static void finish_device_scan(dev_config & cfg, dev_state & state)
{
if ((!cfg.emailaddress.empty() || !cfg.emailcmdline.empty()) && cfg.emailfreq == emailfreqs::unknown) {
if (cfg.state_file.empty())
cfg.emailfreq = emailfreqs::once;
else
cfg.emailfreq = emailfreqs::daily;
}
if (!cfg.test_regex.empty() && !state.scheduled_test_next_check)
state.scheduled_test_next_check = time(nullptr);
}
static void format_set_result_msg(std::string & msg, const char * name, bool ok,
int set_option = 0, bool has_value = false)
{
if (!msg.empty())
msg += ", ";
msg += name;
if (!ok)
msg += ":--";
else if (set_option < 0)
msg += ":off";
else if (has_value)
msg += strprintf(":%d", set_option-1);
else if (set_option > 0)
msg += ":on";
}
static bool is_duplicate_dev_idinfo(const dev_config & cfg, const dev_config_vector & prev_cfgs)
{
if (!cfg.id_is_unique)
return false;
for (const auto & prev_cfg : prev_cfgs) {
if (!prev_cfg.id_is_unique)
continue;
if (cfg.dev_idinfo != prev_cfg.dev_idinfo)
continue;
PrintOut(LOG_INFO, "Device: %s, same identity as %s, ignored\n",
cfg.dev_name.c_str(), prev_cfg.dev_name.c_str());
return true;
}
return false;
}
const bool fix_swapped_id = false;
static int ATADeviceScan(dev_config & cfg, dev_state & state, ata_device * atadev,
const dev_config_vector * prev_cfgs)
{
int supported=0;
struct ata_identify_device drive;
const char *name = cfg.name.c_str();
int retid;
if ((retid = ata_read_identity(atadev, &drive, fix_swapped_id))) {
if (retid<0)
PrintOut(LOG_INFO,"Device: %s, not ATA, no IDENTIFY DEVICE Structure\n",name);
else
PrintOut(LOG_INFO,"Device: %s, packet devices [this device %s] not SMART capable\n",
name, packetdevicetype(retid-1));
CloseDevice(atadev, name);
return 2;
}
char model[40+1], serial[20+1], firmware[8+1];
ata_format_id_string(model, drive.model, sizeof(model)-1);
ata_format_id_string(serial, drive.serial_no, sizeof(serial)-1);
ata_format_id_string(firmware, drive.fw_rev, sizeof(firmware)-1);
ata_size_info sizes;
ata_get_size_info(&drive, sizes);
state.num_sectors = sizes.sectors;
cfg.dev_rpm = ata_get_rotation_rate(&drive);
char wwn[64]; wwn[0] = 0;
unsigned oui = 0; uint64_t unique_id = 0;
int naa = ata_get_wwn(&drive, oui, unique_id);
if (naa >= 0)
snprintf(wwn, sizeof(wwn), "WWN:%x-%06x-%09" PRIx64 ", ", naa, oui, unique_id);
char cap[32];
cfg.dev_idinfo = strprintf("%s, S/N:%s, %sFW:%s, %s", model, serial, wwn, firmware,
format_capacity(cap, sizeof(cap), sizes.capacity, "."));
cfg.id_is_unique = true;
if (sanitize_dev_idinfo(cfg.dev_idinfo))
cfg.id_is_unique = false;
PrintOut(LOG_INFO, "Device: %s, %s\n", name, cfg.dev_idinfo.c_str());
if (prev_cfgs && is_duplicate_dev_idinfo(cfg, *prev_cfgs)) {
CloseDevice(atadev, name);
return 1;
}
if (cfg.ignorepresets)
PrintOut(LOG_INFO, "Device: %s, smartd database not searched (Directive: -P ignore).\n", name);
else {
std::string dbversion;
const drive_settings * dbentry = lookup_drive_apply_presets(
&drive, cfg.attribute_defs, cfg.firmwarebugs, dbversion);
if (!dbentry)
PrintOut(LOG_INFO, "Device: %s, not found in smartd database%s%s.\n", name,
(!dbversion.empty() ? " " : ""), (!dbversion.empty() ? dbversion.c_str() : ""));
else {
PrintOut(LOG_INFO, "Device: %s, found in smartd database%s%s%s%s\n",
name, (!dbversion.empty() ? " " : ""), (!dbversion.empty() ? dbversion.c_str() : ""),
(*dbentry->modelfamily ? ": " : "."), (*dbentry->modelfamily ? dbentry->modelfamily : ""));
if (*dbentry->warningmsg)
PrintOut(LOG_CRIT, "Device: %s, WARNING: %s\n", name, dbentry->warningmsg);
}
}
unsigned short word128 = drive.words088_255[128-88];
bool locked = ((word128 & 0x0007) == 0x0007);
if (locked)
PrintOut(LOG_INFO, "Device: %s, ATA Security is **LOCKED**\n", name);
if (!cfg.curr_pending_set)
cfg.curr_pending_id = get_unc_attr_id(false, cfg.attribute_defs, cfg.curr_pending_incr);
if (!cfg.offl_pending_set)
cfg.offl_pending_id = get_unc_attr_id(true, cfg.attribute_defs, cfg.offl_pending_incr);
if (cfg.showpresets) {
int savedebugmode=debugmode;
PrintOut(LOG_INFO, "Device %s: presets are:\n", name);
if (!debugmode)
debugmode=2;
show_presets(&drive);
debugmode=savedebugmode;
}
supported=ataSmartSupport(&drive);
if (supported!=1) {
if (supported==0)
PrintOut(LOG_INFO,"Device: %s, lacks SMART capability\n",name);
else
PrintOut(LOG_INFO,"Device: %s, ATA IDENTIFY DEVICE words 82-83 don't specify if SMART capable.\n",name);
if (cfg.permissive) {
PrintOut(LOG_INFO,"Device: %s, proceeding since '-T permissive' Directive given.\n",name);
}
else {
PrintOut(LOG_INFO,"Device: %s, to proceed anyway, use '-T permissive' Directive.\n",name);
CloseDevice(atadev, name);
return 2;
}
}
if (ataEnableSmart(atadev)) {
PrintOut(LOG_INFO,"Device: %s, could not enable SMART capability\n",name);
if (ataIsSmartEnabled(&drive) <= 0) {
if (!cfg.permissive) {
PrintOut(LOG_INFO, "Device: %s, to proceed anyway, use '-T permissive' Directive.\n", name);
CloseDevice(atadev, name);
return 2;
}
PrintOut(LOG_INFO, "Device: %s, proceeding since '-T permissive' Directive given.\n", name);
}
else {
PrintOut(LOG_INFO, "Device: %s, proceeding since SMART is already enabled\n", name);
}
}
if (cfg.autosave==1) {
if (ataDisableAutoSave(atadev))
PrintOut(LOG_INFO,"Device: %s, could not disable SMART Attribute Autosave.\n",name);
else
PrintOut(LOG_INFO,"Device: %s, disabled SMART Attribute Autosave.\n",name);
}
if (cfg.autosave==2) {
if (ataEnableAutoSave(atadev))
PrintOut(LOG_INFO,"Device: %s, could not enable SMART Attribute Autosave.\n",name);
else
PrintOut(LOG_INFO,"Device: %s, enabled SMART Attribute Autosave.\n",name);
}
if (cfg.smartcheck && ataSmartStatus2(atadev) == -1) {
PrintOut(LOG_INFO,"Device: %s, not capable of SMART Health Status check\n",name);
cfg.smartcheck = false;
}
bool smart_val_ok = false;
if ( cfg.autoofflinetest || cfg.selftest
|| cfg.errorlog || cfg.xerrorlog
|| cfg.offlinests || cfg.selfteststs
|| cfg.usagefailed || cfg.prefail || cfg.usage
|| cfg.tempdiff || cfg.tempinfo || cfg.tempcrit
|| cfg.curr_pending_id || cfg.offl_pending_id ) {
if (ataReadSmartValues(atadev, &state.smartval)) {
PrintOut(LOG_INFO, "Device: %s, Read SMART Values failed\n", name);
cfg.usagefailed = cfg.prefail = cfg.usage = false;
cfg.tempdiff = cfg.tempinfo = cfg.tempcrit = 0;
cfg.curr_pending_id = cfg.offl_pending_id = 0;
}
else {
smart_val_ok = true;
if (ataReadSmartThresholds(atadev, &state.smartthres)) {
PrintOut(LOG_INFO, "Device: %s, Read SMART Thresholds failed%s\n",
name, (cfg.usagefailed ? ", ignoring -f Directive" : ""));
cfg.usagefailed = false;
memset(&state.smartthres, 0, sizeof(state.smartthres));
}
}
if ( cfg.curr_pending_id
&& !check_pending_id(cfg, state, cfg.curr_pending_id,
"Current_Pending_Sector"))
cfg.curr_pending_id = 0;
if ( cfg.offl_pending_id
&& !check_pending_id(cfg, state, cfg.offl_pending_id,
"Offline_Uncorrectable"))
cfg.offl_pending_id = 0;
if ( (cfg.tempdiff || cfg.tempinfo || cfg.tempcrit)
&& !ata_return_temperature_value(&state.smartval, cfg.attribute_defs)) {
PrintOut(LOG_INFO, "Device: %s, can't monitor Temperature, ignoring -W %d,%d,%d\n",
name, cfg.tempdiff, cfg.tempinfo, cfg.tempcrit);
cfg.tempdiff = cfg.tempinfo = cfg.tempcrit = 0;
}
for (int id = 1; id <= 255; id++) {
if (cfg.monitor_attr_flags.is_set(id, MONITOR_RAW_PRINT)) {
char opt = (!cfg.monitor_attr_flags.is_set(id, MONITOR_RAW) ? 'r' : 'R');
const char * excl = (cfg.monitor_attr_flags.is_set(id,
(opt == 'r' ? MONITOR_AS_CRIT : MONITOR_RAW_AS_CRIT)) ? "!" : "");
int idx = ata_find_attr_index(id, state.smartval);
if (idx < 0)
PrintOut(LOG_INFO,"Device: %s, no Attribute %d, ignoring -%c %d%s\n", name, id, opt, id, excl);
else {
bool prefail = !!ATTRIBUTE_FLAGS_PREFAILURE(state.smartval.vendor_attributes[idx].flags);
if (!((prefail && cfg.prefail) || (!prefail && cfg.usage)))
PrintOut(LOG_INFO,"Device: %s, not monitoring %s Attributes, ignoring -%c %d%s\n", name,
(prefail ? "Prefailure" : "Usage"), opt, id, excl);
}
}
}
}
if (cfg.autoofflinetest) {
const char *what=(cfg.autoofflinetest==1)?"disable":"enable";
if (!smart_val_ok)
PrintOut(LOG_INFO,"Device: %s, could not %s SMART Automatic Offline Testing.\n",name, what);
else {
if (!isSupportAutomaticTimer(&state.smartval))
PrintOut(LOG_INFO,"Device: %s, SMART Automatic Offline Testing unsupported...\n",name);
if ((cfg.autoofflinetest==1)?ataDisableAutoOffline(atadev):ataEnableAutoOffline(atadev))
PrintOut(LOG_INFO,"Device: %s, %s SMART Automatic Offline Testing failed.\n", name, what);
else
PrintOut(LOG_INFO,"Device: %s, %sd SMART Automatic Offline Testing.\n", name, what);
}
}
ata_smart_log_directory smart_logdir, gp_logdir;
bool smart_logdir_ok = false, gp_logdir_ok = false;
if ( isGeneralPurposeLoggingCapable(&drive)
&& (cfg.errorlog || cfg.selftest)
&& !cfg.firmwarebugs.is_set(BUG_NOLOGDIR)) {
if (!ataReadLogDirectory(atadev, &smart_logdir, false))
smart_logdir_ok = true;
}
if (cfg.xerrorlog && !cfg.firmwarebugs.is_set(BUG_NOLOGDIR)) {
if (!ataReadLogDirectory(atadev, &gp_logdir, true))
gp_logdir_ok = true;
}
state.selflogcount = 0; state.selfloghour = 0;
if (cfg.selftest) {
int retval;
if (!( cfg.permissive
|| ( smart_logdir_ok && smart_logdir.entry[0x06-1].numsectors)
|| (!smart_logdir_ok && smart_val_ok && isSmartTestLogCapable(&state.smartval, &drive)))) {
PrintOut(LOG_INFO, "Device: %s, no SMART Self-test Log, ignoring -l selftest (override with -T permissive)\n", name);
cfg.selftest = false;
}
else if ((retval = SelfTestErrorCount(atadev, name, cfg.firmwarebugs)) < 0) {
PrintOut(LOG_INFO, "Device: %s, no SMART Self-test Log, ignoring -l selftest\n", name);
cfg.selftest = false;
}
else {
state.selflogcount=SELFTEST_ERRORCOUNT(retval);
state.selfloghour =SELFTEST_ERRORHOURS(retval);
}
}
state.ataerrorcount = 0;
if (cfg.errorlog) {
int errcnt1;
if (!( cfg.permissive
|| ( smart_logdir_ok && smart_logdir.entry[0x01-1].numsectors)
|| (!smart_logdir_ok && smart_val_ok && isSmartErrorLogCapable(&state.smartval, &drive)))) {
PrintOut(LOG_INFO, "Device: %s, no SMART Error Log, ignoring -l error (override with -T permissive)\n", name);
cfg.errorlog = false;
}
else if ((errcnt1 = read_ata_error_count(atadev, name, cfg.firmwarebugs, false)) < 0) {
PrintOut(LOG_INFO, "Device: %s, no SMART Error Log, ignoring -l error\n", name);
cfg.errorlog = false;
}
else
state.ataerrorcount = errcnt1;
}
if (cfg.xerrorlog) {
int errcnt2;
if (!( cfg.permissive || cfg.firmwarebugs.is_set(BUG_NOLOGDIR)
|| (gp_logdir_ok && gp_logdir.entry[0x03-1].numsectors) )) {
PrintOut(LOG_INFO, "Device: %s, no Extended Comprehensive SMART Error Log, ignoring -l xerror (override with -T permissive)\n",
name);
cfg.xerrorlog = false;
}
else if ((errcnt2 = read_ata_error_count(atadev, name, cfg.firmwarebugs, true)) < 0) {
PrintOut(LOG_INFO, "Device: %s, no Extended Comprehensive SMART Error Log, ignoring -l xerror\n", name);
cfg.xerrorlog = false;
}
else if (cfg.errorlog && state.ataerrorcount != errcnt2) {
PrintOut(LOG_INFO, "Device: %s, SMART Error Logs report different error counts: %d != %d\n",
name, state.ataerrorcount, errcnt2);
if (errcnt2 > state.ataerrorcount)
state.ataerrorcount = errcnt2;
}
else
state.ataerrorcount = errcnt2;
}
if (cfg.offlinests || cfg.selfteststs) {
if (!(cfg.permissive || (smart_val_ok && state.smartval.offline_data_collection_capability))) {
if (cfg.offlinests)
PrintOut(LOG_INFO, "Device: %s, no SMART Offline Data Collection capability, ignoring -l offlinests (override with -T permissive)\n", name);
if (cfg.selfteststs)
PrintOut(LOG_INFO, "Device: %s, no SMART Self-test capability, ignoring -l selfteststs (override with -T permissive)\n", name);
cfg.offlinests = cfg.selfteststs = false;
}
}
if (cfg.powermode) {
int powermode = ataCheckPowerMode(atadev);
if (-1 == powermode) {
PrintOut(LOG_CRIT, "Device: %s, no ATA CHECK POWER STATUS support, ignoring -n Directive\n", name);
cfg.powermode=0;
}
else if (powermode!=0x00 && powermode!=0x01
&& powermode!=0x40 && powermode!=0x41
&& powermode!=0x80 && powermode!=0x81 && powermode!=0x82 && powermode!=0x83
&& powermode!=0xff) {
PrintOut(LOG_CRIT, "Device: %s, CHECK POWER STATUS returned %d, not ATA compliant, ignoring -n Directive\n",
name, powermode);
cfg.powermode=0;
}
}
std::string msg;
if (cfg.set_aam)
format_set_result_msg(msg, "AAM", (cfg.set_aam > 0 ?
ata_set_features(atadev, ATA_ENABLE_AAM, cfg.set_aam-1) :
ata_set_features(atadev, ATA_DISABLE_AAM)), cfg.set_aam, true);
if (cfg.set_apm)
format_set_result_msg(msg, "APM", (cfg.set_apm > 0 ?
ata_set_features(atadev, ATA_ENABLE_APM, cfg.set_apm-1) :
ata_set_features(atadev, ATA_DISABLE_APM)), cfg.set_apm, true);
if (cfg.set_lookahead)
format_set_result_msg(msg, "Rd-ahead", ata_set_features(atadev,
(cfg.set_lookahead > 0 ? ATA_ENABLE_READ_LOOK_AHEAD : ATA_DISABLE_READ_LOOK_AHEAD)),
cfg.set_lookahead);
if (cfg.set_wcache)
format_set_result_msg(msg, "Wr-cache", ata_set_features(atadev,
(cfg.set_wcache > 0? ATA_ENABLE_WRITE_CACHE : ATA_DISABLE_WRITE_CACHE)), cfg.set_wcache);
if (cfg.set_dsn)
format_set_result_msg(msg, "DSN", ata_set_features(atadev,
ATA_ENABLE_DISABLE_DSN, (cfg.set_dsn > 0 ? 0x1 : 0x2)));
if (cfg.set_security_freeze)
format_set_result_msg(msg, "Security freeze",
ata_nodata_command(atadev, ATA_SECURITY_FREEZE_LOCK));
if (cfg.set_standby)
format_set_result_msg(msg, "Standby",
ata_nodata_command(atadev, ATA_IDLE, cfg.set_standby-1), cfg.set_standby, true);
if (!msg.empty())
PrintOut(LOG_INFO, "Device: %s, ATA settings applied: %s\n", name, msg.c_str());
if (cfg.sct_erc_set) {
if (!isSCTErrorRecoveryControlCapable(&drive))
PrintOut(LOG_INFO, "Device: %s, no SCT Error Recovery Control support, ignoring -l scterc\n",
name);
else if (locked)
PrintOut(LOG_INFO, "Device: %s, no SCT support if ATA Security is LOCKED, ignoring -l scterc\n",
name);
else if ( ataSetSCTErrorRecoveryControltime(atadev, 1, cfg.sct_erc_readtime, false, false )
|| ataSetSCTErrorRecoveryControltime(atadev, 2, cfg.sct_erc_writetime, false, false))
PrintOut(LOG_INFO, "Device: %s, set of SCT Error Recovery Control failed\n", name);
else
PrintOut(LOG_INFO, "Device: %s, SCT Error Recovery Control set to: Read: %u, Write: %u\n",
name, cfg.sct_erc_readtime, cfg.sct_erc_writetime);
}
if (!( cfg.smartcheck || cfg.selftest
|| cfg.errorlog || cfg.xerrorlog
|| cfg.offlinests || cfg.selfteststs
|| cfg.usagefailed || cfg.prefail || cfg.usage
|| cfg.tempdiff || cfg.tempinfo || cfg.tempcrit)) {
CloseDevice(atadev, name);
return 3;
}
PrintOut(LOG_INFO,"Device: %s, is SMART capable. Adding to \"monitor\" list.\n",name);
CloseDevice(atadev, name);
if (!state_path_prefix.empty() || !attrlog_path_prefix.empty()) {
std::replace_if(model, model+strlen(model), not_allowed_in_filename, '_');
std::replace_if(serial, serial+strlen(serial), not_allowed_in_filename, '_');
if (!state_path_prefix.empty()) {
cfg.state_file = strprintf("%s%s-%s.ata.state", state_path_prefix.c_str(), model, serial);
if (read_dev_state(cfg.state_file.c_str(), state)) {
PrintOut(LOG_INFO, "Device: %s, state read from %s\n", name, cfg.state_file.c_str());
state.update_temp_state();
}
}
if (!attrlog_path_prefix.empty())
cfg.attrlog_file = strprintf("%s%s-%s.ata.csv", attrlog_path_prefix.c_str(), model, serial);
}
finish_device_scan(cfg, state);
return 0;
}
static int SCSIDeviceScan(dev_config & cfg, dev_state & state, scsi_device * scsidev,
const dev_config_vector * prev_cfgs)
{
int err, req_len, avail_len, version, len;
const char *device = cfg.name.c_str();
struct scsi_iec_mode_page iec;
uint8_t tBuf[64];
uint8_t inqBuf[96];
uint8_t vpdBuf[252];
char lu_id[64], serial[256], vendor[40], model[40];
memset(inqBuf, 0, 96);
req_len = 36;
if ((err = scsiStdInquiry(scsidev, inqBuf, req_len))) {
req_len = 64;
int err64;
if ((err64 = scsiStdInquiry(scsidev, inqBuf, req_len))) {
PrintOut(LOG_INFO, "Device: %s, Both 36 and 64 byte INQUIRY failed; "
"skip device [err=%d, %d]\n", device, err, err64);
return 2;
}
}
version = (inqBuf[2] & 0x7f);
avail_len = inqBuf[4] + 5;
len = (avail_len < req_len) ? avail_len : req_len;
if (len < 36) {
PrintOut(LOG_INFO, "Device: %s, INQUIRY response less than 36 bytes; "
"skip device\n", device);
return 2;
}
int pdt = inqBuf[0] & 0x1f;
switch (pdt) {
case SCSI_PT_DIRECT_ACCESS:
case SCSI_PT_WO:
case SCSI_PT_CDROM:
case SCSI_PT_OPTICAL:
case SCSI_PT_RBC:
case SCSI_PT_HOST_MANAGED:
break;
default:
PrintOut(LOG_INFO, "Device: %s, not a disk like device [PDT=0x%x], "
"skip\n", device, pdt);
return 2;
}
if (supported_vpd_pages_p) {
delete supported_vpd_pages_p;
supported_vpd_pages_p = nullptr;
}
supported_vpd_pages_p = new supported_vpd_pages(scsidev);
lu_id[0] = '\0';
if (version >= 0x3) {
if (0 == scsiInquiryVpd(scsidev, SCSI_VPD_DEVICE_IDENTIFICATION,
vpdBuf, sizeof(vpdBuf))) {
len = vpdBuf[3];
scsi_decode_lu_dev_id(vpdBuf + 4, len, lu_id, sizeof(lu_id), nullptr);
}
}
serial[0] = '\0';
if (0 == scsiInquiryVpd(scsidev, SCSI_VPD_UNIT_SERIAL_NUMBER,
vpdBuf, sizeof(vpdBuf))) {
len = vpdBuf[3];
vpdBuf[4 + len] = '\0';
scsi_format_id_string(serial, &vpdBuf[4], len);
}
char si_str[64];
struct scsi_readcap_resp srr;
uint64_t capacity = scsiGetSize(scsidev, scsidev->use_rcap16(), &srr);
if (capacity)
format_capacity(si_str, sizeof(si_str), capacity, ".");
else
si_str[0] = '\0';
cfg.dev_idinfo = strprintf("[%.8s %.16s %.4s]%s%s%s%s%s%s",
(char *)&inqBuf[8], (char *)&inqBuf[16], (char *)&inqBuf[32],
(lu_id[0] ? ", lu id: " : ""), (lu_id[0] ? lu_id : ""),
(serial[0] ? ", S/N: " : ""), (serial[0] ? serial : ""),
(si_str[0] ? ", " : ""), (si_str[0] ? si_str : ""));
cfg.id_is_unique = (lu_id[0] || serial[0]);
if (sanitize_dev_idinfo(cfg.dev_idinfo))
cfg.id_is_unique = false;
scsi_format_id_string(vendor, &inqBuf[8], 8);
scsi_format_id_string(model, &inqBuf[16], 16);
PrintOut(LOG_INFO, "Device: %s, %s\n", device, cfg.dev_idinfo.c_str());
if (prev_cfgs && is_duplicate_dev_idinfo(cfg, *prev_cfgs)) {
CloseDevice(scsidev, device);
return 1;
}
if ((err = scsiTestUnitReady(scsidev))) {
if (SIMPLE_ERR_NOT_READY == err)
PrintOut(LOG_INFO, "Device: %s, NOT READY (e.g. spun down); skip device\n", device);
else if (SIMPLE_ERR_NO_MEDIUM == err)
PrintOut(LOG_INFO, "Device: %s, NO MEDIUM present; skip device\n", device);
else if (SIMPLE_ERR_BECOMING_READY == err)
PrintOut(LOG_INFO, "Device: %s, BECOMING (but not yet) READY; skip device\n", device);
else
PrintOut(LOG_CRIT, "Device: %s, failed Test Unit Ready [err=%d]\n", device, err);
CloseDevice(scsidev, device);
return 2;
}
if (!(err = scsiFetchIECmpage(scsidev, &iec, state.modese_len)))
state.modese_len = iec.modese_len;
else if (SIMPLE_ERR_BAD_FIELD == err)
;
else {
PrintOut(LOG_INFO,
"Device: %s, Bad IEC (SMART) mode page, err=%d, skip device\n",
device, err);
CloseDevice(scsidev, device);
return 3;
}
if (!scsi_IsExceptionControlEnabled(&iec)) {
PrintOut(LOG_INFO, "Device: %s, IE (SMART) not enabled, skip device\n"
"Try 'smartctl -s on %s' to turn on SMART features\n",
device, device);
CloseDevice(scsidev, device);
return 3;
}
if (0 == scsiLogSense(scsidev, SUPPORTED_LPAGES, 0, tBuf, sizeof(tBuf), 0) ||
0 == scsiLogSense(scsidev, SUPPORTED_LPAGES, 0, tBuf, sizeof(tBuf), 68))
{
for (int k = 4; k < tBuf[3] + LOGPAGEHDRSIZE; ++k) {
switch (tBuf[k]) {
case TEMPERATURE_LPAGE:
state.TempPageSupported = 1;
break;
case IE_LPAGE:
state.SmartPageSupported = 1;
break;
case READ_ERROR_COUNTER_LPAGE:
state.ReadECounterPageSupported = 1;
break;
case WRITE_ERROR_COUNTER_LPAGE:
state.WriteECounterPageSupported = 1;
break;
case VERIFY_ERROR_COUNTER_LPAGE:
state.VerifyECounterPageSupported = 1;
break;
case NON_MEDIUM_ERROR_LPAGE:
state.NonMediumErrorPageSupported = 1;
break;
default:
break;
}
}
}
{
uint8_t asc = 0;
uint8_t ascq = 0;
uint8_t currenttemp = 0;
uint8_t triptemp = 0;
if (scsiCheckIE(scsidev, state.SmartPageSupported, state.TempPageSupported,
&asc, &ascq, ¤ttemp, &triptemp)) {
PrintOut(LOG_INFO, "Device: %s, unexpectedly failed to read SMART values\n", device);
state.SuppressReport = 1;
}
if ( (state.SuppressReport || !currenttemp)
&& (cfg.tempdiff || cfg.tempinfo || cfg.tempcrit)) {
PrintOut(LOG_INFO, "Device: %s, can't monitor Temperature, ignoring -W %d,%d,%d\n",
device, cfg.tempdiff, cfg.tempinfo, cfg.tempcrit);
cfg.tempdiff = cfg.tempinfo = cfg.tempcrit = 0;
}
}
if (cfg.selftest){
int retval = scsiCountFailedSelfTests(scsidev, 0);
if (retval<0) {
PrintOut(LOG_INFO, "Device: %s, does not support SMART Self-Test Log.\n", device);
cfg.selftest = false;
state.selflogcount = 0;
state.selfloghour = 0;
}
else {
state.selflogcount=SELFTEST_ERRORCOUNT(retval);
state.selfloghour =SELFTEST_ERRORHOURS(retval);
}
}
if (cfg.autosave==1){
if (scsiSetControlGLTSD(scsidev, 1, state.modese_len))
PrintOut(LOG_INFO,"Device: %s, could not disable autosave (set GLTSD bit).\n",device);
else
PrintOut(LOG_INFO,"Device: %s, disabled autosave (set GLTSD bit).\n",device);
}
if (cfg.autosave==2){
if (scsiSetControlGLTSD(scsidev, 0, state.modese_len))
PrintOut(LOG_INFO,"Device: %s, could not enable autosave (clear GLTSD bit).\n",device);
else
PrintOut(LOG_INFO,"Device: %s, enabled autosave (cleared GLTSD bit).\n",device);
}
PrintOut(LOG_INFO, "Device: %s, is SMART capable. Adding to \"monitor\" list.\n", device);
cfg.offlinests_ns = cfg.selfteststs_ns = false;
CloseDevice(scsidev, device);
if (!state_path_prefix.empty() || !attrlog_path_prefix.empty()) {
std::replace_if(model, model+strlen(model), not_allowed_in_filename, '_');
std::replace_if(serial, serial+strlen(serial), not_allowed_in_filename, '_');
if (!state_path_prefix.empty()) {
cfg.state_file = strprintf("%s%s-%s-%s.scsi.state", state_path_prefix.c_str(), vendor, model, serial);
if (read_dev_state(cfg.state_file.c_str(), state)) {
PrintOut(LOG_INFO, "Device: %s, state read from %s\n", device, cfg.state_file.c_str());
state.update_temp_state();
}
}
if (!attrlog_path_prefix.empty())
cfg.attrlog_file = strprintf("%s%s-%s-%s.scsi.csv", attrlog_path_prefix.c_str(), vendor, model, serial);
}
finish_device_scan(cfg, state);
return 0;
}
static uint64_t le128_to_uint64(const unsigned char (& val)[16])
{
for (int i = 8; i < 16; i++) {
if (val[i])
return ~(uint64_t)0;
}
uint64_t lo = val[7];
for (int i = 7-1; i >= 0; i--) {
lo <<= 8; lo += val[i];
}
return lo;
}
static int nvme_get_max_temp_kelvin(const nvme_smart_log & smart_log)
{
int k = (smart_log.temperature[1] << 8) | smart_log.temperature[0];
for (auto s : smart_log.temp_sensor) {
if (s > k)
k = s;
}
return k;
}
static bool check_nvme_error_log(const dev_config & cfg, dev_state & state, nvme_device * nvmedev,
uint64_t newcnt = 0)
{
unsigned want_entries = 64;
if (want_entries > cfg.nvme_err_log_max_entries)
want_entries = cfg.nvme_err_log_max_entries;
raw_buffer error_log_buf(want_entries * sizeof(nvme_error_log_page));
nvme_error_log_page * error_log =
reinterpret_cast<nvme_error_log_page *>(error_log_buf.data());
unsigned read_entries = nvme_read_error_log(nvmedev, error_log, want_entries, false );
if (!read_entries) {
PrintOut(LOG_INFO, "Device: %s, Read %u entries from Error Information Log failed\n",
cfg.name.c_str(), want_entries);
return false;
}
if (!newcnt)
return true;
uint64_t oldcnt = state.nvme_err_log_entries, mincnt = newcnt;
int err = 0, ign = 0;
for (unsigned i = 0; i < read_entries; i++) {
const nvme_error_log_page & e = error_log[i];
if (!e.error_count)
continue;
if (e.error_count <= oldcnt)
break;
if (e.error_count < mincnt)
mincnt = e.error_count;
if (e.error_count > newcnt)
newcnt = e.error_count;
uint16_t status = e.status_field >> 1;
if (!nvme_status_is_error(status) || nvme_status_to_errno(status) == EINVAL) {
ign++;
continue;
}
if (++err > 8)
continue;
char buf[64];
PrintOut(LOG_INFO, "Device: %s, NVMe error [%u], count %" PRIu64 ", status 0x%04x: %s\n",
cfg.name.c_str(), i, e.error_count, e.status_field,
nvme_status_to_info_str(buf, e.status_field >> 1));
}
std::string msg = strprintf("Device: %s, NVMe error count increased from %" PRIu64 " to %" PRIu64
" (%d new, %d ignored, %" PRIu64 " unknown)",
cfg.name.c_str(), oldcnt, newcnt, err, ign,
(mincnt > oldcnt + 1 ? mincnt - oldcnt - 1 : 0));
if (!err) {
PrintOut(LOG_INFO, "%s\n", msg.c_str());
}
else {
PrintOut(LOG_CRIT, "%s\n", msg.c_str());
MailWarning(cfg, state, 4, "%s", msg.c_str());
}
state.nvme_err_log_entries = newcnt;
state.must_write = true;
return true;
}
static int NVMeDeviceScan(dev_config & cfg, dev_state & state, nvme_device * nvmedev,
const dev_config_vector * prev_cfgs)
{
const char *name = cfg.name.c_str();
nvme_id_ctrl id_ctrl;
if (!nvme_read_id_ctrl(nvmedev, id_ctrl)) {
PrintOut(LOG_INFO, "Device: %s, NVMe Identify Controller failed\n", name);
CloseDevice(nvmedev, name);
return 2;
}
char model[40+1], serial[20+1], firmware[8+1];
format_char_array(model, id_ctrl.mn);
format_char_array(serial, id_ctrl.sn);
format_char_array(firmware, id_ctrl.fr);
char nsstr[32] = "", capstr[32] = "";
unsigned nsid = nvmedev->get_nsid();
if (nsid != 0xffffffff)
snprintf(nsstr, sizeof(nsstr), ", NSID:%u", nsid);
uint64_t capacity = le128_to_uint64(id_ctrl.tnvmcap);
if (capacity)
format_capacity(capstr, sizeof(capstr), capacity, ".");
cfg.dev_idinfo = strprintf("%s, S/N:%s, FW:%s%s%s%s", model, serial, firmware,
nsstr, (capstr[0] ? ", " : ""), capstr);
cfg.id_is_unique = true;
if (sanitize_dev_idinfo(cfg.dev_idinfo))
cfg.id_is_unique = false;
PrintOut(LOG_INFO, "Device: %s, %s\n", name, cfg.dev_idinfo.c_str());
if (prev_cfgs && is_duplicate_dev_idinfo(cfg, *prev_cfgs)) {
CloseDevice(nvmedev, name);
return 1;
}
nvme_smart_log smart_log;
if (!nvme_read_smart_log(nvmedev, smart_log)) {
PrintOut(LOG_INFO, "Device: %s, failed to read NVMe SMART/Health Information\n", name);
CloseDevice(nvmedev, name);
return 2;
}
if (cfg.tempdiff || cfg.tempinfo || cfg.tempcrit) {
if (!nvme_get_max_temp_kelvin(smart_log)) {
PrintOut(LOG_INFO, "Device: %s, no Temperature sensors, ignoring -W %d,%d,%d\n",
name, cfg.tempdiff, cfg.tempinfo, cfg.tempcrit);
cfg.tempdiff = cfg.tempinfo = cfg.tempcrit = 0;
}
}
cfg.nvme_err_log_max_entries = id_ctrl.elpe + 1;
if (cfg.errorlog || cfg.xerrorlog) {
if (!check_nvme_error_log(cfg, state, nvmedev)) {
PrintOut(LOG_INFO, "Device: %s, Error Information unavailable, ignoring -l [x]error\n", name);
cfg.errorlog = cfg.xerrorlog = false;
}
else
state.nvme_err_log_entries = le128_to_uint64(smart_log.num_err_log_entries);
}
if (!( cfg.smartcheck || cfg.errorlog || cfg.xerrorlog
|| cfg.tempdiff || cfg.tempinfo || cfg.tempcrit )) {
CloseDevice(nvmedev, name);
return 3;
}
PrintOut(LOG_INFO,"Device: %s, is SMART capable. Adding to \"monitor\" list.\n", name);
cfg.offlinests_ns = cfg.selfteststs_ns = false;
CloseDevice(nvmedev, name);
if (!state_path_prefix.empty()) {
std::replace_if(model, model+strlen(model), not_allowed_in_filename, '_');
std::replace_if(serial, serial+strlen(serial), not_allowed_in_filename, '_');
nsstr[0] = 0;
if (nsid != 0xffffffff)
snprintf(nsstr, sizeof(nsstr), "-n%u", nsid);
cfg.state_file = strprintf("%s%s-%s%s.nvme.state", state_path_prefix.c_str(), model, serial, nsstr);
if (read_dev_state(cfg.state_file.c_str(), state))
PrintOut(LOG_INFO, "Device: %s, state read from %s\n", name, cfg.state_file.c_str());
}
finish_device_scan(cfg, state);
return 0;
}
static bool open_device(const dev_config & cfg, dev_state & state, smart_device * device,
const char * type)
{
const char * name = cfg.name.c_str();
if (cfg.emailtest)
MailWarning(cfg, state, 0, "TEST EMAIL from smartd for device: %s", name);
if (device->is_ata() && cfg.powermode && !state.powermodefail && !state.removed) {
if (device->is_powered_down())
{
if (!cfg.powerskipmax || state.powerskipcnt<cfg.powerskipmax) {
if ((!state.powerskipcnt || state.lastpowermodeskipped != -1) && !cfg.powerquiet) {
PrintOut(LOG_INFO, "Device: %s, is in %s mode, suspending checks\n", name, "STANDBY (OS)");
state.lastpowermodeskipped = -1;
}
state.powerskipcnt++;
return false;
}
}
}
if (!device->open()) {
if (!cfg.removable) {
PrintOut(LOG_INFO, "Device: %s, open() of %s device failed: %s\n", name, type, device->get_errmsg());
MailWarning(cfg, state, 9, "Device: %s, unable to open %s device", name, type);
}
else if (!state.removed) {
PrintOut(LOG_INFO, "Device: %s, removed %s device: %s\n", name, type, device->get_errmsg());
state.removed = true;
}
else if (debugmode)
PrintOut(LOG_INFO, "Device: %s, %s device still removed: %s\n", name, type, device->get_errmsg());
return false;
}
if (debugmode)
PrintOut(LOG_INFO,"Device: %s, opened %s device\n", name, type);
if (!cfg.removable)
reset_warning_mail(cfg, state, 9, "open of %s device worked again", type);
else if (state.removed) {
PrintOut(LOG_INFO, "Device: %s, reconnected %s device\n", name, type);
state.removed = false;
}
return true;
}
static void CheckSelfTestLogs(const dev_config & cfg, dev_state & state, int newi)
{
const char * name = cfg.name.c_str();
if (newi<0)
MailWarning(cfg, state, 8, "Device: %s, Read SMART Self-Test Log Failed", name);
else {
reset_warning_mail(cfg, state, 8, "Read SMART Self-Test Log worked again");
int oldc=state.selflogcount;
int newc=SELFTEST_ERRORCOUNT(newi);
int oldh=state.selfloghour;
int newh=SELFTEST_ERRORHOURS(newi);
if (oldc<newc) {
PrintOut(LOG_CRIT, "Device: %s, Self-Test Log error count increased from %d to %d\n",
name, oldc, newc);
MailWarning(cfg, state, 3, "Device: %s, Self-Test Log error count increased from %d to %d",
name, oldc, newc);
state.must_write = true;
}
else if (newc > 0 && oldh != newh) {
PrintOut(LOG_CRIT, "Device: %s, new Self-Test Log error at hour timestamp %d\n",
name, newh);
MailWarning(cfg, state, 3, "Device: %s, new Self-Test Log error at hour timestamp %d",
name, newh);
state.must_write = true;
}
if (oldc > newc) {
PrintOut(LOG_INFO, "Device: %s, Self-Test Log error count decreased from %d to %d\n",
name, oldc, newc);
if (newc == 0)
reset_warning_mail(cfg, state, 3, "Self-Test Log does no longer report errors");
}
state.selflogcount= newc;
state.selfloghour = newh;
}
return;
}
static const char test_type_chars[] = "LncrSCO";
static const unsigned num_test_types = sizeof(test_type_chars)-1;
static char next_scheduled_test(const dev_config & cfg, dev_state & state, bool scsi, time_t usetime = 0)
{
if (cfg.test_regex.empty())
return 0;
if ( state.not_cap_long && state.not_cap_short &&
(scsi || (state.not_cap_conveyance && state.not_cap_offline)))
return 0;
if (!usetime)
FixGlibcTimeZoneBug();
time_t now = (!usetime ? time(nullptr) : usetime);
if (now < state.scheduled_test_next_check) {
if (state.scheduled_test_next_check <= now + 3600)
return 0;
state.scheduled_test_next_check = now;
}
else if (state.scheduled_test_next_check + (3600L*24*90) < now) {
state.scheduled_test_next_check = now - (3600L*24*90);
}
const unsigned max_offsets = 1 + num_test_types;
unsigned offsets[max_offsets] = {0, }, limits[max_offsets] = {0, };
unsigned num_offsets = 1;
for (const char * p = cfg.test_regex.get_pattern(); num_offsets < max_offsets; ) {
const char * q = strchr(p, ':');
if (!q)
break;
p = q + 1;
unsigned offset = 0, limit = 0; int n1 = -1, n2 = -1, n3 = -1;
sscanf(p, "%u%n-%n%u%n", &offset, &n1, &n2, &limit, &n3);
if (!(n1 == 3 && (n2 < 0 || (n3 == 3+1+3 && limit > 0))))
continue;
offsets[num_offsets] = offset; limits[num_offsets] = limit;
num_offsets++;
p += (n3 > 0 ? n3 : n1);
}
char testtype = 0;
time_t testtime = 0; int testhour = 0;
int maxtest = num_test_types-1;
for (time_t t = state.scheduled_test_next_check; ; ) {
for (unsigned i = 0; i < num_offsets; i++) {
unsigned offset = offsets[i], limit = limits[i];
unsigned delay = cfg.test_offset_factor * offset;
if (0 < limit && limit < delay)
delay %= limit + 1;
struct tm tmbuf, * tms = time_to_tm_local(&tmbuf, t - (delay * 3600));
int weekday = (tms->tm_wday ? tms->tm_wday : 7);
for (int j = 0; j <= maxtest; j++) {
switch (test_type_chars[j]) {
case 'L': if (state.not_cap_long) continue; break;
case 'S': if (state.not_cap_short) continue; break;
case 'C': if (scsi || state.not_cap_conveyance) continue; break;
case 'O': if (scsi || state.not_cap_offline) continue; break;
case 'c': case 'n':
case 'r': if (scsi || state.not_cap_selective) continue; break;
default: continue;
}
char pattern[64];
snprintf(pattern, sizeof(pattern), "%c/%02d/%02d/%1d/%02d",
test_type_chars[j], tms->tm_mon+1, tms->tm_mday, weekday, tms->tm_hour);
if (i > 0) {
const unsigned len = sizeof("S/01/01/1/01") - 1;
snprintf(pattern + len, sizeof(pattern) - len, ":%03u", offset);
if (limit > 0)
snprintf(pattern + len + 4, sizeof(pattern) - len - 4, "-%03u", limit);
}
if (cfg.test_regex.full_match(pattern)) {
testtype = pattern[0];
testtime = t; testhour = tms->tm_hour;
maxtest = j-1;
break;
}
}
}
if (maxtest < 0)
break;
if (t >= now)
break;
if ((t += 3600) > now)
t = now;
}
struct tm tmbuf, * tmnow = time_to_tm_local(&tmbuf, now);
state.scheduled_test_next_check = now + (3600 - tmnow->tm_min*60 - tmnow->tm_sec);
if (testtype) {
state.must_write = true;
if (!usetime && !(testhour == tmnow->tm_hour && testtime + 3600 > now)) {
char datebuf[DATEANDEPOCHLEN]; dateandtimezoneepoch(datebuf, testtime);
PrintOut(LOG_INFO, "Device: %s, old test of type %c not run at %s, starting now.\n",
cfg.name.c_str(), testtype, datebuf);
}
}
return testtype;
}
static void PrintTestSchedule(const dev_config_vector & configs, dev_state_vector & states, const smart_device_list & devices)
{
unsigned numdev = configs.size();
if (!numdev)
return;
std::vector<int> testcnts(numdev * num_test_types, 0);
PrintOut(LOG_INFO, "\nNext scheduled self tests (at most 5 of each type per device):\n");
time_t now = time(nullptr);
char datenow[DATEANDEPOCHLEN], date[DATEANDEPOCHLEN];
dateandtimezoneepoch(datenow, now);
long seconds;
for (seconds=checktime; seconds<3600L*24*90; seconds+=checktime) {
time_t testtime = now + seconds;
for (unsigned i = 0; i < numdev; i++) {
const dev_config & cfg = configs.at(i);
dev_state & state = states.at(i);
const char * p;
char testtype = next_scheduled_test(cfg, state, devices.at(i)->is_scsi(), testtime);
if (testtype && (p = strchr(test_type_chars, testtype))) {
unsigned t = (p - test_type_chars);
if (++testcnts[i*num_test_types + t] <= 5) {
dateandtimezoneepoch(date, testtime);
PrintOut(LOG_INFO, "Device: %s, will do test %d of type %c at %s\n", cfg.name.c_str(),
testcnts[i*num_test_types + t], testtype, date);
}
}
}
}
dateandtimezoneepoch(date, now+seconds);
PrintOut(LOG_INFO, "\nTotals [%s - %s]:\n", datenow, date);
for (unsigned i = 0; i < numdev; i++) {
const dev_config & cfg = configs.at(i);
bool scsi = devices.at(i)->is_scsi();
for (unsigned t = 0; t < num_test_types; t++) {
int cnt = testcnts[i*num_test_types + t];
if (cnt == 0 && !strchr((scsi ? "LS" : "LSCO"), test_type_chars[t]))
continue;
PrintOut(LOG_INFO, "Device: %s, will do %3d test%s of type %c\n", cfg.name.c_str(),
cnt, (cnt==1?"":"s"), test_type_chars[t]);
}
}
}
static int DoSCSISelfTest(const dev_config & cfg, dev_state & state, scsi_device * device, char testtype)
{
int retval = 0;
const char *testname = nullptr;
const char *name = cfg.name.c_str();
int inProgress;
if (scsiSelfTestInProgress(device, &inProgress)) {
PrintOut(LOG_CRIT, "Device: %s, does not support Self-Tests\n", name);
state.not_cap_short = state.not_cap_long = true;
return 1;
}
if (1 == inProgress) {
PrintOut(LOG_INFO, "Device: %s, skip since Self-Test already in "
"progress.\n", name);
return 1;
}
switch (testtype) {
case 'S':
testname = "Short Self";
retval = scsiSmartShortSelfTest(device);
break;
case 'L':
testname = "Long Self";
retval = scsiSmartExtendSelfTest(device);
break;
}
if (!testname) {
PrintOut(LOG_CRIT, "Device: %s, not capable of %c Self-Test\n", name,
testtype);
return 1;
}
if (retval) {
if ((SIMPLE_ERR_BAD_OPCODE == retval) ||
(SIMPLE_ERR_BAD_FIELD == retval)) {
PrintOut(LOG_CRIT, "Device: %s, not capable of %s-Test\n", name,
testname);
if ('L'==testtype)
state.not_cap_long = true;
else
state.not_cap_short = true;
return 1;
}
PrintOut(LOG_CRIT, "Device: %s, execute %s-Test failed (err: %d)\n", name,
testname, retval);
return 1;
}
PrintOut(LOG_INFO, "Device: %s, starting scheduled %s-Test.\n", name, testname);
return 0;
}
static int DoATASelfTest(const dev_config & cfg, dev_state & state, ata_device * device, char testtype)
{
const char *name = cfg.name.c_str();
struct ata_smart_values data;
if (ataReadSmartValues(device, &data) || !(data.offline_data_collection_capability)) {
PrintOut(LOG_CRIT, "Device: %s, not capable of Offline or Self-Testing.\n", name);
return 1;
}
int dotest = -1, mode = 0;
const char *testname = nullptr;
switch (testtype) {
case 'O':
testname="Offline Immediate ";
if (isSupportExecuteOfflineImmediate(&data))
dotest=OFFLINE_FULL_SCAN;
else
state.not_cap_offline = true;
break;
case 'C':
testname="Conveyance Self-";
if (isSupportConveyanceSelfTest(&data))
dotest=CONVEYANCE_SELF_TEST;
else
state.not_cap_conveyance = true;
break;
case 'S':
testname="Short Self-";
if (isSupportSelfTest(&data))
dotest=SHORT_SELF_TEST;
else
state.not_cap_short = true;
break;
case 'L':
testname="Long Self-";
if (isSupportSelfTest(&data))
dotest=EXTEND_SELF_TEST;
else
state.not_cap_long = true;
break;
case 'c': case 'n': case 'r':
testname = "Selective Self-";
if (isSupportSelectiveSelfTest(&data)) {
dotest = SELECTIVE_SELF_TEST;
switch (testtype) {
case 'c': mode = SEL_CONT; break;
case 'n': mode = SEL_NEXT; break;
case 'r': mode = SEL_REDO; break;
}
}
else
state.not_cap_selective = true;
break;
}
if (dotest<0) {
PrintOut(LOG_CRIT, "Device: %s, not capable of %sTest\n", name, testname);
return 1;
}
if (15==(data.self_test_exec_status >> 4)) {
if (cfg.firmwarebugs.is_set(BUG_SAMSUNG3) && data.self_test_exec_status == 0xf0) {
PrintOut(LOG_INFO, "Device: %s, will not skip scheduled %sTest "
"despite unclear Self-Test byte (SAMSUNG Firmware bug).\n", name, testname);
} else {
PrintOut(LOG_INFO, "Device: %s, skip scheduled %sTest; %1d0%% remaining of current Self-Test.\n",
name, testname, (int)(data.self_test_exec_status & 0x0f));
return 1;
}
}
if (dotest == SELECTIVE_SELF_TEST) {
ata_selective_selftest_args selargs, prev_args;
selargs.num_spans = 1;
selargs.span[0].mode = mode;
prev_args.num_spans = 1;
prev_args.span[0].start = state.selective_test_last_start;
prev_args.span[0].end = state.selective_test_last_end;
if (ataWriteSelectiveSelfTestLog(device, selargs, &data, state.num_sectors, &prev_args)) {
PrintOut(LOG_CRIT, "Device: %s, prepare %sTest failed\n", name, testname);
return 1;
}
uint64_t start = selargs.span[0].start, end = selargs.span[0].end;
PrintOut(LOG_INFO, "Device: %s, %s test span at LBA %" PRIu64 " - %" PRIu64 " (%" PRIu64 " sectors, %u%% - %u%% of disk).\n",
name, (selargs.span[0].mode == SEL_NEXT ? "next" : "redo"),
start, end, end - start + 1,
(unsigned)((100 * start + state.num_sectors/2) / state.num_sectors),
(unsigned)((100 * end + state.num_sectors/2) / state.num_sectors));
state.selective_test_last_start = start;
state.selective_test_last_end = end;
}
int retval = smartcommandhandler(device, IMMEDIATE_OFFLINE, dotest, nullptr);
if (retval) {
PrintOut(LOG_CRIT, "Device: %s, execute %sTest failed.\n", name, testname);
return retval;
}
if (testtype == 'O')
state.offline_started = true;
else
state.selftest_started = true;
PrintOut(LOG_INFO, "Device: %s, starting scheduled %sTest.\n", name, testname);
return 0;
}
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)
{
int i = ata_find_attr_index(id, smartval);
if (!(i >= 0 && ata_find_attr_index(id, state.smartval) == i))
return;
uint64_t rawval = ata_get_attr_raw_value(smartval.vendor_attributes[i], cfg.attribute_defs);
if (rawval == 0) {
reset_warning_mail(cfg, state, mailtype, "No more %s", msg);
return;
}
uint64_t prev_rawval = ata_get_attr_raw_value(state.smartval.vendor_attributes[i], cfg.attribute_defs);
if (!(!increase_only || prev_rawval < rawval))
return;
std::string s = strprintf("Device: %s, %" PRId64 " %s", cfg.name.c_str(), rawval, msg);
if (prev_rawval > 0 && rawval != prev_rawval)
s += strprintf(" (changed %+" PRId64 ")", rawval - prev_rawval);
PrintOut(LOG_CRIT, "%s\n", s.c_str());
MailWarning(cfg, state, mailtype, "%s", s.c_str());
state.must_write = true;
}
static const char * fmt_temp(unsigned char x, char (& buf)[20])
{
if (!x)
return "??";
snprintf(buf, sizeof(buf), "%u", x);
return buf;
}
static void CheckTemperature(const dev_config & cfg, dev_state & state, unsigned char currtemp, unsigned char triptemp)
{
if (!(0 < currtemp && currtemp < 255)) {
PrintOut(LOG_INFO, "Device: %s, failed to read Temperature\n", cfg.name.c_str());
return;
}
const char * minchg = "", * maxchg = "";
if (currtemp > state.tempmax) {
if (state.tempmax)
maxchg = "!";
state.tempmax = currtemp;
state.must_write = true;
}
char buf[20];
if (!state.temperature) {
if (!state.tempmin || currtemp < state.tempmin)
state.tempmin_delay = time(nullptr) + default_checktime - 60;
PrintOut(LOG_INFO, "Device: %s, initial Temperature is %d Celsius (Min/Max %s/%u%s)\n",
cfg.name.c_str(), (int)currtemp, fmt_temp(state.tempmin, buf), state.tempmax, maxchg);
if (triptemp)
PrintOut(LOG_INFO, " [trip Temperature is %d Celsius]\n", (int)triptemp);
state.temperature = currtemp;
}
else {
if (state.tempmin_delay) {
if ( (state.tempmin && currtemp > state.tempmin)
|| (state.tempmin_delay <= time(nullptr))) {
state.tempmin_delay = 0;
if (!state.tempmin)
state.tempmin = 255;
}
}
if (!state.tempmin_delay && currtemp < state.tempmin) {
state.tempmin = currtemp;
state.must_write = true;
if (currtemp != state.temperature)
minchg = "!";
}
if (cfg.tempdiff && (*minchg || *maxchg || abs((int)currtemp - (int)state.temperature) >= cfg.tempdiff)) {
PrintOut(LOG_INFO, "Device: %s, Temperature changed %+d Celsius to %u Celsius (Min/Max %s%s/%u%s)\n",
cfg.name.c_str(), (int)currtemp-(int)state.temperature, currtemp, fmt_temp(state.tempmin, buf), minchg, state.tempmax, maxchg);
state.temperature = currtemp;
}
}
if (cfg.tempcrit && currtemp >= cfg.tempcrit) {
PrintOut(LOG_CRIT, "Device: %s, Temperature %u Celsius reached critical limit of %u Celsius (Min/Max %s%s/%u%s)\n",
cfg.name.c_str(), currtemp, cfg.tempcrit, fmt_temp(state.tempmin, buf), minchg, state.tempmax, maxchg);
MailWarning(cfg, state, 12, "Device: %s, Temperature %d Celsius reached critical limit of %u Celsius (Min/Max %s%s/%u%s)",
cfg.name.c_str(), currtemp, cfg.tempcrit, fmt_temp(state.tempmin, buf), minchg, state.tempmax, maxchg);
}
else if (cfg.tempinfo && currtemp >= cfg.tempinfo) {
PrintOut(LOG_INFO, "Device: %s, Temperature %u Celsius reached limit of %u Celsius (Min/Max %s%s/%u%s)\n",
cfg.name.c_str(), currtemp, cfg.tempinfo, fmt_temp(state.tempmin, buf), minchg, state.tempmax, maxchg);
}
else if (cfg.tempcrit) {
unsigned char limit = (cfg.tempinfo ? cfg.tempinfo : cfg.tempcrit-5);
if (currtemp < limit)
reset_warning_mail(cfg, state, 12, "Temperature %u Celsius dropped below %u Celsius", currtemp, limit);
}
}
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)
{
ata_attr_state attrstate = ata_get_attr_state(attr, attridx, thresholds, cfg.attribute_defs);
if (attrstate == ATTRSTATE_NON_EXISTING)
return;
if ( cfg.usagefailed && attrstate == ATTRSTATE_FAILED_NOW
&& !cfg.monitor_attr_flags.is_set(attr.id, MONITOR_IGN_FAILUSE)) {
std::string attrname = ata_get_smart_attr_name(attr.id, cfg.attribute_defs, cfg.dev_rpm);
PrintOut(LOG_CRIT, "Device: %s, Failed SMART usage Attribute: %d %s.\n", cfg.name.c_str(), attr.id, attrname.c_str());
MailWarning(cfg, state, 2, "Device: %s, Failed SMART usage Attribute: %d %s.", cfg.name.c_str(), attr.id, attrname.c_str());
state.must_write = true;
}
bool prefail = !!ATTRIBUTE_FLAGS_PREFAILURE(attr.flags);
if (!( ( prefail && cfg.prefail)
|| (!prefail && cfg.usage )))
return;
if (cfg.monitor_attr_flags.is_set(attr.id, MONITOR_IGNORE))
return;
if (attr.id != prev.id) {
PrintOut(LOG_INFO,"Device: %s, same Attribute has different ID numbers: %d = %d\n",
cfg.name.c_str(), attr.id, prev.id);
return;
}
bool valchanged = false;
if (attrstate > ATTRSTATE_NO_NORMVAL) {
if (attr.current != prev.current)
valchanged = true;
}
bool rawchanged = false;
if (cfg.monitor_attr_flags.is_set(attr.id, MONITOR_RAW)) {
if ( ata_get_attr_raw_value(attr, cfg.attribute_defs)
!= ata_get_attr_raw_value(prev, cfg.attribute_defs))
rawchanged = true;
}
if (!(valchanged || rawchanged))
return;
std::string currstr, prevstr;
if (attrstate == ATTRSTATE_NO_NORMVAL) {
currstr = strprintf("%s (Raw)",
ata_format_attr_raw_value(attr, cfg.attribute_defs).c_str());
prevstr = strprintf("%s (Raw)",
ata_format_attr_raw_value(prev, cfg.attribute_defs).c_str());
}
else if (cfg.monitor_attr_flags.is_set(attr.id, MONITOR_RAW_PRINT)) {
currstr = strprintf("%d [Raw %s]", attr.current,
ata_format_attr_raw_value(attr, cfg.attribute_defs).c_str());
prevstr = strprintf("%d [Raw %s]", prev.current,
ata_format_attr_raw_value(prev, cfg.attribute_defs).c_str());
}
else {
currstr = strprintf("%d", attr.current);
prevstr = strprintf("%d", prev.current);
}
std::string msg = strprintf("Device: %s, SMART %s Attribute: %d %s changed from %s to %s",
cfg.name.c_str(), (prefail ? "Prefailure" : "Usage"), attr.id,
ata_get_smart_attr_name(attr.id, cfg.attribute_defs, cfg.dev_rpm).c_str(),
prevstr.c_str(), currstr.c_str());
if ( (valchanged && cfg.monitor_attr_flags.is_set(attr.id, MONITOR_AS_CRIT))
|| (rawchanged && cfg.monitor_attr_flags.is_set(attr.id, MONITOR_RAW_AS_CRIT))) {
PrintOut(LOG_CRIT, "%s\n", msg.c_str());
MailWarning(cfg, state, 2, "%s", msg.c_str());
}
else {
PrintOut(LOG_INFO, "%s\n", msg.c_str());
}
state.must_write = true;
}
static int ATACheckDevice(const dev_config & cfg, dev_state & state, ata_device * atadev,
bool firstpass, bool allow_selftests)
{
if (!open_device(cfg, state, atadev, "ATA"))
return 1;
const char * name = cfg.name.c_str();
if (cfg.powermode && !state.powermodefail) {
int dontcheck=0, powermode=ataCheckPowerMode(atadev);
const char * mode = 0;
if (0 <= powermode && powermode < 0xff) {
int powermode2;
sleep(5);
powermode2 = ataCheckPowerMode(atadev);
if (powermode2 > powermode)
PrintOut(LOG_INFO, "Device: %s, CHECK POWER STATUS spins up disk (0x%02x -> 0x%02x)\n", name, powermode, powermode2);
powermode = powermode2;
}
switch (powermode){
case -1:
mode="SLEEP";
if (cfg.powermode>=1)
dontcheck=1;
break;
case 0x00:
mode="STANDBY";
if (cfg.powermode>=2)
dontcheck=1;
break;
case 0x01:
mode="STANDBY_Y";
if (cfg.powermode>=2)
dontcheck=1;
break;
case 0x80:
mode="IDLE";
if (cfg.powermode>=3)
dontcheck=1;
break;
case 0x81:
mode="IDLE_A";
if (cfg.powermode>=3)
dontcheck=1;
break;
case 0x82:
mode="IDLE_B";
if (cfg.powermode>=3)
dontcheck=1;
break;
case 0x83:
mode="IDLE_C";
if (cfg.powermode>=3)
dontcheck=1;
break;
case 0xff:
case 0x40:
case 0x41:
mode="ACTIVE or IDLE";
break;
default:
PrintOut(LOG_CRIT, "Device: %s, CHECK POWER STATUS returned %d, not ATA compliant, ignoring -n Directive\n",
name, powermode);
state.powermodefail = true;
break;
}
if (dontcheck){
if (!cfg.powerskipmax || state.powerskipcnt<cfg.powerskipmax) {
CloseDevice(atadev, name);
if ((!state.powerskipcnt || state.lastpowermodeskipped != powermode) && !cfg.powerquiet) {
PrintOut(LOG_INFO, "Device: %s, is in %s mode, suspending checks\n", name, mode);
state.lastpowermodeskipped = powermode;
}
state.powerskipcnt++;
return 0;
}
else {
PrintOut(LOG_INFO, "Device: %s, %s mode ignored due to reached limit of skipped checks (%d check%s skipped)\n",
name, mode, state.powerskipcnt, (state.powerskipcnt==1?"":"s"));
}
state.powerskipcnt = 0;
state.tempmin_delay = time(nullptr) + default_checktime - 60;
}
else if (state.powerskipcnt) {
PrintOut(LOG_INFO, "Device: %s, is back in %s mode, resuming checks (%d check%s skipped)\n",
name, mode, state.powerskipcnt, (state.powerskipcnt==1?"":"s"));
state.powerskipcnt = 0;
state.tempmin_delay = time(nullptr) + default_checktime - 60;
}
}
if (cfg.smartcheck) {
int status=ataSmartStatus2(atadev);
if (status==-1){
PrintOut(LOG_INFO,"Device: %s, not capable of SMART self-check\n",name);
MailWarning(cfg, state, 5, "Device: %s, not capable of SMART self-check", name);
state.must_write = true;
}
else if (status==1){
PrintOut(LOG_CRIT, "Device: %s, FAILED SMART self-check. BACK UP DATA NOW!\n", name);
MailWarning(cfg, state, 1, "Device: %s, FAILED SMART self-check. BACK UP DATA NOW!", name);
state.must_write = true;
}
}
if ( cfg.usagefailed || cfg.prefail || cfg.usage
|| cfg.curr_pending_id || cfg.offl_pending_id
|| cfg.tempdiff || cfg.tempinfo || cfg.tempcrit
|| cfg.selftest || cfg.offlinests || cfg.selfteststs) {
ata_smart_values curval;
if (ataReadSmartValues(atadev, &curval)){
PrintOut(LOG_CRIT, "Device: %s, failed to read SMART Attribute Data\n", name);
MailWarning(cfg, state, 6, "Device: %s, failed to read SMART Attribute Data", name);
state.must_write = true;
}
else {
reset_warning_mail(cfg, state, 6, "read SMART Attribute Data worked again");
if (cfg.curr_pending_id)
check_pending(cfg, state, cfg.curr_pending_id, cfg.curr_pending_incr, curval, 10,
(!cfg.curr_pending_incr ? "Currently unreadable (pending) sectors"
: "Total unreadable (pending) sectors" ));
if (cfg.offl_pending_id)
check_pending(cfg, state, cfg.offl_pending_id, cfg.offl_pending_incr, curval, 11,
(!cfg.offl_pending_incr ? "Offline uncorrectable sectors"
: "Total offline uncorrectable sectors"));
if (cfg.tempdiff || cfg.tempinfo || cfg.tempcrit)
CheckTemperature(cfg, state, ata_return_temperature_value(&curval, cfg.attribute_defs), 0);
if (cfg.usagefailed || cfg.prefail || cfg.usage) {
for (int i = 0; i < NUMBER_ATA_SMART_ATTRIBUTES; i++) {
check_attribute(cfg, state,
curval.vendor_attributes[i],
state.smartval.vendor_attributes[i],
i, state.smartthres.thres_entries);
}
}
if (cfg.offlinests) {
if ( curval.offline_data_collection_status
!= state.smartval.offline_data_collection_status
|| state.offline_started
|| (firstpass && (debugmode || (curval.offline_data_collection_status & 0x7d))))
log_offline_data_coll_status(name, curval.offline_data_collection_status);
}
if (cfg.selfteststs) {
if ( curval.self_test_exec_status != state.smartval.self_test_exec_status
|| state.selftest_started
|| (firstpass && (debugmode || (curval.self_test_exec_status & 0xf0))))
log_self_test_exec_status(name, curval.self_test_exec_status);
}
state.smartval = curval;
state.update_persistent_state();
state.attrlog_dirty = true;
}
}
state.offline_started = state.selftest_started = false;
if (cfg.selftest)
CheckSelfTestLogs(cfg, state, SelfTestErrorCount(atadev, name, cfg.firmwarebugs));
if (cfg.errorlog || cfg.xerrorlog) {
int errcnt1 = -1, errcnt2 = -1;
if (cfg.errorlog)
errcnt1 = read_ata_error_count(atadev, name, cfg.firmwarebugs, false);
if (cfg.xerrorlog)
errcnt2 = read_ata_error_count(atadev, name, cfg.firmwarebugs, true);
int newc = (errcnt1 >= errcnt2 ? errcnt1 : errcnt2);
if (newc<0)
MailWarning(cfg, state, 7, "Device: %s, Read SMART Error Log Failed", name);
int oldc = state.ataerrorcount;
if (newc>oldc){
PrintOut(LOG_CRIT, "Device: %s, ATA error count increased from %d to %d\n",
name, oldc, newc);
MailWarning(cfg, state, 4, "Device: %s, ATA error count increased from %d to %d",
name, oldc, newc);
state.must_write = true;
}
if (newc>=0)
state.ataerrorcount=newc;
}
if (allow_selftests && !cfg.test_regex.empty()) {
char testtype = next_scheduled_test(cfg, state, false);
if (testtype)
DoATASelfTest(cfg, state, atadev, testtype);
}
CloseDevice(atadev, name);
return 0;
}
static int SCSICheckDevice(const dev_config & cfg, dev_state & state, scsi_device * scsidev, bool allow_selftests)
{
if (!open_device(cfg, state, scsidev, "SCSI"))
return 1;
const char * name = cfg.name.c_str();
uint8_t asc = 0, ascq = 0;
uint8_t currenttemp = 0, triptemp = 0;
if (!state.SuppressReport) {
if (scsiCheckIE(scsidev, state.SmartPageSupported, state.TempPageSupported,
&asc, &ascq, ¤ttemp, &triptemp)) {
PrintOut(LOG_INFO, "Device: %s, failed to read SMART values\n",
name);
MailWarning(cfg, state, 6, "Device: %s, failed to read SMART values", name);
state.SuppressReport = 1;
}
}
if (asc > 0) {
char b[128];
const char * cp = scsiGetIEString(asc, ascq, b, sizeof(b));
if (cp) {
PrintOut(LOG_CRIT, "Device: %s, SMART Failure: %s\n", name, cp);
MailWarning(cfg, state, 1,"Device: %s, SMART Failure: %s", name, cp);
} else if (asc == 4 && ascq == 9) {
PrintOut(LOG_INFO,"Device: %s, self-test in progress\n", name);
} else if (debugmode)
PrintOut(LOG_INFO,"Device: %s, non-SMART asc,ascq: %d,%d\n",
name, (int)asc, (int)ascq);
} else if (debugmode)
PrintOut(LOG_INFO,"Device: %s, SMART health: passed\n", name);
if (cfg.tempdiff || cfg.tempinfo || cfg.tempcrit)
CheckTemperature(cfg, state, currenttemp, triptemp);
if (cfg.selftest)
CheckSelfTestLogs(cfg, state, scsiCountFailedSelfTests(scsidev, 0));
if (allow_selftests && !cfg.test_regex.empty()) {
char testtype = next_scheduled_test(cfg, state, true);
if (testtype)
DoSCSISelfTest(cfg, state, scsidev, testtype);
}
if (!cfg.attrlog_file.empty()){
uint8_t tBuf[252];
if (state.ReadECounterPageSupported && (0 == scsiLogSense(scsidev,
READ_ERROR_COUNTER_LPAGE, 0, tBuf, sizeof(tBuf), 0))) {
scsiDecodeErrCounterPage(tBuf, &state.scsi_error_counters[0].errCounter,
scsiLogRespLen);
state.scsi_error_counters[0].found=1;
}
if (state.WriteECounterPageSupported && (0 == scsiLogSense(scsidev,
WRITE_ERROR_COUNTER_LPAGE, 0, tBuf, sizeof(tBuf), 0))) {
scsiDecodeErrCounterPage(tBuf, &state.scsi_error_counters[1].errCounter,
scsiLogRespLen);
state.scsi_error_counters[1].found=1;
}
if (state.VerifyECounterPageSupported && (0 == scsiLogSense(scsidev,
VERIFY_ERROR_COUNTER_LPAGE, 0, tBuf, sizeof(tBuf), 0))) {
scsiDecodeErrCounterPage(tBuf, &state.scsi_error_counters[2].errCounter,
scsiLogRespLen);
state.scsi_error_counters[2].found=1;
}
if (state.NonMediumErrorPageSupported && (0 == scsiLogSense(scsidev,
NON_MEDIUM_ERROR_LPAGE, 0, tBuf, sizeof(tBuf), 0))) {
scsiDecodeNonMediumErrPage(tBuf, &state.scsi_nonmedium_error.nme,
scsiLogRespLen);
state.scsi_nonmedium_error.found=1;
}
if (!(cfg.tempdiff || cfg.tempinfo || cfg.tempcrit))
state.temperature = currenttemp;
}
CloseDevice(scsidev, name);
state.attrlog_dirty = true;
return 0;
}
static int NVMeCheckDevice(const dev_config & cfg, dev_state & state, nvme_device * nvmedev)
{
if (!open_device(cfg, state, nvmedev, "NVMe"))
return 1;
const char * name = cfg.name.c_str();
nvme_smart_log smart_log;
if (!nvme_read_smart_log(nvmedev, smart_log)) {
CloseDevice(nvmedev, name);
PrintOut(LOG_INFO, "Device: %s, failed to read NVMe SMART/Health Information\n", name);
MailWarning(cfg, state, 6, "Device: %s, failed to read NVMe SMART/Health Information", name);
state.must_write = true;
return 0;
}
if (cfg.smartcheck && smart_log.critical_warning) {
unsigned char w = smart_log.critical_warning;
std::string msg;
static const char * const wnames[] =
{"LowSpare", "Temperature", "Reliability", "R/O", "VolMemBackup"};
for (unsigned b = 0, cnt = 0; b < 8 ; b++) {
if (!(w & (1 << b)))
continue;
if (cnt)
msg += ", ";
if (++cnt > 3) {
msg += "..."; break;
}
if (b >= sizeof(wnames)/sizeof(wnames[0])) {
msg += "*Unknown*"; break;
}
msg += wnames[b];
}
PrintOut(LOG_CRIT, "Device: %s, Critical Warning (0x%02x): %s\n", name, w, msg.c_str());
MailWarning(cfg, state, 1, "Device: %s, Critical Warning (0x%02x): %s", name, w, msg.c_str());
state.must_write = true;
}
if (cfg.tempdiff || cfg.tempinfo || cfg.tempcrit) {
int k = nvme_get_max_temp_kelvin(smart_log);
int c = k - 273;
if (c < 1)
c = 1;
else if (c > 0xff)
c = 0xff;
CheckTemperature(cfg, state, c, 0);
}
if (cfg.errorlog || cfg.xerrorlog) {
uint64_t newcnt = le128_to_uint64(smart_log.num_err_log_entries);
if (newcnt > state.nvme_err_log_entries) {
check_nvme_error_log(cfg, state, nvmedev, newcnt);
}
}
CloseDevice(nvmedev, name);
state.attrlog_dirty = true;
return 0;
}
static int standby_disable_state = 0;
static void init_disable_standby_check(const dev_config_vector & configs)
{
bool sts1 = false, sts2 = false;
for (const auto & cfg : configs) {
if (cfg.offlinests_ns)
sts1 = true;
if (cfg.selfteststs_ns)
sts2 = true;
}
if (sts1 || sts2 || standby_disable_state == 3) {
if (!smi()->disable_system_auto_standby(false)) {
if (standby_disable_state == 3)
PrintOut(LOG_CRIT, "System auto standby enable failed: %s\n", smi()->get_errmsg());
if (sts1 || sts2) {
PrintOut(LOG_INFO, "Disable auto standby not supported, ignoring ',ns' from %s%s%s\n",
(sts1 ? "-l offlinests,ns" : ""), (sts1 && sts2 ? " and " : ""), (sts2 ? "-l selfteststs,ns" : ""));
sts1 = sts2 = false;
}
}
}
standby_disable_state = (sts1 || sts2 ? 1 : 0);
}
static void do_disable_standby_check(const dev_config_vector & configs, const dev_state_vector & states)
{
if (!standby_disable_state)
return;
bool running = false;
for (unsigned i = 0; i < configs.size() && !running; i++) {
const dev_config & cfg = configs.at(i); const dev_state & state = states.at(i);
if ( ( cfg.offlinests_ns
&& (state.offline_started ||
is_offl_coll_in_progress(state.smartval.offline_data_collection_status)))
|| ( cfg.selfteststs_ns
&& (state.selftest_started ||
is_self_test_in_progress(state.smartval.self_test_exec_status))) )
running = true;
}
if (!running) {
if (standby_disable_state != 1) {
if (!smi()->disable_system_auto_standby(false))
PrintOut(LOG_CRIT, "Self-test(s) completed, system auto standby enable failed: %s\n",
smi()->get_errmsg());
else
PrintOut(LOG_INFO, "Self-test(s) completed, system auto standby enabled\n");
standby_disable_state = 1;
}
}
else if (!smi()->disable_system_auto_standby(true)) {
if (standby_disable_state != 2) {
PrintOut(LOG_INFO, "Self-test(s) in progress, system auto standby disable rejected: %s\n",
smi()->get_errmsg());
standby_disable_state = 2;
}
}
else {
if (standby_disable_state != 3) {
PrintOut(LOG_INFO, "Self-test(s) in progress, system auto standby disabled\n");
standby_disable_state = 3;
}
}
}
static void CheckDevicesOnce(const dev_config_vector & configs, dev_state_vector & states,
smart_device_list & devices, bool firstpass, bool allow_selftests)
{
for (unsigned i = 0; i < configs.size(); i++) {
const dev_config & cfg = configs.at(i);
dev_state & state = states.at(i);
if (state.skip) {
if (debugmode)
PrintOut(LOG_INFO, "Device: %s, skipped (interval=%d)\n", cfg.name.c_str(),
(cfg.checktime ? cfg.checktime : checktime));
continue;
}
smart_device * dev = devices.at(i);
if (dev->is_ata())
ATACheckDevice(cfg, state, dev->to_ata(), firstpass, allow_selftests);
else if (dev->is_scsi())
SCSICheckDevice(cfg, state, dev->to_scsi(), allow_selftests);
else if (dev->is_nvme())
NVMeCheckDevice(cfg, state, dev->to_nvme());
notify_extend_timeout();
}
do_disable_standby_check(configs, states);
}
static void install_signal_handlers()
{
set_signal_if_not_ignored(SIGTERM, sighandler);
set_signal_if_not_ignored(SIGQUIT, sighandler);
set_signal_if_not_ignored(SIGINT, (debugmode ? HUPhandler : sighandler));
set_signal_if_not_ignored(SIGHUP, HUPhandler);
set_signal_if_not_ignored(SIGUSR1, USR1handler);
#ifdef _WIN32
set_signal_if_not_ignored(SIGUSR2, USR2handler);
#endif
}
#ifdef _WIN32
static void ToggleDebugMode()
{
if (!debugmode) {
PrintOut(LOG_INFO,"Signal USR2 - enabling debug mode\n");
if (!daemon_enable_console("smartd [Debug]")) {
debugmode = 1;
daemon_signal(SIGINT, HUPhandler);
PrintOut(LOG_INFO,"smartd debug mode enabled, PID=%d\n", getpid());
}
else
PrintOut(LOG_INFO,"enable console failed\n");
}
else if (debugmode == 1) {
daemon_disable_console();
debugmode = 0;
daemon_signal(SIGINT, sighandler);
PrintOut(LOG_INFO,"Signal USR2 - debug mode disabled\n");
}
else
PrintOut(LOG_INFO,"Signal USR2 - debug mode %d not changed\n", debugmode);
}
#endif
time_t calc_next_wakeuptime(time_t wakeuptime, time_t timenow, int ct)
{
if (timenow < wakeuptime)
return wakeuptime;
return timenow + ct - (timenow - wakeuptime) % ct;
}
static time_t dosleep(time_t wakeuptime, const dev_config_vector & configs,
dev_state_vector & states, bool & sigwakeup)
{
time_t timenow = time(nullptr);
unsigned n = configs.size();
int ct;
if (!checktime_min) {
wakeuptime = calc_next_wakeuptime(wakeuptime, timenow, checktime);
ct = checktime;
}
else {
wakeuptime = 0;
for (unsigned i = 0; i < n; i++) {
const dev_config & cfg = configs.at(i);
dev_state & state = states.at(i);
if (!state.skip)
state.wakeuptime = calc_next_wakeuptime((state.wakeuptime ? state.wakeuptime : timenow),
timenow, (cfg.checktime ? cfg.checktime : checktime));
if (!wakeuptime || state.wakeuptime < wakeuptime)
wakeuptime = state.wakeuptime;
}
ct = checktime_min;
}
notify_wait(wakeuptime, n);
bool no_skip = false;
int addtime = 0;
while (timenow < wakeuptime+addtime && !caughtsigUSR1 && !caughtsigHUP && !caughtsigEXIT) {
if (wakeuptime > timenow + ct) {
PrintOut(LOG_INFO, "System clock time adjusted to the past. Resetting next wakeup time.\n");
wakeuptime = timenow + ct;
for (auto & state : states)
state.wakeuptime = 0;
no_skip = true;
}
sleep(wakeuptime+addtime-timenow);
#ifdef _WIN32
if (caughtsigUSR2) {
ToggleDebugMode();
caughtsigUSR2 = 0;
}
#endif
timenow = time(nullptr);
if (!addtime && timenow > wakeuptime+60) {
if (debugmode)
PrintOut(LOG_INFO, "Sleep time was %d seconds too long, assuming wakeup from standby mode.\n",
(int)(timenow-wakeuptime));
addtime = timenow-wakeuptime+20;
int nextcheck = ct - addtime % ct;
if (nextcheck <= 20)
addtime += nextcheck;
}
}
if (caughtsigUSR1){
PrintOut(LOG_INFO,"Signal USR1 - checking devices now rather than in %d seconds.\n",
wakeuptime-timenow>0?(int)(wakeuptime-timenow):0);
caughtsigUSR1=0;
sigwakeup = no_skip = true;
}
if (checktime_min) {
for (auto & state : states)
state.skip = (!no_skip && timenow < state.wakeuptime);
}
return wakeuptime;
}
static void printoutvaliddirectiveargs(int priority, char d)
{
switch (d) {
case 'n':
PrintOut(priority, "never[,N][,q], sleep[,N][,q], standby[,N][,q], idle[,N][,q]");
break;
case 's':
PrintOut(priority, "valid_regular_expression");
break;
case 'd':
PrintOut(priority, "%s", smi()->get_valid_dev_types_str().c_str());
break;
case 'T':
PrintOut(priority, "normal, permissive");
break;
case 'o':
case 'S':
PrintOut(priority, "on, off");
break;
case 'l':
PrintOut(priority, "error, selftest");
break;
case 'M':
PrintOut(priority, "\"once\", \"always\", \"daily\", \"diminishing\", \"test\", \"exec\"");
break;
case 'v':
PrintOut(priority, "\n%s\n", create_vendor_attribute_arg_list().c_str());
break;
case 'P':
PrintOut(priority, "use, ignore, show, showall");
break;
case 'F':
PrintOut(priority, "%s", get_valid_firmwarebug_args());
break;
case 'e':
PrintOut(priority, "aam,[N|off], apm,[N|off], lookahead,[on|off], dsn,[on|off] "
"security-freeze, standby,[N|off], wcache,[on|off]");
break;
case 'c':
PrintOut(priority, "i=N, interval=N");
break;
}
}
static int GetInteger(const char *arg, const char *name, const char *token, int lineno, const char *cfgfile,
int min, int max, char * suffix = 0)
{
if (!arg) {
PrintOut(LOG_CRIT,"File %s line %d (drive %s): Directive: %s takes integer argument from %d to %d.\n",
cfgfile, lineno, name, token, min, max);
return -1;
}
char *endptr;
int val = strtol(arg,&endptr,10);
if (suffix) {
if (!strcmp(endptr, suffix))
endptr += strlen(suffix);
else
*suffix = 0;
}
if (!(!*endptr && min <= val && val <= max)) {
PrintOut(LOG_CRIT,"File %s line %d (drive %s): Directive: %s has argument: %s; needs integer from %d to %d.\n",
cfgfile, lineno, name, token, arg, min, max);
return -1;
}
return val;
}
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)
{
unsigned v1 = 0, v2 = 0, v3 = 0;
int n1 = -1, n2 = -1, n3 = -1, len;
if (!arg) {
PrintOut(LOG_CRIT,"File %s line %d (drive %s): Directive: %s takes 1-3 integer argument(s) from 0 to 255.\n",
cfgfile, lineno, name, token);
return -1;
}
len = strlen(arg);
if (!( sscanf(arg, "%u%n,%u%n,%u%n", &v1, &n1, &v2, &n2, &v3, &n3) >= 1
&& (n1 == len || n2 == len || n3 == len) && v1 <= 255 && v2 <= 255 && v3 <= 255)) {
PrintOut(LOG_CRIT,"File %s line %d (drive %s): Directive: %s has argument: %s; needs 1-3 integer(s) from 0 to 255.\n",
cfgfile, lineno, name, token, arg);
return -1;
}
*val1 = (unsigned char)v1; *val2 = (unsigned char)v2; *val3 = (unsigned char)v3;
return 0;
}
#ifdef _WIN32
static const char * strtok_dequote(const char * delimiters)
{
const char * t = strtok(nullptr, delimiters);
if (!t || t[0] != '"')
return t;
static std::string token;
token = t+1;
for (;;) {
t = strtok(nullptr, delimiters);
if (!t || !*t)
return "\"";
token += ' ';
int len = strlen(t);
if (t[len-1] == '"') {
token += std::string(t, len-1);
break;
}
token += t;
}
return token.c_str();
}
#endif
static int ParseToken(char * token, dev_config & cfg, smart_devtype_list & scan_types)
{
char sym;
const char * name = cfg.name.c_str();
int lineno=cfg.lineno;
const char *delim = " \n\t";
int badarg = 0;
int missingarg = 0;
const char *arg = 0;
if (*token=='#')
return 1;
if (*token!='-' || strlen(token)!=2) {
PrintOut(LOG_CRIT,"File %s line %d (drive %s): unknown Directive: %s\n",
configfile, lineno, name, token);
PrintOut(LOG_CRIT, "Run smartd -D to print a list of valid Directives.\n");
return -1;
}
sym=token[1];
int val;
char plus[] = "+", excl[] = "!";
switch (sym) {
case 'C':
if ((val = GetInteger((arg = strtok(nullptr, delim)), name, token, lineno, configfile, 0, 255, plus)) < 0)
return -1;
cfg.curr_pending_id = (unsigned char)val;
cfg.curr_pending_incr = (*plus == '+');
cfg.curr_pending_set = true;
break;
case 'U':
if ((val = GetInteger((arg = strtok(nullptr, delim)), name, token, lineno, configfile, 0, 255, plus)) < 0)
return -1;
cfg.offl_pending_id = (unsigned char)val;
cfg.offl_pending_incr = (*plus == '+');
cfg.offl_pending_set = true;
break;
case 'T':
if (!(arg = strtok(nullptr, delim))) {
missingarg = 1;
} else if (!strcmp(arg, "normal")) {
cfg.permissive = false;
} else if (!strcmp(arg, "permissive")) {
cfg.permissive = true;
} else {
badarg = 1;
}
break;
case 'd':
if (!(arg = strtok(nullptr, delim))) {
missingarg = 1;
} else if (!strcmp(arg, "ignore")) {
cfg.ignore = true;
} else if (!strcmp(arg, "removable")) {
cfg.removable = true;
} else if (!strcmp(arg, "auto")) {
cfg.dev_type = "";
scan_types.clear();
} else {
cfg.dev_type = arg;
scan_types.push_back(arg);
}
break;
case 'F':
if (!(arg = strtok(nullptr, delim)))
missingarg = 1;
else if (!parse_firmwarebug_def(arg, cfg.firmwarebugs))
badarg = 1;
break;
case 'H':
cfg.smartcheck = true;
break;
case 'f':
cfg.usagefailed = true;
break;
case 't':
cfg.prefail = true;
cfg.usage = true;
break;
case 'p':
cfg.prefail = true;
break;
case 'u':
cfg.usage = true;
break;
case 'l':
if (!(arg = strtok(nullptr, delim))) {
missingarg = 1;
} else if (!strcmp(arg, "selftest")) {
cfg.selftest = true;
} else if (!strcmp(arg, "error")) {
cfg.errorlog = true;
} else if (!strcmp(arg, "xerror")) {
cfg.xerrorlog = true;
} else if (!strcmp(arg, "offlinests")) {
cfg.offlinests = true;
} else if (!strcmp(arg, "offlinests,ns")) {
cfg.offlinests = cfg.offlinests_ns = true;
} else if (!strcmp(arg, "selfteststs")) {
cfg.selfteststs = true;
} else if (!strcmp(arg, "selfteststs,ns")) {
cfg.selfteststs = cfg.selfteststs_ns = true;
} else if (!strncmp(arg, "scterc,", sizeof("scterc,")-1)) {
unsigned rt = ~0, wt = ~0; int nc = -1;
sscanf(arg,"scterc,%u,%u%n", &rt, &wt, &nc);
if (nc == (int)strlen(arg) && rt <= 999 && wt <= 999) {
cfg.sct_erc_set = true;
cfg.sct_erc_readtime = rt;
cfg.sct_erc_writetime = wt;
}
else
badarg = 1;
} else {
badarg = 1;
}
break;
case 'a':
cfg.smartcheck = true;
cfg.prefail = true;
cfg.usagefailed = true;
cfg.usage = true;
cfg.selftest = true;
cfg.errorlog = true;
cfg.selfteststs = true;
break;
case 'o':
if (!(arg = strtok(nullptr, delim))) {
missingarg = 1;
} else if (!strcmp(arg, "on")) {
cfg.autoofflinetest = 2;
} else if (!strcmp(arg, "off")) {
cfg.autoofflinetest = 1;
} else {
badarg = 1;
}
break;
case 'n':
if (!(arg = strtok(nullptr, delim)))
missingarg = 1;
else {
char *endptr = nullptr;
char *next = strchr(const_cast<char*>(arg), ',');
cfg.powerquiet = false;
cfg.powerskipmax = 0;
if (next)
*next = '\0';
if (!strcmp(arg, "never"))
cfg.powermode = 0;
else if (!strcmp(arg, "sleep"))
cfg.powermode = 1;
else if (!strcmp(arg, "standby"))
cfg.powermode = 2;
else if (!strcmp(arg, "idle"))
cfg.powermode = 3;
else
badarg = 1;
if (!badarg && next) {
next++;
cfg.powerskipmax = strtol(next, &endptr, 10);
if (endptr == next)
cfg.powerskipmax = 0;
else {
next = endptr + (*endptr != '\0');
if (cfg.powerskipmax <= 0)
badarg = 1;
}
if (*next != '\0') {
if (!strcmp("q", next))
cfg.powerquiet = true;
else {
badarg = 1;
}
}
}
}
break;
case 'S':
if (!(arg = strtok(nullptr, delim))) {
missingarg = 1;
} else if (!strcmp(arg, "on")) {
cfg.autosave = 2;
} else if (!strcmp(arg, "off")) {
cfg.autosave = 1;
} else {
badarg = 1;
}
break;
case 's':
if (!cfg.test_regex.empty()){
PrintOut(LOG_INFO, "File %s line %d (drive %s): ignoring previous Test Directive -s %s\n",
configfile, lineno, name, cfg.test_regex.get_pattern());
cfg.test_regex = regular_expression();
}
if (!(arg = strtok(nullptr, delim))) {
missingarg = 1;
}
else {
if (!cfg.test_regex.compile(arg)) {
PrintOut(LOG_CRIT, "File %s line %d (drive %s): -s argument \"%s\" is INVALID extended regular expression. %s.\n",
configfile, lineno, name, arg, cfg.test_regex.get_errmsg());
return -1;
}
static const regular_expression syntax_check(
"[^]$()*+./:?^[|0-9LSCOncr-]+|"
":[0-9]{0,2}($|[^0-9])|:[0-9]{4,}|"
":[0-9]{3}-(000|[0-9]{0,2}($|[^0-9])|[0-9]{4,})"
);
regular_expression::match_range range;
if (syntax_check.execute(arg, 1, &range) && 0 <= range.rm_so && range.rm_so < range.rm_eo)
PrintOut(LOG_INFO, "File %s line %d (drive %s): warning, \"%.*s\" looks odd in "
"extended regular expression \"%s\"\n",
configfile, lineno, name, (int)(range.rm_eo - range.rm_so), arg + range.rm_so, arg);
}
break;
case 'm':
if (!(arg = strtok(nullptr, delim)))
missingarg = 1;
else {
if (!cfg.emailaddress.empty())
PrintOut(LOG_INFO, "File %s line %d (drive %s): ignoring previous Address Directive -m %s\n",
configfile, lineno, name, cfg.emailaddress.c_str());
cfg.emailaddress = arg;
}
break;
case 'M':
if (!(arg = strtok(nullptr, delim)))
missingarg = 1;
else if (!strcmp(arg, "once"))
cfg.emailfreq = emailfreqs::once;
else if (!strcmp(arg, "always"))
cfg.emailfreq = emailfreqs::always;
else if (!strcmp(arg, "daily"))
cfg.emailfreq = emailfreqs::daily;
else if (!strcmp(arg, "diminishing"))
cfg.emailfreq = emailfreqs::diminishing;
else if (!strcmp(arg, "test"))
cfg.emailtest = true;
else if (!strcmp(arg, "exec")) {
#ifdef _WIN32
arg = strtok_dequote(delim);
if (arg && arg[0] == '"') {
PrintOut(LOG_CRIT, "File %s line %d (drive %s): Directive %s 'exec' argument: missing closing quote\n",
configfile, lineno, name, token);
return -1;
}
#else
arg = strtok(nullptr, delim);
#endif
if (!arg) {
PrintOut(LOG_CRIT, "File %s line %d (drive %s): Directive %s 'exec' argument must be followed by executable path.\n",
configfile, lineno, name, token);
return -1;
}
if (!cfg.emailcmdline.empty())
PrintOut(LOG_INFO, "File %s line %d (drive %s): ignoring previous mail Directive -M exec %s\n",
configfile, lineno, name, cfg.emailcmdline.c_str());
cfg.emailcmdline = arg;
}
else
badarg = 1;
break;
case 'i':
if ((val = GetInteger((arg = strtok(nullptr, delim)), name, token, lineno, configfile, 1, 255)) < 0)
return -1;
cfg.monitor_attr_flags.set(val, MONITOR_IGN_FAILUSE);
break;
case 'I':
if ((val = GetInteger((arg = strtok(nullptr, delim)), name, token, lineno, configfile, 1, 255)) < 0)
return -1;
cfg.monitor_attr_flags.set(val, MONITOR_IGNORE);
break;
case 'r':
if ((val = GetInteger((arg = strtok(nullptr, delim)), name, token, lineno, configfile, 1, 255, excl)) < 0)
return -1;
cfg.monitor_attr_flags.set(val, MONITOR_RAW_PRINT);
if (*excl == '!')
cfg.monitor_attr_flags.set(val, MONITOR_AS_CRIT);
break;
case 'R':
if ((val = GetInteger((arg = strtok(nullptr, delim)), name, token, lineno, configfile, 1, 255, excl)) < 0)
return -1;
cfg.monitor_attr_flags.set(val, MONITOR_RAW_PRINT|MONITOR_RAW);
if (*excl == '!')
cfg.monitor_attr_flags.set(val, MONITOR_RAW_AS_CRIT);
break;
case 'W':
if (Get3Integers((arg = strtok(nullptr, delim)), name, token, lineno, configfile,
&cfg.tempdiff, &cfg.tempinfo, &cfg.tempcrit) < 0)
return -1;
break;
case 'v':
if (!(arg = strtok(nullptr, delim))) {
missingarg = 1;
} else if (!parse_attribute_def(arg, cfg.attribute_defs, PRIOR_USER)) {
badarg = 1;
}
break;
case 'P':
if (!(arg = strtok(nullptr, delim))) {
missingarg = 1;
} else if (!strcmp(arg, "use")) {
cfg.ignorepresets = false;
} else if (!strcmp(arg, "ignore")) {
cfg.ignorepresets = true;
} else if (!strcmp(arg, "show")) {
cfg.showpresets = true;
} else if (!strcmp(arg, "showall")) {
showallpresets();
} else {
badarg = 1;
}
break;
case 'e':
if (!(arg = strtok(nullptr, delim))) {
missingarg = true;
}
else {
char arg2[16+1]; unsigned uval;
int n1 = -1, n2 = -1, n3 = -1, len = strlen(arg);
if (sscanf(arg, "%16[^,=]%n%*[,=]%n%u%n", arg2, &n1, &n2, &uval, &n3) >= 1
&& (n1 == len || n2 > 0)) {
bool on = (n2 > 0 && !strcmp(arg+n2, "on"));
bool off = (n2 > 0 && !strcmp(arg+n2, "off"));
if (n3 != len)
uval = ~0U;
if (!strcmp(arg2, "aam")) {
if (off)
cfg.set_aam = -1;
else if (uval <= 254)
cfg.set_aam = uval + 1;
else
badarg = true;
}
else if (!strcmp(arg2, "apm")) {
if (off)
cfg.set_apm = -1;
else if (1 <= uval && uval <= 254)
cfg.set_apm = uval + 1;
else
badarg = true;
}
else if (!strcmp(arg2, "lookahead")) {
if (off)
cfg.set_lookahead = -1;
else if (on)
cfg.set_lookahead = 1;
else
badarg = true;
}
else if (!strcmp(arg, "security-freeze")) {
cfg.set_security_freeze = true;
}
else if (!strcmp(arg2, "standby")) {
if (off)
cfg.set_standby = 0 + 1;
else if (uval <= 255)
cfg.set_standby = uval + 1;
else
badarg = true;
}
else if (!strcmp(arg2, "wcache")) {
if (off)
cfg.set_wcache = -1;
else if (on)
cfg.set_wcache = 1;
else
badarg = true;
}
else if (!strcmp(arg2, "dsn")) {
if (off)
cfg.set_dsn = -1;
else if (on)
cfg.set_dsn = 1;
else
badarg = true;
}
else
badarg = true;
}
else
badarg = true;
}
break;
case 'c':
{
if (!(arg = strtok(nullptr, delim))) {
missingarg = true;
break;
}
int n = 0, nc = -1, len = strlen(arg);
if ( ( sscanf(arg, "i=%d%n", &n, &nc) == 1
|| sscanf(arg, "interval=%d%n", &n, &nc) == 1)
&& nc == len && n >= 10)
cfg.checktime = n;
else
badarg = true;
}
break;
default:
PrintOut(LOG_CRIT,"File %s line %d (drive %s): unknown Directive: %s\n",
configfile, lineno, name, token);
PrintOut(LOG_CRIT, "Run smartd -D to print a list of valid Directives.\n");
return -1;
}
if (missingarg) {
PrintOut(LOG_CRIT, "File %s line %d (drive %s): Missing argument to %s Directive\n",
configfile, lineno, name, token);
}
if (badarg) {
PrintOut(LOG_CRIT, "File %s line %d (drive %s): Invalid argument to %s Directive: %s\n",
configfile, lineno, name, token, arg);
}
if (missingarg || badarg) {
PrintOut(LOG_CRIT, "Valid arguments to %s Directive are: ", token);
printoutvaliddirectiveargs(LOG_CRIT, sym);
PrintOut(LOG_CRIT, "\n");
return -1;
}
return 1;
}
#define SCANDIRECTIVE "DEVICESCAN"
static int ParseConfigLine(dev_config_vector & conf_entries, dev_config & default_conf,
smart_devtype_list & scan_types, int lineno, char * line)
{
const char *delim = " \n\t";
const char * name = strtok(line, delim);
if (!name || *name == '#')
return 0;
int retval;
if (!strcmp("DEFAULT", name)) {
retval = 0;
default_conf = dev_config();
}
else {
retval = (!strcmp(SCANDIRECTIVE, name) ? -1 : 1);
conf_entries.push_back(default_conf);
}
dev_config & cfg = (retval ? conf_entries.back() : default_conf);
cfg.name = name;
cfg.dev_name = name;
cfg.lineno = lineno;
while (char * token = strtok(nullptr, delim)) {
int rc = ParseToken(token, cfg, scan_types);
if (rc < 0)
return -2;
if (rc == 0)
break;
}
if (retval != -1 && scan_types.size() > 1) {
PrintOut(LOG_CRIT, "Drive: %s, invalid multiple -d TYPE Directives on line %d of file %s\n",
cfg.name.c_str(), cfg.lineno, configfile);
return -2;
}
if (retval == 0)
return retval;
if (!( cfg.smartcheck || cfg.selftest
|| cfg.errorlog || cfg.xerrorlog
|| cfg.offlinests || cfg.selfteststs
|| cfg.usagefailed || cfg.prefail || cfg.usage
|| cfg.tempdiff || cfg.tempinfo || cfg.tempcrit)) {
PrintOut(LOG_INFO,"Drive: %s, implied '-a' Directive on line %d of file %s\n",
cfg.name.c_str(), cfg.lineno, configfile);
cfg.smartcheck = true;
cfg.usagefailed = true;
cfg.prefail = true;
cfg.usage = true;
cfg.selftest = true;
cfg.errorlog = true;
cfg.selfteststs = true;
}
if ( cfg.emailaddress.empty()
&& (!cfg.emailcmdline.empty() || cfg.emailfreq != emailfreqs::unknown || cfg.emailtest)) {
PrintOut(LOG_CRIT,"Drive: %s, -M Directive(s) on line %d of file %s need -m ADDRESS Directive\n",
cfg.name.c_str(), cfg.lineno, configfile);
return -2;
}
if (cfg.emailaddress == "<nomailer>") {
if (cfg.emailcmdline.empty()){
PrintOut(LOG_CRIT,"Drive: %s, -m <nomailer> Directive on line %d of file %s needs -M exec Directive\n",
cfg.name.c_str(), cfg.lineno, configfile);
return -2;
}
cfg.emailaddress.clear();
}
return retval;
}
static int ParseConfigFile(dev_config_vector & conf_entries, smart_devtype_list & scan_types)
{
const int MAXLINELEN = 256;
const int MAXCONTLINE = 1023;
stdio_file f;
if (!(configfile == configfile_stdin)) {
if (!f.open(configfile,"r") && (errno!=ENOENT || !configfile_alt.empty())) {
int ret = (errno!=ENOENT ? -3 : -2);
PrintOut(LOG_CRIT,"%s: Unable to open configuration file %s\n",
strerror(errno),configfile);
return ret;
}
}
else
f.open(stdin);
dev_config default_conf;
int entry = 0;
if (!f) {
char fakeconfig[] = SCANDIRECTIVE " -a";
if (ParseConfigLine(conf_entries, default_conf, scan_types, 0, fakeconfig) != -1)
throw std::logic_error("Internal error parsing " SCANDIRECTIVE);
return 0;
}
#ifdef __CYGWIN__
setmode(fileno(f), O_TEXT);
#endif
PrintOut(LOG_INFO,"Opened configuration file %s\n",configfile);
int lineno = 1, cont = 0, contlineno = 0;
char line[MAXLINELEN+2];
char fullline[MAXCONTLINE+1];
for (;;) {
int len=0,scandevice;
char *lastslash;
char *comment;
char *code;
memset(line,0,sizeof(line));
code=fgets(line, MAXLINELEN+2, f);
if (!code){
if (cont) {
scandevice = ParseConfigLine(conf_entries, default_conf, scan_types, contlineno, fullline);
if (scandevice==-1)
return 0;
if (scandevice==-2)
return -1;
entry+=scandevice;
}
break;
}
contlineno++;
len=strlen(line);
if (len>MAXLINELEN){
const char *warn;
if (line[len-1]=='\n')
warn="(including newline!) ";
else
warn="";
PrintOut(LOG_CRIT,"Error: line %d of file %s %sis more than MAXLINELEN=%d characters.\n",
(int)contlineno,configfile,warn,(int)MAXLINELEN);
return -1;
}
if ((comment=strchr(line,'#'))){
*comment='\0';
len=strlen(line);
}
if (cont+len>MAXCONTLINE){
PrintOut(LOG_CRIT,"Error: continued line %d (actual line %d) of file %s is more than MAXCONTLINE=%d characters.\n",
lineno, (int)contlineno, configfile, (int)MAXCONTLINE);
return -1;
}
snprintf(fullline+cont, sizeof(fullline)-cont, "%s" ,line);
cont+=len;
if ( (lastslash=strrchr(line,'\\')) && !strtok(lastslash+1," \n\t")){
*(fullline+(cont-len)+(lastslash-line))=' ';
continue;
}
scan_types.clear();
scandevice = ParseConfigLine(conf_entries, default_conf, scan_types, contlineno, fullline);
if (scandevice==-1)
return 0;
if (scandevice==-2)
return -1;
entry+=scandevice;
lineno++;
cont=0;
}
return entry;
}
<LIST> is the list of valid arguments for option opt. */
static void PrintValidArgs(char opt)
{
const char *s;
PrintOut(LOG_CRIT, "=======> VALID ARGUMENTS ARE: ");
if (!(s = GetValidArgList(opt)))
PrintOut(LOG_CRIT, "Error constructing argument list for option %c", opt);
else
PrintOut(LOG_CRIT, "%s", (char *)s);
PrintOut(LOG_CRIT, " <=======\n");
}
#ifndef _WIN32
static bool check_abs_path(char option, const std::string & path)
{
if (path.empty() || path[0] == '/')
return true;
debugmode = 1;
PrintHead();
PrintOut(LOG_CRIT, "=======> INVALID ARGUMENT TO -%c: %s <=======\n\n", option, path.c_str());
PrintOut(LOG_CRIT, "Error: relative path names are not allowed\n\n");
return false;
}
#endif
static int parse_options(int argc, char **argv)
{
#ifndef _WIN32
configfile = SMARTMONTOOLS_SYSCONFDIR "/smartd.conf";
warning_script = SMARTMONTOOLS_SMARTDSCRIPTDIR "/smartd_warning.sh";
#else
std::string exedir = get_exe_dir();
static std::string configfile_str = exedir + "/smartd.conf";
configfile = configfile_str.c_str();
warning_script = exedir + "/smartd_warning.cmd";
#endif
static const char shortopts[] = "c:l:q:dDni:p:r:s:A:B:w:Vh?"
#if defined(HAVE_POSIX_API) || defined(_WIN32)
"u:"
#endif
#ifdef HAVE_LIBCAP_NG
"C"
#endif
;
struct option longopts[] = {
{ "configfile", required_argument, 0, 'c' },
{ "logfacility", required_argument, 0, 'l' },
{ "quit", required_argument, 0, 'q' },
{ "debug", no_argument, 0, 'd' },
{ "showdirectives", no_argument, 0, 'D' },
{ "interval", required_argument, 0, 'i' },
#ifndef _WIN32
{ "no-fork", no_argument, 0, 'n' },
#else
{ "service", no_argument, 0, 'n' },
#endif
{ "pidfile", required_argument, 0, 'p' },
{ "report", required_argument, 0, 'r' },
{ "savestates", required_argument, 0, 's' },
{ "attributelog", required_argument, 0, 'A' },
{ "drivedb", required_argument, 0, 'B' },
{ "warnexec", required_argument, 0, 'w' },
{ "version", no_argument, 0, 'V' },
{ "license", no_argument, 0, 'V' },
{ "copyright", no_argument, 0, 'V' },
{ "help", no_argument, 0, 'h' },
{ "usage", no_argument, 0, 'h' },
#if defined(HAVE_POSIX_API) || defined(_WIN32)
{ "warn-as-user", required_argument, 0, 'u' },
#endif
#ifdef HAVE_LIBCAP_NG
{ "capabilities", optional_argument, 0, 'C' },
#endif
{ 0, 0, 0, 0 }
};
opterr=optopt=0;
bool badarg = false;
const char * badarg_msg = nullptr;
bool use_default_db = true;
int optchar;
while ((optchar = getopt_long(argc, argv, shortopts, longopts, nullptr)) != -1) {
char *arg;
char *tailptr;
long lchecktime;
switch(optchar) {
case 'q':
quit_nodev0 = false;
if (!strcmp(optarg, "nodev"))
quit = QUIT_NODEV;
else if (!strcmp(optarg, "nodev0")) {
quit = QUIT_NODEV;
quit_nodev0 = true;
}
else if (!strcmp(optarg, "nodevstartup"))
quit = QUIT_NODEVSTARTUP;
else if (!strcmp(optarg, "nodev0startup")) {
quit = QUIT_NODEVSTARTUP;
quit_nodev0 = true;
}
else if (!strcmp(optarg, "errors"))
quit = QUIT_ERRORS;
else if (!strcmp(optarg, "errors,nodev0")) {
quit = QUIT_ERRORS;
quit_nodev0 = true;
}
else if (!strcmp(optarg, "never"))
quit = QUIT_NEVER;
else if (!strcmp(optarg, "onecheck")) {
quit = QUIT_ONECHECK;
debugmode = 1;
}
else if (!strcmp(optarg, "showtests")) {
quit = QUIT_SHOWTESTS;
debugmode = 1;
}
else
badarg = true;
break;
case 'l':
if (!strcmp(optarg, "daemon"))
facility=LOG_DAEMON;
else if (!strcmp(optarg, "local0"))
facility=LOG_LOCAL0;
else if (!strcmp(optarg, "local1"))
facility=LOG_LOCAL1;
else if (!strcmp(optarg, "local2"))
facility=LOG_LOCAL2;
else if (!strcmp(optarg, "local3"))
facility=LOG_LOCAL3;
else if (!strcmp(optarg, "local4"))
facility=LOG_LOCAL4;
else if (!strcmp(optarg, "local5"))
facility=LOG_LOCAL5;
else if (!strcmp(optarg, "local6"))
facility=LOG_LOCAL6;
else if (!strcmp(optarg, "local7"))
facility=LOG_LOCAL7;
else
badarg = true;
break;
case 'd':
debugmode = 1;
break;
case 'n':
#ifndef _WIN32
do_fork = false;
#endif
break;
case 'D':
debugmode = 1;
Directives();
return 0;
case 'i':
errno = 0;
lchecktime = strtol(optarg, &tailptr, 10);
if (*tailptr != '\0' || lchecktime < 10 || lchecktime > INT_MAX || errno) {
debugmode=1;
PrintHead();
PrintOut(LOG_CRIT, "======> INVALID INTERVAL: %s <=======\n", optarg);
PrintOut(LOG_CRIT, "======> INTERVAL MUST BE INTEGER BETWEEN %d AND %d <=======\n", 10, INT_MAX);
PrintOut(LOG_CRIT, "\nUse smartd -h to get a usage summary\n\n");
return EXIT_BADCMD;
}
checktime = (int)lchecktime;
break;
case 'r':
{
int n1 = -1, n2 = -1, len = strlen(optarg);
char s[9+1]; unsigned i = 1;
sscanf(optarg, "%9[a-z]%n,%u%n", s, &n1, &i, &n2);
if (!((n1 == len || n2 == len) && 1 <= i && i <= 4)) {
badarg = true;
} else if (!strcmp(s,"ioctl")) {
ata_debugmode = scsi_debugmode = nvme_debugmode = i;
} else if (!strcmp(s,"ataioctl")) {
ata_debugmode = i;
} else if (!strcmp(s,"scsiioctl")) {
scsi_debugmode = i;
} else if (!strcmp(s,"nvmeioctl")) {
nvme_debugmode = i;
} else {
badarg = true;
}
}
break;
case 'c':
if (strcmp(optarg,"-"))
configfile = (configfile_alt = optarg).c_str();
else
configfile=configfile_stdin;
break;
case 'p':
pid_file = optarg;
break;
case 's':
state_path_prefix = (strcmp(optarg, "-") ? optarg : "");
break;
case 'A':
attrlog_path_prefix = (strcmp(optarg, "-") ? optarg : "");
break;
case 'B':
{
const char * path = optarg;
if (*path == '+' && path[1])
path++;
else
use_default_db = false;
unsigned char savedebug = debugmode; debugmode = 1;
if (!read_drive_database(path))
return EXIT_BADCMD;
debugmode = savedebug;
}
break;
case 'w':
warning_script = optarg;
break;
#ifdef HAVE_POSIX_API
case 'u':
warn_as_user = false;
if (strcmp(optarg, "-")) {
warn_uname = warn_gname = "unknown";
badarg_msg = parse_ugid(optarg, warn_uid, warn_gid,
warn_uname, warn_gname );
if (badarg_msg)
break;
warn_as_user = true;
}
break;
#elif defined(_WIN32)
case 'u':
if (!strcmp(optarg, "restricted"))
warn_as_restr_user = true;
else if (!strcmp(optarg, "unchanged"))
warn_as_restr_user = false;
else
badarg = true;
break;
#endif
case 'V':
debugmode = 1;
PrintOut(LOG_INFO, "%s", format_version_info("smartd", 3 ).c_str());
return 0;
#ifdef HAVE_LIBCAP_NG
case 'C':
if (!optarg)
capabilities_mode = 1;
else if (!strcmp(optarg, "mail"))
capabilities_mode = 2;
else
badarg = true;
break;
#endif
case 'h':
debugmode=1;
PrintHead();
Usage();
return 0;
case '?':
default:
debugmode=1;
PrintHead();
arg = argv[optind-1];
if (arg[1] == '-' && optchar != 'h') {
if (optopt && strchr(shortopts, optopt)) {
PrintOut(LOG_CRIT, "=======> ARGUMENT REQUIRED FOR OPTION: %s <=======\n",arg+2);
PrintValidArgs(optopt);
} else {
PrintOut(LOG_CRIT, "=======> UNRECOGNIZED OPTION: %s <=======\n\n",arg+2);
}
PrintOut(LOG_CRIT, "\nUse smartd --help to get a usage summary\n\n");
return EXIT_BADCMD;
}
if (optopt) {
if (strchr(shortopts, optopt)){
PrintOut(LOG_CRIT, "=======> ARGUMENT REQUIRED FOR OPTION: %c <=======\n",optopt);
PrintValidArgs(optopt);
} else {
PrintOut(LOG_CRIT, "=======> UNRECOGNIZED OPTION: %c <=======\n\n",optopt);
}
PrintOut(LOG_CRIT, "\nUse smartd -h to get a usage summary\n\n");
return EXIT_BADCMD;
}
Usage();
return 0;
}
if (badarg || badarg_msg) {
debugmode=1;
PrintHead();
PrintOut(LOG_CRIT, "=======> INVALID ARGUMENT TO -%c: %s <======= \n", optchar, optarg);
if (badarg_msg)
PrintOut(LOG_CRIT, "%s\n", badarg_msg);
else
PrintValidArgs(optchar);
PrintOut(LOG_CRIT, "\nUse smartd -h to get a usage summary\n\n");
return EXIT_BADCMD;
}
}
if (argc > optind) {
debugmode=1;
PrintHead();
PrintOut(LOG_CRIT, "=======> UNRECOGNIZED ARGUMENT: %s <=======\n\n", argv[optind]);
PrintOut(LOG_CRIT, "\nUse smartd -h to get a usage summary\n\n");
return EXIT_BADCMD;
}
if (debugmode && !pid_file.empty()) {
debugmode=1;
PrintHead();
PrintOut(LOG_CRIT, "=======> INVALID CHOICE OF OPTIONS: -d and -p <======= \n\n");
PrintOut(LOG_CRIT, "Error: pid file %s not written in debug (-d) mode\n\n", pid_file.c_str());
return EXIT_BADCMD;
}
#ifndef _WIN32
if (!debugmode) {
if (!( check_abs_path('p', pid_file)
&& check_abs_path('s', state_path_prefix)
&& check_abs_path('A', attrlog_path_prefix)))
return EXIT_BADCMD;
}
#endif
#ifdef _WIN32
if (warn_as_restr_user && !popen_as_restr_check()) {
PrintHead();
PrintOut(LOG_CRIT, "Option '--warn-as-user=restricted' is not effective if the current user\n");
PrintOut(LOG_CRIT, "is the local 'SYSTEM' or 'Administrator' account\n\n");
return EXIT_BADCMD;
}
#endif
{
unsigned char savedebug = debugmode; debugmode = 1;
if (!init_drive_database(use_default_db))
return EXIT_BADCMD;
debugmode = savedebug;
}
if (!notify_post_init())
return EXIT_BADCMD;
PrintOut(LOG_INFO, "%s\n", format_version_info("smartd", (debugmode ? 2 : 1)).c_str());
return -1;
}
static int MakeConfigEntries(const dev_config & base_cfg,
dev_config_vector & conf_entries, smart_device_list & scanned_devs,
const smart_devtype_list & types)
{
smart_device_list devlist;
if (!smi()->scan_smart_devices(devlist, types)) {
PrintOut(LOG_CRIT, "DEVICESCAN failed: %s\n", smi()->get_errmsg());
return 0;
}
if (devlist.size() == 0)
return 0;
while (scanned_devs.size() < conf_entries.size())
scanned_devs.push_back((smart_device *)0);
for (unsigned i = 0; i < devlist.size(); i++) {
smart_device * dev = devlist.release(i);
scanned_devs.push_back(dev);
conf_entries.push_back(base_cfg);
dev_config & cfg = conf_entries.back();
cfg.name = dev->get_info().info_name;
cfg.dev_name = dev->get_info().dev_name;
if (!types.empty())
cfg.dev_type = dev->get_info().dev_type;
else
cfg.dev_type.clear();
}
return devlist.size();
}
static int ReadOrMakeConfigEntries(dev_config_vector & conf_entries, smart_device_list & scanned_devs)
{
smart_devtype_list scan_types;
int entries = ParseConfigFile(conf_entries, scan_types);
if (entries < 0) {
conf_entries.clear();
if (entries == -1)
PrintOut(LOG_CRIT, "Configuration file %s has fatal syntax errors.\n", configfile);
return entries;
}
if (entries) {
PrintOut(LOG_INFO, "Configuration file %s parsed.\n", configfile);
}
else if (!conf_entries.empty()) {
dev_config first = conf_entries.back();
conf_entries.pop_back();
if (first.lineno)
PrintOut(LOG_INFO,"Configuration file %s was parsed, found %s, scanning devices\n", configfile, SCANDIRECTIVE);
else
PrintOut(LOG_INFO,"No configuration file %s found, scanning devices\n", configfile);
MakeConfigEntries(first, conf_entries, scanned_devs, scan_types);
if (conf_entries.empty())
PrintOut(LOG_CRIT,"In the system's table of devices NO devices found to scan\n");
}
else
PrintOut(LOG_CRIT, "Configuration file %s parsed but has no entries\n", configfile);
return conf_entries.size();
}
static bool register_device(dev_config & cfg, dev_state & state, smart_device_auto_ptr & dev,
const dev_config_vector * prev_cfgs)
{
bool scanning;
if (!dev) {
dev = smi()->get_smart_device(cfg.name.c_str(), cfg.dev_type.c_str());
if (!dev) {
if (cfg.dev_type.empty())
PrintOut(LOG_INFO, "Device: %s, unable to autodetect device type\n", cfg.name.c_str());
else
PrintOut(LOG_INFO, "Device: %s, unsupported device type '%s'\n", cfg.name.c_str(), cfg.dev_type.c_str());
return false;
}
scanning = false;
}
else {
scanning = true;
}
smart_device::device_info oldinfo = dev->get_info();
dev.replace( dev->autodetect_open() );
if (oldinfo.dev_type != dev->get_dev_type())
PrintOut(LOG_INFO, "Device: %s, type changed from '%s' to '%s'\n",
cfg.name.c_str(), oldinfo.dev_type.c_str(), dev->get_dev_type());
if (!dev->is_open()) {
if (debugmode || !scanning)
PrintOut(LOG_INFO, "Device: %s, open() failed: %s\n", dev->get_info_name(), dev->get_errmsg());
return false;
}
cfg.name = dev->get_info().info_name;
PrintOut(LOG_INFO, "Device: %s, opened\n", cfg.name.c_str());
int status;
const char * typemsg;
if (dev->is_ata()){
typemsg = "ATA";
status = ATADeviceScan(cfg, state, dev->to_ata(), prev_cfgs);
}
else if (dev->is_scsi()){
typemsg = "SCSI";
status = SCSIDeviceScan(cfg, state, dev->to_scsi(), prev_cfgs);
}
else if (dev->is_nvme()) {
typemsg = "NVMe";
status = NVMeDeviceScan(cfg, state, dev->to_nvme(), prev_cfgs);
}
else {
PrintOut(LOG_INFO, "Device: %s, neither ATA, SCSI nor NVMe device\n", cfg.name.c_str());
return false;
}
if (status) {
if (!scanning || debugmode) {
if (cfg.lineno)
PrintOut(scanning ? LOG_INFO : LOG_CRIT,
"Unable to register %s device %s at line %d of file %s\n",
typemsg, cfg.name.c_str(), cfg.lineno, configfile);
else
PrintOut(LOG_INFO, "Unable to register %s device %s\n",
typemsg, cfg.name.c_str());
}
return false;
}
return true;
}
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)
{
configs.clear();
devices.clear();
states.clear();
typedef std::map<std::string, std::string> prev_unique_names_map;
prev_unique_names_map prev_unique_names;
for (unsigned i = 0; i < conf_entries.size(); i++) {
dev_config cfg = conf_entries[i];
std::string unique_name = smi()->get_unique_dev_name(cfg.dev_name.c_str(), cfg.dev_type.c_str());
if (debugmode && unique_name != cfg.dev_name) {
pout("Device: %s%s%s%s, unique name: %s\n", cfg.name.c_str(),
(!cfg.dev_type.empty() ? " [" : ""), cfg.dev_type.c_str(),
(!cfg.dev_type.empty() ? "]" : ""), unique_name.c_str());
}
if (cfg.ignore) {
PrintOut(LOG_INFO, "Device: %s%s%s%s, ignored\n", cfg.name.c_str(),
(!cfg.dev_type.empty() ? " [" : ""), cfg.dev_type.c_str(),
(!cfg.dev_type.empty() ? "]" : ""));
prev_unique_names[unique_name] = cfg.name;
continue;
}
smart_device_auto_ptr dev;
bool scanning = false;
if (i < scanned_devs.size()) {
dev = scanned_devs.release(i);
if (dev) {
prev_unique_names_map::iterator ui = prev_unique_names.find(unique_name);
if (ui != prev_unique_names.end()) {
bool ne = (ui->second != cfg.name);
PrintOut(LOG_INFO, "Device: %s, %s%s, ignored\n", dev->get_info_name(),
(ne ? "same as " : "duplicate"), (ne ? ui->second.c_str() : ""));
continue;
}
scanning = true;
}
}
notify_extend_timeout();
dev_state state;
if (!register_device(cfg, state, dev, (scanning ? &configs : 0))) {
if (!scanning) {
if (!(cfg.removable || quit == QUIT_NEVER)) {
PrintOut(LOG_CRIT, "Unable to register device %s (no Directive -d removable). Exiting.\n",
cfg.name.c_str());
return false;
}
PrintOut(LOG_INFO, "Device: %s, not available\n", cfg.name.c_str());
prev_unique_names[unique_name] = cfg.name;
}
continue;
}
configs.push_back(cfg);
states.push_back(state);
devices.push_back(dev);
if (!scanning)
prev_unique_names[unique_name] = cfg.name;
}
checktime_min = 0;
unsigned factor = 0;
for (auto & cfg : configs) {
if (cfg.checktime && (!checktime_min || checktime_min > cfg.checktime))
checktime_min = cfg.checktime;
if (!cfg.test_regex.empty())
cfg.test_offset_factor = factor++;
}
if (checktime_min && checktime_min > checktime)
checktime_min = checktime;
init_disable_standby_check(configs);
return true;
}
static int main_worker(int argc, char **argv)
{
smart_interface::init();
if (!smi())
return 1;
notify_init();
int status = parse_options(argc,argv);
if (status >= 0)
return status;
dev_config_vector configs;
dev_state_vector states;
smart_device_list devices;
capabilities_drop_now();
notify_msg("Initializing ...");
bool firstpass = true, write_states_always = true;
time_t wakeuptime = 0;
do {
if (firstpass || caughtsigHUP){
if (!firstpass) {
if (!state_path_prefix.empty())
write_all_dev_states(configs, states);
PrintOut(LOG_INFO,
caughtsigHUP==1?
"Signal HUP - rereading configuration file %s\n":
"\a\nSignal INT - rereading configuration file %s (" SIGQUIT_KEYNAME " quits)\n\n",
configfile);
notify_msg("Reloading ...");
}
{
dev_config_vector conf_entries;
smart_device_list scanned_devs;
int entries = ReadOrMakeConfigEntries(conf_entries, scanned_devs);
if (entries>=0) {
if (!register_devices(conf_entries, scanned_devs, configs, states, devices)) {
status = EXIT_BADDEV;
break;
}
if (!(configs.size() == devices.size() && configs.size() == states.size()))
throw std::logic_error("Invalid result from RegisterDevices");
}
else if ( quit == QUIT_NEVER
|| ((quit == QUIT_NODEV || quit == QUIT_NODEVSTARTUP) && !firstpass)) {
if (!firstpass)
PrintOut(LOG_INFO,"Reusing previous configuration\n");
}
else {
status = (entries == -3 ? EXIT_READCONF : entries == -2 ? EXIT_NOCONF : EXIT_BADCONF);
break;
}
}
if (!( devices.size() > 0 || quit == QUIT_NEVER
|| (quit == QUIT_NODEVSTARTUP && !firstpass))) {
status = (!quit_nodev0 ? EXIT_NODEV : 0);
PrintOut((status ? LOG_CRIT : LOG_INFO),
"Unable to monitor any SMART enabled devices. Exiting.\n");
break;
}
int numata = 0, numscsi = 0;
for (unsigned i = 0; i < devices.size(); i++) {
const smart_device * dev = devices.at(i);
if (dev->is_ata())
numata++;
else if (dev->is_scsi())
numscsi++;
}
PrintOut(LOG_INFO, "Monitoring %d ATA/SATA, %d SCSI/SAS and %d NVMe devices\n",
numata, numscsi, (int)devices.size() - numata - numscsi);
if (quit == QUIT_SHOWTESTS) {
PrintTestSchedule(configs, states, devices);
return 0;
}
caughtsigHUP=0;
write_states_always = true;
}
notify_check((int)devices.size());
CheckDevicesOnce(configs, states, devices, firstpass, (!firstpass || quit == QUIT_ONECHECK));
if (!state_path_prefix.empty())
write_all_dev_states(configs, states, write_states_always);
write_states_always = false;
if (!attrlog_path_prefix.empty())
write_all_dev_attrlogs(configs, states);
if (quit == QUIT_ONECHECK) {
PrintOut(LOG_INFO,"Started with '-q onecheck' option. All devices successfully checked once.\n"
"smartd is exiting (exit status 0)\n");
return 0;
}
if (firstpass) {
if (!debugmode) {
status = daemon_init();
if (status >= 0)
return status;
if (!write_pid_file())
return EXIT_PID;
}
install_signal_handlers();
wakeuptime = time(nullptr);
firstpass = false;
}
wakeuptime = dosleep(wakeuptime, configs, states, write_states_always);
} while (!caughtsigEXIT);
if (caughtsigEXIT && status < 0) {
if (caughtsigEXIT == SIGTERM || (debugmode && caughtsigEXIT == SIGQUIT)) {
PrintOut(LOG_INFO, "smartd received signal %d: %s\n",
caughtsigEXIT, strsignal(caughtsigEXIT));
}
else {
PrintOut(LOG_CRIT, "smartd received unexpected signal %d: %s\n",
caughtsigEXIT, strsignal(caughtsigEXIT));
status = EXIT_SIGNAL;
}
}
if (status < 0)
status = 0;
if (!firstpass) {
if (!status && !state_path_prefix.empty())
write_all_dev_states(configs, states);
if (!pid_file.empty() && unlink(pid_file.c_str()))
PrintOut(LOG_CRIT,"Can't unlink PID file %s (%s).\n",
pid_file.c_str(), strerror(errno));
}
PrintOut((status ? LOG_CRIT : LOG_INFO), "smartd is exiting (exit status %d)\n", status);
return status;
}
#ifndef _WIN32
int main(int argc, char **argv)
#else
static int smartd_main(int argc, char **argv)
#endif
{
int status;
try {
status = main_worker(argc, argv);
}
catch (const std::bad_alloc & ) {
PrintOut(LOG_CRIT, "Smartd: Out of memory\n");
status = EXIT_NOMEM;
}
catch (const std::exception & ex) {
PrintOut(LOG_CRIT, "Smartd: Exception: %s\n", ex.what());
status = EXIT_BADCODE;
}
if (smart_device::get_num_objects() != 0) {
PrintOut(LOG_CRIT, "Smartd: Internal Error: %d device object(s) left at exit.\n",
smart_device::get_num_objects());
status = EXIT_BADCODE;
}
if (status == EXIT_BADCODE)
PrintOut(LOG_CRIT, "Please inform " PACKAGE_BUGREPORT ", including output of smartd -V.\n");
notify_exit(status);
#ifdef _WIN32
daemon_winsvc_exitcode = status;
#endif
return status;
}
#ifdef _WIN32
int main(int argc, char **argv){
static const daemon_winsvc_options svc_opts = {
"--service",
"smartd", "SmartD Service",
"Controls and monitors storage devices using the Self-Monitoring, "
"Analysis and Reporting Technology System (SMART) built into "
"ATA/SATA and SCSI/SAS hard drives and solid-state drives. "
"www.smartmontools.org"
};
return daemon_main("smartd", &svc_opts , smartd_main, argc, argv);
}
#endif