Merge pull request #40 from avances123/master
[monitoring-plugins.git] / plugins / check_apt.c
blobdaeb75781ec7cfe7fc61e142f462600372f1443c
1 /*****************************************************************************
2 *
3 * Nagios check_apt plugin
4 *
5 * License: GPL
6 * Copyright (c) 2006-2008 Nagios Plugins Development Team
7 *
8 * Original author: Sean Finney
9 *
10 * Description:
12 * This file contains the check_apt plugin
14 * Check for available updates in apt package management systems
17 * This program is free software: you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation, either version 3 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program. If not, see <http://www.gnu.org/licenses/>.
30 *****************************************************************************/
32 const char *progname = "check_apt";
33 const char *copyright = "2006-2008";
34 const char *email = "nagiosplug-devel@lists.sourceforge.net";
36 #include "common.h"
37 #include "runcmd.h"
38 #include "utils.h"
39 #include "regex.h"
41 /* some constants */
42 typedef enum { UPGRADE, DIST_UPGRADE, NO_UPGRADE } upgrade_type;
44 /* Character for hidden input file option (for testing). */
45 #define INPUT_FILE_OPT CHAR_MAX+1
46 /* the default opts can be overridden via the cmdline */
47 #define UPGRADE_DEFAULT_OPTS "-o 'Debug::NoLocking=true' -s -qq"
48 #define UPDATE_DEFAULT_OPTS "-q"
49 /* until i commit the configure.in patch which gets this, i'll define
50 * it here as well */
51 #ifndef PATH_TO_APTGET
52 # define PATH_TO_APTGET "/usr/bin/apt-get"
53 #endif /* PATH_TO_APTGET */
54 /* String found at the beginning of the apt output lines we're interested in */
55 #define PKGINST_PREFIX "Inst "
56 /* the RE that catches security updates */
57 #define SECURITY_RE "^[^\\(]*\\(.* (Debian-Security:|Ubuntu:[^/]*/[^-]*-security)"
59 /* some standard functions */
60 int process_arguments(int, char **);
61 void print_help(void);
62 void print_usage(void);
64 /* construct the appropriate apt-get cmdline */
65 char* construct_cmdline(upgrade_type u, const char *opts);
66 /* run an apt-get update */
67 int run_update(void);
68 /* run an apt-get upgrade */
69 int run_upgrade(int *pkgcount, int *secpkgcount);
70 /* add another clause to a regexp */
71 char* add_to_regexp(char *expr, const char *next);
73 /* configuration variables */
74 static int verbose = 0; /* -v */
75 static int do_update = 0; /* whether to call apt-get update */
76 static upgrade_type upgrade = UPGRADE; /* which type of upgrade to do */
77 static char *upgrade_opts = NULL; /* options to override defaults for upgrade */
78 static char *update_opts = NULL; /* options to override defaults for update */
79 static char *do_include = NULL; /* regexp to only include certain packages */
80 static char *do_exclude = NULL; /* regexp to only exclude certain packages */
81 static char *do_critical = NULL; /* regexp specifying critical packages */
82 static char *input_filename = NULL; /* input filename for testing */
84 /* other global variables */
85 static int stderr_warning = 0; /* if a cmd issued output on stderr */
86 static int exec_warning = 0; /* if a cmd exited non-zero */
88 int main (int argc, char **argv) {
89 int result=STATE_UNKNOWN, packages_available=0, sec_count=0;
91 /* Parse extra opts if any */
92 argv=np_extra_opts(&argc, argv, progname);
94 if (process_arguments(argc, argv) == ERROR)
95 usage_va(_("Could not parse arguments"));
97 /* Set signal handling and alarm timeout */
98 if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
99 usage_va(_("Cannot catch SIGALRM"));
102 /* handle timeouts gracefully... */
103 alarm (timeout_interval);
105 /* if they want to run apt-get update first... */
106 if(do_update) result = run_update();
108 /* apt-get upgrade */
109 result = max_state(result, run_upgrade(&packages_available, &sec_count));
111 if(sec_count > 0){
112 result = max_state(result, STATE_CRITICAL);
113 } else if(packages_available > 0){
114 result = max_state(result, STATE_WARNING);
115 } else if(result > STATE_UNKNOWN){
116 result = STATE_UNKNOWN;
119 printf(_("APT %s: %d packages available for %s (%d critical updates). %s%s%s%s|available_upgrades=%d;;;0 critical_updates=%d;;;0\n"),
120 state_text(result),
121 packages_available,
122 (upgrade==DIST_UPGRADE)?"dist-upgrade":"upgrade",
123 sec_count,
124 (stderr_warning)?" warnings detected":"",
125 (stderr_warning && exec_warning)?",":"",
126 (exec_warning)?" errors detected":"",
127 (stderr_warning||exec_warning)?". run with -v for information.":"",
128 packages_available,
129 sec_count
132 return result;
135 /* process command-line arguments */
136 int process_arguments (int argc, char **argv) {
137 int c;
139 static struct option longopts[] = {
140 {"version", no_argument, 0, 'V'},
141 {"help", no_argument, 0, 'h'},
142 {"verbose", no_argument, 0, 'v'},
143 {"timeout", required_argument, 0, 't'},
144 {"update", optional_argument, 0, 'u'},
145 {"upgrade", optional_argument, 0, 'U'},
146 {"no-upgrade", no_argument, 0, 'n'},
147 {"dist-upgrade", optional_argument, 0, 'd'},
148 {"include", required_argument, 0, 'i'},
149 {"exclude", required_argument, 0, 'e'},
150 {"critical", required_argument, 0, 'c'},
151 {"input-file", required_argument, 0, INPUT_FILE_OPT},
152 {0, 0, 0, 0}
155 while(1) {
156 c = getopt_long(argc, argv, "hVvt:u::U::d::ni:e:c:", longopts, NULL);
158 if(c == -1 || c == EOF || c == 1) break;
160 switch(c) {
161 case 'h':
162 print_help();
163 exit(STATE_OK);
164 case 'V':
165 print_revision(progname, NP_VERSION);
166 exit(STATE_OK);
167 case 'v':
168 verbose++;
169 break;
170 case 't':
171 timeout_interval=atoi(optarg);
172 break;
173 case 'd':
174 upgrade=DIST_UPGRADE;
175 if(optarg!=NULL){
176 upgrade_opts=strdup(optarg);
177 if(upgrade_opts==NULL) die(STATE_UNKNOWN, "strdup failed");
179 break;
180 case 'U':
181 upgrade=UPGRADE;
182 if(optarg!=NULL){
183 upgrade_opts=strdup(optarg);
184 if(upgrade_opts==NULL) die(STATE_UNKNOWN, "strdup failed");
186 break;
187 case 'n':
188 upgrade=NO_UPGRADE;
189 break;
190 case 'u':
191 do_update=1;
192 if(optarg!=NULL){
193 update_opts=strdup(optarg);
194 if(update_opts==NULL) die(STATE_UNKNOWN, "strdup failed");
196 break;
197 case 'i':
198 do_include=add_to_regexp(do_include, optarg);
199 break;
200 case 'e':
201 do_exclude=add_to_regexp(do_exclude, optarg);
202 break;
203 case 'c':
204 do_critical=add_to_regexp(do_critical, optarg);
205 break;
206 case INPUT_FILE_OPT:
207 input_filename = optarg;
208 break;
209 default:
210 /* print short usage statement if args not parsable */
211 usage5();
215 return OK;
219 /* run an apt-get upgrade */
220 int run_upgrade(int *pkgcount, int *secpkgcount){
221 int i=0, result=STATE_UNKNOWN, regres=0, pc=0, spc=0;
222 struct output chld_out, chld_err;
223 regex_t ireg, ereg, sreg;
224 char *cmdline=NULL, rerrbuf[64];
226 if(upgrade==NO_UPGRADE) return STATE_OK;
228 /* compile the regexps */
229 if (do_include != NULL) {
230 regres=regcomp(&ireg, do_include, REG_EXTENDED);
231 if (regres!=0) {
232 regerror(regres, &ireg, rerrbuf, 64);
233 die(STATE_UNKNOWN, _("%s: Error compiling regexp: %s"), progname, rerrbuf);
237 if(do_exclude!=NULL){
238 regres=regcomp(&ereg, do_exclude, REG_EXTENDED);
239 if(regres!=0) {
240 regerror(regres, &ereg, rerrbuf, 64);
241 die(STATE_UNKNOWN, _("%s: Error compiling regexp: %s"),
242 progname, rerrbuf);
246 const char *crit_ptr = (do_critical != NULL) ? do_critical : SECURITY_RE;
247 regres=regcomp(&sreg, crit_ptr, REG_EXTENDED);
248 if(regres!=0) {
249 regerror(regres, &ereg, rerrbuf, 64);
250 die(STATE_UNKNOWN, _("%s: Error compiling regexp: %s"),
251 progname, rerrbuf);
254 cmdline=construct_cmdline(upgrade, upgrade_opts);
255 if (input_filename != NULL) {
256 /* read input from a file for testing */
257 result = cmd_file_read(input_filename, &chld_out, 0);
258 } else {
259 /* run the upgrade */
260 result = np_runcmd(cmdline, &chld_out, &chld_err, 0);
263 /* apt-get upgrade only changes exit status if there is an
264 * internal error when run in dry-run mode. therefore we will
265 * treat such an error as UNKNOWN */
266 if(result != 0){
267 exec_warning=1;
268 result = STATE_UNKNOWN;
269 fprintf(stderr, _("'%s' exited with non-zero status.\n"),
270 cmdline);
273 /* parse the output, which should only consist of lines like
275 * Inst package ....
276 * Conf package ....
278 * so we'll filter based on "Inst" for the time being. later
279 * we may need to switch to the --print-uris output format,
280 * in which case the logic here will slightly change.
282 for(i = 0; i < chld_out.lines; i++) {
283 if(verbose){
284 printf("%s\n", chld_out.line[i]);
286 /* if it is a package we care about */
287 if (strncmp(PKGINST_PREFIX, chld_out.line[i], strlen(PKGINST_PREFIX)) == 0 &&
288 (do_include == NULL || regexec(&ireg, chld_out.line[i], 0, NULL, 0) == 0)) {
289 /* if we're not excluding, or it's not in the
290 * list of stuff to exclude */
291 if(do_exclude==NULL ||
292 regexec(&ereg, chld_out.line[i], 0, NULL, 0)!=0){
293 pc++;
294 if(regexec(&sreg, chld_out.line[i], 0, NULL, 0)==0){
295 spc++;
296 if(verbose) printf("*");
298 if(verbose){
299 printf("*%s\n", chld_out.line[i]);
304 *pkgcount=pc;
305 *secpkgcount=spc;
307 /* If we get anything on stderr, at least set warning */
308 if (input_filename == NULL && chld_err.buflen) {
309 stderr_warning=1;
310 result = max_state(result, STATE_WARNING);
311 if(verbose){
312 for(i = 0; i < chld_err.lines; i++) {
313 fprintf(stderr, "%s\n", chld_err.line[i]);
317 if (do_include != NULL) regfree(&ireg);
318 regfree(&sreg);
319 if(do_exclude!=NULL) regfree(&ereg);
320 free(cmdline);
321 return result;
324 /* run an apt-get update (needs root) */
325 int run_update(void){
326 int i=0, result=STATE_UNKNOWN;
327 struct output chld_out, chld_err;
328 char *cmdline;
330 /* run the upgrade */
331 cmdline = construct_cmdline(NO_UPGRADE, update_opts);
332 result = np_runcmd(cmdline, &chld_out, &chld_err, 0);
333 /* apt-get update changes exit status if it can't fetch packages.
334 * since we were explicitly asked to do so, this is treated as
335 * a critical error. */
336 if(result != 0){
337 exec_warning=1;
338 result = STATE_CRITICAL;
339 fprintf(stderr, _("'%s' exited with non-zero status.\n"),
340 cmdline);
343 if(verbose){
344 for(i = 0; i < chld_out.lines; i++) {
345 printf("%s\n", chld_out.line[i]);
349 /* If we get anything on stderr, at least set warning */
350 if(chld_err.buflen){
351 stderr_warning=1;
352 result = max_state(result, STATE_WARNING);
353 if(verbose){
354 for(i = 0; i < chld_err.lines; i++) {
355 fprintf(stderr, "%s\n", chld_err.line[i]);
359 free(cmdline);
360 return result;
363 char* add_to_regexp(char *expr, const char *next){
364 char *re=NULL;
366 if(expr==NULL){
367 re=malloc(sizeof(char)*(strlen("()")+strlen(next)+1));
368 if(!re) die(STATE_UNKNOWN, "malloc failed!\n");
369 sprintf(re, "(%s)", next);
370 } else {
371 /* resize it, adding an extra char for the new '|' separator */
372 re=realloc(expr, sizeof(char)*(strlen(expr)+1+strlen(next)+1));
373 if(!re) die(STATE_UNKNOWN, "realloc failed!\n");
374 /* append it starting at ')' in the old re */
375 sprintf((char*)(re+strlen(re)-1), "|%s)", next);
378 return re;
381 char* construct_cmdline(upgrade_type u, const char *opts){
382 int len=0;
383 const char *opts_ptr=NULL, *aptcmd=NULL;
384 char *cmd=NULL;
386 switch(u){
387 case UPGRADE:
388 if(opts==NULL) opts_ptr=UPGRADE_DEFAULT_OPTS;
389 else opts_ptr=opts;
390 aptcmd="upgrade";
391 break;
392 case DIST_UPGRADE:
393 if(opts==NULL) opts_ptr=UPGRADE_DEFAULT_OPTS;
394 else opts_ptr=opts;
395 aptcmd="dist-upgrade";
396 break;
397 case NO_UPGRADE:
398 if(opts==NULL) opts_ptr=UPDATE_DEFAULT_OPTS;
399 else opts_ptr=opts;
400 aptcmd="update";
401 break;
404 len+=strlen(PATH_TO_APTGET)+1; /* "/usr/bin/apt-get " */
405 len+=strlen(opts_ptr)+1; /* "opts " */
406 len+=strlen(aptcmd)+1; /* "upgrade\0" */
408 cmd=(char*)malloc(sizeof(char)*len);
409 if(cmd==NULL) die(STATE_UNKNOWN, "malloc failed");
410 sprintf(cmd, "%s %s %s", PATH_TO_APTGET, opts_ptr, aptcmd);
411 return cmd;
414 /* informative help message */
415 void
416 print_help (void)
418 print_revision(progname, NP_VERSION);
420 printf(_(COPYRIGHT), copyright, email);
422 printf("%s\n", _("This plugin checks for software updates on systems that use"));
423 printf("%s\n", _("package management systems based on the apt-get(8) command"));
424 printf("%s\n", _("found in Debian GNU/Linux"));
426 printf ("\n\n");
428 print_usage();
430 printf(UT_HELP_VRSN);
431 printf(UT_EXTRA_OPTS);
433 printf(UT_TIMEOUT, timeout_interval);
435 printf (" %s\n", "-U, --upgrade=OPTS");
436 printf (" %s\n", _("[Default] Perform an upgrade. If an optional OPTS argument is provided,"));
437 printf (" %s\n", _("apt-get will be run with these command line options instead of the"));
438 printf (" %s", _("default "));
439 printf ("(%s).\n", UPGRADE_DEFAULT_OPTS);
440 printf (" %s\n", _("Note that you may be required to have root privileges if you do not use"));
441 printf (" %s\n", _("the default options."));
442 printf (" %s\n", "-d, --dist-upgrade=OPTS");
443 printf (" %s\n", _("Perform a dist-upgrade instead of normal upgrade. Like with -U OPTS"));
444 printf (" %s\n", _("can be provided to override the default options."));
445 printf (" %s\n", " -n, --no-upgrade");
446 printf (" %s\n", _("Do not run the upgrade. Probably not useful (without -u at least)."));
447 printf (" %s\n", "-i, --include=REGEXP");
448 printf (" %s\n", _("Include only packages matching REGEXP. Can be specified multiple times"));
449 printf (" %s\n", _("the values will be combined together. Any packages matching this list"));
450 printf (" %s\n", _("cause the plugin to return WARNING status. Others will be ignored."));
451 printf (" %s\n", _("Default is to include all packages."));
452 printf (" %s\n", "-e, --exclude=REGEXP");
453 printf (" %s\n", _("Exclude packages matching REGEXP from the list of packages that would"));
454 printf (" %s\n", _("otherwise be included. Can be specified multiple times; the values"));
455 printf (" %s\n", _("will be combined together. Default is to exclude no packages."));
456 printf (" %s\n", "-c, --critical=REGEXP");
457 printf (" %s\n", _("If the full package information of any of the upgradable packages match"));
458 printf (" %s\n", _("this REGEXP, the plugin will return CRITICAL status. Can be specified"));
459 printf (" %s\n", _("multiple times like above. Default is a regexp matching security"));
460 printf (" %s\n", _("upgrades for Debian and Ubuntu:"));
461 printf (" \t\%s\n", SECURITY_RE);
462 printf (" %s\n", _("Note that the package must first match the include list before its"));
463 printf (" %s\n\n", _("information is compared against the critical list."));
465 printf ("%s\n\n", _("The following options require root privileges and should be used with care:"));
466 printf (" %s\n", "-u, --update=OPTS");
467 printf (" %s\n", _("First perform an 'apt-get update'. An optional OPTS parameter overrides"));
468 printf (" %s\n", _("the default options. Note: you may also need to adjust the global"));
469 printf (" %s\n", _("timeout (with -t) to prevent the plugin from timing out if apt-get"));
470 printf (" %s\n", _("upgrade is expected to take longer than the default timeout."));
472 printf(UT_SUPPORT);
476 /* simple usage heading */
477 void
478 print_usage(void)
480 printf ("%s\n", _("Usage:"));
481 printf ("%s [[-d|-u|-U]opts] [-n] [-t timeout]\n", progname);