Subversion Repositories Kolibri OS

Rev

Rev 8466 | Rev 8565 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
8542 superturbo 1
/* Copyright (C) 2019-2021 Logaev Maxim (turbocat2001), GPLv2 */
8430 superturbo 2
 
8073 superturbo 3
#include 
8430 superturbo 4
#include 
8073 superturbo 5
#include 
8373 superturbo 6
#include 
8073 superturbo 7
#include 
8373 superturbo 8
#include 
9
#include 
10
#include 
8430 superturbo 11
#include 
8466 superturbo 12
#include 
8073 superturbo 13
 
14
#define TRUE 1;
15
#define FALSE 0;
16
#define MAX_HASH_LEN 65 // Максимальная длина строки
17
#define WINDOW_W 665
8466 superturbo 18
#define VERSION "%s - thashview 2.6"
19
#define EDIT_TEXT_SIZE 0x10000000
8073 superturbo 20
 
21
struct kolibri_system_colors sys_color_table;
22
 
23
char hash_str_md5[MAX_HASH_LEN]=   "Click the 'MD5:' button to show the md5-checksum!      "; //Вывод MD5
24
char hash_str_sha1[MAX_HASH_LEN]=  "Click the 'SHA1:' button to show the sha1-checksum!    "; //Вывод SHA1
25
char hash_str_sha256[MAX_HASH_LEN]="Click the 'SHA256:' button to show the sha256-checksum!"; //Вывод SHA256
26
char edit_box_buff[MAX_HASH_LEN]; // Буффер для ввода
27
char *filename; // Имя обрабатываемого файла
28
char *title; // Заголовок окна
29
 
30
enum MYCOLORS // Цвета
31
{
8466 superturbo 32
    GREEN = 0x067D06 | EDIT_TEXT_SIZE,
33
    RED   = 0xFF0000 | EDIT_TEXT_SIZE,
34
    BLACK = 0x000000 | EDIT_TEXT_SIZE,
35
    WHITE = 0xFFFFFF,
36
    GREY  = 0x919191
8073 superturbo 37
};
38
 
8466 superturbo 39
edit_box hash_edit_box={WINDOW_W-140,10,121,WHITE,0,0,GREY,EDIT_TEXT_SIZE, MAX_HASH_LEN-1, edit_box_buff,NULL,ed_focus}; // Создаём структуру edit_box
8073 superturbo 40
int md5_flag=0, sha1_flag=0, sha256_flag=0; // Флаги показывающие была ли уже рассчитана котрольная сумма в функции check_sum()
41
 
42
enum BUTTONS // Кнопки в интрефейсе
43
{
44
    BTN_QUIT=1,        //Выход
45
    BTN_MD5 = 10,      //Рассчитать md5-контрольную сумму
46
    BTN_SHA1 = 20,     //Рассчитать sha1-контрольную сумму
47
    BTN_SHA256 = 30,   //Рассчитать sha256-контрольную сумму
48
    BTN_COPY_MD5= 11,  //Скопировать в буффер обмена
49
    BTN_COPY_SHA1= 21,
50
    BTN_COPY_SHA256=31,
51
    BTN_CMP=40,        //Сравнить edit_box и контрольную сумму
52
    BTN_PASTE=50       //Вставить в edit_box(пока в разработке)
53
};
54
 
8373 superturbo 55
void notify_show(char *text)
56
{
57
   start_app("/sys/@notify", text);
58
}
8073 superturbo 59
 
60
void* safe_malloc(size_t size) // Безопасный malloc. Показывает уведомление об ошибке и закрывает программу если память не была выделена
61
{
62
    void *p=malloc(size);
63
    if(p==NULL)
64
    {
65
       notify_show("'Memory allocation error!' -E");
66
       exit(0);
67
    }
68
    else
69
    {
70
        return p;
71
    }
72
}
73
 
