Back to index

nagios-plugins  1.4.16
check_apt.c
Go to the documentation of this file.
00001 /*****************************************************************************
00002 * 
00003 * Nagios check_apt plugin
00004 * 
00005 * License: GPL
00006 * Copyright (c) 2006-2008 Nagios Plugins Development Team
00007 * 
00008 * Original author: Sean Finney
00009 * 
00010 * Description:
00011 * 
00012 * This file contains the check_apt plugin
00013 * 
00014 * Check for available updates in apt package management systems
00015 * 
00016 * 
00017 * This program is free software: you can redistribute it and/or modify
00018 * it under the terms of the GNU General Public License as published by
00019 * the Free Software Foundation, either version 3 of the License, or
00020 * (at your option) any later version.
00021 * 
00022 * This program is distributed in the hope that it will be useful,
00023 * but WITHOUT ANY WARRANTY; without even the implied warranty of
00024 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00025 * GNU General Public License for more details.
00026 * 
00027 * You should have received a copy of the GNU General Public License
00028 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
00029 * 
00030 *****************************************************************************/
00031 
00032 const char *progname = "check_apt";
00033 const char *copyright = "2006-2008";
00034 const char *email = "nagiosplug-devel@lists.sourceforge.net";
00035 
00036 #include "common.h"
00037 #include "runcmd.h"
00038 #include "utils.h"
00039 #include "regex.h"
00040 
00041 /* some constants */
00042 typedef enum { UPGRADE, DIST_UPGRADE, NO_UPGRADE } upgrade_type;
00043 
00044 /* the default opts can be overridden via the cmdline */
00045 #define UPGRADE_DEFAULT_OPTS "-o 'Debug::NoLocking=true' -s -qq"
00046 #define UPDATE_DEFAULT_OPTS "-q"
00047 /* until i commit the configure.in patch which gets this, i'll define
00048  * it here as well */
00049 #ifndef PATH_TO_APTGET
00050 # define PATH_TO_APTGET "/usr/bin/apt-get"
00051 #endif /* PATH_TO_APTGET */
00052 /* the RE that catches security updates */
00053 #define SECURITY_RE "^[^\\(]*\\([^ ]* (Debian-Security:|Ubuntu:[^/]*/[^-]*-security)"
00054 
00055 /* some standard functions */
00056 int process_arguments(int, char **);
00057 void print_help(void);
00058 void print_usage(void);
00059 
00060 /* construct the appropriate apt-get cmdline */
00061 char* construct_cmdline(upgrade_type u, const char *opts);
00062 /* run an apt-get update */
00063 int run_update(void);
00064 /* run an apt-get upgrade */
00065 int run_upgrade(int *pkgcount, int *secpkgcount);
00066 /* add another clause to a regexp */
00067 char* add_to_regexp(char *expr, const char *next);
00068 
00069 /* configuration variables */
00070 static int verbose = 0;      /* -v */
00071 static int do_update = 0;    /* whether to call apt-get update */
00072 static upgrade_type upgrade = UPGRADE; /* which type of upgrade to do */
00073 static char *upgrade_opts = NULL; /* options to override defaults for upgrade */
00074 static char *update_opts = NULL; /* options to override defaults for update */
00075 static char *do_include = NULL;  /* regexp to only include certain packages */
00076 static char *do_exclude = NULL;  /* regexp to only exclude certain packages */
00077 static char *do_critical = NULL;  /* regexp specifying critical packages */
00078 
00079 /* other global variables */
00080 static int stderr_warning = 0;   /* if a cmd issued output on stderr */
00081 static int exec_warning = 0;     /* if a cmd exited non-zero */
00082 
00083 int main (int argc, char **argv) {
00084        int result=STATE_UNKNOWN, packages_available=0, sec_count=0;
00085 
00086        /* Parse extra opts if any */
00087        argv=np_extra_opts(&argc, argv, progname);
00088 
00089        if (process_arguments(argc, argv) == ERROR)
00090               usage_va(_("Could not parse arguments"));
00091 
00092        /* Set signal handling and alarm timeout */
00093        if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
00094               usage_va(_("Cannot catch SIGALRM"));
00095        }
00096 
00097        /* handle timeouts gracefully... */
00098        alarm (timeout_interval);
00099 
00100        /* if they want to run apt-get update first... */
00101        if(do_update) result = run_update();
00102 
00103        /* apt-get upgrade */
00104        result = max_state(result, run_upgrade(&packages_available, &sec_count));
00105 
00106        if(sec_count > 0){
00107               result = max_state(result, STATE_CRITICAL);
00108        } else if(packages_available > 0){
00109               result = max_state(result, STATE_WARNING);
00110        } else {
00111               result = max_state(result, STATE_OK);
00112        }
00113 
00114        printf(_("APT %s: %d packages available for %s (%d critical updates). %s%s%s%s\n"),
00115               state_text(result),
00116               packages_available,
00117               (upgrade==DIST_UPGRADE)?"dist-upgrade":"upgrade",
00118                  sec_count,
00119               (stderr_warning)?" warnings detected":"",
00120               (stderr_warning && exec_warning)?",":"",
00121               (exec_warning)?" errors detected":"",
00122               (stderr_warning||exec_warning)?". run with -v for information.":""
00123               );
00124 
00125        return result;
00126 }
00127 
00128 /* process command-line arguments */
00129 int process_arguments (int argc, char **argv) {
00130        int c;
00131 
00132        static struct option longopts[] = {
00133               {"version", no_argument, 0, 'V'},
00134               {"help", no_argument, 0, 'h'},
00135               {"verbose", no_argument, 0, 'v'},
00136               {"timeout", required_argument, 0, 't'},
00137               {"update", optional_argument, 0, 'u'},
00138               {"upgrade", optional_argument, 0, 'U'},
00139               {"no-upgrade", no_argument, 0, 'n'},
00140               {"dist-upgrade", optional_argument, 0, 'd'},
00141               {"include", required_argument, 0, 'i'},
00142               {"exclude", required_argument, 0, 'e'},
00143               {"critical", required_argument, 0, 'c'},
00144               {0, 0, 0, 0}
00145        };
00146 
00147        while(1) {
00148               c = getopt_long(argc, argv, "hVvt:u::U::d::ni:e:c:", longopts, NULL);
00149 
00150               if(c == -1 || c == EOF || c == 1) break;
00151 
00152               switch(c) {
00153               case 'h':
00154                      print_help();
00155                      exit(STATE_OK);
00156               case 'V':
00157                      print_revision(progname, NP_VERSION);
00158                      exit(STATE_OK);
00159               case 'v':
00160                      verbose++;
00161                      break;
00162               case 't':
00163                      timeout_interval=atoi(optarg);
00164                      break;
00165               case 'd':
00166                      upgrade=DIST_UPGRADE;
00167                      if(optarg!=NULL){
00168                             upgrade_opts=strdup(optarg);
00169                             if(upgrade_opts==NULL) die(STATE_UNKNOWN, "strdup failed");
00170                      }
00171                      break;
00172               case 'U':
00173                      upgrade=UPGRADE;
00174                      if(optarg!=NULL){
00175                             upgrade_opts=strdup(optarg);
00176                             if(upgrade_opts==NULL) die(STATE_UNKNOWN, "strdup failed");
00177                      }
00178                      break;
00179               case 'n':
00180                      upgrade=NO_UPGRADE;
00181                      break;
00182               case 'u':
00183                      do_update=1;
00184                      if(optarg!=NULL){
00185                             update_opts=strdup(optarg);
00186                             if(update_opts==NULL) die(STATE_UNKNOWN, "strdup failed");
00187                      }
00188                      break;
00189               case 'i':
00190                      do_include=add_to_regexp(do_include, optarg);
00191                      break;
00192               case 'e':
00193                      do_exclude=add_to_regexp(do_exclude, optarg);
00194                      break;
00195               case 'c':
00196                      do_critical=add_to_regexp(do_critical, optarg);
00197                      break;
00198               default:
00199                      /* print short usage statement if args not parsable */
00200                      usage5();
00201               }
00202        }
00203 
00204        return OK;
00205 }
00206 
00207 
00208 /* run an apt-get upgrade */
00209 int run_upgrade(int *pkgcount, int *secpkgcount){
00210        int i=0, result=STATE_UNKNOWN, regres=0, pc=0, spc=0;
00211        struct output chld_out, chld_err;
00212        regex_t ireg, ereg, sreg;
00213        char *cmdline=NULL, rerrbuf[64];
00214        const char *include_ptr=NULL, *crit_ptr=NULL;
00215 
00216        if(upgrade==NO_UPGRADE) return STATE_OK;
00217 
00218        /* compile the regexps */
00219        if(do_include!=NULL) include_ptr=do_include;
00220        else include_ptr="^Inst";
00221        if(do_critical!=NULL) crit_ptr=do_critical;
00222        else crit_ptr=SECURITY_RE;
00223 
00224        regres=regcomp(&ireg, include_ptr, REG_EXTENDED);
00225        if(regres!=0) {
00226               regerror(regres, &ireg, rerrbuf, 64);
00227               die(STATE_UNKNOWN, _("%s: Error compiling regexp: %s"), progname, rerrbuf);
00228        }
00229 
00230        if(do_exclude!=NULL){
00231               regres=regcomp(&ereg, do_exclude, REG_EXTENDED);
00232               if(regres!=0) {
00233                      regerror(regres, &ereg, rerrbuf, 64);
00234                      die(STATE_UNKNOWN, _("%s: Error compiling regexp: %s"),
00235                          progname, rerrbuf);
00236               }
00237        }
00238        regres=regcomp(&sreg, crit_ptr, REG_EXTENDED);
00239        if(regres!=0) {
00240               regerror(regres, &ereg, rerrbuf, 64);
00241               die(STATE_UNKNOWN, _("%s: Error compiling regexp: %s"),
00242                   progname, rerrbuf);
00243        }
00244 
00245        cmdline=construct_cmdline(upgrade, upgrade_opts);
00246        /* run the upgrade */
00247        result = np_runcmd(cmdline, &chld_out, &chld_err, 0);
00248        /* apt-get upgrade only changes exit status if there is an
00249         * internal error when run in dry-run mode.  therefore we will
00250         * treat such an error as UNKNOWN */
00251        if(result != 0){
00252               exec_warning=1;
00253               result = STATE_UNKNOWN;
00254               fprintf(stderr, _("'%s' exited with non-zero status.\n"),
00255                   cmdline);
00256        }
00257 
00258        /* parse the output, which should only consist of lines like
00259         *
00260         * Inst package ....
00261         * Conf package ....
00262         *
00263         * so we'll filter based on "Inst" for the time being.  later
00264         * we may need to switch to the --print-uris output format,
00265         * in which case the logic here will slightly change.
00266         */
00267        for(i = 0; i < chld_out.lines; i++) {
00268               if(verbose){
00269                      printf("%s\n", chld_out.line[i]);
00270               }
00271               /* if it is a package we care about */
00272               if(regexec(&ireg, chld_out.line[i], 0, NULL, 0)==0){
00273                      /* if we're not excluding, or it's not in the
00274                       * list of stuff to exclude */
00275                      if(do_exclude==NULL ||
00276                         regexec(&ereg, chld_out.line[i], 0, NULL, 0)!=0){
00277                             pc++;
00278                             if(regexec(&sreg, chld_out.line[i], 0, NULL, 0)==0){
00279                                    spc++;
00280                                    if(verbose) printf("*");
00281                             }
00282                             if(verbose){
00283                                    printf("*%s\n", chld_out.line[i]);
00284                             }
00285                      }
00286               }
00287        }
00288        *pkgcount=pc;
00289        *secpkgcount=spc;
00290 
00291        /* If we get anything on stderr, at least set warning */
00292        if(chld_err.buflen){
00293               stderr_warning=1;
00294               result = max_state(result, STATE_WARNING);
00295               if(verbose){
00296                      for(i = 0; i < chld_err.lines; i++) {
00297                             fprintf(stderr, "%s\n", chld_err.line[i]);
00298                      }
00299               }
00300        }
00301        regfree(&ireg);
00302        regfree(&sreg);
00303        if(do_exclude!=NULL) regfree(&ereg);
00304        free(cmdline);
00305        return result;
00306 }
00307 
00308 /* run an apt-get update (needs root) */
00309 int run_update(void){
00310        int i=0, result=STATE_UNKNOWN;
00311        struct output chld_out, chld_err;
00312        char *cmdline;
00313 
00314        /* run the upgrade */
00315        cmdline = construct_cmdline(NO_UPGRADE, update_opts);
00316        result = np_runcmd(cmdline, &chld_out, &chld_err, 0);
00317        /* apt-get update changes exit status if it can't fetch packages.
00318         * since we were explicitly asked to do so, this is treated as
00319         * a critical error. */
00320        if(result != 0){
00321               exec_warning=1;
00322               result = STATE_CRITICAL;
00323               fprintf(stderr, _("'%s' exited with non-zero status.\n"),
00324                       cmdline);
00325        }
00326 
00327        if(verbose){
00328               for(i = 0; i < chld_out.lines; i++) {
00329                      printf("%s\n", chld_out.line[i]);
00330               }
00331        }
00332 
00333        /* If we get anything on stderr, at least set warning */
00334        if(chld_err.buflen){
00335               stderr_warning=1;
00336               result = max_state(result, STATE_WARNING);
00337               if(verbose){
00338                      for(i = 0; i < chld_err.lines; i++) {
00339                             fprintf(stderr, "%s\n", chld_err.line[i]);
00340                      }
00341               }
00342        }
00343        free(cmdline);
00344        return result;
00345 }
00346 
00347 char* add_to_regexp(char *expr, const char *next){
00348        char *re=NULL;
00349 
00350        if(expr==NULL){
00351               re=malloc(sizeof(char)*(strlen("^Inst () ")+strlen(next)+1));
00352               if(!re) die(STATE_UNKNOWN, "malloc failed!\n");
00353               sprintf(re, "^Inst (%s) ", next);
00354        } else {
00355               /* resize it, adding an extra char for the new '|' separator */
00356               re=realloc(expr, sizeof(char)*strlen(expr)+1+strlen(next)+1);
00357               if(!re) die(STATE_UNKNOWN, "realloc failed!\n");
00358               /* append it starting at ')' in the old re */
00359               sprintf((char*)(re+strlen(re)-2), "|%s) ", next);
00360        }
00361 
00362        return re;
00363 }
00364 
00365 char* construct_cmdline(upgrade_type u, const char *opts){
00366        int len=0;
00367        const char *opts_ptr=NULL, *aptcmd=NULL;
00368        char *cmd=NULL;
00369 
00370        switch(u){
00371        case UPGRADE:
00372               if(opts==NULL) opts_ptr=UPGRADE_DEFAULT_OPTS;
00373               else opts_ptr=opts;
00374               aptcmd="upgrade";
00375               break;
00376        case DIST_UPGRADE:
00377               if(opts==NULL) opts_ptr=UPGRADE_DEFAULT_OPTS;
00378               else opts_ptr=opts;
00379               aptcmd="dist-upgrade";
00380               break;
00381        case NO_UPGRADE:
00382               if(opts==NULL) opts_ptr=UPDATE_DEFAULT_OPTS;
00383               else opts_ptr=opts;
00384               aptcmd="update";
00385               break;
00386        }
00387 
00388        len+=strlen(PATH_TO_APTGET)+1; /* "/usr/bin/apt-get " */
00389        len+=strlen(opts_ptr)+1;       /* "opts " */
00390        len+=strlen(aptcmd)+1;         /* "upgrade\0" */
00391 
00392        cmd=(char*)malloc(sizeof(char)*len);
00393        if(cmd==NULL) die(STATE_UNKNOWN, "malloc failed");
00394        sprintf(cmd, "%s %s %s", PATH_TO_APTGET, opts_ptr, aptcmd);
00395        return cmd;
00396 }
00397 
00398 /* informative help message */
00399 void
00400 print_help (void)
00401 {
00402   print_revision(progname, NP_VERSION);
00403 
00404   printf(_(COPYRIGHT), copyright, email);
00405 
00406   printf("%s\n", _("This plugin checks for software updates on systems that use"));
00407   printf("%s\n", _("package management systems based on the apt-get(8) command"));
00408   printf("%s\n", _("found in Debian GNU/Linux"));
00409 
00410   printf ("\n\n");
00411 
00412   print_usage();
00413 
00414   printf(UT_HELP_VRSN);
00415   printf(UT_EXTRA_OPTS);
00416 
00417   printf(UT_TIMEOUT, timeout_interval);
00418 
00419   printf (" %s\n", "-U, --upgrade=OPTS");
00420   printf ("    %s\n", _("[Default] Perform an upgrade.  If an optional OPTS argument is provided,"));
00421   printf ("    %s\n", _("apt-get will be run with these command line options instead of the"));
00422   printf ("    %s", _("default "));
00423   printf ("(%s).\n", UPGRADE_DEFAULT_OPTS);
00424   printf ("    %s\n", _("Note that you may be required to have root privileges if you do not use"));
00425   printf ("    %s\n", _("the default options."));
00426   printf (" %s\n", "-d, --dist-upgrade=OPTS");
00427   printf ("    %s\n", _("Perform a dist-upgrade instead of normal upgrade. Like with -U OPTS"));
00428   printf ("    %s\n", _("can be provided to override the default options."));
00429   printf (" %s\n", " -n, --no-upgrade");
00430   printf ("    %s\n", _("Do not run the upgrade.  Probably not useful (without -u at least)."));
00431   printf (" %s\n", "-i, --include=REGEXP");
00432   printf ("    %s\n", _("Include only packages matching REGEXP.  Can be specified multiple times"));
00433   printf ("    %s\n", _("the values will be combined together.  Any patches matching this list"));
00434   printf ("    %s\n", _("cause the plugin to return WARNING status.  Others will be ignored."));
00435   printf ("    %s\n", _("Default is to include all packages."));
00436   printf (" %s\n", "-e, --exclude=REGEXP");
00437   printf ("    %s\n", _("Exclude packages matching REGEXP from the list of packages that would"));
00438   printf ("    %s\n", _("otherwise be included.  Can be specified multiple times; the values"));
00439   printf ("    %s\n", _("will be combined together.  Default is to exclude no packages."));
00440   printf (" %s\n", "-c, --critical=REGEXP");
00441   printf ("    %s\n", _("If the full package information of any of the upgradable packages match"));
00442   printf ("    %s\n", _("this REGEXP, the plugin will return CRITICAL status.  Can be specified"));
00443   printf ("    %s\n", _("multiple times like above.  Default is a regexp matching security"));
00444   printf ("    %s\n", _("upgrades for Debian and Ubuntu:"));
00445   printf ("    \t\%s\n", SECURITY_RE);
00446   printf ("    %s\n", _("Note that the package must first match the include list before its"));
00447   printf ("    %s\n\n", _("information is compared against the critical list."));
00448 
00449   printf ("%s\n\n", _("The following options require root privileges and should be used with care:"));
00450   printf (" %s\n", "-u, --update=OPTS");
00451   printf ("    %s\n", _("First perform an 'apt-get update'.  An optional OPTS parameter overrides"));
00452   printf ("    %s\n", _("the default options.  Note: you may also need to adjust the global"));
00453   printf ("    %s\n", _("timeout (with -t) to prevent the plugin from timing out if apt-get"));
00454   printf ("    %s\n", _("upgrade is expected to take longer than the default timeout."));
00455 
00456   printf(UT_SUPPORT);
00457 }
00458 
00459 
00460 /* simple usage heading */
00461 void
00462 print_usage(void)
00463 {
00464   printf ("%s\n", _("Usage:"));
00465   printf ("%s [[-d|-u|-U]opts] [-n] [-t timeout]\n", progname);
00466 }