Debian Codegraph @

protolib/examples/detourExample.cpp

raw
1
2 #include "protoApp.h"
3 #include "protoDetour.h"
4 #include "protoPktIP.h"
5
6 #include <stdlib.h> // for atoi()
7 #include <stdio.h> // for stdout/stderr printouts
8 #include <string.h>
9 #include "protoBase64.h"
10
11 /**
12 * @class DetourExample
13 *
14 * @brief An example using a ProtoDetour class instance to intercept
15 * outbound packets
16 */
17 class DetourExample : public ProtoApp
18 {
19 public:
20 DetourExample();
21 ~DetourExample();
22
23 // Overrides from ProtoApp or NsProtoSimAgent base
24 bool OnStartup(int argc, const char*const* argv);
25 bool ProcessCommands(int argc, const char*const* argv);
26 void OnShutdown();
27
28 private:
29 void DetourEventHandler(ProtoChannel& theChannel,
30 ProtoChannel::Notification theNotification);
31
32 enum CmdType {CMD_INVALID, CMD_ARG, CMD_NOARG};
33 static const char* const CMD_LIST[];
34 static CmdType GetCmdType(const char* string);
35 bool OnCommand(const char* cmd, const char* val);
36 void Usage();
37
38 ProtoDetour* detour;
39 bool ipv6_mode;
40 bool allow; // toggled variable for test
41
42 }; // end class DetourExample
43
44 const char* const DetourExample::CMD_LIST[] =
45 {
46 "-ipv6", // IPv6 test (instead of IPv4)
47 NULL
48 };
49
50 // This macro creates our ProtoApp derived application instance
51 PROTO_INSTANTIATE_APP(DetourExample)
52
53 DetourExample::DetourExample()
54 : detour(NULL), ipv6_mode(false), allow(true)
55
56 {
57
58 }
59
60 DetourExample::~DetourExample()
61 {
62 }
63
64 void DetourExample::Usage()
65 {
66 #ifdef WIN32
67 fprintf(stderr, "detourExample [ipv6][background]\n");
68 #else
69 fprintf(stderr, "detourExample\n");
70 #endif // if/else WIN32/UNIX
71 } // end DetourExample::Usage()
72
73
74 DetourExample::CmdType DetourExample::GetCmdType(const char* cmd)
75 {
76 if (!cmd) return CMD_INVALID;
77 unsigned int len = strlen(cmd);
78 bool matched = false;
79 CmdType type = CMD_INVALID;
80 const char* const* nextCmd = CMD_LIST;
81 while (*nextCmd)
82 {
83 if (!strncmp(cmd, *nextCmd+1, len))
84 {
85 if (matched)
86 {
87 // ambiguous command (command should match only once)
88 return CMD_INVALID;
89 }
90 else
91 {
92 matched = true;
93 if ('+' == *nextCmd[0])
94 type = CMD_ARG;
95 else
96 type = CMD_NOARG;
97 }
98 }
99 nextCmd++;
100 }
101 return type;
102 } // end DetourExample::GetCmdType()
103
104
105 bool DetourExample::OnStartup(int argc, const char*const* argv)
106 {
107 SetDebugLevel(3);
108
109 if (!ProcessCommands(argc, argv))
110 {
111 PLOG(PL_ERROR, "detourExample::OnStartup() error processing command line options\n");
112 return false;
113 }
114
115 // Create our cap_rcvr instance and initialize ...
116 if (!(detour = ProtoDetour::Create()))
117 {
118 PLOG(PL_ERROR, "detourExample::OnStartup() new ProtoDetour error: %s\n", GetErrorString());
119 return false;
120 }
121
122 detour->SetNotifier(static_cast<ProtoChannel::Notifier*>(&dispatcher));
123 detour->SetListener(this, &DetourExample::DetourEventHandler);
124
125 // Set detour filter for outbound multicast packets
126 ProtoAddress srcFilter;
127 ProtoAddress dstFilter;
128 unsigned int dstFilterMask;
129 if (ipv6_mode)
130 {
131 srcFilter.Reset(ProtoAddress::IPv6); // unspecified address
132 dstFilter.ResolveFromString("ff00::");
133 dstFilterMask = 8;
134 }
135 else
136 {
137 srcFilter.Reset(ProtoAddress::IPv4); // unspecified address
138 dstFilter.ResolveFromString("239.0.0.0");
139 dstFilterMask = 4;
140 }
141
142 if (!detour->Open(ProtoDetour::INPUT, srcFilter, 0, dstFilter, dstFilterMask))
143 {
144 PLOG(PL_ERROR, "detourExample::OnStartup() ProtoDetour::Open() error\n");
145 }
146
147 #ifdef NEVER //HAVE_SCHED
148 // Boost process priority for real-time operation
149 // (This _may_ work on Linux-only at this point)
150 struct sched_param schp;
151 memset(&schp, 0, sizeof(schp));
152 schp.sched_priority = sched_get_priority_max(SCHED_FIFO);
153 if (sched_setscheduler(0, SCHED_FIFO, &schp))
154 {
155 schp.sched_priority = sched_get_priority_max(SCHED_OTHER);
156 if (sched_setscheduler(0, SCHED_OTHER, &schp))
157 PLOG(PL_ERROR, "detourExample: Warning! Couldn't set any real-time priority: %s\n", GetErrorString());
158 }
159 #endif // HAVE_SCHED
160
161 #ifdef WIN32
162 #ifndef _WIN32_WCE
163 if (!SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS))
164 PLOG(PL_ERROR, "detourExample: Warning! SetPriorityClass() error: %s\n", GetErrorString());
165 #endif // !_WIN32_WCE
166 if (!SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL))
167 PLOG(PL_ERROR, "detourExample: Warning! SetThreadPriority() error: %s\n", GetErrorString());
168 #endif // WIN32
169
170 TRACE("startup returning control to dispatcher ...\n");
171
172 return true;
173 } // end DetourExample::OnStartup()
174
175 void DetourExample::OnShutdown()
176 {
177 if (NULL != detour)
178 {
179 detour->Close();
180 delete detour;
181 detour = NULL;
182 }
183 PLOG(PL_ERROR, "detourExample: Done.\n");
184 CloseDebugLog();
185 } // end DetourExample::OnShutdown()
186
187 bool DetourExample::ProcessCommands(int argc, const char*const* argv)
188 {
189 // Dispatch command-line commands to our OnCommand() method
190 int i = 1;
191 while ( i < argc)
192 {
193 // Is it a class DetourExample command?
194 switch (GetCmdType(argv[i]))
195 {
196 case CMD_INVALID:
197 {
198 PLOG(PL_ERROR, "DetourExample::ProcessCommands() Invalid command:%s\n",
199 argv[i]);
200 return false;
201 }
202 case CMD_NOARG:
203 if (!OnCommand(argv[i], NULL))
204 {
205 PLOG(PL_ERROR, "DetourExample::ProcessCommands() ProcessCommand(%s) error\n",
206 argv[i]);
207 return false;
208 }
209 i++;
210 break;
211 case CMD_ARG:
212 if (!OnCommand(argv[i], argv[i+1]))
213 {
214 PLOG(PL_ERROR, "DetourExample::ProcessCommands() ProcessCommand(%s, %s) error\n",
215 argv[i], argv[i+1]);
216 return false;
217 }
218 i += 2;
219 break;
220 }
221 }
222 return true;
223 } // end DetourExample::ProcessCommands()
224
225 bool DetourExample::OnCommand(const char* cmd, const char* val)
226 {
227 // (TBD) move command processing into Mgen class ???
228 CmdType type = GetCmdType(cmd);
229 ASSERT(CMD_INVALID != type);
230 size_t len = strlen(cmd);
231 if ((CMD_ARG == type) && !val)
232 {
233 PLOG(PL_ERROR, "DetourExample::ProcessCommand(%s) missing argument\n", cmd);
234 return false;
235 }
236 else if (!strncmp("ipv6", cmd, len))
237 {
238 ipv6_mode = true;
239 }
240 else
241 {
242 PLOG(PL_ERROR, "detourExample:: invalid command\n");
243 return false;
244 }
245 return true;
246 } // end DetourExample::OnCommand()
247
248 void DetourExample::DetourEventHandler(ProtoChannel& theChannel,
249 ProtoChannel::Notification theNotification)
250 {
251 if (ProtoChannel::NOTIFY_INPUT == theNotification)
252 {
253 UINT32 buffer[8192/4];
254 unsigned int numBytes = 8192;
255 if (detour->Recv((char*)buffer, numBytes))
256 {
257 TRACE("detour recv'd packet ...\n");
258 if (0 != numBytes)
259 {
260 allow = true;
261 if (allow)
262 {
263 TRACE("detour allowing packet len:%u\n", numBytes);
264
265 ProtoPktIP ipPkt(buffer, numBytes);
266 ipPkt.InitFromBuffer(numBytes);
267
268 // This some example code that "translates" the dst addr
269 // of certain outbound IP packets 224.0.0.251 -> 224.1.2.3
270 // (These are MDNS packets, by the way)
271 ProtoAddress dstAddr;
272 ipPkt.GetDstAddr(dstAddr);
273 ProtoAddress matchAddress;
274 matchAddress.ResolveFromString("224.0.0.251");
275 ProtoAddress goalAddress;
276 goalAddress.ResolveFromString("224.1.2.3");
277 if (dstAddr.HostIsEqual(matchAddress))
278 {
279 ipPkt.SetDstAddr(goalAddress);
280 // Need to update UDP checksum if UDP packet
281 // (yucky cross-layer UDP checksum)
282 ProtoPktUDP udpPkt;
283 if (udpPkt.InitFromPacket(ipPkt))
284 udpPkt.FinalizeChecksum(ipPkt);
285 }
286
287 // Some UDP packet manipulation code
288 ProtoPktUDP udpPkt;
289 if (udpPkt.InitFromPacket(ipPkt))// && (5000 == udpPkt.GetDstPort()))
290 {
291 if (udpPkt.ChecksumIsValid(ipPkt))
292 {
293 TRACE(" UDP with valid checksum %04x (computed: %04x)\n",
294 udpPkt.GetChecksum(), udpPkt.ComputeChecksum(ipPkt));
295 }
296 else
297 {
298 TRACE(" UDP with INVALID checksum %04x (computed: %04x)\n",
299 udpPkt.GetChecksum(), udpPkt.ComputeChecksum(ipPkt));
300
301
302 ProtoAddress srcAddr;
303 ipPkt.GetSrcAddr(srcAddr);
304 TRACE(" src:%s\n", srcAddr.GetHostString());
305 TRACE(" dst:%s\n", dstAddr.GetHostString());
306 ProtoPktIPv4 ipv4Pkt(ipPkt);
307 TRACE(" proto:%d\n", ipv4Pkt.GetProtocol());
308
309 /*
310 char base64Buffer[8192];
311 unsigned int length = ProtoBase64::Encode((char*)buffer, numBytes, base64Buffer, 8192);
312 TRACE("packet(base64)=\n %s\n", base64Buffer);
313 */
314 for (unsigned int i = 0; i < numBytes; i++)
315 {
316 if (0 == i)
317 ;
318 else if (0 == (i%16))
319 TRACE("\n");
320 else if (0 == (i%2))
321 TRACE(" ");
322 unsigned char* ptr = (unsigned char*)buffer;
323 TRACE("%02x", ptr[i]);
324 }
325 }
326
327 }
328
329
330 detour->Allow((char*)buffer, numBytes);
331 //allow = false; // uncomment this to drop every other packet
332 }
333 else
334 {
335 TRACE("detour dropping/injecting packet ...\n");
336 detour->Drop();
337 detour->Inject((char*)buffer, numBytes);
338 allow = true;
339 }
340 }
341 numBytes = 8192;
342 }
343 }
344 } // end DetourExample::DetourEventHandler()