Debian Codegraph @

protolib/examples/arposer.cpp

raw
1 #include "protoApp.h"
2 #include "protoCap.h"
3 #include "protoPktIP.h"
4 #include "protoPktETH.h"
5 #include "protoPktARP.h"
6 #include "protoNet.h"
7
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <string.h>
11 #include <ctype.h> // for "isspace()"
12
13 /**
14 * @class ArposerApp
15 *
16 * @brief simple app that gratuitously responds to ARP requests
17 * with its own MAC address as the response
18 *
19 */
20 class ArposerApp : public ProtoApp
21 {
22 public:
23 ArposerApp();
24 ~ArposerApp();
25
26 bool OnStartup(int argc, const char*const* argv);
27 bool ProcessCommands(int argc, const char*const* argv);
28 void OnShutdown();
29
30
31
32 private:
33 enum CmdType {CMD_INVALID, CMD_ARG, CMD_NOARG};
34 static const char* const CMD_LIST[];
35 static CmdType GetCmdType(const char* string);
36 bool OnCommand(const char* cmd, const char* val);
37 void Usage();
38
39
40
41 void PeekPkt(ProtoPktETH& ethPkt, bool inbound);
42
43 void OnInboundPkt(ProtoChannel& theChannel,
44 ProtoChannel::Notification notifyType);
45
46 ProtoCap* cap;
47 char if_name[256];
48
49
50 }; // end class ArposerApp
51
52 void ArposerApp::Usage()
53 {
54 fprintf(stderr, "Usage: arposer interface <ifName> [debug <level>][help]\n");
55 }
56
57 const char* const ArposerApp::CMD_LIST[] =
58 {
59 "-help", // print help info an exit
60 "+interface", // name of interface on which to listen / respond
61 "+debug", // <debugLevel>
62 NULL
63 };
64
65 /**
66 * This macro creates our ProtoApp derived application instance
67 */
68 PROTO_INSTANTIATE_APP(ArposerApp)
69
70 ArposerApp::ArposerApp()
71 : cap(NULL)
72 {
73 if_name[0] = '\0';
74 }
75
76 ArposerApp::~ArposerApp()
77 {
78 }
79
80 ArposerApp::CmdType ArposerApp::GetCmdType(const char* cmd)
81 {
82 if (!cmd) return CMD_INVALID;
83 unsigned int len = strlen(cmd);
84 bool matched = false;
85 CmdType type = CMD_INVALID;
86 const char* const* nextCmd = CMD_LIST;
87 while (*nextCmd)
88 {
89 if (!strncmp(cmd, *nextCmd+1, len))
90 {
91 if (matched)
92 {
93 // ambiguous command (command should match only once)
94 return CMD_INVALID;
95 }
96 else
97 {
98 matched = true;
99 if ('+' == *nextCmd[0])
100 type = CMD_ARG;
101 else
102 type = CMD_NOARG;
103 }
104 }
105 nextCmd++;
106 }
107 return type;
108 } // end ArposerApp::GetCmdType()
109
110
111 bool ArposerApp::OnStartup(int argc, const char*const* argv)
112 {
113 // Seed rand() with time of day usec
114 // (comment out for repeatable results)
115 struct timeval currentTime;
116 ProtoSystemTime(currentTime);
117 srand((unsigned int)currentTime.tv_usec);
118
119 if (!ProcessCommands(argc, argv))
120 {
121 PLOG(PL_ERROR, "ArposerApp::OnStartup() error processing command line options\n");
122 Usage();
123 return false;
124 }
125
126 // Check for valid parameters.
127 if (0 == strlen(if_name))
128 {
129 PLOG(PL_ERROR, "ArposerApp::OnStartup() error: missng required 'interface' command!\n");
130 Usage();
131 return false;
132 }
133
134 // Create our cap instance and initialize ...
135 if (!(cap = ProtoCap::Create()))
136 {
137 PLOG(PL_ERROR, "ArposerApp::OnStartup() new ProtoCap error: %s\n", GetErrorString());
138 return false;
139 }
140 cap->SetNotifier(static_cast<ProtoChannel::Notifier*>(&dispatcher));
141 cap->SetListener(this,&ArposerApp::OnInboundPkt);
142 if (!cap->Open(if_name))
143 {
144 PLOG(PL_ERROR,"ArposerApp::OnStartup() ProtoCap::Open(\"%s\") error\n", if_name);
145 Usage();
146 return false;
147 }
148
149 PLOG(PL_INFO, "arposer: running on interface: %s\n", if_name);
150
151 return true;
152 } // end ArposerApp::OnStartup()
153
154 void ArposerApp::OnShutdown()
155 {
156 if (NULL != cap)
157 {
158 cap->Close();
159 delete cap;
160 cap = NULL;
161 }
162
163 PLOG(PL_INFO, "arposer: Done.\n");
164
165 } // end ArposerApp::OnShutdown()
166
167 bool ArposerApp::ProcessCommands(int argc, const char*const* argv)
168 {
169 // Dispatch command-line commands to our OnCommand() method
170 int i = 1;
171 while ( i < argc)
172 {
173 // Is it a arposer command?
174 switch (GetCmdType(argv[i]))
175 {
176 case CMD_INVALID:
177 {
178 PLOG(PL_ERROR, "ArposerApp::ProcessCommands() Invalid command:%s\n",
179 argv[i]);
180 Usage();
181 return false;
182 }
183 case CMD_NOARG:
184 if (!OnCommand(argv[i], NULL))
185 {
186 PLOG(PL_ERROR, "ArposerApp::ProcessCommands() ProcessCommand(%s) error\n",
187 argv[i]);
188 Usage();
189 return false;
190 }
191 i++;
192 break;
193 case CMD_ARG:
194 if (!OnCommand(argv[i], argv[i+1]))
195 {
196 PLOG(PL_ERROR, "ArposerApp::ProcessCommands() ProcessCommand(%s, %s) error\n",
197 argv[i], argv[i+1]);
198 Usage();
199 return false;
200 }
201 i += 2;
202 break;
203 }
204 }
205 return true;
206 } // end ArposerApp::ProcessCommands()
207
208 bool ArposerApp::OnCommand(const char* cmd, const char* val)
209 {
210 // (TBD) move command processing into Mgen class ???
211 CmdType type = GetCmdType(cmd);
212 ASSERT(CMD_INVALID != type);
213 size_t len = strlen(cmd);
214 if ((CMD_ARG == type) && !val)
215 {
216 PLOG(PL_ERROR, "ArposerApp::ProcessCommand(%s) missing argument\n", cmd);
217 Usage();
218 return false;
219 }
220 else if (!strncmp("help", cmd, len))
221 {
222 Usage();
223 exit(0);
224 }
225 else if (!strncmp("interface", cmd, len))
226 {
227 strncpy(if_name, val, 255);
228 if_name[255] = '\0';
229 }
230 else if (!strncmp("debug", cmd, len))
231 {
232 SetDebugLevel(atoi(val));
233 }
234 else
235 {
236 PLOG(PL_ERROR, "arposer error: invalid command\n");
237 Usage();
238 return false;
239 }
240 return true;
241 } // end ArposerApp::OnCommand()
242
243
244 void ArposerApp::PeekPkt(ProtoPktETH& ethPkt, bool inbound)
245 {
246 switch (ethPkt.GetType())
247 {
248 case ProtoPktETH::IP:
249 case ProtoPktETH::IPv6:
250 {
251 unsigned int payloadLength = ethPkt.GetPayloadLength();
252 ProtoPktIP ipPkt;
253 // The void* cast here suppresses the alignment warning we get otherwise. This cast is OK
254 // because of how we set up the "alignedBuffer" elsewhere
255 if (!ipPkt.InitFromBuffer(payloadLength, (UINT32*)((void*)ethPkt.AccessPayload()), payloadLength))
256 {
257 PLOG(PL_ERROR, "arposer::PeekPkt() error: bad %sbound IP packet\n",
258 inbound ? "in" : "out");
259 break;
260 }
261 ProtoAddress dstAddr;
262 ProtoAddress srcAddr;
263 switch (ipPkt.GetVersion())
264 {
265 case 4:
266 {
267 ProtoPktIPv4 ip4Pkt(ipPkt);
268 ip4Pkt.GetDstAddr(dstAddr);
269 ip4Pkt.GetSrcAddr(srcAddr);
270 break;
271 }
272 case 6:
273 {
274 ProtoPktIPv6 ip6Pkt(ipPkt);
275 ip6Pkt.GetDstAddr(dstAddr);
276 ip6Pkt.GetSrcAddr(srcAddr);
277 break;
278 }
279 default:
280 {
281 PLOG(PL_ERROR,"ArposerApp::PeekPkt() Error: Invalid IP pkt version.\n");
282 break;
283 }
284 }
285 PLOG(PL_ALWAYS, "ArposerApp::PeekPkt() %sbound packet IP dst>%s ",
286 inbound ? "in" : "out", dstAddr.GetHostString());
287 PLOG(PL_ALWAYS, "src>%s length>%d\n", srcAddr.GetHostString(), ipPkt.GetLength());
288 break;
289 }
290 case ProtoPktETH::ARP:
291 {
292 ProtoPktARP arp;
293 // The void* cast here suppresses the alignment warning we get otherwise. This cast is OK
294 // because of how we set up the "alignedBuffer" elsewhere
295 if (!arp.InitFromBuffer((UINT32*)((void*)ethPkt.AccessPayload()), ethPkt.GetPayloadLength()))
296 {
297 PLOG(PL_ERROR, "ArposerApp::PeekPkt() received bad ARP packet?\n");
298 break;
299 }
300 PLOG(PL_ALWAYS,"ArposerApp::PeekPkt() %sbound ARP ",
301 inbound ? "in" : "out");
302 switch(arp.GetOpcode())
303 {
304 case ProtoPktARP::ARP_REQ:
305 PLOG(PL_ALWAYS, "request ");
306 break;
307 case ProtoPktARP::ARP_REP:
308 PLOG(PL_ALWAYS, "reply ");
309 break;
310 default:
311 PLOG(PL_ALWAYS, "??? ");
312 break;
313 }
314 ProtoAddress addr;
315 arp.GetSenderHardwareAddress(addr);
316 PLOG(PL_ALWAYS, "from eth:%s ", addr.GetHostString());
317 arp.GetSenderProtocolAddress(addr);
318 PLOG(PL_ALWAYS, "ip:%s ", addr.GetHostString());
319 arp.GetTargetProtocolAddress(addr);
320 PLOG(PL_ALWAYS, "for ip:%s ", addr.GetHostString());
321 if (ProtoPktARP::ARP_REP == arp.GetOpcode())
322 {
323
324 arp.GetTargetHardwareAddress(addr);
325 PLOG(PL_ALWAYS, "eth:%s ", addr.GetHostString());
326 }
327 PLOG(PL_ALWAYS, "\n");
328 break;
329 }
330 default:
331 PLOG(PL_ERROR, "ArposerApp::PeekPkt() unknown %s packet type\n", inbound ? "inbound" : "outbound");
332 break;
333 }
334 } // end ArposerApp::PeekPkt()
335
336
337 /**
338 * @note We offset the buffer here by 2 bytes since
339 * Ethernet header is 14 bytes
340 * (i.e. not a multiple of 4 (sizeof(UINT32))
341 * This gives us a properly aligned buffer for
342 * 32-bit aligned IP packets
343 */
344 void ArposerApp::OnInboundPkt(ProtoChannel& theChannel,
345 ProtoChannel::Notification notifyType)
346 {
347 ProtoTime currentTime;
348 if (ProtoChannel::NOTIFY_INPUT != notifyType) return;
349 while(1)
350 {
351 ProtoCap::Direction direction;
352
353 const int BUFFER_MAX = 4096;
354 UINT32 alignedBuffer[BUFFER_MAX/sizeof(UINT32)];
355 // offset by 2-bytes so IP content is 32-bit aligned
356 UINT16* ethBuffer = ((UINT16*)alignedBuffer) + 1;
357 unsigned int numBytes = BUFFER_MAX - 2;
358
359 if (!cap->Recv((char*)ethBuffer, numBytes, &direction))
360 {
361 PLOG(PL_ERROR, "ArposerApp::OnInboundPkt() ProtoCap::Recv() error\n");
362 break;
363 }
364
365 if (numBytes == 0) break; // no more packets to receive
366
367 if ((ProtoCap::OUTBOUND != direction))
368 {
369 // Map ProtoPktETH instance into buffer and init for processing
370 // (void* cast here is OK since ProtoPktETH is OK w/ UINT16*
371 ProtoPktETH ethPkt((UINT32*)((void*)ethBuffer), BUFFER_MAX - 2);
372 if (!ethPkt.InitFromBuffer(numBytes))
373 {
374 PLOG(PL_ERROR, "ArposerApp::OnInboundPkt() error: bad Ether frame\n");
375 continue;
376 }
377
378 // In "MNE" environment, ignore packets from blocked MAC sources
379 ProtoAddress srcMacAddr;
380 ethPkt.GetSrcAddr(srcMacAddr);
381
382 // Only handle ARP packets (skip others)
383 if (ProtoPktETH::ARP == ethPkt.GetType())
384 {
385
386 ProtoPktARP arp;
387 if (!arp.InitFromBuffer((UINT32*)((void*)ethPkt.AccessPayload()), ethPkt.GetPayloadLength()))
388 {
389 PLOG(PL_ERROR, "ArposerApp::PeekPkt() received bad ARP packet?\n");
390 break;
391 }
392 // Skip ARP replies (only respond to ARP requests)
393 if (ProtoPktARP::ARP_REQ != arp.GetOpcode())
394 continue;
395
396 PLOG(PL_ALWAYS,"ArposerApp::PeekPkt() inbound ARP ");
397 switch(arp.GetOpcode())
398 {
399 case ProtoPktARP::ARP_REQ:
400 PLOG(PL_ALWAYS, "request ");
401 break;
402 case ProtoPktARP::ARP_REP:
403 PLOG(PL_ALWAYS, "reply ");
404 break;
405 default:
406 PLOG(PL_ALWAYS, "??? ");
407 break;
408 }
409 ProtoAddress senderMAC;
410 arp.GetSenderHardwareAddress(senderMAC);
411 PLOG(PL_ALWAYS, "from eth:%s ", senderMAC.GetHostString());
412 ProtoAddress senderIP;
413 arp.GetSenderProtocolAddress(senderIP);
414 PLOG(PL_ALWAYS, "ip:%s ", senderIP.GetHostString());
415 ProtoAddress targetIP;
416 arp.GetTargetProtocolAddress(targetIP);
417 PLOG(PL_ALWAYS, "for ip:%s ", targetIP.GetHostString());
418 if (ProtoPktARP::ARP_REP == arp.GetOpcode())
419 {
420 ProtoAddress targetMAC;
421 arp.GetTargetHardwareAddress(targetMAC);
422 PLOG(PL_ALWAYS, "eth:%s ", targetMAC.GetHostString());
423 }
424 PLOG(PL_ALWAYS, "\n");
425
426 // Build our ARP reply
427 arp.InitIntoBuffer((UINT32*)((void*)ethPkt.AccessPayload()), BUFFER_MAX - 16);
428 arp.SetOpcode(ProtoPktARP::ARP_REP);
429 arp.SetSenderHardwareAddress(cap->GetInterfaceAddr());
430 arp.SetSenderProtocolAddress(targetIP); // target IP from above
431 arp.SetTargetHardwareAddress(senderMAC); // hw addr of requestor
432 arp.SetTargetProtocolAddress(senderIP); // IP addr of requestor
433
434 // Send the reply
435 ethPkt.SetSrcAddr(cap->GetInterfaceAddr());
436 ethPkt.SetDstAddr(srcMacAddr);
437 ethPkt.SetPayloadLength(arp.GetLength());
438
439 numBytes = ethPkt.GetLength();
440 cap->Send((char*)ethBuffer, numBytes); // tbd - check result
441 }
442
443 }
444 } // end while(1)
445
446 } // end ArposerApp::OnInboundPkt
447