1 |
#include <iostream> |
2 |
#include <fstream> |
3 |
#include <string> |
4 |
#include <sstream> |
5 |
#include <vector> |
6 |
#include <iomanip> |
7 |
#include <GeoIP.h> |
8 |
|
9 |
|
10 |
using namespace std; |
11 |
GeoIP* gi = 0; |
12 |
bool lookup = false; |
13 |
|
14 |
vector<string> getTokens(const string& str){ |
15 |
string buf; |
16 |
stringstream ss(str); |
17 |
vector<string> tokens; |
18 |
while (ss >> buf) |
19 |
tokens.push_back(buf); |
20 |
return tokens; |
21 |
} |
22 |
|
23 |
void lookupIP(const string& ip) { |
24 |
if (!lookup) |
25 |
return; |
26 |
const char* cc = GeoIP_country_code_by_addr(gi, ip.c_str()); |
27 |
|
28 |
if (cc) |
29 |
cout << setw(3) << cc << " "; |
30 |
else |
31 |
cout << setw(3) << "n/a "; |
32 |
|
33 |
} |
34 |
|
35 |
void analyseWord(const string& word) { |
36 |
int delim = word.find("="); |
37 |
|
38 |
if (delim == -1) //delimiter not found; |
39 |
return; |
40 |
string key = word.substr(0,delim); |
41 |
string val = word.substr(delim+1, 1024); // the rest |
42 |
|
43 |
if (key == "SRC") { |
44 |
cout << setw(15) << left << val << " "; |
45 |
lookupIP(val); |
46 |
} |
47 |
|
48 |
if (key == "DST") |
49 |
cout << setw(15) << left << val << " "; |
50 |
|
51 |
if (key == "PROTO") |
52 |
cout << val << " "; |
53 |
|
54 |
if (key == "SPT") |
55 |
cout << setw(5) << right << val << " "; |
56 |
|
57 |
if (key == "DPT") |
58 |
cout << setw(6) << right << val << " "; |
59 |
} |
60 |
|
61 |
void analyseLine(string line) { |
62 |
vector<string> words = getTokens(line); |
63 |
|
64 |
//print date and time |
65 |
cout << words[0] << " " << words[1] << " " << words[2] << " "; |
66 |
for (unsigned i=3; i<words.size(); i++) { |
67 |
analyseWord(words[i]); |
68 |
} |
69 |
|
70 |
|
71 |
cout << endl; |
72 |
} |
73 |
|
74 |
|
75 |
void printUsage() { |
76 |
cout << "Usage: analyser [-l] <logfile>" << endl; |
77 |
cout << "Options:" << endl; |
78 |
cout << " -l : geoip lookup on source IP adresses" << endl; |
79 |
} |
80 |
|
81 |
int main(int argc, char** argv) |
82 |
{ |
83 |
if (argc < 2) { |
84 |
printUsage(); |
85 |
return 1; |
86 |
} |
87 |
|
88 |
string file = ""; |
89 |
|
90 |
if (string(argv[1]) == "-l") { |
91 |
if (argc != 3) { |
92 |
printUsage(); |
93 |
return 1; |
94 |
} |
95 |
|
96 |
file = argv[2]; |
97 |
lookup = true; |
98 |
} else { |
99 |
file = argv[1]; |
100 |
} |
101 |
|
102 |
|
103 |
ifstream in(file.c_str()); |
104 |
|
105 |
if (!in) { |
106 |
cout << "Could not open " << file << endl; |
107 |
return 1; |
108 |
} |
109 |
|
110 |
|
111 |
if (lookup){ |
112 |
gi = GeoIP_new(GEOIP_STANDARD); |
113 |
} |
114 |
|
115 |
while (!in.eof()) { |
116 |
char buffer[1024]; |
117 |
in.getline(buffer,1024); |
118 |
if (buffer[0] == 0) |
119 |
continue; //empty line |
120 |
analyseLine(buffer); |
121 |
} |
122 |
|
123 |
if (lookup) { |
124 |
} |
125 |
|
126 |
return 0; |
127 |
} |