Debian Codegraph @

protolib/examples/join.cpp

raw
1
2 #include "protoApp.h"
3 #include "protoCap.h"
4
5 #include "protoPktETH.h"
6 #include "protoPktIP.h"
7 #include "protoPktIGMP.h"
8 #include "protoAddress.h"
9 #include "protoString.h" // for ProtoTokenator
10 #include "protoNet.h"
11
12 #include <stdlib.h> // for atoi(), rand(), RAND_MAX
13 #include <stdio.h> // for stdout/stderr printouts
14 #include <string.h>
15 #include <math.h> // for log()
16
17 /**
18 * @class JoinApp
19 *
20 * @brief This example sends repeating IGMP JOIN messages on a specified
21 * interface for a set of IP multicast group addresses.
22 *
23 * Usage:
24 * join [interval <sec>] interface <interfaceName> <group1>[,<group2>,<group2> ...]
25 */
26 class JoinApp : public ProtoApp
27 {
28 public:
29 JoinApp();
30 ~JoinApp();
31
32 // Overrides from ProtoApp or NsProtoSimAgent base
33 bool OnStartup(int argc, const char*const* argv);
34 bool ProcessCommands(int argc, const char*const* argv);
35 void OnShutdown();
36
37 static double ExponentialRand(double mean)
38 {return(-log(((double)rand())/((double)RAND_MAX))*mean);}
39
40 private:
41
42 enum {STRETCH_MAX = 4};
43
44 enum CmdType {CMD_INVALID, CMD_ARG, CMD_NOARG};
45 static const char* const CMD_LIST[];
46 static CmdType GetCmdType(const char* string);
47 bool OnCommand(const char* cmd, const char* val);
48 void Usage();
49
50 bool OnIgmpTimeout(ProtoTimer& theTimer);
51
52 //char iface_name[64];
53 ProtoCap* proto_cap;
54 ProtoAddress iface_addr;
55 UINT16 ip_id;
56
57 ProtoTimer igmp_timer;
58 double join_interval; // Average group join interval
59
60 ProtoAddressList group_list;
61 unsigned int group_count;
62 ProtoAddressList::Iterator group_iterator;
63
64 }; // end class JoinApp
65
66 // This macro creates our ProtoApp derived application instance
67 PROTO_INSTANTIATE_APP(JoinApp)
68
69 JoinApp::JoinApp()
70 : proto_cap(NULL), ip_id(0), join_interval(10.0), group_count(0), group_iterator(group_list)
71
72 {
73 igmp_timer.SetListener(this, &JoinApp::OnIgmpTimeout);
74 igmp_timer.SetInterval(0.0); // Interval will be dynamically adjusted on timeouts
75 igmp_timer.SetRepeat(-1);
76 }
77
78 JoinApp::~JoinApp()
79 {
80 }
81
82 void JoinApp::Usage()
83 {
84 fprintf(stderr, "join [interval <sec>] interface <interfaceName> <group1>[,<group2>,<group2> ...]\n");
85 } // end JoinApp::Usage()
86
87
88 const char* const JoinApp::CMD_LIST[] =
89 {
90 "+interface", // recv raw packets on given interface name
91 "+interval", // average IGMP JOIN interval
92 "+join",
93 NULL
94 };
95
96 JoinApp::CmdType JoinApp::GetCmdType(const char* cmd)
97 {
98 if (!cmd) return CMD_INVALID;
99 unsigned int len = strlen(cmd);
100 bool matched = false;
101 CmdType type = CMD_INVALID;
102 const char* const* nextCmd = CMD_LIST;
103 while (*nextCmd)
104 {
105 if (!strncmp(cmd, *nextCmd+1, len))
106 {
107 if (matched)
108 {
109 // ambiguous command (command should match only once)
110 return CMD_INVALID;
111 }
112 else
113 {
114 matched = true;
115 if ('+' == *nextCmd[0])
116 type = CMD_ARG;
117 else
118 type = CMD_NOARG;
119 }
120 }
121 nextCmd++;
122 }
123 return type;
124 } // end JoinApp::GetCmdType()
125
126 bool JoinApp::ProcessCommands(int argc, const char*const* argv)
127 {
128 // Dispatch command-line commands to our OnCommand() method
129 int i = 1;
130 while ( i < argc)
131 {
132 // Is it a class JoinApp command?
133 switch (GetCmdType(argv[i]))
134 {
135 case CMD_INVALID:
136 {
137 // Assume it's a group address
138 return OnCommand("join", argv[i]);
139 }
140 case CMD_NOARG:
141 if (!OnCommand(argv[i], NULL))
142 {
143 PLOG(PL_ERROR, "JoinApp::ProcessCommands() ProcessCommand(%s) error\n",
144 argv[i]);
145 return false;
146 }
147 i++;
148 break;
149 case CMD_ARG:
150 if (!OnCommand(argv[i], argv[i+1]))
151 {
152 PLOG(PL_ERROR, "JoinApp::ProcessCommands() ProcessCommand(%s, %s) error\n",
153 argv[i], argv[i+1]);
154 return false;
155 }
156 i += 2;
157 break;
158 }
159 }
160 return true;
161 } // end JoinApp::ProcessCommands()
162
163 bool JoinApp::OnCommand(const char* cmd, const char* val)
164 {
165 CmdType type = GetCmdType(cmd);
166 ASSERT(CMD_INVALID != type);
167 unsigned int len = strlen(cmd);
168 if ((CMD_ARG == type) && !val)
169 {
170 fprintf(stderr, "join::command \"%s\" missing argument\n", cmd);
171 return false;
172 }
173 else if (!strncmp("interface", cmd, len))
174 {
175 // Make sure "val" is an interface name
176 int ifIndex = ProtoSocket::GetInterfaceIndex(val);
177 char ifName[256];
178
179 ifName[255] = '\0';
180 if (!ProtoSocket::GetInterfaceName(ifIndex, ifName, 255))
181 {
182 fprintf(stderr, "join: invalid <interfaceName>\n");
183 return false;
184 }
185 if (!ProtoNet::GetInterfaceAddress(ifName, ProtoAddress::IPv4, iface_addr))
186 {
187 fprintf(stderr, "join error: interface %s has no IP address!\n", ifName);
188 return false;
189 }
190 if (!proto_cap->Open(ifName))
191 {
192 fprintf(stderr, "join: ProtoCap::Open() error: %s\n", GetErrorString());
193 return false;
194 }
195 //strncpy(iface_name, ifName, 64);
196 //iface_name[63] = '\0';
197 if (group_count > 0) ActivateTimer(igmp_timer);
198 }
199 else if (!strncmp("interval", cmd, len))
200 {
201 float interval;
202 if (1 != scanf(val, "%f", &interval))
203 {
204 fprintf(stderr, "join error: invalid \"interval\" value\n");
205 Usage();
206 return false;
207 }
208 join_interval = interval;
209 if (igmp_timer.IsActive())
210 {
211 double scaledInterval = join_interval / (double)group_count;
212 double nextInterval;
213 do
214 {
215 nextInterval = ExponentialRand(scaledInterval);
216 } while (nextInterval > STRETCH_MAX*scaledInterval);
217 double elapsed = igmp_timer.GetInterval() - igmp_timer.GetTimeRemaining();
218 if (elapsed > nextInterval)
219 igmp_timer.SetInterval(0.0);
220 else
221 igmp_timer.SetInterval(nextInterval - elapsed);
222 igmp_timer.Reschedule();
223 }
224 }
225 else if (!strncmp("join", cmd, len))
226 {
227 ProtoTokenator tk(val, ',');
228 const char* addrText;
229 while (NULL != (addrText = tk.GetNextItem()))
230 {
231 ProtoAddress groupAddr;
232 if (!groupAddr.ConvertFromString(addrText))
233 {
234 fprintf(stderr, "join error: invalid IP address: %s\n", addrText);
235 Usage();
236 return false;
237 }
238 else if (!groupAddr.IsMulticast())
239 {
240 fprintf(stderr, "join error: invalid multicast address: %s\n", addrText);
241 Usage();
242 return false;
243 }
244 group_list.Insert(groupAddr);
245 group_count++;
246 if (igmp_timer.IsActive())
247 {
248 // Join new group immediately
249 igmp_timer.SetInterval(0.0);
250 igmp_timer.Reschedule();
251 }
252 else if (proto_cap->IsOpen())
253 {
254 ActivateTimer(igmp_timer);
255 }
256 }
257 }
258 else
259 {
260 fprintf(stderr, "join: invalid command\n");
261 return false;
262 }
263 return true;
264 } // end JoinApp::OnCommand()
265
266
267 bool JoinApp::OnStartup(int argc, const char*const* argv)
268 {
269 // Create out proto_cap instance and initialize ...
270 if (!(proto_cap = ProtoCap::Create()))
271 {
272 fprintf(stderr, "join: new ProtoCap error: %s\n", GetErrorString());
273 return false;
274 }
275
276 if (!ProcessCommands(argc, argv))
277 {
278 //fprintf(stderr, "join error: bad command line\n");
279 return false;
280 }
281
282 if ((0 == group_count) || (!proto_cap->IsOpen()))
283 {
284 fprintf(stderr, "join: missing required command-line parameter(s)\n");
285 Usage();
286 return false;
287 }
288
289 return true;
290 } // end JoinApp::OnStartup()
291
292 void JoinApp::OnShutdown()
293 {
294 if (igmp_timer.IsActive())
295 igmp_timer.Deactivate();
296 group_list.Destroy();
297 if (NULL != proto_cap)
298 {
299 proto_cap->Close();
300 delete proto_cap;
301 proto_cap = NULL;
302 }
303 } // end JoinApp::OnShutdown()
304
305 bool JoinApp::OnIgmpTimeout(ProtoTimer& /*theTimer*/)
306 {
307 ProtoAddress groupAddr;
308 if (!group_iterator.GetNextAddress(groupAddr))
309 {
310 group_iterator.Reset();
311 group_iterator.GetNextAddress(groupAddr);
312 }
313 ASSERT(groupAddr.IsValid());
314 ASSERT(groupAddr.IsMulticast());
315
316
317 // Build up an IGMP/IP/ETH frame to send
318 const int BUFFER_MAX = 4096;
319 const int ETH_MAX = BUFFER_MAX - 2;
320 UINT32 alignedBuffer[BUFFER_MAX/sizeof(UINT32)];
321 // offset by 2-bytes so IP content will be 32-bit aligned
322 UINT16* ethBuffer = ((UINT16*)alignedBuffer) + 1;
323 ProtoPktETH ethPkt((UINT32*)ethBuffer, ETH_MAX); // TBD - suppress warning here
324
325 // Set Ethernet destination MAC addr to IGMP addr (224.0.0.22)
326 ProtoAddress igmpAddr;
327 igmpAddr.ConvertFromString("224.0.0.22");
328 ProtoAddress igmpMacAddr;
329 igmpMacAddr.GetEthernetMulticastAddress(igmpAddr);
330
331 ethPkt.SetDstAddr(igmpMacAddr);
332 ethPkt.SetType(ProtoPktETH::IP);
333
334 const int IP_MAX = ETH_MAX - 14;
335 UINT32* ipBuffer = alignedBuffer + 4; // 16-byte offset given the 2-byte ethBuffer offset
336 ProtoPktIPv4 ipPkt;
337 ipPkt.InitIntoBuffer(ipBuffer, IP_MAX);
338 ipPkt.SetTOS(0);
339 ipPkt.SetID(ip_id++);
340 ipPkt.SetTTL(1);
341 ipPkt.SetProtocol(ProtoPktIP::IGMP);
342 ipPkt.SetSrcAddr(iface_addr);
343 ipPkt.SetDstAddr(igmpAddr);
344
345 // Generate an IGMPv3 group join message (TBD - make version configurable?)
346 ProtoPktIGMP igmpMsg(ipPkt.AccessPayload(), IP_MAX - 20);
347 igmpMsg.InitIntoBuffer(ProtoPktIGMP::REPORT_V3, 3);
348 ProtoPktIGMP::GroupRecord groupRecord;
349 igmpMsg.AttachGroupRecord(groupRecord);
350 groupRecord.SetType(ProtoPktIGMP::GroupRecord::CHANGE_TO_EXCLUDE_MODE);
351 groupRecord.SetGroupAddress(&groupAddr);
352 igmpMsg.AppendGroupRecord(groupRecord);
353
354 ipPkt.SetPayloadLength(igmpMsg.GetLength());
355
356 ethPkt.SetPayloadLength(ipPkt.GetLength());
357
358 // Now send the IGMP/IP/Ethernet frame
359
360 unsigned int numBytes = ethPkt.GetLength();
361 proto_cap->Send(ethPkt.GetBuffer(), numBytes);
362
363 //TRACE("sending JOIN for group %s ...\n", groupAddr.GetHostString());
364
365 // Schedule next timeout
366 double scaledInterval = join_interval / (double)group_count;
367 double nextInterval;
368 do
369 {
370 nextInterval = ExponentialRand(scaledInterval);
371 } while (nextInterval > STRETCH_MAX*scaledInterval);
372 igmp_timer.SetInterval(nextInterval);
373
374 return true;
375 } // end JoinApp::OnIgmpTimeout()
376