File: test_request.cc

package info (click to toggle)
xorp 1.8.5-4
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 28,560 kB
  • ctags: 54,995
  • sloc: cpp: 397,204; sh: 17,490; ansic: 17,029; python: 7,643; lex: 1,632; yacc: 1,474; awk: 956; makefile: 251; perl: 217; sed: 33
file content (462 lines) | stat: -rw-r--r-- 11,523 bytes parent folder | download | duplicates (3)
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
// -*- c-basic-offset: 4; tab-width: 8; indent-tabs-mode: t -*-

// Copyright (c) 2001-2011 XORP, Inc and Others
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License, Version 2, June
// 1991 as published by the Free Software Foundation. Redistribution
// and/or modification of this program under the terms of any other
// version of the GNU General Public License is not permitted.
// 
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For more details,
// see the GNU General Public License, Version 2, a copy of which can be
// found in the XORP LICENSE.gpl file.
// 
// XORP Inc, 2953 Bunker Hill Lane, Suite 204, Santa Clara, CA 95054, USA;
// http://xorp.net





#include "rip_module.h"
#include "libxorp/xlog.h"

#include "libxorp/c_format.hh"
#include "libxorp/eventloop.hh"
#include "libxorp/ipv4.hh"
#include "libxorp/ipv4net.hh"

#include "auth.hh"
#include "port.hh"
#include "peer.hh"
#include "route_db.hh"
#include "system.hh"

#include "test_utils.hh"

#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif

///////////////////////////////////////////////////////////////////////////////
//
// Constants
//

static const char *program_name         = "test_request";
static const char *program_description  = "Test RIP handling route requests";
static const char *program_version_id   = "0.1";
static const char *program_date         = "July, 2003";
static const char *program_copyright    = "See file LICENSE";
static const char *program_return_value = "0 on success, 1 if test error, 2 if internal error";


// ----------------------------------------------------------------------------
// Spoof Port that supports just a single Peer
//

template <typename A>
class SpoofPort : public Port<A> {
public:
    SpoofPort(PortManagerBase<A>& pm, A addr) : Port<A>(pm)
    {
	this->_peers.push_back(new Peer<A>(*this, addr));
	verbose_log("Constructing SpoofPort instance\n");
	this->set_enabled(true);
    }
    ~SpoofPort()
    {
	verbose_log("Destructing SpoofPort instance\n");
	while (this->_peers.empty() == false) {
	    delete this->_peers.front();
	    this->_peers.pop_front();
	}
    }
};


// ----------------------------------------------------------------------------
// Type specific helpers

template <typename A>
struct DefaultPeer {
    static A get();
};

template <>
IPv4 DefaultPeer<IPv4>::get() { return IPv4("10.0.0.1"); }

template <>
IPv6 DefaultPeer<IPv6>::get() { return IPv6("10::1"); }

// ----------------------------------------------------------------------------
// Spoof Port Manager instance support a single Spoof Port which in turn
// contains a single Peer.
//

template <typename A>
class SpoofPortManager : public PortManagerBase<A> {
public:
    SpoofPortManager(System<A>& s, const IfMgrIfTree& iftree)
	: PortManagerBase<A>(s, iftree)
    {
	this->_ports.push_back(new SpoofPort<A>(*this, DefaultPeer<A>::get()));
    }

    ~SpoofPortManager()
    {
	while (!this->_ports.empty()) {
	    delete this->_ports.front();
	    this->_ports.pop_front();
	}
    }

    Port<A>* the_port()
    {
	XLOG_ASSERT(this->_ports.size() == 1);
	return this->_ports.front();
    }

    Peer<A>* the_peer()
    {
	XLOG_ASSERT(this->_ports.size() == 1);
	XLOG_ASSERT(this->_ports.front()->peers().size() == 1);
	return this->_ports.front()->peers().front();
    }
};

// ----------------------------------------------------------------------------
// Test PortIO class

template <typename A>
class SpoofPortIO : public PortIOBase<A>
{
public:
    typedef A			Addr;
    typedef PortIOUserBase<A>	PortIOUser;

public:
    SpoofPortIO(PortIOUserBase<A>& user)
	: PortIOBase<A>(user, "if0", "vif0", IPv4("10.0.0.1"))
    {
	last_rip_send_flush();
    }

    /**
     * Called by RIP Port instance.
     */
    bool send(const Addr&    addr,
	      uint16_t	     port,
	      const vector<uint8_t>& rip_packet)
    {
	_lo_addr = addr;
	_lo_port = port;
	_lo_data = rip_packet;
	_pending = true;
	return true;
    }

