arzmq-sys 0.6.3

Low-level bindings to the zeromq library
Documentation
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
// This program replays IP packets from a pcap trace file using a ProtoCap socket
// Note that it needs root privileges to execute

// Usage:  pcapReplay interface <ifaceName> [input <pcapFile>][dst <addr[/<port>]>][src <addr[/<port>]][edst <macAddr>]

// TBD - add option for specific network address translation rules

#include <protoString.h>    // for ProtoTokenator
#include <protoCap.h>       // for ProtoCap
#include <protoNet.h>       
#include <protoPktETH.h>
#include <protoPktIP.h>
#include <protoApp.h>       // base class for command-line app
#include <protoDebug.h>
#include <stdio.h>
#include <pcap.h>

// Maximum supported frame size
#define FRAME_MAX 8192

class PcapReplay : public ProtoApp
{
    public:
        PcapReplay();
        ~PcapReplay();

        // Overrides from ProtoApp or NsProtoSimAgent base
        bool OnStartup(int argc, const char*const* argv);
        bool ProcessCommands(int argc, const char*const* argv);
        void OnShutdown();

    private:
        enum CmdType {CMD_INVALID, CMD_ARG, CMD_NOARG};
        static const char* const CMD_LIST[];
        static CmdType GetCmdType(const char* string);
        bool OnCommand(const char* cmd, const char* val);        
        void Usage();
        bool ParseAddrPort(const char* string, ProtoAddress& addr);
        double ReadFrame();
        void OnTxTimeout(ProtoTimer& theTimer);

        const char*     pcap_file;
        ProtoCap*       tx_cap;
        ProtoTimer      tx_timer;
        ProtoAddress    dst_addr;
        ProtoAddress    dst_mac;
        ProtoAddress    src_addr;
        pcap_t*         pcap_device;
        int             pcap_link_type;
        ProtoTime       last_time;
        UINT32          aligned_buffer[(FRAME_MAX+4)/4];
        void*           ip_buffer;
        UINT16          ip_length;
      
}; // end class PcapReplay

// This macro creates our ProtoApp derived application instance 
PROTO_INSTANTIATE_APP(PcapReplay)
        
PcapReplay::PcapReplay()
 : pcap_file(NULL), tx_cap(NULL), pcap_device(NULL), ip_buffer(NULL), ip_length(0)
   
{       
    tx_timer.SetListener(this, &PcapReplay::OnTxTimeout);
    tx_timer.SetRepeat(-1);
    memset(aligned_buffer, 0, FRAME_MAX+4);
}

PcapReplay::~PcapReplay()
{
}

void PcapReplay::Usage()
{
    fprintf(stderr, "pcapReplay interface <ifaceName> [input <pcapFile>][dst <addr[/<port>]>][edst <dstMac>][src <addr[/<port>]>]\n");
}  // end PcapReplay::Usage()


const char* const PcapReplay::CMD_LIST[] =
{
    "+input",       // <fileName> pcap input file name
    "+interface",   // <ifaceName> interface for transmission
    "+dst",         // <addr[/<port>]> remap packets' destination to given address and optional port
    "+src",         // <addr[/<port>]> remap packets' source to given address and optional port
    "+edst",        // <macAddr>  (colon-delimited)
    NULL
};

PcapReplay::CmdType PcapReplay::GetCmdType(const char* cmd)
{
    if (!cmd) return CMD_INVALID;
    unsigned int len = strlen(cmd);
    bool matched = false;
    CmdType type = CMD_INVALID;
    const char* const* nextCmd = CMD_LIST;
    while (*nextCmd)
    {
        if (!strncmp(cmd, *nextCmd+1, len))
        {
            if (matched)
            {
                // ambiguous command (command should match only once)
                return CMD_INVALID;
            }
            else
            {
                matched = true;
                if ('+' == *nextCmd[0])
                    type = CMD_ARG;
                else
                    type = CMD_NOARG;
            }
        }
        nextCmd++;
    }
    return type;
}  // end PcapReplay::GetCmdType()

bool PcapReplay::ProcessCommands(int argc, const char*const* argv)
{
    // Dispatch command-line commands to our OnCommand() method
    int i = 1;
    while ( i < argc)
    {
        // Is it a class PcapReplay command?
        switch (GetCmdType(argv[i]))
        {
            case CMD_INVALID:
            {
                PLOG(PL_ERROR, "PcapReplay::ProcessCommands() Invalid command:%s\n", 
                        argv[i]);
                return false;
            }
            case CMD_NOARG:
                if (!OnCommand(argv[i], NULL))
                {
                    PLOG(PL_ERROR, "PcapReplay::ProcessCommands() ProcessCommand(%s) error\n", 
                            argv[i]);
                    return false;
                }
                i++;
                break;
            case CMD_ARG:
                if (!OnCommand(argv[i], argv[i+1]))
                {
                    PLOG(PL_ERROR, "PcapReplay::ProcessCommands() ProcessCommand(%s, %s) error\n", 
                            argv[i], argv[i+1]);
                    return false;
                }
                i += 2;
                break;
        }
    }
    return true;
}  // end PcapReplay::ProcessCommands()

