Code

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