    bool pending() const
    {
	return _lo_port != 0;
    }

    const Addr&	last_rip_send_addr() const		{ return _lo_addr; }
    uint16_t	last_rip_send_port() const		{ return _lo_port; }
    const vector<uint8_t>& last_rip_send_data() const	{ return _lo_data; }

    void last_rip_send_flush()
    {
	_lo_addr = A::ZERO();
	_lo_port = 0;
	_lo_data.resize(0);
	_pending = false;
    }

private:
    vector<uint8_t>	_lo_data;
    Addr		_lo_addr;
    uint16_t		_lo_port;
    bool		_pending;
};


static const IPv4	REQUESTING_HOST = IPv4("10.0.100.1");
static const uint16_t	REQUESTING_PORT = 1092;
static const uint8_t	ROUTE_COST	= 5;

static const IfMgrIfTree ift_dummy = IfMgrIfTree();

class RequestPacketTester {
public:
    static const uint32_t INJECTED_ROUTES  = 10;
    static const uint32_t REQUESTED_ROUTES = 25;

public:
    RequestPacketTester() : _e(), _rip_system(_e), _pm(_rip_system, ift_dummy)
    {
	_portio	= new SpoofPortIO<IPv4>(*_pm.the_port());
	_pm.the_port()->set_io_handler(_portio, false);
	_portio->set_enabled(true);
    }

    ~RequestPacketTester()
    {
	_portio->set_enabled(false);
	delete _portio;
	RouteDB<IPv4>& rdb = _rip_system.route_db();
	rdb.flush_routes();
    }

    bool init_nets()
    {
	string ifname, vifname;		// XXX: not set, because not needed

	RouteDB<IPv4>& rdb = _rip_system.route_db();
	make_nets(_testnets, REQUESTED_ROUTES);

	set<IPv4Net>::const_iterator n = _testnets.begin();
	for (uint32_t i = 0; i < INJECTED_ROUTES; i++) {
	    if (rdb.update_route(*n, IPv4::ZERO(), ifname, vifname, ROUTE_COST,
				 0, _pm.the_peer(), PolicyTags(),
				 false) == false) {
		verbose_log("Failed to add route for %s\n",
			    n->str().c_str());
		return false;
	    }
	    n++;
	}
	return true;
    }

    bool
    send_rip_route_queries()
    {
	vector<uint8_t> buf;
	buf.resize(RipPacketHeader::SIZE +
		   REQUESTED_ROUTES * PacketRouteEntry<IPv4>::size());

	RipPacketHeaderWriter rph(&buf[0]);
	rph.initialize(RipPacketHeader::REQUEST, 2);

	set<IPv4Net>::const_iterator n = _testnets.begin();
	for (uint32_t i = 0; i < REQUESTED_ROUTES; i++) {
	    XLOG_ASSERT(n != _testnets.end());
	    uint32_t offset = RipPacketHeader::SIZE +
		i * PacketRouteEntry<IPv4>::size();

	    PacketRouteEntryWriter<IPv4> pre(&(buf[offset]));

	    pre.initialize(0, *n, IPv4::ZERO(), 0);
	    n++;
	}
	XLOG_ASSERT(_pm.the_port() != 0);
	_pm.the_port()->port_io_receive(REQUESTING_HOST, REQUESTING_PORT,
					&(buf[0]), buf.size());
	return true;
    }