bool PcapReplay::ParseAddrPort(const char* string, ProtoAddress& addr)
{
    ProtoTokenator tk(string, '/');
    const char* token = tk.GetNextItem();
    if (!addr.ResolveFromString(token))
    {
        PLOG(PL_ERROR, "pcapReplay error: invalid address: %s\n", token);
        return false;
    }
    token = tk.GetNextItem();
    if (NULL != token)
    {
        UINT16 port;
        if (1 != sscanf(token, "%hu", &port))
        {
            PLOG(PL_ERROR, "pcapReplay error: invalid port: %s\n", token);
            return false;
        }
        addr.SetPort(port);
    }
    else
    {
        addr.SetPort(0);
    }
    return true;
}  // end PcapReplay::ParseAddrPort()

bool PcapReplay::OnCommand(const char* cmd, const char* val)
{
    // (TBD) move command processing into Mgen class ???
    CmdType type = GetCmdType(cmd);
    ASSERT(CMD_INVALID != type);
    unsigned int len = strlen(cmd);
    if ((CMD_ARG == type) && !val)
    {
        PLOG(PL_ERROR, "PcapReplay::ProcessCommand(%s) missing argument\n", cmd);
        return false;
    }
    else if (!strncmp("input", cmd, len))
    {
        pcap_file = val;
    }
    else if (!strncmp("interface", cmd, len))
    {
        // Make sure "val" is a valid interface name
        int ifIndex = ProtoNet::GetInterfaceIndex(val);
        char ifName[256];
        ifName[255] = '\0';
        if (!ProtoNet::GetInterfaceName(ifIndex, ifName, 255))
        {
            PLOG(PL_ERROR, "pcapReplay: invalid <interfaceName>\n");
            return false;
        }
        if (NULL == tx_cap)
        {
            if (NULL == (tx_cap = ProtoCap::Create()))
            {
                PLOG(PL_ERROR, "pcapReplay: new ProtoCap error: %s\n", GetErrorString());
                return false;
            }
        } else if (tx_cap->IsOpen())
        {
            tx_cap->Close();
        }
        if (!tx_cap->Open(ifName))
        {
            PLOG(PL_ERROR, "pcapReplay: ProtoCap::Open() error.\n");
            return false;   
        }
    }
    else if (!strncmp("dst", cmd, len))
    {
        if (!ParseAddrPort(val, dst_addr)) 
        {
            PLOG(PL_ERROR, "pcapReplay error: invalid destination address: \"%s\"\n", val);
            return false;
        }
    }
    else if (!strncmp("edst", cmd, len))
    {
        if (!dst_mac.ResolveEthFromString(val))
        {
            PLOG(PL_ERROR, "pcapReplay error: invalid mac address: \"%s\"\n", val);
            return false;
        }
    }
    else if (!strncmp("src", cmd, len))
    {
        if (!ParseAddrPort(val, src_addr))
        {
            PLOG(PL_ERROR, "pcapReplay error: invalid source address: \"%s\"\n", val);
            return false;
        }
    }
    else
    {
        PLOG(PL_ERROR, "pcapReplay:: invalid command\n");
        return false;
    }
    return true;
}  // end PcapReplay::OnCommand()

bool PcapReplay::OnStartup(int argc, const char*const* argv)
{
    if (!ProcessCommands(argc, argv))
    {
        PLOG(PL_ERROR, "protoCapExample: Error! bad command line\n");
        return false;
    }
    if (NULL == tx_cap)
    {
        PLOG(PL_ERROR, "pcapReplay error: no transmit 'interface' specified?!\n");
        Usage();
        return false;
    }
    FILE* infile = stdin;  // by default
    if (NULL != pcap_file)
    {
        if (NULL == (infile = fopen(pcap_file, "r")))
        {
            PLOG(PL_ERROR, "pcapReplay error: invalid pcap file \"%s\"\n", pcap_file);
            return false;
        }
    }
    char pcapErrBuf[PCAP_ERRBUF_SIZE+1];
    pcapErrBuf[PCAP_ERRBUF_SIZE] = '\0';
    pcap_device = pcap_fopen_offline(infile, pcapErrBuf);
    if (NULL == pcap_device)
    {
        fprintf(stderr, "pcap2mgen: pcap_fopen_offline() error: %s\n", pcapErrBuf);
        if (stdin != infile) fclose(infile);
        return false;
    }
    pcap_link_type = pcap_datalink(pcap_device);
    tx_timer.SetInterval(0.0);
    ActivateTimer(tx_timer);
    return true;
}  // end PcapReplay::OnStartup()