74
void global_var_init(unsigned int size)  // Инициализируются глобальные массивы
75
{
76
  filename=safe_malloc(size);
77
  title=safe_malloc(size+20);
78
}
79
 
80
/* Функции генерации контрольных сумм */
81
void md5_hash(FILE* input, BYTE* hash )
82
{
83
    int input_size;
84
    BYTE *temp_buffer;
85
    temp_buffer=safe_malloc(1024);
86
    MD5_CTX ctx;
87
    md5_init(&ctx);
88
    while((input_size = fread(temp_buffer, 1, 1024, input)) > 0){
89
                md5_update(&ctx, temp_buffer, input_size);
90
    }
91
    md5_final(&ctx, hash);
92
    free(temp_buffer);
93
}
94
 
95
void sha1_hash(FILE* input, BYTE* hash )
96
{
97
    int input_size;
98
    BYTE *buffer;
99
    buffer=safe_malloc(1024);
100
    SHA1_CTX ctx;
101
    sha1_init(&ctx);
102
    while((input_size = fread(buffer, 1, 1024, input)) > 0){
103
                sha1_update(&ctx, buffer, input_size);
104
    }
105
    sha1_final(&ctx, hash);
106
    free(buffer);
107
}
108
 
109
void sha256_hash(FILE* input, BYTE* hash )
110
{
111
    int input_size;
112
    BYTE *buffer;
113
    buffer=safe_malloc(1024);
114
    SHA256_CTX ctx;
115
    sha256_init(&ctx);
116
    while((input_size = fread(buffer, 1, 1024, input)) > 0){
117
                sha256_update(&ctx, buffer, input_size);
118
    }
119
    sha256_final(&ctx, hash);
120
    free(buffer);
121
}
122
 
123
 
124
BYTE* check_sum(int alg) // Генерируем контрольные суммы используя один из алгоритмов
125
{
126
    FILE* input_file;
127
    BYTE *hash;
128
    input_file=fopen(filename,"rb");
129
    hash = safe_malloc(alg);
130
    switch (alg)
131
    {
132
        case MD5_BLOCK_SIZE :
133
            md5_hash(input_file, hash);
134
            md5_flag=1;
135
        break;
136
 
137
        case SHA1_BLOCK_SIZE :
138
            sha1_hash(input_file, hash);
139
            sha1_flag=1;
140
        break;
141
 
142
        case SHA256_BLOCK_SIZE :
143
            sha256_hash(input_file, hash);
144
            sha256_flag=1;
145
        break;
146
    }
147
    fclose(input_file);
148
    return hash;
149
}
150
 