    bool
    check_response()
    {
	if (_portio->pending() == false) {
	    verbose_log("No response packet sent by rip\n");
	    return false;
	}
	if (_portio->last_rip_send_addr() != REQUESTING_HOST) {
	    verbose_log("Response was not sent to originator\n");
	    return false;
	}
	if (_portio->last_rip_send_port() != REQUESTING_PORT) {
	    verbose_log("Response was not sent to originators port\n");
	    return false;
	}

	const vector<uint8_t> buf = _portio->last_rip_send_data();

	// Validate RIP packet header
	const RipPacketHeader rph(&buf[0]);

	if (rph.valid_command() == false) {
	    verbose_log("Invalid command\n");
	    return false;
	}

	if (rph.valid_version(RipPacketHeader::IPv4_VERSION) == false) {
	    verbose_log("Invalid version\n");
	    return false;
	}

	if (rph.valid_padding() == false) {
	    verbose_log("Invalid padding\n");
	    return false;
	}

	if (rph.command() != RipPacketHeader::RESPONSE) {
	    verbose_log("Not a response packet\n");
	    return false;
	}

	// Validate entries
	const uint8_t* pre_ptr = &buf[0] + RipPacketHeader::size();
	uint32_t n_entries = buf.size() / PacketRouteEntry<IPv4>::size() - 1;

	if (n_entries > _testnets.size()) {
	    verbose_log("Got more routes than requested (%u > %u).\n",
			XORP_UINT_CAST(n_entries),
			XORP_UINT_CAST(_testnets.size()));
	    return false;
	}

	set<IPv4Net>::const_iterator ni = _testnets.begin();

	for (uint32_t i = 0; i < n_entries;
	     i++, pre_ptr += PacketRouteEntry<IPv4>::size()) {
	    const PacketRouteEntry<IPv4> pre(pre_ptr);
	    verbose_log("%s %s %u %u\n",
			pre.net().str().c_str(),
			pre.nexthop().str().c_str(),
			XORP_UINT_CAST(pre.metric()),
			pre.tag());
	    if (pre.addr_family() != PacketRouteEntry<IPv4>::ADDR_FAMILY) {
		verbose_log("Invalid address family in route entry %u\n",
			    XORP_UINT_CAST(i));
		return false;
	    }
	    if (*ni != pre.net()) {
		verbose_log("Mismatched net in route entry %u\n",
			    XORP_UINT_CAST(i));
		return false;
	    }
	    if (i < INJECTED_ROUTES) {
		if (pre.metric() != ROUTE_COST) {
		    verbose_log("Metric changed.\n");
		    return false;
		}
	    } else {
		if (pre.metric() != RIP_INFINITY) {
		    verbose_log("Non-existant route with finite metric??\n");
		}
	    }
	    ni++;
	}
	return true;
    }

    int run_test()
    {
	if (init_nets() == false) {
	    return -1;
	}

	bool start_test = false;
	XorpTimer d = _e.set_flag_after_ms(1 * 1000, &start_test);
	while (start_test == false) {
	    _e.run();
	}

	if (send_rip_route_queries() == false) {
	    return -1;
	}

	if (check_response() == false) {
	    return -1;
	}
	return 0;
    }

protected:
    EventLoop			_e;
    System<IPv4>		_rip_system;
    SpoofPortManager<IPv4>	_pm;
    SpoofPortIO<IPv4>*		_portio;
    set<IPv4Net>		_testnets;
};


/**
 * Print program info to output stream.
 *
 * @param stream the output stream the print the program info to.
 */
static void
print_program_info(FILE *stream)
{
    fprintf(stream, "Name:          %s\n", program_name);
    fprintf(stream, "Description:   %s\n", program_description);
    fprintf(stream, "Version:       %s\n", program_version_id);
    fprintf(stream, "Date:          %s\n", program_date);
    fprintf(stream, "Copyright:     %s\n", program_copyright);
    fprintf(stream, "Return:        %s\n", program_return_value);
}

/*
 * Print program usage information to the stderr.
 *
 * @param progname the name of the program.
 */
static void
usage(const char* progname)
{
    print_program_info(stderr);
    fprintf(stderr, "usage: %s [-v] [-h]\n", progname);
    fprintf(stderr, "       -h          : usage (this message)\n");
    fprintf(stderr, "       -v          : verbose output\n");
}

int
main(int argc, char* const argv[])
{
    //
    // Initialize and start xlog
    //
    xlog_init(argv[0], NULL);
    xlog_set_verbose(XLOG_VERBOSE_LOW);         // Least verbose messages
    // XXX: verbosity of the error messages temporary increased
    xlog_level_set_verbose(XLOG_LEVEL_ERROR, XLOG_VERBOSE_HIGH);
    xlog_add_default_output();
    xlog_start();

    int ch;
    while ((ch = getopt(argc, argv, "hv")) != -1) {
        switch (ch) {
        case 'v':
            set_verbose(true);
            break;
        case 'h':
        case '?':
        default:
            usage(argv[0]);
            xlog_stop();
            xlog_exit();
            if (ch == 'h')
                return (0);
            else
                return (1);
        }
    }
    argc -= optind;
    argv += optind;

    int rval = 0;
    XorpUnexpectedHandler x(xorp_unexpected_handler);
    try {
	RequestPacketTester rpt;
	rval = rpt.run_test();
    } catch (...) {
        // Internal error
        xorp_print_standard_exceptions();
        rval = 2;
    }

    //
    // Gracefully stop and exit xlog
    //
    xlog_stop();
    xlog_exit();

    return rval;
}