double PcapReplay::ReadFrame()
{
    // TBD - read/buffer next pcap item and set interval timer
    pcap_pkthdr hdr;
    const u_char* pktData;
    // TBD - make this a loop to seek IP packets?
    if (NULL != (pktData = pcap_next(pcap_device, &hdr)))
    {
        if (hdr.len > hdr.caplen)
        {
            PLOG(PL_ERROR, "pcapRelay error: pcap snap length was too small!\n");
            return -1.0;
        }
        unsigned int numBytes = hdr.caplen;
        if (numBytes > FRAME_MAX)
        {
            PLOG(PL_ERROR, "pcapRelay error: encountered oversized frame length  %u\n", numBytes);
            return -1.0;
        }
        if (DLT_LINUX_SLL == pcap_link_type)
        {
             memcpy(aligned_buffer, pktData, numBytes);
             ip_buffer = aligned_buffer + 4;  // assumes 16-byte header (i.e. 6-byte link address on SLL frame)
             ip_length = numBytes - 16;
        }
        else  // assume DLT_EN10MB
        {
            UINT16* ethBuffer = ((UINT16*)aligned_buffer) + 1; 
            memcpy(ethBuffer, pktData, numBytes);
            ProtoPktETH ethPkt(ethBuffer, FRAME_MAX);
            if (!ethPkt.InitFromBuffer(hdr.len))
            {
                fprintf(stderr, "pcapRelay error: invalid Ether frame in pcap file\n");
                return -1.0;
            }    
            ip_buffer = ethPkt.AccessPayload();
            ip_length = ethPkt.GetPayloadLength();
        }
        // Now determine interval for tx_timer
        ProtoTime thisTime(hdr.ts);
        double interval;
        if (last_time.IsValid())
        {
            interval = ProtoTime::Delta(thisTime, last_time);
            if (interval < 0.0)
            {
                PLOG(PL_WARN, "pcapRelay warning: negative pcap interval detected?!\n");
                interval = 0.0;
            }
        }
        else
        {
            interval = 0.0;  // first frame
        }
        last_time = thisTime;
        return interval;
    }
    else
    {
        // end of pcap input reached
        return -1.0;
    }
    
}  // end PcapRelay::ReadFrame()

void PcapReplay::OnTxTimeout(ProtoTimer& theTimer)
{
    if (0 != ip_length)
    {
        ProtoPktIP ipPkt;
        if (ipPkt.InitFromBuffer(ip_length, ip_buffer, ip_length))
        {
            if (dst_addr.IsValid())
                ipPkt.SetDstAddr(dst_addr);
            // TBD - support port number translation
            if (0 != dst_addr.GetPort())
                PLOG(PL_WARN, "pcapRelay warning: port translation not yet supported!\n");
            if (src_addr.IsValid())
                ipPkt.SetSrcAddr(src_addr);
            if (0 != src_addr.GetPort())
                PLOG(PL_WARN, "pcapRelay warning: port translation not yet supported!\n");
            // Fix UDP checksum  
            ProtoPktIP::Protocol protocol;
            switch (ipPkt.GetVersion())
            {
                case 4:
                {
                    ProtoPktIPv4 ip4Pkt(ipPkt);
                    protocol = ip4Pkt.GetProtocol();;
                    break;
                }
                case 6:
                {
                    ProtoPktIPv6 ip6Pkt(ipPkt);
                    protocol = ip6Pkt.GetNextHeader();;
                    break;
                }
                default:
                    PLOG(PL_WARN, "pcapRelay warning: unknown IP version!\n");
                    protocol = ProtoPktIP::RESERVED;
                    break;
            }
            if (ProtoPktIP::UDP == protocol)
            {
                ProtoPktUDP udpPkt;
                if (udpPkt.InitFromPacket(ipPkt))
                    udpPkt.FinalizeChecksum(ipPkt);
                else
                    PLOG(PL_WARN, "pcapRelay warning: invalid UDP packet?!\n");
            }
                
            // Set appropriate Ethernet header
            UINT16* ethBuffer = (UINT16*)ip_buffer - 7;
            ProtoPktETH ethPkt(ethBuffer, ip_length + 14);
            ethPkt.SetDstAddr(dst_mac);
            ethPkt.SetType(ProtoPktETH::IP);
            ethPkt.SetPayloadLength(ip_length);
            unsigned int numBytes = ethPkt.GetLength();
            if (!tx_cap->Forward((char*)ethPkt.GetBuffer(), numBytes))
            {
                PLOG(PL_ERROR, "pcapRelay error: unable to forward frame!\n");
            }
        }
        else
        {
            PLOG(PL_ERROR, "pcapRelay error: bad IP packet!\n");
        }
    }
    double interval = ReadFrame();  // read next pcap frame
    if (interval < 0.0)
        Stop();
    else
        theTimer.SetInterval(interval);
}  // end PcapReplay::OnTxTimeout()

void PcapReplay::OnShutdown()
{
    if (tx_timer.IsActive()) tx_timer.Deactivate();
    if (NULL != tx_cap)
    {
        tx_cap->Close();
        delete tx_cap;
        tx_cap = NULL;
    }
    if (NULL != pcap_device)
    {
        pcap_close(pcap_device);
        pcap_device = NULL;
    }
    PLOG(PL_ERROR, "PcapReplay: Done.\n"); 
    CloseDebugLog();
}  // end PcapReplay::OnShutdown()