Compare commits
22 Commits
7a611ebbb8
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| f2e98ce3bd | |||
| f00309aaa8 | |||
| 851e5c25eb | |||
| d25f82d0f1 | |||
| 68d2678305 | |||
| 9c565598f9 | |||
| 8ee591f28d | |||
| b7c68b3d91 | |||
| 80a50f0043 | |||
| d41b133885 | |||
| 9aaa0a3d25 | |||
| 6a28281d1c | |||
| 279a4bf802 | |||
| 2734c06fb1 | |||
| 34ddd60a0a | |||
| 17e1925034 | |||
| e622c95666 | |||
| a655f026b4 | |||
| 2d8bdd3658 | |||
| e7b9521a8a | |||
| e83a4f15cf | |||
| 31503d8b68 |
16
readme.md
16
readme.md
@@ -1,3 +1,6 @@
|
||||
# РЕПОЗИТОРИЙ АРХИВИРОВАН И ЗДЕСЬ БОЛЬШЕ *НЕ* БУДЕТ ОБНОВЛЕНИЙ!
|
||||
Этот форк разрабатывался в рамках курсовой работы и дальнейшие изменения проекта будут проходить в его [оригинальном репозитории](https://git.ds1.thiflict.ru/Thiflict/RPIVirusScaner)
|
||||
|
||||
# Raspberry Pi virus checker for USB volumes.
|
||||
## Сканер вирусов на USB флеш-накопителях на базе Raspberry Pi
|
||||
|
||||
@@ -32,15 +35,4 @@
|
||||
|
||||
|
||||
> - Первый контакт тактовой кнопки: GPIO 24 (Физический пин 18)
|
||||
> - Второй контакт тактовой кнопки: Любой из GND (Физические пины: 6, 9, 14, 20, 25, 30, 34, 39)
|
||||
|
||||
Для загрузки можно также воспользоваться скриптом установки. **(НЕ ТЕСТИРОВАН!)**
|
||||
Для этого его необходимо загрузить из релиза или из исходника, затем сделать его executable
|
||||
|
||||
```bash
|
||||
sudo chmod +x install_script.sh
|
||||
```
|
||||
Затем, выполнить его от имени суперпользователя:
|
||||
```bash
|
||||
sudo ./install_script.sh
|
||||
```
|
||||
> - Второй контакт тактовой кнопки: Любой из GND (Физические пины: 6, 9, 14, 20, 25, 30, 34, 39)
|
||||
@@ -6,12 +6,13 @@ import ru.thiflict.PinConfig.BUTTON
|
||||
import java.io.BufferedReader
|
||||
import java.io.InputStreamReader
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
|
||||
// Событие клика по кнопке
|
||||
class ButtonClickEvent
|
||||
class ButtonLongPressEvent
|
||||
|
||||
// Слушатель событий клика
|
||||
typealias ButtonClickListener = (ButtonClickEvent) -> Unit
|
||||
typealias ButtonLongPressListener = (ButtonLongPressEvent) -> Unit
|
||||
|
||||
class ButtonListener(
|
||||
private var process: Process? = null,
|
||||
@@ -19,63 +20,105 @@ class ButtonListener(
|
||||
private var isListening: AtomicBoolean = AtomicBoolean(false),
|
||||
private var listenerJob: Job? = null
|
||||
) {
|
||||
|
||||
private val clickListeners = mutableListOf<ButtonClickListener>()
|
||||
private val longPressListeners = mutableListOf<ButtonLongPressListener>()
|
||||
|
||||
var shortPressThresholdMs: Long = 100
|
||||
var longPressThresholdMs: Long = 1000
|
||||
|
||||
private var pressStartTime: Long = 0
|
||||
|
||||
fun addClickListener(listener: ButtonClickListener) {
|
||||
clickListeners.add(listener)
|
||||
}
|
||||
|
||||
fun addLongPressListener(listener: ButtonLongPressListener) {
|
||||
longPressListeners.add(listener)
|
||||
}
|
||||
|
||||
private fun notifyClick() {
|
||||
println("=== [CLICK] Короткое нажатие ===")
|
||||
val event = ButtonClickEvent()
|
||||
clickListeners.forEach { it.invoke(event) }
|
||||
}
|
||||
|
||||
private fun notifyLongPress() {
|
||||
println("=== [LONG] Длинное нажатие ===")
|
||||
val event = ButtonLongPressEvent()
|
||||
longPressListeners.forEach { it.invoke(event) }
|
||||
}
|
||||
|
||||
fun startListening(onStateChange: ((Boolean) -> Unit)? = null): Boolean {
|
||||
if (isListening.get()) {
|
||||
return currentButtonState.get()
|
||||
}
|
||||
|
||||
startListeningInternal(onStateChange)
|
||||
return currentButtonState.get()
|
||||
}
|
||||
|
||||
private fun startListeningInternal(onStateChange: ((Boolean) -> Unit)? = null) {
|
||||
try {
|
||||
val cmd = listOf("gpiomon", "--chip=0", "$BUTTON")
|
||||
val processBuilder = ProcessBuilder(cmd)
|
||||
.redirectErrorStream(true)
|
||||
|
||||
// Сохраняем процесс в поле
|
||||
process = processBuilder.start()
|
||||
isListening.set(true)
|
||||
|
||||
listenerJob = CoroutineScope(Dispatchers.IO).launch {
|
||||
// Используем process, который теперь не null
|
||||
val reader = BufferedReader(InputStreamReader(process!!.inputStream))
|
||||
var line: String?
|
||||
|
||||
while (reader.readLine().also { line = it } != null) {
|
||||
println(if (isDebug) "$line" else "")
|
||||
when {
|
||||
line?.contains("rising") == true -> {
|
||||
currentButtonState.set(true)
|
||||
onStateChange?.invoke(true)
|
||||
println(if (isDebug) "Кнопка нажата" else "")
|
||||
// Генерируем событие клика при нажатии
|
||||
notifyClick()
|
||||
}
|
||||
line?.contains("falling") == true -> {
|
||||
currentButtonState.set(false)
|
||||
onStateChange?.invoke(false)
|
||||
println(if (isDebug) "Кнопка разжата" else "")
|
||||
// Убрана проверка на разжатие для генерации события
|
||||
try {
|
||||
while (reader.readLine().also { line = it } != null) {
|
||||
println(if (isDebug) "$line" else "")
|
||||
when {
|
||||
line?.contains("rising") == true -> {
|
||||
currentButtonState.set(true)
|
||||
onStateChange?.invoke(true)
|
||||
pressStartTime = System.currentTimeMillis()
|
||||
println(if (isDebug) "Кнопка нажата, время: $pressStartTime" else "")
|
||||
}
|
||||
line?.contains("falling") == true -> {
|
||||
val pressDuration = System.currentTimeMillis() - pressStartTime
|
||||
currentButtonState.set(false)
|
||||
onStateChange?.invoke(false)
|
||||
println(if (isDebug) "Кнопка отпущена, длительность: ${pressDuration}ms" else "")
|
||||
|
||||
when {
|
||||
pressDuration >= longPressThresholdMs -> {
|
||||
println(if (isDebug) "Длинное нажатие (${pressDuration}ms)" else "")
|
||||
notifyLongPress()
|
||||
}
|
||||
pressDuration >= shortPressThresholdMs -> {
|
||||
println(if (isDebug) "Короткое нажатие (${pressDuration}ms)" else "")
|
||||
notifyClick()
|
||||
}
|
||||
else -> {
|
||||
println(if (isDebug) "Слишком короткое нажатие (${pressDuration}ms) - игнорируем" else "")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
println("Ошибка чтения процесса: ${e.message}")
|
||||
}
|
||||
|
||||
val exitCode = process!!.waitFor()
|
||||
println(if (isDebug) "Процесс завершён ($exitCode)" else "")
|
||||
println("Процесс завершён ($exitCode)")
|
||||
isListening.set(false)
|
||||
|
||||
if (isListening.get()) {
|
||||
println("Перезапуск прослушивания...")
|
||||
delay(100.milliseconds)
|
||||
startListeningInternal(onStateChange)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
isListening.set(false)
|
||||
}
|
||||
return currentButtonState.get()
|
||||
}
|
||||
}
|
||||
@@ -6,18 +6,15 @@ class GPIOController(private val pin: Int) {
|
||||
|
||||
fun setValue(value: Int) {
|
||||
try {
|
||||
// Пробуем разные варианты синтаксиса gpioset
|
||||
val commands = listOf("gpioset", "--chip=0", "$pin=$value")
|
||||
|
||||
try {
|
||||
val process = ProcessBuilder(commands)
|
||||
.redirectErrorStream(true)
|
||||
.start()
|
||||
Thread.sleep(50)
|
||||
process.destroy()
|
||||
} catch (e: Exception) {
|
||||
// Пробуем следующую команду
|
||||
}
|
||||
try {
|
||||
val process = ProcessBuilder(commands)
|
||||
.redirectErrorStream(true)
|
||||
.start()
|
||||
Thread.sleep(30)
|
||||
process.destroy()
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
|
||||
} catch (e: Exception) {
|
||||
println(if (isDebug) "Ошибка установки GPIO $pin = $value: ${e.message}" else "")
|
||||
@@ -38,10 +35,4 @@ class GPIOController(private val pin: Int) {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
fun close() {
|
||||
// Ничего не делаем
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -8,8 +8,8 @@ import java.io.InputStreamReader
|
||||
import kotlin.system.exitProcess
|
||||
import java.util.*
|
||||
import java.util.concurrent.*
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
|
||||
// Конфигурация GPIO (BCM номера)
|
||||
object PinConfig {
|
||||
const val GREEN_LED = 17
|
||||
const val YELLOW_LED = 27
|
||||
@@ -25,9 +25,8 @@ object DebugMode {
|
||||
}
|
||||
}
|
||||
|
||||
// Состояния системы
|
||||
enum class SystemState {
|
||||
IDLE, SCANNING, CLEAN, INFECTED, ERROR, INIT
|
||||
IDLE, SCANNING, CLEAN, INFECTED, ERROR, INIT, SAMBA
|
||||
}
|
||||
|
||||
class USBVirusScanner {
|
||||
@@ -47,22 +46,19 @@ class USBVirusScanner {
|
||||
println(if (isDebug) "Инициализация..." else "")
|
||||
|
||||
try {
|
||||
// Проверяем доступность gpiod
|
||||
checkLibgpiod()
|
||||
checkLibgpiod() // Проверка установленных библиотек
|
||||
|
||||
greenLed = GPIOController(PinConfig.GREEN_LED)
|
||||
yellowLed = GPIOController(PinConfig.YELLOW_LED)
|
||||
redLed = GPIOController(PinConfig.RED_LED)
|
||||
|
||||
// Выключаем все светодиоды
|
||||
greenLed.setValue(0)
|
||||
yellowLed.setValue(0)
|
||||
redLed.setValue(0)
|
||||
|
||||
// Запускаем индикацию состояния
|
||||
startStateIndication()
|
||||
startStateIndication() // Запуск системы индикации
|
||||
|
||||
antivirusDatabaseUpdater()
|
||||
antivirusDatabaseUpdater() // Первоначальная проверка обновлений антивирусных баз данных
|
||||
|
||||
Thread.sleep(1000)
|
||||
|
||||
@@ -72,7 +68,7 @@ class USBVirusScanner {
|
||||
|
||||
} catch (e: Exception) {
|
||||
currentState = SystemState.ERROR
|
||||
println(if (isDebug) "❌ Ошибка инициализации: ${e.message}" else "")
|
||||
println(if (isDebug) "Ошибка инициализации: ${e.message}" else "")
|
||||
e.printStackTrace()
|
||||
throw e
|
||||
}
|
||||
@@ -88,30 +84,16 @@ class USBVirusScanner {
|
||||
}
|
||||
|
||||
val output = process.inputStream.bufferedReader().readText()
|
||||
println(if (isDebug) "✅ libgpiod найден" else "")
|
||||
println(if (isDebug) "libgpiod найден" else "")
|
||||
if (output.isNotBlank()) {
|
||||
println(if (isDebug) "Доступные чипы: ${output.trim()}" else "")
|
||||
}
|
||||
|
||||
} catch (e: Exception) {
|
||||
throw Exception(if (isDebug) "libgpiod Не установлен!" else "")
|
||||
} catch (_: Exception) {
|
||||
throw Exception(if (isDebug) "libgpiod Не установлен" else "")
|
||||
}
|
||||
}
|
||||
|
||||
fun buttonPress(defaultButtonState: Boolean): Boolean {
|
||||
var finalButtonState = defaultButtonState
|
||||
println(if (isDebug) "Начало finalButtonState: $finalButtonState" else "")
|
||||
|
||||
val buttonListener = ButtonListener()
|
||||
val initialState = buttonListener.startListening { isPressed ->
|
||||
if (isPressed) {
|
||||
finalButtonState = true
|
||||
}
|
||||
}
|
||||
println(if (isDebug) "finalButtonState: $finalButtonState" else "")
|
||||
return finalButtonState
|
||||
}
|
||||
|
||||
private fun startStateIndication() {
|
||||
indicationJob = scope.launch {
|
||||
while (isRunning) {
|
||||
@@ -120,45 +102,56 @@ class USBVirusScanner {
|
||||
greenLed.setValue(1)
|
||||
yellowLed.setValue(1)
|
||||
redLed.setValue(1)
|
||||
delay(200)
|
||||
delay(200.milliseconds)
|
||||
|
||||
greenLed.setValue(0)
|
||||
yellowLed.setValue(0)
|
||||
redLed.setValue(0)
|
||||
delay(200)
|
||||
delay(200.milliseconds)
|
||||
}
|
||||
|
||||
SystemState.IDLE -> {
|
||||
// Зелёный медленно мигает
|
||||
blinkLed(greenLed, 1000)
|
||||
yellowLed.setValue(0)
|
||||
redLed.setValue(0)
|
||||
}
|
||||
|
||||
SystemState.SCANNING -> {
|
||||
// Жёлтый быстро мигает
|
||||
greenLed.setValue(0)
|
||||
blinkLed(yellowLed, 150)
|
||||
redLed.setValue(0)
|
||||
}
|
||||
|
||||
SystemState.CLEAN -> {
|
||||
// Зелёный горит
|
||||
greenLed.setValue(1)
|
||||
yellowLed.setValue(0)
|
||||
redLed.setValue(0)
|
||||
delay(100)
|
||||
delay(100.milliseconds)
|
||||
}
|
||||
|
||||
SystemState.INFECTED -> {
|
||||
// Красный горит
|
||||
greenLed.setValue(0)
|
||||
yellowLed.setValue(0)
|
||||
redLed.setValue(1)
|
||||
delay(100)
|
||||
delay(100.milliseconds)
|
||||
}
|
||||
|
||||
SystemState.ERROR -> {
|
||||
// Красный мигает
|
||||
greenLed.setValue(0)
|
||||
yellowLed.setValue(0)
|
||||
blinkLed(redLed, 500)
|
||||
}
|
||||
|
||||
SystemState.SAMBA -> {
|
||||
blinkLed(greenLed, 200)
|
||||
blinkLed(yellowLed, 200)
|
||||
redLed.setValue(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -166,9 +159,9 @@ class USBVirusScanner {
|
||||
|
||||
private suspend fun blinkLed(led: GPIOController, intervalMs: Long) {
|
||||
led.setValue(1)
|
||||
delay(intervalMs / 2)
|
||||
delay((intervalMs / 2).milliseconds)
|
||||
led.setValue(0)
|
||||
delay(intervalMs / 2)
|
||||
delay((intervalMs / 2).milliseconds)
|
||||
}
|
||||
|
||||
fun startScan() {
|
||||
@@ -188,12 +181,12 @@ class USBVirusScanner {
|
||||
if (usbDevices.isEmpty()) {
|
||||
println(if (isDebug) "Устройства не найдены" else "")
|
||||
currentState = SystemState.ERROR
|
||||
delay(5000)
|
||||
delay(5000.milliseconds)
|
||||
currentState = SystemState.IDLE
|
||||
return@launch
|
||||
}
|
||||
|
||||
println(if (isDebug) "📀 Найдены USB-устройства:" else "")
|
||||
println(if (isDebug) "Найдены USB-устройства:" else "")
|
||||
usbDevices.forEach { device ->
|
||||
println(" - ${device.mountPoint}")
|
||||
}
|
||||
@@ -203,30 +196,28 @@ class USBVirusScanner {
|
||||
val scanResults = mutableListOf<ScanResult>()
|
||||
|
||||
for (device in usbDevices) {
|
||||
println(if (isDebug) "🔍 Сканирование: ${device.mountPoint}" else "")
|
||||
println(if (isDebug) "Сканирование: ${device.mountPoint}" else "")
|
||||
val result = scanWithClamAV(device.mountPoint)
|
||||
scanResults.add(result)
|
||||
|
||||
if (result.isInfected) {
|
||||
hasVirus = true
|
||||
println(if (isDebug) "⚠️ ВНИМАНИЕ! Найдены угрозы!" else "")
|
||||
println(if (isDebug) "ВНИМАНИЕ! Найдены угрозы!" else "")
|
||||
result.infectedFiles.take(10).forEach { file ->
|
||||
println(" 🦠 ${file.take(100)}")
|
||||
println(" - ${file.take(100)}")
|
||||
}
|
||||
if (result.infectedFiles.size > 10) {
|
||||
println(if (isDebug) " ... и ещё ${result.infectedFiles.size - 10} файлов" else "")
|
||||
}
|
||||
unmount()
|
||||
} else if (result.error != null) {
|
||||
println(if (isDebug) "❌ Ошибка сканирования: ${result.error}" else "")
|
||||
println(if (isDebug) "Ошибка сканирования: ${result.error}" else "")
|
||||
} else {
|
||||
println(if (isDebug) "✅ Сканирование завершено: угроз не найдено" else "")
|
||||
println(if (isDebug) "Сканирование завершено: угроз не найдено" else "")
|
||||
}
|
||||
println()
|
||||
}
|
||||
|
||||
// Сохраняем лог
|
||||
saveScanLog(scanResults)
|
||||
|
||||
currentState = if (hasVirus) {
|
||||
SystemState.INFECTED
|
||||
} else {
|
||||
@@ -234,21 +225,41 @@ class USBVirusScanner {
|
||||
}
|
||||
|
||||
val message = if (hasVirus) {
|
||||
if (isDebug) "🦠 Найдены вирусы! Красный LED горит" else ""
|
||||
if (isDebug) "Debug: Найдены вирусы" else ""
|
||||
} else {
|
||||
if (isDebug) "✅ Флешка чиста! Зелёный LED горит" else ""
|
||||
if (isDebug) "Debug: Флешка чиста" else ""
|
||||
}
|
||||
println(if (isDebug) message else "")
|
||||
|
||||
// Держим состояние 5 секунд
|
||||
delay(5000)
|
||||
delay(10000.milliseconds) // Удерживание состояния на 10 секунд
|
||||
|
||||
if (!hasVirus) {
|
||||
currentState = SystemState.SAMBA
|
||||
sambaStartSharing()
|
||||
|
||||
val buttonListener = ButtonListener()
|
||||
var isEventHappened = false
|
||||
|
||||
buttonListener.addLongPressListener { _ ->
|
||||
isEventHappened = true
|
||||
}
|
||||
buttonListener.startListening()
|
||||
while (!isEventHappened) {
|
||||
delay(500.milliseconds)
|
||||
}
|
||||
}
|
||||
|
||||
currentState = SystemState.IDLE
|
||||
|
||||
} catch (e: Exception) {
|
||||
println(if (isDebug) "❌ Критическая ошибка: ${e.message}" else "")
|
||||
} catch (_: kotlinx.coroutines.CancellationException) {
|
||||
currentState = SystemState.IDLE
|
||||
println(if (isDebug) "Программа получила CancellationException. Возврат к состоянию IDLE." else "")
|
||||
}
|
||||
catch (e: Exception) {
|
||||
println(if (isDebug) "Критическая ошибка: ${e.message}" else "")
|
||||
e.printStackTrace()
|
||||
currentState = SystemState.ERROR
|
||||
delay(5000)
|
||||
delay(10000.milliseconds)
|
||||
currentState = SystemState.IDLE
|
||||
}
|
||||
|
||||
@@ -259,8 +270,7 @@ class USBVirusScanner {
|
||||
private fun findUSBDevices(): List<USBDevice> {
|
||||
val devices = mutableListOf<USBDevice>()
|
||||
|
||||
try {
|
||||
// Проверяем /media директории
|
||||
try { // Проверка директории /media
|
||||
val mediaDirs = listOf("/media", "/media/pi")
|
||||
|
||||
for (mediaDirPath in mediaDirs) {
|
||||
@@ -285,7 +295,7 @@ class USBVirusScanner {
|
||||
}
|
||||
}
|
||||
|
||||
// Проверяем /proc/mounts для дополнительных точек монтирования
|
||||
// Проверка /proc/mounts не предмет дополнительных точек монтирования
|
||||
val mountsFile = File("/proc/mounts")
|
||||
if (mountsFile.exists()) {
|
||||
mountsFile.readLines().forEach { line ->
|
||||
@@ -295,7 +305,8 @@ class USBVirusScanner {
|
||||
|
||||
if ((mountPoint.startsWith("/media")) &&
|
||||
File(mountPoint).exists() &&
|
||||
devices.none { it.mountPoint == mountPoint }) {
|
||||
devices.none { it.mountPoint == mountPoint }
|
||||
) {
|
||||
|
||||
devices.add(USBDevice("auto", mountPoint))
|
||||
}
|
||||
@@ -316,7 +327,7 @@ class USBVirusScanner {
|
||||
|
||||
try {
|
||||
// Проверяем установлен ли ClamAV
|
||||
val checkProcess = ProcessBuilder("which", "clamscan").start()
|
||||
val checkProcess = ProcessBuilder("which", "clamdscan").start()
|
||||
val checkExitCode = checkProcess.waitFor()
|
||||
|
||||
if (checkExitCode != 0) {
|
||||
@@ -325,11 +336,11 @@ class USBVirusScanner {
|
||||
infectedFiles = emptyList(),
|
||||
virusNames = emptyMap(),
|
||||
exitCode = -1,
|
||||
error = if (isDebug) "ClamAV не установлен. Установите: sudo apt install clamav" else ""
|
||||
error = if (isDebug) "ClamAV не установлен." else ""
|
||||
)
|
||||
}
|
||||
|
||||
// Проверяем существование пути
|
||||
// Проверка существования пути
|
||||
val pathFile = File(path)
|
||||
if (!pathFile.exists() || !pathFile.isDirectory) {
|
||||
return ScanResult(
|
||||
@@ -337,20 +348,18 @@ class USBVirusScanner {
|
||||
infectedFiles = emptyList(),
|
||||
virusNames = emptyMap(),
|
||||
exitCode = -1,
|
||||
error = if (isDebug)"Путь не существует или не является директорией: $path" else ""
|
||||
error = if (isDebug) "Путь не существует или не является директорией: $path" else ""
|
||||
)
|
||||
}
|
||||
|
||||
println(if (isDebug) " Запуск clamscan (это может занять некоторое время)..." else "")
|
||||
println(if (isDebug) " Запуск clamdcan..." else "")
|
||||
|
||||
// Запускаем ClamAV
|
||||
// Запуск непосредственной антивирусной проверки
|
||||
val processBuilder = ProcessBuilder(
|
||||
"clamscan",
|
||||
"-r",
|
||||
"clamdscan",
|
||||
"--multiscan",
|
||||
"--stdout",
|
||||
"--infected",
|
||||
"--max-filesize=1M",
|
||||
"--max-scansize=10M",
|
||||
path
|
||||
)
|
||||
|
||||
@@ -360,7 +369,7 @@ class USBVirusScanner {
|
||||
val output = process.inputStream.bufferedReader().readText()
|
||||
val exitCode = process.waitFor()
|
||||
|
||||
// Парсим вывод
|
||||
// Парс вывода
|
||||
output.lines().forEach { line ->
|
||||
if (line.contains(" FOUND")) {
|
||||
val colonIndex = line.indexOf(": ")
|
||||
@@ -382,7 +391,7 @@ class USBVirusScanner {
|
||||
)
|
||||
|
||||
} catch (e: Exception) {
|
||||
println(if (isDebug) " Ошибка при выполнении clamscan: ${e.message}" else "")
|
||||
println(if (isDebug) "Ошибка при выполнении clamdscan: ${e.message}" else "")
|
||||
return ScanResult(
|
||||
isInfected = false,
|
||||
infectedFiles = emptyList(),
|
||||
@@ -393,47 +402,56 @@ class USBVirusScanner {
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveScanLog(results: List<ScanResult>) {
|
||||
suspend fun sambaStartSharing() {
|
||||
try {
|
||||
val logDir = File("/home/${System.getProperty("user.name")}/usb-scanner-logs")
|
||||
if (!logDir.exists()) {
|
||||
logDir.mkdirs()
|
||||
currentState = SystemState.SAMBA
|
||||
|
||||
var process: Process? = null
|
||||
val sambaStartServiceCmd = listOf("systemctl", "start", "smbd")
|
||||
val processBuilder = ProcessBuilder(sambaStartServiceCmd)
|
||||
.redirectErrorStream(true)
|
||||
|
||||
process = withContext(Dispatchers.IO) {
|
||||
processBuilder.start()
|
||||
}
|
||||
|
||||
val timestamp = System.currentTimeMillis()
|
||||
val logFile = File(logDir, "scan_$timestamp.log")
|
||||
|
||||
logFile.bufferedWriter().use { writer ->
|
||||
writer.write("=== USB Virus Scanner Log ===\n")
|
||||
writer.write("Time: ${java.time.LocalDateTime.now()}\n\n")
|
||||
|
||||
results.forEachIndexed { index, result ->
|
||||
writer.write("Device ${index + 1}:\n")
|
||||
if (result.isInfected) {
|
||||
writer.write("Status: INFECTED\n")
|
||||
writer.write("Found ${result.infectedFiles.size} infected files:\n")
|
||||
result.infectedFiles.take(20).forEach { file ->
|
||||
writer.write(" $file: ${result.virusNames[file]}\n")
|
||||
}
|
||||
if (result.infectedFiles.size > 20) {
|
||||
writer.write(" ... and ${result.infectedFiles.size - 20} more files\n")
|
||||
}
|
||||
} else if (result.error != null) {
|
||||
writer.write("Status: ERROR\n")
|
||||
writer.write("Error: ${result.error}\n")
|
||||
} else {
|
||||
writer.write("Status: CLEAN\n")
|
||||
}
|
||||
writer.write("\n")
|
||||
}
|
||||
}
|
||||
|
||||
println(if (isDebug) "📝 Лог сохранён: ${logFile.absolutePath}" else "")
|
||||
} catch (e: Exception) {
|
||||
println(if (isDebug) "Ошибка сохранения лога: ${e.message}" else "")
|
||||
e.printStackTrace()
|
||||
currentState = SystemState.ERROR
|
||||
delay(10000.milliseconds)
|
||||
}
|
||||
}
|
||||
|
||||
fun sambaShutdown() {
|
||||
unmount()
|
||||
try {
|
||||
var process: Process? = null
|
||||
val sambaStopServiceCmd = listOf("systemctl", "stop", "smbd")
|
||||
val processBuilder = ProcessBuilder(sambaStopServiceCmd)
|
||||
.redirectErrorStream(true)
|
||||
process = processBuilder.start()
|
||||
scanJob?.cancel()
|
||||
currentState = SystemState.IDLE
|
||||
} catch (_: Exception) {}
|
||||
}
|
||||
|
||||
fun unmount() {
|
||||
for (i in 0..9) {
|
||||
val path = if (i == 0) "/media/usb" else "/media/usb$i"
|
||||
try {
|
||||
val processBuilder = ProcessBuilder("umount", "-f", path)
|
||||
.redirectErrorStream(true)
|
||||
val process = processBuilder.start()
|
||||
val exitCode = process.waitFor()
|
||||
if (exitCode == 0) {
|
||||
println(if (isDebug) "Успешно размонтировано: $path" else "")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
println(if (isDebug) "Ошибка при размонтировании $path: ${e.message}" else "")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
fun shutdown() {
|
||||
println(if (isDebug) "\nЗавершение работы..." else "")
|
||||
isRunning = false
|
||||
@@ -443,17 +461,13 @@ class USBVirusScanner {
|
||||
|
||||
scope.cancel()
|
||||
|
||||
// Выключаем все светодиоды
|
||||
try {
|
||||
if (::greenLed.isInitialized) {
|
||||
greenLed.setValue(0)
|
||||
yellowLed.setValue(0)
|
||||
redLed.setValue(0)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// Игнорируем ошибки при закрытии
|
||||
}
|
||||
|
||||
} catch (_: Exception) {}
|
||||
println(if (isDebug) "✅ Система остановлена" else "")
|
||||
}
|
||||
}
|
||||
@@ -497,7 +511,7 @@ fun scheduleUpdaterAt3AM() {
|
||||
TimeUnit.MILLISECONDS
|
||||
)
|
||||
|
||||
println("Планировщик запущен. Первый запуск через ${initialDelay / 1000 / 60} минут")
|
||||
println(if (isDebug) "Планировщик обновления антивирусных баз запущен." else "")
|
||||
}
|
||||
|
||||
fun antivirusDatabaseUpdater() {
|
||||
@@ -521,15 +535,7 @@ fun main(args: Array<String>) {
|
||||
if (args.contains("--debug")) {
|
||||
DebugMode.enableDebugging()
|
||||
}
|
||||
|
||||
scheduleUpdaterAt3AM()
|
||||
|
||||
println(if (isDebug) "Зелёный - ${PinConfig.GREEN_LED}" else "")
|
||||
println(if (isDebug) "Жёлтый - ${PinConfig.YELLOW_LED}" else "")
|
||||
println(if (isDebug) "Красный - ${PinConfig.RED_LED}" else "")
|
||||
println(if (isDebug) "Кнопка - ${PinConfig.BUTTON}" else "")
|
||||
|
||||
val defaultButtonState = false
|
||||
val scanner = USBVirusScanner()
|
||||
|
||||
Runtime.getRuntime().addShutdownHook(Thread {
|
||||
@@ -540,29 +546,26 @@ fun main(args: Array<String>) {
|
||||
scanner.initialize()
|
||||
|
||||
val buttonListener = ButtonListener()
|
||||
buttonListener.addClickListener { event ->
|
||||
buttonListener.addClickListener { _ ->
|
||||
scanner.startScan()
|
||||
}
|
||||
buttonListener.addLongPressListener { _ ->
|
||||
scanner.sambaShutdown()
|
||||
}
|
||||
|
||||
buttonListener.startListening()
|
||||
|
||||
println(if (isDebug) """
|
||||
═══════════════════════════════════════
|
||||
USB Virus Scanner готов к работе
|
||||
═══════════════════════════════════════
|
||||
📌 Вставьте флешку и нажмите кнопку
|
||||
📌 Зелёный LED мигает - режим ожидания
|
||||
📌 Жёлтый LED мигает - идёт проверка
|
||||
📌 Зелёный LED горит - флешка чиста
|
||||
📌 Красный LED горит - найдены вирусы
|
||||
📌 Для выхода нажмите Ctrl+C
|
||||
""".trimIndent() else "")
|
||||
println(
|
||||
if (isDebug) "!!! ПРОГРАММА ПОЛНОСТЬЮ ГОТОВА К РАБОТЕ !!!" else ""
|
||||
)
|
||||
|
||||
while (true) {
|
||||
Thread.sleep(1000)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
println(if (isDebug) "❌ Критическая ошибка: ${e.message}" else "")
|
||||
e.printStackTrace()
|
||||
println(if (isDebug) "Критическая ошибка: ${e.message}" else "")
|
||||
if (isDebug) e.printStackTrace()
|
||||
if (isDebug) println("Общий Exception")
|
||||
scanner.shutdown()
|
||||
exitProcess(1)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user