-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickchat.c
More file actions
1620 lines (1337 loc) · 47.9 KB
/
Copy pathquickchat.c
File metadata and controls
1620 lines (1337 loc) · 47.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// QuickChat LAN Messenger by WinXP655.
// Repository: https://github.com/WinXP655/quickchat.
// Distributed under MIT License.
// ======= 1. Headers =======
#include <winsock2.h>
#include <windows.h>
#include <stdbool.h>
#include <stdio.h>
#include <time.h>
#include <commctrl.h>
#include <process.h>
#include <shellapi.h>
#include <errno.h>
#include "key.h" // XOR key here
// ======= 2. Defines =======
// --- Fixed ---
#define SOUND_JOIN 0
#define SOUND_LEAVE 1
#define SOUND_MSG 2
#define BUFFER_SIZE 8192 // Unicode = 2 bytes
#define PORT_QCS 65501
#define PORT_QC 65502
#define QC_LABEL "QC:"
#define INI_FILE L"quickchat.ini"
// --- UI Controls ---
#define ID_EDIT 101
#define ID_SEND 102
#define ID_MSG_DISPLAY 103
// --- Dialog ---
#define IDC_IP 1001
// --- Menu: Connection ---
#define IDM_CLOSE 2001
#define IDM_LEAVE 2002
#define IDM_SAVE 2003
// --- Menu: View ---
#define IDM_ALWAYS_ON_TOP 2101
#define IDM_CLEAR_CHAT 2102
// --- Menu: Options ---
#define ID_FLASH_TOGGLE 2201
#define ID_SOUND_TOGGLE 2202
#define IDM_RESET_SETTINGS 2203
// --- Menu: Help ---
#define IDM_ABOUT 2301
// --- Menu: Other ---
#define IDM_COMPUTER_INFO 2401
#define IDM_PING_REMOTE 2402
// ======= 3. Global variables =======
// ----- Control flags -----
bool is_server = false;
bool xor_enabled = true;
bool logging_enabled = false;
bool is_running = true;
bool sound_enabled = true;
bool flash_enabled = true;
bool always_on_top = false;
int error_counter = 0;
// ----- Network state -----
SOCKET client_socket = INVALID_SOCKET;
HANDLE hReceiveThread = NULL;
wchar_t server_ip[16] = L"127.0.0.1";
wchar_t peer_ip[16] = L"";
wchar_t peer_name[256] = L"";
wchar_t computer_name[256] = L"";
// ----- Logging -----
FILE* chat_log = NULL;
// ----- UI handles -----
HWND hWndGlobal = NULL;
HWND hEdit = NULL;
HWND hSendBtn = NULL;
HWND hMsgDisplay = NULL;
// ----- UI resources -----
WNDPROC oldEditProc = NULL;
HFONT hFontBold = NULL;
HFONT hFontMono = NULL;
// ----- Thread sync -----
volatile BOOL mainWindowReady = FALSE;
// ======= 4. Prototypes =======
// ----- Core Functions -----
void LoadSettings(void);
LONG WINAPI CrashHandler(EXCEPTION_POINTERS* ExceptionInfo);
// ----- Helper Functions -----
void EnableVisualStyles(void);
void PlayNotifySound(int sound);
void AddMessage(const wchar_t* msg);
void DisableChatControls(BOOL disable);
void FlashMessageWindow(HWND hWnd);
void ShowError(const wchar_t* msg, DWORD err);
bool GetDefaultIP(wchar_t* ip_buffer, size_t size);
bool IsValidTargetIP(const wchar_t* ip_str);
void CloseConnection(void);
void Disconnect(void);
void CleanupAndExit(void);
void LogMessage(const wchar_t* message);
void SaveChatToFile(HWND hWnd);
void ResetSettings(HWND hWnd);
void GetLocalComputerName(void);
// ----- Network Core -----
bool InitializeNetwork(bool server_mode, HINSTANCE hInstance, int nCmdShow);
void XorObf(unsigned char* data, int len);
unsigned int __stdcall ReceiveMessages(void* arg);
void SendCurrentMessage(HWND hWnd);
// ----- User Interface -----
INT_PTR CALLBACK ConnectDialogProc(HWND, UINT, WPARAM, LPARAM);
DWORD WINAPI ShowServerIPMessage(LPVOID lpParam);
void ShowMainWindow(HINSTANCE hInstance, int nCmdShow);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void CreateMenuBar(HWND hWnd);
LRESULT CALLBACK EditProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
// ----- Drag and Drop -----
void ProcessDroppedFile(HWND hWnd, HDROP hDrop);
static bool IsValidTextExtension(const wchar_t *path);
static wchar_t* ReadTextFileContent(const wchar_t *path, HWND hWnd);
static void InsertTextIntoEdit(const wchar_t *text);
// ======== 5. Core Functions =======
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) {
(void)hPrevInstance;
(void)lpCmdLine;
SetUnhandledExceptionFilter(CrashHandler);
EnableVisualStyles();
GetLocalComputerName();
LoadSettings();
int mode = MessageBoxW(NULL,
L"Welcome to QuickChat!\n\n"
L"What do you want to do?\n"
L"Yes - Host (wait for connections)\n"
L"No - Join (connect to existing chat)\n"
L"Cancel - Exit",
L"QuickChat", MB_YESNOCANCEL | MB_ICONQUESTION);
if (mode == IDCANCEL) return 0;
is_server = (mode == IDYES);
if (is_server) {
int proto = MessageBoxW(NULL,
L"Select a protocol to use for connection\n\n"
L"Yes - QCS (QuickChat Obfuscated)\n"
L"No - QC (QuickChat, plain text)\n\n"
L"Warning: QC is not recommended as main protocol.",
L"QuickChat", MB_YESNO | MB_ICONQUESTION);
xor_enabled = (proto == IDYES);
int enable_logs = MessageBoxW(NULL,
L"Enable logs for this session?",
L"QuickChat", MB_YESNO | MB_ICONQUESTION);
logging_enabled = (enable_logs == IDYES);
if (logging_enabled) {
chat_log = _wfopen(L"chatlog.txt", L"a");
if (chat_log == NULL) {
wchar_t log_err[512];
swprintf(log_err, sizeof(log_err) / sizeof(wchar_t), L"Failed to open chat log file. Logging will be disabled for this session. Error: %d.", GetLastError());
MessageBoxW(NULL, log_err, L"QuickChat", MB_OK | MB_ICONWARNING);
logging_enabled = false;
} else {
time_t now = time(NULL);
struct tm *t = localtime(&now);
wchar_t timestamp[64];
wcsftime(timestamp, 64, L"%H:%M:%S %d/%m/%Y", t);
fwprintf(chat_log, L"\n=== New session started at %ls ===\n", timestamp);
fflush(chat_log);
}
}
if (!InitializeNetwork(true, hInstance, nCmdShow)) return 0;
} else {
while (1) {
INT_PTR dlg = DialogBoxParamW(hInstance, MAKEINTRESOURCEW(1), NULL, ConnectDialogProc, 0);
if (dlg < 0) {
MessageBoxW(NULL,
L"Could not load connection dialog.",
L"QuickChat", MB_OK | MB_ICONERROR);
return 0;
}
if (dlg != IDOK) return 0;
int proto = MessageBoxW(NULL,
L"Select a protocol to use for connection\n\n"
L"Yes - QCS (QuickChat Obfuscated)\n"
L"No - QC (QuickChat, plain text)\n"
L"Cancel - Return to connection dialog\n\n"
L"Warning: QC is not recommended as main protocol.",
L"QuickChat", MB_YESNOCANCEL | MB_ICONQUESTION);
if (proto == IDCANCEL) continue;
xor_enabled = (proto == IDYES);
break;
}
if (!InitializeNetwork(false, hInstance, nCmdShow)) return 0;
}
PlayNotifySound(SOUND_JOIN);
MSG msg;
while (GetMessageW(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
void LoadSettings(void) {
FILE *settings_file = _wfopen(INI_FILE, L"r");
if (settings_file) {
wchar_t line[128];
while (fgetws(line, sizeof(line) / sizeof(wchar_t), settings_file)) {
size_t len = wcslen(line);
if (len && line[len-1] == L'\n') line[--len] = L'\0';
if (len && line[len-1] == L'\r') line[--len] = L'\0';
if (line[0] == L'\0' || line[0] == L';' || line[0] == L'#') continue;
if (line[0] == L'[') continue;
wchar_t *eq = wcschr(line, L'=');
if (!eq) continue;
*eq = L'\0';
wchar_t *key = line;
wchar_t *val = eq + 1;
while (*key == L' ') key++;
while (*val == L' ') val++;
if (wcscmp(key, L"always_on_top") == 0)
always_on_top = _wtoi(val) != 0;
else if (wcscmp(key, L"flash") == 0)
flash_enabled = _wtoi(val) != 0;
else if (wcscmp(key, L"sound") == 0)
sound_enabled = _wtoi(val) != 0;
}
fclose(settings_file);
}
}
void SaveSettings(void) {
FILE *settings_file = _wfopen(INI_FILE, L"w");
if (settings_file) {
fwprintf(settings_file, L"[QuickChat]\n");
fwprintf(settings_file, L"always_on_top=%d\n", always_on_top ? 1 : 0);
fwprintf(settings_file, L"flash=%d\n", flash_enabled ? 1 : 0);
fwprintf(settings_file, L"sound=%d\n", sound_enabled ? 1 : 0);
fclose(settings_file);
}
}
LONG WINAPI CrashHandler(EXCEPTION_POINTERS* ExceptionInfo) {
DWORD code = ExceptionInfo->ExceptionRecord->ExceptionCode;
void* address = ExceptionInfo->ExceptionRecord->ExceptionAddress;
wchar_t user_msg[512];
swprintf(user_msg, sizeof(user_msg) / sizeof(wchar_t),
L"A critical error has occurred.\n"
L"Error code: 0x%08lX\n"
L"Address: %p\n\n"
L"Click OK to exit QuickChat",
code, address);
MessageBoxW(NULL, user_msg, L"QuickChat", MB_OK | MB_ICONERROR);
FILE* crash_log = fopen("crash.txt", "w");
if (crash_log) {
time_t current = time(NULL);
struct tm* time_info = localtime(¤t);
char timestamp[64];
strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", time_info);
fprintf(crash_log, "--- Crash Report ---\n");
fprintf(crash_log, "Time: %s\n", timestamp);
fprintf(crash_log, "Error code: 0x%08lX\n", code);
fprintf(crash_log, "Address: %p\n", address);
fclose(crash_log);
}
return EXCEPTION_EXECUTE_HANDLER;
}
// ======= 6. Helper Functions =======
// ----- UI Helpers -----
void EnableVisualStyles() {
INITCOMMONCONTROLSEX icex;
icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
icex.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&icex);
}
void PlayNotifySound(int sound) {
if (!sound_enabled) return;
const wchar_t* filename = NULL;
switch (sound) {
case SOUND_JOIN:
filename = L"join.wav";
break;
case SOUND_LEAVE:
filename = L"leave.wav";
break;
case SOUND_MSG:
filename = L"newmsg.wav";
break;
default:
return;
}
PlaySoundW(filename, NULL, SND_FILENAME | SND_ASYNC);
}
void AddMessage(const wchar_t* msg) {
// Ensure display is ready.
if (!hMsgDisplay || !msg || !*msg) return;
if (wcslen(msg) > BUFFER_SIZE) {
wchar_t longmsg_err[511] = L"[ERROR]: Message is too long to be displayed.";
AddMessage(longmsg_err);
if (is_server) LogMessage(longmsg_err);
return;
}
int len = GetWindowTextLengthW(hMsgDisplay);
SendMessageW(hMsgDisplay, EM_SETSEL, len, len);
if (len > 0) SendMessageW(hMsgDisplay, EM_REPLACESEL, FALSE, (LPARAM)L"\r\n");
if (!SendMessageW(hMsgDisplay, EM_REPLACESEL, FALSE, (LPARAM)msg)) {
if (is_server) {
wchar_t addmsg_err[512];
swprintf(addmsg_err, sizeof(addmsg_err) / sizeof(wchar_t), L"[ERROR]: Failed to display message. Error: %lu.", GetLastError());
if (is_server) LogMessage(addmsg_err);
}
SetFocus(hEdit);
return;
}
SendMessageW(hMsgDisplay, WM_VSCROLL, SB_BOTTOM, 0);
}
void DisableChatControls(BOOL disable) {
if (hEdit && IsWindow(hEdit)) EnableWindow(hEdit, !disable);
if (hSendBtn && IsWindow(hSendBtn)) EnableWindow(hSendBtn, !disable);
}
void FlashMessageWindow(HWND hWnd) {
if (!flash_enabled) return;
FLASHWINFO fi;
fi.cbSize = sizeof(FLASHWINFO);
fi.hwnd = hWnd;
fi.dwFlags = FLASHW_ALL | FLASHW_TIMERNOFG;
fi.uCount = 3;
fi.dwTimeout = 0;
FlashWindowEx(&fi);
}
void ShowError(const wchar_t* msg, DWORD err) {
wchar_t buffer[512];
swprintf(buffer, sizeof(buffer) / sizeof(wchar_t), L"%ls. Error: %lu", msg, err);
MessageBoxW(NULL, buffer, L"QuickChat", MB_OK | MB_ICONERROR);
}
// ----- Network Helpers -----
bool GetDefaultIP(wchar_t *ip_buffer, size_t size) {
// UDP hack: connect to 8.8.8.8:53 (DNS), then getsockname returns local IP.
// Works only when there is a route to the internet. Returns 0.0.0.0 if no route.
WSADATA wsa;
if (WSAStartup(MAKEWORD(2,2), &wsa) != 0) return false;
SOCKET s = socket(AF_INET, SOCK_DGRAM, 0);
if (s == INVALID_SOCKET) {
MessageBoxW(NULL, L"Failed to initialize socket for UDP.", L"QuickChat", MB_OK | MB_ICONWARNING);
WSACleanup();
return false;
}
struct sockaddr_in remote = {0};
remote.sin_family = AF_INET;
remote.sin_port = htons(53);
remote.sin_addr.s_addr = inet_addr("8.8.8.8");
if (connect(s, (struct sockaddr*)&remote, sizeof(remote)) != 0) {
MessageBoxW(NULL, L"Failed to connect to 8.8.8.8.", L"QuickChat", MB_OK | MB_ICONWARNING);
closesocket(s);
WSACleanup();
return false;
}
struct sockaddr_in local;
int len = sizeof(local);
if (getsockname(s, (struct sockaddr*)&local, &len) != 0) {
MessageBoxW(NULL, L"Failed to get host IP address.", L"QuickChat", MB_OK | MB_ICONWARNING);
closesocket(s);
WSACleanup();
return false;
}
char ip_utf8[16];
strncpy(ip_utf8, inet_ntoa(local.sin_addr), 15);
ip_utf8[15] = '\0';
MultiByteToWideChar(CP_UTF8, 0, ip_utf8, -1, ip_buffer, size);
closesocket(s);
WSACleanup();
return true;
}
bool IsValidTargetIP(const wchar_t* ip_str) {
int o1, o2, o3, o4;
if (swscanf(ip_str, L"%d.%d.%d.%d", &o1, &o2, &o3, &o4) != 4) return false;
// Block:
// 0.x.x.x
// x.x.x.0 (network address)
// x.x.x.255 (network broadcast)
// 224.0.0.0 - 239.255.255.255 (multicast)
// 240.0.0.0 - 255.255.255.254 (reserved)
// 255.255.255.255 (global broadcast)
if (o1 == 0) return false;
if (o4 == 0) return false;
if (o4 == 255) return false;
if (o1 >= 224 && o1 <= 239) return false;
if (o1 >= 240) return false;
// Allow any other IP
return true;
}
void CloseConnection(void) {
// Only host can disconnect client.
if (!is_server) return;
if (client_socket == INVALID_SOCKET) {
AddMessage(L"[INFO]: No active connection to close.");
return;
}
is_running = 0;
shutdown(client_socket, SD_BOTH);
struct linger linger_opt = { 1, 0 };
setsockopt(client_socket, SOL_SOCKET, SO_LINGER, (char*)&linger_opt, sizeof(linger_opt));
closesocket(client_socket);
client_socket = INVALID_SOCKET;
DisableChatControls(TRUE);
wchar_t closeconn[512] = L"[DISCONNECT]: Host closed the connection.";
AddMessage(closeconn);
LogMessage(closeconn);
}
void Disconnect(void) {
wchar_t leave_msg[512];
swprintf(leave_msg, sizeof(leave_msg) / sizeof(wchar_t), L"[DISCONNECT]: %ls left the chat.", computer_name);
AddMessage(leave_msg);
if (client_socket != INVALID_SOCKET && is_running) {
char utf8_msg[256];
WideCharToMultiByte(CP_UTF8, 0, leave_msg, -1, utf8_msg, sizeof(utf8_msg), NULL, NULL);
int msg_len = strlen(utf8_msg);
unsigned char encbuf[256];
memcpy(encbuf, utf8_msg, msg_len);
XorObf(encbuf, msg_len);
send(client_socket, (char*)encbuf, msg_len, 0);
}
if (is_server) LogMessage(leave_msg);
CleanupAndExit();
}
void CleanupAndExit(void) {
SaveSettings();
is_running = 0;
if (client_socket != INVALID_SOCKET) {
shutdown(client_socket, SD_BOTH);
closesocket(client_socket);
client_socket = INVALID_SOCKET;
}
// Avoid WaitForSingleObject on recv thread.
if (hReceiveThread != NULL) {
CloseHandle(hReceiveThread);
hReceiveThread = NULL;
}
if (chat_log != NULL) {
time_t now = time(NULL);
struct tm *t = localtime(&now);
wchar_t timestamp[64];
wcsftime(timestamp, sizeof(timestamp) / sizeof(wchar_t), L"%H:%M:%S %d/%m/%Y", t);
fwprintf(chat_log, L"=== Session ended at %ls ===\n\n", timestamp);
fclose(chat_log);
chat_log = NULL;
}
WSACleanup();
PostQuitMessage(0);
}
// ----- Logging -----
void LogMessage(const wchar_t* message) {
if (!logging_enabled) return;
if (chat_log == NULL) {
AddMessage(L"[ERROR]: Log file is not opened. Writing data is not available.");
return;
}
SYSTEMTIME st;
GetLocalTime(&st);
wchar_t timestamp[64];
swprintf(timestamp, sizeof(timestamp) / sizeof(wchar_t),
L"%04d-%02d-%02d %02d:%02d:%02d.%03d",
st.wYear, st.wMonth, st.wDay,
st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
char timestamp_utf8[64];
char msg_utf8[1024];
WideCharToMultiByte(CP_UTF8, 0, timestamp, -1, timestamp_utf8, sizeof(timestamp_utf8), NULL, NULL);
WideCharToMultiByte(CP_UTF8, 0, message, -1, msg_utf8, sizeof(msg_utf8), NULL, NULL);
int written = fprintf(chat_log, "[%s] %s\n", timestamp_utf8, msg_utf8);
if (written < 0 || ferror(chat_log)) {
error_counter++;
int err_code = errno;
if (err_code == 0) err_code = EIO;
wchar_t err_msg[512];
swprintf(err_msg, sizeof(err_msg) / sizeof(wchar_t), L"[ERROR]: Failed to write to log. Error: %d. Error count: %d.", err_code, error_counter);
AddMessage(err_msg);
if (error_counter >= 3) {
AddMessage(L"[ERROR]: Logging was disabled for this session.");
logging_enabled = false;
fclose(chat_log);
chat_log = NULL;
}
return;
}
fflush(chat_log);
}
// ----- File Operations -----
void SaveChatToFile(HWND hWnd) {
wchar_t filename[MAX_PATH];
time_t now = time(NULL);
struct tm *tm_info = localtime(&now);
wcsftime(filename, MAX_PATH, L"Chat-%Y%m%d-%H%M%S.txt", tm_info);
int len = GetWindowTextLengthW(hMsgDisplay);
wchar_t *chatText = (wchar_t*)malloc((len + 1) * sizeof(wchar_t));
GetWindowTextW(hMsgDisplay, chatText, len + 1);
FILE *f = _wfopen(filename, L"wb");
if (f) {
// Use only for UTF-8 with BOM.
// fwrite("\xEF\xBB\xBF", 1, 3, f);
char *utf8 = (char*)malloc(len * 3 + 1);
WideCharToMultiByte(CP_UTF8, 0, chatText, -1, utf8, len * 3 + 1, NULL, NULL);
fwrite(utf8, 1, strlen(utf8), f);
free(utf8);
fclose(f);
wchar_t save_msg[512];
swprintf(save_msg, sizeof(save_msg) / sizeof(wchar_t), L"Chat saved to %ls", filename);
MessageBoxW(hWnd, save_msg, L"QuickChat", MB_OK | MB_ICONINFORMATION);
} else {
wchar_t save_err[512];
swprintf(save_err, sizeof(save_err) / sizeof(wchar_t), L"Failed to save chat history. Error: %d.", GetLastError());
MessageBoxW(hWnd, save_err, L"QuickChat", MB_OK | MB_ICONERROR);
}
free(chatText);
}
// ----- Settings -----
void ResetSettings(HWND hWnd) {
int result = MessageBoxW(hWnd,
L"Are you sure you want to reset all settings?",
L"QuickChat",
MB_YESNO | MB_ICONWARNING);
if (result == IDYES) {
// Remove settings file
_wremove(INI_FILE);
// Reset variables
always_on_top = false;
flash_enabled = true;
sound_enabled = true;
// Reset menu
CheckMenuItem(GetMenu(hWnd), IDM_ALWAYS_ON_TOP, MF_BYCOMMAND | MF_UNCHECKED);
CheckMenuItem(GetMenu(hWnd), ID_FLASH_TOGGLE, MF_BYCOMMAND | MF_CHECKED);
CheckMenuItem(GetMenu(hWnd), ID_SOUND_TOGGLE, MF_BYCOMMAND | MF_CHECKED);
// Remove Always on Top flag
SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
MessageBoxW(hWnd, L"Settings have been reset to default values.", L"QuickChat", MB_OK | MB_ICONINFORMATION);
}
}
// ----- System Helpers -----
void GetLocalComputerName() {
DWORD size = sizeof(computer_name) / sizeof(wchar_t);
GetComputerNameW(computer_name, &size);
}
// ======= 7. Network Core =======
bool InitializeNetwork(bool server_mode, HINSTANCE hInstance, int nCmdShow) {
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
ShowError(L"WSAStartup failed.", WSAGetLastError());
return false;
}
if (server_mode) {
SOCKET server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == INVALID_SOCKET) {
ShowError(L"Failed to create socket.", WSAGetLastError());
WSACleanup();
return false;
}
int active_port = xor_enabled ? PORT_QCS : PORT_QC;
struct sockaddr_in server_addr = {0};
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(active_port);
if (bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
DWORD err = WSAGetLastError();
if (err == WSAEADDRINUSE) {
MessageBoxW(NULL,
L"Port is already in use. Another QuickChat host may be running.",
L"QuickChat", MB_OK | MB_ICONWARNING);
} else {
ShowError(L"Bind failed.", err);
}
closesocket(server_fd);
WSACleanup();
return false;
}
GetDefaultIP(server_ip, sizeof(server_ip) / sizeof(wchar_t));
wchar_t bind_msg[512];
const wchar_t* mode_str = xor_enabled ? L"QCS (Obfuscated)" : L"QC (Plaintext)";
swprintf(bind_msg, sizeof(bind_msg) / sizeof(wchar_t), L"Host started: %ls on address %ls port %d.", mode_str, server_ip, active_port);
LogMessage(bind_msg);
if (listen(server_fd, 1) == SOCKET_ERROR) {
ShowError(L"Listen failed.", WSAGetLastError());
closesocket(server_fd);
WSACleanup();
return false;
}
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ShowServerIPMessage, NULL, 0, NULL);
while (1) {
struct sockaddr_in client_addr;
int addr_len = sizeof(client_addr);
SOCKET temp_client = accept(server_fd, (struct sockaddr*)&client_addr, &addr_len);
if (temp_client == INVALID_SOCKET) {
ShowError(L"Accept failed.", WSAGetLastError());
continue;
}
struct timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
setsockopt(temp_client, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv));
char hs[256];
int recv_len = recv(temp_client, hs, sizeof(hs) - 1, 0);
if (recv_len <= 0) {
LogMessage(L"[SECURITY]: Empty or timed-out handshake. Connection closed.");
closesocket(temp_client);
continue;
}
// Waiting for handshake
XorObf((unsigned char*)hs, recv_len);
hs[recv_len] = '\0';
if (strncmp(hs, QC_LABEL, strlen(QC_LABEL)) != 0) {
LogMessage(L"[SECURITY]: Invalid handshake. Connection closed.");
if (!xor_enabled) {
send(temp_client, "QCERR: Invalid handshake", 24, 0);
}
closesocket(temp_client);
continue;
}
const char* name_ptr = hs + strlen(QC_LABEL);
if (*name_ptr == '\0') {
LogMessage(L"[SECURITY]: Empty name in handshake. Connection closed.");
closesocket(temp_client);
continue;
}
client_socket = temp_client;
char ip_utf8[16];
strncpy(ip_utf8, inet_ntoa(client_addr.sin_addr), 15);
ip_utf8[15] = '\0';
MultiByteToWideChar(CP_UTF8, 0, ip_utf8, -1, peer_ip, sizeof(peer_ip) / sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0, name_ptr, -1, peer_name, sizeof(peer_name) / sizeof(wchar_t));
break;
}
closesocket(server_fd);
// Send handshake reply.
char hs_reply[256];
int pos = snprintf(hs_reply, sizeof(hs_reply), "%s", QC_LABEL);
WideCharToMultiByte(CP_UTF8, 0, computer_name, -1, hs_reply + pos, sizeof(hs_reply) - pos, NULL, NULL);
int hs_r_len = strlen(hs_reply);
XorObf((unsigned char*)hs_reply, hs_r_len);
send(client_socket, hs_reply, hs_r_len, 0);
ShowMainWindow(hInstance, nCmdShow);
while (!mainWindowReady) {
Sleep(10);
MSG msg;
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
wchar_t join_msg[512];
swprintf(join_msg, sizeof(join_msg) / sizeof(wchar_t), L"[CONNECT]: %ls connected from %ls.", peer_name, peer_ip);
AddMessage(join_msg);
LogMessage(join_msg);
} else {
client_socket = socket(AF_INET, SOCK_STREAM, 0);
if (client_socket == INVALID_SOCKET) {
ShowError(L"Failed to create socket.", WSAGetLastError());
WSACleanup();
return false;
}
struct timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
setsockopt(client_socket, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout, sizeof(timeout));
int active_port = xor_enabled ? PORT_QCS : PORT_QC;
struct sockaddr_in server_addr = {0};
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(active_port);
char server_ip_utf8[16];
WideCharToMultiByte(CP_UTF8, 0, server_ip, -1, server_ip_utf8, sizeof(server_ip_utf8), NULL, NULL);
server_addr.sin_addr.s_addr = inet_addr(server_ip_utf8);
if (connect(client_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
int err = WSAGetLastError();
switch (err) {
case WSAETIMEDOUT:
MessageBoxW(NULL, L"Connection timed out.", L"QuickChat", MB_OK | MB_ICONERROR);
break;
case WSAECONNREFUSED:
MessageBoxW(NULL, L"Connection refused.", L"QuickChat", MB_OK | MB_ICONERROR);
break;
default:
ShowError(L"Connection failed.", err);
}
closesocket(client_socket);
WSACleanup();
return false;
}
timeout.tv_sec = 0;
setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
// Disabling "Weak Host Model" on pre-Vista versions (known problem on XP and 2000).
// On Vista and newer - switching from "soft bind" to "hard bind".
struct sockaddr_in server_info;
int len = sizeof(server_info);
getsockname(client_socket, (struct sockaddr*)&server_info, &len);
wchar_t ip_w[16];
DWORD ip_len = 16;
WSAAddressToStringW((LPSOCKADDR)&server_info, sizeof(server_info), NULL, ip_w, &ip_len);
wcscpy(peer_ip, ip_w);
char hs[256];
int pos = snprintf(hs, sizeof(hs), "%s", QC_LABEL);
WideCharToMultiByte(CP_UTF8, 0, computer_name, -1, hs + pos, sizeof(hs) - pos, NULL, NULL);
int hs_len = strlen(hs);
XorObf((unsigned char*)hs, hs_len);
send(client_socket, hs, hs_len, 0);
char hs_reply[256];
int recv_len = recv(client_socket, hs_reply, sizeof(hs_reply) - 1, 0);
if (recv_len <= 0) {
ShowError(L"Failed to receive peer handshake.", WSAGetLastError());
closesocket(client_socket);
WSACleanup();
return false;
}
XorObf((unsigned char*)hs_reply, recv_len);
hs_reply[recv_len] = '\0';
if (strncmp(hs_reply, QC_LABEL, strlen(QC_LABEL)) != 0) {
MessageBoxW(NULL, L"Remote host sent an invalid handshake,", L"QuickChat", MB_OK | MB_ICONERROR);
closesocket(client_socket);
WSACleanup();
return false;
}
const char* name_ptr = hs_reply + strlen(QC_LABEL);
MultiByteToWideChar(CP_UTF8, 0, name_ptr, -1, peer_name, 256);
if (peer_name[0] == L'\0') wcscpy(peer_name, L"<Unknown>");
ShowMainWindow(hInstance, nCmdShow);
while (!mainWindowReady) {
Sleep(10);
MSG msg;
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
wchar_t join_msg[512];
swprintf(join_msg, sizeof(join_msg) / sizeof(wchar_t), L"[CONNECT]: Connected to %ls at %ls.", peer_name, server_ip);
AddMessage(join_msg);
}
unsigned int threadID;
HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, ReceiveMessages, NULL, 0, &threadID);
if (hThread == NULL) {
ShowError(L"Failed to start receive thread.", GetLastError());
CleanupAndExit();
return false;
}
return true;
}
void XorObf(unsigned char *data, int len) {
if (!xor_enabled) return;
unsigned char k[KEY_LEN];
memcpy(k, key, KEY_LEN);
for (int i = 0; i < len; i++) data[i] ^= k[i % KEY_LEN];
memset(k, 0, KEY_LEN);
}
unsigned int __stdcall ReceiveMessages(void* arg) {
(void)arg;
char buffer[BUFFER_SIZE];
while (is_running) {
int bytes = recv(client_socket, buffer, BUFFER_SIZE - 1, 0);
if (!is_running)
break;
if (bytes == SOCKET_ERROR) {
int err_code = WSAGetLastError();
if (err_code == WSAETIMEDOUT) continue;
wchar_t connlost_err[512];
swprintf(connlost_err, sizeof(connlost_err) / sizeof(wchar_t), L"[ERROR]: Connection with remote computer lost. (Error: %d)", err_code);
AddMessage(connlost_err);
if (is_server) LogMessage(connlost_err);
DisableChatControls(TRUE);
DragAcceptFiles(hWndGlobal, FALSE);
is_running = 0;
break;
}
if (bytes == 0) {
wchar_t close_msg[512] = L"[DISCONNECT]: Remote computer has closed the connection.";
AddMessage(close_msg);
if (is_server) LogMessage(close_msg);
DisableChatControls(TRUE);
is_running = 0;
break;
}
XorObf((unsigned char*)buffer, bytes);
buffer[bytes] = '\0';
if (strcmp(buffer, "QCPING") == 0) {
char pong_msg[] = "QCPONG";
int len = strlen(pong_msg);
XorObf((unsigned char*)pong_msg, len);
send(client_socket, pong_msg, len, 0);
continue;
}
if (strcmp(buffer, "QCPONG") == 0) {
wchar_t ping_msg[512] = L"[INFO]: Client responded to PING packet.";
LogMessage(ping_msg);
AddMessage(ping_msg);
continue;
}
FlashMessageWindow(hWndGlobal);
if (strncmp(buffer, "[DISCONNECT]", 12) == 0) {
DisableChatControls(TRUE);
PlayNotifySound(SOUND_LEAVE);
DragAcceptFiles(hWndGlobal, FALSE);
} else {
PlayNotifySound(SOUND_MSG);
}
wchar_t wide_buffer[BUFFER_SIZE];
MultiByteToWideChar(CP_UTF8, 0, buffer, -1, wide_buffer, BUFFER_SIZE);
AddMessage(wide_buffer);
if (is_server) LogMessage(wide_buffer);
}
_endthread();
return 0;
}
void SendCurrentMessage(HWND hWnd) {
int msglen = GetWindowTextLengthW(hEdit);
int maxallowed = (BUFFER_SIZE - 1) - wcslen(computer_name) - 8;
if (msglen > maxallowed) {
wchar_t toolong_err[512] = L"[ERROR]: Message is too long to send.";
AddMessage(toolong_err);
if (is_server) LogMessage(toolong_err);
return;
}
wchar_t buffer[BUFFER_SIZE];
int text_len = GetWindowTextW(hEdit, buffer, BUFFER_SIZE - 1);
buffer[text_len] = L'\0';
wchar_t* start = buffer;
while (*start == L' ' || *start == L'\t' || *start == L'\r' || *start == L'\n') {
start++;
}
int len = wcslen(start);
if (len > 0) {
wchar_t* end = start + len - 1;
while (end >= start && (*end == L' ' || *end == L'\t' || *end == L'\r' || *end == L'\n')) {
*end = L'\0';
end--;
len--;
}