3 Commits

Author SHA1 Message Date
localhorst 45dac1a4a7 random 2022-08-20 10:39:26 +02:00
localhorst e7a1cb1887 memset 2022-08-20 09:59:27 +02:00
localhorst 42668e54d2 dummy code for shredding static selected drive 2022-08-19 18:38:02 +02:00
33 changed files with 2168 additions and 3208 deletions
+1 -4
View File
@@ -41,10 +41,7 @@
reHDD reHDD
*.log reHDD.log
*.ods
*.txt
.vscode/
ignoreDrives.conf ignoreDrives.conf
-3
View File
@@ -1,3 +0,0 @@
[submodule "tfnoisegen"]
path = tfnoisegen
url = https://git.mosad.xyz/localhorst/tfnoisegen.git
+15 -26
View File
@@ -1,45 +1,34 @@
# reHDD # reHDD
## Features: ## Useful for:
* show S.M.A.R.T values of attached drives * checking new drives for the first time
* checking used drives for their next live based on threshold limits * checking used drives for their next live
* delete a drive instant with wipefs
* deleting a drive securely via overwriting * deleting a drive securely via overwriting
* only needs a display and keyboard
* process multiple drives at once
## Download USB Image ##
See reHDD-Bootable how the live image is created: https://git.mosad.xyz/localhorst/reHDD-Bootable
Use [Etcher](https://www.balena.io/etcher/#download) or `dd` to create an bootable USB drive .
## Screenshot ## Screenshot
![Screenshot of reHDD with multiple drives in different states](https://git.mosad.xyz/localhorst/reHDD/raw/commit/c40dfe2cbb8f86490b49caf82db70a10015f06f9/doc/screenshot.png "Screenshot") ![alt text](https://git.mosad.xyz/localhorst/reHDD/raw/commit/42bc26eac95429e20c0f0d59f684dfec0d600e75/doc/screenshot.png "Screenshot")
## openSUSE Build Notes ## Debian Build Notes
* `zypper install ncurses-devel git make gcc-c++` * `apt-get install ncurses-dev git make g++`
* `git submodule init`
* `git submodule update`
* `make release` * `make release`
## Enable Label Printer ## ## Create Standalone with Debian 11
Just install [reHDDPrinter](https://git.mosad.xyz/localhorst/reHDDPrinter). Instructions how to create a standalone machine that boots directly to reHDD. This is aimed for production use, like several drives a day shredding.
No further settings needed. * Start reHDD after boot without login (as a tty1 shell)
* Start dmesg after boot without login (as a tty2 shell)
* Start htop after boot without login (as a tty3 shell)
* Upload reHDD log every 12h if wanted
### Software requirements ### Software requirements
* `zypper install hwinfo smartmontools curl htop sudo` * `apt-get install hwinfo smartmontools curl`
### Installation ### Installation
clone this repo into /root/ clone this repo into /root/
```
git submodule init
git submodule update
```
`cd /root/reHDD/` `cd /root/reHDD/`
`make release` `make release`
@@ -48,7 +37,7 @@ git submodule update
If you want to upload the logs, edit `scripts/reHDDLogUploader.bash` with your nextcloud token If you want to upload the logs, edit `scripts/reHDDLogUploader.bash` with your nextcloud token
Add ignored drives in `/root/reHDD/ignoreDrives.conf` like: Add your system drive in `/root/reHDD/ignoreDrives.conf` like:
```e102f49d``` ```e102f49d```
Get the first 8 Bytes from your UUID via `blkid /dev/sdX` Get the first 8 Bytes from your UUID via `blkid /dev/sdX`
+17
View File
@@ -0,0 +1,17 @@
#! /bin/bash
echo starting astyle for $PWD
astyle --style=gnu src/*.cpp
rm -f src/*.orig
astyle --style=gnu src/logger/*.cpp
rm -f src/logger/*.orig
astyle --style=gnu include/*.h
rm -f include/*.orig
astyle --style=gnu include/logger/*.h
rm -f include//logger/*.orig
echo finished astyle for $PWD
Binary file not shown.

Before

Width:  |  Height:  |  Size: 92 KiB

After

Width:  |  Height:  |  Size: 90 KiB

-1
View File
@@ -1,3 +1,2 @@
4673974d 4673974d
2cb3dea4 2cb3dea4
8ffbc421
+4 -2
View File
@@ -13,11 +13,13 @@
class Delete class Delete
{ {
protected: protected:
public: public:
static void deleteDrive(Drive *drive); static void deleteDrive(Drive* drive);
private: private:
Delete(void); Delete(void);
}; };
#endif // DELETE_H_ #endif // DELETE_H_
+51 -100
View File
@@ -14,123 +14,73 @@ class Drive
{ {
public: public:
enum class TaskState enum TaskState {NONE,
{ SHRED_SELECTED,
NONE, SHRED_ACTIVE,
SHRED_SELECTED, DELETE_SELECTED,
SHRED_ACTIVE, // shred iterations active DELETE_ACTIVE,
CHECK_ACTIVE, // optional checking active FROZEN
CHECK_SUCCESSFUL, } state;
CHECK_FAILED,
DELETE_SELECTED,
DELETE_ACTIVE,
FROZEN
};
enum class ConnectionType
{
UNKNOWN,
USB,
SATA,
NVME
};
struct ShredSpeed
{
time_t u32ShredTimeDelta;
std::chrono::time_point<std::chrono::system_clock>
chronoShredTimestamp;
unsigned long ulWrittenBytes;
unsigned long ulSpeedMetricBytesWritten;
};
std::atomic<TaskState> state;
std::atomic<ConnectionType> connectionType;
std::atomic<ShredSpeed> sShredSpeed;
bool bWasShredded = false; // all shred iterations done
bool bWasShredStarted = false; // shred was atleast once started
bool bWasChecked = false; // all shred iterations and optional checking done
bool bWasDeleted = false;
bool bIsOffline = false;
uint32_t u32DriveChecksumAfterShredding = 0U;
uint16_t u16DriveIndex = 0U; // Index of TUI list
private:
std::string sPath;
time_t u32Timestamp = 0U; // unix timestamp for detecting a frozen drive
double d32TaskPercentage = 0U; // in percent for Shred (1 to 100)
time_t u32TimestampTaskStart = 0U; // unix timestamp for duration of an action
time_t u32TaskDuration = 0U; // time needed to complete the task
struct struct
{ {
std::string sModelFamily; time_t u32ShredTimeDelta;
std::string sModelName; std::chrono::time_point<std::chrono::system_clock> chronoShredTimestamp;
std::string sSerial; unsigned long ulWrittenBytes;
uint64_t u64Capacity = 0U; // in byte } sShredSpeed;
uint32_t u32ErrorCount = 0U;
uint32_t u32PowerOnHours = 0U; // in hours bool bWasShredded = false;
uint32_t u32PowerCycles = 0U; bool bWasDeleteted = false;
uint32_t u32Temperature = 0U; // in Fahrenheit, just kidding: degree Celsius bool bIsOffline = false;
uint32_t u32ReallocatedSectors = 0U; // ID 0x05 - Reallocated Sectors Count uint32_t u32DriveChecksumAferShredding = 0U;
uint32_t u32PendingSectors = 0U; // ID 0xC5 - Current Pending Sector Count
uint32_t u32UncorrectableSectors = 0U; // ID 0xC6 - Offline Uncorrectable Sector Count private:
} sSmartData; string sPath;
string sModelFamily;
string sModelName;
string sSerial;
uint64_t u64Capacity = 0U; //in byte
uint32_t u32ErrorCount = 0U;
uint32_t u32PowerOnHours = 0U; //in hours
uint32_t u32PowerCycles = 0U;
time_t u32Timestamp = 0U; //unix timestamp for detecting a frozen drive
double d32TaskPercentage = 0U; //in percent for Shred (1 to 100)
time_t u32TimestampTaskStart = 0U; //unix timestamp for duration of an action
time_t u32TaskDuration = 0U; //time needed to complete the task
private: private:
void setTimestamp(); void setTimestamp();
protected: protected:
public: public:
// Copy constructor Drive(string path)
Drive(const Drive &other);
// Copy assignment operator
Drive &operator=(const Drive &other);
// Move constructor
Drive(Drive &&other) noexcept;
// Move assignment operator
Drive &operator=(Drive &&other) noexcept;
Drive(std::string path)
{ {
this->sPath = path; this->sPath = path;
} }
std::string getPath(void); string getPath(void);
std::string getModelFamily(void); string getModelFamily(void);
std::string getModelName(void); string getModelName(void);
std::string getSerial(void); string getSerial(void);
uint64_t getCapacity(void); // in byte uint64_t getCapacity(void); //in byte
uint32_t getErrorCount(void); uint32_t getErrorCount(void);
uint32_t getPowerOnHours(void); // in hours uint32_t getPowerOnHours(void); //in hours
uint32_t getPowerCycles(void); uint32_t getPowerCycles(void);
uint32_t getTemperature(void); // in Fahrenheit, just kidding: degree Celsius
uint32_t getReallocatedSectors(void);
uint32_t getPendingSectors(void);
uint32_t getUncorrectableSectors(void);
void checkFrozenDrive(void); void checkFrozenDrive(void);
void setDriveSMARTData(std::string modelFamily, void setDriveSMARTData( string modelFamily,
std::string modelName, string modelName,
std::string serial, string serial,
uint64_t capacity, uint64_t capacity,
uint32_t errorCount, uint32_t errorCount,
uint32_t powerOnHours, uint32_t powerOnHours,
uint32_t powerCycles, uint32_t powerCycles);
uint32_t temperature,
uint32_t reallocatedSectors,
uint32_t pendingSectors,
uint32_t uncorrectableSectors);
std::string sCapacityToText(); string sCapacityToText();
std::string sErrorCountToText(); string sErrorCountToText();
std::string sPowerOnHoursToText(); string sPowerOnHoursToText();
std::string sPowerCyclesToText(); string sPowerCyclesToText();
std::string sTemperatureToText();
void setTaskPercentage(double d32TaskPercentage); void setTaskPercentage(double d32TaskPercentage);
double getTaskPercentage(void); double getTaskPercentage(void);
@@ -140,6 +90,7 @@ public:
void calculateTaskDuration(); void calculateTaskDuration();
time_t getTaskDuration(); time_t getTaskDuration();
}; };
#endif // DRIVE_H_ #endif // DRIVE_H_
+9 -12
View File
@@ -16,10 +16,6 @@
#include <sys/socket.h> #include <sys/socket.h>
#include <arpa/inet.h> #include <arpa/inet.h>
#include <netinet/in.h> #include <netinet/in.h>
#include <ifaddrs.h>
#include <netpacket/packet.h>
#include <cstring>
#include <string>
#include <errno.h> #include <errno.h>
#include <stdlib.h> #include <stdlib.h>
#include <sys/ioctl.h> #include <sys/ioctl.h>
@@ -32,26 +28,26 @@
using namespace std; using namespace std;
#define MENU_LINE_SIZE 110 // Size of menu lines #define MENU_LINE_SIZE 110 //Size of menu lines
#ifndef LOG_PATH #ifndef LOG_PATH
// #define LOG_PATH "./test.txt" //#define LOG_PATH "./test.txt"
#endif #endif
#ifndef DESCRIPTION #ifndef DESCRIPTION
#define DESCRIPTION "Software-Name - Copyright Company 2020" // use your values here #define DESCRIPTION "Software-Name - Copyright Company 2020" //use your values here
#endif #endif
#ifndef DEVICE_ID #ifndef DEVICE_ID
#define DEVICE_ID "Device-Name" // use your values here #define DEVICE_ID "Device-Name" //use your values here
#endif #endif
#ifndef SOFTWARE_VERSION #ifndef SOFTWARE_VERSION
#define SOFTWARE_VERSION "0.1.1.8" // use your values here #define SOFTWARE_VERSION "0.1.1.8" //use your values here
#endif #endif
#ifndef HARDWARE_VERSION #ifndef HARDWARE_VERSION
#define HARDWARE_VERSION "7.77.9" // use your values here #define HARDWARE_VERSION "7.77.9" //use your values here
#endif #endif
class Logger class Logger
@@ -72,12 +68,13 @@ private:
~Logger(); ~Logger();
public: public:
void info(string s); void info(string s);
void warning(string s); void warning(string s);
void error(string s); void error(string s);
void newLine(); void newLine();
static Logger *logThis(); static Logger* logThis();
}; };
#endif // LOGGER_H_ #endif // LOGGER_H_
-56
View File
@@ -1,56 +0,0 @@
/**
* @file printer.h
* @brief Send drive data to printer service using ipc msg queue
* @author Hendrik Schutter
* @date 24.11.2022
*/
#ifndef PRINTER_H_
#define PRINTER_H_
#include "reHDD.h"
#include <sys/ipc.h>
#include <sys/msg.h>
#define STR_BUFFER_SIZE 64U
#define IPC_MSG_QUEUE_KEY 0x1B11193C0
typedef struct
{
char caDriveIndex[STR_BUFFER_SIZE];
char caDriveHours[STR_BUFFER_SIZE];
char caDriveCycles[STR_BUFFER_SIZE];
char caDriveErrors[STR_BUFFER_SIZE];
char caDriveShredTimestamp[STR_BUFFER_SIZE];
char caDriveShredDuration[STR_BUFFER_SIZE];
char caDriveCapacity[STR_BUFFER_SIZE];
char caDriveState[STR_BUFFER_SIZE];
char caDriveConnectionType[STR_BUFFER_SIZE];
char caDriveModelFamily[STR_BUFFER_SIZE];
char caDriveModelName[STR_BUFFER_SIZE];
char caDriveSerialnumber[STR_BUFFER_SIZE];
char caDriveReHddVersion[STR_BUFFER_SIZE];
} t_driveData;
typedef struct
{
long msg_queue_type;
t_driveData driveData;
} t_msgQueueData;
class Printer
{
protected:
public:
static Printer *getPrinter();
void print(Drive *drive);
private:
static bool instanceFlag;
static Printer *single;
int msqid;
Printer();
~Printer();
};
#endif // PRINTER_H_
+32 -39
View File
@@ -8,34 +8,32 @@
#ifndef REHDD_H_ #ifndef REHDD_H_
#define REHDD_H_ #define REHDD_H_
#define REHDD_VERSION "V1.4.0" #define REHDD_VERSION "bV0.2.2"
// Drive handling Settings // Drive handling Settings
#define WORSE_HOURS 19200 // mark drive if at this limit or beyond #define WORSE_HOURS 19200 //mark drive if at this limit or beyond
#define WORSE_POWERUP 10000 // mark drive if at this limit or beyond #define WORSE_POWERUP 10000 //mark drive if at this limit or beyond
#define WORSE_TEMPERATURE 55 // mark drive if at this limit or beyond #define SHRED_ITERATIONS 1U
#define SHRED_ITERATIONS 3U #define FROZEN_TIMEOUT 10 //After this timeout (minutes) the drive will be marked as frozen
#define FROZEN_TIMEOUT 20 // After this timeout (minutes) the drive will be marked as frozen, if no progress
#define METRIC_THRESHOLD 3L * 1000L * 1000L * 1000L // calc shred speed with this minimum of time delta
// Logger Settings // Logger Settings
#define LOG_PATH "./reHDD.log" #define LOG_PATH "./reHDD.log"
#define DESCRIPTION "reHDD - Copyright Hendrik Schutter 2026" #define DESCRIPTION "reHDD - Copyright Hendrik Schutter 2022"
#define DEVICE_ID "generic" #define DEVICE_ID "generic"
#define SOFTWARE_VERSION REHDD_VERSION #define SOFTWARE_VERSION "alpha"
#define HARDWARE_VERSION "generic" #define HARDWARE_VERSION "generic"
// #define LOG_LEVEL_HIGH // log everything, like drive scan thread //#define LOG_LEVEL_HIGH //log everything, like drive scan thread
#ifndef LOG_LEVEL_HIGH #ifndef LOG_LEVEL_HIGH
#define LOG_LEVEL_LOW // log only user actions and tasks #define LOG_LEVEL_LOW //log only user actions and tasks
#endif #endif
// Logic // Logic
// #define DRYRUN // don't touch the drives //#define DRYRUN //don´t touch the drives
#define FROZEN_ALERT // show alert if drive is frozen #define FROZEN_ALERT //show alert if drive is frozen
#define ZERO_CHECK // check drive after shred if all bytes are zero, show alert if this fails #define ZERO_CHECK_ALERT //check drive after shred if all bytes are zero, show alert if this fails
// IPC pipes //IPC pipes
#define READ 0 #define READ 0
#define WRITE 1 #define WRITE 1
@@ -56,19 +54,19 @@
#include <sstream> #include <sstream>
#include <iomanip> #include <iomanip>
#include <signal.h> #include <signal.h>
#include <atomic>
using namespace std;
#include "drive.h" #include "drive.h"
#include "smart.h" #include "smart.h"
#include "shred.h" #include "shred.h"
#include "delete.h" #include "delete.h"
#include "tui.h" #include "tui.h"
#include "printer.h"
#include "logger/logger.h" #include "logger/logger.h"
extern Logger *logging; extern Logger* logging;
template <typename T, typename I> template <typename T, typename I> T* iterator_to_pointer(I i)
T *iterator_to_pointer(I i)
{ {
return (&(*i)); return (&(*i));
} }
@@ -76,33 +74,28 @@ T *iterator_to_pointer(I i)
class reHDD class reHDD
{ {
protected: protected:
public: public:
reHDD(void); reHDD(void);
static void app_logic(); static void app_logic();
private: private:
static void searchDrives(list<Drive> *plistDrives);
static void printDrives(list<Drive> *plistDrives); static void searchDrives(list <Drive>* plistDrives);
static void startShredAllDrives(list<Drive> *plistDrives); static void printDrives(list <Drive>* plistDrives);
static void stopShredAllDrives(list<Drive> *plistDrives); static void filterIgnoredDrives(list <Drive>* plistDrives);
static void updateShredMetrics(list<Drive> *plistDrives); static void filterNewDrives(list <Drive>* plistOldDrives, list <Drive>* plistNewDrives);
static void filterIgnoredDrives(list<Drive> *plistDrives); static void addSMARTData(list <Drive>* plistDrives);
static void filterInvalidDrives(list<Drive> *plistDrives); static void ThreadScannDevices();
static void filterNewDrives(list<Drive> *plistOldDrives, list<Drive> *plistNewDrives);
static void addSMARTData(list<Drive> *plistDrives);
static void printAllDrives(list<Drive> *plistDrives);
static void printDrive(Drive *const pDrive);
static void ThreadScanDevices();
static void ThreadUserInput(); static void ThreadUserInput();
static void ThreadShred(Drive *const pDrive); static void ThreadShred();
static void ThreadDelete(Drive *const pDrive); static void ThreadDelete();
static void ThreadCheckFrozenDrives(); static void ThreadCheckFrozenDrives();
static void handleArrowKey(TUI::UserInput userInput); static void handleArrowKey(TUI::UserInput userInput);
static void handleEnter(); static void handleEnter();
static void handleESC(); static void handleESC();
static void handleAbort(); static void handleAbort();
static Drive *getSelectedDrive(); static Drive* getSelectedDrive();
static bool getSystemDrive(string &systemDrive);
}; };
#endif // REHDD_H_ #endif // REHDD_H_
+14 -57
View File
@@ -16,84 +16,41 @@
#include <fcntl.h> #include <fcntl.h>
#include <unistd.h> #include <unistd.h>
#include <string.h> #include <string.h>
#include <chrono>
// Adaptive chunk size optimization with multi-armed bandit - always enabled #define CHUNK_SIZE 1024*1024*2 //amount of bytes that are overwritten at once --> 2MB
// Chunk size configuration #define CHUNK_DIMENSION 100U //amount of chunks are read at once from random source
#define CHUNK_SIZE_START 1024 * 1024 * 32 // Starting chunk size: 32MB
#define CHUNK_SIZE_MIN 1024 * 1024 * 16 // Minimum chunk size: 16MB (increased from 4MB to prevent premature convergence)
#define CHUNK_SIZE_MAX 1024 * 1024 * 128 // Maximum chunk size: 128MB
#define CHUNK_SIZE_STEP_UP 1024 * 1024 * 4 // Increase step: 4MB (symmetric with step down)
#define CHUNK_SIZE_STEP_DOWN 1024 * 1024 * 4 // Decrease step: 4MB (symmetric exploration)
#define CHUNK_MEASURE_INTERVAL 64 // Measure performance every 64 chunks
#define WARMUP_MEASUREMENTS 16 // Skip first 16 measurements (cache writes)
// Multi-armed bandit exploration parameters //#define DEMO_DRIVE_SIZE 1024*1024*256L // 256MB
#define EXPLORATION_EPSILON 0.10 // 10% exploration rate (epsilon-greedy) //#define DEMO_DRIVE_SIZE 1024*1024*1024L // 1GB
#define REEXPLORATION_INTERVAL 500 // Force re-exploration every 500 chunks //#define DEMO_DRIVE_SIZE 1024*1024*1024*10L // 10GB
// Buffer sizes - always use maximum for adaptive mode
#define CHUNK_SIZE CHUNK_SIZE_MAX
#define TFNG_DATA_SIZE CHUNK_SIZE_MAX
// #define DEMO_DRIVE_SIZE 1024*1024*256L // 256MB
// #define DEMO_DRIVE_SIZE 1024*1024*1024L // 1GB
// #define DEMO_DRIVE_SIZE 5*1024*1024*1024L // 5GB
// #define DEMO_DRIVE_SIZE 1024*1024*1024*10L // 10GB
typedef int fileDescriptor; typedef int fileDescriptor;
class Shred class Shred
{ {
protected: protected:
public: public:
Shred(); Shred();
~Shred(); ~Shred();
int shredDrive(Drive *drive, int *ipSignalFd); int shredDrive(Drive* drive, int* ipSignalFd);
private: private:
fileDescriptor randomSrcFileDiscr; fileDescriptor randomSrcFileDiscr;
fileDescriptor driveFileDiscr; fileDescriptor driveFileDiscr;
unsigned char caChunk[CHUNK_DIMENSION][CHUNK_SIZE];
unsigned char *caTfngData;
unsigned char *caReadBuffer;
unsigned long ulDriveByteSize; unsigned long ulDriveByteSize;
unsigned long ulDriveByteOverallCount = 0; // all bytes shredded in all iterations + checking -> used for progress calculation unsigned long ulDriveByteOverallCount = 0; //all bytes shredded in all iterations + checking -> used for progress calculation
double d32Percent = 0.0; double d32Percent = 0.0;
double d32TmpPercent = 0.0; double d32TmpPercent = 0.0;
// Adaptive chunk size optimization members
size_t currentChunkSize;
size_t bestChunkSize;
unsigned int chunkCounter;
unsigned int totalChunkCounter; // Total chunks written (for periodic re-exploration)
unsigned int warmupCounter; // Count warm-up measurements
std::chrono::high_resolution_clock::time_point measurementStartTime;
double bestThroughputMBps;
double lastThroughputMBps;
unsigned long bytesWrittenInMeasurement;
bool throughputIncreasing;
// Multi-armed bandit exploration state
bool explorationMode; // Currently in exploration mode?
size_t explorationChunkSize; // Chunk size being tested during exploration
// Adaptive methods
void startMeasurement();
void evaluateThroughput(Drive *drive);
void adjustChunkSize(Drive *drive);
size_t getCurrentChunkSize() const;
// Multi-armed bandit methods
bool shouldExplore(); // Decide: explore or exploit?
void performExploration(Drive *drive); // Execute exploration phase
inline double calcProgress(); inline double calcProgress();
int iRewindDrive(fileDescriptor file); int iRewindDrive(fileDescriptor file);
long getDriveSizeInBytes(fileDescriptor file); unsigned long getDriveSizeInBytes(fileDescriptor file);
unsigned int uiCalcChecksum(fileDescriptor file, Drive *drive, int *ipSignalFd); unsigned int uiCalcChecksum(fileDescriptor file, Drive* drive, int* ipSignalFd);
void cleanup(); void cleanup();
}; };
#endif // SHRED_H_ #endif // SHRED_H_
+20 -18
View File
@@ -10,29 +10,31 @@
#include "reHDD.h" #include "reHDD.h"
/**
* @brief SMART data reader for drives
*
* Parses smartctl JSON output to extract:
* - Device information (model, serial, capacity)
* - Power statistics (hours, cycles)
* - Temperature
* - Critical sector counts (reallocated, pending, uncorrectable)
*
* Uses deterministic state machine parser for reliable multi-line JSON parsing.
*/
class SMART class SMART
{ {
protected: protected:
public: public:
/** static void readSMARTData(Drive* drive);
* @brief Read S.M.A.R.T. data from drive and populate Drive object
* @param drive Pointer to Drive instance to populate with SMART data
*/
static void readSMARTData(Drive *drive);
private: private:
SMART(void); // Utility class - no instances SMART(void);
static void parseModelFamily(string sLine);
static void parseModelName(string sLine);
static void parseSerial(string sLine);
static void parseCapacity(string sLine);
static void parseErrorCount(string sLine);
static void parsePowerOnHours(string sLine);
static void parsePowerCycle(string sLine);
static string modelFamily;
static string modelName;
static string serial;
static uint64_t capacity;
static uint32_t errorCount;
static uint32_t powerOnHours;
static uint32_t powerCycle;
}; };
#endif // SMART_H_ #endif // SMART_H_
+30 -45
View File
@@ -12,30 +12,17 @@
#define COLOR_AREA_STDSCR 1 #define COLOR_AREA_STDSCR 1
#define COLOR_AREA_OVERVIEW 2 #define COLOR_AREA_OVERVIEW 2
#define COLOR_AREA_ENTRY_EVEN 3 #define COLOR_AREA_ENTRY 3
#define COLOR_AREA_ENTRY_ODD 4 #define COLOR_AREA_ENTRY_SELECTED 4
#define COLOR_AREA_ENTRY_SELECTED 5 #define COLOR_AREA_DETAIL 5
#define COLOR_AREA_DETAIL 6
class TUI class TUI
{ {
protected: protected:
public: public:
enum UserInput
{ enum UserInput { UpKey, DownKey, Abort, Shred, Delete, Enter, ESC, Undefined};
UpKey,
DownKey,
Abort,
Shred,
ShredAll,
Delete,
Enter,
ESC,
Terminate,
Print,
PrintAll,
Undefined
};
struct MenuState struct MenuState
{ {
bool bAbort; bool bAbort;
@@ -49,39 +36,37 @@ public:
static void initTUI(); static void initTUI();
void updateTUI(std::list<Drive> *plistDrives, uint8_t u8SelectedEntry); void updateTUI(list <Drive>* plistDrives, uint8_t u8SelectedEntry);
static enum UserInput readUserInput(); static enum UserInput readUserInput();
static void terminateTUI();
private: private:
static std::string sCpuUsage; static string sCpuUsage;
static std::string sRamUsage; static string sRamUsage;
static std::string sLocalTime; static string sLocalTime;
WINDOW *overview; WINDOW* overview;
WINDOW *systemview; WINDOW* systemview;
WINDOW *detailview; WINDOW* detailview;
WINDOW *menuview; WINDOW* menuview;
WINDOW *dialog; WINDOW* dialog;
WINDOW *smartWarning; WINDOW* smartWarning;
static void centerTitle(WINDOW *pwin, const char *title); static void centerTitle(WINDOW *pwin, const char * title);
static WINDOW *createOverViewWindow(int iXSize, int iYSize); static WINDOW *createOverViewWindow( int iXSize, int iYSize);
static WINDOW *createDetailViewWindow(int iXSize, int iYSize, int iXStart, Drive &drive); static WINDOW *createDetailViewWindow( int iXSize, int iYSize, int iXStart, Drive drive);
static WINDOW *overwriteDetailViewWindow(int iXSize, int iYSize, int iXStart); static WINDOW *overwriteDetailViewWindow( int iXSize, int iYSize, int iXStart);
static WINDOW *createEntryWindow(int iXSize, int iYSize, int iXStart, int iYStart, int iListIndex, std::string sModelFamily, std::string sSerial, std::string sCapacity, std::string sState, std::string sTime, std::string sSpeed, std::string sTemp, std::string sConnection, bool bSelected); static WINDOW *createEntryWindow(int iXSize, int iYSize, int iXStart, int iYStart, string sModelFamily, string sModelName, string sCapacity, string sState, string sTime, string sSpeed, bool bSelected);
static WINDOW *createSystemStats(int iXSize, int iYSize, int iXStart, int iYStart); static WINDOW *createSystemStats(int iXSize, int iYSize, int iXStart, int iYStart);
static WINDOW *createMenuView(int iXSize, int iYSize, int iXStart, int iYStart, struct MenuState menustate); static WINDOW *createMenuView(int iXSize, int iYSize, int iXStart, int iYStart, struct MenuState menustate);
static WINDOW *createDialog(int iXSize, int iYSize, int iXStart, int iYStart, std::string selectedTask, std::string optionA, std::string optionB); static WINDOW *createDialog(int iXSize, int iYSize, int iXStart, int iYStart, string selectedTask, string optionA, string optionB);
static WINDOW *createFrozenWarning(int iXSize, int iYSize, int iXStart, int iYStart, std::string sPath, std::string sModelFamily, std::string sModelName, std::string sSerial, std::string sProgress); static WINDOW* createFrozenWarning(int iXSize, int iYSize, int iXStart, int iYStart, string sPath, string sModelFamily, string sModelName, string sSerial, string sProgress);
static WINDOW *createSmartWarning(int iXSize, int iYSize, int iXStart, int iYStart, std::string sPath, uint32_t u32PowerOnHours, uint32_t u32PowerCycles, uint32_t u32ErrorCount, uint32_t u32Temperature, uint32_t u32ReallocatedSectors, uint32_t u32PendingSectors, uint32_t u32UncorrectableSectors); static WINDOW* createSmartWarning(int iXSize, int iYSize, int iXStart, int iYStart, string sPath, uint32_t u32PowerOnHours, uint32_t u32PowerCycles, uint32_t u32ErrorCount);
static WINDOW *createZeroChecksumWarning(int iXSize, int iYSize, int iXStart, int iYStart, std::string sPath, std::string sModelFamily, std::string sModelName, std::string sSerial, uint32_t u32Checksum); static WINDOW* createZeroChecksumWarning(int iXSize, int iYSize, int iXStart, int iYStart, string sPath, string sModelFamily, string sModelName, string sSerial, uint32_t u32Checksum);
void displaySelectedDrive(Drive drive, int stdscrX, int stdscrY);
string formatTimeDuration(time_t u32Duration);
string formatSpeed(time_t u32ShredTimeDelta, unsigned long ulWrittenBytes);
void displaySelectedDrive(Drive &drive, int stdscrX, int stdscrY);
std::string formatTimeDuration(time_t u32Duration);
std::string formatSpeed(time_t u32ShredTimeDelta, unsigned long ulWrittenBytes);
static void vTruncateText(std::string *psText, uint16_t u16MaxLenght);
}; };
#endif // TUI_H_ #endif // TUI_H_
+6 -16
View File
@@ -1,6 +1,6 @@
#### PROJECT SETTINGS #### #### PROJECT SETTINGS ####
# The name of the executable to be created # The name of the executable to be created
BIN_NAME := reHDD BIN_NAME := shredTest
# Compiler used # Compiler used
CXX ?= g++ CXX ?= g++
# Extension of source files used in the project # Extension of source files used in the project
@@ -8,22 +8,19 @@ SRC_EXT = cpp
# Path to the source directory, relative to the makefile # Path to the source directory, relative to the makefile
SRC_PATH = src SRC_PATH = src
# Space-separated pkg-config libraries used by this project # Space-separated pkg-config libraries used by this project
LIBS = lib LIBS =
# General compiler flags # General compiler flags
COMPILE_FLAGS = -std=c++23 -Wall -Wextra -g COMPILE_FLAGS = -std=c++17 -Wall -Wextra -g
# Additional release-specific flags # Additional release-specific flags
RCOMPILE_FLAGS = -D NDEBUG -Ofast RCOMPILE_FLAGS = -D NDEBUG -O3
# Additional debug-specific flags # Additional debug-specific flags
DCOMPILE_FLAGS = -D DEBUG DCOMPILE_FLAGS = -D DEBUG
# Add additional include paths # Add additional include paths
INCLUDES = include INCLUDES = include
# General linker settings # General linker settings
LINK_FLAGS = -Llib -lpthread -lncurses -ltfng -latomic LINK_FLAGS = -lpthread -lncurses
# Doc # Doc
DOCDIR = doc DOCDIR = doc
TFRANDDIR = tfnoisegen
TFRANDLIB = libtfng.a
#### END PROJECT SETTINGS #### #### END PROJECT SETTINGS ####
# Optionally you may move the section above to a separate config.mk file, and # Optionally you may move the section above to a separate config.mk file, and
@@ -54,7 +51,7 @@ ifeq ($(V),true)
endif endif
# Combine compiler and linker flags # Combine compiler and linker flags
release: export CXXFLAGS := $(CXXFLAGS) $(COMPILE_FLAGS) $(RCOMPILE_FLAGS) release: export CXXFLAGS := $(CXXFLAGS) $(COMPILE_FLAGS) $(RCOMPILE_FLAGS)
release: export LDFLAGS := $(LDFLAGS) $(LINK_FLAGS) $(RLINK_FLAGS) release: export LDFLAGS := $(LDFLAGS) $(LINK_FLAGS) $(RLINK_FLAGS)
debug: export CXXFLAGS := $(CXXFLAGS) $(COMPILE_FLAGS) $(DCOMPILE_FLAGS) debug: export CXXFLAGS := $(CXXFLAGS) $(COMPILE_FLAGS) $(DCOMPILE_FLAGS)
debug: export LDFLAGS := $(LDFLAGS) $(LINK_FLAGS) $(DLINK_FLAGS) debug: export LDFLAGS := $(LDFLAGS) $(LINK_FLAGS) $(DLINK_FLAGS)
@@ -161,7 +158,6 @@ dirs:
@echo "Creating directories" @echo "Creating directories"
@mkdir -p $(dir $(OBJECTS)) @mkdir -p $(dir $(OBJECTS))
@mkdir -p $(BIN_PATH) @mkdir -p $(BIN_PATH)
@mkdir -p $(LIBS)
# Removes all build files # Removes all build files
.PHONY: clean .PHONY: clean
@@ -171,22 +167,16 @@ clean:
@echo "Deleting directories" @echo "Deleting directories"
@$(RM) -r build @$(RM) -r build
@$(RM) -r bin @$(RM) -r bin
@$(RM) -r $(LIBS)
@$(RM) -f reHDD.log @$(RM) -f reHDD.log
$(MAKE) clean -C tfnoisegen
# Main rule, checks the executable and symlinks to the output # Main rule, checks the executable and symlinks to the output
all: $(BIN_PATH)/$(BIN_NAME) all: $(BIN_PATH)/$(BIN_NAME)
$(MAKE) libtfng.a -C tfnoisegen
@cp $(TFRANDDIR)/$(TFRANDLIB) $(LIBS)
@echo "Making symlink: $(BIN_NAME) -> $<" @echo "Making symlink: $(BIN_NAME) -> $<"
@$(RM) $(BIN_NAME) @$(RM) $(BIN_NAME)
@ln -s $(BIN_PATH)/$(BIN_NAME) $(BIN_NAME) @ln -s $(BIN_PATH)/$(BIN_NAME) $(BIN_NAME)
# Link the executable # Link the executable
$(BIN_PATH)/$(BIN_NAME): $(OBJECTS) $(BIN_PATH)/$(BIN_NAME): $(OBJECTS)
$(MAKE) libtfng.a -C tfnoisegen
@cp $(TFRANDDIR)/$(TFRANDLIB) $(LIBS)
@echo "Linking: $@" @echo "Linking: $@"
@$(START_TIME) @$(START_TIME)
$(CMD_PREFIX)$(CXX) $(OBJECTS) $(LDFLAGS) -o $@ $(CMD_PREFIX)$(CXX) $(OBJECTS) $(LDFLAGS) -o $@
Symlink
+1
View File
@@ -0,0 +1 @@
bin/release/reHDDShred
+1108
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -4,7 +4,7 @@ Description=dmesg on tty2
[Service] [Service]
WorkingDirectory=/usr/bin/ WorkingDirectory=/usr/bin/
ExecStart= ExecStart=
ExecStart=-/usr/bin/dmesg -wHT ExecStart=-/usr/bin/dmesg -wH
StandardInput=tty StandardInput=tty
StandardOutput=tty StandardOutput=tty
Restart=always Restart=always
+6
View File
@@ -0,0 +1,6 @@
#!/bin/bash
# remove comment for the following to activate log telemetie
curl -k -T /root/reHDD/reHDD.log -u "__Place_your_token_here__:" -H 'X-Requested-With: XMLHttpRequest' https://schuttercloud.com/public.php/webdav/`echo $(date '+%Y-%m-%d_%H-%M')`_reHDD.log
rm -f /root/reHDD/reHDD.log
+18
View File
@@ -0,0 +1,18 @@
[Unit]
Description=reHDD log uploader
After=syslog.target
After=network.target
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
User=root
Group=root
RemainAfterExit=yes
ExecStart=/usr/bin/bash /root/reHDD/scripts/reHDDLogUploader.bash
[Install]
WantedBy=multi-user.target
+11
View File
@@ -0,0 +1,11 @@
[Unit]
Description=reHDD log uploader timer
[Timer]
OnActiveSec=30s
OnBootSec=10min
OnUnitActiveSec=12h
[Install]
WantedBy=basic.target
+2 -8
View File
@@ -6,9 +6,9 @@ systemctl stop /lib/systemd/system/getty@tty1.service.d
cd /root/reHDD/ cd /root/reHDD/
FILE=../ignoreDrives.conf FILE=./ignoreDrives.conf
if test -f "$FILE"; then if test -f "$FILE"; then
echo "backup exits already" echo backup exits
else else
cp /root/reHDD/ignoreDrives.conf /root/ignoreDrives.conf cp /root/reHDD/ignoreDrives.conf /root/ignoreDrives.conf
fi fi
@@ -23,12 +23,6 @@ git checkout master
git pull git pull
git submodule init
git submodule update
make clean
make release make release
cp /root/ignoreDrives.conf /root/reHDD/ignoreDrives.conf cp /root/ignoreDrives.conf /root/reHDD/ignoreDrives.conf
Symlink
+1
View File
@@ -0,0 +1 @@
bin/release/shredTest
+10 -17
View File
@@ -6,18 +6,17 @@
*/ */
#include "../include/reHDD.h" #include "../include/reHDD.h"
using namespace std;
/** /**
* \brief delete drive with wipefs * \brief delete drive with wipefs
* \param pointer of Drive instance * \param pointer of Drive instance
* \return void * \return void
*/ */
void Delete::deleteDrive(Drive *drive) void Delete::deleteDrive(Drive* drive)
{ {
size_t len = 0; // lenght of found line size_t len = 0; //lenght of found line
char *cLine = NULL; // found line char* cLine = NULL; //found line
#ifndef DRYRUN #ifndef DRYRUN
string sCMD = ("wipefs -af "); string sCMD = ("wipefs -af ");
@@ -26,24 +25,18 @@ void Delete::deleteDrive(Drive *drive)
#endif #endif
#ifdef DRYRUN #ifdef DRYRUN
// cout << "dryrun for " << drive->getPath() << endl; //cout << "dryrun for " << drive->getPath() << endl;
string sCMD = ("echo"); string sCMD = ("echo");
#endif #endif
const char *cpComand = sCMD.c_str(); const char* cpComand = sCMD.c_str();
// cout << "delete: " << cpComand << endl; //cout << "delete: " << cpComand << endl;
if (drive->bWasShredStarted == false) FILE* deleteCmdOutput = popen(cpComand, "r");
{
// only start delete if the drive was not shredded before
FILE *deleteCmdOutput = popen(cpComand, "r");
while ((getline(&cLine, &len, deleteCmdOutput)) != -1) while ((getline(&cLine, &len, deleteCmdOutput)) != -1)
{ {
// wipefs running //wipefs running
} }
pclose(deleteCmdOutput);
free(cLine);
pclose(deleteCmdOutput);
}
} }
+50 -191
View File
@@ -6,95 +6,6 @@
*/ */
#include "../include/reHDD.h" #include "../include/reHDD.h"
using namespace std;
// Copy constructor
Drive::Drive(const Drive &other)
: state(other.state.load()),
connectionType(other.connectionType.load()),
sShredSpeed(other.sShredSpeed.load()),
bWasShredded(other.bWasShredded),
bWasShredStarted(other.bWasShredStarted),
bWasChecked(other.bWasChecked),
bWasDeleted(other.bWasDeleted),
bIsOffline(other.bIsOffline),
u32DriveChecksumAfterShredding(other.u32DriveChecksumAfterShredding),
sPath(other.sPath),
u32Timestamp(other.u32Timestamp),
d32TaskPercentage(other.d32TaskPercentage),
u32TimestampTaskStart(other.u32TimestampTaskStart),
u32TaskDuration(other.u32TaskDuration),
sSmartData(other.sSmartData)
{
}
// Copy assignment operator
Drive &Drive::operator=(const Drive &other)
{
if (this != &other)
{
state = other.state.load();
connectionType = other.connectionType.load();
sShredSpeed = other.sShredSpeed.load();
bWasShredded = other.bWasShredded;
bWasShredStarted = other.bWasShredStarted;
bWasChecked = other.bWasChecked;
bWasDeleted = other.bWasDeleted;
bIsOffline = other.bIsOffline;
u32DriveChecksumAfterShredding = other.u32DriveChecksumAfterShredding;
sPath = other.sPath;
u32Timestamp = other.u32Timestamp;
d32TaskPercentage = other.d32TaskPercentage;
u32TimestampTaskStart = other.u32TimestampTaskStart;
u32TaskDuration = other.u32TaskDuration;
sSmartData = other.sSmartData;
}
return *this;
}
// Move constructor
Drive::Drive(Drive &&other) noexcept
: state(other.state.load()),
connectionType(other.connectionType.load()),
sShredSpeed(other.sShredSpeed.load()),
bWasShredded(other.bWasShredded),
bWasShredStarted(other.bWasShredStarted),
bWasChecked(other.bWasChecked),
bWasDeleted(other.bWasDeleted),
bIsOffline(other.bIsOffline),
u32DriveChecksumAfterShredding(other.u32DriveChecksumAfterShredding),
sPath(std::move(other.sPath)),
u32Timestamp(other.u32Timestamp),
d32TaskPercentage(other.d32TaskPercentage),
u32TimestampTaskStart(other.u32TimestampTaskStart),
u32TaskDuration(other.u32TaskDuration),
sSmartData(std::move(other.sSmartData))
{
}
// Move assignment operator
Drive &Drive::operator=(Drive &&other) noexcept
{
if (this != &other)
{
state = other.state.load();
connectionType = other.connectionType.load();
sShredSpeed = other.sShredSpeed.load();
bWasShredded = other.bWasShredded;
bWasShredStarted = other.bWasShredStarted;
bWasChecked = other.bWasChecked;
bWasDeleted = other.bWasDeleted;
bIsOffline = other.bIsOffline;
u32DriveChecksumAfterShredding = other.u32DriveChecksumAfterShredding;
sPath = std::move(other.sPath);
u32Timestamp = other.u32Timestamp;
d32TaskPercentage = other.d32TaskPercentage;
u32TimestampTaskStart = other.u32TimestampTaskStart;
u32TaskDuration = other.u32TaskDuration;
sSmartData = std::move(other.sSmartData);
}
return *this;
}
string Drive::getPath(void) string Drive::getPath(void)
{ {
@@ -103,75 +14,51 @@ string Drive::getPath(void)
string Drive::getModelFamily(void) string Drive::getModelFamily(void)
{ {
return sSmartData.sModelFamily; return sModelFamily;
} }
string Drive::getModelName(void) string Drive::getModelName(void)
{ {
return sSmartData.sModelName; return sModelName;
} }
string Drive::getSerial(void) string Drive::getSerial(void)
{ {
return sSmartData.sSerial; return sSerial;
} }
uint64_t Drive::getCapacity(void) uint64_t Drive::getCapacity(void)
{ {
return sSmartData.u64Capacity; return u64Capacity;
} }
uint32_t Drive::getErrorCount(void) uint32_t Drive::getErrorCount(void)
{ {
return sSmartData.u32ErrorCount; return u32ErrorCount;
} }
uint32_t Drive::getPowerOnHours(void) uint32_t Drive::getPowerOnHours(void)
{ {
return sSmartData.u32PowerOnHours; return u32PowerOnHours;
} }
uint32_t Drive::getPowerCycles(void) uint32_t Drive::getPowerCycles(void)
{ {
return sSmartData.u32PowerCycles; return u32PowerCycles;
}
uint32_t Drive::getTemperature(void)
{
return sSmartData.u32Temperature;
}
uint32_t Drive::getReallocatedSectors(void)
{
return sSmartData.u32ReallocatedSectors;
}
uint32_t Drive::getPendingSectors(void)
{
return sSmartData.u32PendingSectors;
}
uint32_t Drive::getUncorrectableSectors(void)
{
return sSmartData.u32UncorrectableSectors;
} }
string Drive::sCapacityToText() string Drive::sCapacityToText()
{ {
char acBuffer[16]; char acBuffer[16];
double dSize = (double)getCapacity(); double dSize = (double) getCapacity();
uint16_t u16UnitIndex = 0; uint16_t u16UnitIndex = 0;
const char *units[] = {"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}; const char* units[] = {"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
while (dSize >= 1000) // using the marketing capacity while (dSize >= 1000) //using the marketing capacity
{ {
dSize /= 1000; dSize /= 1000;
u16UnitIndex++; u16UnitIndex++;
} }
if (u16UnitIndex >= 9)
{ sprintf(acBuffer, "%.*f %s", u16UnitIndex-3, dSize, units[u16UnitIndex]);
u16UnitIndex = 8;
}
int precision = (u16UnitIndex >= 3) ? (u16UnitIndex - 3) : 0;
sprintf(acBuffer, "%.*f %s", precision, dSize, units[u16UnitIndex]);
return acBuffer; return acBuffer;
} }
@@ -180,6 +67,7 @@ string Drive::sErrorCountToText()
return to_string(getErrorCount()); return to_string(getErrorCount());
} }
string Drive::sPowerOnHoursToText() string Drive::sPowerOnHoursToText()
{ {
double dDays = 0U; double dDays = 0U;
@@ -188,8 +76,8 @@ string Drive::sPowerOnHoursToText()
stringstream streamDays; stringstream streamDays;
stringstream streamYears; stringstream streamYears;
dDays = (double)((double)u32Hours / (double)24U); dDays = (double) ((double)u32Hours/(double)24U);
dYears = (double)((double)u32Hours / (double)8760U); dYears = (double) ((double)u32Hours/(double)8760U);
streamDays << fixed << setprecision(0) << dDays; streamDays << fixed << setprecision(0) << dDays;
streamYears << fixed << setprecision(1) << dYears; streamYears << fixed << setprecision(1) << dYears;
@@ -204,24 +92,20 @@ string Drive::sPowerCyclesToText()
return to_string(getPowerCycles()); return to_string(getPowerCycles());
} }
string Drive::sTemperatureToText()
{
return to_string(getTemperature()) + " C";
}
void Drive::setTaskPercentage(double d32TaskPercentage) void Drive::setTaskPercentage(double d32TaskPercentage)
{ {
if (d32TaskPercentage <= 100) if(d32TaskPercentage <= 100)
{ {
this->d32TaskPercentage = d32TaskPercentage; this->d32TaskPercentage = d32TaskPercentage;
this->setTimestamp(); // set timestamp for this progress for detecting a frozen drive this->setTimestamp(); //set timestamp for this progress for detecting a frozen drive
} }
} }
double Drive::getTaskPercentage(void) double Drive::getTaskPercentage(void)
{ {
return this->d32TaskPercentage; return this->d32TaskPercentage;
} }
/** /**
* \brief set S.M.A.R.T. values in model * \brief set S.M.A.R.T. values in model
* \param string modelFamily * \param string modelFamily
@@ -231,50 +115,34 @@ double Drive::getTaskPercentage(void)
* \param uint32_t errorCount * \param uint32_t errorCount
* \param uint32_t powerOnHours * \param uint32_t powerOnHours
* \param uint32_t powerCycle * \param uint32_t powerCycle
* \param uint32_t temperature
* \return void * \return void
*/ */
void Drive::setDriveSMARTData(string modelFamily, void Drive::setDriveSMARTData( string modelFamily,
string modelName, string modelName,
string serial, string serial,
uint64_t capacity, uint64_t capacity,
uint32_t errorCount, uint32_t errorCount,
uint32_t powerOnHours, uint32_t powerOnHours,
uint32_t powerCycle, uint32_t powerCycle)
uint32_t temperature,
uint32_t reallocatedSectors,
uint32_t pendingSectors,
uint32_t uncorrectableSectors)
{ {
this->sSmartData.sModelFamily = modelFamily; this->sModelFamily = modelFamily;
this->sSmartData.sModelName = modelName; sModelName = modelName;
this->sSmartData.sSerial = serial; sSerial = serial;
this->sSmartData.u64Capacity = capacity; u64Capacity = capacity;
this->sSmartData.u32ErrorCount = errorCount; u32ErrorCount = errorCount;
this->sSmartData.u32PowerOnHours = powerOnHours; u32PowerOnHours = powerOnHours;
this->sSmartData.u32PowerCycles = powerCycle; u32PowerCycles = powerCycle;
this->sSmartData.u32Temperature = temperature;
this->sSmartData.u32ReallocatedSectors = reallocatedSectors;
this->sSmartData.u32PendingSectors = pendingSectors;
this->sSmartData.u32UncorrectableSectors = uncorrectableSectors;
} }
void Drive::setTimestamp() void Drive::setTimestamp()
{ {
if (time(&this->u32Timestamp) == -1) time(&this->u32Timestamp);
{
// handle error
this->u32Timestamp = 0U;
}
} }
void Drive::setActionStartTimestamp() void Drive::setActionStartTimestamp()
{ {
if (time(&this->u32TimestampTaskStart) == -1) time(&this->u32TimestampTaskStart);
{
// handle error
this->u32TimestampTaskStart = 0U;
}
} }
time_t Drive::getActionStartTimestamp() time_t Drive::getActionStartTimestamp()
@@ -285,11 +153,7 @@ time_t Drive::getActionStartTimestamp()
void Drive::calculateTaskDuration() void Drive::calculateTaskDuration()
{ {
time_t u32localtime; time_t u32localtime;
if (time(&u32localtime) == -1) time(&u32localtime);
{
// handle error
u32localtime = 0U;
}
this->u32TaskDuration = u32localtime - this->u32TimestampTaskStart; this->u32TaskDuration = u32localtime - this->u32TimestampTaskStart;
} }
@@ -303,17 +167,12 @@ void Drive::checkFrozenDrive(void)
{ {
time_t u32localtime; time_t u32localtime;
time(&u32localtime); time(&u32localtime);
if (time(&u32localtime) == -1)
{
// handle error
u32localtime = 0U;
}
if ((u32localtime - this->u32Timestamp) >= (FROZEN_TIMEOUT * 60) && (this->u32Timestamp > 0) && (this->getTaskPercentage() < 100.0)) if((u32localtime - this->u32Timestamp) >= (FROZEN_TIMEOUT*60) && (this->u32Timestamp > 0))
{ {
Logger::logThis()->warning("Drive Frozen: " + this->getModelName() + " " + this->getSerial()); Logger::logThis()->warning("Drive Frozen: " + this->getModelName() + " " + this->getSerial());
this->bWasDeleted = false; this->bWasDeleteted = false;
this->bWasShredded = false; this->bWasShredded = false;
this->state = Drive::TaskState::FROZEN; this->state = Drive::FROZEN;
} }
} }
+58 -72
View File
@@ -5,18 +5,21 @@
* @date 04.09.2020 * @date 04.09.2020
*/ */
#include "../../include/reHDD.h" //for logger settings #include "../../include/reHDD.h" //for logger settings
#include "../../include/logger/logger.h" #include "../../include/logger/logger.h"
using namespace std; using namespace std;
string version = "0.2.1"; // logger version string version = "0.2.1"; //logger version
bool Logger::instanceFlag = false; bool Logger::instanceFlag = false;
Logger *Logger::single = NULL; Logger* Logger::single = NULL;
/** /**
* \brief create new logger instance * \brief create new logger instance
* \param path to log file
* \param struct with data
* \return instance of Logger * \return instance of Logger
*/ */
Logger::Logger() Logger::Logger()
@@ -94,13 +97,13 @@ void Logger::error(string s)
void Logger::writeLog(string s) void Logger::writeLog(string s)
{ {
ofstream logFile; ofstream logFile;
Logger::mtxLog.lock(); // lock this section for other threads Logger::mtxLog.lock(); //lock this section for other threads
logFile.open(this->logPath, ios_base::app); logFile.open(this->logPath, ios_base::app);
logFile << (s + "\n"); // append to existing file logFile << (s + "\n"); //append to existing file
logFile.close(); logFile.close();
Logger::mtxLog.unlock(); // unlock this section for other threads Logger::mtxLog.unlock(); //unlock this section for other threads
} }
/** /**
@@ -119,22 +122,22 @@ void Logger::newLine()
*/ */
string Logger::getTimestamp() string Logger::getTimestamp()
{ {
struct tm *timeinfo; struct tm * timeinfo;
struct timeval tv; struct timeval tv;
int millisec; int millisec;
char cpDate[80]; char cpDate [80];
char buffer[120]; char buffer [120];
gettimeofday(&tv, NULL); gettimeofday(&tv, NULL);
millisec = lrint(tv.tv_usec / 1000.0); // Round to nearest millisec millisec = lrint(tv.tv_usec/1000.0); // Round to nearest millisec
if (millisec >= 1000) // Allow for rounding up to nearest second if (millisec>=1000) // Allow for rounding up to nearest second
{ {
millisec -= 1000; millisec -=1000;
tv.tv_sec++; tv.tv_sec++;
} }
timeinfo = localtime(&tv.tv_sec); timeinfo = localtime(&tv.tv_sec);
strftime(cpDate, 80, "%d/%m/%Y %T", timeinfo); strftime (cpDate,80,"%d/%m/%Y %T",timeinfo);
snprintf(buffer, sizeof(buffer), "%s.%03d", cpDate, millisec); sprintf(buffer, "%s.%03d", cpDate, millisec);
return buffer; return buffer;
} }
@@ -143,44 +146,25 @@ string Logger::getTimestamp()
* \param void * \param void
* \return string MAC address (formatted) * \return string MAC address (formatted)
*/ */
std::string Logger::getMacAddress() string Logger::getMacAddress()
{ {
struct ifaddrs *ifaddr, *ifa; struct ifreq ifr;
int s = socket(AF_INET, SOCK_STREAM,0);
// default MAC if none found strcpy(ifr.ifr_name, "eth0");
std::string result = "00:00:00:00:00:00"; if (ioctl(s, SIOCGIFHWADDR, &ifr) < 0)
if (getifaddrs(&ifaddr) == -1)
return result;
for (ifa = ifaddr; ifa != nullptr; ifa = ifa->ifa_next)
{
if (!ifa->ifa_addr)
continue;
// We want AF_PACKET interfaces (Ethernet)
if (ifa->ifa_addr->sa_family == AF_PACKET &&
!(ifa->ifa_flags & IFF_LOOPBACK) && // skip loopback interface
(ifa->ifa_flags & IFF_UP)) // must be up
{ {
struct sockaddr_ll *s = (struct sockaddr_ll *)ifa->ifa_addr; strcpy(ifr.ifr_name, "eno1");
if (s->sll_halen == 6)
{
char buf[32];
snprintf(buf, sizeof(buf),
"%02X:%02X:%02X:%02X:%02X:%02X",
s->sll_addr[0], s->sll_addr[1], s->sll_addr[2],
s->sll_addr[3], s->sll_addr[4], s->sll_addr[5]);
freeifaddrs(ifaddr);
return std::string(buf);
}
} }
}
freeifaddrs(ifaddr); unsigned char *hwaddr = (unsigned char *)ifr.ifr_hwaddr.sa_data;
return result; char buffer [80];
sprintf(buffer,"%02X:%02X:%02X:%02X:%02X:%02X", hwaddr[0], hwaddr[1], hwaddr[2],
hwaddr[3], hwaddr[4], hwaddr[5]);
close(s);
string tmp = buffer;
return tmp;
} }
/** /**
@@ -192,22 +176,22 @@ std::string Logger::getMacAddress()
*/ */
string Logger::padStringMenu(char cBorder, string text, uint8_t u8LineLenght) string Logger::padStringMenu(char cBorder, string text, uint8_t u8LineLenght)
{ {
string result(1, cBorder); string result(1,cBorder);
uint8_t u8TextSize = text.length(); uint8_t u8TextSize = text.length();
uint8_t u8Padding = ((u8LineLenght - u8TextSize) / 2); uint8_t u8Padding = ((u8LineLenght-u8TextSize)/2);
for (uint8_t i = 0; i < u8Padding; i++) for(uint8_t i = 0 ; i < u8Padding; i++)
{ {
result.append(" "); result.append(" ");
} }
result.append(text); result.append(text);
while ((uint8_t)result.length() < (u8LineLenght - 1)) while((uint8_t)result.length() < (u8LineLenght-1))
{ {
result.append(" "); result.append(" ");
} }
result.append(string(1, cBorder)); result.append(string(1, cBorder));
return result; return result;
@@ -221,12 +205,12 @@ string Logger::padStringMenu(char cBorder, string text, uint8_t u8LineLenght)
*/ */
string Logger::menuLine(char cBorder, uint8_t u8LineLenght) string Logger::menuLine(char cBorder, uint8_t u8LineLenght)
{ {
string result(1, cBorder); string result(1,cBorder);
while ((uint8_t)result.length() < u8LineLenght) while((uint8_t)result.length() < u8LineLenght)
{ {
result.append(string(1, cBorder)); result.append(string(1, cBorder));
} }
return result; return result;
} }
@@ -234,16 +218,18 @@ string Logger::menuLine(char cBorder, uint8_t u8LineLenght)
* \brief return a instance of the logger * \brief return a instance of the logger
* \return logger obj * \return logger obj
*/ */
Logger *Logger::logThis() Logger* Logger::logThis()
{ {
if (!instanceFlag) if (!instanceFlag)
{ {
single = new Logger(); // create new obj single = new Logger(); //create new obj
instanceFlag = true; instanceFlag = true;
return single; return single;
} }
else else
{ {
return single; // return existing obj return single; //return existing obj
} }
} }
+2 -3
View File
@@ -6,7 +6,6 @@
*/ */
#include "../include/reHDD.h" #include "../include/reHDD.h"
using namespace std;
/** /**
* \brief app entry point * \brief app entry point
@@ -17,7 +16,7 @@ int main(void)
{ {
// cout << "refurbishingHddTool" << endl; // cout << "refurbishingHddTool" << endl;
reHDD app; reHDD* app = new reHDD();
app.app_logic(); app->app_logic();
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
-101
View File
@@ -1,101 +0,0 @@
/**
* @file printer.cpp
* @brief Send drive data to printer service using ipc msg queue
* @author Hendrik Schutter
* @date 24.11.2022
*/
#include "../include/reHDD.h"
bool Printer::instanceFlag = false;
Printer *Printer::single = NULL;
/**
* \brief create new Printer instance
* \param path to log file
* \param struct with data
* \return instance of Printer
*/
Printer::Printer()
{
if (-1 == (this->msqid = msgget((key_t)IPC_MSG_QUEUE_KEY, IPC_CREAT | 0666)))
{
Logger::logThis()->error("Printer: Create mgs queue failed!");
}
}
/**
* \brief deconstructor
* \return void
*/
Printer::~Printer()
{
instanceFlag = false;
}
/**
* \brief send data to msg queue
* \return void
*/
void Printer::print(Drive *drive)
{
t_msgQueueData msgQueueData;
msgQueueData.msg_queue_type = 1;
snprintf(msgQueueData.driveData.caDriveIndex, STR_BUFFER_SIZE, "%i", drive->u16DriveIndex);
snprintf(msgQueueData.driveData.caDriveState, STR_BUFFER_SIZE, "shredded");
snprintf(msgQueueData.driveData.caDriveModelFamily, STR_BUFFER_SIZE, "%s", drive->getModelFamily().c_str());
snprintf(msgQueueData.driveData.caDriveModelName, STR_BUFFER_SIZE, "%s", drive->getModelName().c_str());
snprintf(msgQueueData.driveData.caDriveCapacity, STR_BUFFER_SIZE, "%li", drive->getCapacity());
snprintf(msgQueueData.driveData.caDriveSerialnumber, STR_BUFFER_SIZE, "%s", drive->getSerial().c_str());
snprintf(msgQueueData.driveData.caDriveHours, STR_BUFFER_SIZE, "%i", drive->getPowerOnHours());
snprintf(msgQueueData.driveData.caDriveCycles, STR_BUFFER_SIZE, "%i", drive->getPowerCycles());
snprintf(msgQueueData.driveData.caDriveErrors, STR_BUFFER_SIZE, "%i", drive->getErrorCount());
snprintf(msgQueueData.driveData.caDriveShredTimestamp, STR_BUFFER_SIZE, "%li", drive->getActionStartTimestamp());
snprintf(msgQueueData.driveData.caDriveShredDuration, STR_BUFFER_SIZE, "%li", drive->getTaskDuration());
switch (drive->connectionType)
{
case Drive::ConnectionType::USB:
strncpy(msgQueueData.driveData.caDriveConnectionType, "usb", STR_BUFFER_SIZE);
break;
case Drive::ConnectionType::SATA:
strncpy(msgQueueData.driveData.caDriveConnectionType, "sata", STR_BUFFER_SIZE);
break;
case Drive::ConnectionType::NVME:
strncpy(msgQueueData.driveData.caDriveConnectionType, "nvme", STR_BUFFER_SIZE);
break;
case Drive::ConnectionType::UNKNOWN:
default:
strncpy(msgQueueData.driveData.caDriveConnectionType, "na", STR_BUFFER_SIZE);
}
snprintf(msgQueueData.driveData.caDriveReHddVersion, STR_BUFFER_SIZE, "%s", REHDD_VERSION);
if (-1 == msgsnd(this->msqid, &msgQueueData, sizeof(t_msgQueueData) - sizeof(long), 0))
{
Logger::logThis()->error("Printer: Send mgs queue failed!");
}
else
{
Logger::logThis()->info("Printer: print triggered - Drive: " + drive->getSerial());
}
}
/**
* \brief return a instance of the printer
* \return printer obj
*/
Printer *Printer::getPrinter()
{
if (!instanceFlag)
{
single = new Printer(); // create new obj
instanceFlag = true;
return single;
}
else
{
return single; // return existing obj
}
}
+42 -830
View File
@@ -6,21 +6,14 @@
*/ */
#include "../include/reHDD.h" #include "../include/reHDD.h"
using namespace std;
static int fdNewDrivesInformPipe[2]; // File descriptor for pipe that informs if new drives are found static int fdNewDrivesInformPipe[2];//File descriptor for pipe that informs if new drives are found
static int fdShredInformPipe[2]; // File descriptor for pipe that informs if a wipe thread signals static int fdShredInformPipe[2];//File descriptor for pipe that informs if a wipe thread signals
static std::mutex mxDrives; static Drive* pDummyDrive;
list<Drive> listNewDrives; // store found drives that are updated every 5sec static uint8_t u8SelectedEntry;
static list<Drive> listDrives; // stores all drive data from scan thread
TUI *ui;
static uint16_t u16SelectedEntry;
static fd_set selectSet; static fd_set selectSet;
@@ -31,7 +24,7 @@ static fd_set selectSet;
*/ */
reHDD::reHDD(void) reHDD::reHDD(void)
{ {
u16SelectedEntry = 0U; u8SelectedEntry = 0U;
} }
/** /**
@@ -41,839 +34,58 @@ reHDD::reHDD(void)
*/ */
void reHDD::app_logic(void) void reHDD::app_logic(void)
{ {
ui = new TUI(); pDummyDrive = new Drive("/dev/sdc");
ui->initTUI(); pDummyDrive->state = Drive::NONE;
pDummyDrive->bIsOffline = false;
if (pipe(fdNewDrivesInformPipe) == -1) pipe(fdNewDrivesInformPipe);
{ pipe(fdShredInformPipe);
Logger::logThis()->error("Unable to open pipe 'fdNewDrivesInformPipe'");
}
if (pipe(fdShredInformPipe) == -1) getSelectedDrive()->state = Drive::TaskState::SHRED_ACTIVE;
{ thread(ThreadShred).detach();
Logger::logThis()->error("Unable to open pipe 'fdShredInformPipe'");
}
thread thDevices(ThreadScanDevices); // start thread that scans for drives while(1)
thread thUserInput(ThreadUserInput); // start thread that reads user input
thread thCheckFrozenDrives(ThreadCheckFrozenDrives); // start thread that checks timeout for drives
while (1)
{
FD_ZERO(&selectSet);
FD_SET(fdNewDrivesInformPipe[0], &selectSet);
FD_SET(fdShredInformPipe[0], &selectSet);
select(FD_SETSIZE, &selectSet, NULL, NULL, NULL);
if (FD_ISSET(fdNewDrivesInformPipe[0], &selectSet))
{ {
mxDrives.lock(); FD_ZERO(&selectSet);
char dummy; FD_SET(fdNewDrivesInformPipe[0], &selectSet);
read(fdNewDrivesInformPipe[0], &dummy, 1); FD_SET(fdShredInformPipe[0], &selectSet);
filterNewDrives(&listDrives, &listNewDrives); // filter and copy to app logic vector
printDrives(&listDrives);
mxDrives.unlock();
}
if (FD_ISSET(fdShredInformPipe[0], &selectSet))
{
char dummy;
read(fdShredInformPipe[0], &dummy, 1);
updateShredMetrics(&listDrives);
#ifdef LOG_LEVEL_HIGH
Logger::logThis()->info("got progress signal from a shred task");
#endif
}
ui->updateTUI(&listDrives, u16SelectedEntry);
} // endless loop
thDevices.join();
thUserInput.join();
thCheckFrozenDrives.join();
}
Drive *reHDD::getSelectedDrive() select(FD_SETSIZE, &selectSet, NULL, NULL, NULL);
{
mxDrives.lock();
if (u16SelectedEntry < listDrives.size())
{
list<Drive>::iterator it = listDrives.begin();
advance(it, u16SelectedEntry);
it->u16DriveIndex = u16SelectedEntry;
mxDrives.unlock();
return &(*it);
}
else
{
Logger::logThis()->warning("selected drive not present");
mxDrives.unlock();
return nullptr;
}
}
void reHDD::ThreadScanDevices() if(FD_ISSET(fdShredInformPipe[0], &selectSet))
{
while (true)
{
mxDrives.lock();
listNewDrives.clear();
searchDrives(&listNewDrives); // search for new drives and store them in list
filterIgnoredDrives(&listNewDrives); // filter out ignored drives
addSMARTData(&listNewDrives); // add S.M.A.R.T. Data to the drives
filterInvalidDrives(&listNewDrives); // filter out drives that report zero capacity
mxDrives.unlock();
write(fdNewDrivesInformPipe[1], "A", 1);
sleep(5); // sleep 5 sec
}
}
void reHDD::ThreadCheckFrozenDrives()
{
while (true)
{
mxDrives.lock();
for (auto it = begin(listDrives); it != end(listDrives); ++it)
{
if (it->state == Drive::TaskState::SHRED_ACTIVE)
{
it->checkFrozenDrive();
}
}
mxDrives.unlock();
sleep(13); // sleep 13 sec
}
}
void reHDD::ThreadUserInput()
{
while (true)
{
Drive *tmpSelectedDrive = getSelectedDrive();
// cout << TUI::readUserInput() << endl;
switch (TUI::readUserInput())
{
case TUI::UserInput::DownKey:
// cout << "Down" << endl;
handleArrowKey(TUI::UserInput::DownKey);
ui->updateTUI(&listDrives, u16SelectedEntry);
break;
case TUI::UserInput::UpKey:
// cout << "Up" << endl;
handleArrowKey(TUI::UserInput::UpKey);
ui->updateTUI(&listDrives, u16SelectedEntry);
break;
case TUI::UserInput::Undefined:
// cout << "Undefined" << endl;
break;
case TUI::UserInput::Abort:
// cout << "Abort" << endl;
handleAbort();
ui->updateTUI(&listDrives, u16SelectedEntry);
break;
case TUI::UserInput::Delete:
// cout << "Delete" << endl;
if (tmpSelectedDrive != nullptr)
{
if (tmpSelectedDrive->state == Drive::TaskState::NONE)
{ {
tmpSelectedDrive->state = Drive::TaskState::DELETE_SELECTED; char dummy;
read (fdShredInformPipe[0],&dummy,1);
stringstream stream;
stream << fixed << setprecision(3) << (getSelectedDrive()->getTaskPercentage());
string sState = "Shredding: " + stream.str() + "%";
std::ostringstream out;
double dDeltaSec = ((double)((getSelectedDrive()->sShredSpeed.u32ShredTimeDelta)/1000000000.0)); //convert nano in sec
double speed = ((getSelectedDrive()->sShredSpeed.ulWrittenBytes/1000000.0)/dDeltaSec);
char s[25];
sprintf(s, "%0.2lf MB/s", speed);
out << s;
Logger::logThis()->info(sState + " - " + out.str());
} }
} } //endless loop
ui->updateTUI(&listDrives, u16SelectedEntry);
break;
case TUI::UserInput::Shred:
// cout << "Shred" << endl;
if (tmpSelectedDrive != nullptr)
{
if (tmpSelectedDrive->state == Drive::TaskState::NONE)
{
tmpSelectedDrive->state = Drive::TaskState::SHRED_SELECTED;
}
}
ui->updateTUI(&listDrives, u16SelectedEntry);
break;
case TUI::UserInput::ShredAll:
// cout << "ShredAll" << endl;
startShredAllDrives(&listDrives);
ui->updateTUI(&listDrives, u16SelectedEntry);
break;
case TUI::UserInput::Enter:
// cout << "Enter" << endl;
handleEnter();
ui->updateTUI(&listDrives, u16SelectedEntry);
break;
case TUI::UserInput::ESC:
// cout << "ESC" << endl;
handleESC();
ui->updateTUI(&listDrives, u16SelectedEntry);
break;
case TUI::UserInput::Terminate:
// cout << "Terminate" << endl;
stopShredAllDrives(&listDrives);
ui->terminateTUI();
sleep(5); // sleep 5 sec
std::exit(1); // Terminates main, doesn't wait for threads
break;
case TUI::UserInput::Print:
// cout << "Print" << endl;
if (tmpSelectedDrive != nullptr)
{
printDrive(tmpSelectedDrive);
}
ui->updateTUI(&listDrives, u16SelectedEntry);
break;
case TUI::UserInput::PrintAll:
// cout << "PrintAll" << endl;
printAllDrives(&listDrives);
ui->updateTUI(&listDrives, u16SelectedEntry);
break;
default:
break;
}
}
} }
/** Drive* reHDD::getSelectedDrive()
* \brief print all shredded drives
* \param pointer of list <Drive>* plistDrives
* \return void
*/
void reHDD::printAllDrives(list<Drive> *plistDrives)
{ {
list<Drive>::iterator it; return pDummyDrive;
mxDrives.lock();
for (it = plistDrives->begin(); it != plistDrives->end(); ++it)
{
Drive *pTmpDrive = iterator_to_pointer<Drive, std::list<Drive>::iterator>(it);
printDrive(pTmpDrive);
}
mxDrives.unlock();
} }
/** void reHDD::ThreadShred()
* \brief print a shredded drives
* \param pointer of a drive
* \return void
*/
void reHDD::printDrive(Drive *const pDrive)
{ {
if (pDrive->bWasShredded) if (getSelectedDrive() != nullptr)
{
#ifdef ZERO_CHECK
if (pDrive->bWasChecked && (pDrive->u32DriveChecksumAfterShredding != 0U))
{ {
return; // Drive was shredded&checked but checksum failed, don't print label Logger::logThis()->info("Starting Shred Thread");
getSelectedDrive()->setActionStartTimestamp(); //save timestamp at start of shredding
Shred* pShredTask = new Shred(); //create new shred task
pShredTask->shredDrive(getSelectedDrive(), &fdShredInformPipe[1]); //start new shred task
delete pShredTask; //delete shred task
} }
#endif
Logger::logThis()->info("User print for: " + pDrive->getModelName() + "-" + pDrive->getSerial());
Printer::getPrinter()->print(pDrive);
}
} }
void reHDD::ThreadShred(Drive *const pDrive)
{
if (pDrive != nullptr)
{
pDrive->setActionStartTimestamp(); // save timestamp at start of shredding
Shred *pShredInstance = new Shred(); // create new shred task
pShredInstance->shredDrive(pDrive, &fdShredInformPipe[1]); // start new shred task
delete pShredInstance; // delete shred task
ui->updateTUI(&listDrives, u16SelectedEntry);
}
}
void reHDD::ThreadDelete(Drive *const pDrive)
{
if (pDrive != nullptr)
{
pDrive->state = Drive::TaskState::DELETE_ACTIVE;
pDrive->setActionStartTimestamp(); // save timestamp at start of deleting
Delete::deleteDrive(pDrive); // blocking, no thread
pDrive->state = Drive::TaskState::NONE; // delete finished
pDrive->bWasDeleted = true;
Logger::logThis()->info("Finished delete for: " + pDrive->getModelName() + "-" + pDrive->getSerial());
ui->updateTUI(&listDrives, u16SelectedEntry);
}
}
void reHDD::filterNewDrives(list<Drive> *plistOldDrives, list<Drive> *plistNewDrives)
{
list<Drive>::iterator itOld; // Iterator for current (old) drive list
list<Drive>::iterator itNew; // Iterator for new drive list that was created from to scan thread
// remove offline old drives from previously run
for (itOld = plistOldDrives->begin(); itOld != plistOldDrives->end();)
{
if (itOld->bIsOffline == true)
{
Logger::logThis()->warning("Offline drive found: " + itOld->getPath());
itOld = plistOldDrives->erase(itOld);
/*
if(plistOldDrives->size() > 0){ //This can be a risk if the user starts a task for the selected drive and the selected drive changes
u8SelectedEntry = 0U;
}
*/
}
else
{
++itOld;
}
}
// search offline drives and mark them
for (itOld = plistOldDrives->begin(); itOld != plistOldDrives->end(); ++itOld)
{
itOld->bIsOffline = true; // set offline before searching in the new list
for (itNew = plistNewDrives->begin(); itNew != plistNewDrives->end();)
{
if ((itOld->getSerial() == itNew->getSerial()) || (itOld->getPath() == itNew->getPath()))
{
itOld->bIsOffline = false; // drive is still attached
// copy new smart data to existing drive
itOld->setDriveSMARTData(itNew->getModelFamily(), itNew->getModelName(), itNew->getSerial(), itNew->getCapacity(), itNew->getErrorCount(), itNew->getPowerOnHours(), itNew->getPowerCycles(), itNew->getTemperature(), itNew->getReallocatedSectors(), itNew->getPendingSectors(), itNew->getUncorrectableSectors());
#ifdef LOG_LEVEL_HIGH
Logger::logThis()->info("Delete new drive, because already attached: " + itNew->getModelName());
#endif
itNew = plistNewDrives->erase(itNew); // This drive is already attached, remove from new list
}
else
{
++itNew;
}
}
}
// mark offline old drives
for (itOld = plistOldDrives->begin(); itOld != plistOldDrives->end(); ++itOld)
{
if (itOld->bIsOffline == true)
{
// cout << "offline drive found: " << itOld->getPath() << endl;
Logger::logThis()->warning("Mark offline drive found: " + itOld->getPath());
itOld->state = Drive::TaskState::NONE; // clear state --> shred task will terminate
}
}
// add new drives to drive list
for (itNew = plistNewDrives->begin(); itNew != plistNewDrives->end(); ++itNew)
{
plistOldDrives->push_back(*itNew);
// Logger::logThis()->info("Add new drive: " + itNew->getModelName());
}
plistNewDrives->clear();
}
/**
* \brief search attached drives on /dev/sd*
* \param pointer of list <Drive>* plistDrives
* \return void
*/
void reHDD::searchDrives(std::list<Drive> *plistDrives)
{
FILE *fp = popen("lsblk -d -n -o NAME,TRAN", "r");
if (!fp)
{
Logger::logThis()->error("Unable to execute lsblk to scan drives");
exit(EXIT_FAILURE);
}
char line[256];
while (fgets(line, sizeof(line), fp))
{
std::string devName, transport;
std::istringstream iss(line);
iss >> devName >> transport;
if (devName.empty())
continue;
Drive tmpDrive("/dev/" + devName);
tmpDrive.state = Drive::TaskState::NONE;
tmpDrive.bIsOffline = false;
// Set connection type
if (transport == "sata")
tmpDrive.connectionType = Drive::ConnectionType::SATA;
else if (transport == "usb")
tmpDrive.connectionType = Drive::ConnectionType::USB;
else if (transport == "nvme")
tmpDrive.connectionType = Drive::ConnectionType::NVME;
else
tmpDrive.connectionType = Drive::ConnectionType::UNKNOWN;
plistDrives->push_back(tmpDrive);
Logger::logThis()->info(
"Drive found: " + tmpDrive.getPath() +
" (type: " +
(tmpDrive.connectionType == Drive::ConnectionType::USB ? "USB" : tmpDrive.connectionType == Drive::ConnectionType::SATA ? "SATA"
: tmpDrive.connectionType == Drive::ConnectionType::NVME ? "NVME"
: "UNKNOWN") +
")");
}
pclose(fp);
}
/**
* \brief filter out drives that are listed in "ignoreDrives.conf", loop devices, and optical drives
* \param pointer of list <Drive>* plistDrives
* \return void
*/
void reHDD::filterIgnoredDrives(list<Drive> *plistDrives)
{
string systemDrivePath;
if (getSystemDrive(systemDrivePath))
{
// Logger::logThis()->info("Found system drive: " + systemDrivePath);
list<Drive>::iterator it = plistDrives->begin();
while (it != plistDrives->end())
{
string driveName = it->getPath();
// Remove /dev/ prefix
if (driveName.find("/dev/") == 0)
{
driveName = driveName.substr(5); // Skip "/dev/"
}
if (systemDrivePath.find(driveName) != std::string::npos) // compare found system drive and current drive
{
// system drive found --> ignore this drive
#ifdef LOG_LEVEL_HIGH
Logger::logThis()->info("system drive found --> ignore this drive: " + it->getPath());
#endif
it = plistDrives->erase(it);
}
else
{
++it;
}
}
}
// Filter out loop devices (loop0, loop1, etc.)
list<Drive>::iterator it = plistDrives->begin();
while (it != plistDrives->end())
{
string driveName = it->getPath();
if (driveName.find("/dev/") == 0)
{
driveName = driveName.substr(5);
}
if (driveName.find("loop") == 0)
{
#ifdef LOG_LEVEL_HIGH
Logger::logThis()->info("loop device found --> ignore this drive: " + it->getPath());
#endif
it = plistDrives->erase(it);
}
else
{
++it;
}
}
// Filter out optical drives (sr0, sr1, cdrom, dvd, etc.)
it = plistDrives->begin();
while (it != plistDrives->end())
{
string driveName = it->getPath();
if (driveName.find("/dev/") == 0)
{
driveName = driveName.substr(5);
}
if (driveName.find("sr") == 0 ||
driveName.find("cdrom") == 0 ||
driveName.find("dvd") == 0 ||
driveName.find("cdrw") == 0)
{
#ifdef LOG_LEVEL_HIGH
Logger::logThis()->info("optical drive found --> ignore this drive: " + it->getPath());
#endif
it = plistDrives->erase(it);
}
else
{
++it;
}
}
// Read ignored drives from config file
list<tuple<string>> vtlIgnoredDevices;
ifstream input("ignoreDrives.conf");
for (string sLine; getline(input, sLine);)
{
// Skip empty lines and comments
if (!sLine.empty() && sLine[0] != '#')
{
vtlIgnoredDevices.emplace_back(sLine);
}
}
// Loop through found entries in ignore file
for (auto row : vtlIgnoredDevices)
{
it = plistDrives->begin();
while (it != plistDrives->end())
{
string sUUID;
char *cLine = NULL;
size_t len = 0;
string sCMD = "blkid ";
sCMD.append(it->getPath());
FILE *outputfileBlkid = popen(sCMD.c_str(), "r");
if (outputfileBlkid == NULL)
{
Logger::logThis()->error("Failed to execute blkid for: " + it->getPath());
++it;
continue;
}
while ((getline(&cLine, &len, outputfileBlkid)) != -1)
{
size_t ptuuidPos = string(cLine).find("PTUUID");
if (ptuuidPos != string::npos)
{
string sBlkidOut = string(cLine);
sBlkidOut.erase(0, ptuuidPos + 8);
if (sBlkidOut.length() >= 8)
{
sBlkidOut.erase(8, sBlkidOut.length());
}
sUUID = sBlkidOut;
}
}
free(cLine);
pclose(outputfileBlkid);
if (!get<0>(row).compare(sUUID))
{
#ifdef LOG_LEVEL_HIGH
Logger::logThis()->info("same uuid found in ignore file --> ignore this drive: " + it->getPath());
#endif
it = plistDrives->erase(it);
}
else
{
++it;
}
}
}
}
/**
* \brief filter out drives that are not indented for processing
* \param pointer of list <Drive>* plistDrives
* \return void
*/
void reHDD::filterInvalidDrives(list<Drive> *plistDrives)
{
list<Drive>::iterator it;
for (it = plistDrives->begin(); it != plistDrives->end(); ++it)
{
if (it->getCapacity() == 0U)
{
#ifdef LOG_LEVEL_HIGH
Logger::logThis()->info("Drive reports zero capacity --> ignore this drive: " + it->getPath());
#endif
it = plistDrives->erase(it);
}
}
}
/**
* \brief start shred for all drives
* \param pointer of list <Drive>* plistDrives
* \return void
*/
void reHDD::startShredAllDrives(list<Drive> *plistDrives)
{
list<Drive>::iterator it;
mxDrives.lock();
for (it = plistDrives->begin(); it != plistDrives->end(); ++it)
{
if (it->state == Drive::TaskState::NONE)
{
Drive *pTmpDrive = iterator_to_pointer<Drive, std::list<Drive>::iterator>(it);
#ifdef LOG_LEVEL_HIGH
ostringstream address;
address << (void const *)&(*pTmpDrive);
Logger::logThis()->info("Started shred (all) for: " + pTmpDrive->getModelName() + "-" + pTmpDrive->getSerial() + " @" + address.str());
#endif
thread(ThreadShred, pTmpDrive).detach();
}
}
mxDrives.unlock();
}
/**
* \brief stop shred for all drives
* \param pointer of list <Drive>* plistDrives
* \return void
*/
void reHDD::stopShredAllDrives(list<Drive> *plistDrives)
{
list<Drive>::iterator it;
mxDrives.lock();
for (it = plistDrives->begin(); it != plistDrives->end(); ++it)
{
if (it->state == Drive::TaskState::SHRED_ACTIVE || it->state == Drive::TaskState::DELETE_ACTIVE)
{
it->state = Drive::TaskState::NONE;
Logger::logThis()->info("Abort-Shred-Signal for: " + it->getModelName() + "-" + it->getSerial());
// task for drive is running --> remove selection
}
#ifdef LOG_LEVEL_HIGH
ostringstream address;
address << (void const *)&(*it);
Logger::logThis()->info("Started shred (all) for: " + it->getModelName() + "-" + it->getSerial() + " @" + address.str());
#endif
}
mxDrives.unlock();
}
/**
* \brief print drives with all information
* \param pointer of list <Drive>* plistDrives
* \return void
*/
void reHDD::printDrives(list<Drive> *plistDrives)
{
#ifdef LOG_LEVEL_HIGH
Logger::logThis()->info("------------DRIVES START------------");
// cout << "------------DRIVES---------------" << endl;
list<Drive>::iterator it;
uint8_t u8Index = 0;
for (it = plistDrives->begin(); it != plistDrives->end(); ++it)
{
/*
cout << " Drive: " << distance(pvecDrives->begin(), it) << endl;
cout << "Path: " << it->getPath() << endl;
cout << "ModelFamily: " << it->getModelFamily() << endl;
cout << "ModelName: " << it->getModelName() << endl;
cout << "Capacity: " << it->getCapacity() << endl;
cout << "Serial: " << it->getSerial() << endl;
cout << "PowerOnHours: " << it->getPowerOnHours() << endl;
cout << "PowerCycle: " << it->getPowerCycles() << endl;
cout << "ErrorCount: " << it->getErrorCount() << endl;
cout << endl;*/
ostringstream address;
address << (void const *)&(*it);
Logger::logThis()->info(to_string(u8Index++) + ": " + it->getPath() + " - " + it->getModelFamily() + " - " + it->getSerial() + " @" + address.str());
}
Logger::logThis()->info("------------DRIVES END--------------");
// cout << "---------------------------------" << endl;
#endif
}
/**
* \brief update shred metrics for all drives
* \param pointer of list <Drive>* plistDrives
* \return void
*/
void reHDD::updateShredMetrics(list<Drive> *plistDrives)
{
list<Drive>::iterator it;
for (it = plistDrives->begin(); it != plistDrives->end(); ++it)
{
if (it->state == Drive::TaskState::SHRED_ACTIVE)
{
Drive *pTmpDrive = iterator_to_pointer<Drive, std::list<Drive>::iterator>(it);
// set metrics for calculating shred speed
std::chrono::time_point<std::chrono::system_clock> chronoCurrentTimestamp = std::chrono::system_clock::now();
auto shredSpeed = pTmpDrive->sShredSpeed.load();
time_t u32ShredTimeDelta = (chronoCurrentTimestamp - shredSpeed.chronoShredTimestamp).count();
if (u32ShredTimeDelta > METRIC_THRESHOLD)
{
shredSpeed.u32ShredTimeDelta = u32ShredTimeDelta;
shredSpeed.chronoShredTimestamp = std::chrono::system_clock::now();
shredSpeed.ulWrittenBytes = shredSpeed.ulSpeedMetricBytesWritten;
shredSpeed.ulSpeedMetricBytesWritten = 0U;
pTmpDrive->sShredSpeed.store(shredSpeed);
}
}
}
}
/**
* \brief add S.M.A.R.T data from SMART
* \param pointer of list <Drive>* plistDrives
* \return void
*/
void reHDD::addSMARTData(list<Drive> *plistDrives)
{
list<Drive>::iterator it;
for (it = plistDrives->begin(); it != plistDrives->end(); ++it)
{
Drive *pTmpDrive = iterator_to_pointer<Drive, std::list<Drive>::iterator>(it);
SMART::readSMARTData(pTmpDrive);
}
}
void reHDD::handleArrowKey(TUI::UserInput userInput)
{
uint8_t u8EntrySize = (uint8_t)listDrives.size();
switch (userInput)
{
case TUI::UserInput::DownKey:
u16SelectedEntry++;
if (u16SelectedEntry >= u8EntrySize)
{
u16SelectedEntry = 0;
}
break;
case TUI::UserInput::UpKey:
if (u16SelectedEntry == 0)
{
u16SelectedEntry = (u8EntrySize - 1);
}
else
{
u16SelectedEntry--;
}
break;
default:
u16SelectedEntry = 0;
break;
}
// Logger::logThis()->info("ArrowKey - selected drive: " + to_string(u8SelectedEntry));
}
void reHDD::handleEnter()
{
Drive *tmpSelectedDrive = getSelectedDrive();
if (tmpSelectedDrive != nullptr)
{
if (tmpSelectedDrive->state == Drive::TaskState::SHRED_SELECTED)
{
Logger::logThis()->info("Started shred/check for: " + tmpSelectedDrive->getModelName() + "-" + tmpSelectedDrive->getSerial());
thread(ThreadShred, tmpSelectedDrive).detach();
}
if (tmpSelectedDrive->state == Drive::TaskState::DELETE_SELECTED)
{
Logger::logThis()->info("Started delete for: " + tmpSelectedDrive->getModelName() + "-" + tmpSelectedDrive->getSerial());
thread(ThreadDelete, tmpSelectedDrive).detach();
}
}
}
void reHDD::handleESC()
{
Drive *tmpSelectedDrive = getSelectedDrive();
if (tmpSelectedDrive != nullptr)
{
if (tmpSelectedDrive->state == Drive::TaskState::SHRED_SELECTED)
{
tmpSelectedDrive->state = Drive::TaskState::NONE;
// task for drive is selected --> remove selection
}
if (tmpSelectedDrive->state == Drive::TaskState::DELETE_SELECTED)
{
tmpSelectedDrive->state = Drive::TaskState::NONE;
// task for drive is selected --> remove selection
}
}
}
void reHDD::handleAbort()
{
Drive *tmpSelectedDrive = getSelectedDrive();
if (tmpSelectedDrive != nullptr)
{
if (tmpSelectedDrive->state == Drive::TaskState::SHRED_ACTIVE || tmpSelectedDrive->state == Drive::TaskState::DELETE_ACTIVE)
{
tmpSelectedDrive->state = Drive::TaskState::NONE;
Logger::logThis()->info("Abort-Shred-Signal for: " + tmpSelectedDrive->getModelName() + "-" + tmpSelectedDrive->getSerial());
// task for drive is running --> remove selection
}
}
}
bool reHDD::getSystemDrive(string &systemDrive)
{
char *cLine = NULL;
size_t len = 0;
bool systemDriveFound = false;
FILE *outputfileHwinfo = popen("lsblk -e 11 -o NAME,MOUNTPOINT", "r");
if (outputfileHwinfo == NULL)
{
Logger::logThis()->error("Unable to scan attached drives for system drive");
exit(EXIT_FAILURE);
}
while ((getline(&cLine, &len, outputfileHwinfo)) != -1)
{
string currentLine = cLine;
if (currentLine.find("NAME") != std::string::npos)
{
continue;
}
// Extract drive name from line (removing tree characters)
if ((cLine[0U] != '|') && (cLine[0U] != '`'))
{
systemDrive = currentLine;
// Find the actual drive name (after tree characters like └─, ├─)
size_t lastAlpha = 0;
for (size_t i = 0; i < systemDrive.length(); i++)
{
if (isalpha(systemDrive[i]))
{
lastAlpha = i;
break;
}
}
systemDrive = systemDrive.substr(lastAlpha);
}
if (currentLine.ends_with(" /boot/efi\n"s))
{
systemDriveFound = true;
break;
}
if (currentLine.ends_with(" /run/overlay/live\n"s))
{
systemDriveFound = true;
break;
}
if (currentLine.ends_with(" /\n"s))
{
systemDriveFound = true;
break;
}
}
pclose(outputfileHwinfo);
// Remove mountpoint (everything after first space)
size_t spacePos = systemDrive.find(' ');
if (spacePos != std::string::npos)
{
systemDrive = systemDrive.substr(0, spacePos);
}
// Remove all unwanted characters
systemDrive.erase(std::remove(systemDrive.begin(), systemDrive.end(), '\n'), systemDrive.end());
systemDrive.erase(std::remove(systemDrive.begin(), systemDrive.end(), '/'), systemDrive.end());
systemDrive.erase(std::remove(systemDrive.begin(), systemDrive.end(), '\r'), systemDrive.end());
return systemDriveFound;
}
+193 -756
View File
File diff suppressed because it is too large Load Diff
+156 -365
View File
@@ -6,382 +6,173 @@
*/ */
#include "../include/reHDD.h" #include "../include/reHDD.h"
#include <sys/wait.h> // For WIFSIGNALED, WTERMSIG
using namespace std;
/** string SMART::modelFamily;
* \brief Parse context for SMART attribute values string SMART::modelName;
*/ string SMART::serial;
struct SMARTParseContext uint64_t SMART::capacity = 0U;
{ uint32_t SMART::errorCount = 0U;
// Device information (top-level JSON fields) uint32_t SMART::powerOnHours = 0U;
string modelFamily; uint32_t SMART::powerCycle = 0U;
string modelName;
string serial;
uint64_t capacity;
// Power and temperature (top-level JSON fields)
uint32_t errorCount;
uint32_t powerOnHours;
uint32_t powerCycles;
uint32_t temperature;
// Critical sector counts (from ata_smart_attributes table)
uint32_t reallocatedSectors; // ID 5
uint32_t pendingSectors; // ID 197
uint32_t uncorrectableSectors; // ID 198
// Parser state machine
enum State
{
SEARCHING, // Looking for next field
IN_ATTRIBUTE_5, // Inside ID 5 object
IN_ATTRIBUTE_197, // Inside ID 197 object
IN_ATTRIBUTE_198, // Inside ID 198 object
IN_RAW_SECTION // Inside "raw": { } of current attribute
};
State state;
int currentAttributeId; // Which attribute are we parsing? (5, 197, 198)
SMARTParseContext()
: capacity(0),
errorCount(0),
powerOnHours(0),
powerCycles(0),
temperature(0),
reallocatedSectors(0),
pendingSectors(0),
uncorrectableSectors(0),
state(SEARCHING),
currentAttributeId(0)
{
}
};
/**
* \brief Extract JSON string value
* \param line containing "key": "value"
* \return extracted string value
*/
static string extractStringValue(const string &line)
{
size_t colonPos = line.find(": ");
if (colonPos == string::npos)
return "";
size_t firstQuote = line.find('"', colonPos + 2);
if (firstQuote == string::npos)
return "";
size_t secondQuote = line.find('"', firstQuote + 1);
if (secondQuote == string::npos)
return "";
return line.substr(firstQuote + 1, secondQuote - firstQuote - 1);
}
/**
* \brief Extract JSON integer value
* \param line containing "key": number
* \return extracted integer value
*/
static uint64_t extractIntegerValue(const string &line)
{
size_t colonPos = line.find(": ");
if (colonPos == string::npos)
return 0;
string valueStr = line.substr(colonPos + 2);
// Remove whitespace, commas, braces
valueStr.erase(remove_if(valueStr.begin(), valueStr.end(),
[](char c)
{ return c == ' ' || c == ',' || c == '}' || c == '\n'; }),
valueStr.end());
// Verify it's a valid number
if (valueStr.empty() || valueStr.find_first_not_of("0123456789") != string::npos)
return 0;
try
{
return stoull(valueStr);
}
catch (...)
{
return 0;
}
}
/**
* \brief Process a single line of JSON output
* \param line from smartctl JSON output
* \param context parsing context with state
* \return void
*/
static void processLine(const string &line, SMARTParseContext &ctx)
{
// Trim whitespace for consistent parsing
string trimmed = line;
size_t firstNonSpace = trimmed.find_first_not_of(" \t\r\n");
if (firstNonSpace != string::npos)
{
trimmed = trimmed.substr(firstNonSpace);
}
// Parse top-level device information
if (trimmed.find("\"model_family\":") == 0)
{
ctx.modelFamily = extractStringValue(line);
return;
}
if (trimmed.find("\"model_name\":") == 0)
{
ctx.modelName = extractStringValue(line);
return;
}
if (trimmed.find("\"serial_number\":") == 0)
{
ctx.serial = extractStringValue(line);
return;
}
// Parse capacity from user_capacity.bytes
if (trimmed.find("\"bytes\":") == 0)
{
ctx.capacity = extractIntegerValue(line);
return;
}
// Parse error count from self_test log
if (trimmed.find("\"error_count_total\":") == 0)
{
ctx.errorCount = extractIntegerValue(line);
return;
}
// Parse power-on hours
if (trimmed.find("\"hours\":") == 0)
{
ctx.powerOnHours = extractIntegerValue(line);
return;
}
// Parse power cycle count
if (trimmed.find("\"power_cycle_count\":") == 0)
{
ctx.powerCycles = extractIntegerValue(line);
return;
}
// Parse temperature
if (trimmed.find("\"current\":") == 0 && ctx.temperature == 0)
{
// Only parse first occurrence (temperature section, not other "current" fields)
ctx.temperature = extractIntegerValue(line);
return;
}
// State machine for SMART attributes parsing
switch (ctx.state)
{
case SMARTParseContext::SEARCHING:
// Look for critical attribute IDs
if (trimmed.find("\"id\": 5,") == 0)
{
ctx.state = SMARTParseContext::IN_ATTRIBUTE_5;
ctx.currentAttributeId = 5;
}
else if (trimmed.find("\"id\": 197,") == 0)
{
ctx.state = SMARTParseContext::IN_ATTRIBUTE_197;
ctx.currentAttributeId = 197;
}
else if (trimmed.find("\"id\": 198,") == 0)
{
ctx.state = SMARTParseContext::IN_ATTRIBUTE_198;
ctx.currentAttributeId = 198;
}
break;
case SMARTParseContext::IN_ATTRIBUTE_5:
case SMARTParseContext::IN_ATTRIBUTE_197:
case SMARTParseContext::IN_ATTRIBUTE_198:
// Look for "raw": { start
if (trimmed.find("\"raw\":") == 0)
{
ctx.state = SMARTParseContext::IN_RAW_SECTION;
}
// Look for end of attribute object (more indented closing brace = end of attribute)
// " }," or " }" at attribute level (6 spaces)
else if (line.find(" },") == 0 || line.find(" }") == 0)
{
ctx.state = SMARTParseContext::SEARCHING;
ctx.currentAttributeId = 0;
}
break;
case SMARTParseContext::IN_RAW_SECTION:
// Look for "value": number inside raw section
if (trimmed.find("\"value\":") == 0)
{
uint64_t value = extractIntegerValue(line);
// Store value in appropriate field based on current attribute
if (ctx.currentAttributeId == 5)
{
ctx.reallocatedSectors = static_cast<uint32_t>(value);
}
else if (ctx.currentAttributeId == 197)
{
ctx.pendingSectors = static_cast<uint32_t>(value);
}
else if (ctx.currentAttributeId == 198)
{
ctx.uncorrectableSectors = static_cast<uint32_t>(value);
}
// Stay in raw section - closing brace will exit
}
// Look for end of raw object (less indented = back to attribute level)
// " }" at raw level (8 spaces)
else if (line.find(" }") == 0)
{
// Return to attribute state (raw section closed)
ctx.state = (ctx.currentAttributeId == 5) ? SMARTParseContext::IN_ATTRIBUTE_5 : (ctx.currentAttributeId == 197) ? SMARTParseContext::IN_ATTRIBUTE_197
: SMARTParseContext::IN_ATTRIBUTE_198;
}
break;
}
}
/** /**
* \brief get and set S.M.A.R.T. values in Drive * \brief get and set S.M.A.R.T. values in Drive
* \param pointer of Drive instance * \param pointer of Drive instance
* \return void * \return void
*/ */
void SMART::readSMARTData(Drive *drive) void SMART::readSMARTData(Drive* drive)
{ {
SMARTParseContext ctx; modelFamily.clear();
uint8_t exitStatus = 255U; modelName.clear();
serial.clear();
capacity = 0U;
errorCount = 0U;
powerOnHours = 0U;
powerCycle = 0U;
// Command order optimized for USB adapters size_t len = 0; //lenght of found line
// Standard commands first, then device-specific variants char* cLine = NULL; //found line
string sSmartctlCommands[] = {
" --json -a ", // Try standard first
" --json -d sat -a ", // SAT (SCSI/ATA Translation) - most USB adapters
" --json -d usbjmicron -a ", // USB JMicron
" --json -d usbprolific -a ", // USB Prolific
" --json -d usbsunplus -a " // USB Sunplus
};
for (const string &sSmartctlCommand : sSmartctlCommands) string sCMD = ("smartctl --json -a ");
{ sCMD.append(drive->getPath());
// Build command with timeout const char* cpComand = sCMD.c_str();
string sCMD = "timeout 5 smartctl"; // 5 second timeout prevents hanging
sCMD.append(sSmartctlCommand);
sCMD.append(drive->getPath());
// Note: stderr NOT suppressed for debugging
Logger::logThis()->info("SMART: Executing: " + sCMD); FILE* outputfileSmart = popen(cpComand, "r");
// Execute smartctl with timeout protection while ((getline(&cLine, &len, outputfileSmart)) != -1)
FILE *outputfileSmart = popen(sCMD.c_str(), "r");
if (outputfileSmart == nullptr)
{ {
Logger::logThis()->error("SMART: Failed to execute smartctl"); string sLine = string(cLine);
continue;
SMART::parseModelFamily(sLine);
SMART::parseModelName(sLine);
SMART::parseSerial(sLine);
SMART::parseCapacity(sLine);
SMART::parseErrorCount(sLine);
SMART::parsePowerOnHours(sLine);
SMART::parsePowerCycle(sLine);
} }
pclose(outputfileSmart);
// Reset context for new attempt drive->setDriveSMARTData(modelFamily, modelName, serial, capacity, errorCount, powerOnHours, powerCycle); //wirte data in drive
ctx = SMARTParseContext();
// Parse output line by line
char *cLine = nullptr;
size_t len = 0;
int lineCount = 0;
while (getline(&cLine, &len, outputfileSmart) != -1)
{
string sLine(cLine);
lineCount++;
// Parse exit status
if (sLine.find("\"exit_status\":") != string::npos)
{
exitStatus = static_cast<uint8_t>(extractIntegerValue(sLine));
}
// Process this line
processLine(sLine, ctx);
}
free(cLine);
int pcloseStatus = pclose(outputfileSmart);
Logger::logThis()->info("SMART: Parsed " + to_string(lineCount) + " lines, exit status: " + to_string(exitStatus));
// Check if timeout killed the process
if (WIFSIGNALED(pcloseStatus) && WTERMSIG(pcloseStatus) == SIGTERM)
{
Logger::logThis()->warning("SMART: Command timed out (5s) - skipping to next variant");
continue;
}
// IGNORE exit status - instead check if we got valid data!
// Exit status 64 means "error log contains errors" but SMART data is still valid
// Exit status 4 means "some prefail attributes concerning" but data is valid
// What matters: Did we parse model name and serial?
if (!ctx.modelName.empty() && !ctx.serial.empty())
{
Logger::logThis()->info("SMART: Successfully parsed data");
Logger::logThis()->info("SMART: Model: " + ctx.modelName);
Logger::logThis()->info("SMART: Serial: " + ctx.serial);
Logger::logThis()->info("SMART: Capacity: " + to_string(ctx.capacity) + " bytes");
Logger::logThis()->info("SMART: Power-On Hours: " + to_string(ctx.powerOnHours));
Logger::logThis()->info("SMART: Temperature: " + to_string(ctx.temperature) + " C");
Logger::logThis()->info("SMART: Reallocated Sectors: " + to_string(ctx.reallocatedSectors));
Logger::logThis()->info("SMART: Pending Sectors: " + to_string(ctx.pendingSectors));
Logger::logThis()->info("SMART: Uncorrectable Sectors: " + to_string(ctx.uncorrectableSectors));
if (exitStatus != 0)
{
Logger::logThis()->info("SMART: Note - exit status " + to_string(exitStatus) + " indicates warnings/errors in SMART log");
}
break; // Success - we got data!
}
else
{
Logger::logThis()->warning("SMART: No valid data parsed (exit status: " + to_string(exitStatus) + ")");
}
}
// Check if we got ANY data
if (ctx.modelName.empty() && ctx.serial.empty())
{
Logger::logThis()->warning("SMART: No SMART data available for this drive - may not support SMART or need root privileges");
// Try basic device info without SMART (use hdparm or similar as fallback)
// For now, just log that SMART is not available
ctx.modelName = "SMART not available";
ctx.serial = "N/A";
}
// Write parsed data to drive
drive->setDriveSMARTData(
ctx.modelFamily,
ctx.modelName,
ctx.serial,
ctx.capacity,
ctx.errorCount,
ctx.powerOnHours,
ctx.powerCycles,
ctx.temperature,
ctx.reallocatedSectors,
ctx.pendingSectors,
ctx.uncorrectableSectors);
} }
/**
* \brief parse ModelFamiliy
* \param string output line of smartctl
* \return void
*/
void SMART::parseModelFamily(string sLine)
{
string search("\"model_family\": ");
size_t found = sLine.find(search);
if (found!=string::npos)
{
sLine.erase(0, sLine.find(": ") + 3);
sLine.erase(sLine.length()-3, 3);
modelFamily = sLine;
}
}
/**
* \brief parse ModelName
* \param string output line of smartctl
* \return void
*/
void SMART::parseModelName(string sLine)
{
string search("\"model_name\": ");
size_t found = sLine.find(search);
if (found!=string::npos)
{
sLine.erase(0, sLine.find(": ") + 3);
sLine.erase(sLine.length()-3, 3);
modelName = sLine;
}
}
/**
* \brief parse Serial
* \param string output line of smartctl
* \return void
*/
void SMART::parseSerial(string sLine)
{
string search("\"serial_number\": ");
size_t found = sLine.find(search);
if (found!=string::npos)
{
sLine.erase(0, sLine.find(": ") + 3);
sLine.erase(sLine.length()-3, 3);
serial = sLine;
}
}
/**
* \brief parse Capacity
* \param string output line of smartctl
* \return void
*/
void SMART::parseCapacity(string sLine)
{
string search("\"bytes\": ");
size_t found = sLine.find(search);
if (found!=string::npos)
{
sLine.erase(0, sLine.find(": ") + 2);
sLine.erase(sLine.length()-1, 1);
capacity = stol(sLine);
}
}
/**
* \brief parse ErrorCount
* \param string output line of smartctl
* \return void
*/
void SMART::parseErrorCount(string sLine)
{
string search("\"error_count_total\": ");
size_t found = sLine.find(search);
if (found!=string::npos)
{
sLine.erase(0, sLine.find(": ")+2);
sLine.erase(sLine.length()-2, 2);
errorCount = stol(sLine);
}
}
/**
* \brief parse PowerOnHours
* \param string output line of smartctl
* \return void
*/
void SMART::parsePowerOnHours(string sLine)
{
string search("\"hours\": ");
size_t found = sLine.find(search);
if (found!=string::npos)
{
sLine.erase(0, sLine.find(": ") + 2);
sLine.erase(sLine.length()-1, 1);
powerOnHours = stol(sLine);
}
}
/**
* \brief parse PowerCycle
* \param string output line of smartctl
* \return void
*/
void SMART::parsePowerCycle(string sLine)
{
string search("\"power_cycle_count\": ");
size_t found = sLine.find(search);
if (found!=string::npos)
{
sLine.erase(0, sLine.find(": ") + 2);
sLine.erase(sLine.length()-2, 2);
powerCycle = stol(sLine);
}
}
+310 -484
View File
File diff suppressed because it is too large Load Diff
Submodule tfnoisegen deleted from 488716ef22