-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsource.cpp
326 lines (271 loc) · 9.57 KB
/
source.cpp
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
#include <winsock2.h>
#include <ws2tcpip.h>
#include <Windows.h>
#include <WinDNS.h>
#include <iphlpapi.h>
#include <icmpapi.h>
#include <fstream>
#include <iostream>
#include <string>
#include <ShlObj.h>
#pragma comment(lib, "Dnsapi.lib")
#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "iphlpapi.lib")
using namespace std;
BOOL debugging_enabled = FALSE;
BOOL dnsCheck();
BOOL pingCheck();
void logWrite(string);
string getDocumentsFolder();
void createLogDirectory(LPCWSTR);
string getDateTime(string);
wstring convertStringToWString(string&);
string convertPCWSTRToString(PCWSTR);
string convertWcharBufferToString(wchar_t*);
PCWSTR domains[5] = { L"google.com", L"microsoft.com", L"yahoo.com", L"amazon.com", L"cisco.com" };
BOOL domainResult[5];
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
string currentStatus = "UP";
string previousStatus = "UP";
// DEBUG output
if (debugging_enabled == TRUE) { logWrite("DEBUG: WinMain function running"); }
// Internet status check loop
while (true) {
if (dnsCheck() == FALSE && pingCheck() == FALSE) {
// Internet is down
if (debugging_enabled == TRUE) { logWrite("DEBUG: Internet currently down. Ping and DNS was unsuccessful."); }
currentStatus = "DOWN";
}
else
{
// Internet is up
if (debugging_enabled == TRUE) { logWrite("DEBUG: Internet currently up. Ping and/or DNS was successful."); }
currentStatus = "UP";
}
if (currentStatus != previousStatus) {
logWrite("Internet status change: " + currentStatus);
}
previousStatus = currentStatus;
Sleep(5000); // Sleep for 5 second before running pingCheck and dnsCheck again.
}
return 0;
}
BOOL dnsCheck() {
PDNS_RECORD pDnsRecord = NULL; // Pointer to DNS_RECORD structure.
DNS_STATUS queryStatus; // Return value of DnsQuery.
// DEBUG output
if (debugging_enabled == TRUE) { logWrite("DEBUG: dnsCheck function running"); }
for (int x = 0; x < 5; x++) {
// Perform the DNS query for the A (IPv4) record on domains
queryStatus = DnsQuery(domains[x], DNS_TYPE_A, DNS_QUERY_STANDARD, NULL, &pDnsRecord, NULL);
if (queryStatus == 0) {
if (debugging_enabled == TRUE) {
string currentDomain = convertPCWSTRToString(domains[x]);
logWrite("DEBUG: DNS resolution succeeded for: " + currentDomain);
}
// Traverse the linked list of DNS records returned
while (pDnsRecord) {
if (pDnsRecord->wType == DNS_TYPE_A) {
wchar_t ipStr[INET_ADDRSTRLEN]; // Buffer to hold the IP address string
IP4_ADDRESS ipaddr = pDnsRecord->Data.A.IpAddress;
if (debugging_enabled == TRUE) {
InetNtop(AF_INET, &ipaddr, ipStr, INET_ADDRSTRLEN);
string currentIP = convertWcharBufferToString(ipStr);
logWrite("DEBUG: IP Address: " + currentIP);
}
}
pDnsRecord = pDnsRecord->pNext;
}
// Free memory allocated for DNS records
DnsRecordListFree(pDnsRecord, DnsFreeRecordList);
domainResult[x] = TRUE;
}
else {
if (debugging_enabled == TRUE) {
logWrite("DEBUG: DNS resolution failed with status: " + queryStatus); }
domainResult[x] = FALSE;
}
}
// DNS comparison to determine if any DNS resolutions completed successfully
if (domainResult[0] == TRUE || domainResult[1] == TRUE || domainResult[2] == TRUE || domainResult[3] == TRUE || domainResult[4] == TRUE) {
return TRUE;
}
else {
return FALSE;
}
}
BOOL pingCheck() {
string currentDomain;
string currentReplyIP;
// DEBUG output
if (debugging_enabled == TRUE) { logWrite("DEBUG: dnsCheck function running"); }
// Initialize WinSock
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
if (debugging_enabled == TRUE) { logWrite("DEBUG: pingCheck: WSAStartup failed."); }
return FALSE;
}
// Open the ping handle
HANDLE hIcmp = IcmpCreateFile();
if (hIcmp == INVALID_HANDLE_VALUE) {
if (debugging_enabled == TRUE) { logWrite("DEBUG: pingCheck: Failed to create ICMP handle."); }
WSACleanup();
return FALSE;
}
// Setup the echo request
wchar_t sendData[] = L"Data Buffer";
DWORD replySize = sizeof(ICMP_ECHO_REPLY) + sizeof(sendData) + 8;
auto* replyBuffer = new char[replySize];
memset(replyBuffer, 0, replySize);
// Resolve the domain name to an IP address
struct addrinfoW hints = {};
hints.ai_family = AF_INET; // IPv4 addresses only
struct addrinfoW* result = nullptr;
for (int x = 0; x < 5; x++) {
// Domains IP resolution
if (GetAddrInfoW(domains[x], NULL, &hints, &result) != 0) {
if (debugging_enabled == TRUE) {
currentDomain = convertPCWSTRToString(domains[x]);
logWrite("DEBUG: DNS resolution failed for: " + currentDomain);
}
IcmpCloseHandle(hIcmp);
WSACleanup();
return FALSE;
}
// Convert the first resolved IP to a string
wchar_t ipStr[INET_ADDRSTRLEN];
struct sockaddr_in* sockaddr_ipv4 = (struct sockaddr_in*)result->ai_addr;
InetNtop(AF_INET, &sockaddr_ipv4->sin_addr, ipStr, sizeof(ipStr));
// Convert string IP to binary form using InetPton
IN_ADDR ipaddr;
InetPton(AF_INET, ipStr, &ipaddr);
// Send the ping to the resolved IP address
DWORD dwRetVal = IcmpSendEcho(hIcmp, ipaddr.S_un.S_addr, sendData, sizeof(sendData), NULL, replyBuffer, replySize, 1000);
if (dwRetVal != 0) {
ICMP_ECHO_REPLY* echoReply = (ICMP_ECHO_REPLY*)replyBuffer;
// Output and handling of ICMP echo reply
if (echoReply->Status == IP_SUCCESS) {
wchar_t replyIp[INET_ADDRSTRLEN];
InetNtop(AF_INET, &echoReply->Address, replyIp, INET_ADDRSTRLEN);
if (debugging_enabled == TRUE) {
logWrite("DEBUG: ICMP Echo Sent to: " + currentDomain);
currentReplyIP = convertWcharBufferToString(replyIp);
logWrite("DEBUG: Reply from: " + currentReplyIP + " - RTT: " + to_string(echoReply->RoundTripTime) + "ms");
}
domainResult[x] = TRUE;
}
else
{
if (debugging_enabled == TRUE) {
logWrite("DEBUG: Ping to: " + currentDomain + " failed with status : " + to_string(echoReply->Status));
}
domainResult[x] = FALSE;
}
}
else
{
if (debugging_enabled == TRUE) {
logWrite("DEBUG: Call to IcmpSendEcho failed. Error: " + GetLastError());
}
domainResult[x] = FALSE;
}
}
// Clean up
FreeAddrInfoW(result);
delete[] replyBuffer;
IcmpCloseHandle(hIcmp);
WSACleanup();
// Ping comparison to determine if any pings completed successfully
if (domainResult[0] == TRUE || domainResult[1] == TRUE || domainResult[2] == TRUE || domainResult[3] == TRUE || domainResult[4] == TRUE) {
return TRUE;
}
else {
return FALSE;
}
}
void logWrite(string message) {
string logFileName;
string currentDate = getDateTime("%m-%d-%Y");
string dateTime = getDateTime("%m-%d-%Y %H:%M:%S");
if (debugging_enabled == TRUE) {
logFileName = "InternetCheck-Report-" + currentDate + "-DEBUG.log";
}
else
{
logFileName = "InternetCheck-Report-" + currentDate + ".log";
}
string logDirPath = getDocumentsFolder() + "\\InternetCheck";
wstring logDirPathW = convertStringToWString(logDirPath);
LPCWSTR logDirPathPtr = logDirPathW.c_str();
createLogDirectory(logDirPathPtr);
string logFullPath = logDirPath + "\\" + logFileName;
ofstream logFile(logFullPath, ios::app); // Create log file and output dateTime and message to the log file
if (!logFile.is_open()) {
// Error handling for not being able to create log file
}
else
{
logFile << dateTime << " - " << message << endl;
logFile.close();
}
}
string getDocumentsFolder() {
PWSTR path = nullptr;
HRESULT result = SHGetKnownFolderPath(FOLDERID_Documents, 0, NULL, &path);
if (SUCCEEDED(result) && path != nullptr) {
wstring ws(path);
CoTaskMemFree(static_cast<LPVOID>(path)); // Free the allocated path
std::string documentsPath(ws.begin(), ws.end());
return documentsPath;
}
else {
// Handle error
cerr << "Failed to get Documents folder path." << endl;
return "";
}
}
void createLogDirectory(LPCWSTR directoryPath) {
if (CreateDirectory(directoryPath, NULL) || GetLastError() == ERROR_ALREADY_EXISTS) {
// Directory created successfully or already exists
}
else
{
cerr << "Failed to create directory at " << directoryPath << endl;
}
}
string getDateTime(string format) {
time_t currentTime = time(nullptr);
tm localTime;
localtime_s(&localTime, ¤tTime);
char dateTime[100];
strftime(dateTime, sizeof(dateTime), format.c_str(), &localTime);
return string(dateTime);
}
wstring convertStringToWString (string& str) {
// Get the required size of the buffer that receives the Unicode string
int size_needed = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.length(), NULL, 0);
// Create a buffer to hold the Unicode string
wstring wstrTo(size_needed, 0);
// Convert the UTF-8 string to Unicode (wstring)
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.length(), &wstrTo[0], size_needed);
return wstrTo;
}
string convertPCWSTRToString(PCWSTR pcwstr) {
if (pcwstr == nullptr) return string();
// Get the length of the required buffer
int len = WideCharToMultiByte(CP_UTF8, 0, pcwstr, -1, nullptr, 0, nullptr, nullptr);
if (len <= 0) return string();
// Allocate buffer and convert
string result(len - 1, '\0'); // Length includes the null terminator
WideCharToMultiByte(CP_UTF8, 0, pcwstr, -1, &result[0], len, nullptr, nullptr);
return result;
}
string convertWcharBufferToString(wchar_t* wcharBuffer) {
if(wcharBuffer == nullptr) return string(); // Handle null pointer
// Determine the length of the buffer we need
int len = WideCharToMultiByte(CP_UTF8, 0, wcharBuffer, -1, nullptr, 0, nullptr, nullptr);
if (len <= 0) return string(); // Handle error
string str(len - 1, '\0'); // Allocate string of sufficient length
WideCharToMultiByte(CP_UTF8, 0, wcharBuffer, -1, &str[0], len, nullptr, nullptr);
return str;
}