151
void sprint_hash(BYTE *hash, char* hash_str, int hash_size) //Преобрауем двоичные данные из hash в строку hash_str
152
{
153
    char block[3];
154
    memset(hash_str, 0, MAX_HASH_LEN); // Очищаем строку для strcat
155
    for(int i=0; i
156
    {
157
        sprintf(block,"%02x", hash[i]);
158
        strcat(hash_str,block);
159
    }
160
    free(hash);
161
}
162
 
163
void redraw_window() //Рисуем окно
164
{
165
    sprintf(title,VERSION, filename); // Устанавливаем заголовок окна
8430 superturbo 166
    pos_t win_pos = get_mouse_pos(0); // Получаем координаты курсора
8073 superturbo 167
    begin_draw(); //Начинаем рисование интерфейса )
8250 superturbo 168
    sys_create_window(win_pos.x, win_pos.y, WINDOW_W, 150, title, sys_color_table.work_area, 0x14); // Создаём окно.
8073 superturbo 169
 
8466 superturbo 170
    edit_box_draw(&hash_edit_box); // Рисуем edit_box
8073 superturbo 171
 
8466 superturbo 172
    define_button(X_W(10,60), Y_H(30,20), BTN_MD5, GREEN); // Определяем кнопку md5
173
    define_button(X_W(10,60), Y_H(60,20), BTN_SHA1, GREEN);// Определяем кнопку sha1
174
    define_button(X_W(10,60), Y_H(90,20), BTN_SHA256, GREEN);// Определяем кнопку sha256
8073 superturbo 175
 
176
    draw_text_sys("MD5:", 15, 34, 0,   0x90000000 | sys_color_table.work_button_text); // Пищем текст на кнопках
177
    draw_text_sys("SHA1:", 15, 64, 0,  0x90000000 | sys_color_table.work_button_text);
178
    draw_text_sys("SHA256:", 15,94, 0, 0x90000000 | sys_color_table.work_button_text);
179
 
180
    draw_text_sys(hash_str_md5, 80, 34, 0, 0x90000000 | sys_color_table.work_text); // Выводим контрольные суммы в окно
181
    draw_text_sys(hash_str_sha1, 80, 64, 0, 0x90000000 | sys_color_table.work_text);
182
    draw_text_sys(hash_str_sha256, 80, 94, 0, 0x90000000| sys_color_table.work_text);
183
 
8466 superturbo 184
    define_button(X_W(610,42), Y_H(30, 20), BTN_COPY_MD5, sys_color_table.work_button); // Определяем кнопки для копирования
185
    define_button(X_W(610,42), Y_H(60, 20), BTN_COPY_SHA1, sys_color_table.work_button);
186
    define_button(X_W(610,42), Y_H(90, 20), BTN_COPY_SHA256, sys_color_table.work_button);
8073 superturbo 187
 
188
    draw_text_sys("Copy", 615, 34, 0,   0x90000000 | sys_color_table.work_button_text); // Пишем copy на всех кнопках для копирования
189
    draw_text_sys("Copy", 615, 64, 0,  0x90000000 | sys_color_table.work_button_text);
190
    draw_text_sys("Copy", 615, 94, 0, 0x90000000 | sys_color_table.work_button_text);
191
 
8466 superturbo 192
    define_button(X_W(592,60), Y_H(120,20), BTN_CMP, GREEN); // Определяем кнопку для сравнения контольных сумм
8073 superturbo 193
    draw_text_sys("Compare", 595, 124 , 0,0x90000000 | sys_color_table.work_button_text); // Пишем текс на кнопке.
8466 superturbo 194
    define_button(X_W(540, 45), Y_H(120,20), BTN_PASTE, sys_color_table.work_button); //Кнопка для вставки (неработает)
8073 superturbo 195
    draw_text_sys("Paste", 543, 124 , 0,0x90000000 | sys_color_table.work_button_text); // Текст paste на кнопке
196
    end_draw();
197
}
198
 
199
void paste_to_edit_buffer()    // Вставить из буффера обмена
200
{
8250 superturbo 201
    char *temp_buff=NULL;
202
    if(kol_clip_num()>0)
8073 superturbo 203
    {
8250 superturbo 204
        temp_buff=kol_clip_get(kol_clip_num()-1);
205
        memset(edit_box_buff,0,MAX_HASH_LEN);
8430 superturbo 206
        if(DATA(int, temp_buff,0)>0 && DATA(int,temp_buff,4)==TEXT && DATA(int,temp_buff,8)==CP866)
8250 superturbo 207
        {
208
            strncpy(edit_box_buff,temp_buff+12, MAX_HASH_LEN-1);
8466 superturbo 209
            edit_box_set_text(&hash_edit_box,edit_box_buff);
8250 superturbo 210
            notify_show("'Pasted from clipboard!' -I");
8466 superturbo 211
            hash_edit_box.text_color = BLACK;
8250 superturbo 212
            user_free(temp_buff);
213
        }
8073 superturbo 214
    }
215
}
216
 
217
void copy_to_clipboard(char *text) // Копирлвать в буффер обмена
218
{
219
    if(55!=strlen(text))
220
    {
221
        char *temp_buffer=safe_malloc(MAX_HASH_LEN+12);
222
        memset(temp_buffer, 0, MAX_HASH_LEN);
8430 superturbo 223
        DATA(char,temp_buffer,4)=TEXT;
224
        DATA(char,temp_buffer,8)=CP866;
8073 superturbo 225
        strncpy(temp_buffer+12, text, MAX_HASH_LEN-1);
226
        kol_clip_set(strlen(text)+12, temp_buffer);
227
        notify_show("'Copied to clipboard!' -I");
228
        free(temp_buffer);
229
    }
230
}
231
 
232
void print_pending_calc(char *str) // Выводим сообщение о том что контрольная суммма вычисляется.
233
{
234
  strcpy(str, "Please wait! Calculating checksum...                   ");
235
  redraw_window();
236
}
237
 
238
bool calc_and_cmp(char *hash_str_universal,int alg) // Вычисляем контрольную сумму и сравниваем с edit_box_buff.
239
{
240
   print_pending_calc(hash_str_universal);
241
   sprint_hash(check_sum(alg),hash_str_universal, alg);
242
   return !strcmp(edit_box_buff, hash_str_universal);
243
}
244
 
245
bool hash_compare() // Главная функция для сравнения
246
{
247
   int alg=strlen(edit_box_buff)/2;
248
 
249
        switch (alg) // Если вычисления ещё небыло
250
        {
251
        case MD5_BLOCK_SIZE:
8466 superturbo 252
            if(md5_flag){
8073 superturbo 253
                return !strcmp(edit_box_buff,hash_str_md5);
8466 superturbo 254
            }else{
8073 superturbo 255
                return calc_and_cmp(hash_str_md5,alg);
256
            }
257
        break;
258
 
259
        case SHA1_BLOCK_SIZE:
8466 superturbo 260
            if(sha1_flag){
8073 superturbo 261
                return !strcmp(edit_box_buff,hash_str_sha1);
8466 superturbo 262
            }else{
8073 superturbo 263
                return calc_and_cmp(hash_str_sha1,alg);
264
            }
265
        break;
266
 
267
        case SHA256_BLOCK_SIZE:
268
 
8466 superturbo 269
            if(sha256_flag){
8073 superturbo 270
                return !strcmp(edit_box_buff,hash_str_sha256);
8466 superturbo 271
            }else{
8073 superturbo 272
                return calc_and_cmp(hash_str_sha256,alg);
273
            }
274
        break;
275
 
276
        default:
277
            return FALSE;
278
        break;
279
        }
280
}
281
 
282
int main(int argc, char** argv)
283
{
8466 superturbo 284
    kolibri_boxlib_init(); // Загружаем boxlib
8430 superturbo 285
    if(argc<2) // Если аргументов нет, то запускаем диалог выбора файла
8073 superturbo 286
    {
8466 superturbo 287
        kolibri_dialog_init(); // загружаем proc_lib(libdialog)
8430 superturbo 288
        open_dialog* dialog = kolibri_new_open_dialog(OPEN,0, 0, 420, 320);
289
        OpenDialog_init(dialog);
290
        OpenDialog_start(dialog);
291
        if(dialog->status==SUCCESS) // Если файл выбран
292
        {
293
            global_var_init(strlen(dialog->openfile_path));
294
            strcpy(filename, dialog->openfile_path);
295
        }
296
        else // Если файл не выбран
297
        {
298
            notify_show("'No file selected!' -E");
299
            exit(0);
300
        }
301
        free(dialog);
8073 superturbo 302
    }
8430 superturbo 303
    else
304
    {
305
        global_var_init(strlen(argv[1]));
306
        strcpy(filename, argv[1]);
307
    }
8073 superturbo 308
 
309
    if(NULL==fopen(filename,"rb")) // Если файла нет или не открывается
310
    {
311
        notify_show("'File not found!' -E");
312
        exit(0);
313
    }
314
 
315
    if(GetScreenSize()/65536
316
    {
317
        notify_show("'Low screen resolution! Program will not display correctrly!' -W");
318
    }
319
 
8430 superturbo 320
    int gui_event; // Переменная для хранения события
8073 superturbo 321
    uint32_t pressed_button = 0; // Код нажатой кнопки в окне
322
 
323
    get_system_colors(&sys_color_table);
8466 superturbo 324
    hash_edit_box.shift_color=sys_color_table.work_button;
325
 
8430 superturbo 326
    set_event_mask(0xC0000027);// Устанавливаем маску событий
8073 superturbo 327
    do // Цикл обработки событий
328
    {
329
        gui_event = get_os_event(); // Получаем событие
330
        switch(gui_event) // Обрабатываем события
331
        {
332
        case KOLIBRI_EVENT_NONE:
333
            break;
334
        case KOLIBRI_EVENT_REDRAW:
335
            redraw_window();
336
            break;
8466 superturbo 337
        case KOLIBRI_EVENT_MOUSE:
338
            edit_box_mouse(&hash_edit_box);
339
            break;
8073 superturbo 340
        case KOLIBRI_EVENT_KEY:
8466 superturbo 341
            hash_edit_box.text_color = BLACK;
342
            edit_box_key(&hash_edit_box,get_key().val);
8073 superturbo 343
            break;
344
        case KOLIBRI_EVENT_BUTTON: // Событие обработки кнопок
345
            pressed_button = get_os_button(); // Получение кода нажатой кнопки.
346
            switch (pressed_button) // Проверка какая кнопка была нажата
347
            {
348
                case BTN_MD5:
349
                    print_pending_calc(hash_str_md5);
350
                    sprint_hash(check_sum(MD5_BLOCK_SIZE),hash_str_md5, MD5_BLOCK_SIZE);
351
                    redraw_window();
352
                break;
353
 
354
                case BTN_SHA1:
355
                    print_pending_calc(hash_str_sha1);
356
                    sprint_hash(check_sum(SHA1_BLOCK_SIZE),hash_str_sha1, SHA1_BLOCK_SIZE);
357
                    redraw_window();
358
                break;
359
 
360
                case BTN_SHA256:
361
                    print_pending_calc(hash_str_sha256);
362
                    sprint_hash(check_sum(SHA256_BLOCK_SIZE),hash_str_sha256, SHA256_BLOCK_SIZE);
363
                    redraw_window();
364
                break;
365
 
366
                case BTN_COPY_MD5:
8466 superturbo 367
                    copy_to_clipboard(hash_str_md5);
8073 superturbo 368
                    redraw_window();
369
                break;
370
 
371
                case BTN_COPY_SHA1:
8466 superturbo 372
                    copy_to_clipboard(hash_str_sha1);
8073 superturbo 373
                    redraw_window();
374
                break;
375
 
376
                case BTN_COPY_SHA256:
8466 superturbo 377
                    copy_to_clipboard(hash_str_sha256);
8073 superturbo 378
                    redraw_window();
379
                break;
380
 
381
                case BTN_PASTE:
382
                    paste_to_edit_buffer();
383
                    redraw_window();
384
                break;
385
 
386
                case BTN_CMP:
387
                if(hash_compare())
388
                {
389
                    notify_show("'The checksum matches :)' -OK");
8466 superturbo 390
                    hash_edit_box.text_color = GREEN; // Устанавливаем текст ввода зелёным если контрольная сумма совпадает
391
                }else{
8073 superturbo 392
                    notify_show("'The checksum does not match! :(' -W");
8466 superturbo 393
                    hash_edit_box.text_color = RED; // Устанавливаем текст ввода красным если контрольная суммы не совпадает
8073 superturbo 394
                }
395
                redraw_window();
396
                break;
397
 
398
                case BTN_QUIT:
399
                    exit(0);
400
                break;
401
            }
402
        }
403
    }while(1);
8430 superturbo 404
    exit(0);
8073 superturbo 405
}