Skip to content
Snippets Groups Projects
Commit 77954df7 authored by Neal Cardwell's avatar Neal Cardwell
Browse files

packetdrill: initial commit

Initial commit for the packetdrill network stack testing tool:

  https://code.google.com/p/packetdrill/



Signed-off-by: default avatarNeal Cardwell <ncardwell@google.com>
parents
No related branches found
No related tags found
No related merge requests found
Showing
with 2413 additions and 0 deletions
packetdrill
checksum_test
packet_parser_test
packet_to_string_test
# parser files generated by bison:
parser.c
parser.h
parser.output
# lexer files generated by flex:
lexer.c
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
packetdrill-ext-libs := -lpthread -lpcap
.include "Makefile.common"
packetdrill-ext-libs := -lpthread -lrt
include Makefile.common
packetdrill-ext-libs := -lpthread -lpcap
.include "Makefile.common"
packetdrill-ext-libs := -lpthread -lpcap
.include "Makefile.common"
all: binaries
CFLAGS = -g -Wall -Werror
parser.o: parser.y
bison --output=parser.c --defines=parser.h --report=state parser.y
cc $(CFLAGS) -c parser.c
lexer.o: lexer.l parser.o
flex -olexer.c lexer.l
cc -O2 -g -Wall -c lexer.c
packetdrill-lib := checksum.o code.o config.o hash.o hash_map.o ip_address.o \
netdev.o net_utils.o \
packet.o packet_socket_linux.o packet_socket_pcap.o \
packet_checksum.o packet_parser.o packet_to_string.o \
symbols_linux.o \
symbols_freebsd.o \
symbols_openbsd.o \
symbols_netbsd.o \
icmp_packet.o ip_packet.o tcp_packet.o udp_packet.o \
run.o run_command.o run_packet.o run_system_call.o \
script.o socket.o system.o \
tcp_options.o tcp_options_iterator.o tcp_options_to_string.o \
logging.o types.o lexer.o parser.o \
fmemopen.o open_memstream.o \
link_layer.o wire_conn.o wire_protocol.o \
wire_client.o wire_client_netdev.o \
wire_server.o wire_server_netdev.o
packetdrill-objs := packetdrill.o $(packetdrill-lib)
packetdrill: $(packetdrill-objs)
gcc -o packetdrill -g -static $(packetdrill-objs) $(packetdrill-ext-libs)
test-bins := checksum_test packet_parser_test packet_to_string_test
tests: $(test-bins)
./checksum_test
./packet_parser_test
./packet_to_string_test
binaries: packetdrill $(test-bins)
checksum_test-objs := $(packetdrill-lib) checksum_test.o
checksum_test: $(checksum_test-objs)
gcc -o checksum_test $(checksum_test-objs) $(packetdrill-ext-libs)
packet_parser_test-objs := $(packetdrill-lib) packet_parser_test.o
packet_parser_test: $(packet_parser_test-objs)
gcc -o packet_parser_test $(packet_parser_test-objs) \
$(packetdrill-ext-libs)
packet_to_string_test-objs := $(packetdrill-lib) packet_to_string_test.o
packet_to_string_test: $(packet_to_string_test-objs)
gcc -o packet_to_string_test $(packet_to_string_test-objs) \
$(packetdrill-ext-libs)
clean:
/bin/rm -f *.o packetdrill lexer.c parser.c parser.h parser.output \
$(test-bins)
packetdrill
===========
This directory contains the source code for the packetdrill network
stack testing tool.
The web site for packetdrill is here:
https://code.google.com/p/packetdrill/
building
========
To build packetdrill, first install flex and bison.
Then set up the Makefile for your platform:
# ./configure
Then build the tool:
# make
running
=======
Here's a quick example.
On FreeBSD, OpenBSD, and NetBSD, try:
# ./packetdrill examples/fr-4pkt-sack-bsd.pkt
On Linux try:
# ./packetdrill examples/fr-4pkt-sack-linux.pkt
license
=======
The packetdrill tool is released under version 2 of the GPL. See the
COPYING file for full details.
discussion and contributions
==============================
If you have any questions, or code or patches to offer, please join
the packetdrill e-mail list at:
http://groups.google.com/group/packetdrill
Contributions of code or tests are both welcomed!
Enjoy!
/*
* Copyright 2013 Google Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* 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. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/*
* Author: ncardwell@google.com (Neal Cardwell)
*
* Helpers to calculate IP, TCP, and UDP checksums.
*/
#include "checksum.h"
#include <assert.h>
/* Add bytes in buffer to a running checksum. Returns the new
* intermediate checksum. Use ip_checksum_fold() to convert the
* intermediate checksum to final form.
*/
static u64 ip_checksum_partial(const void *p, size_t len, u64 sum)
{
/* Main loop: 32 bits at a time.
* We take advantage of intel's ability to do unaligned memory
* accesses with minimal additional cost. Other architectures
* probably want to be more careful here.
*/
const u32 *p32 = (const u32 *)(p);
for (; len >= sizeof(*p32); len -= sizeof(*p32))
sum += *p32++;
/* Handle un-32bit-aligned trailing bytes */
const u16 *p16 = (const u16 *)(p32);
if (len >= 2) {
sum += *p16++;
len -= sizeof(*p16);
}
if (len > 0) {
const u8 *p8 = (const u8 *)(p16);
sum += ntohs(*p8 << 8); /* RFC says pad last byte */
}
return sum;
}
static __be16 ip_checksum_fold(u64 sum)
{
while (sum & ~0xffffffffULL)
sum = (sum >> 32) + (sum & 0xffffffffULL);
while (sum & 0xffff0000ULL)
sum = (sum >> 16) + (sum & 0xffffULL);
return ~sum;
}
static u64 tcp_udp_v4_header_checksum_partial(
struct in_addr src_ip, struct in_addr dst_ip, u8 protocol, u16 len)
{
/* The IPv4 pseudo-header is defined in RFC 793, Section 3.1. */
struct ipv4_pseudo_header_t {
/* We use a union here to avoid aliasing issues with gcc -O2 */
union {
struct header {
struct in_addr src_ip;
struct in_addr dst_ip;
__u8 mbz;
__u8 protocol;
__be16 length;
} __packed fields;
u32 words[3];
};
};
struct ipv4_pseudo_header_t pseudo_header;
assert(sizeof(pseudo_header) == 12);
/* Fill in the pseudo-header. */
pseudo_header.fields.src_ip = src_ip;
pseudo_header.fields.dst_ip = dst_ip;
pseudo_header.fields.mbz = 0;
pseudo_header.fields.protocol = protocol;
pseudo_header.fields.length = htons(len);
return ip_checksum_partial(&pseudo_header, sizeof(pseudo_header), 0);
}
__be16 tcp_udp_v4_checksum(struct in_addr src_ip, struct in_addr dst_ip,
u8 protocol, const void *payload, u16 len)
{
u64 sum = tcp_udp_v4_header_checksum_partial(
src_ip, dst_ip, protocol, len);
sum = ip_checksum_partial(payload, len, sum);
return ip_checksum_fold(sum);
}
/* Calculates and returns IPv4 header checksum. */
__be16 ipv4_checksum(void *ip_header, size_t ip_header_bytes)
{
return ip_checksum_fold(
ip_checksum_partial(ip_header, ip_header_bytes, 0));
}
static u64 tcp_udp_v6_header_checksum_partial(
const struct in6_addr *src_ip,
const struct in6_addr *dst_ip,
u8 protocol, u32 len)
{
/* The IPv6 pseudo-header is defined in RFC 2460, Section 8.1. */
struct ipv6_pseudo_header_t {
/* We use a union here to avoid aliasing issues with gcc -O2 */
union {
struct header {
struct in6_addr src_ip;
struct in6_addr dst_ip;
__be32 length;
__u8 mbz[3];
__u8 next_header;
} __packed fields;
u32 words[10];
};
};
struct ipv6_pseudo_header_t pseudo_header;
assert(sizeof(pseudo_header) == 40);
/* Fill in the pseudo-header. */
pseudo_header.fields.src_ip = *src_ip;
pseudo_header.fields.dst_ip = *dst_ip;
pseudo_header.fields.length = htonl(len);
memset(pseudo_header.fields.mbz, 0, sizeof(pseudo_header.fields.mbz));
pseudo_header.fields.next_header = protocol;
return ip_checksum_partial(&pseudo_header, sizeof(pseudo_header), 0);
}
__be16 tcp_udp_v6_checksum(const struct in6_addr *src_ip,
const struct in6_addr *dst_ip,
u8 protocol, const void *payload, u32 len)
{
u64 sum = tcp_udp_v6_header_checksum_partial(
src_ip, dst_ip, protocol, len);
sum = ip_checksum_partial(payload, len, sum);
return ip_checksum_fold(sum);
}
/*
* Copyright 2013 Google Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* 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. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/*
* Author: ncardwell@google.com (Neal Cardwell)
*
* Helpers to calculate IP, TCP, and UDP checksums.
*/
#ifndef __CHECKSUM_H__
#define __CHECKSUM_H__
#include "types.h"
#include <netinet/in.h>
#include <sys/types.h>
/* IPv4 ... */
/* Calculates and returns IPv4 header checksum (in network byte order). */
extern __be16 ipv4_checksum(void *ip_header, size_t ip_header_bytes);
/* Calculates TCP or UDP checksum for IPv4 (in network byte order). */
extern __be16 tcp_udp_v4_checksum(struct in_addr src_ip, struct in_addr dst_ip,
u8 protocol, const void *payload, u16 len);
/* IPv6 ... */
/* Calculates TCP, UDP, or ICMP checksum for IPv6 (in network byte order). */
extern __be16 tcp_udp_v6_checksum(const struct in6_addr *src_ip,
const struct in6_addr *dst_ip,
u8 protocol, const void *payload, u32 len);
#endif /* __CHECKSUM_H__ */
/*
* Copyright 2013 Google Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* 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. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/*
* Author: ncardwell@google.com (Neal Cardwell)
*
* Unit test for checksum.c.
*/
#include "checksum.h"
#include <arpa/inet.h>
#include <assert.h>
#include "ip.h"
#include "ipv6.h"
#include "tcp.h"
static void test_tcp_udp_v4_checksum(void)
{
u8 data[] = {
0x45, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x00,
0xff, 0x06, 0xf9, 0x10, 0x01, 0x01, 0x01, 0x01,
0xc0, 0xa8, 0x00, 0x01, 0x04, 0xd2, 0xeb, 0x35,
0x00, 0x00, 0x00, 0x00, 0xc6, 0xf0, 0x56, 0x00,
0xa0, 0x12, 0x16, 0xa0, 0x54, 0x12, 0x00, 0x00,
0x02, 0x04, 0x05, 0xb4, 0x04, 0x02, 0x08, 0x0a,
0x00, 0x00, 0x02, 0xbc, 0x00, 0x06, 0x0a, 0xd8,
0x01, 0x03, 0x03, 0x07,
};
struct in_addr src_ip, dst_ip;
struct tcp *tcp = (struct tcp *) (data + sizeof(struct ipv4));
int len = sizeof(data) - sizeof(struct ipv4);
u16 checksum = 0;
assert(inet_pton(AF_INET, "1.1.1.1", &src_ip) == 1);
assert(inet_pton(AF_INET, "192.168.0.1", &dst_ip) == 1);
checksum =
ntohs(tcp_udp_v4_checksum(src_ip, dst_ip, IPPROTO_TCP, tcp, len));
assert(checksum == 0);
tcp->check = 0;
checksum =
ntohs(tcp_udp_v4_checksum(src_ip, dst_ip, IPPROTO_TCP, tcp, len));
assert(checksum == 0x5412);
}
static void test_tcp_udp_v6_checksum(void)
{
u8 data[] = {
0x60, 0x00, 0x00, 0x00, 0x00, 0x20, 0x06, 0xff,
0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0xfd, 0x3d, 0xfa, 0x7b, 0xd1, 0x7d, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0xd3, 0xe2, 0x1f, 0x90, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x80, 0x02, 0x80, 0x18,
0x06, 0x60, 0x00, 0x00, 0x02, 0x04, 0x03, 0xe8,
0x04, 0x02, 0x01, 0x01, 0x01, 0x03, 0x03, 0x07,
};
struct ipv6 *ipv6 = (struct ipv6 *) (data);
struct tcp *tcp = (struct tcp *) (data + sizeof(struct ipv6));
int len = sizeof(data) - sizeof(struct ipv6);
u16 checksum = 0;
checksum =
ntohs(tcp_udp_v6_checksum(&ipv6->src_ip,
&ipv6->dst_ip,
IPPROTO_TCP, tcp, len));
assert(checksum == 0);
tcp->check = 0;
checksum =
ntohs(tcp_udp_v6_checksum(&ipv6->src_ip,
&ipv6->dst_ip,
IPPROTO_TCP, tcp, len));
assert(checksum == 0x0660);
}
static void test_ipv4_checksum(void)
{
u8 data[] = {
0x45, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x00,
0xff, 0x06, 0xf9, 0x10, 0x01, 0x01, 0x01, 0x01,
0xc0, 0xa8, 0x00, 0x01,
};
struct ipv4 *ip = (struct ipv4 *) data;
u16 checksum = 0;
checksum = ntohs(ipv4_checksum(data, sizeof(data)));
assert(checksum == 0);
ip->check = 0;
checksum = ntohs(ipv4_checksum(data, sizeof(data)));
assert(checksum == 0xf910);
}
int main(void)
{
test_tcp_udp_v4_checksum();
test_tcp_udp_v6_checksum();
test_ipv4_checksum();
return 0;
}
/*
* Copyright 2013 Google Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* 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. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/*
* Author: ncardwell@google.com (Neal Cardwell)
*
* Implementation for a module to write out post-processing code that
* can run custom programmatic analyses and constraint verification.
*/
#include "code.h"
#include <assert.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "run.h"
#include "tcp.h"
/* We emit the following Python preamble at the top of the output
* Python code. It defines a custom exception hook so that when an
* exception is raised (such as a failed assertion) we print the file
* name and line number of the code snippet in the original test
* script that caused the error, not just the file name and line
* number in the generated Python file (which will be meaningless or
* confusing to the user).
*/
const char python_preamble[] =
"import sys\n"
"import traceback\n"
"def excepthook(etype, value, tb):\n"
" sys.stderr.write(\"%s:%d: error in Python code\\n\" %\n"
" (_file, _line))\n"
" traceback.print_exception(etype, value, tb)\n"
"\n"
"sys.excepthook = excepthook\n"
"\n";
/* Write out the standard utility routines useful for a given language. */
static void write_preamble(struct code_state *code)
{
assert(code->format > FORMAT_NONE);
assert(code->format < FORMAT_NUM_TYPES);
switch (code->format) {
case FORMAT_NONE:
case FORMAT_NUM_TYPES:
assert(!"bad code format type");
case FORMAT_PYTHON:
fprintf(code->file, "%s\n", python_preamble);
break;
/* omitting default so compiler catches missing cases */
}
}
#if HAVE_TCP_INFO
/* Write out a formatted text representation of an assignment of the
* given value to the given named variable.
*/
static void emit_var(struct code_state *code, const char *name, u64 value)
{
assert(code->format > FORMAT_NONE);
assert(code->format < FORMAT_NUM_TYPES);
switch (code->format) {
case FORMAT_NONE:
case FORMAT_NUM_TYPES:
assert(!"bad code format type");
case FORMAT_PYTHON:
fprintf(code->file, "%s = %llu\n", name, value);
break;
/* omitting default so compiler catches missing cases */
}
}
/* Write out a newline to terminate a sequence of variable assignments */
static void emit_var_end(struct code_state *code)
{
fprintf(code->file, "\n");
}
/* Write out a formatted representation of useful symbolic names. */
static void write_symbols(struct code_state *code)
{
#ifdef linux
/* Emit symbolic names for tcpi_ca_state values. */
emit_var(code, "TCP_CA_Open", TCP_CA_Open);
emit_var(code, "TCP_CA_Disorder", TCP_CA_Disorder);
emit_var(code, "TCP_CA_CWR", TCP_CA_CWR);
emit_var(code, "TCP_CA_Recovery", TCP_CA_Recovery);
emit_var(code, "TCP_CA_Loss", TCP_CA_Loss);
#endif /* linux */
/* tcpi_options flags */
#ifdef linux
emit_var(code, "TCPI_OPT_TIMESTAMPS", TCPI_OPT_TIMESTAMPS);
emit_var(code, "TCPI_OPT_WSCALE", TCPI_OPT_WSCALE);
emit_var(code, "TCPI_OPT_ECN", TCPI_OPT_ECN);
#endif /* linux */
}
#endif /* HAVE_TCP_INFO */
#ifdef linux
/* Write out a formatted representation of the given tcp_info buffer. */
static void write_tcp_info(struct code_state *code,
const struct _tcp_info *info,
int len)
{
assert(len >= sizeof(struct _tcp_info));
write_symbols(code);
/* Emit the recorded values of tcpi_foo values. */
emit_var(code, "tcpi_state", info->tcpi_state);
emit_var(code, "tcpi_ca_state", info->tcpi_ca_state);
emit_var(code, "tcpi_retransmits", info->tcpi_retransmits);
emit_var(code, "tcpi_probes", info->tcpi_probes);
emit_var(code, "tcpi_backoff", info->tcpi_backoff);
emit_var(code, "tcpi_options", info->tcpi_options);
emit_var(code, "tcpi_snd_wscale", info->tcpi_snd_wscale);
emit_var(code, "tcpi_rcv_wscale", info->tcpi_rcv_wscale);
emit_var(code, "tcpi_rto", info->tcpi_rto);
emit_var(code, "tcpi_ato", info->tcpi_ato);
emit_var(code, "tcpi_snd_mss", info->tcpi_snd_mss);
emit_var(code, "tcpi_rcv_mss", info->tcpi_rcv_mss);
emit_var(code, "tcpi_unacked", info->tcpi_unacked);
emit_var(code, "tcpi_sacked", info->tcpi_sacked);
emit_var(code, "tcpi_lost", info->tcpi_lost);
emit_var(code, "tcpi_retrans", info->tcpi_retrans);
emit_var(code, "tcpi_fackets", info->tcpi_fackets);
emit_var(code, "tcpi_last_data_sent", info->tcpi_last_data_sent);
emit_var(code, "tcpi_last_ack_sent", info->tcpi_last_ack_sent);
emit_var(code, "tcpi_last_data_recv", info->tcpi_last_data_recv);
emit_var(code, "tcpi_last_ack_recv", info->tcpi_last_ack_recv);
emit_var(code, "tcpi_pmtu", info->tcpi_pmtu);
emit_var(code, "tcpi_rcv_ssthresh", info->tcpi_rcv_ssthresh);
emit_var(code, "tcpi_rtt", info->tcpi_rtt);
emit_var(code, "tcpi_rttvar", info->tcpi_rttvar);
emit_var(code, "tcpi_snd_ssthresh", info->tcpi_snd_ssthresh);
emit_var(code, "tcpi_snd_cwnd", info->tcpi_snd_cwnd);
emit_var(code, "tcpi_advmss", info->tcpi_advmss);
emit_var(code, "tcpi_reordering", info->tcpi_reordering);
emit_var(code, "tcpi_total_retrans", info->tcpi_total_retrans);
emit_var(code, "tcpi_rcv_rtt", info->tcpi_rcv_rtt);
emit_var(code, "tcpi_rcv_space", info->tcpi_rcv_space);
emit_var_end(code);
}
#endif /* linux */
#if defined(__FreeBSD__)
/* Write out a formatted representation of the given tcp_info buffer. */
static void write_tcp_info(struct code_state *code,
const struct _tcp_info *info,
int len)
{
assert(len >= sizeof(struct _tcp_info));
write_symbols(code);
/* Emit the recorded values of tcpi_foo values. */
emit_var(code, "tcpi_state", info->tcpi_state);
emit_var(code, "tcpi_options", info->tcpi_options);
emit_var(code, "tcpi_snd_wscale", info->tcpi_snd_wscale);
emit_var(code, "tcpi_rcv_wscale", info->tcpi_rcv_wscale);
emit_var(code, "tcpi_rto", info->tcpi_rto);
emit_var(code, "tcpi_snd_mss", info->tcpi_snd_mss);
emit_var(code, "tcpi_rcv_mss", info->tcpi_rcv_mss);
emit_var(code, "tcpi_last_data_recv", info->tcpi_last_data_recv);
emit_var(code, "tcpi_rtt", info->tcpi_rtt);
emit_var(code, "tcpi_rttvar", info->tcpi_rttvar);
emit_var(code, "tcpi_snd_ssthresh", info->tcpi_snd_ssthresh);
emit_var(code, "tcpi_snd_cwnd", info->tcpi_snd_cwnd);
emit_var(code, "tcpi_rcv_space", info->tcpi_rcv_space);
/* FreeBSD extensions to tcp_info. */
emit_var(code, "tcpi_snd_wnd", info->tcpi_snd_wnd);
emit_var(code, "tcpi_snd_bwnd", info->tcpi_snd_bwnd);
emit_var(code, "tcpi_snd_nxt", info->tcpi_snd_nxt);
emit_var(code, "tcpi_rcv_nxt", info->tcpi_rcv_nxt);
emit_var(code, "tcpi_toe_tid", info->tcpi_toe_tid);
emit_var(code, "tcpi_snd_rexmitpack", info->tcpi_snd_rexmitpack);
emit_var(code, "tcpi_rcv_ooopack", info->tcpi_rcv_ooopack);
emit_var(code, "tcpi_snd_zerowin", info->tcpi_snd_zerowin);
emit_var_end(code);
}
#endif /* __FreeBSD__ */
/* Allocate a new empty struct code_text struct. */
static struct code_text *text_new(void)
{
struct code_text *text = calloc(1, sizeof(struct code_text));
return text;
}
/* Free the given text struct and all storage to which it points. */
static void text_free(struct code_text *text)
{
free(text->text);
free(text->file_name);
free(text);
}
/* Allocate a new empty struct code_data struct. */
static struct code_data *data_new(void)
{
struct code_data *data = calloc(1, sizeof(struct code_data));
return data;
}
/* Free the given data and all storage to which it points. */
static void data_free(struct code_data *data)
{
free(data->buffer);
free(data);
}
/* Allocate a new empty fragment. */
static struct code_fragment *fragment_new(void)
{
struct code_fragment *fragment =
calloc(1, sizeof(struct code_fragment));
return fragment;
}
/* Free the given fragment and all storage to which it points. */
static void fragment_free(struct code_fragment *fragment)
{
assert(fragment->type > FRAGMENT_NONE);
assert(fragment->type < FRAGMENT_NUM_TYPES);
switch (fragment->type) {
case FRAGMENT_NONE:
case FRAGMENT_NUM_TYPES:
assert(!"bad code fragment type");
break;
case FRAGMENT_TEXT:
text_free(fragment->contents.text);
break;
case FRAGMENT_DATA:
data_free(fragment->contents.data);
break;
/* omitting default so compiler catches missing cases */
}
free(fragment);
}
/* Write out the text to the given file. */
static void write_text(struct code_state *code, struct code_text *text)
{
assert(code->format > FORMAT_NONE);
assert(code->format < FORMAT_NUM_TYPES);
switch (code->format) {
case FORMAT_NONE:
case FORMAT_NUM_TYPES:
assert(!"bad code format type");
case FORMAT_PYTHON:
fprintf(code->file,
"_file = '%s'\n"
"_line = %d\n"
"%s\n\n",
text->file_name, text->line_number, text->text);
break;
/* omitting default so compiler catches missing cases */
}
}
/* Write out a textual representation of the data to the given file. */
static void write_data(struct code_state *code, struct code_data *data)
{
assert(data->type > DATA_NONE);
assert(data->type < DATA_NUM_TYPES);
switch (data->type) {
case DATA_NONE:
case DATA_NUM_TYPES:
assert(!"bad data type");
break;
#if HAVE_TCP_INFO
case DATA_TCP_INFO:
write_tcp_info(code, data->buffer, data->len);
break;
#endif /* HAVE_TCP_INFO */
/* omitting default so compiler catches missing cases */
}
}
/* Write out a textual representation of the fragment to the given file. */
static void write_fragment(struct code_state *code,
struct code_fragment *fragment)
{
assert(fragment->type > FRAGMENT_NONE);
assert(fragment->type < FRAGMENT_NUM_TYPES);
switch (fragment->type) {
case FRAGMENT_NONE:
case FRAGMENT_NUM_TYPES:
assert(!"bad code fragment type");
break;
case FRAGMENT_TEXT:
write_text(code, fragment->contents.text);
break;
case FRAGMENT_DATA:
write_data(code, fragment->contents.data);
break;
/* omitting default so compiler catches missing cases */
}
}
/* Format and write out all the code fragments. */
static void write_all_fragments(struct code_state *code)
{
struct code_fragment *fragment = NULL;
for (fragment = code->list_head; fragment != NULL;
fragment = fragment->next) {
write_fragment(code, fragment);
}
}
/* Append the code fragment to the end of the list of code fragments. */
static void append_fragment(struct code_state *code,
struct code_fragment *fragment)
{
*(code->list_tail) = fragment;
code->list_tail = &(fragment->next);
}
/* Append a literal ASCII text code snippet that we should emit.
* Takes ownership of the malloc-allocated text memory and frees it.
*/
static void append_text(struct code_state *code,
const char *file_name, int line_number,
char *text_buffer)
{
struct code_text *text = text_new();
text->text = text_buffer;
text->file_name = strdup(file_name);
text->line_number = line_number;
struct code_fragment *fragment = fragment_new();
fragment->type = FRAGMENT_TEXT;
fragment->contents.text = text;
append_fragment(code, fragment);
}
/* Append a live binary buffer that we should translate into the
* format configured earlier by the user for this script.
* Takes ownership of the malloc-allocated buffer and frees it.
*/
static void append_data(struct code_state *code, enum code_data_t data_type,
void *data_buffer, int data_len)
{
struct code_data *data = data_new();
data->buffer = data_buffer;
data->type = data_type;
data->len = data_len;
struct code_fragment *fragment = fragment_new();
fragment->type = FRAGMENT_DATA;
fragment->contents.data = data;
append_fragment(code, fragment);
}
struct code_state *code_new(struct config *config)
{
struct code_state *code = calloc(1, sizeof(struct code_state));
/* Set up the pointer to the tail of the empty linked list. */
code->list_tail = &(code->list_head);
if (strcmp(config->code_format, "python") == 0)
code->format = FORMAT_PYTHON;
else
die("unsupported --code_format '%s'\n", config->code_format);
/* See which getsockopt we should use to get data for our code. */
if (strcmp(config->code_sockopt, "") == 0) {
code->data_type = DATA_NONE; /* auto-detect */
#if HAVE_TCP_INFO
} else if (strcmp(config->code_sockopt, "TCP_INFO") == 0) {
code->data_type = DATA_TCP_INFO;
#endif
} else {
die("unsupported --code_sockopt '%s'\n", config->code_sockopt);
}
code->command_line = strdup(config->code_command_line);
code->verbose = config->verbose;
return code;
}
void code_free(struct code_state *code)
{
if (code->command_line != NULL)
free(code->command_line);
if (code->path != NULL)
free(code->path);
/* Free all the code fragments. */
struct code_fragment *fragment = code->list_head;
while (fragment != NULL) {
struct code_fragment *dead_fragment = fragment;
fragment = fragment->next;
fragment_free(dead_fragment);
}
memset(code, 0, sizeof(*code)); /* paranoia to help catch bugs */
free(code);
}
/* Write all the code fragments to a newly-chosen temporary file and
* store the name of the file in code->path.
*/
static void write_code_file(struct code_state *code)
{
/* mkstemp will fill this in with the actual unique path name. */
char path_template[] = "/tmp/code_XXXXXX";
int code_fd = mkstemp(path_template);
if (code_fd < 0)
die_perror("error making temp output file for code: mkstemp");
assert(code->path == NULL);
code->path = strdup(path_template);
code->file = fdopen(code_fd, "w");
if (code->file == NULL)
die_perror("error opening temp output file for code: fdopen");
write_preamble(code);
write_all_fragments(code);
if (fclose(code->file) != 0)
die_perror("error closing temp output file for code: fclose");
code->file = NULL;
}
/* Execute the code in the file at code->path by executing the
* configured command line. On success, returns STATUS_OK. On error
* returns STATUS_ERR and fills in *error.
*/
static int execute_code_command_line(struct code_state *code, char **error)
{
int result = STATUS_ERR; /* return value */
char *full_command_line = NULL;
asprintf(&full_command_line, "%s %s", code->command_line, code->path);
/* For verbose debugging we dump the full output file. */
if (code->verbose) {
char *verbose_command_line = NULL;
asprintf(&verbose_command_line, "cat %s", code->path);
system(verbose_command_line);
free(verbose_command_line);
printf("running: '%s'\n", full_command_line);
}
int status = system(full_command_line);
if (status == -1) {
asprintf(error, "error running '%s' with system(3): %s",
code->command_line, strerror(errno));
goto out;
}
if (WIFSIGNALED(status) &&
(WTERMSIG(status) == SIGINT || WTERMSIG(status) == SIGQUIT)) {
asprintf(error, "'%s' got signal %d (%s)",
code->command_line,
WTERMSIG(status), strsignal(WTERMSIG(status)));
goto out;
}
if (WEXITSTATUS(status) != 0) {
asprintf(error, "'%s' returned non-zero status %d",
code->command_line, WEXITSTATUS(status));
goto out;
}
result = STATUS_OK;
out:
free(full_command_line);
return result;
}
/* Delete the temporary file at code->path. */
static void delete_code_file(struct code_state *code)
{
if ((code->path != NULL) && (unlink(code->path) != 0))
die_perror("error deleting code file: unlink:");
}
/* Write out the code to a file, execute the code, and delete the file. */
int code_execute(struct code_state *code, char **error)
{
if (code->list_head == NULL)
return STATUS_OK; /* no code to execute */
write_code_file(code);
int result = execute_code_command_line(code, error);
delete_code_file(code);
return result;
}
/* Run a getsockopt for the given fd to grab data of the given type.
* On success, return a pointer the filled-in buffer (allocated by malloc);
* on failure, return NULL.
*/
static void *get_data(int fd, enum code_data_t data_type, int *len)
{
int opt_name = 0;
int data_len = 0;
int min_data_len = 0;
assert(data_type > DATA_NONE);
assert(data_type < DATA_NUM_TYPES);
switch (data_type) {
case DATA_NONE:
case DATA_NUM_TYPES:
assert(!"bad data type");
break;
#if HAVE_TCP_INFO
case DATA_TCP_INFO:
opt_name = TCP_INFO;
data_len = sizeof(struct _tcp_info);
min_data_len = data_len;
break;
#endif /* HAVE_TCP_INFO */
/* omitting default so compiler catches missing cases */
}
assert(opt_name != 0);
assert(data_len > 0);
socklen_t opt_len = data_len;
void *data = calloc(1, data_len);
int result = getsockopt(fd, SOL_TCP, opt_name, data, &opt_len);
if (result < 0) {
free(data);
return NULL;
}
if (opt_len < min_data_len) {
die("expected getsockopt(SOL_TCP, %d) output "
"of at least %d bytes; got %d bytes",
opt_name, min_data_len, opt_len);
}
*len = opt_len;
return data;
}
void run_code_event(struct state *state, struct event *event,
const char *text)
{
DEBUGP("%d: run code event\n", event->line_number);
char *error = NULL;
/* Wait for the right time before firing off this event. */
wait_for_event(state);
if (state->socket_under_test == NULL) {
asprintf(&error, "no socket to use for code");
goto error_out;
}
int fd = state->socket_under_test->live.fd;
struct code_state *code = state->code;
void *data = NULL;
int data_len = 0;
if (code->data_type == DATA_NONE) {
/* First time: try various getsockopt calls until one works. */
#if HAVE_TCP_INFO
if (data == NULL) {
code->data_type = DATA_TCP_INFO;
data = get_data(fd, code->data_type, &data_len);
}
#endif /* HAVE_TCP_INFO */
if (data == NULL) {
asprintf(&error,
"can't find getsockopt to get TCP info");
goto error_out;
}
} else {
/* Run the getsockopt we already picked above. */
data = get_data(fd, code->data_type, &data_len);
if (!data) {
asprintf(&error, "can't get info for socket");
goto error_out;
}
}
assert(code->data_type != DATA_NONE);
assert(data != NULL);
append_data(code, code->data_type, data, data_len);
append_text(code, state->config->script_path, event->line_number,
strdup(text));
return;
error_out:
die("%s:%d: runtime error in code: %s\n",
state->config->script_path, event->line_number, error);
free(error);
}
/*
* Copyright 2013 Google Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* 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. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/*
* Author: ncardwell@google.com (Neal Cardwell)
*
* Interface for a module to write out post-processing code that
* can run custom programmatic analyses and constraint verification.
*/
#ifndef __CODE_H__
#define __CODE_H__
#include "types.h"
#include "config.h"
#include "script.h"
/* Post-processing format syntax variants we support. */
enum code_format_t {
FORMAT_NONE, /* uninitialized or no code so far */
FORMAT_PYTHON, /* Python syntax: var_name = 123 */
FORMAT_NUM_TYPES, /* number of types of format */
};
/* The type of a particular fragment of code. */
enum code_fragment_t {
FRAGMENT_NONE, /* uninitialized or none so far */
FRAGMENT_TEXT, /* literal code text to emit */
FRAGMENT_DATA, /* binary buffer to dump as text */
FRAGMENT_NUM_TYPES, /* number of types of fragments */
};
/* The type of a particular binary data buffer. */
enum code_data_t {
DATA_NONE, /* uninitialized or none so far */
#if HAVE_TCP_INFO
DATA_TCP_INFO, /* binary tcp_info */
#endif /* HAVE_TCP_INFO */
DATA_NUM_TYPES, /* number of types of fragments */
};
/* Info about a textual code snippet to encode in the post-processing code. */
struct code_text {
char *text; /* the code snippet string */
char *file_name; /* name of script text was read from */
int line_number; /* line on which text started */
};
/* Info about a data buffer to encode in the post-processing code. */
struct code_data {
void *buffer; /* malloc-allocated buffer */
enum code_data_t type; /* type of data in the buffer */
int len; /* length of data in buffer */
};
/* Info about a fragment to insert in the post-processing code. */
struct code_fragment {
enum code_fragment_t type; /* what's in this fragment? */
union {
struct code_text *text; /* ASCII text code snippet */
struct code_data *data; /* typed binary data buffer */
} contents;
struct code_fragment *next; /* next in linked list */
};
/* Internal state for the code execution module. */
struct code_state {
bool verbose; /* print debug info? */
enum code_format_t format; /* language syntax to emit */
enum code_data_t data_type; /* data to get for snippets */
char *command_line; /* system(3) command to run */
char *path; /* path where we write code */
FILE *file; /* output file we're writing */
struct code_fragment *list_head; /* linked list head */
struct code_fragment **list_tail; /* pointer to tail */
};
/* Allocate and return a new code executor using the given config. */
extern struct code_state *code_new(struct config *config);
/* Tear down a code executor and free up the resources it has allocated. */
extern void code_free(struct code_state *code);
/* Run the TCP_INFO getsockopt on the current socket under test to
* get a snapshot of socket state, and stash the resulting data and
* code snippet so that at the end of the test we can emit the data
* and the code snippet, and then execute both.
*/
struct state;
extern void run_code_event(struct state *state,
struct event *event, const char *text);
/* Call this at the end of test execution to run the code by writing
* out the text of the code and invoking the command line supplied by
* the user. On success, returns STATUS_OK. On error returns
* STATUS_ERR and fills in *error.
*/
extern int code_execute(struct code_state *code, char **error);
#endif /* __CODE_H__ */
/*
* Copyright 2013 Google Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* 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. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/*
* Author: ncardwell@google.com (Neal Cardwell)
*
* Helper functions for configuration information for a test run.
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include "config.h"
#include "logging.h"
/* For the sake of clarity, we require long option names, e.g. --foo,
* for all options except -v.
*/
enum option_codes {
OPT_IP_VERSION = 256,
OPT_BIND_PORT,
OPT_CODE_COMMAND,
OPT_CODE_FORMAT,
OPT_CODE_SOCKOPT,
OPT_CONNECT_PORT,
OPT_REMOTE_IP,
OPT_LOCAL_IP,
OPT_GATEWAY_IP,
OPT_NETMASK_IP,
OPT_SPEED,
OPT_MTU,
OPT_INIT_SCRIPTS,
OPT_TOLERANCE_USECS,
OPT_WIRE_CLIENT,
OPT_WIRE_SERVER,
OPT_WIRE_SERVER_IP,
OPT_WIRE_SERVER_PORT,
OPT_WIRE_CLIENT_DEV,
OPT_WIRE_SERVER_DEV,
OPT_TCP_TS_TICK_USECS,
OPT_NON_FATAL,
OPT_VERBOSE = 'v', /* our only single-letter option */
};
/* Specification of command line options for getopt_long(). */
struct option options[] = {
{ "ip_version", .has_arg = true, NULL, OPT_IP_VERSION },
{ "bind_port", .has_arg = true, NULL, OPT_BIND_PORT },
{ "code_command", .has_arg = true, NULL, OPT_CODE_COMMAND },
{ "code_format", .has_arg = true, NULL, OPT_CODE_FORMAT },
{ "code_sockopt", .has_arg = true, NULL, OPT_CODE_SOCKOPT },
{ "connect_port", .has_arg = true, NULL, OPT_CONNECT_PORT },
{ "remote_ip", .has_arg = true, NULL, OPT_REMOTE_IP },
{ "local_ip", .has_arg = true, NULL, OPT_LOCAL_IP },
{ "gateway_ip", .has_arg = true, NULL, OPT_GATEWAY_IP },
{ "netmask_ip", .has_arg = true, NULL, OPT_NETMASK_IP },
{ "speed", .has_arg = true, NULL, OPT_SPEED },
{ "mtu", .has_arg = true, NULL, OPT_MTU },
{ "init_scripts", .has_arg = true, NULL, OPT_INIT_SCRIPTS },
{ "tolerance_usecs", .has_arg = true, NULL, OPT_TOLERANCE_USECS },
{ "wire_client", .has_arg = false, NULL, OPT_WIRE_CLIENT },
{ "wire_server", .has_arg = false, NULL, OPT_WIRE_SERVER },
{ "wire_server_ip", .has_arg = true, NULL, OPT_WIRE_SERVER_IP },
{ "wire_server_port", .has_arg = true, NULL, OPT_WIRE_SERVER_PORT },
{ "wire_client_dev", .has_arg = true, NULL, OPT_WIRE_CLIENT_DEV },
{ "wire_server_dev", .has_arg = true, NULL, OPT_WIRE_SERVER_DEV },
{ "tcp_ts_tick_usecs", .has_arg = true, NULL, OPT_TCP_TS_TICK_USECS },
{ "non_fatal", .has_arg = true, NULL, OPT_NON_FATAL },
{ "verbose", .has_arg = false, NULL, OPT_VERBOSE },
{ NULL },
};
void show_usage(void)
{
fprintf(stderr, "Usage: packetdrill\n"
"\t[--ip_version=[ipv4,ipv4-mapped-ipv6,ipv6]]\n"
"\t[--bind_port=bind_port]\n"
"\t[--code_command=code_command]\n"
"\t[--code_format=code_format]\n"
"\t[--code_sockopt=TCP_INFO]\n"
"\t[--connect_port=connect_port]\n"
"\t[--remote_ip=remote_ip]\n"
"\t[--local_ip=local_ip]\n"
"\t[--gateway_ip=gateway_ip]\n"
"\t[--netmask_ip=netmask_ip]\n"
"\t[--init_scripts=<comma separated filenames>\n"
"\t[--speed=<speed in Mbps>\n"
"\t[--mtu=<MTU in bytes>\n"
"\t[--tolerance_usecs=tolerance_usecs]\n"
"\t[--tcp_ts_tick_usecs=<microseconds per TCP TS val tick>]\n"
"\t[--non_fatal=<comma separated types: packet,syscall>]\n"
"\t[--wire_client]\n"
"\t[--wire_server]\n"
"\t[--wire_server_ip=<server_ipv4_address>]\n"
"\t[--wire_server_port=<server_port>]\n"
"\t[--wire_client_dev=<eth_dev_name>]\n"
"\t[--wire_server_dev=<eth_dev_name>]\n"
"\t[--verbose|-v]\n"
"\tscript_path ...\n");
}
/* Address Configuration for IPv4
*
* For IPv4, we use the 192.168.0.0/16 RFC 1918 private IP space for
* our tun interface. To avoid accidents and confusion we want remote
* addresses to be permanently unallocated addresses outside of the
* private/unroutable RFC 1918 ranges (kernel code can behave
* differently for private addresses). So for remote addresses we use
* the 192.0.2.0/24 TEST-NET-1 range (see RFC 5737).
*
* Summary for IPv4:
* - local address: 192.168.0.0/16 private IP space (RFC 1918)
* - remote address: 192.0.2.0/24 TEST-NET-1 range (RFC 5737)
*/
#define DEFAULT_V4_LIVE_REMOTE_IP_STRING "192.0.2.1"
#define DEFAULT_V4_LIVE_LOCAL_IP_STRING "192.168.0.1"
#define DEFAULT_V4_LIVE_GATEWAY_IP_STRING "192.168.0.2"
#define DEFAULT_V4_LIVE_NETMASK_IP_STRING "255.255.0.0"
/* Address Configuration for IPv6
*
* For IPv6 we use a ULA (unique local address) for our local (tun)
* interface, and the RFC 3849 documentation space for our remote
* address.
*
* Summary for IPv6:
* - local address: fd3d:fa7b:d17d::/48 in unique local address space (RFC 4193)
* - remote address: 2001:DB8::/32 documentation prefix (RFC 3849)
*/
#define DEFAULT_V6_LIVE_REMOTE_IP_STRING "2001:DB8::1"
#define DEFAULT_V6_LIVE_LOCAL_IP_STRING "fd3d:fa7b:d17d::1"
#define DEFAULT_V6_LIVE_GATEWAY_IP_STRING "fd3d:fa7b:d17d::2"
#define DEFAULT_V6_LIVE_PREFIX_LEN 48
/* Fill in any as-yet-unspecified IP address attributes using IPv4 defaults. */
static void set_ipv4_defaults(struct config *config)
{
if (strlen(config->live_remote_ip_string) == 0)
strcpy(config->live_remote_ip_string,
DEFAULT_V4_LIVE_REMOTE_IP_STRING);
if (strlen(config->live_local_ip_string) == 0)
strcpy(config->live_local_ip_string,
DEFAULT_V4_LIVE_LOCAL_IP_STRING);
if (strlen(config->live_gateway_ip_string) == 0)
strcpy(config->live_gateway_ip_string,
DEFAULT_V4_LIVE_GATEWAY_IP_STRING);
if (strlen(config->live_netmask_ip_string) == 0)
strcpy(config->live_netmask_ip_string,
DEFAULT_V4_LIVE_NETMASK_IP_STRING);
}
/* Fill in any as-yet-unspecified IP address attributes using IPv6 defaults. */
static void set_ipv6_defaults(struct config *config)
{
if (strlen(config->live_remote_ip_string) == 0)
strcpy(config->live_remote_ip_string,
DEFAULT_V6_LIVE_REMOTE_IP_STRING);
if (strlen(config->live_local_ip_string) == 0)
strcpy(config->live_local_ip_string,
DEFAULT_V6_LIVE_LOCAL_IP_STRING);
if (strlen(config->live_gateway_ip_string) == 0)
strcpy(config->live_gateway_ip_string,
DEFAULT_V6_LIVE_GATEWAY_IP_STRING);
}
/* Set default configuration before we begin parsing. */
void set_default_config(struct config *config)
{
memset(config, 0, sizeof(*config));
config->code_command_line = "/usr/bin/python";
config->code_format = "python";
config->code_sockopt = ""; /* auto-detect */
config->ip_version = IP_VERSION_4;
config->live_bind_port = 8080;
config->live_connect_port = 8080;
config->tolerance_usecs = 4000;
config->speed = TUN_DRIVER_SPEED_CUR;
config->mtu = TUN_DRIVER_DEFAULT_MTU;
/* For now, by default we disable checks of outbound TS val
* values, since there are timestamp val bugs in the tests and
* kernel. TODO(ncardwell): Switch default tcp_ts_tick_usecs
* to 1000 when TCP timestamp val bugs have been eradicated
* from kernel and tests.
*/
config->tcp_ts_tick_usecs = 0; /* disable checks of TS val */
config->live_remote_ip_string[0] = '\0';
config->live_local_ip_string[0] = '\0';
config->live_gateway_ip_string[0] = '\0';
config->live_netmask_ip_string[0] = '\0';
config->init_scripts = NULL;
config->wire_server_port = 8081;
config->wire_client_device = "eth0";
config->wire_server_device = "eth0";
}
/* Here's a table summarizing the types of various entities in the
* different flavors of IP that we support:
*
* flavor socket_domain bind/connect/accept IP local/remote IP
* -------- ------------- ------------------------- ---------------
* 4 AF_INET AF_INET AF_INET
* 4-mapped-6 AF_INET6 AF_INET6 mapped from IPv4 AF_INET
* 6 AF_INET6 AF_INET6 AF_INET6
*/
/* Calculate final configuration values needed for IPv4 */
static void finalize_ipv4_config(struct config *config)
{
set_ipv4_defaults(config);
config->live_local_ip = ipv4_parse(config->live_local_ip_string);
config->live_remote_ip = ipv4_parse(config->live_remote_ip_string);
config->live_prefix_len =
netmask_to_prefix(config->live_netmask_ip_string);
config->live_gateway_ip = ipv4_parse(config->live_gateway_ip_string);
config->live_bind_ip = ipv4_parse("0.0.0.0");
config->live_connect_ip = config->live_remote_ip;
config->socket_domain = AF_INET;
config->wire_protocol = AF_INET;
}
/* Calculate final configuration values needed for ipv4-mapped-ipv6 */
static void finalize_ipv4_mapped_ipv6_config(struct config *config)
{
set_ipv4_defaults(config);
config->live_local_ip = ipv4_parse(config->live_local_ip_string);
config->live_remote_ip = ipv4_parse(config->live_remote_ip_string);
config->live_prefix_len =
netmask_to_prefix(config->live_netmask_ip_string);
config->live_gateway_ip = ipv4_parse(config->live_gateway_ip_string);
config->live_bind_ip = ipv6_parse("::");
config->live_connect_ip = ipv6_map_from_ipv4(config->live_remote_ip);
config->socket_domain = AF_INET6;
config->wire_protocol = AF_INET;
}
/* Calculate final configuration values needed for IPv6 */
static void finalize_ipv6_config(struct config *config)
{
set_ipv6_defaults(config);
config->live_local_ip = ipv6_parse(config->live_local_ip_string);
config->live_remote_ip = ipv6_parse(config->live_remote_ip_string);
config->live_prefix_len = DEFAULT_V6_LIVE_PREFIX_LEN;
config->live_gateway_ip = ipv6_parse(config->live_gateway_ip_string);
config->live_bind_ip = ipv6_parse("::");
config->live_connect_ip = config->live_remote_ip;
config->socket_domain = AF_INET6;
config->wire_protocol = AF_INET6;
}
void finalize_config(struct config *config)
{
assert(config->ip_version >= IP_VERSION_4);
assert(config->ip_version <= IP_VERSION_6);
switch (config->ip_version) {
case IP_VERSION_4:
finalize_ipv4_config(config);
break;
case IP_VERSION_4_MAPPED_6:
finalize_ipv4_mapped_ipv6_config(config);
break;
case IP_VERSION_6:
finalize_ipv6_config(config);
break;
/* omitting default so compiler will catch missing cases */
}
}
/* Expect that arg is comma-delimited, allowing for spaces. */
void parse_non_fatal_arg(char *arg, struct config *config)
{
char *argdup, *saveptr, *token;
if (arg == NULL || strlen(arg) == 0)
return;
argdup = strdup(arg);
token = strtok_r(argdup, ", ", &saveptr);
while (token != NULL) {
if (strcmp(token, "packet") == 0)
config->non_fatal_packet = true;
else if (strcmp(token, "syscall") == 0)
config->non_fatal_syscall = true;
token = strtok_r(NULL, ", ", &saveptr);
}
free(argdup);
}
/* Process a command line option */
static void process_option(int opt, char *optarg, struct config *config,
char *where)
{
int port = 0;
char *end = NULL;
unsigned long speed = 0;
DEBUGP("process_option %d ('%c') = %s\n",
opt, (char)opt, optarg);
switch (opt) {
case OPT_IP_VERSION:
if (strcmp(optarg, "ipv4") == 0)
config->ip_version = IP_VERSION_4;
else if (strcmp(optarg, "ipv4-mapped-ipv6") == 0)
config->ip_version = IP_VERSION_4_MAPPED_6;
else if (strcmp(optarg, "ipv6") == 0)
config->ip_version = IP_VERSION_6;
else
die("%s: bad --ip_version: %s\n", where, optarg);
break;
case OPT_BIND_PORT:
port = atoi(optarg);
if ((port <= 0) || (port > 0xffff))
die("%s: bad --bind_port: %s\n", where, optarg);
config->live_bind_port = port;
break;
case OPT_CODE_COMMAND:
config->code_command_line = optarg;
break;
case OPT_CODE_FORMAT:
config->code_format = optarg;
break;
case OPT_CODE_SOCKOPT:
config->code_sockopt = optarg;
break;
case OPT_CONNECT_PORT:
port = atoi(optarg);
if ((port <= 0) || (port > 0xffff))
die("%s: bad --connect_port: %s\n", where, optarg);
config->live_connect_port = port;
break;
case OPT_REMOTE_IP:
strncpy(config->live_remote_ip_string, optarg, ADDR_STR_LEN-1);
break;
case OPT_LOCAL_IP:
strncpy(config->live_local_ip_string, optarg, ADDR_STR_LEN-1);
break;
case OPT_GATEWAY_IP:
strncpy(config->live_gateway_ip_string, optarg, ADDR_STR_LEN-1);
break;
case OPT_MTU:
config->mtu = atoi(optarg);
if (config->mtu < 0)
die("%s: bad --mtu: %s\n", where, optarg);
break;
case OPT_NETMASK_IP:
strncpy(config->live_netmask_ip_string, optarg, ADDR_STR_LEN-1);
break;
case OPT_INIT_SCRIPTS:
config->init_scripts = optarg;
break;
case OPT_NON_FATAL:
parse_non_fatal_arg(optarg, config);
break;
case OPT_SPEED:
speed = strtoul(optarg, &end, 10);
if (end == optarg || *end || !is_valid_u32(speed))
die("%s: bad --speed: %s\n", where, optarg);
config->speed = speed;
break;
case OPT_TOLERANCE_USECS:
config->tolerance_usecs = atoi(optarg);
if (config->tolerance_usecs <= 0)
die("%s: bad --tolerance_usecs: %s\n", where, optarg);
break;
case OPT_TCP_TS_TICK_USECS:
config->tcp_ts_tick_usecs = atoi(optarg);
if (config->tcp_ts_tick_usecs < 0 ||
config->tcp_ts_tick_usecs > 1000000)
die("%s: bad --tcp_ts_tick_usecs: %s\n", where, optarg);
break;
case OPT_WIRE_CLIENT:
config->is_wire_client = true;
break;
case OPT_WIRE_SERVER:
config->is_wire_server = true;
break;
case OPT_WIRE_SERVER_IP:
config->wire_server_ip_string = strdup(optarg);
config->wire_server_ip =
ipv4_parse(config->wire_server_ip_string);
break;
case OPT_WIRE_SERVER_PORT:
port = atoi(optarg);
if ((port <= 0) || (port > 0xffff))
die("%s: bad --wire_server_port: %s\n", where, optarg);
config->wire_server_port = port;
break;
case OPT_WIRE_CLIENT_DEV:
config->wire_client_device = strdup(optarg);
break;
case OPT_WIRE_SERVER_DEV:
config->wire_server_device = strdup(optarg);
break;
case OPT_VERBOSE:
config->verbose = true;
break;
default:
show_usage();
exit(EXIT_FAILURE);
}
}
/* Parse command line options. Returns a pointer to the first argument
* beyond the options.
*/
char **parse_command_line_options(int argc, char *argv[],
struct config *config)
{
int c = 0;
int i = 0;
DEBUGP("parse_command_line_options argc=%d\n", argc);
for (i = 0; i < argc; ++i)
DEBUGP("argv[%d] = '%s'\n", i, argv[i]);
/* Make a copy of our arguments for later, in case we need to
* pass our options to a server. We use argc+1 here because,
* following main() calling conventions, we make the array
* element at argv[argc] a NULL pointer.
*/
config->argv = calloc(argc + 1, sizeof(char *));
for (i = 0; argv[i]; ++i)
config->argv[i] = strdup(argv[i]);
/* Parse the arguments. */
optind = 0;
while ((c = getopt_long(argc, argv, "v", options, NULL)) > 0)
process_option(c, optarg, config, "Command Line");
return argv + optind;
}
static void parse_script_options(struct config *config,
struct option_list *option_list)
{
struct option_list *opt = option_list;
while (opt != NULL) {
int i;
int c = 0;
for (i = 0; options[i].name != NULL; i++) {
if (strcmp(options[i].name, opt->name) == 0) {
c = options[i].val;
break;
}
}
if (c != 0) {
process_option(options[i].val,
opt->value, config,
config->script_path);
} else {
die("%s: option '%s' unknown in file: %s\n",
config->script_path, opt->name,
config->script_path);
}
opt = opt->next;
}
}
/* The parser calls this callback after it finishes parsing all
* --foo=bar options inside the script. At this point we know all
* command line and in-script options, and can finalize our
* configuration. Notably, this allows us to know when we parse a TCP
* packet line in the script whether we should create an IPv4 or IPv6
* packet.
*/
void parse_and_finalize_config(struct invocation *invocation)
{
DEBUGP("parse_and_finalize_config\n");
/* Parse options in script */
parse_script_options(invocation->config,
invocation->script->option_list);
/* Command line options overwrite options in script */
parse_command_line_options(invocation->argc, invocation->argv,
invocation->config);
/* Now take care of the last details */
finalize_config(invocation->config);
}
/*
* Copyright 2013 Google Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* 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. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/*
* Author: ncardwell@google.com (Neal Cardwell)
*
* Configuration information for a test run, and helper functions.
*/
#ifndef __CONFIG_H__
#define __CONFIG_H__
#include "types.h"
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <getopt.h>
#include "ip_address.h"
#include "script.h"
#define TUN_DRIVER_SPEED_CUR 0 /* don't change current speed */
#define TUN_DRIVER_DEFAULT_MTU 1500 /* default MTU for tun device */
extern struct option options[];
struct config {
const char **argv; /* a copy of process argv */
enum ip_version_t ip_version; /* v4, v4-mapped-v6, v6 */
int socket_domain; /* AF_INET or AF_INET6 */
int wire_protocol; /* AF_INET or AF_INET6 */
u16 live_bind_port; /* local port for bind() */
u16 live_connect_port; /* remote port for connect() */
struct ip_address live_bind_ip; /* address for bind() */
struct ip_address live_connect_ip; /* address for connect() */
struct ip_address live_local_ip; /* local interface IP */
struct ip_address live_remote_ip; /* remote interface IP */
struct ip_address live_gateway_ip; /* gateway interface IP */
char live_local_ip_string[ADDR_STR_LEN]; /* human-readable IP */
char live_remote_ip_string[ADDR_STR_LEN]; /* human-readable IP */
char live_gateway_ip_string[ADDR_STR_LEN]; /* local gateway IP */
char live_netmask_ip_string[ADDR_STR_LEN]; /* local netmask */
int live_prefix_len; /* IPv4/IPv6 interface prefix len */
int tolerance_usecs; /* tolerance for time divergence */
int tcp_ts_tick_usecs; /* microseconds per TS val tick */
u32 speed; /* speed reported by tun driver;
* may require special tun driver
*/
int mtu; /* MTU of tun device */
bool non_fatal_packet; /* treat packet asserts as non-fatal */
bool non_fatal_syscall; /* treat syscall asserts as non-fatal */
bool verbose; /* print detailed debug info? */
char *script_path; /* pathname of script file */
/* Shell command to invoke via system(3) to run post-processing code */
char *code_command_line;
/* Language to emit when generating post-processing code */
char *code_format;
/* setsockopt option number (TCP_INFO) for code */
char *code_sockopt;
/* File scripts to run at beginning of test (using system) */
char *init_scripts;
/* For remote on-the-wire testing using a real NIC. */
bool is_wire_client; /* use a real NIC and be client? */
bool is_wire_server; /* use a real NIC and be server? */
char *wire_client_device; /* iface name for send/receive */
char *wire_server_device; /* iface name for send/receive */
struct ip_address wire_server_ip; /* IP of on-the-wire server */
char *wire_server_ip_string; /* malloc-ed server IP string */
u16 wire_server_port; /* the port the server listens on */
};
/* Top-level info about the invocation of a test script */
struct invocation {
int argc; /* count of process command line args */
char **argv; /* process command line args */
struct config *config; /* run-time configuration */
struct script *script; /* parse tree of the script to run */
};
/* Set default configuration */
extern void set_default_config(struct config *config);
/* Parse the "non-fatal" command line options given the (comma-delimited) string
* from the command line. Modifies the associated booleans in the given
* config.
*/
extern void parse_non_fatal_arg(char *arg, struct config *config);
/* Perform configuration processing that can only be done after we've
* seen the full config. For example, we only know how to use IP
* addresses after we know if we're doing ipv4, ipv4-mapped-ipv6, or
* ipv6. Call this after all options have been parsed.
*/
extern void finalize_config(struct config *config);
extern void show_usage(void);
/* Parse command line options. Returns a pointer to the first argument
* beyond the options.
*/
extern char **parse_command_line_options(int argc, char *argv[],
struct config *config);
/* The parser calls this function to finalize processing of config info. */
extern void parse_and_finalize_config(struct invocation *invocation);
#endif /* __CONFIG_H__ */
#!/bin/sh
ln -sf Makefile.`uname` Makefile
/*
* Copyright 2013 Google Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* 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. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/*
* Author: ncardwell@google.com (Neal Cardwell)
*
* Ethernet-related declarations.
*
* We cannot include the kernel's linux/if_ether.h because this tool
* tries to compile and work for basically any Linux/BSD kernel
* version. So we have our version of the Ethernet-related
* declarations we require here.
*/
#ifndef __ETHERNET_H__
#define __ETHERNET_H__
#include "types.h"
/* Bytes in an Ethernet address. */
#define ETH_ALEN 6
/* Ethernet header ether_type values. */
#define ETHERTYPE_IP 0x0800 /* IP protocol version 4 */
#define ETHERTYPE_IPV6 0x86dd /* IP protocol version 6 */
/* To tell a packet socket that you want traffic for all protocols. */
#define ETH_P_ALL 0x0003
/* Ethernet address. */
struct ether_addr {
u8 ether_addr_octet[ETH_ALEN];
} __attribute__ ((__packed__));
/* Ethernet header. */
struct ether_header {
u8 ether_dhost[ETH_ALEN]; /* destination Ethernet address */
u8 ether_shost[ETH_ALEN]; /* source Ethernet address */
u16 ether_type; /* packet type ID field */
} __attribute__ ((__packed__));
static inline void ether_copy(void *dst, const void *src)
{
memcpy(dst, src, sizeof(struct ether_addr));
}
/* Return the ether_type field for packets of the given address family. */
static inline u16 ether_type_for_family(int address_family)
{
if (address_family == AF_INET)
return ETHERTYPE_IP;
else if (address_family == AF_INET6)
return ETHERTYPE_IPV6;
else
assert(!"bad address family");
}
#endif /* __ETHERNET_H__ */
// Test fast retransmit with 4 packets outstanding, receiver sending SACKs.
// In this variant the receiver supports SACK.
// Establish a connection.
0 socket(..., SOCK_STREAM, IPPROTO_TCP) = 3
+0 setsockopt(3, SOL_SOCKET, SO_REUSEADDR, [1], 4) = 0
+0 bind(3, ..., ...) = 0
+0 listen(3, 1) = 0
+0 < S 0:0(0) win 32792 <mss 1000,sackOK,nop,nop,nop,wscale 7>
+0 > S. 0:0(0) ack 1 <...>
+.1 < . 1:1(0) ack 1 win 257
+0 accept(3, ..., ...) = 4
// Send 1 data segment and get an ACK, so cwnd is now 4.
+0 write(4, ..., 1000) = 1000
+0 > P. 1:1001(1000) ack 1
+.1 < . 1:1(0) ack 1001 win 257
// Write 4 data segments.
+0 write(4, ..., 4000) = 4000
+0 > . 1001:2001(1000) ack 1
+0 > . 2001:3001(1000) ack 1
+0 > . 3001:4001(1000) ack 1
+0 > P. 4001:5001(1000) ack 1
// Get 3 SACKs.
+.1 < . 1:1(0) ack 1001 win 257 <sack 2001:3001,nop,nop>
+0 < . 1:1(0) ack 1001 win 257 <sack 2001:4001,nop,nop>
+0 < . 1:1(0) ack 1001 win 257 <sack 2001:5001,nop,nop>
// We've received 3 duplicate ACKs, so we do a fast retransmit.
+0 > . 1001:2001(1000) ack 1
// Receiver ACKs all data.
+.1 < . 1:1(0) ack 6001 win 257
// Test fast retransmit with 4 packets outstanding, receiver sending SACKs.
// In this variant the receiver supports SACK.
// Establish a connection.
0 socket(..., SOCK_STREAM, IPPROTO_TCP) = 3
+0 setsockopt(3, SOL_SOCKET, SO_REUSEADDR, [1], 4) = 0
+0 bind(3, ..., ...) = 0
+0 listen(3, 1) = 0
+0 < S 0:0(0) win 32792 <mss 1000,sackOK,nop,nop,nop,wscale 7>
+0 > S. 0:0(0) ack 1 <...>
+.1 < . 1:1(0) ack 1 win 257
+0 accept(3, ..., ...) = 4
// Send 1 data segment and get an ACK, so cwnd is now 4.
+0 write(4, ..., 1000) = 1000
+0 > P. 1:1001(1000) ack 1
+.1 < . 1:1(0) ack 1001 win 257
// Write 4 data segments.
+0 write(4, ..., 4000) = 4000
+0 > P. 1001:5001(4000) ack 1
// Get 3 SACKs.
+.1 < . 1:1(0) ack 1001 win 257 <sack 2001:3001,nop,nop>
+0 < . 1:1(0) ack 1001 win 257 <sack 2001:4001,nop,nop>
+0 < . 1:1(0) ack 1001 win 257 <sack 2001:5001,nop,nop>
// We've received 3 duplicate ACKs, so we do a fast retransmit.
+0 > . 1001:2001(1000) ack 1
// Receiver ACKs all data.
+.1 < . 1:1(0) ack 6001 win 257
/*
* Copyright 2013 Google Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* 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. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/*
* Author: ncardwell@google.com (Neal Cardwell)
*
* FreeBSD does not have an fmemopen(), so we roll our own minimalist
* implementation here.
*/
#include "types.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "fmemopen.h"
#if !defined(HAVE_FMEMOPEN)
struct fmemopen_read_state {
char *next; /* the next byte to return */
char *end; /* the byte after the end of the string */
};
static int fmemopen_readfn(void *cookie, char *buf, int len)
{
struct fmemopen_read_state *read_cookie =
(struct fmemopen_read_state *)cookie;
int bytes = 0;
assert(read_cookie->next <= read_cookie->end);
if (read_cookie->next == read_cookie->end)
return 0;
bytes = read_cookie->end - read_cookie->next;
if (len < bytes)
bytes = len;
memcpy(buf, read_cookie->next, bytes);
read_cookie->next += bytes;
return bytes;
}
FILE *fmemopen(char *str, size_t size, const char *mode)
{
FILE *f = NULL;
struct fmemopen_read_state *read_cookie;
assert(strcmp(mode, "r") == 0); /* only support read for now */
read_cookie = calloc(1, sizeof(struct fmemopen_read_state));
read_cookie->next = str;
read_cookie->end = str + size;
f = fropen(read_cookie, fmemopen_readfn);
if (!f) {
free(read_cookie);
return NULL;
}
return f;
}
#endif /* HAVE_FMEMOPEN */
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment