/* ** Copyright (C) 2007 by Carnegie Mellon University. ** ** @OPENSOURCE_HEADER_START@ ** ** Use of the SILK system and related source code is subject to the terms ** of the following licenses: ** ** GNU Public License (GPL) Rights pursuant to Version 2, June 1991 ** Government Purpose License Rights (GPLR) pursuant to DFARS 252.225-7013 ** ** NO WARRANTY ** ** ANY INFORMATION, MATERIALS, SERVICES, INTELLECTUAL PROPERTY OR OTHER ** PROPERTY OR RIGHTS GRANTED OR PROVIDED BY CARNEGIE MELLON UNIVERSITY ** PURSUANT TO THIS LICENSE (HEREINAFTER THE "DELIVERABLES") ARE ON AN ** "AS-IS" BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY ** KIND, EITHER EXPRESS OR IMPLIED AS TO ANY MATTER INCLUDING, BUT NOT ** LIMITED TO, WARRANTY OF FITNESS FOR A PARTICULAR PURPOSE, ** MERCHANTABILITY, INFORMATIONAL CONTENT, NONINFRINGEMENT, OR ERROR-FREE ** OPERATION. CARNEGIE MELLON UNIVERSITY SHALL NOT BE LIABLE FOR INDIRECT, ** SPECIAL OR CONSEQUENTIAL DAMAGES, SUCH AS LOSS OF PROFITS OR INABILITY ** TO USE SAID INTELLECTUAL PROPERTY, UNDER THIS LICENSE, REGARDLESS OF ** WHETHER SUCH PARTY WAS AWARE OF THE POSSIBILITY OF SUCH DAMAGES. ** LICENSEE AGREES THAT IT WILL NOT MAKE ANY WARRANTY ON BEHALF OF ** CARNEGIE MELLON UNIVERSITY, EXPRESS OR IMPLIED, TO ANY PERSON ** CONCERNING THE APPLICATION OF OR THE RESULTS TO BE OBTAINED WITH THE ** DELIVERABLES UNDER THIS LICENSE. ** ** Licensee hereby agrees to defend, indemnify, and hold harmless Carnegie ** Mellon University, its trustees, officers, employees, and agents from ** all claims or demands made against them (and any related losses, ** expenses, or attorney's fees) arising out of, or relating to Licensee's ** and/or its sub licensees' negligent use or willful misuse of or ** negligent conduct or willful misconduct regarding the Software, ** facilities, or other rights or assistance granted by Carnegie Mellon ** University under this License, including, but not limited to, any ** claims of product liability, personal injury, death, damage to ** property, or violation of any laws or regulations. ** ** Carnegie Mellon University Software Engineering Institute authored ** documents are sponsored by the U.S. Department of Defense under ** Contract F19628-00-C-0003. Carnegie Mellon University retains ** copyrights in all material produced under this contract. The U.S. ** Government retains a non-exclusive, royalty-free license to publish or ** reproduce these documents, or allow others to do so, for U.S. ** Government purposes only pursuant to the copyright license under the ** contract clause at 252.227.7013. ** ** @OPENSOURCE_HEADER_END@ */ /* * * rwsetmember.c * * Determine in the IP specified on the command line is a member of * an IPset. */ #include "silk.h" RCSIDENT("$SiLK: rwsetmember.c 7319 2007-05-29 14:00:06Z mthomas $"); #include "iptree.h" #include "utils.h" /* LOCAL DEFINES AND TYPEDEFS */ /* where to write output from --help */ #define USAGE_FH stdout /* LOCAL FUNCTIONS */ static void appUsageLong(void); /* never returns */ static void appTeardown(void); static void appSetup(int argc, char **argv); /* never returns */ static int appOptionsHandler(clientData cData, int opt_index, char *opt_arg); /* LOCAL VARIABLES */ /* The address pattern to be matched */ static char *pattern = NULL; /* If set to true, no output will be produced */ static uint32_t quiet = 0; /* If true, print a count of how many matches */ static uint32_t count = 0; /* index of first option that is not handled by the options handler. */ static int arg_index = 0; /* OPTIONS SETUP */ typedef enum { OPT_COUNT, OPT_QUIET, } appOptionsEnum; static struct option appOptions[] = { {"count", NO_ARG, 0, OPT_COUNT}, {"quiet", NO_ARG, 0, OPT_QUIET}, {0, 0, 0, 0} /* sentinel entry */ }; static const char *appHelp[] = { "Print count of matches along with filenames", "No output, only set exit status", (char *) NULL }; /* FUNCTION DEFINITIONS */ /* * appUsageLong(); * * Print complete usage information to USAGE_FH. Pass this * function to skOptionsSetUsageCallback(); optionsParse() will * call this funciton and then exit the program when the --help * option is given. */ static void appUsageLong(void) { #define USAGE_MSG \ ("[SWITCHES] WILDCARD_IP INPUT_SET [INPUT_SET]...\n" \ "\tDetermine existence of IP address(es) in one or more IPset files.\n" \ "\tBy default, print names of INPUT_SETs that contain WILDCARD_IP.\n") FILE *fh = USAGE_FH; skAppStandardUsage(fh, USAGE_MSG, appOptions, appHelp); } /* * appTeardown() * * Teardown all modules, close all files, and tidy up all * application state. * * This function is idempotent. */ static void appTeardown(void) { static int teardownFlag = 0; if (teardownFlag) { return; } teardownFlag = 1; skAppUnregister(); } /* * appSetup(argc, argv); * * Perform all the setup for this application include setting up * required modules, parsing options, etc. This function should be * passed the same arguments that were passed into main(). * * Returns to the caller if all setup succeeds. If anything fails, * this function will cause the application to exit with a FAILURE * exit status. */ static void appSetup(int argc, char **argv) { /* verify same number of options and help strings */ assert((sizeof(appHelp) / sizeof(char *)) == (sizeof(appOptions) / sizeof(struct option))); /* register the application */ skAppRegister(argv[0]); skOptionsSetUsageCallback(&appUsageLong); /* register the options */ if (optionsRegister(appOptions, (optHandler) appOptionsHandler, NULL)) { skAppPrintErr("unable to register options"); exit(EXIT_FAILURE); } /* parse options */ arg_index = optionsParse(argc, argv); assert(arg_index <= argc); if (arg_index < 0) { /* optionsParse() printed the error */ skAppUsage(); /* never returns */ } pattern = argv[arg_index++]; if (pattern == NULL) { skAppPrintErr("No pattern specified"); skAppUsage(); } /* either need name of set file(s) after options or a set file on stdin */ if ((arg_index == argc) && (FILEIsATty(stdin))) { skAppPrintErr("No files on the command line and" " stdin is connected to a terminal"); skAppUsage(); } if (atexit(appTeardown) < 0) { skAppPrintErr("unable to register appTeardown() with atexit()"); appTeardown(); exit(EXIT_FAILURE); } return; /* OK */ } /* * status = appOptionsHandler(cData, opt_index, opt_arg); * * This function is passed to optionsRegister(); it will be called * by optionsParse() for each user-specified switch that the * application has registered; it should handle the switch as * required---typically by setting global variables---and return 1 * if the switch processing failed or 0 if it succeeded. Returning * a non-zero from from the handler causes optionsParse() to return * a negative value. * * The clientData in 'cData' is typically ignored; 'opt_index' is * the index number that was specified as the last value for each * struct option in appOptions[]; 'opt_arg' is the user's argument * to the switch for options that have a REQUIRED_ARG or an * OPTIONAL_ARG. */ static int appOptionsHandler( clientData UNUSED(cData), int opt_index, char UNUSED(*opt_arg)) { switch ((appOptionsEnum) opt_index) { case OPT_COUNT: count = 1; break; case OPT_QUIET: quiet = 1; break; } return 0; /* OK */ } /* * filename = appNextInput(argc, argv); * * Return the name of the next input file from the command line or * the standard input if no files were given on the command line. */ static const char *appNextInput(int argc, char **argv) { static int initialized = 0; const char *fname = NULL; if (arg_index < argc) { /* get current file and prepare to get next */ fname = argv[arg_index]; ++arg_index; } else { if (initialized) { /* no more input */ return NULL; } /* input is from stdin */ fname = "stdin"; } initialized = 1; return fname; } int main(int argc, char **argv) { const char *filename = NULL; skOctetMap_t octet_map; skOctetMapIterator_t map_iter; skIPTree_t *input_set = NULL; uint32_t ip; uint64_t matches = 0; int rv = 1; appSetup(argc, argv); /* never returns on error */ /* Build an IP set from the pattern argument */ if (skStringParseWildcardIP(&octet_map, pattern)) { skAppPrintErr("Error parsing IP pattern %s", pattern); skAppUsage(); } /* Iterate over the set files */ while ((filename = appNextInput(argc, argv)) != NULL) { matches = 0; /* Load the input set */ if (0 != skIPTreeLoad(filename, &input_set)) { skAppPrintErr("Error reading IPset from file '%s'", filename); return 2; } skOctetMapIteratorInitialize(&map_iter, &octet_map); while (skOctetMapIteratorNext(&ip, &map_iter) == SK_ITERATOR_OK) { if (skIPTreeCheckAddress(ip, input_set)) { rv = 0; if (quiet) { /* short-circuit if the user wants no output */ goto done; } matches++; if (! count) { /* no need to continue if we're just printing filenames */ break; } } } skIPTreeDelete(&input_set); input_set = NULL; if (count) { printf(("%s:%" PRIu64 "\n"), filename, matches); } else if (matches) { printf("%s\n", filename); } } done: /* done */ if (input_set) { skIPTreeDelete(&input_set); } appTeardown(); return rv; } /* ** Local variables: ** mode:c ** indent-tabs-mode:nil ** c-basic-offset:4 ** End: */