1 /******************************************************************************
3 * Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org) *
5 * This program is free software; you can redistribute it and/or *
6 * modify it under the terms of the GNU General Public License *
7 * as published by the Free Software Foundation; either version 2 *
8 * of the License, or (at your option) any later version. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the Free Software Foundation *
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
18 ******************************************************************************/
20 #ifndef WIN32_LEAN_AND_MEAN
21 #define WIN32_LEAN_AND_MEAN //else winsock will be included with windows.h and conflict with winsock2
34 #include "check_ping.h"
38 namespace po = boost::program_options;
40 static BOOL debug = FALSE;
42 INT wmain(INT argc, WCHAR **argv)
45 printInfoStruct printInfo;
49 WORD req = MAKEWORD(1, 1);
51 WSAStartup(req, &dat);
53 if (parseArguments(argc, argv, vm, printInfo) != -1)
56 if (check_ping4(printInfo, response) != -1)
59 if (check_ping6(printInfo, response) != -1)
64 return printOutput(printInfo, response);
67 INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo)
69 WCHAR namePath[MAX_PATH];
70 GetModuleFileName(NULL, namePath, MAX_PATH);
71 WCHAR *progName = PathFindFileName(namePath);
73 po::options_description desc;
76 ("help,h", "Print usage message and exit")
77 ("version,V", "Print version and exit")
78 ("debug,d", "Verbose/Debug output")
79 ("host,H", po::wvalue<std::wstring>()->required(), "Host ip to ping")
80 (",4", "--Host is an ipv4 address (default)")
81 (",6", "--Host is an ipv6 address")
82 ("timeout,t", po::value<INT>(), "Specify timeout for requests in ms (default=1000)")
83 ("packets,p", po::value<INT>(), "Declare ping count (default=5)")
84 ("warning,w", po::wvalue<std::wstring>(), "Warning values: rtt,package loss")
85 ("critical,c", po::wvalue<std::wstring>(), "Critical values: rtt,package loss")
88 po::basic_command_line_parser<WCHAR> parser(ac, av);
95 po::command_line_style::unix_style |
96 po::command_line_style::allow_long_disguise &
97 ~po::command_line_style::allow_guessing
102 } catch (std::exception& e) {
103 std::cout << e.what() << '\n' << desc << '\n';
107 if (vm.count("help")) {
108 std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n';
110 L"%s is a simple program to ping an ip4 address.\n"
111 L"You can use the following options to define its behaviour:\n\n", progName);
114 L"\nIt will take at least timeout times number of pings to run\n"
115 L"Then it will output a string looking something like this:\n\n"
116 L"\tPING WARNING RTA: 72ms Packet loss: 20% | ping=72ms;40;80;71;77 pl=20%;20;50;0;100\n\n"
117 L"\"PING\" being the type of the check, \"WARNING\" the returned status\n"
118 L"and \"RTA: 72ms Packet loss: 20%\" the relevant information.\n"
119 L"The performance data is found behind the \"|\", in order:\n"
120 L"returned value, warning threshold, critical threshold, minimal value and,\n"
121 L"if applicable, the maximal value. \n\n"
122 L"%s' exit codes denote the following:\n"
123 L" 0\tOK,\n\tNo Thresholds were broken or the programs check part was not executed\n"
124 L" 1\tWARNING,\n\tThe warning, but not the critical threshold was broken\n"
125 L" 2\tCRITICAL,\n\tThe critical threshold was broken\n"
126 L" 3\tUNKNOWN, \n\tThe program experienced an internal or input error\n\n"
127 L"Threshold syntax:\n\n"
129 L"warn if threshold is broken, which means VALUE > THRESHOLD\n"
130 L"(unless stated differently)\n\n"
132 L"inverts threshold check, VALUE < THRESHOLD (analogous to above)\n\n"
134 L"warn is VALUE is inside the range spanned by THR1 and THR2\n\n"
136 L"warn if VALUE is outside the range spanned by THR1 and THR2\n\n"
138 L"if the plugin accepts percentage based thresholds those will be used.\n"
139 L"Does nothing if the plugin does not accept percentages, or only uses\n"
140 L"percentage thresholds. Ranges can be used with \"%%\", but both range values need\n"
141 L"to end with a percentage sign.\n\n"
142 L"All of these options work with the critical threshold \"-c\" too."
148 if (vm.count("version")) {
149 std::cout << progName << " Version: " << VERSION << '\n';
153 if (vm.count("-4") && vm.count("-6")) {
154 std::cout << "Conflicting options \"4\" and \"6\"" << '\n';
158 if (vm.count("warning")) {
159 std::vector<std::wstring> sVec = splitMultiOptions(vm["warning"].as<std::wstring>());
160 if (sVec.size() != 2) {
161 std::cout << "Wrong format for warning thresholds" << '\n';
165 printInfo.warn = threshold(*sVec.begin());
166 printInfo.wpl = threshold(sVec.back());
167 if (!printInfo.wpl.perc) {
168 std::cout << "Packet loss must be percentage" << '\n';
171 } catch (std::invalid_argument& e) {
172 std::cout << e.what() << '\n';
176 if (vm.count("critical")) {
177 std::vector<std::wstring> sVec = splitMultiOptions(vm["critical"].as<std::wstring>());
178 if (sVec.size() != 2) {
179 std::cout << "Wrong format for critical thresholds" << '\n';
183 printInfo.crit = threshold(*sVec.begin());
184 printInfo.cpl = threshold(sVec.back());
185 if (!printInfo.wpl.perc) {
186 std::cout << "Packet loss must be percentage" << '\n';
189 } catch (std::invalid_argument& e) {
190 std::cout << e.what() << '\n';
195 if (vm.count("timeout"))
196 printInfo.timeout = vm["timeout"].as<INT>();
197 if (vm.count("count"))
198 printInfo.num = vm["count"].as<INT>();
200 printInfo.ipv4 = FALSE;
202 printInfo.host = vm["host"].as<std::wstring>();
204 if (vm.count("debug"))
210 INT printOutput(printInfoStruct& printInfo, response& response)
213 std::wcout << L"Constructing output string" << '\n';
217 double plp = ((double)response.dropped / printInfo.num) * 100.0;
219 if (printInfo.warn.rend(response.avg) || printInfo.wpl.rend(plp))
222 if (printInfo.crit.rend(response.avg) || printInfo.cpl.rend(plp))
225 std::wstringstream perf;
226 perf << L"rta=" << response.avg << L"ms;" << printInfo.warn.pString() << L";"
227 << printInfo.crit.pString() << L";0;" << " pl=" << removeZero(plp) << "%;"
228 << printInfo.wpl.pString() << ";" << printInfo.cpl.pString() << ";0;100";
230 if (response.dropped == printInfo.num) {
231 std::wcout << L"PING CRITICAL ALL CONNECTIONS DROPPED | " << perf.str() << '\n';
237 std::wcout << L"PING OK RTA: " << response.avg << L"ms Packet loss: " << removeZero(plp) << "% | " << perf.str() << '\n';
240 std::wcout << L"PING WARNING RTA: " << response.avg << L"ms Packet loss: " << removeZero(plp) << "% | " << perf.str() << '\n';
243 std::wcout << L"PING CRITICAL RTA: " << response.avg << L"ms Packet loss: " << removeZero(plp) << "% | " << perf.str() << '\n';
250 INT check_ping4(const printInfoStruct& pi, response& response)
254 DWORD dwRet = 0, dwRepSize = 0;
255 LPVOID repBuf = NULL;
258 LARGE_INTEGER frequency, timer1, timer2;
262 std::wcout << L"Parsing ip address" << '\n';
264 if (RtlIpv4StringToAddress(pi.host.c_str(), TRUE, &term, &ipDest4) == STATUS_INVALID_PARAMETER) {
265 std::wcout << pi.host << " is not a valid ip address\n";
269 if (*term != L'\0') {
270 std::wcout << pi.host << " is not a valid ip address\n";
275 std::wcout << L"Creating Icmp File\n";
277 if ((hIcmp = IcmpCreateFile()) == INVALID_HANDLE_VALUE)
280 dwRepSize = sizeof(ICMP_ECHO_REPLY) + 8;
281 repBuf = reinterpret_cast<VOID *>(new BYTE[dwRepSize]);
286 QueryPerformanceFrequency(&frequency);
288 QueryPerformanceCounter(&timer1);
291 std::wcout << L"Sending Icmp echo\n";
293 if (!IcmpSendEcho2(hIcmp, NULL, NULL, NULL, ipDest4.S_un.S_addr,
294 NULL, 0, NULL, repBuf, dwRepSize, pi.timeout)) {
297 std::wcout << L"Dropped: Response was 0" << '\n';
302 std::wcout << "Ping recieved" << '\n';
304 PICMP_ECHO_REPLY pEchoReply = static_cast<PICMP_ECHO_REPLY>(repBuf);
306 if (pEchoReply->Status != IP_SUCCESS) {
309 std::wcout << L"Dropped: echo reply status " << pEchoReply->Status << '\n';
314 std::wcout << L"Recorded rtt of " << pEchoReply->RoundTripTime << '\n';
316 rtt += pEchoReply->RoundTripTime;
317 if (response.pMin == 0 || pEchoReply->RoundTripTime < response.pMin)
318 response.pMin = pEchoReply->RoundTripTime;
319 else if (pEchoReply->RoundTripTime > response.pMax)
320 response.pMax = pEchoReply->RoundTripTime;
322 QueryPerformanceCounter(&timer2);
323 if (((timer2.QuadPart - timer1.QuadPart) * 1000 / frequency.QuadPart) < pi.timeout)
324 Sleep(pi.timeout - ((timer2.QuadPart - timer1.QuadPart) * 1000 / frequency.QuadPart));
328 std::wcout << L"All pings sent. Cleaning up and returning" << '\n';
331 IcmpCloseHandle(hIcmp);
333 delete reinterpret_cast<VOID *>(repBuf);
335 response.avg = ((double)rtt / pi.num);
342 IcmpCloseHandle(hIcmp);
344 delete reinterpret_cast<VOID *>(repBuf);
349 INT check_ping6(const printInfoStruct& pi, response& response)
351 sockaddr_in6 ipDest6, ipSource6;
352 IP_OPTION_INFORMATION ipInfo = { 30, 0, 0, 0, NULL };
353 DWORD dwRepSize = sizeof(ICMPV6_ECHO_REPLY) + 8;
354 LPVOID repBuf = reinterpret_cast<VOID *>(new BYTE[dwRepSize]);
357 LARGE_INTEGER frequency, timer1, timer2;
362 std::wcout << L"Parsing ip address" << '\n';
364 if (RtlIpv6StringToAddressEx(pi.host.c_str(), &ipDest6.sin6_addr, &ipDest6.sin6_scope_id, &ipDest6.sin6_port)) {
365 std::wcout << pi.host << " is not a valid ipv6 address" << '\n';
369 ipDest6.sin6_family = AF_INET6;
371 ipSource6.sin6_addr = in6addr_any;
372 ipSource6.sin6_family = AF_INET6;
373 ipSource6.sin6_flowinfo = 0;
374 ipSource6.sin6_port = 0;
377 std::wcout << L"Creating Icmp File" << '\n';
379 hIcmp = Icmp6CreateFile();
380 if (hIcmp == INVALID_HANDLE_VALUE) {
384 QueryPerformanceFrequency(&frequency);
386 QueryPerformanceCounter(&timer1);
389 std::wcout << L"Sending Icmp echo" << '\n';
391 if (!Icmp6SendEcho2(hIcmp, NULL, NULL, NULL, &ipSource6, &ipDest6,
392 NULL, 0, &ipInfo, repBuf, dwRepSize, pi.timeout)) {
395 std::wcout << L"Dropped: Response was 0" << '\n';
400 std::wcout << "Ping recieved" << '\n';
402 Icmp6ParseReplies(repBuf, dwRepSize);
404 ICMPV6_ECHO_REPLY *pEchoReply = static_cast<ICMPV6_ECHO_REPLY *>(repBuf);
406 if (pEchoReply->Status != IP_SUCCESS) {
409 std::wcout << L"Dropped: echo reply status " << pEchoReply->Status << '\n';
413 rtt += pEchoReply->RoundTripTime;
416 std::wcout << L"Recorded rtt of " << pEchoReply->RoundTripTime << '\n';
418 if (response.pMin == 0 || pEchoReply->RoundTripTime < response.pMin)
419 response.pMin = pEchoReply->RoundTripTime;
420 else if (pEchoReply->RoundTripTime > response.pMax)
421 response.pMax = pEchoReply->RoundTripTime;
423 QueryPerformanceCounter(&timer2);
424 if (((timer2.QuadPart - timer1.QuadPart) * 1000 / frequency.QuadPart) < pi.timeout)
425 Sleep(pi.timeout - ((timer2.QuadPart - timer1.QuadPart) * 1000 / frequency.QuadPart));
429 std::wcout << L"All pings sent. Cleaning up and returning" << '\n';
432 IcmpCloseHandle(hIcmp);
434 delete reinterpret_cast<VOID *>(repBuf);
435 response.avg = ((double)rtt / pi.num);
442 IcmpCloseHandle(hIcmp);
444 delete reinterpret_cast<VOID *>(repBuf);