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