]> granicus.if.org Git - icinga2/blob - plugins/check_update.cpp
Clean up check plugins.
[icinga2] / plugins / check_update.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2014 Icinga Development Team (http://www.icinga.org)    *
4  *                                                                            *
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.                     *
9  *                                                                            *
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.                               *
14  *                                                                            *
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  ******************************************************************************/
19 #include <windows.h>
20 #include <Shlwapi.h>
21 #include <iostream>
22 #include <wuapi.h>
23 #include <wuerror.h>
24
25 #include "thresholds.h"
26
27 #include "boost/program_options.hpp"
28
29 #define VERSION 1.0
30
31 #define CRITERIA L"(IsInstalled = 0 and CategoryIDs contains '0fa1201d-4330-4fa8-8ae9-b877473b6441') or (IsInstalled = 0 and CategoryIDs contains 'E6CF1350-C01B-414D-A61F-263D14D133B4')"
32
33 namespace po = boost::program_options;
34
35 using std::wcout; using std::endl;
36 using std::wstring; using std::cout;
37
38 struct printInfoStruct 
39 {
40         BOOL warn, crit;
41         LONG numUpdates;
42         BOOL important, reboot, careForCanRequest;
43 };
44
45 static int parseArguments(int, wchar_t **, po::variables_map&, printInfoStruct&);
46 static int printOutput(const printInfoStruct&);
47 static int check_update(printInfoStruct&);
48 static void die(DWORD err = 0);
49
50 int main(int argc, wchar_t **argv) 
51 {
52         po::variables_map vm;
53         printInfoStruct printInfo = { FALSE, FALSE, 0, FALSE, FALSE, FALSE };
54
55         int ret = parseArguments(argc, argv, vm, printInfo);
56         if (ret != -1)
57                 return ret;
58         
59         ret = check_update(printInfo);
60         if (ret != -1)
61                 return ret;
62
63         return printOutput(printInfo);
64 }
65
66 int printOutput(const printInfoStruct& printInfo) 
67 {
68         state state = OK;
69         wstring output = L"UPDATE ";
70
71         if (printInfo.important)
72                 state = WARNING;
73
74         if (printInfo.reboot)
75                 state = CRITICAL;
76
77         switch (state) {
78         case OK:
79                 output.append(L"OK ");
80                 break;
81         case WARNING:
82                 output.append(L"WARNING ");
83                 break;
84         case CRITICAL:
85                 output.append(L"CRITICAL ");
86                 break;
87         }
88
89         wcout << output << printInfo.numUpdates << L"|update=" << printInfo.numUpdates << L";"
90                 << printInfo.warn << L";" << printInfo.crit << L";0" << endl;
91         
92         return state;
93 }
94
95 int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& printInfo) 
96 {
97         wchar_t namePath[MAX_PATH];
98         GetModuleFileName(NULL, namePath, MAX_PATH);
99         wchar_t *progName = PathFindFileName(namePath);
100
101         po::options_description desc;
102
103         desc.add_options()
104                 (",h", "print help message and exit")
105                 ("help", "print verbose help and exit")
106                 ("version,v", "print version and exit")
107                 ("warning,w", "warn if there are important updates available")
108                 ("critical,c", "critical if there are important updates that require a reboot")
109                 ("possible-reboot", "treat \"update may need to reboot\" as \"update needs to reboot\"")
110                 ;
111
112         po::basic_command_line_parser<wchar_t> parser(ac, av);
113
114         try {
115                 po::store(
116                         parser
117                         .options(desc)
118                         .style(
119                         po::command_line_style::unix_style |
120                         po::command_line_style::allow_long_disguise)
121                         .run(),
122                         vm);
123                 vm.notify();
124         } catch (std::exception& e) {
125                 cout << e.what() << endl << desc << endl;
126                 return 3;
127         }
128
129         if (vm.count("h")) {
130                 cout << desc << endl;
131                 return 0;
132         } 
133     
134         if (vm.count("help")) {
135                 wcout << progName << " Help\n\tVersion: " << VERSION << endl;
136                 wprintf(
137                         L"%s is a simple program to check a machines required updates.\n"
138                         L"You can use the following options to define its behaviour:\n\n", progName);
139                 cout << desc;
140                 wprintf(
141                         L"\nAfter some time, it will then output a string like this one:\n\n"
142                         L"\tUPDATE WARNING 8|updates=8;1;1;0\n\n"
143                         L"\"UPDATE\" being the type of the check, \"WARNING\" the returned status\n"
144                         L"and \"8\" is the number of important updates updates.\n"
145                         L"The performance data is found behind the \"|\", in order:\n"
146                         L"returned value, warning threshold, critical threshold, minimal value and,\n"
147                         L"if applicable, the maximal value. Performance data will only be displayed when\n"
148                         L"you set at least one threshold\n\n"
149                         L"An update counts as important when it is part of the Security- or\n"
150                         L"CriticalUpdates group.\n"
151                         L"Consult the msdn on WSUS Classification GUIDs for more information.\n"
152                         L"%s' exit codes denote the following:\n"
153                         L" 0\tOK,\n\tNo Thresholds were broken or the programs check part was not executed\n"
154                         L" 1\tWARNING,\n\tThe warning, but not the critical threshold was broken\n"
155                         L" 2\tCRITICAL,\n\tThe critical threshold was broken\n"
156                         L" 3\tUNKNOWN, \n\tThe program experienced an internal or input error\n\n"
157                         L"%s works different from other plugins in that you do not set thresholds\n"
158                         L"but only activate them. Using \"-w\" triggers warning state if there are not\n"
159                         L"installed and non-optional updates. \"-c\" triggers critical if there are\n"
160                         L"non-optional updates that require a reboot.\n"
161                         L"The \"possible-reboot\" option is not recommended since this true for nearly\n"
162                         L"every update."
163                         , progName, progName);
164                 cout << endl;
165                 return 0;
166         }  if (vm.count("version")) {
167                 cout << "Version: " << VERSION << endl;
168                 return 0;
169         }
170
171         if (vm.count("warning"))
172                 printInfo.warn = TRUE;
173
174         if (vm.count("critical"))
175                 printInfo.crit = TRUE;
176
177         if (vm.count("possible-reboot"))
178                 printInfo.careForCanRequest = TRUE;
179
180         return -1;
181 }
182
183 int check_update(printInfoStruct& printInfo) 
184 {
185         CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
186         ISearchResult *pResult;
187         IUpdateSession *pSession;
188         IUpdateSearcher *pSearcher;
189
190         HRESULT err;
191
192         CoCreateInstance(CLSID_UpdateSession, NULL, CLSCTX_INPROC_SERVER, IID_IUpdateSession, (LPVOID*)&pSession);
193         pSession->CreateUpdateSearcher(&pSearcher);
194
195         /*
196          IsInstalled = 0: All updates, including languagepacks and features
197          BrowseOnly = 0: No features or languagepacks, security and unnamed
198          BrowseOnly = 1: Nothing, broken
199          RebootRequired = 1: Reboot required
200         */
201
202         BSTR criteria = SysAllocString(CRITERIA);
203         // http://msdn.microsoft.com/en-us/library/windows/desktop/aa386526%28v=vs.85%29.aspx
204         // http://msdn.microsoft.com/en-us/library/ff357803%28v=vs.85%29.aspx
205
206         err = pSearcher->Search(criteria, &pResult);
207         if (!SUCCEEDED(err))
208                 goto die;
209         SysFreeString(criteria);
210
211         IUpdateCollection *pCollection;
212         IUpdate *pUpdate;
213
214         LONG updateSize;
215         pResult->get_Updates(&pCollection);
216         pCollection->get_Count(&updateSize);
217
218         if (updateSize == 0)
219                 return -1;
220
221         printInfo.numUpdates = updateSize;
222         printInfo.important = printInfo.warn;
223
224         if (!printInfo.crit)
225                 return -1;
226
227         IInstallationBehavior *pIbehav;
228         InstallationRebootBehavior updateReboot;
229
230         for (LONG i = 0; i < updateSize; i++) {
231                 pCollection->get_Item(i, &pUpdate);
232                 pUpdate->get_InstallationBehavior(&pIbehav);
233                 pIbehav->get_RebootBehavior(&updateReboot);
234                 if (updateReboot == irbAlwaysRequiresReboot) {
235                         printInfo.reboot = TRUE;
236                         continue;
237                 }
238                 if (printInfo.careForCanRequest && updateReboot == irbCanRequestReboot)
239                         printInfo.reboot = TRUE;
240         }
241
242         return 0;
243
244 die:
245         if (criteria)
246                 SysFreeString(criteria);
247         die(err);
248         return 3;
249 }
250
251 void die(DWORD err)
252 {
253         if (!err)
254                 err = GetLastError();
255         LPWSTR mBuf = NULL;
256         size_t mS = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
257                                                           NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&mBuf, 0, NULL);
258         wcout << mBuf << endl;
259 }