new upstream release (3.3.0); modify package compatibility for Stretch
[ossec-hids.git] / src / analysisd / decoders / geoip.c
1 /* @(#) $Id: ./src/analysisd/decoders/geoip.c, 2014/03/08 dcid Exp $
2  */
3
4 /* Copyright (C) 2014 Daniel Cid
5  * All right reserved.
6  *
7  * This program is a free software; you can redistribute it
8  * and/or modify it under the terms of the GNU General Public
9  * License (version 2) as published by the FSF - Free Software
10  * Foundation
11  */
12
13
14 /* GeoIP - Every IP address will have its geolocation added to it */
15
16 #ifdef LIBGEOIP_ENABLED
17
18
19 #include "config.h"
20 #include "os_regex/os_regex.h"
21 #include "eventinfo.h"
22 #include "alerts/alerts.h"
23 #include "decoder.h"
24 #include "GeoIP.h"
25 #include "GeoIPCity.h"
26
27
28 char *GetGeoInfobyIP(char *ip_addr)
29 {
30     GeoIPRecord *geoiprecord;
31     char *geodata = NULL;
32     char geobuffer[256 +1];
33
34     if(!geoipdb)
35     {
36         return(NULL);
37     }
38
39     if(!ip_addr)
40     {
41         return(NULL);
42     }
43
44     geoiprecord = GeoIP_record_by_name(geoipdb, (const char *)ip_addr);
45     if(geoiprecord == NULL)
46     {
47         return(NULL);
48     }
49     
50     if(geoiprecord->country_code == NULL)
51     {
52         GeoIPRecord_delete(geoiprecord);
53         return(NULL);
54     }
55
56     if(strlen(geoiprecord->country_code) < 2)
57     {
58         GeoIPRecord_delete(geoiprecord);
59         return(NULL);
60     }
61    
62
63     if(geoiprecord->region != NULL && geoiprecord->region[0] != '\0')
64     {
65         const char *regionname = NULL;
66         regionname = GeoIP_region_name_by_code(geoiprecord->country_code, geoiprecord->region);
67         if(regionname != NULL)
68         {
69             snprintf(geobuffer, 255, "%s / %s", geoiprecord->country_code, regionname);
70             geobuffer[255] = '\0';
71             geodata = strdup(geobuffer);
72         }
73         else
74         {
75             geodata = strdup(geoiprecord->country_code);
76         }
77     }
78     else
79     {
80         geodata = strdup(geoiprecord->country_code);
81     }
82
83     GeoIPRecord_delete(geoiprecord);
84     return(geodata);
85  
86 }
87
88 #endif
89