1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
// This is a test application for experimenting
// with the NORM API implementation during its
// development. A better-documented and complete
// example of the NORM API usage will be provided
// when the NORM API is more complete.
#include "normApi.h"
#include "protokit.h" // for protolib debug, stuff, etc
#include <stdio.h>
#include <stdlib.h> // for srand()
#ifdef UNIX
#include <unistd.h> // for "sleep()"
#endif // UNIX
int main(int argc, char* argv[])
{
bool send = false;
bool recv = false;
bool cc = false;
bool trace = false;
int debugLevel = 2;
double loss = 0.0;
int sendMax = 3000;//-1; // -1 means unlimited
const char* cmd = NULL;
// 1) Parse command-line options
for (int i = 1; i < argc; i++)
{
if (!strcmp(argv[i], "send"))
{
send = true;
}
else if (!strcmp(argv[i], "recv"))
{
recv = true;
}
else if (!strcmp(argv[i], "cc"))
{
cc = true;
}
else if (!strcmp(argv[i], "trace"))
{
trace = true;
}
else if (!strcmp(argv[i], "debug"))
{
debugLevel = atoi(argv[++i]);
}
else if (!strcmp(argv[i], "loss"))
{
loss = (double)atoi(argv[++i]);
}
else if (!strcmp(argv[i], "smax"))
{
sendMax = atoi(argv[++i]);
}
else if (!strcmp(argv[i], "cmd"))
{
cmd = argv[++i];
}
}
TRACE("loss = %lf\n", loss);
int sendMid = sendMax / 2;
if (!send && !recv)
{
TRACE("normTest: neither 'send' or 'recv' operation was specified?!\n");
TRACE("Usage: normTest {send, recv} [cc]\n");
return -1;
}
bool loopback = (send && recv);
NormInstanceHandle instance = NormCreateInstance();
#ifdef WIN32
const char* cachePath = "C:\\Adamson\\Temp\\cache\\";
#else
const char* cachePath = "/tmp/";
#endif // if/else WIN32/UNIX
NormSetCacheDirectory(instance, cachePath);
// Here's a trick to generate a _hopefully_ unique NormNodeId
// based on an XOR of the system's IP address and the process id.
// (We use ProtoAddress::GetEndIdentifier() to get the local
// "default" IP address for the system)
// (Note that passing "NORM_NODE_ANY" to the last arg of
// NormCreateSession() does a similar thing but without
// the processId XOR ... perhaps we should add the processId
// hack to that default "NORM_NODE_ANY" local NormNodeId picker???
ProtoAddress localAddr;
if (!localAddr.ResolveLocalAddress())
{
fprintf(stderr, "normTest: error resolving local IP address\n");
NormDestroyInstance(instance);
return -1;
}
NormNodeId localId = localAddr.EndIdentifier();
#ifdef WIN32
DWORD processId = GetCurrentProcessId();
#else
pid_t processId = getpid();
#endif // if/else WIN32/UNIX
localId ^= (NormNodeId)processId;
// If needed, permutate to a valid, random NormNodeId
while ((NORM_NODE_ANY == localId) ||
(NORM_NODE_NONE == localId))
{
localId ^= (NormNodeId)rand();
}
//localId = 15; // for testing purposes
// Create a NORM session instance
NormSessionHandle session = NormCreateSession(instance,
"224.1.1.1",
6001,
localId);
//NormSetTOS(session, 0x20);
// NOTE: These are debugging routines available (not for normal app use)
// (IMPORTANT NOTE: On Win32 builds with Norm.dll, this "SetDebugLevel()" has no
// effect on the Protolib instance in the NORM DLL !!!
// (TBD - provide a "NormSetDebugLevel()" function for this purpose!)
SetDebugLevel(debugLevel);
// Option to turn on debug NORM message tracing
NormSetMessageTrace(session, trace);
// Uncomment to turn on some random packet loss
NormSetTxLoss(session, loss);
//NormSetRxLoss(session, 20.0);
struct timeval currentTime;
ProtoSystemTime(currentTime);
// Uncomment to get different packet loss patterns from run to run
// (and a different sender sessionId)
srand(currentTime.tv_sec); // seed random number generator
NormSetGrttEstimate(session, 0.25); // 1 msec initial grtt
NormSetTxRate(session, 5.0e+06); // in bits/second
// Option to enable TCP-friendly congestion control (overrides NormSetTxRate())
if (cc) NormSetCongestionControl(session, true);
NormSetTxRateBounds(session, 5.0e+06, 6.0e+06);
//NormSetDefaultRepairBoundary(session, NORM_BOUNDARY_BLOCK);
// Uncomment to use a _specific_ transmit port number
// (Can be the same as session port (rx port), but this
// is _not_ recommended when unicast feedback may be
// possible!)
//NormSetTxPort(session, 6001);
//NormSetDefaultUnicastNack(session, true);
// Uncomment to allow reuse of rx port
// (This allows multiple "normTest" instances on the same machine
// for the same NormSession - note those instances must use
// unique local NormNodeIds (see NormCreateSession() above).
//NormSetRxPortReuse(session, true);
// Uncomment to receive your own traffic
if (loopback)
NormSetLoopback(session, true);
//NormSetSilentReceiver(session, true);
// Uncomment this line to participate as a receiver
if (recv) NormStartReceiver(session, 1024*1024);
// We use a random "sessionId"
NormSessionId sessionId = (NormSessionId)rand();
if (send) NormStartSender(session, sessionId, 2097152, 1420, 16, 4);
// Uncomment to set large rx socket buffer size
// (might be needed for high rate sessions)
//NormSetRxSocketBuffer(session, 512000);
//NormSetAutoParity(session, 6);
// Uncomment to set large tx socket buffer size
// (might be needed for high rate sessions)
//NormSetTxSocketBuffer(session, 512000);
NormAddAckingNode(session, NORM_NODE_NONE); //15); //NormGetLocalNodeId(session));
NormObjectHandle stream = NORM_OBJECT_INVALID;
#ifdef WIN32
const char* filePath = "C:\\Adamson\\Images\\Art\\giger205.jpg";
#else
const char* filePath = "/home/adamson/images/art/giger/giger205.jpg";
#endif
//const char* filePath = "/home/adamson/pkgs/rh73.tgz";
const char* fileName = "file1.jpg";
const char* fileName2 = "file2.jpg";
// Uncomment this line to send a stream instead of the file
stream = NormStreamOpen(session, 2*1024*1024);
// NORM_FLUSH_PASSIVE automatically flushes full writes to
// the stream.
NormStreamSetAutoFlush(stream, NORM_FLUSH_PASSIVE);
//NormStreamWrite(stream, 0, 0);//txBuffer+txIndex, want);
// Some variable for stream input/output
char txBuffer[8192], rxBuffer[8192];
int txIndex = 0;
int txLen = 0;
int rxIndex = 0;
#define STREAM_MSG_PREFIX_SIZE 1000 // we pad with 'a' character value (the msgPrefix is a prefix)
char msgPrefix[STREAM_MSG_PREFIX_SIZE];
memset(msgPrefix, 'a', STREAM_MSG_PREFIX_SIZE);
bool msgSync = false;
int msgCount = 0;
int recvCount = -1; // used to monitor reliable stream reception
int sendCount = 0;
int fileMax = 1;
NormObjectHandle txFile = NORM_OBJECT_INVALID;
NormEvent theEvent;
bool rxActive = false;
if (NULL != cmd)
NormSendCommand(session, cmd, strlen(cmd) + 1, false);
while (NormGetNextEvent(instance, &theEvent))
{
switch (theEvent.type)
{
case NORM_CC_ACTIVE:
PLOG(PL_INFO, "normTest: NORM_CC_ACTIVE event ...\n");
if (rxActive)
{
break;
}
else
{
rxActive = true;
// assume there is vacancy
}
case NORM_TX_QUEUE_VACANCY:
case NORM_TX_QUEUE_EMPTY:
//if (!rxActive) break;
/*
if (NORM_TX_QUEUE_VACANCY == theEvent.type)
TRACE("NORM_TX_QUEUE_VACANCY ...\n");
else if (NORM_TX_QUEUE_EMPTY == theEvent.type)
TRACE("NORM_TX_QUEUE_EMPTY ...\n");
else
TRACE("writing to stream after CC_ACTIVE\n");
*/
if ((sendMax > 0) && (sendCount >= sendMax))
{
// send "cmd" again at end
if (NULL != cmd)
NormSendCommand(session, cmd, strlen(cmd) + 1, false);
break;
}
//if (NORM_OBJECT_INVALID != theEvent.object)
if (true)
{
// We loop here to keep stream buffer full ....
bool keepWriting = true;
while (keepWriting)
{
if (0 == txLen)
{
memset(txBuffer, 'a', STREAM_MSG_PREFIX_SIZE);
// Write a message into the "txBuffer" for transmission
sprintf(txBuffer+STREAM_MSG_PREFIX_SIZE, " normTest says hello %d ...\n", sendCount);
txLen = strlen(txBuffer);
}
unsigned int want = txLen - txIndex;
unsigned int put = NormStreamWrite(stream, txBuffer+txIndex, want);
if (put != want) keepWriting = false;
txIndex += put;
if (txIndex == txLen)
{
// _Instead_ of "NormStreamSetAutoFlush(stream, NORM_FLUSH_PASSIVE)" above
// _and_ "NormStreamMarkEom()" here, I could have used
// "NormStreamFlush(stream, true)" here to perform explicit flushing
// and EOM marking in one fell swoop. That would be a simpler approach
// for apps where very big stream messages might need to be written with
// multiple calls to "NormStreamWrite()"
NormStreamMarkEom(stream);
txLen = txIndex = 0;
sendCount++;
if ((NULL != cmd) && (sendCount == sendMid))
NormSendCommand(session, cmd, strlen(cmd) + 1, true);
if (0 == (sendCount % 1000))
TRACE("normTest: sender sent %d messages ...\n", sendCount);
if (sendCount == 15)
{
//NormSetWatermark(session, stream);
}
if ((sendMax > 0) && (sendCount >= sendMax))
{
// Uncomment to gracefully shut down the stream
// after "sendMax" messages
TRACE("normTest: sender closing stream ...\n");
NormStreamClose(stream, true);
keepWriting = false;
}
}
} // end while(keepWriting)
}
else if (NORM_OBJECT_INVALID == stream) // we aren't sending a stream
{
if ((fileMax < 0) || (sendCount < fileMax))
{
const char* namePtr = (0 == (sendCount & 0x01)) ? fileName : fileName2;
txFile =
NormFileEnqueue(session,
filePath,
namePtr,
strlen(fileName));
// Repeatedly queue our file for sending
if (NORM_OBJECT_INVALID == txFile)
{
PLOG(PL_ERROR, "normTest: error queuing file: %s\n", filePath);
break;
}
else
{
TRACE("QUEUED FILE ...\n");
sendCount++;
if (sendCount < 2) NormSetWatermark(session, txFile);
}
}
}
break;
case NORM_TX_FLUSH_COMPLETED:
PLOG(PL_INFO, "normTest: NORM_TX_FLUSH_COMPLETED event ...\n");
// This line of code "requeues" the last file sent
// (Good for use with silent receivers ... can repeat transmit object this way)
NormRequeueObject(session, txFile);
break;
case NORM_TX_WATERMARK_COMPLETED:
PLOG(PL_INFO, "normTest: NORM_TX_WATERMARK_COMPLETED event ...\n");
break;
case NORM_TX_CMD_SENT:
PLOG(PL_INFO, "normTest: NORM_TX_CMD_SENT event ...\n");
break;
case NORM_TX_OBJECT_SENT:
PLOG(PL_INFO, "normTest: NORM_TX_WATERMARK_COMPLETED event ...\n");
break;
case NORM_TX_OBJECT_PURGED:
PLOG(PL_INFO, "normTest: NORM_TX_OBJECT_PURGED event ...\n");
break;
case NORM_CC_INACTIVE:
PLOG(PL_INFO, "normTest: NORM_CC_INACTIVE event ...\n");
rxActive = false;
// (TBD) add APIs to delete remote sender's state entirely
// (TBD) add APIs to automate buffer freeing, remote sender managment somewhat
break;
case NORM_REMOTE_SENDER_ACTIVE:
break;
case NORM_REMOTE_SENDER_INACTIVE:
NormNodeFreeBuffers(theEvent.sender); // frees up some memory allocated for this remote sender's state
break;
case NORM_RX_CMD_NEW:
{
char cmdBuffer[8192];
unsigned int cmdLength = 8192;
if (NormNodeGetCommand(theEvent.sender, cmdBuffer, &cmdLength))
{
char addrBuffer[16];
unsigned int addrLength = 16;
if (!NormNodeGetAddress(theEvent.sender, addrBuffer, &addrLength))
PLOG(PL_ERROR, "normTest: error getting sender addr!\n");
ProtoAddress senderAddr;
if (4 == addrLength)
senderAddr.SetRawHostAddress(ProtoAddress::IPv4, addrBuffer, 4);
else if (16 == addrLength)
senderAddr.SetRawHostAddress(ProtoAddress::IPv6, addrBuffer, 16);
cmdBuffer[cmdLength] = '\0';
PLOG(PL_ERROR, "normTest: recvd cmd \"%s\" from sender %s\n",
cmdBuffer, senderAddr.GetHostString());
}
PLOG(PL_INFO, "normTest: NORM_RX_CMD_NEW event ...\n");
break;
}
case NORM_RX_OBJECT_NEW:
PLOG(PL_INFO, "normTest: NORM_RX_OBJECT_NEW event ...\n");
break;
case NORM_RX_OBJECT_INFO:
// Assume info contains '/' delimited <path/fileName> string
if (NORM_OBJECT_FILE == NormObjectGetType(theEvent.object))
{
char fileName[PATH_MAX];
strcpy(fileName, cachePath);
int pathLen = strlen(fileName);
unsigned short nameLen = PATH_MAX - pathLen;
nameLen = NormObjectGetInfo(theEvent.object, fileName+pathLen, nameLen);
fileName[nameLen + pathLen] = '\0';
char* ptr = fileName + 5;
while ('\0' != *ptr)
{
if ('/' == *ptr) *ptr = PROTO_PATH_DELIMITER;
ptr++;
}
if (!NormFileRename(theEvent.object, fileName))
TRACE("normTest: NormSetFileName(%s) error\n", fileName);
PLOG(PL_DEBUG, "normTest: recv'd info for file: %s\n", fileName);
}
break;
case NORM_RX_OBJECT_UPDATED:
{
//TRACE("normTest: NORM_RX_OBJECT_UPDATE event ...\n");
if (NORM_OBJECT_STREAM != NormObjectGetType(theEvent.object))
break;
unsigned int len;
do
{
if (!msgSync)
msgSync = NormStreamSeekMsgStart(theEvent.object);
if (!msgSync) break;
len = 8191 - rxIndex;
if (NormStreamRead(theEvent.object, rxBuffer+rxIndex, &len))
{
rxIndex += len;
rxBuffer[rxIndex] = '\0';
if (rxIndex > 0)
{
// The '\n' indicates we have received an entire message
int parsedLen = 0;
bool searching = true;
char* startPtr = rxBuffer;
while (searching)
{
char* endPtr = strchr(startPtr, '\n');
if (endPtr)
{
// Save sub-string message length
parsedLen += (endPtr - startPtr + 1);
// Validate received message string
if (0 == memcmp(rxBuffer, msgPrefix, STREAM_MSG_PREFIX_SIZE))
{
char* ptr = strstr(startPtr, "hello");
if (ptr)
{
int value;
if (1 == sscanf(ptr, "hello %d", &value))
{
msgCount++; // successful recv
if (recvCount >= 0)
{
if (0 != (value - recvCount))
TRACE("WARNING! possible break? value:%d recvCount:%d\n",
value, recvCount);
}
//else
// TRACE("validated recv msg len:%d\n", len);
recvCount = value+1;
if (0 == msgCount % 1000)
{
TRACE("normTest: recv status> msgCount:%d of total:%d (%lf)\n",
msgCount, recvCount, 100.0*((double)msgCount)/((double)recvCount));
}
}
else
{
TRACE("couldn't find index!? len:%d in %s\n", len, ptr);
ASSERT(0);
}
}
else
{
TRACE("couldn't find \"hello\"!? len:%d in %s\n", len, rxBuffer);
ASSERT(0);
}
}
else
{
TRACE("invalid received message!?\n");
ASSERT(0);
}
if (parsedLen >= rxIndex)
{
rxIndex = 0;
searching = false;
}
else
{
startPtr = rxBuffer + parsedLen;
}
} // end if (endPtr)
else if (parsedLen > 0)
{
memmove(rxBuffer, rxBuffer+parsedLen, rxIndex - parsedLen);
rxIndex -= parsedLen;
searching = false;
}
else
{
searching = false;
}
} // end while(searching)
}
}
else
{
TRACE("normTest: error reading stream\n");
TRACE("normTest: recv status> msgCount:%d of total:%d (%lf)\n",
msgCount, recvCount, 100.0*((double)msgCount)/((double)recvCount));
msgSync = false;
rxIndex = 0;
break;
}
} while (0 != len);
break;
}
case NORM_RX_OBJECT_COMPLETED:
TRACE("normTest: NORM_RX_OBJECT_COMPLETED event ...\n");
TRACE("normTest: recv status> msgCount:%d of total:%d (%lf)\n",
msgCount, recvCount, 100.0*((double)msgCount)/((double)recvCount));
//NormStopReceiver(session);
break;
case NORM_RX_OBJECT_ABORTED:
TRACE("normTest: NORM_RX_OBJECT_ABORTED event ...\n");
break;
case NORM_GRTT_UPDATED:
//TRACE("normTest: NORM_GRTT_UPDATED event ...\n");
break;
default:
TRACE("Got event type: %d\n", theEvent.type);
} // end switch(theEvent.type)
// Uncomment to exit program after sending "sendMax" messages or files
//if ((sendMax > 0) && (sendCount >= sendMax)) break;
} // end while (NormGetNextEvent())
#ifdef WIN32
Sleep(30000);
#else
sleep(30); // allows time for cleanup if we're sending to someone else
#endif // if/else WIN32/UNIX
//NormStreamClose(stream); // stream is already closed in loop above
NormStopReceiver(session);
NormStopSender(session);
NormDestroySession(session);
NormDestroyInstance(instance);
fprintf(stderr, "normTest: Done.\n");
return 0;
} // end main()