Merge pull request #1563 from jacobbaungard/ipv6_check_icmp
[monitoring-plugins.git] / plugins / check_apt.c
blobb69680c274d91e20172745a13e87dce9234f0d58
1 /*****************************************************************************
2 *
3 * Monitoring check_apt plugin
4 *
5 * License: GPL
6 * Copyright (c) 2006-2008 Monitoring 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 = "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 int list = 0; /* list packages available for upgrade */
80 static int do_update = 0; /* whether to call apt-get update */
81 static int only_critical = 0; /* 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 */
90 /* other global variables */
91 static int stderr_warning = 0; /* if a cmd issued output on stderr */
92 static int exec_warning = 0; /* if a cmd exited non-zero */
94 int main (int argc, char **argv) {
95 int result=STATE_UNKNOWN, packages_available=0, sec_count=0, i=0;
96 char **packages_list=NULL, **secpackages_list=NULL;
98 /* Parse extra opts if any */
99 argv=np_extra_opts(&argc, argv, progname);
101 if (process_arguments(argc, argv) == ERROR)
102 usage_va(_("Could not parse arguments"));
104 /* Set signal handling and alarm timeout */
105 if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
106 usage_va(_("Cannot catch SIGALRM"));
109 /* handle timeouts gracefully... */
110 alarm (timeout_interval);
112 /* if they want to run apt-get update first... */
113 if(do_update) result = run_update();
115 /* apt-get upgrade */
116 result = max_state(result, run_upgrade(&packages_available, &sec_count, &packages_list, &secpackages_list));
118 if(sec_count > 0){
119 result = max_state(result, STATE_CRITICAL);
120 } else if(packages_available > 0 && only_critical == 0){
121 result = max_state(result, STATE_WARNING);
122 } else if(result > STATE_UNKNOWN){
123 result = STATE_UNKNOWN;
126 printf(_("APT %s: %d packages available for %s (%d critical updates). %s%s%s%s|available_upgrades=%d;;;0 critical_updates=%d;;;0\n"),
127 state_text(result),
128 packages_available,
129 (upgrade==DIST_UPGRADE)?"dist-upgrade":"upgrade",
130 sec_count,
131 (stderr_warning)?" warnings detected":"",
132 (stderr_warning && exec_warning)?",":"",
133 (exec_warning)?" errors detected":"",
134 (stderr_warning||exec_warning)?".":"",
135 packages_available,
136 sec_count
139 if(list) {
140 qsort(secpackages_list, sec_count, sizeof(char*), cmpstringp);
141 qsort(packages_list, packages_available-sec_count, sizeof(char*), cmpstringp);
143 for(i = 0; i < sec_count; i++)
144 printf("%s (security)\n", secpackages_list[i]);
145 if (only_critical == 0) {
146 for(i = 0; i < packages_available - sec_count; i++)
147 printf("%s\n", packages_list[i]);
151 return result;
154 /* process command-line arguments */
155 int process_arguments (int argc, char **argv) {
156 int c;
158 static struct option longopts[] = {
159 {"version", no_argument, 0, 'V'},
160 {"help", no_argument, 0, 'h'},
161 {"verbose", no_argument, 0, 'v'},
162 {"timeout", required_argument, 0, 't'},
163 {"update", optional_argument, 0, 'u'},
164 {"upgrade", optional_argument, 0, 'U'},
165 {"no-upgrade", no_argument, 0, 'n'},
166 {"dist-upgrade", optional_argument, 0, 'd'},
167 {"list", no_argument, 0, 'l'},
168 {"include", required_argument, 0, 'i'},
169 {"exclude", required_argument, 0, 'e'},
170 {"critical", required_argument, 0, 'c'},
171 {"only-critical", no_argument, 0, 'o'},
172 {"input-file", required_argument, 0, INPUT_FILE_OPT},
173 {0, 0, 0, 0}
176 while(1) {
177 c = getopt_long(argc, argv, "hVvt:u::U::d::nli:e:c:o", longopts, NULL);
179 if(c == -1 || c == EOF || c == 1) break;
181 switch(c) {
182 case 'h':
183 print_help();
184 exit(STATE_UNKNOWN);
185 case 'V':
186 print_revision(progname, NP_VERSION);
187 exit(STATE_UNKNOWN);
188 case 'v':
189 verbose++;
190 break;
191 case 't':
192 timeout_interval=atoi(optarg);
193 break;
194 case 'd':
195 upgrade=DIST_UPGRADE;
196 if(optarg!=NULL){
197 upgrade_opts=strdup(optarg);
198 if(upgrade_opts==NULL) die(STATE_UNKNOWN, "strdup failed");
200 break;
201 case 'U':
202 upgrade=UPGRADE;
203 if(optarg!=NULL){
204 upgrade_opts=strdup(optarg);
205 if(upgrade_opts==NULL) die(STATE_UNKNOWN, "strdup failed");
207 break;
208 case 'n':
209 upgrade=NO_UPGRADE;
210 break;
211 case 'u':
212 do_update=1;
213 if(optarg!=NULL){
214 update_opts=strdup(optarg);
215 if(update_opts==NULL) die(STATE_UNKNOWN, "strdup failed");
217 break;
218 case 'l':
219 list=1;
220 break;
221 case 'i':
222 do_include=add_to_regexp(do_include, optarg);
223 break;
224 case 'e':
225 do_exclude=add_to_regexp(do_exclude, optarg);
226 break;
227 case 'c':
228 do_critical=add_to_regexp(do_critical, optarg);
229 break;
230 case 'o':
231 only_critical=1;
232 break;
233 case INPUT_FILE_OPT:
234 input_filename = optarg;
235 break;
236 default:
237 /* print short usage statement if args not parsable */
238 usage5();
242 return OK;
246 /* run an apt-get upgrade */
247 int run_upgrade(int *pkgcount, int *secpkgcount, char ***pkglist, char ***secpkglist){
248 int i=0, result=STATE_UNKNOWN, regres=0, pc=0, spc=0;
249 struct output chld_out, chld_err;
250 regex_t ireg, ereg, sreg;
251 char *cmdline=NULL, rerrbuf[64];
253 /* initialize ereg as it is possible it is printed while uninitialized */
254 memset(&ereg, '\0', sizeof(ereg.buffer));
256 if(upgrade==NO_UPGRADE) return STATE_OK;
258 /* compile the regexps */
259 if (do_include != NULL) {
260 regres=regcomp(&ireg, do_include, REG_EXTENDED);
261 if (regres!=0) {
262 regerror(regres, &ireg, rerrbuf, 64);
263 die(STATE_UNKNOWN, _("%s: Error compiling regexp: %s"), progname, rerrbuf);
267 if(do_exclude!=NULL){
268 regres=regcomp(&ereg, do_exclude, REG_EXTENDED);
269 if(regres!=0) {
270 regerror(regres, &ereg, rerrbuf, 64);
271 die(STATE_UNKNOWN, _("%s: Error compiling regexp: %s"),
272 progname, rerrbuf);
276 const char *crit_ptr = (do_critical != NULL) ? do_critical : SECURITY_RE;
277 regres=regcomp(&sreg, crit_ptr, REG_EXTENDED);
278 if(regres!=0) {
279 regerror(regres, &ereg, rerrbuf, 64);
280 die(STATE_UNKNOWN, _("%s: Error compiling regexp: %s"),
281 progname, rerrbuf);
284 cmdline=construct_cmdline(upgrade, upgrade_opts);
285 if (input_filename != NULL) {
286 /* read input from a file for testing */
287 result = cmd_file_read(input_filename, &chld_out, 0);
288 } else {
289 /* run the upgrade */
290 result = np_runcmd(cmdline, &chld_out, &chld_err, 0);
293 /* apt-get upgrade only changes exit status if there is an
294 * internal error when run in dry-run mode. therefore we will
295 * treat such an error as UNKNOWN */
296 if(result != 0){
297 exec_warning=1;
298 result = STATE_UNKNOWN;
299 fprintf(stderr, _("'%s' exited with non-zero status.\n"),
300 cmdline);
303 *pkglist=malloc(sizeof(char *) * chld_out.lines);
304 if(!pkglist) die(STATE_UNKNOWN, "malloc failed!\n");
305 *secpkglist=malloc(sizeof(char *) * chld_out.lines);
306 if(!secpkglist) die(STATE_UNKNOWN, "malloc failed!\n");
308 /* parse the output, which should only consist of lines like
310 * Inst package ....
311 * Conf package ....
313 * so we'll filter based on "Inst" for the time being. later
314 * we may need to switch to the --print-uris output format,
315 * in which case the logic here will slightly change.
317 for(i = 0; i < chld_out.lines; i++) {
318 if(verbose){
319 printf("%s\n", chld_out.line[i]);
321 /* if it is a package we care about */
322 if (strncmp(PKGINST_PREFIX, chld_out.line[i], strlen(PKGINST_PREFIX)) == 0 &&
323 (do_include == NULL || regexec(&ireg, chld_out.line[i], 0, NULL, 0) == 0)) {
324 /* if we're not excluding, or it's not in the
325 * list of stuff to exclude */
326 if(do_exclude==NULL ||
327 regexec(&ereg, chld_out.line[i], 0, NULL, 0)!=0){
328 pc++;
329 if(regexec(&sreg, chld_out.line[i], 0, NULL, 0)==0){
330 spc++;
331 if(verbose) printf("*");
332 (*secpkglist)[spc-1] = pkg_name(chld_out.line[i]);
333 } else {
334 (*pkglist)[pc-spc-1] = pkg_name(chld_out.line[i]);
336 if(verbose){
337 printf("*%s\n", chld_out.line[i]);
342 *pkgcount=pc;
343 *secpkgcount=spc;
345 /* If we get anything on stderr, at least set warning */
346 if (input_filename == NULL && chld_err.buflen) {
347 stderr_warning=1;
348 result = max_state(result, STATE_WARNING);
349 if(verbose){
350 for(i = 0; i < chld_err.lines; i++) {
351 fprintf(stderr, "%s\n", chld_err.line[i]);
355 if (do_include != NULL) regfree(&ireg);
356 regfree(&sreg);
357 if(do_exclude!=NULL) regfree(&ereg);
358 free(cmdline);
359 return result;
362 /* run an apt-get update (needs root) */
363 int run_update(void){
364 int i=0, result=STATE_UNKNOWN;
365 struct output chld_out, chld_err;
366 char *cmdline;
368 /* run the upgrade */
369 cmdline = construct_cmdline(NO_UPGRADE, update_opts);
370 result = np_runcmd(cmdline, &chld_out, &chld_err, 0);
371 /* apt-get update changes exit status if it can't fetch packages.
372 * since we were explicitly asked to do so, this is treated as
373 * a critical error. */
374 if(result != 0){
375 exec_warning=1;
376 result = STATE_CRITICAL;
377 fprintf(stderr, _("'%s' exited with non-zero status.\n"),
378 cmdline);
381 if(verbose){
382 for(i = 0; i < chld_out.lines; i++) {
383 printf("%s\n", chld_out.line[i]);
387 /* If we get anything on stderr, at least set warning */
388 if(chld_err.buflen){
389 stderr_warning=1;
390 result = max_state(result, STATE_WARNING);
391 if(verbose){
392 for(i = 0; i < chld_err.lines; i++) {
393 fprintf(stderr, "%s\n", chld_err.line[i]);
397 free(cmdline);
398 return result;
401 char* pkg_name(char *line){
402 char *start=NULL, *space=NULL, *pkg=NULL;
403 int len=0;
405 start = line + strlen(PKGINST_PREFIX);
406 len = strlen(start);
408 space = index(start, ' ');
409 if(space!=NULL){
410 len = space - start;
413 pkg=malloc(sizeof(char)*(len+1));
414 if(!pkg) die(STATE_UNKNOWN, "malloc failed!\n");
416 strncpy(pkg, start, len);
417 pkg[len]='\0';
419 return pkg;
422 int cmpstringp(const void *p1, const void *p2){
423 return strcmp(* (char * const *) p1, * (char * const *) p2);
426 char* add_to_regexp(char *expr, const char *next){
427 char *re=NULL;
429 if(expr==NULL){
430 re=malloc(sizeof(char)*(strlen("()")+strlen(next)+1));
431 if(!re) die(STATE_UNKNOWN, "malloc failed!\n");
432 sprintf(re, "(%s)", next);
433 } else {
434 /* resize it, adding an extra char for the new '|' separator */
435 re=realloc(expr, sizeof(char)*(strlen(expr)+1+strlen(next)+1));
436 if(!re) die(STATE_UNKNOWN, "realloc failed!\n");
437 /* append it starting at ')' in the old re */
438 sprintf((char*)(re+strlen(re)-1), "|%s)", next);
441 return re;
444 char* construct_cmdline(upgrade_type u, const char *opts){
445 int len=0;
446 const char *opts_ptr=NULL, *aptcmd=NULL;
447 char *cmd=NULL;
449 switch(u){
450 case UPGRADE:
451 if(opts==NULL) opts_ptr=UPGRADE_DEFAULT_OPTS;
452 else opts_ptr=opts;
453 aptcmd="upgrade";
454 break;
455 case DIST_UPGRADE:
456 if(opts==NULL) opts_ptr=UPGRADE_DEFAULT_OPTS;
457 else opts_ptr=opts;
458 aptcmd="dist-upgrade";
459 break;
460 case NO_UPGRADE:
461 if(opts==NULL) opts_ptr=UPDATE_DEFAULT_OPTS;
462 else opts_ptr=opts;
463 aptcmd="update";
464 break;
467 len+=strlen(PATH_TO_APTGET)+1; /* "/usr/bin/apt-get " */
468 len+=strlen(opts_ptr)+1; /* "opts " */
469 len+=strlen(aptcmd)+1; /* "upgrade\0" */
471 cmd=(char*)malloc(sizeof(char)*len);
472 if(cmd==NULL) die(STATE_UNKNOWN, "malloc failed");
473 sprintf(cmd, "%s %s %s", PATH_TO_APTGET, opts_ptr, aptcmd);
474 return cmd;
477 /* informative help message */
478 void
479 print_help (void)
481 print_revision(progname, NP_VERSION);
483 printf(_(COPYRIGHT), copyright, email);
485 printf("%s\n", _("This plugin checks for software updates on systems that use"));
486 printf("%s\n", _("package management systems based on the apt-get(8) command"));
487 printf("%s\n", _("found in Debian GNU/Linux"));
489 printf ("\n\n");
491 print_usage();
493 printf(UT_HELP_VRSN);
494 printf(UT_EXTRA_OPTS);
496 printf(UT_PLUG_TIMEOUT, timeout_interval);
498 printf (" %s\n", "-U, --upgrade=OPTS");
499 printf (" %s\n", _("[Default] Perform an upgrade. If an optional OPTS argument is provided,"));
500 printf (" %s\n", _("apt-get will be run with these command line options instead of the"));
501 printf (" %s", _("default "));
502 printf ("(%s).\n", UPGRADE_DEFAULT_OPTS);
503 printf (" %s\n", _("Note that you may be required to have root privileges if you do not use"));
504 printf (" %s\n", _("the default options."));
505 printf (" %s\n", "-d, --dist-upgrade=OPTS");
506 printf (" %s\n", _("Perform a dist-upgrade instead of normal upgrade. Like with -U OPTS"));
507 printf (" %s\n", _("can be provided to override the default options."));
508 printf (" %s\n", "-n, --no-upgrade");
509 printf (" %s\n", _("Do not run the upgrade. Probably not useful (without -u at least)."));
510 printf (" %s\n", "-l, --list");
511 printf (" %s\n", _("List packages available for upgrade. Packages are printed sorted by"));
512 printf (" %s\n", _("name with security packages listed first."));
513 printf (" %s\n", "-i, --include=REGEXP");
514 printf (" %s\n", _("Include only packages matching REGEXP. Can be specified multiple times"));
515 printf (" %s\n", _("the values will be combined together. Any packages matching this list"));
516 printf (" %s\n", _("cause the plugin to return WARNING status. Others will be ignored."));
517 printf (" %s\n", _("Default is to include all packages."));
518 printf (" %s\n", "-e, --exclude=REGEXP");
519 printf (" %s\n", _("Exclude packages matching REGEXP from the list of packages that would"));
520 printf (" %s\n", _("otherwise be included. Can be specified multiple times; the values"));
521 printf (" %s\n", _("will be combined together. Default is to exclude no packages."));
522 printf (" %s\n", "-c, --critical=REGEXP");
523 printf (" %s\n", _("If the full package information of any of the upgradable packages match"));
524 printf (" %s\n", _("this REGEXP, the plugin will return CRITICAL status. Can be specified"));
525 printf (" %s\n", _("multiple times like above. Default is a regexp matching security"));
526 printf (" %s\n", _("upgrades for Debian and Ubuntu:"));
527 printf (" \t\%s\n", SECURITY_RE);
528 printf (" %s\n", _("Note that the package must first match the include list before its"));
529 printf (" %s\n", _("information is compared against the critical list."));
530 printf (" %s\n", "-o, --only-critical");
531 printf (" %s\n", _("Only warn about upgrades matching the critical list. The total number"));
532 printf (" %s\n", _("of upgrades will be printed, but any non-critical upgrades will not cause"));
533 printf (" %s\n\n", _("the plugin to return WARNING status."));
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."));
542 printf(UT_SUPPORT);
546 /* simple usage heading */
547 void
548 print_usage(void)
550 printf ("%s\n", _("Usage:"));
551 printf ("%s [[-d|-u|-U]opts] [-n] [-l] [-t timeout]\n", progname);