]> git.stg.codes - stg.git/blob - stargazer/plugins/capture/pcap/pcap_cap.cpp
Public interfaces: part 3
[stg.git] / stargazer / plugins / capture / pcap / pcap_cap.cpp
1 /*
2  *    This program is free software; you can redistribute it and/or modify
3  *    it under the terms of the GNU General Public License as published by
4  *    the Free Software Foundation; either version 2 of the License, or
5  *    (at your option) any later version.
6  *
7  *    This program is distributed in the hope that it will be useful,
8  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *    GNU General Public License for more details.
11  *
12  *    You should have received a copy of the GNU General Public License
13  *    along with this program; if not, write to the Free Software
14  *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
15  */
16
17 /*
18 * Author : Maxim Mamontov <faust@stargazer.dp.ua>
19 */
20
21 #include "pcap_cap.h"
22
23 #include "stg/traffcounter.h"
24 #include "stg/common.h"
25 #include "stg/raw_ip_packet.h"
26
27 #include <signal.h>
28
29 //-----------------------------------------------------------------------------
30 //-----------------------------------------------------------------------------
31 //-----------------------------------------------------------------------------
32 namespace
33 {
34
35 const size_t SNAP_LEN = 1518;
36 const size_t ETHER_ADDR_LEN = 6;
37
38 struct ETH
39 {
40 u_char     ether_dhost[ETHER_ADDR_LEN];    /* destination host address */
41 u_char     ether_shost[ETHER_ADDR_LEN];    /* source host address */
42 u_short    ether_type;                     /* IP? ARP? RARP? etc */
43 };
44
45 }
46
47 //-----------------------------------------------------------------------------
48 //-----------------------------------------------------------------------------
49 //-----------------------------------------------------------------------------
50 extern "C" STG::Plugin* GetPlugin()
51 {
52     static PCAP_CAP plugin;
53     return &plugin;
54 }
55 //-----------------------------------------------------------------------------
56 //-----------------------------------------------------------------------------
57 //-----------------------------------------------------------------------------
58 std::string PCAP_CAP::GetVersion() const
59 {
60 return "pcap_cap v.1.0";
61 }
62 //-----------------------------------------------------------------------------
63 PCAP_CAP::PCAP_CAP()
64     : nonstop(false),
65       isRunning(false),
66       traffCnt(NULL),
67       logger(STG::PluginLogger::get("pcap_cap"))
68 {
69 }
70 //-----------------------------------------------------------------------------
71 int PCAP_CAP::ParseSettings()
72 {
73 devices.erase(devices.begin(), devices.end());
74
75 if (settings.moduleParams.empty())
76     {
77     devices.push_back(DEV());
78     logger("Defaulting to pseudo-device 'any'.");
79     return 0;
80     }
81
82 for (size_t i = 0; i < settings.moduleParams.size(); i++)
83     if (settings.moduleParams[i].param == "interfaces")
84         for (size_t j = 0; j < settings.moduleParams[i].value.size(); j++)
85             devices.push_back(DEV(settings.moduleParams[i].value[j]));
86
87 for (size_t i = 0; i < settings.moduleParams.size(); i++)
88     if (settings.moduleParams[i].param == "filters")
89         for (size_t j = 0; j < settings.moduleParams[i].value.size(); j++)
90             if (j < devices.size())
91                 devices[j].filterExpression = settings.moduleParams[i].value[j];
92
93 if (devices.empty())
94     {
95     devices.push_back(DEV());
96     logger("Defaulting to pseudo-device 'all'.");
97     return 0;
98     }
99
100 return 0;
101 }
102 //-----------------------------------------------------------------------------
103 int PCAP_CAP::Start()
104 {
105 if (isRunning)
106     return 0;
107
108 DEV_MAP::iterator it(devices.begin());
109 while (it != devices.end())
110     {
111     bpf_u_int32 mask;
112     bpf_u_int32 net;
113     char errbuf[PCAP_ERRBUF_SIZE];
114
115     /* get network number and mask associated with capture device */
116     if (pcap_lookupnet(it->device.c_str(), &net, &mask, errbuf) == -1)
117         {
118         errorStr = "Couldn't get netmask for device " + it->device + ": " + errbuf;
119         logger(errorStr);
120         printfd(__FILE__, "%s\n", errorStr.c_str());
121         return -1;
122         }
123
124     /* open capture device */
125     it->handle = pcap_open_live(it->device.c_str(), SNAP_LEN, 1, 1000, errbuf);
126     if (it->handle == NULL)
127         {
128         errorStr = "Couldn't open device " + it->device + ": " + errbuf;
129         logger(errorStr);
130         printfd(__FILE__, "%s\n", errorStr.c_str());
131         return -1;
132         }
133
134     if (pcap_setnonblock(it->handle, true, errbuf) == -1)
135         {
136         errorStr = "Couldn't put device " + it->device + " into non-blocking mode: " + errbuf;
137         logger(errorStr);
138         printfd(__FILE__, "%s\n", errorStr.c_str());
139         return -1;
140         }
141
142     /* make sure we're capturing on an Ethernet device [2] */
143     if (pcap_datalink(it->handle) != DLT_EN10MB)
144         {
145         errorStr = it->device + " is not an Ethernet";
146         logger(errorStr);
147         printfd(__FILE__, "%s\n", errorStr.c_str());
148         return -1;
149         }
150
151     /* compile the filter expression */
152     if (pcap_compile(it->handle, &it->filter, it->filterExpression.c_str(), 0, net) == -1)
153         {
154         errorStr = "Couldn't parse filter " + it->filterExpression + ": " + pcap_geterr(it->handle);
155         logger(errorStr);
156         printfd(__FILE__, "%s\n", errorStr.c_str());
157         return -1;
158         }
159
160     /* apply the compiled filter */
161     if (pcap_setfilter(it->handle, &it->filter) == -1)
162         {
163         errorStr = "Couldn't install filter " + it->filterExpression + ": " + pcap_geterr(it->handle);
164         logger(errorStr);
165         printfd(__FILE__, "%s\n", errorStr.c_str());
166         return -1;
167         }
168
169     it->fd = pcap_get_selectable_fd(it->handle);
170     if (it->fd == -1)
171         {
172         errorStr = "Couldn't get a file descriptor for " + it->device + ": " + pcap_geterr(it->handle);
173         logger(errorStr);
174         printfd(__FILE__, "%s\n", errorStr.c_str());
175         return -1;
176         }
177
178     ++it;
179     }
180
181 nonstop = true;
182
183 if (pthread_create(&thread, NULL, Run, this))
184     {
185     errorStr = "Cannot create thread.";
186     logger("Cannot create thread.");
187     printfd(__FILE__, "Cannot create thread\n");
188     return -1;
189     }
190
191 return 0;
192 }
193 //-----------------------------------------------------------------------------
194 int PCAP_CAP::Stop()
195 {
196 if (!isRunning)
197     return 0;
198
199 nonstop = false;
200
201 //5 seconds to thread stops itself
202 for (int i = 0; i < 25 && isRunning; i++)
203     {
204     struct timespec ts = {0, 200000000};
205     nanosleep(&ts, NULL);
206     }
207 //after 5 seconds waiting thread still running. now killing it
208 if (isRunning)
209     {
210     if (pthread_kill(thread, SIGUSR1))
211         {
212         errorStr = "Cannot kill thread.";
213         logger("Cannot send signal to thread.");
214         return -1;
215         }
216     for (int i = 0; i < 25 && isRunning; ++i)
217         {
218         struct timespec ts = {0, 200000000};
219         nanosleep(&ts, NULL);
220         }
221     if (isRunning)
222         {
223         errorStr = "PCAP_CAP not stopped.";
224         logger("Cannot stop thread.");
225         printfd(__FILE__, "Cannot stop thread\n");
226         return -1;
227         }
228     }
229
230 pthread_join(thread, NULL);
231
232 for (DEV_MAP::iterator it(devices.begin()); it != devices.end(); ++it)
233     {
234     pcap_freecode(&it->filter);
235     pcap_close(it->handle);
236     }
237
238 return 0;
239 }
240 //-----------------------------------------------------------------------------
241 void * PCAP_CAP::Run(void * d)
242 {
243 sigset_t signalSet;
244 sigfillset(&signalSet);
245 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
246
247 PCAP_CAP * dc = static_cast<PCAP_CAP *>(d);
248 dc->isRunning = true;
249
250 fd_set fds;
251 FD_ZERO(&fds);
252 int maxFd = 0;
253 for (DEV_MAP::const_iterator it(dc->devices.begin()); it != dc->devices.end(); ++it)
254     {
255     FD_SET(it->fd, &fds);
256     maxFd = std::max(maxFd, it->fd);
257     }
258
259 while (dc->nonstop)
260     {
261     fd_set rfds = fds;
262     struct timeval tv = {0, 500000};
263
264     if (select(maxFd + 1, &rfds, NULL, NULL, &tv) > 0)
265         dc->TryRead(rfds);
266     }
267
268 dc->isRunning = false;
269 return NULL;
270 }
271
272 void PCAP_CAP::TryRead(const fd_set & set)
273 {
274 for (DEV_MAP::const_iterator it(devices.begin()); it != devices.end(); ++it)
275     if (FD_ISSET(it->fd, &set))
276         TryReadDev(*it);
277 }
278
279 void PCAP_CAP::TryReadDev(const DEV & dev)
280 {
281 struct pcap_pkthdr * header;
282 const u_char * packet;
283 if (pcap_next_ex(dev.handle, &header, &packet) == -1)
284     {
285     printfd(__FILE__, "Failed to read data from '%s': %s\n", dev.device.c_str(), pcap_geterr(dev.handle));
286     return;
287     }
288
289 const ETH * eth = reinterpret_cast<const ETH *>(packet);
290 if (eth->ether_type != 0x8)
291     return;
292
293 STG::RawPacket ip;
294 memcpy(&ip.rawPacket, packet + 14, sizeof(ip.rawPacket));
295 traffCnt->process(ip);
296 }