dca_interface  6.3.4
ipr_samples/iprsample/main.cpp
1 /* IBM Source Code */
2 /* (C) Copyright IBM Corp. 2009, 2012 */
3 /* Licensed Materials - Property of IBM */
4 /* US Government Users Restricted Rights - Use duplication or disclosure restricted by GSA Schedule Contract with IBM Corp. */
5 
35 #include <string>
36 #include <vector>
37 #include <iostream>
38 #include <fstream>
39 #include <ctime>
40 
41 #include "dca/dca_base.h"
43 #include "dca/dca_callbacks.h"
44 
45 #ifdef WIN32
46 # include <winsock2.h>
47 #endif
48 
49 using namespace dca;
50 using namespace dca_ipr;
51 
52 const std::string S_ToolName = "iprsample";
53 const std::string S_ToolVersion = "1.3";
54 
59 const std::string S_UsageString =
60  "<dca-redist-folder> <ticket> <product> <input-file>\n"
61  " dca-redist-folder - the folder where the DCA is installed\n"
62  " ticket - a valid ticket\n"
63  " product - the product associated with your ticket\n"
64  " input-file - a file with sample IP addresses\n\n"
65  ;
66 
71 #ifdef WIN32
72 # define DCA_BINDIR "bin/Win32"
73 #else
74 # define DCA_BINDIR "bin/linux"
75 #endif
76 
81 #define DCA_INITDIR "init"
82 
86 #define DCA_LOGDIR "./logs"
87 
98 static void SetupInitData( const std::string& strRedistFolder,
99  InitData& aInitData )
100 {
101  aInitData.binDir = strRedistFolder + DCA_BINDIR;
102  aInitData.initDir = strRedistFolder + DCA_INITDIR;
103  aInitData.logDir = DCA_LOGDIR;
104 }
105 
117 static bool StartupLibraries()
118 {
119 #ifdef WIN32
120  // Windows needs an extra socket-startup for this process to work
121  // correctly with e.g. IP(v6) input IP addresses
122  WORD wVersionRequested = MAKEWORD( 2, 2 );
123  WSADATA wsaData;
124  int err = WSAStartup( wVersionRequested, &wsaData );
125  if ( err != 0 ) {
126  std::cout << "Error on WSAStartup (" << err << ") occured, aborting" <<
127  std::endl;
128  return false;
129  }
130 #endif
131 
132  // init the 3rd party libraries
133  InitCUrl();
135  return true;
136 }
137 
144 static void ShutdownLibraries()
145 {
146  // deinit the 3rd party libraries
148  DeinitCUrl();
149 
150 #ifdef WIN32
151  // Cleanup Windows sockets for this process
152  WSACleanup();
153 #endif
154 }
155 
164 static void SetupLicense( const std::string& strTicket,
165  const std::string& strProduct,
166  LicenseData& aLicenseData )
167 {
168  aLicenseData.ticket = strTicket;
169  aLicenseData.product = strProduct;
170 }
171 
180 static void SetupConnectionData( DbConnectionData& aDbConnectionData )
181 {
182  aDbConnectionData.useLocalDatabase = true;
183  aDbConnectionData.dbType = DBT_Ipr;
184 }
185 
193 static void PrintDbConnectionInfo( const DbConnection& aDbConnection )
194 {
195  DatabaseInformation databaseInformation =
196  aDbConnection.getDatabaseInformation();
197 
198  std::cout << "IPR Database Version: " << databaseInformation.versionString
199  << " as of " << databaseInformation.creationDateUTC << std::endl;
200 }
201 
208 static void PrintLicenseInfo( const License& aLicense )
209 {
210  const time_t expirationDate = aLicense.getExpirationDate();
211  struct tm *expirationTime = localtime( &expirationDate );
212 
213  std::cout << "License Info:" << std::endl;
214  std::cout << " DCA is " << ( aLicense.isLicensed() ? "licensed." :
215  "not licensed." ) << std::endl;
216  std::cout << " MaxUsers:" << aLicense.getMaxUsers() <<
217  std::endl;
218  std::cout << " MaxSessions:" << aLicense.getMaxSessions() <<
219  std::endl;
220  std::cout << " Ticket:" << aLicense.getTicket() <<
221  std::endl;
222  std::cout << " Session:" << aLicense.getSession() <<
223  std::endl;
224  std::cout << " Last Message:" << aLicense.getLastMessage() <<
225  std::endl;
226  std::cout << " Expiration Date:" << asctime( expirationTime ) <<
227  std::endl;
228 }
229 
234 static void PrintToolHeader()
235 {
236  std::cout << "IBM DCA Sample: " << S_ToolName << " (" << S_ToolVersion <<
237  ")" << std::endl;
238 }
239 
246 static void PrintUsage( const char *pSampleName )
247 {
248  std::cout << pSampleName << " usage:" << std::endl;
249  std::cout << S_UsageString << std::endl;
250 }
251 
261 void PrintResult( const IprClassificationResult& aIprClassificationResult,
262  const IprCategories& aIprCategories,
263  const IprEnums& aIprEnums,
264  const std::string& strIndent = "" )
265 {
266  // each result item contains of a category id and a value related to the
267  // category
268  DCA_CATEGORY_ID_TYPE myCatId = aIprClassificationResult.categoryId;
269  int myValue = aIprClassificationResult.value;
270 
271  // retrieve the category object to print out its name
272  IprCategory myIprCategory = aIprCategories.byId( myCatId );
273 
274  std::cout << strIndent << "IprCategory '" << myIprCategory.name() <<
275  "' (id=" << myCatId << ")" << std::endl;
276 
277  // if the matched category contains one or more related IprEnum objects,
278  // print out the matched one
279  const DCA_SIZE_TYPE numOfEnums = myIprCategory.enumsSize();
280  if( numOfEnums > 0 ) {
281  // the retrieved value points to a unique IprEnum object id
282  int enumId = myIprCategory.enumByValue( myValue );
283  // retrieve the object with the enumId
284  const IprEnum myIprEnum = aIprEnums.byId( enumId );
285  std::cout << strIndent << "\t IprEnum '" << myIprEnum.name() << "' (id=" <<
286  enumId << ")" << std::endl;
287  }
288  else {
289  // no Enum object retrieved print out the value
290  std::cout << strIndent << "\tValue " << myValue << std::endl;
291  }
292 }
293 
301 void PrintResults( const IprClassificationResults& aIprClassificationResults,
302  const IprCategoriesInfo& aIprCategoriesInfo )
303 {
304  if( !aIprClassificationResults.isCategorized() ) {
305  std::cout << "Results: None" << std::endl;
306  return;
307  }
308 
309  const DCA_SIZE_TYPE numOfResults = aIprClassificationResults.size();
310 
311  std::cout << "Results (" << numOfResults << ") categories" << std::endl;
312 
313  const IprCategories myIprCategories = aIprCategoriesInfo.getCategories();
314  const IprEnums myIprEnums = aIprCategoriesInfo.getEnums();
315 
316  for( DCA_INDEX_TYPE i = 0; i < numOfResults; ++i ) {
317  const IprClassificationResult myIprClassificationResult = aIprClassificationResults[ i ];
318  PrintResult( myIprClassificationResult, myIprCategories, myIprEnums, "\t" );
319  }
320 }
321 
330 void DoCallIprClassification( const std::vector<std::string>& aIpStrings,
331  const IprClassifier& aIprClassifier,
332  const IprCategoriesInfo& aIprCategoriesInfo )
333 {
334  std::vector< std::string >::const_iterator I = aIpStrings.begin();
335  std::vector< std::string >::const_iterator IEnd = aIpStrings.end();
336 
337  IprClassificationResults myIprClassificationResults;
338  FunctionResult myFR;
339 
340  for( ; I != IEnd; ++I ) {
341  const std::string& strIp = *I;
342 
343  std::cout << "IP Classification ('" << strIp << "')..." << std::endl;
344 
345  const Ip myIp( strIp.c_str(), strIp.length() );
346  myFR = aIprClassifier.classify( myIp, myIprClassificationResults );
347 
348  if( !myFR ) {
349  std::cout << "Error: rc=" << myFR.getReturnCode() <<
350  ", description=" << myFR.getDescription() << std::endl;
351  }
352  else PrintResults( myIprClassificationResults, aIprCategoriesInfo );
353  }
354 }
355 
364 void TestIprClassification( const IprClassifier& aIprClassifier,
365  const IprCategoriesInfo& aIprCategoriesInfo,
366  const std::string& strFileName )
367 {
368  std::ifstream fstream( strFileName.c_str(), std::ios::in );
369  if ( !fstream.is_open() ) {
370  std::cout << "Error: File '" << strFileName << "' could not be opened!" << std::endl;
371  return;
372  }
373 
374  std::string strLine;
375  std::vector< std::string > myIpStrings;
376 
377  while( std::getline( fstream, strLine ) ) {
378  if( strLine.empty() )
379  continue;
380 
381  // delete all \r\n at the end of the line
382  while( strLine[strLine.length()-1] == '\r' ||
383  strLine[strLine.length()-1] == '\n' )
384  strLine.erase( strLine.length() - 1 );
385 
386  if( strLine.empty() )
387  continue;
388 
389  if( strLine[0] == '#' ) // allow comment lines started with a # at first char
390  continue;
391 
392  // add line to myIpStrings
393  myIpStrings.push_back( strLine );
394  }
395 
396  fstream.close();
397 
398  if( !myIpStrings.empty() )
399  DoCallIprClassification( myIpStrings, aIprClassifier, aIprCategoriesInfo );
400  else
401  std::cout << "Could not read any IP address from file!" << std::endl;
402 }
403 
412 int main( int argc, char *argv[] )
413 {
414  PrintToolHeader();
415 
416  int rc = 5;
417 
418  try {
419  if( argc < 5 ) {
420  PrintUsage( argv[0] );
421  return 5;
422  }
423 
424  std::string strRedistFolder = argv[ 1 ];
425  const std::string strTicket = argv[ 2 ];
426  const std::string strProduct = argv[ 3 ];
427  const std::string strFileName = argv[ 4 ];
428 
429  if( strRedistFolder.empty() ||
430  strTicket.empty() ||
431  strProduct.empty() ||
432  strFileName.empty() )
433  {
434  PrintUsage( argv[0] );
435  return 5;
436  }
437 
438  // check for trailing fileslash - and add if necessary
439  const char c = strRedistFolder[ strRedistFolder.length() - 1 ];
440  if( c != '/' && c != '\\' )
441  strRedistFolder += "/";
442 
443  // Initialize socket on Windows and 3rd party libraries
444  if( !StartupLibraries() )
445  return 5;
446 
447  {
448  // setup DCA directories
449  InitData myInitData;
450  SetupInitData( strRedistFolder, myInitData );
451 
452  // instantiate DCA API
453  DcaInstance myDca;
454  myDca = DcaInstance::create( myInitData );
455 
456  // setup license data
457  LicenseData myLicenseData;
458  SetupLicense( strTicket, strProduct, myLicenseData );
459  const License myLicense = myDca.createLicense( myLicenseData );
460 
461  PrintLicenseInfo( myLicense );
462 
463  if( myLicense.isLicensed( IprClassification::ID ) ) {
464  // initialize the IPR Classification module
465  const IprClassification myIprClassification =
466  IprClassification::create( myDca, myLicense );
467 
468  DbConnectionData myDbConnectionData;
469  SetupConnectionData( myDbConnectionData );
470 
471  // A DbConnection data to a local database must exist to use
472  // IprClassification
473  const DbConnection myDbConnection =
474  myDca.createDbConnection( myLicense, myDbConnectionData );
475  PrintDbConnectionInfo( myDbConnection );
476 
477  // create a IprClassifier to use in the TestIprClassification()
478  // function
479  const IprClassifier myClassifier =
480  myIprClassification.createClassifier( myDbConnection );
481 
482  // create a categories info for printing out the result
483  // categories and values per input data
484  const IprCategoriesInfo myCategoriesInfo =
485  myIprClassification.getCategoriesInfo();
486 
487  // call classification routine
488  TestIprClassification( myClassifier, myCategoriesInfo,
489  strFileName );
490 
491  rc = 0;
492  }
493  }
494  }
495  catch( const ExDca& ex ) {
496  std::cerr << "DCA Exception occured. Details: " << ex.getDescription()
497  << " (" << ex.getReturnCode() << ")." << std::endl;
498  rc = 10;
499  }
500  catch( const std::exception& s ) {
501  std::cerr << "std::exception occured. Details: " << s.what() << "." <<
502  std::endl;
503  rc = 10;
504  }
505  catch(...) {
506  std::cerr << "Unknown exception caught." << std::endl;
507  rc = 10;
508  }
509 
510  // deinit the 3rd party libraries
511  ShutdownLibraries();
512 
513  return rc;
514 }
DCA_ENUM_ID_TYPE enumByValue(int value) const
Returns the id of an enum item associated with the current IprCategory.
DCA_SIZE_TYPE enumsSize() const
Returns the count of IprEnum items associated with current IprCategory.
Is used to create a License object. A license first must be created with DcaInstance::createLicense t...
Definition: base_classes.h:547
Definition of the Ip class.
Definition: ipr_ipdata.h:33
Exception class used in the DCA.
Definition: base_classes.h:237
void InitCUrl()
Initializes libcurl. Do not use any DCA function before initializing libcurl.
std::string initDir
the directory in which the DCA init files are stored
Definition: base_classes.h:266
int getMaxSessions() const
Returns the maximum allowed sessions associated with your ticket/license.
time_t getExpirationDate() const
Returns the expiration date of the license in UTC.
std::string getDescription() const
Returns a description of the error.
IprEnums getEnums() const
Returns the contained IprEnums.
DatabaseInformation getDatabaseInformation() const
Returns information about the underlying database.
Contains information about underlying database.
Definition: base_classes.h:834
DCA_RESULT_TYPE getReturnCode() const
Returns the last error code (if any).
static void SetupInitData(const std::string &redist_folder, InitData &initData)
Sets up the given initData by substituting the given redist_folder with DCA subdirectories.
Defintion of the IprClassifier class.
std::string creationDateUTC
Definition: base_classes.h:842
Container class for all IPR enumeration objects.
std::string binDir
the directory in which the DCA binary (*.dca) files are stored
Definition: base_classes.h:265
This header includes initialization/deinitialization support functions for the 3rd party libraries us...
DCA_CATEGORY_ID_TYPE categoryId
A IPR category id.
void SetOpenSslCallbacks()
Initializes the required callbacks for OpenSSL when using HTTPS or SSL connections in a multi-threade...
Stores the connection data for a database.
Definition: base_classes.h:815
void UnsetOpenSslCallbacks()
Unsets the openssl callbacks. Do not call any DCA function after you have called this function.
IprCategories getCategories() const
Returns the contained IprCategories.
IprEnum byId(DCA_ENUM_ID_TYPE id) const
Returns the IprEnum with the given id.
int getMaxUsers() const
Returns the maximum allowed users associated with your ticket/license.
void DeinitCUrl()
Deinitializes libcurl. Do not call any DCA function after you have called this function.
const DbType DBT_Ipr
Used to specify an IP Classification database when creating a dca::DbConnection instance.
Database connection class for a local or remote database.
Definition: base_classes.h:859
Package header file for the IPR (IP Reputation) Classification Package.
The result item of a IPR classification.
#define DCA_LOGDIR
Relative directory for logfile(s).
#define DCA_INITDIR
DCA subdirectory of the DCA initialization data.
DCA_RESULT_TYPE getReturnCode() const
Gets the code of the error.
static void PrintToolHeader()
Prints out the name and the version of this sample.
Use a License to initialize a classification package or a toolbox package.
Definition: base_classes.h:560
bool isLicensed(DCA_MODULE_ID_TYPE id=0, bool force=false) const
Checks whether the given License is valid for the given module id.
static void PrintLicenseInfo(const License &aLicense)
Prints out the information about the provided License.
DCA_SIZE_TYPE size() const
Returns the number of classification results.
std::string ticket
The ticket as provided in the license.
Definition: base_classes.h:548
This header includes all header files of the DCA Base Package.
std::string versionString
Definition: base_classes.h:840
bool useLocalDatabase
Set to true to connect to a local or custom database, set to false to use a remote database.
Definition: base_classes.h:821
std::string name(const std::string &localeString=std::string()) const
Returns the localized (display) name of the category.
Encapsulates the init and deinit of the DCA API.
Definition: base_classes.h:315
The IprEnum class describes a single enumerable item, for example the Geo Location "Greenland".
Definition: ipr_enum.h:26
std::string product
The product code used with the license.
Definition: base_classes.h:549
Definition of the IprClassificationResults class.
std::string name(const std::string &localeString=std::string()) const
Returns the localized (display) name of the enumerable item.
Definition of a container class for IprEnum objects.
Definition: ipr_enums.h:30
int DCA_CATEGORY_ID_TYPE
Type for category ids.
Definition: base_types.h:31
std::string logDir
the directory in which the DCA log file should be created
Definition: base_classes.h:267
static void PrintUsage(const char *name)
Prints out the syntax of the sample.
std::string getLastMessage() const
Returns the last message received from our license server or if none available the last available mes...
size_t DCA_INDEX_TYPE
Type for index access (used for arrays and collections).
Definition: base_types.h:66
DbType dbType
The type of the database.
Definition: base_classes.h:820
IprClassifier createClassifier(const dca::DbConnection &aDbConnection, const IprClassifierOptions &aIprClassifierOptions=IprClassifierOptions()) const
Creates a IprClassifier that is used to classify dca_ipr::Ip objects.
dca::FunctionResult classify(const Ip &input, IprClassificationResults &result) const
Classification function that takes the given input and returns the results (if any) in the provided r...
std::string getDescription() const
Returns the description for the error or warning.
IprCategory byId(DCA_CATEGORY_ID_TYPE catid) const
Returns the category with the given category id.
size_t DCA_SIZE_TYPE
Type for size (used for size of array and collections).
Definition: base_types.h:72
Definition of a container class for IprCategory objects.
std::string getTicket() const
Returns the ticket of the license as string.
Definition of the IprClassification class.
#define DCA_BINDIR
DCA subdirectory of the DCA binaries.
Standard function result.
Definition: base_classes.h:148
IprCategoriesInfo getCategoriesInfo() const
Retrieve the IprCategoriesInfo class.
std::string getSession() const
Returns the session of the license as string.
int value
The value related to the given category.
bool isCategorized() const
If the classification returned a result this function returns true.
The IprCategory class contains information for a single category. An IP address can be assigned to on...
Definition: ipr_category.h:27
const std::string S_UsageString
Usage string, displayed if a parameter is missing.
DbConnection createDbConnection(const License &aLicense, const DbConnectionData &dbcData, const ProxySettings &proxySettings=ProxySettings(), LogLevel aLogLevel=LOG_Initial) const
Creates a DbConnection object using the given DbConnectionData.
This structure is used to initialize the DcaInstance.
Definition: base_classes.h:264
static DcaInstance create(const InitData &initData)
Creates a DcaInstance, starts up the DCA API and initializes the required main module.
static void SetupLicense(const std::string &ticket, const std::string &product, LicenseData &licenseData)
Sets up the given licenseData by copying the given ticket and product strings.
License createLicense(const LicenseData &licData, const ProxySettings &proxySettings=ProxySettings(), LogLevel aLogLevel=LOG_Initial) const
Creates a License object using the given LicenseData.
int main(int argc, char *argv[])
The main routine.