check_ups: additional alarm conditions (#1961)
[monitoring-plugins.git] / plugins / check_apt.c
blob5c0f6e28e42f9872c59ae4e321960c0da4d24784
1 /*****************************************************************************
3 * Monitoring check_apt plugin
5 * License: GPL
6 * Copyright (c) 2006-2008 Monitoring Plugins Development Team
8 * Original author: Sean Finney
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 = "devel@monitoring-plugins.org";
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, char ***pkglist, char ***secpkglist);
70 /* add another clause to a regexp */
71 char* add_to_regexp(char *expr, const char *next);
72 /* extract package name from Inst line */
73 char* pkg_name(char *line);
74 /* string comparison function for qsort */
75 int cmpstringp(const void *p1, const void *p2);
77 /* configuration variables */
78 static int verbose = 0; /* -v */
79 static bool list = false; /* list packages available for upgrade */
80 static bool do_update = false; /* whether to call apt-get update */
81 static bool only_critical = false; /* whether to warn about non-critical updates */
82 static upgrade_type upgrade = UPGRADE; /* which type of upgrade to do */
83 static char *upgrade_opts = NULL; /* options to override defaults for upgrade */
84 static char *update_opts = NULL; /* options to override defaults for update */
85 static char *do_include = NULL; /* regexp to only include certain packages */
86 static char *do_exclude = NULL; /* regexp to only exclude certain packages */
87 static char *do_critical = NULL; /* regexp specifying critical packages */
88 static char *input_filename = NULL; /* input filename for testing */
89 /* number of packages available for upgrade to return WARNING status */
90 static int packages_warning = 1;
92 /* other global variables */
93 static int stderr_warning = 0; /* if a cmd issued output on stderr */
94 static int exec_warning = 0; /* if a cmd exited non-zero */
96 int main (int argc, char **argv) {
97 int result=STATE_UNKNOWN, packages_available=0, sec_count=0;
98 char **packages_list=NULL, **secpackages_list=NULL;
100 /* Parse extra opts if any */
101 argv=np_extra_opts(&argc, argv, progname);
103 if (process_arguments(argc, argv) == ERROR)
104 usage_va(_("Could not parse arguments"));
106 /* Set signal handling and alarm timeout */
107 if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
108 usage_va(_("Cannot catch SIGALRM"));
111 /* handle timeouts gracefully... */
112 alarm (timeout_interval);
114 /* if they want to run apt-get update first... */
115 if(do_update) result = run_update();
117 /* apt-get upgrade */
118 result = max_state(result, run_upgrade(&packages_available, &sec_count, &packages_list, &secpackages_list));
120 if(sec_count > 0){
121 result = max_state(result, STATE_CRITICAL);
122 } else if(packages_available >= packages_warning && only_critical == false){
123 result = max_state(result, STATE_WARNING);
124 } else if(result > STATE_UNKNOWN){
125 result = STATE_UNKNOWN;
128 printf(_("APT %s: %d packages available for %s (%d critical updates). %s%s%s%s|available_upgrades=%d;;;0 critical_updates=%d;;;0\n"),
129 state_text(result),
130 packages_available,
131 (upgrade==DIST_UPGRADE)?"dist-upgrade":"upgrade",
132 sec_count,
133 (stderr_warning)?" warnings detected":"",
134 (stderr_warning && exec_warning)?",":"",
135 (exec_warning)?" errors detected":"",
136 (stderr_warning||exec_warning)?".":"",
137 packages_available,
138 sec_count
141 if(list) {
142 qsort(secpackages_list, sec_count, sizeof(char*), cmpstringp);
143 qsort(packages_list, packages_available-sec_count, sizeof(char*), cmpstringp);
145 for(int i = 0; i < sec_count; i++)
146 printf("%s (security)\n", secpackages_list[i]);
148 if (only_critical == false) {
149 for(int i = 0; i < packages_available - sec_count; i++)
150 printf("%s\n", packages_list[i]);
154 return result;
157 /* process command-line arguments */
158 int process_arguments (int argc, char **argv) {
159 int c;
161 static struct option longopts[] = {
162 {"version", no_argument, 0, 'V'},
163 {"help", no_argument, 0, 'h'},
164 {"verbose", no_argument, 0, 'v'},
165 {"timeout", required_argument, 0, 't'},
166 {"update", optional_argument, 0, 'u'},
167 {"upgrade", optional_argument, 0, 'U'},
168 {"no-upgrade", no_argument, 0, 'n'},
169 {"dist-upgrade", optional_argument, 0, 'd'},
170 {"list", no_argument, false, 'l'},
171 {"include", required_argument, 0, 'i'},
172 {"exclude", required_argument, 0, 'e'},
173 {"critical", required_argument, 0, 'c'},
174 {"only-critical", no_argument, 0, 'o'},
175 {"input-file", required_argument, 0, INPUT_FILE_OPT},
176 {"packages-warning", required_argument, 0, 'w'},
177 {0, 0, 0, 0}
180 while(1) {
181 c = getopt_long(argc, argv, "hVvt:u::U::d::nli:e:c:ow:", longopts, NULL);
183 if(c == -1 || c == EOF || c == 1) break;
185 switch(c) {
186 case 'h':
187 print_help();
188 exit(STATE_UNKNOWN);
189 case 'V':
190 print_revision(progname, NP_VERSION);
191 exit(STATE_UNKNOWN);
192 case 'v':
193 verbose++;
194 break;
195 case 't':
196 timeout_interval=atoi(optarg);
197 break;
198 case 'd':
199 upgrade=DIST_UPGRADE;
200 if(optarg!=NULL){
201 upgrade_opts=strdup(optarg);
202 if(upgrade_opts==NULL) die(STATE_UNKNOWN, "strdup failed");
204 break;
205 case 'U':
206 upgrade=UPGRADE;
207 if(optarg!=NULL){
208 upgrade_opts=strdup(optarg);
209 if(upgrade_opts==NULL) die(STATE_UNKNOWN, "strdup failed");
211 break;
212 case 'n':
213 upgrade=NO_UPGRADE;
214 break;
215 case 'u':
216 do_update=true;
217 if(optarg!=NULL){
218 update_opts=strdup(optarg);
219 if(update_opts==NULL) die(STATE_UNKNOWN, "strdup failed");
221 break;
222 case 'l':
223 list=true;
224 break;
225 case 'i':
226 do_include=add_to_regexp(do_include, optarg);
227 break;
228 case 'e':
229 do_exclude=add_to_regexp(do_exclude, optarg);
230 break;
231 case 'c':
232 do_critical=add_to_regexp(do_critical, optarg);
233 break;
234 case 'o':
235 only_critical=true;
236 break;
237 case INPUT_FILE_OPT:
238 input_filename = optarg;
239 break;
240 case 'w':
241 packages_warning = atoi(optarg);
242 break;
243 default:
244 /* print short usage statement if args not parsable */
245 usage5();
249 return OK;
253 /* run an apt-get upgrade */
254 int run_upgrade(int *pkgcount, int *secpkgcount, char ***pkglist, char ***secpkglist){
255 int result=STATE_UNKNOWN, regres=0, pc=0, spc=0;
256 struct output chld_out, chld_err;
257 regex_t ireg, ereg, sreg;
258 char *cmdline=NULL, rerrbuf[64];
260 /* initialize ereg as it is possible it is printed while uninitialized */
261 memset(&ereg, '\0', sizeof(ereg.buffer));
263 if(upgrade==NO_UPGRADE) return STATE_OK;
265 /* compile the regexps */
266 if (do_include != NULL) {
267 regres=regcomp(&ireg, do_include, REG_EXTENDED);
268 if (regres!=0) {
269 regerror(regres, &ireg, rerrbuf, 64);
270 die(STATE_UNKNOWN, _("%s: Error compiling regexp: %s"), progname, rerrbuf);
274 if(do_exclude!=NULL){
275 regres=regcomp(&ereg, do_exclude, REG_EXTENDED);
276 if(regres!=0) {
277 regerror(regres, &ereg, rerrbuf, 64);
278 die(STATE_UNKNOWN, _("%s: Error compiling regexp: %s"),
279 progname, rerrbuf);
283 const char *crit_ptr = (do_critical != NULL) ? do_critical : SECURITY_RE;
284 regres=regcomp(&sreg, crit_ptr, REG_EXTENDED);
285 if(regres!=0) {
286 regerror(regres, &ereg, rerrbuf, 64);
287 die(STATE_UNKNOWN, _("%s: Error compiling regexp: %s"),
288 progname, rerrbuf);
291 cmdline=construct_cmdline(upgrade, upgrade_opts);
292 if (input_filename != NULL) {
293 /* read input from a file for testing */
294 result = cmd_file_read(input_filename, &chld_out, 0);
295 } else {
296 /* run the upgrade */
297 result = np_runcmd(cmdline, &chld_out, &chld_err, 0);
300 /* apt-get upgrade only changes exit status if there is an
301 * internal error when run in dry-run mode. therefore we will
302 * treat such an error as UNKNOWN */
303 if(result != 0){
304 exec_warning=1;
305 result = STATE_UNKNOWN;
306 fprintf(stderr, _("'%s' exited with non-zero status.\n"),
307 cmdline);
310 *pkglist=malloc(sizeof(char *) * chld_out.lines);
311 if(!pkglist) die(STATE_UNKNOWN, "malloc failed!\n");
312 *secpkglist=malloc(sizeof(char *) * chld_out.lines);
313 if(!secpkglist) die(STATE_UNKNOWN, "malloc failed!\n");
315 /* parse the output, which should only consist of lines like
317 * Inst package ....
318 * Conf package ....
320 * so we'll filter based on "Inst" for the time being. later
321 * we may need to switch to the --print-uris output format,
322 * in which case the logic here will slightly change.
324 for(size_t i = 0; i < chld_out.lines; i++) {
325 if(verbose){
326 printf("%s\n", chld_out.line[i]);
328 /* if it is a package we care about */
329 if (strncmp(PKGINST_PREFIX, chld_out.line[i], strlen(PKGINST_PREFIX)) == 0 &&
330 (do_include == NULL || regexec(&ireg, chld_out.line[i], 0, NULL, 0) == 0)) {
331 /* if we're not excluding, or it's not in the
332 * list of stuff to exclude */
333 if(do_exclude==NULL ||
334 regexec(&ereg, chld_out.line[i], 0, NULL, 0)!=0){
335 pc++;
336 if(regexec(&sreg, chld_out.line[i], 0, NULL, 0)==0){
337 spc++;
338 if(verbose) printf("*");
339 (*secpkglist)[spc-1] = pkg_name(chld_out.line[i]);
340 } else {
341 (*pkglist)[pc-spc-1] = pkg_name(chld_out.line[i]);
343 if(verbose){
344 printf("*%s\n", chld_out.line[i]);
349 *pkgcount=pc;
350 *secpkgcount=spc;
352 /* If we get anything on stderr, at least set warning */
353 if (input_filename == NULL && chld_err.buflen) {
354 stderr_warning=1;
355 result = max_state(result, STATE_WARNING);
356 if(verbose){
357 for(size_t i = 0; i < chld_err.lines; i++) {
358 fprintf(stderr, "%s\n", chld_err.line[i]);
362 if (do_include != NULL) regfree(&ireg);
363 regfree(&sreg);
364 if(do_exclude!=NULL) regfree(&ereg);
365 free(cmdline);
366 return result;
369 /* run an apt-get update (needs root) */
370 int run_update(void){
371 int result=STATE_UNKNOWN;
372 struct output chld_out, chld_err;
373 char *cmdline;
375 /* run the update */
376 cmdline = construct_cmdline(NO_UPGRADE, update_opts);
377 result = np_runcmd(cmdline, &chld_out, &chld_err, 0);
378 /* apt-get update changes exit status if it can't fetch packages.
379 * since we were explicitly asked to do so, this is treated as
380 * a critical error. */
381 if(result != 0){
382 exec_warning=1;
383 result = STATE_CRITICAL;
384 fprintf(stderr, _("'%s' exited with non-zero status.\n"),
385 cmdline);
388 if(verbose){
389 for(size_t i = 0; i < chld_out.lines; i++) {
390 printf("%s\n", chld_out.line[i]);
394 /* If we get anything on stderr, at least set warning */
395 if(chld_err.buflen){
396 stderr_warning=1;
397 result = max_state(result, STATE_WARNING);
398 if(verbose){
399 for(size_t i = 0; i < chld_err.lines; i++) {
400 fprintf(stderr, "%s\n", chld_err.line[i]);
404 free(cmdline);
405 return result;
408 char* pkg_name(char *line){
409 char *start=NULL, *space=NULL, *pkg=NULL;
410 int len=0;
412 start = line + strlen(PKGINST_PREFIX);
413 len = strlen(start);
415 space = index(start, ' ');
416 if(space!=NULL){
417 len = space - start;
420 pkg=malloc(sizeof(char)*(len+1));
421 if(!pkg) die(STATE_UNKNOWN, "malloc failed!\n");
423 strncpy(pkg, start, len);
424 pkg[len]='\0';
426 return pkg;
429 int cmpstringp(const void *p1, const void *p2){
430 return strcmp(* (char * const *) p1, * (char * const *) p2);
433 char* add_to_regexp(char *expr, const char *next){
434 char *re=NULL;
436 if(expr==NULL){
437 re=malloc(sizeof(char)*(strlen("()")+strlen(next)+1));
438 if(!re) die(STATE_UNKNOWN, "malloc failed!\n");
439 sprintf(re, "(%s)", next);
440 } else {
441 /* resize it, adding an extra char for the new '|' separator */
442 re=realloc(expr, sizeof(char)*(strlen(expr)+1+strlen(next)+1));
443 if(!re) die(STATE_UNKNOWN, "realloc failed!\n");
444 /* append it starting at ')' in the old re */
445 sprintf((char*)(re+strlen(re)-1), "|%s)", next);
448 return re;
451 char* construct_cmdline(upgrade_type u, const char *opts){
452 int len=0;
453 const char *opts_ptr=NULL, *aptcmd=NULL;
454 char *cmd=NULL;
456 switch(u){
457 case UPGRADE:
458 if(opts==NULL) opts_ptr=UPGRADE_DEFAULT_OPTS;
459 else opts_ptr=opts;
460 aptcmd="upgrade";
461 break;
462 case DIST_UPGRADE:
463 if(opts==NULL) opts_ptr=UPGRADE_DEFAULT_OPTS;
464 else opts_ptr=opts;
465 aptcmd="dist-upgrade";
466 break;
467 case NO_UPGRADE:
468 if(opts==NULL) opts_ptr=UPDATE_DEFAULT_OPTS;
469 else opts_ptr=opts;
470 aptcmd="update";
471 break;
474 len+=strlen(PATH_TO_APTGET)+1; /* "/usr/bin/apt-get " */
475 len+=strlen(opts_ptr)+1; /* "opts " */
476 len+=strlen(aptcmd)+1; /* "upgrade\0" */
478 cmd=(char*)malloc(sizeof(char)*len);
479 if(cmd==NULL) die(STATE_UNKNOWN, "malloc failed");
480 sprintf(cmd, "%s %s %s", PATH_TO_APTGET, opts_ptr, aptcmd);
481 return cmd;
484 /* informative help message */
485 void
486 print_help (void)
488 print_revision(progname, NP_VERSION);
490 printf(_(COPYRIGHT), copyright, email);
492 printf("%s\n", _("This plugin checks for software updates on systems that use"));
493 printf("%s\n", _("package management systems based on the apt-get(8) command"));
494 printf("%s\n", _("found in Debian GNU/Linux"));
496 printf ("\n\n");
498 print_usage();
500 printf(UT_HELP_VRSN);
501 printf(UT_EXTRA_OPTS);
503 printf(UT_PLUG_TIMEOUT, timeout_interval);
505 printf (" %s\n", "-n, --no-upgrade");
506 printf (" %s\n", _("Do not run the upgrade. Probably not useful (without -u at least)."));
507 printf (" %s\n", "-l, --list");
508 printf (" %s\n", _("List packages available for upgrade. Packages are printed sorted by"));
509 printf (" %s\n", _("name with security packages listed first."));
510 printf (" %s\n", "-i, --include=REGEXP");
511 printf (" %s\n", _("Include only packages matching REGEXP. Can be specified multiple times"));
512 printf (" %s\n", _("the values will be combined together. Any packages matching this list"));
513 printf (" %s\n", _("cause the plugin to return WARNING status. Others will be ignored."));
514 printf (" %s\n", _("Default is to include all packages."));
515 printf (" %s\n", "-e, --exclude=REGEXP");
516 printf (" %s\n", _("Exclude packages matching REGEXP from the list of packages that would"));
517 printf (" %s\n", _("otherwise be included. Can be specified multiple times; the values"));
518 printf (" %s\n", _("will be combined together. Default is to exclude no packages."));
519 printf (" %s\n", "-c, --critical=REGEXP");
520 printf (" %s\n", _("If the full package information of any of the upgradable packages match"));
521 printf (" %s\n", _("this REGEXP, the plugin will return CRITICAL status. Can be specified"));
522 printf (" %s\n", _("multiple times like above. Default is a regexp matching security"));
523 printf (" %s\n", _("upgrades for Debian and Ubuntu:"));
524 printf (" \t%s\n", SECURITY_RE);
525 printf (" %s\n", _("Note that the package must first match the include list before its"));
526 printf (" %s\n", _("information is compared against the critical list."));
527 printf (" %s\n", "-o, --only-critical");
528 printf (" %s\n", _("Only warn about upgrades matching the critical list. The total number"));
529 printf (" %s\n", _("of upgrades will be printed, but any non-critical upgrades will not cause"));
530 printf (" %s\n", _("the plugin to return WARNING status."));
531 printf (" %s\n", "-w, --packages-warning");
532 printf (" %s\n", _("Minimum number of packages available for upgrade to return WARNING status."));
533 printf (" %s\n\n", _("Default is 1 package."));
535 printf ("%s\n\n", _("The following options require root privileges and should be used with care:"));
536 printf (" %s\n", "-u, --update=OPTS");
537 printf (" %s\n", _("First perform an 'apt-get update'. An optional OPTS parameter overrides"));
538 printf (" %s\n", _("the default options. Note: you may also need to adjust the global"));
539 printf (" %s\n", _("timeout (with -t) to prevent the plugin from timing out if apt-get"));
540 printf (" %s\n", _("upgrade is expected to take longer than the default timeout."));
541 printf (" %s\n", "-U, --upgrade=OPTS");
542 printf (" %s\n", _("Perform an upgrade. If an optional OPTS argument is provided,"));
543 printf (" %s\n", _("apt-get will be run with these command line options instead of the"));
544 printf (" %s", _("default "));
545 printf ("(%s).\n", UPGRADE_DEFAULT_OPTS);
546 printf (" %s\n", _("Note that you may be required to have root privileges if you do not use"));
547 printf (" %s\n", _("the default options, which will only run a simulation and NOT perform the upgrade"));
548 printf (" %s\n", "-d, --dist-upgrade=OPTS");
549 printf (" %s\n", _("Perform a dist-upgrade instead of normal upgrade. Like with -U OPTS"));
550 printf (" %s\n", _("can be provided to override the default options."));
552 printf(UT_SUPPORT);
556 /* simple usage heading */
557 void
558 print_usage(void)
560 printf ("%s\n", _("Usage:"));
561 printf ("%s [[-d|-u|-U]opts] [-n] [-l] [-t timeout] [-w packages-warning]\n", progname);