Initial Commit, working C89 IP address analyzer/net architecture planner
This commit is contained in:
commit
863aa70120
7 changed files with 1563 additions and 0 deletions
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
# Don't commit the binary or pycache (local-run only artifacts)
|
||||
ipvarch
|
||||
__pycache__/
|
||||
34
Makefile
Normal file
34
Makefile
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
# IPVarch - Internet Protocol Version Architect
|
||||
# Primary compiler is tcc (Tiny C Compiler); falls back to gcc automatically.
|
||||
# Override explicitly if desired: make CC=clang
|
||||
|
||||
CC := $(shell command -v tcc 2>/dev/null || command -v gcc 2>/dev/null || echo cc)
|
||||
CFLAGS := -Wall
|
||||
TARGET := ipvarch
|
||||
|
||||
.PHONY: all check test test-sanitize clean
|
||||
|
||||
all: $(TARGET)
|
||||
|
||||
$(TARGET): ipvarch.c
|
||||
$(CC) $(CFLAGS) -o $@ ipvarch.c
|
||||
|
||||
# Strict C89 conformance + glibc fortify build (needs gcc; tcc has no such mode)
|
||||
check:
|
||||
@if command -v gcc >/dev/null 2>&1; then \
|
||||
gcc -std=c89 -pedantic -Wall -Wextra -D_FORTIFY_SOURCE=2 -O2 \
|
||||
-o /tmp/opencode/ipvarch-check ipvarch.c && \
|
||||
echo "check: strict C89 build OK (/tmp/opencode/ipvarch-check)"; \
|
||||
else \
|
||||
echo "check: gcc not available, skipping (tcc has no strict mode)"; fi
|
||||
|
||||
# Validity test suite (python3, stdlib only)
|
||||
test: $(TARGET)
|
||||
python3 tests/runner.py --bin ./$(TARGET)
|
||||
|
||||
# Full matrix rebuilt with gcc/clang ASan+UBSan instrumentation
|
||||
test-sanitize: $(TARGET)
|
||||
python3 tests/runner.py --bin ./$(TARGET) --sanitize
|
||||
|
||||
clean:
|
||||
rm -f $(TARGET) /tmp/opencode/ipvarch-asan
|
||||
86
README.md
Normal file
86
README.md
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
# IPVarch — Internet Protocol Version Architect
|
||||
|
||||
A tiny ANSI C (C89, tcc-friendly) command-line tool for inspecting and
|
||||
planning IP addresses and IPv4 networks. Rules follow `ipaddrinfo.html`
|
||||
(IPv4 classes A–E, RFC 1918 private ranges, IPv6 unicast/multicast/
|
||||
link-local/unique-local).
|
||||
|
||||
## Usage
|
||||
|
||||
```text
|
||||
ipvarch <address> inspect an IPv4 or IPv6 address
|
||||
ipvarch --plan-network <ipv4>/<prefix> plan a network (/8 /16 /24 /32)
|
||||
ipvarch --random-ipv4network <scope> <prefix> random valid network plan
|
||||
```
|
||||
|
||||
### Examples
|
||||
|
||||
```
|
||||
$ ipvarch 192.168.1.1
|
||||
Address: 192.168.1.1
|
||||
Type: IPv4
|
||||
Class: C
|
||||
Scope: Private (RFC 1918)
|
||||
Octets: 192, 168, 1, 1
|
||||
|
||||
$ ipvarch 2001:db8::1
|
||||
Address: 2001:db8::1
|
||||
Type: IPv6
|
||||
Class: n/a (IPv6 has no address classes)
|
||||
Scope: Public (global unicast)
|
||||
Groups: 2001 0db8 0000 0000 0000 0000 0000 0001
|
||||
Octets: 32, 1, 13, 184, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
|
||||
|
||||
$ ipvarch --plan-network 192.168.1.0/24
|
||||
┌───────────────────┬───────────────────────────────┐
|
||||
│ IPVarch Network Plan - 192.168.1.0 /24 │
|
||||
├───────────────────┼───────────────────────────────┤
|
||||
│ Network address │ 192.168.1.0 │
|
||||
│ Netmask │ 255.255.255.0 /24 │
|
||||
│ Broadcast │ 192.168.1.255 │
|
||||
│ Usable host range │ 192.168.1.1 - 192.168.1.254 │
|
||||
│ Usable hosts │ 254 │
|
||||
│ Class │ C │
|
||||
│ Scope │ Private (RFC 1918) │
|
||||
│ Gateway IP │ 192.168.1.1 │
|
||||
│ DNS/DHCP server │ 192.168.1.2 │
|
||||
│ DHCP pool │ 192.168.1.100 - 192.168.1.254 │
|
||||
└───────────────────┴───────────────────────────────┘
|
||||
```
|
||||
|
||||
`--plan-network` takes literal CIDR masks (`/8`=255.0.0.0, `/16`, `/24`,
|
||||
`/32`=single host). Host bits must be zero (it tells you the canonical
|
||||
network address otherwise). The gateway is the first usable host, the
|
||||
DNS/DHCP server the second, and the DHCP pool is the fixed last-octet
|
||||
`.100`–`.254` range.
|
||||
|
||||
`--random-ipv4network private|public /8|/16|/24|/32` generates a random
|
||||
valid network constrained to real private space (10/8, 172.16/12,
|
||||
192.168/16) or public/global-unicast space (never multicast, loopback,
|
||||
reserved, or documentation ranges) and prints the same plan table.
|
||||
|
||||
## Testing (Make + python3, stdlib only)
|
||||
|
||||
```sh
|
||||
make # build (tcc, falls back to gcc)
|
||||
make test # full validity matrix: info, canonicalization, plan,
|
||||
# random (statistical), invalid inputs, edge cases, usage
|
||||
make test-sanitize # rebuild with gcc/clang ASan+UBSan and run full matrix
|
||||
make check # strict C89 build: -std=c89 -pedantic -Wall -Wextra
|
||||
make clean
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- The runner prints `PASS`/`FAIL` per case and exits nonzero on failure.
|
||||
- Run a subset with `python3 tests/runner.py --bin ./ipvarch --filter plan`.
|
||||
- Add cases as simple dict entries in `tests/cases.py`.
|
||||
- Memory safety runs through compiler instrumentation (tcc has no
|
||||
sanitizer support, so `test-sanitize` uses gcc/clang); the runner
|
||||
detects sanitizer aborts explicitly and reports them per case.
|
||||
|
||||
## Exit codes
|
||||
|
||||
- `0` — success
|
||||
- `1` — any error (bad address, bad prefix, bad usage); the message goes
|
||||
to stderr prefixed with `ipvarch: error:`.
|
||||
114
ipaddrinfo.html
Normal file
114
ipaddrinfo.html
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
<div>
|
||||
<h3>Understanding IP Addresses</h3>
|
||||
<!-- IPv4 Education -->
|
||||
<div>
|
||||
<h4>IPv4 Address Format</h4>
|
||||
<div>
|
||||
<p>
|
||||
IPv4 addresses consist of four octets (numbers from 0-255) separated by dots.
|
||||
Each octet represents 8 bits, making IPv4 addresses 32 bits total.
|
||||
</p>
|
||||
<div>
|
||||
<h5>IPv4 Address Classes:</h5>
|
||||
<ul>
|
||||
<li><strong>Class A:</strong> <span>1.0.0.0 - 126.255.255.255</span> (Large networks)</li>
|
||||
<li><strong>Class B:</strong> <span>128.0.0.0 - 191.255.255.255</span> (Medium networks)</li>
|
||||
<li><strong>Class C:</strong> <span>192.0.0.0 - 223.255.255.255</span> (Small networks)</li>
|
||||
<li><strong>Class D:</strong> <span>224.0.0.0 - 239.255.255.255</span> (Multicast)</li>
|
||||
<li><strong>Class E:</strong> <span>240.0.0.0 - 255.255.255.255</span> (Reserved)</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<h5>Private IP Ranges:</h5>
|
||||
<ul>
|
||||
<li><code>10.0.0.0/8</code> - <span>10.0.0.0 to 10.255.255.255</span></li>
|
||||
<li><code>172.16.0.0/12</code> - <span>172.16.0.0 to 172.31.255.255</span></li>
|
||||
<li><code>192.168.0.0/16</code> - <span>192.168.0.0 to 192.168.255.255</span></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- IPv6 Education -->
|
||||
<div>
|
||||
<h4>IPv6 Address Format</h4>
|
||||
<div>
|
||||
<p>
|
||||
IPv6 addresses are 128 bits long and written as eight groups of four hexadecimal digits,
|
||||
separated by colons. They can be compressed using double colons (::) to represent consecutive zeros.
|
||||
</p>
|
||||
<div>
|
||||
<h5>IPv6 Address Types:</h5>
|
||||
<ul>
|
||||
<li><strong>Unicast:</strong> Identifies a single interface</li>
|
||||
<li><strong>Multicast:</strong> Identifies multiple interfaces (starts with ff)</li>
|
||||
<li><strong>Link-Local:</strong> Used on single network segment (fe80::/10)</li>
|
||||
<li><strong>Unique Local:</strong> Private addresses (fc00::/7)</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<h5>IPv6 Notation Examples:</h5>
|
||||
<ul>
|
||||
<li><strong>Full:</strong> <code>2001:0db8:0000:0000:0000:0000:0000:0001</code></li>
|
||||
<li><strong>Compressed:</strong> <code>2001:db8::1</code></li>
|
||||
<li><strong>Mixed:</strong> <code>2001:db8::192.168.1.1</code></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Common Examples -->
|
||||
<div>
|
||||
<h4>Try These Examples</h4>
|
||||
<div>
|
||||
<div>
|
||||
<h5>Valid IPv4 Addresses</h5>
|
||||
<ul>
|
||||
<li>
|
||||
<button type="button">
|
||||
192.168.1.1
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button type="button">
|
||||
10.0.0.1
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button type="button">
|
||||
172.16.254.1
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button type="button">
|
||||
8.8.8.8
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<h5>Valid IPv6 Addresses</h5>
|
||||
<ul>
|
||||
<li>
|
||||
<button type="button">
|
||||
2001:db8::1
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button type="button">
|
||||
fe80::1
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button type="button">
|
||||
::1
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button type="button">
|
||||
2001:db8::192.168.1.1
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
809
ipvarch.c
Normal file
809
ipvarch.c
Normal file
|
|
@ -0,0 +1,809 @@
|
|||
/*
|
||||
* ipvarch.c - IPVarch: Internet Protocol Version Architect
|
||||
*
|
||||
* A small ANSI C (C89) command line tool for inspecting and planning
|
||||
* IP addresses and IPv4 networks.
|
||||
*
|
||||
* Modes:
|
||||
* ipvarch <address> inspect an IPv4 or IPv6 address
|
||||
* ipvarch --plan-network <ipv4>/<prefix> print a network plan table
|
||||
* ipvarch --random-ipv4network <scope> <prefix>
|
||||
* generate a random valid plan
|
||||
*
|
||||
* Targets tcc (Tiny C Compiler); also builds with gcc -std=c89 -pedantic.
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdarg.h>
|
||||
#include <time.h>
|
||||
|
||||
typedef unsigned char byte;
|
||||
|
||||
/* UTF-8 encoded box drawing characters (U+2500 block). */
|
||||
#define BOX_H "\xe2\x94\x80" /* horizontal line */
|
||||
#define BOX_V "\xe2\x94\x82" /* vertical line */
|
||||
#define BOX_TL "\xe2\x94\x8c" /* top left ┌ */
|
||||
#define BOX_TR "\xe2\x94\x90" /* top right ┐ */
|
||||
#define BOX_BL "\xe2\x94\x94" /* bottom left └ */
|
||||
#define BOX_BR "\xe2\x94\x98" /* bottom right ┘ */
|
||||
#define BOX_TJ "\xe2\x94\xac" /* top join ┬ */
|
||||
#define BOX_BJ "\xe2\x94\xb4" /* bottom join ┴ */
|
||||
#define BOX_LJ "\xe2\x94\x9c" /* left join ├ */
|
||||
#define BOX_RJ "\xe2\x94\xa4" /* right join ┤ */
|
||||
#define BOX_CJ "\xe2\x94\xbc" /* centre join ┼ */
|
||||
|
||||
typedef const char *Row[2];
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Helpers */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
static void die(const char *fmt, ...)
|
||||
{
|
||||
va_list ap;
|
||||
fprintf(stderr, "ipvarch: error: ");
|
||||
va_start(ap, fmt);
|
||||
vfprintf(stderr, fmt, ap);
|
||||
va_end(ap);
|
||||
fputc('\n', stderr);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
static void usage(void)
|
||||
{
|
||||
printf("IPVarch - Internet Protocol Version Architect\n\n");
|
||||
printf("Usage:\n");
|
||||
printf(" ipvarch <address> inspect an IPv4/IPv6 address\n");
|
||||
printf(" ipvarch --plan-network <ipv4>/<prefix> plan a network (/8 /16 /24 /32)\n");
|
||||
printf(" ipvarch --random-ipv4network <scope> <prefix>\n");
|
||||
printf(" random valid network plan\n\n");
|
||||
printf("Examples:\n");
|
||||
printf(" ipvarch 192.168.1.1\n");
|
||||
printf(" ipvarch 2001:db8::1\n");
|
||||
printf(" ipvarch --plan-network 172.16.4.0/16\n");
|
||||
printf(" ipvarch --random-ipv4network private /24\n");
|
||||
return;
|
||||
}
|
||||
|
||||
/* Display width of a UTF-8 string (continuation bytes occupy no column). */
|
||||
static int dwidth(const char *s)
|
||||
{
|
||||
int w = 0;
|
||||
while (*s != '\0') {
|
||||
if ((((unsigned char)*s) & 0xC0) != 0x80)
|
||||
w++;
|
||||
s++;
|
||||
}
|
||||
return w;
|
||||
}
|
||||
|
||||
static void dashes(int n)
|
||||
{
|
||||
while (n-- > 0)
|
||||
fputs(BOX_H, stdout);
|
||||
return;
|
||||
}
|
||||
|
||||
static void padcell(const char *s, int w)
|
||||
{
|
||||
int d = dwidth(s) + 1;
|
||||
putchar(' ');
|
||||
fputs(s, stdout);
|
||||
while (d < w) {
|
||||
putchar(' ');
|
||||
d++;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
static void centercell(const char *s, int w)
|
||||
{
|
||||
int d = dwidth(s) + 1;
|
||||
int l = (w - d) / 2;
|
||||
int r = w - d - l;
|
||||
while (l-- > 0)
|
||||
putchar(' ');
|
||||
putchar(' ');
|
||||
fputs(s, stdout);
|
||||
while (r-- > 0)
|
||||
putchar(' ');
|
||||
return;
|
||||
}
|
||||
|
||||
static void print_table(const char *title, const char *rows[][2], int nrows)
|
||||
{
|
||||
int w1 = 0, w2 = 0, tw, i;
|
||||
|
||||
for (i = 0; i < nrows; i++) {
|
||||
int a = dwidth(rows[i][0]) + 2; /* room for cell padding */
|
||||
int b = dwidth(rows[i][1]) + 2;
|
||||
if (a > w1) w1 = a;
|
||||
if (b > w2) w2 = b;
|
||||
}
|
||||
tw = dwidth(title) + 2;
|
||||
if (tw > w1 + w2 - 1)
|
||||
w2 = tw - w1 + 1;
|
||||
|
||||
fputs(BOX_TL, stdout); dashes(w1); fputs(BOX_TJ, stdout);
|
||||
dashes(w2); fputs(BOX_TR "\n", stdout);
|
||||
|
||||
fputs(BOX_V, stdout); centercell(title, w1 + w2 + 1); fputs(BOX_V "\n", stdout);
|
||||
|
||||
fputs(BOX_LJ, stdout); dashes(w1); fputs(BOX_CJ, stdout);
|
||||
dashes(w2); fputs(BOX_RJ "\n", stdout);
|
||||
|
||||
for (i = 0; i < nrows; i++) {
|
||||
fputs(BOX_V, stdout); padcell(rows[i][0], w1);
|
||||
fputs(BOX_V, stdout); padcell(rows[i][1], w2);
|
||||
fputs(BOX_V "\n", stdout);
|
||||
}
|
||||
|
||||
fputs(BOX_BL, stdout); dashes(w1); fputs(BOX_BJ, stdout);
|
||||
dashes(w2); fputs(BOX_BR "\n", stdout);
|
||||
return;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Parsing */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
static int parse_ipv4(const char *s, byte out[4])
|
||||
{
|
||||
const char *p = s;
|
||||
int i;
|
||||
|
||||
for (i = 0; i < 4; i++) {
|
||||
int v = 0, digits = 0;
|
||||
if (i > 0) {
|
||||
if (*p != '.')
|
||||
return 0;
|
||||
p++;
|
||||
}
|
||||
while (*p >= '0' && *p <= '9') {
|
||||
v = v * 10 + (*p - '0');
|
||||
digits++;
|
||||
p++;
|
||||
if (digits > 3 || v > 255)
|
||||
return 0;
|
||||
}
|
||||
if (digits == 0)
|
||||
return 0;
|
||||
out[i] = (byte)v;
|
||||
}
|
||||
if (*p != '\0')
|
||||
return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int hexval(int c)
|
||||
{
|
||||
if (c >= '0' && c <= '9') return c - '0';
|
||||
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Parse a colon separated piece list such as "ffff:0:192.168.1.1".
|
||||
* The final token may be an embedded IPv4 address (two groups).
|
||||
* Returns count via *cnt and 1 on success. */
|
||||
static int parse_piece(const char *piece, unsigned short *gr, int *cnt)
|
||||
{
|
||||
char buf[48];
|
||||
byte v4[4];
|
||||
const char *p;
|
||||
int n = 0;
|
||||
|
||||
if (strlen(piece) >= sizeof(buf))
|
||||
return 0;
|
||||
strcpy(buf, piece);
|
||||
p = buf;
|
||||
|
||||
while (*p != '\0') {
|
||||
const char *tok = p;
|
||||
int hasdot = 0;
|
||||
|
||||
while (*p != '\0' && *p != ':') {
|
||||
if (*p == '.')
|
||||
hasdot = 1;
|
||||
p++;
|
||||
}
|
||||
|
||||
if (hasdot) {
|
||||
if (*p != '\0') /* embedded IPv4 must be last */
|
||||
return 0;
|
||||
if (!parse_ipv4(tok, v4))
|
||||
return 0;
|
||||
if (n > 6)
|
||||
return 0;
|
||||
gr[n++] = (unsigned short)((v4[0] << 8) | v4[1]);
|
||||
gr[n++] = (unsigned short)((v4[2] << 8) | v4[3]);
|
||||
} else {
|
||||
int len = (int)(p - tok);
|
||||
int j, val = 0;
|
||||
if (len < 1 || len > 4)
|
||||
return 0;
|
||||
for (j = 0; j < len; j++) {
|
||||
int hv = hexval((unsigned char)tok[j]);
|
||||
if (hv < 0)
|
||||
return 0;
|
||||
val = (val << 4) | hv;
|
||||
}
|
||||
if (n >= 8)
|
||||
return 0;
|
||||
gr[n++] = (unsigned short)val;
|
||||
}
|
||||
|
||||
if (*p == '\0')
|
||||
break;
|
||||
p++; /* skip ':' */
|
||||
if (*p == '\0') /* trailing colon */
|
||||
return 0;
|
||||
}
|
||||
|
||||
*cnt = n;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Parse an IPv6 address (RFC 4291 text form, compressed "::" allowed,
|
||||
* embedded IPv4 in the tail allowed) into 16 bytes. */
|
||||
static int parse_ipv6(const char *s, byte out[16])
|
||||
{
|
||||
char buf[80];
|
||||
char *dd, *head, *tail;
|
||||
unsigned short gr[16];
|
||||
int nh = 0, nt = 0, total, i;
|
||||
|
||||
if (strlen(s) >= sizeof(buf))
|
||||
return 0;
|
||||
strcpy(buf, s);
|
||||
|
||||
dd = strstr(buf, "::");
|
||||
if (dd != NULL) {
|
||||
if (strstr(dd + 1, "::") != NULL)
|
||||
return 0;
|
||||
*dd = '\0';
|
||||
head = buf;
|
||||
tail = dd + 2;
|
||||
/* An embedded IPv4 is only valid in the tail piece. */
|
||||
if (strchr(head, '.') != NULL && strchr(head, ':') == NULL)
|
||||
return 0;
|
||||
} else {
|
||||
head = buf;
|
||||
tail = NULL;
|
||||
}
|
||||
|
||||
if (!parse_piece(head, gr, &nh))
|
||||
return 0;
|
||||
if (tail != NULL) {
|
||||
if (!parse_piece(tail, gr + nh, &nt))
|
||||
return 0;
|
||||
}
|
||||
total = nh + nt;
|
||||
|
||||
if (dd != NULL) {
|
||||
if (total > 7) /* "::" must stand for zero groups */
|
||||
return 0;
|
||||
memset(out, 0, 16);
|
||||
for (i = 0; i < nh; i++) {
|
||||
out[2 * i] = (byte)(gr[i] >> 8);
|
||||
out[2 * i + 1] = (byte)(gr[i] & 0xFF);
|
||||
}
|
||||
for (i = 0; i < nt; i++) {
|
||||
int k = 8 - nt + i;
|
||||
out[2 * k] = (byte)(gr[nh + i] >> 8);
|
||||
out[2 * k + 1] = (byte)(gr[nh + i] & 0xFF);
|
||||
}
|
||||
} else {
|
||||
if (total != 8)
|
||||
return 0;
|
||||
for (i = 0; i < 8; i++) {
|
||||
out[2 * i] = (byte)(gr[i] >> 8);
|
||||
out[2 * i + 1] = (byte)(gr[i] & 0xFF);
|
||||
}
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Formatting */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
static void fmt_v4(char *dst, const byte a[4])
|
||||
{
|
||||
sprintf(dst, "%u.%u.%u.%u",
|
||||
(unsigned)a[0], (unsigned)a[1], (unsigned)a[2], (unsigned)a[3]);
|
||||
return;
|
||||
}
|
||||
|
||||
/* Compressed RFC 5952 style text form. */
|
||||
static void fmt_v6(char *dst, const byte a[16])
|
||||
{
|
||||
unsigned short g[8];
|
||||
int i, zs = -1, zl = 0, bs = -1, bl = 0, first = 1, suppress = 0;
|
||||
char *p = dst;
|
||||
|
||||
for (i = 0; i < 8; i++)
|
||||
g[i] = (unsigned short)((a[2 * i] << 8) | a[2 * i + 1]);
|
||||
|
||||
for (i = 0; i < 8; i++) {
|
||||
if (g[i] == 0) {
|
||||
if (zl == 0)
|
||||
zs = i;
|
||||
zl++;
|
||||
if (zl > bl) {
|
||||
bl = zl;
|
||||
bs = zs;
|
||||
}
|
||||
} else {
|
||||
zl = 0;
|
||||
}
|
||||
}
|
||||
if (bl < 2) {
|
||||
bs = 0;
|
||||
bl = 0;
|
||||
}
|
||||
|
||||
if (bl == 8) {
|
||||
strcpy(dst, "::");
|
||||
return;
|
||||
}
|
||||
|
||||
i = 0;
|
||||
while (i < 8) {
|
||||
if (bl > 0 && i >= bs && i < bs + bl) {
|
||||
*p++ = ':';
|
||||
*p++ = ':';
|
||||
suppress = 1; /* "::" replaces the join */
|
||||
first = 0;
|
||||
i = bs + bl;
|
||||
continue;
|
||||
}
|
||||
if (!first && !suppress)
|
||||
*p++ = ':';
|
||||
suppress = 0;
|
||||
p += sprintf(p, "%x", (unsigned)g[i]);
|
||||
first = 0;
|
||||
i++;
|
||||
}
|
||||
*p = '\0';
|
||||
return;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Classification (rules per ipaddrinfo.html) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
static void classify_v4(const byte a[4], const char **cls, const char **scope)
|
||||
{
|
||||
if (a[0] == 0) {
|
||||
*cls = "0 (reserved)";
|
||||
*scope = "Reserved (this network)";
|
||||
} else if (a[0] < 128) {
|
||||
*cls = "A";
|
||||
*scope = "Public";
|
||||
} else if (a[0] < 192) {
|
||||
*cls = "B";
|
||||
*scope = "Public";
|
||||
} else if (a[0] < 224) {
|
||||
*cls = "C";
|
||||
*scope = "Public";
|
||||
} else if (a[0] < 240) {
|
||||
*cls = "D";
|
||||
*scope = "Multicast";
|
||||
} else {
|
||||
*cls = "E";
|
||||
*scope = "Reserved";
|
||||
}
|
||||
|
||||
if (a[0] == 127)
|
||||
*scope = "Loopback";
|
||||
else if (a[0] == 10)
|
||||
*scope = "Private (RFC 1918)";
|
||||
else if (a[0] == 172 && a[1] >= 16 && a[1] <= 31)
|
||||
*scope = "Private (RFC 1918)";
|
||||
else if (a[0] == 192 && a[1] == 168)
|
||||
*scope = "Private (RFC 1918)";
|
||||
else if (a[0] == 169 && a[1] == 254)
|
||||
*scope = "Link-local (APIPA)";
|
||||
else if (a[0] == 192 && a[1] == 0 && a[2] == 2)
|
||||
*scope = "Documentation (TEST-NET-1)";
|
||||
else if (a[0] == 198 && a[1] == 51 && a[2] == 100)
|
||||
*scope = "Documentation (TEST-NET-2)";
|
||||
else if (a[0] == 203 && a[1] == 0 && a[2] == 113)
|
||||
*scope = "Documentation (TEST-NET-3)";
|
||||
else if (a[0] == 100 && a[1] >= 64 && a[1] <= 127)
|
||||
*scope = "Shared (CGNAT)";
|
||||
else if (a[0] == 198 && (a[1] == 18 || a[1] == 19))
|
||||
*scope = "Benchmarking";
|
||||
return;
|
||||
}
|
||||
|
||||
static void classify_v6(const byte a[16], const char **scope)
|
||||
{
|
||||
int i;
|
||||
|
||||
for (i = 0; i < 16; i++) {
|
||||
if (a[i] != 0)
|
||||
break;
|
||||
}
|
||||
if (i == 16) {
|
||||
*scope = "Unspecified (::)";
|
||||
return;
|
||||
}
|
||||
if (a[0] == 0 && a[1] == 0 && a[2] == 0 && a[3] == 0 && a[4] == 0 &&
|
||||
a[5] == 0 && a[6] == 0 && a[7] == 0 && a[8] == 0 && a[9] == 0 &&
|
||||
a[10] == 0 && a[11] == 0 && a[12] == 0 && a[13] == 0 &&
|
||||
a[14] == 0 && a[15] == 1) {
|
||||
*scope = "Loopback (::1)";
|
||||
return;
|
||||
}
|
||||
if (a[0] == 0 && a[1] == 0 && a[2] == 0 && a[3] == 0 && a[4] == 0 &&
|
||||
a[5] == 0 && a[6] == 0 && a[7] == 0 && a[8] == 0 && a[9] == 0 &&
|
||||
a[10] == 0xFF && a[11] == 0xFF) {
|
||||
*scope = "IPv4-mapped (::ffff:0:0/96)";
|
||||
return;
|
||||
}
|
||||
if (a[0] == 0xFF) {
|
||||
*scope = "Multicast (ff00::/8)";
|
||||
return;
|
||||
}
|
||||
if (a[0] == 0xFE && (a[1] & 0xC0) == 0x80) {
|
||||
*scope = "Link-local (fe80::/10)";
|
||||
return;
|
||||
}
|
||||
if ((a[0] & 0xFE) == 0xFC) {
|
||||
*scope = "Private (unique local, fc00::/7)";
|
||||
return;
|
||||
}
|
||||
if (a[0] == 0x20 && a[1] == 0x01 && a[2] == 0x0D && a[3] == 0xB8) {
|
||||
*scope = "Documentation (2001:db8::/32)";
|
||||
return;
|
||||
}
|
||||
*scope = "Public (global unicast)";
|
||||
return;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* IPv4 network math */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
static unsigned long v4_to_u32(const byte a[4])
|
||||
{
|
||||
return ((unsigned long)a[0] << 24) | ((unsigned long)a[1] << 16) |
|
||||
((unsigned long)a[2] << 8) | (unsigned long)a[3];
|
||||
}
|
||||
|
||||
static void u32_to_v4(unsigned long u, byte out[4])
|
||||
{
|
||||
out[0] = (byte)((u >> 24) & 0xFF);
|
||||
out[1] = (byte)((u >> 16) & 0xFF);
|
||||
out[2] = (byte)((u >> 8) & 0xFF);
|
||||
out[3] = (byte)(u & 0xFF);
|
||||
return;
|
||||
}
|
||||
|
||||
static void print_plan(unsigned long net, int prefix)
|
||||
{
|
||||
unsigned long mask, bc, cnt, firstu, lastu;
|
||||
byte a[4], m4[4], b4[4], lo4[4], hi4[4];
|
||||
char tmp1[24], tmp2[24];
|
||||
char nb[24], mb[40], bb[24], rb[64], cb[24], gb[24], db[24], pb[64];
|
||||
char sb[48], tb[80];
|
||||
const char *cls, *scope;
|
||||
Row rows[10];
|
||||
int nr = 0;
|
||||
|
||||
mask = (prefix == 8) ? 0xFF000000ul :
|
||||
(prefix == 16) ? 0xFFFF0000ul :
|
||||
(prefix == 24) ? 0xFFFFFF00ul : 0xFFFFFFFFul;
|
||||
bc = net | (~mask & 0xFFFFFFFFul);
|
||||
|
||||
u32_to_v4(net, a);
|
||||
u32_to_v4(mask, m4);
|
||||
classify_v4(a, &cls, &scope);
|
||||
|
||||
fmt_v4(nb, a);
|
||||
fmt_v4(tmp1, m4);
|
||||
sprintf(mb, "%s /%d", tmp1, prefix);
|
||||
|
||||
if (prefix == 32) {
|
||||
strcpy(bb, "n/a (single host)");
|
||||
strcpy(rb, nb); /* the host address itself */
|
||||
strcpy(cb, "1");
|
||||
strcpy(gb, "n/a (single host)");
|
||||
strcpy(db, "n/a (single host)");
|
||||
strcpy(pb, "disabled (single-host network)");
|
||||
} else {
|
||||
firstu = net + 1;
|
||||
lastu = bc - 1;
|
||||
cnt = (1ul << (32 - prefix)) - 2;
|
||||
|
||||
u32_to_v4(bc, b4);
|
||||
fmt_v4(bb, b4);
|
||||
u32_to_v4(firstu, lo4);
|
||||
fmt_v4(tmp1, lo4);
|
||||
u32_to_v4(lastu, hi4);
|
||||
fmt_v4(tmp2, hi4);
|
||||
sprintf(rb, "%s - %s", tmp1, tmp2);
|
||||
sprintf(cb, "%lu", cnt);
|
||||
|
||||
fmt_v4(gb, lo4); /* gateway: first usable */
|
||||
u32_to_v4(firstu + 1, hi4);
|
||||
fmt_v4(db, hi4); /* DNS/DHCP: next usable */
|
||||
|
||||
hi4[0] = a[0]; hi4[1] = a[1]; hi4[2] = a[2]; hi4[3] = 254;
|
||||
lo4[3] = 100;
|
||||
fmt_v4(tmp1, lo4);
|
||||
fmt_v4(tmp2, hi4);
|
||||
sprintf(pb, "%s - %s", tmp1, tmp2);
|
||||
}
|
||||
|
||||
sprintf(sb, "%s", scope);
|
||||
sprintf(tb, "IPVarch Network Plan - %s /%d", nb, prefix);
|
||||
|
||||
rows[nr][0] = "Network address"; rows[nr][1] = nb; nr++;
|
||||
rows[nr][0] = "Netmask"; rows[nr][1] = mb; nr++;
|
||||
rows[nr][0] = "Broadcast"; rows[nr][1] = bb; nr++;
|
||||
rows[nr][0] = "Usable host range"; rows[nr][1] = rb; nr++;
|
||||
rows[nr][0] = "Usable hosts"; rows[nr][1] = cb; nr++;
|
||||
rows[nr][0] = "Class"; rows[nr][1] = cls; nr++;
|
||||
rows[nr][0] = "Scope"; rows[nr][1] = sb; nr++;
|
||||
rows[nr][0] = "Gateway IP"; rows[nr][1] = gb; nr++;
|
||||
rows[nr][0] = "DNS/DHCP server"; rows[nr][1] = db; nr++;
|
||||
rows[nr][0] = "DHCP pool"; rows[nr][1] = pb; nr++;
|
||||
|
||||
print_table(tb, rows, nr);
|
||||
return;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Random network generation */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
static int is_ok_public(const byte a[4])
|
||||
{
|
||||
if (a[0] == 0 || a[0] == 10 || a[0] == 127)
|
||||
return 0;
|
||||
if (a[0] == 172 && a[1] >= 16 && a[1] <= 31)
|
||||
return 0;
|
||||
if (a[0] == 192 && a[1] == 168)
|
||||
return 0;
|
||||
if (a[0] == 169 && a[1] == 254)
|
||||
return 0;
|
||||
if (a[0] == 100 && a[1] >= 64 && a[1] <= 127)
|
||||
return 0;
|
||||
if (a[0] == 198 && (a[1] == 18 || a[1] == 19))
|
||||
return 0;
|
||||
if (a[0] == 192 && a[1] == 0 && a[2] == 2)
|
||||
return 0;
|
||||
if (a[0] == 198 && a[1] == 51 && a[2] == 100)
|
||||
return 0;
|
||||
if (a[0] == 203 && a[1] == 0 && a[2] == 113)
|
||||
return 0;
|
||||
if (a[0] >= 224)
|
||||
return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void random_network(int prefix, int wantprivate, byte out[4])
|
||||
{
|
||||
int tries, r;
|
||||
byte a[4];
|
||||
|
||||
for (tries = 0; tries < 10000; tries++) {
|
||||
r = rand();
|
||||
if (wantprivate) {
|
||||
if (prefix == 8) {
|
||||
/* Only one valid private /8 exists: 10.0.0.0/8 */
|
||||
a[0] = 10; a[1] = 0; a[2] = 0; a[3] = 0;
|
||||
} else if (prefix == 16) {
|
||||
if (r % 2) {
|
||||
a[0] = 192; a[1] = 168; a[2] = rand() % 256;
|
||||
} else {
|
||||
a[0] = 172; a[1] = 16 + rand() % 16; a[2] = rand() % 256;
|
||||
}
|
||||
a[3] = 0;
|
||||
} else {
|
||||
r = rand() % 8;
|
||||
if (r < 4) {
|
||||
a[0] = 10; a[1] = rand() % 256; a[2] = rand() % 256;
|
||||
} else if (r < 6) {
|
||||
a[0] = 172; a[1] = 16 + rand() % 16; a[2] = rand() % 256;
|
||||
} else {
|
||||
a[0] = 192; a[1] = 168; a[2] = rand() % 256;
|
||||
}
|
||||
if (prefix == 24)
|
||||
a[3] = 0;
|
||||
else
|
||||
a[3] = 1 + rand() % 254;
|
||||
}
|
||||
} else {
|
||||
a[0] = (rand() % 223) + 1; /* avoids class D/E and 0 */
|
||||
if (a[0] == 10 || a[0] == 127)
|
||||
continue;
|
||||
a[1] = rand() % 256;
|
||||
a[2] = rand() % 256;
|
||||
a[3] = (prefix == 32) ? (1 + rand() % 254) : 0;
|
||||
}
|
||||
/* Zero the host bits for the chosen prefix. */
|
||||
if (prefix == 8) { a[1] = 0; a[2] = 0; a[3] = 0; }
|
||||
if (prefix == 16) { a[2] = 0; a[3] = 0; }
|
||||
if (prefix == 24) { a[3] = 0; }
|
||||
if (!wantprivate && !is_ok_public(a))
|
||||
continue;
|
||||
out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3];
|
||||
return;
|
||||
}
|
||||
die("could not generate a suitable random network; please retry");
|
||||
return;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Modes */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
static void mode_info(const char *arg)
|
||||
{
|
||||
byte a[16];
|
||||
const char *cls = "", *scope = "";
|
||||
char nb[64], gb[96], ob[96];
|
||||
int i;
|
||||
unsigned short g[8];
|
||||
char *q;
|
||||
|
||||
if (strchr(arg, '/') != NULL)
|
||||
die("info mode takes a plain address; for subnets use --plan-network");
|
||||
|
||||
if (strchr(arg, ':') != NULL) {
|
||||
if (!parse_ipv6(arg, a))
|
||||
die("invalid IPv6 address: %s", arg);
|
||||
fmt_v6(nb, a);
|
||||
classify_v6(a, &scope);
|
||||
for (i = 0; i < 8; i++)
|
||||
g[i] = (unsigned short)((a[2 * i] << 8) | a[2 * i + 1]);
|
||||
|
||||
printf("Address: %s\n", nb);
|
||||
printf("Type: IPv6\n");
|
||||
printf("Class: n/a (IPv6 has no address classes)\n");
|
||||
printf("Scope: %s\n", scope);
|
||||
|
||||
q = gb;
|
||||
for (i = 0; i < 8; i++)
|
||||
q += sprintf(q, "%s%04x", i > 0 ? " " : "", (unsigned)g[i]);
|
||||
printf("Groups: %s\n", gb);
|
||||
|
||||
q = ob;
|
||||
for (i = 0; i < 16; i++)
|
||||
q += sprintf(q, "%s%u", i > 0 ? ", " : "", (unsigned)a[i]);
|
||||
printf("Octets: %s\n", ob);
|
||||
} else {
|
||||
byte a4[4];
|
||||
if (!parse_ipv4(arg, a4))
|
||||
die("invalid IPv4 or IPv6 address: %s", arg);
|
||||
classify_v4(a4, &cls, &scope);
|
||||
|
||||
q = ob;
|
||||
for (i = 0; i < 4; i++)
|
||||
q += sprintf(q, "%s%u", i > 0 ? ", " : "", (unsigned)a4[i]);
|
||||
|
||||
printf("Address: %u.%u.%u.%u\n",
|
||||
(unsigned)a4[0], (unsigned)a4[1], (unsigned)a4[2], (unsigned)a4[3]);
|
||||
printf("Type: IPv4\n");
|
||||
printf("Class: %s\n", cls);
|
||||
printf("Scope: %s\n", scope);
|
||||
printf("Octets: %s\n", ob);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
static void mode_plan(const char *arg)
|
||||
{
|
||||
char buf[80];
|
||||
char *slash;
|
||||
byte a[4];
|
||||
unsigned long u, mask, net;
|
||||
int prefix;
|
||||
|
||||
if (strlen(arg) >= sizeof(buf) - 1)
|
||||
die("argument too long: %s", arg);
|
||||
strcpy(buf, arg);
|
||||
|
||||
slash = strchr(buf, '/');
|
||||
if (slash == NULL)
|
||||
die("expected a subnet with a mask suffix (e.g. 192.168.1.0/24)");
|
||||
*slash = '\0';
|
||||
|
||||
if (!parse_ipv4(buf, a))
|
||||
die("invalid IPv4 address in subnet: %s", buf);
|
||||
|
||||
prefix = atoi(slash + 1);
|
||||
if (prefix != 8 && prefix != 16 && prefix != 24 && prefix != 32)
|
||||
die("unsupported prefix '%s' (supported: /8 /16 /24 /32)", slash + 1);
|
||||
|
||||
mask = (prefix == 8) ? 0xFF000000ul :
|
||||
(prefix == 16) ? 0xFFFF0000ul :
|
||||
(prefix == 24) ? 0xFFFFFF00ul : 0xFFFFFFFFul;
|
||||
u = v4_to_u32(a);
|
||||
net = u & mask;
|
||||
|
||||
if (net != u) {
|
||||
byte c[4];
|
||||
u32_to_v4(net, c);
|
||||
die("host bits are set; the network address for that mask is %u.%u.%u.%u/%d",
|
||||
(unsigned)c[0], (unsigned)c[1], (unsigned)c[2], (unsigned)c[3], prefix);
|
||||
}
|
||||
if (a[0] == 0)
|
||||
die("0.0.0.0 networks are reserved and cannot be planned");
|
||||
if (a[0] >= 224)
|
||||
die("multicast and reserved networks (class D/E) cannot be planned");
|
||||
|
||||
print_plan(net, prefix);
|
||||
return;
|
||||
}
|
||||
|
||||
static void mode_random(const char *scope_s, const char *prefix_s)
|
||||
{
|
||||
char lc[16];
|
||||
const char *p;
|
||||
byte net[4];
|
||||
int prefix, priv;
|
||||
char *q;
|
||||
|
||||
if (strlen(scope_s) >= sizeof(lc))
|
||||
die("invalid scope: %s", scope_s);
|
||||
q = lc;
|
||||
for (p = scope_s; *p != '\0'; p++)
|
||||
*q++ = (char)((*p >= 'A' && *p <= 'Z') ? (*p - 'A' + 'a') : *p);
|
||||
*q = '\0';
|
||||
|
||||
if (strcmp(lc, "private") == 0)
|
||||
priv = 1;
|
||||
else if (strcmp(lc, "public") == 0)
|
||||
priv = 0;
|
||||
else
|
||||
die("invalid scope '%s' (expected private or public)", scope_s);
|
||||
|
||||
if (prefix_s[0] == '/')
|
||||
prefix_s++;
|
||||
prefix = atoi(prefix_s);
|
||||
if (prefix != 8 && prefix != 16 && prefix != 24 && prefix != 32)
|
||||
die("unsupported prefix '/%s' (supported: /8 /16 /24 /32)", prefix_s);
|
||||
|
||||
srand((unsigned)time(NULL));
|
||||
random_network(prefix, priv, net);
|
||||
|
||||
printf("Random network plan (--random-ipv4network %s /%d)\n\n",
|
||||
priv ? "private" : "public", prefix);
|
||||
print_plan(v4_to_u32(net), prefix);
|
||||
return;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
if (argc >= 2 &&
|
||||
(strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0 ||
|
||||
strcmp(argv[1], "help") == 0)) {
|
||||
usage();
|
||||
return 0;
|
||||
}
|
||||
if (argc >= 2 && strcmp(argv[1], "--plan-network") == 0) {
|
||||
if (argc != 3)
|
||||
die("--plan-network takes exactly one argument: <ipv4>/<prefix>");
|
||||
mode_plan(argv[2]);
|
||||
return 0;
|
||||
}
|
||||
if (argc >= 2 && strcmp(argv[1], "--random-ipv4network") == 0) {
|
||||
if (argc != 4)
|
||||
die("--random-ipv4network takes two arguments: <private|public> </8|/16|/24|/32>");
|
||||
mode_random(argv[2], argv[3]);
|
||||
return 0;
|
||||
}
|
||||
if (argc == 2) {
|
||||
mode_info(argv[1]);
|
||||
return 0;
|
||||
}
|
||||
usage();
|
||||
return 1;
|
||||
}
|
||||
206
tests/cases.py
Normal file
206
tests/cases.py
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
"""IPVarch test cases.
|
||||
|
||||
Each case is a dict:
|
||||
name : id shown on pass/fail
|
||||
args : argv passed after the binary name
|
||||
exit : expected exit code (default 0)
|
||||
must : substrings required in stdout ('stderr:' prefix targets stderr)
|
||||
must_not : substrings forbidden in stdout
|
||||
validator : key of a structural validator run on stdout (see runner.py)
|
||||
repeat : run the case this many times (for random/statistical checks)
|
||||
"""
|
||||
|
||||
def case(name, args, exit=0, must=None, must_not=None, validator=None, repeat=1):
|
||||
return {
|
||||
"name": name,
|
||||
"args": args,
|
||||
"exit": exit,
|
||||
"must": must or [],
|
||||
"must_not": must_not or [],
|
||||
"validator": validator,
|
||||
"repeat": repeat,
|
||||
}
|
||||
|
||||
GROUPS = [
|
||||
("info: IPv4", [
|
||||
case("public class A", ["8.8.8.8"],
|
||||
must=["Address: 8.8.8.8", "Type: IPv4", "Class: A",
|
||||
"Scope: Public", "Octets: 8, 8, 8, 8"]),
|
||||
case("public class C", ["198.140.10.1"],
|
||||
must=["Class: C", "Scope: Public"]),
|
||||
case("private class C", ["192.168.1.1"],
|
||||
must=["Class: C", "Scope: Private (RFC 1918)",
|
||||
"Octets: 192, 168, 1, 1"]),
|
||||
case("private class A", ["10.0.0.1"],
|
||||
must=["Class: A", "Scope: Private (RFC 1918)"]),
|
||||
case("private class B", ["172.16.254.1"],
|
||||
must=["Class: B", "Scope: Private (RFC 1918)"]),
|
||||
case("class D multicast", ["224.0.0.1"],
|
||||
must=["Class: D", "Scope: Multicast"]),
|
||||
case("class E reserved", ["240.0.0.1"],
|
||||
must=["Class: E", "Scope: Reserved"]),
|
||||
case("loopback", ["127.0.0.1"],
|
||||
must=["Scope: Loopback"]),
|
||||
case("this-network zero", ["0.0.0.0"],
|
||||
must=["Class: 0 (reserved)", "Scope: Reserved (this network)"]),
|
||||
case("class B public", ["172.32.0.1"],
|
||||
must=["Class: B", "Scope: Public"]),
|
||||
case("link-local APIPA", ["169.254.9.9"],
|
||||
must=["Scope: Link-local (APIPA)"]),
|
||||
]),
|
||||
|
||||
("info: IPv6", [
|
||||
case("documentation 2001:db8", ["2001:db8::1"],
|
||||
must=["Scope: Documentation (2001:db8::/32)"]),
|
||||
case("documentation 3fff", ["3fff:ffff::1"],
|
||||
must=["Scope: Public (global unicast)"]),
|
||||
case("documentation 2620:4f", ["2620:4f:0:0:0:0:0:1"],
|
||||
must=["Scope: Public (global unicast)"]),
|
||||
case("plain global unicast", ["2610:0:0:0:0:0:0:1"],
|
||||
must=["Address: 2610::1", "Type: IPv6",
|
||||
"Groups: 2610 0000 0000 0000 0000 0000 0000 0001"]),
|
||||
case("link-local", ["fe80::1"],
|
||||
must=["Address: fe80::1", "Scope: Link-local (fe80::/10)"]),
|
||||
case("loopback", ["::1"],
|
||||
must=["Address: ::1", "Scope: Loopback (::1)",
|
||||
"Groups: 0000 0000 0000 0000 0000 0000 0000 0001"]),
|
||||
case("unspecified", ["::"],
|
||||
must=["Address: ::", "Scope: Unspecified (::)",
|
||||
"Groups: 0000 0000 0000 0000 0000 0000 0000 0000"]),
|
||||
case("multicast", ["ff02::1"],
|
||||
must=["Scope: Multicast (ff00::/8)"]),
|
||||
case("unique local", ["fd12::1"],
|
||||
must=["Scope: Private (unique local, fc00::/7)"]),
|
||||
case("embedded IPv4 tail", ["2001:db8::192.168.1.1"],
|
||||
must=["Address: 2001:db8::c0a8:101",
|
||||
"Groups: 2001 0db8 0000 0000 0000 0000 c0a8 0101"]),
|
||||
case("IPv4-mapped", ["::ffff:192.168.1.1"],
|
||||
must=["Address: ::ffff:c0a8:101",
|
||||
"Scope: IPv4-mapped (::ffff:0:0/96)"]),
|
||||
case("no classes in IPv6", ["::1"],
|
||||
must=["Class: n/a (IPv6 has no address classes)"]),
|
||||
]),
|
||||
|
||||
("canonicalization round-trips", [
|
||||
case("expanded form compresses", ["2001:0db8:0000:0000:0000:0000:0000:0001"],
|
||||
must=["Address: 2001:db8::1"]),
|
||||
case("expanded octets normalize", ["2001:0db8:0000:0000:0000:0000:0000:0001"],
|
||||
must=["Groups: 2001 0db8 0000 0000 0000 0000 0000 0001"]),
|
||||
case("run of zeros compressed", ["2001:db8:0:0:0:0:2:1"],
|
||||
must=["Address: 2001:db8::2:1"]),
|
||||
case("longest run wins", ["2001:0:0:1:0:0:0:1"],
|
||||
must=["Address: 2001:0:0:1::1"]),
|
||||
case("run of one not compressed", ["1:2:3:4:5:6:0:8"],
|
||||
must=["Address: 1:2:3:4:5:6:0:8"]),
|
||||
case("full uncompressed round-trip", ["1:2:3:4:5:6:7:8"],
|
||||
must=["Address: 1:2:3:4:5:6:7:8"]),
|
||||
case("embedded IPv4 expanded head", ["0:0:0:0:0:ffff:1.2.3.4"],
|
||||
must=["Address: ::ffff:102:304"]),
|
||||
case("leading zero group", ["0db8:0000:0000:0000:0000:0000:0000:0001"],
|
||||
must=["Address: db8::1"]),
|
||||
]),
|
||||
|
||||
("network plan", [
|
||||
case("/24 plan", ["--plan-network", "192.168.1.0/24"],
|
||||
must=["IPVarch Network Plan - 192.168.1.0 /24",
|
||||
"255.255.255.0 /24", "192.168.1.255",
|
||||
"192.168.1.1 - 192.168.1.254", "254",
|
||||
"192.168.1.1", "192.168.1.2",
|
||||
"192.168.1.100 - 192.168.1.254"],
|
||||
validator="plan"),
|
||||
case("/8 plan", ["--plan-network", "10.0.0.0/8"],
|
||||
must=["IPVarch Network Plan - 10.0.0.0 /8",
|
||||
"255.0.0.0 /8", "10.255.255.255",
|
||||
"10.0.0.1 - 10.255.255.254", "16777214",
|
||||
"10.0.0.100 - 10.0.0.254"],
|
||||
validator="plan"),
|
||||
case("/16 plan", ["--plan-network", "172.18.0.0/16"],
|
||||
must=["IPVarch Network Plan - 172.18.0.0 /16",
|
||||
"255.255.0.0 /16", "172.18.255.255",
|
||||
"172.18.0.1 - 172.18.255.254", "65534",
|
||||
"172.18.0.100 - 172.18.0.254"],
|
||||
validator="plan"),
|
||||
case("/32 single-host plan", ["--plan-network", "192.168.1.7/32"],
|
||||
must=["IPVarch Network Plan - 192.168.1.7 /32",
|
||||
"255.255.255.255 /32", "n/a (single host)",
|
||||
"192.168.1.7", "1",
|
||||
"disabled (single-host network)"],
|
||||
validator="plan"),
|
||||
case("gateway is first usable", ["--plan-network", "192.168.1.0/24"],
|
||||
validator="plan-gateway"),
|
||||
]),
|
||||
|
||||
("random networks", [
|
||||
case("random private /8", ["--random-ipv4network", "private", "/8"],
|
||||
must=["Network address", "DHCP pool"],
|
||||
validator="random-private", repeat=3),
|
||||
case("random private /16", ["--random-ipv4network", "private", "/16"],
|
||||
validator="random-private", repeat=10),
|
||||
case("random private /24", ["--random-ipv4network", "private", "/24"],
|
||||
validator="random-private", repeat=20),
|
||||
case("random private /32", ["--random-ipv4network", "private", "/32"],
|
||||
validator="random-private", repeat=5),
|
||||
case("random public /24", ["--random-ipv4network", "public", "/24"],
|
||||
validator="random-public", repeat=20),
|
||||
case("random public /32", ["--random-ipv4network", "public", "/32"],
|
||||
validator="random-public", repeat=5),
|
||||
]),
|
||||
|
||||
("invalid inputs", [
|
||||
case("octet too big", ["256.1.1.1"], exit=1,
|
||||
must=["stderr:ipvarch: error:"]),
|
||||
case("too few octets", ["1.2.3"], exit=1,
|
||||
must=["stderr:ipvarch: error:"]),
|
||||
case("trailing dot", ["1.2.3.4."], exit=1),
|
||||
case("empty octet", ["1..2.3"], exit=1),
|
||||
case("four-digit octet", ["1.2.3.0001"], exit=1),
|
||||
case("too many groups", ["1:2:3:4:5:6:7:8:9"], exit=1),
|
||||
case("double ::", ["::1::2"], exit=1),
|
||||
case("trailing colon", ["1:2:3:4::5:"], exit=1),
|
||||
case("colon then garbage", [":::g:1"], exit=1),
|
||||
case("hex overflow group", ["::fffff"], exit=1),
|
||||
case("embedded IPv4 in head", ["1.2.3.4::"], exit=1),
|
||||
case("embedded IPv4 not last", ["::1.2.3.4:5"], exit=1),
|
||||
case("garbage text", ["not an ip at all"], exit=1,
|
||||
must_not=["Address:"]),
|
||||
case("info mode rejects mask", ["192.168.1.1/24"], exit=1,
|
||||
must=["stderr:--plan-network"]),
|
||||
case("plan missing argument", ["--plan-network"], exit=1),
|
||||
case("plan unsupported prefix", ["--plan-network", "192.168.1.0/12"], exit=1,
|
||||
must=["stderr:/8 /16 /24 /32"]),
|
||||
case("plan host bits set", ["--plan-network", "10.5.0.182/8"], exit=1,
|
||||
must=["stderr:10.0.0.0/8"]),
|
||||
case("plan host bits set /16", ["--plan-network", "192.168.1.0/16"], exit=1,
|
||||
must=["stderr:192.168.0.0/16"]),
|
||||
case("plan zero network", ["--plan-network", "0.0.0.0/8"], exit=1),
|
||||
case("plan multicast network", ["--plan-network", "224.0.0.0/24"], exit=1),
|
||||
case("plan reserved network", ["--plan-network", "250.0.0.0/8"], exit=1),
|
||||
case("random bad scope", ["--random-ipv4network", "residential", "/24"], exit=1),
|
||||
case("random bad prefix", ["--random-ipv4network", "private", "/12"], exit=1),
|
||||
case("random missing argument", ["--random-ipv4network", "private"], exit=1),
|
||||
]),
|
||||
|
||||
("edge & boundaries", [
|
||||
case("limited broadcast", ["255.255.255.255"],
|
||||
must=["Class: E", "Scope: Reserved"]),
|
||||
case("leading zeros accepted", ["010.000.000.001"],
|
||||
must=["Address: 10.0.0.1", "Octets: 10, 0, 0, 1"]),
|
||||
case(":: with tail-only IPv4", ["::1.2.3.4"],
|
||||
must=["Address: ::102:304"]),
|
||||
case("all-zero long form", ["0:0:0:0:0:0:0:0"], must=["Address: ::"]),
|
||||
case("full hex range", ["fedc:ba98:7654:3210:fedc:ba98:7654:3210"],
|
||||
must=["Address: fedc:ba98:7654:3210:fedc:ba98:7654:3210"]),
|
||||
case("79-char garbage (buffer boundary)", ["a" * 79], exit=1),
|
||||
case("63-hex-group garbage", ["1:2:3:4:5:6:7:8:9:10:11:12:13:14:15:16"],
|
||||
exit=1),
|
||||
case("upper-case IPv6 accepted", ["2001:0DB8::1"],
|
||||
must=["Address: 2001:db8::1"]),
|
||||
]),
|
||||
|
||||
("usage", [
|
||||
case("-h", ["-h"], must=["Usage:", "IPVarch"]),
|
||||
case("--help", ["--help"], must=["Usage:"]),
|
||||
case("help", ["help"], must=["Usage:"]),
|
||||
case("no arguments", [], exit=1, must=["Usage:"]),
|
||||
]),
|
||||
]
|
||||
311
tests/runner.py
Normal file
311
tests/runner.py
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
#!/usr/bin/env python3
|
||||
"""IPVarch test runner.
|
||||
|
||||
Runs every case in cases.py against the IPVarch binary and checks
|
||||
validity (exit codes, output contracts, structural table rules) and,
|
||||
with --sanitize, memory safety by rebuilding ipvarch.c with
|
||||
AddressSanitizer + UndefinedBehaviorSanitizer via gcc/clang.
|
||||
|
||||
Usage:
|
||||
python3 tests/runner.py [--bin ./ipvarch]
|
||||
[--sanitize] [--filter substring-of-group-or-case]
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from cases import GROUPS # noqa: E402
|
||||
|
||||
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
SAN_BIN = os.path.join("/tmp/opencode", "ipvarch-asan")
|
||||
|
||||
# ---------------------------------------------------------------- table
|
||||
|
||||
|
||||
def parse_table(out):
|
||||
"""Parse a network-plan table into (rows dict, prefix or None)."""
|
||||
rows = {}
|
||||
prefix = None
|
||||
for line in out.splitlines():
|
||||
if not line.startswith("│"):
|
||||
continue
|
||||
if "IPVarch Network Plan" in line: # title row spans both cells
|
||||
label = line.strip("│").strip()
|
||||
m = re.search(r"/(\d+)$", label)
|
||||
prefix = int(m.group(1)) if m else None
|
||||
rows["__title__"] = label
|
||||
continue
|
||||
cells = [c.strip() for c in line.split("│")]
|
||||
if len(cells) < 4:
|
||||
continue
|
||||
label, value = cells[1], cells[2]
|
||||
if label:
|
||||
rows[label] = value
|
||||
return rows, prefix
|
||||
|
||||
|
||||
def v_table_layout(out):
|
||||
"""Every non-title table row must have exactly 3 vertical bars."""
|
||||
rows, prefix = parse_table(out)
|
||||
if not rows.get("__title__"):
|
||||
return False, "no table title"
|
||||
if prefix is None:
|
||||
return False, "title missing prefix"
|
||||
for line in out.splitlines():
|
||||
if line.startswith("│") and "IPVarch Network Plan" not in line:
|
||||
if line.count("│") != 3:
|
||||
return False, "malformed row: %r" % line
|
||||
return True, ""
|
||||
|
||||
|
||||
def _ip_u32(s):
|
||||
parts = [int(p) for p in s.split(".")]
|
||||
if len(parts) != 4 or any(p < 0 or p > 255 for p in parts):
|
||||
return None
|
||||
return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]
|
||||
|
||||
|
||||
def _u32_ip(u):
|
||||
return "%u.%u.%u.%u" % ((u >> 24) & 255, (u >> 16) & 255,
|
||||
(u >> 8) & 255, u & 255)
|
||||
|
||||
|
||||
EXPECTED_HOSTS = {8: "16777214", 16: "65534", 24: "254", 32: "1"}
|
||||
PREFIX_MASK = {8: 0xFF000000, 16: 0xFFFF0000, 24: 0xFFFFFF00, 32: 0xFFFFFFFF}
|
||||
|
||||
|
||||
def v_plan(out):
|
||||
ok, msg = v_table_layout(out)
|
||||
if not ok:
|
||||
return ok, msg
|
||||
rows, prefix = parse_table(out)
|
||||
labels = ["Network address", "Netmask", "Broadcast", "Usable host range",
|
||||
"Usable hosts", "Class", "Scope", "Gateway IP",
|
||||
"DNS/DHCP server", "DHCP pool"]
|
||||
for label in labels:
|
||||
if label not in rows:
|
||||
return False, "missing row %r" % label
|
||||
if rows["Usable hosts"] != EXPECTED_HOSTS.get(prefix):
|
||||
return False, ("usable hosts %r != %r" %
|
||||
(rows["Usable hosts"], EXPECTED_HOSTS.get(prefix)))
|
||||
net = _ip_u32(rows["Network address"])
|
||||
if net is None:
|
||||
return False, "bad network address %r" % rows["Network address"]
|
||||
if prefix == 32:
|
||||
if not rows["Gateway IP"].startswith("n/a"):
|
||||
return False, "/32 gateway should be n/a: %r" % rows["Gateway IP"]
|
||||
if rows["DHCP pool"] != "disabled (single-host network)":
|
||||
return False, "/32 DHCP pool wrong: %r" % rows["DHCP pool"]
|
||||
return True, ""
|
||||
first = (net & PREFIX_MASK[prefix]) + 1
|
||||
if rows["Gateway IP"] != _u32_ip(first):
|
||||
return False, "gateway %r != first usable %r" % (rows["Gateway IP"],
|
||||
_u32_ip(first))
|
||||
if rows["DNS/DHCP server"] != _u32_ip(first + 1):
|
||||
return False, "DNS/DHCP %r != second usable %r" % (
|
||||
rows["DNS/DHCP server"], _u32_ip(first + 1))
|
||||
base = rows["Network address"].rsplit(".", 1)[0]
|
||||
if rows["DHCP pool"] != base + ".100 - " + base + ".254":
|
||||
return False, "DHCP pool %r != %r" % (rows["DHCP pool"],
|
||||
base + ".100 - " + base + ".254")
|
||||
return True, ""
|
||||
|
||||
|
||||
def _is_private_net(net, prefix):
|
||||
a = [(net >> 24) & 255, (net >> 16) & 255, (net >> 8) & 255, net & 255]
|
||||
if a[0] == 10 or a[0] == 192 and a[1] == 168:
|
||||
return True
|
||||
if a[0] == 172 and 16 <= a[1] <= 31:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _is_public_net(net):
|
||||
a = [(net >> 24) & 255, (net >> 16) & 255, (net >> 8) & 255, net & 255]
|
||||
if a[0] in (0, 10, 127):
|
||||
return False
|
||||
if a[0] == 172 and 16 <= a[1] <= 31:
|
||||
return False
|
||||
if a[0] == 192 and a[1] == 168:
|
||||
return False
|
||||
if a[0] == 169 and a[1] == 254:
|
||||
return False
|
||||
if a[0] == 100 and 64 <= a[1] <= 127:
|
||||
return False
|
||||
if a[0] == 198 and a[1] in (18, 19):
|
||||
return False
|
||||
if a[0] == 192 and a[1] == 0 and a[2] == 2:
|
||||
return False
|
||||
if a[0] == 198 and a[1] == 51 and a[2] == 100:
|
||||
return False
|
||||
if a[0] == 203 and a[1] == 0 and a[2] == 113:
|
||||
return False
|
||||
if a[0] >= 224:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _random_check(out, want_private):
|
||||
ok, msg = v_plan(out)
|
||||
if not ok:
|
||||
return ok, msg
|
||||
rows, prefix = parse_table(out)
|
||||
net = _ip_u32(rows["Network address"])
|
||||
shape = "zeroed" if prefix != 32 else "any"
|
||||
if want_private:
|
||||
if not rows["Scope"].startswith("Private"):
|
||||
return False, "scope should be Private: %r" % rows["Scope"]
|
||||
if not _is_private_net(net, prefix):
|
||||
return False, "network %r not private" % rows["Network address"]
|
||||
else:
|
||||
if not rows["Scope"].startswith("Public"):
|
||||
return False, "scope should be Public: %r" % rows["Scope"]
|
||||
if not _is_public_net(net):
|
||||
return False, ("network %r is in a reserved/special range" %
|
||||
rows["Network address"])
|
||||
if prefix != 32:
|
||||
expect_net = net & PREFIX_MASK[prefix]
|
||||
if net != expect_net:
|
||||
return False, "host bits set in random network %r" % _u32_ip(net)
|
||||
expect_bc = net | (~PREFIX_MASK[prefix] & 0xFFFFFFFF)
|
||||
if rows["Broadcast"] != _u32_ip(expect_bc):
|
||||
return False, "broadcast %r wrong" % rows["Broadcast"]
|
||||
return True, ""
|
||||
|
||||
|
||||
VALIDATORS = {
|
||||
"plan": v_plan,
|
||||
"plan-gateway": v_plan,
|
||||
"table": v_table_layout,
|
||||
"random-private": lambda out: _random_check(out, True),
|
||||
"random-public": lambda out: _random_check(out, False),
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------- run
|
||||
|
||||
|
||||
def run_bin(bin_path, args, timeout=15):
|
||||
try:
|
||||
proc = subprocess.run([bin_path] + args, capture_output=True,
|
||||
text=True, timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
return None, "TIMEOUT (%ss) on args=%r" % (timeout, args), ""
|
||||
except OSError as exc:
|
||||
return None, "cannot run binary: %s" % exc, ""
|
||||
return proc.returncode, proc.stdout, proc.stderr
|
||||
|
||||
|
||||
def check_once(bin_path, case):
|
||||
rc, out, err = run_bin(bin_path, case["args"])
|
||||
if rc is None:
|
||||
return False, err
|
||||
if rc != case["exit"]:
|
||||
head = err.strip().splitlines()[0] if err.strip() else ""
|
||||
if any(s in err for s in ("AddressSanitizer", "LeakSanitizer",
|
||||
"runtime error:")):
|
||||
return False, "sanitizer abort (rc=%d): %s" % (rc, head)
|
||||
return False, "exit %d, expected %d; stderr=%r" % (rc, case["exit"],
|
||||
head)
|
||||
for sub in case["must"]:
|
||||
hay = err if sub.startswith("stderr:") else out
|
||||
clean = sub[len("stderr:"):] if sub.startswith("stderr:") else sub
|
||||
if clean not in hay:
|
||||
return False, "output missing %r" % clean
|
||||
for sub in case["must_not"]:
|
||||
if sub in out:
|
||||
return False, "output unexpectedly contains %r" % sub
|
||||
if case["validator"]:
|
||||
ok, msg = VALIDATORS[case["validator"]](out)
|
||||
if not ok:
|
||||
return False, "validator %s: %s" % (case["validator"], msg)
|
||||
return True, ""
|
||||
|
||||
|
||||
def run_case(bin_path, case):
|
||||
reps = case.get("repeat", 1)
|
||||
for i in range(reps):
|
||||
ok, msg = check_once(bin_path, case)
|
||||
if not ok:
|
||||
suffix = " (iteration %d/%d)" % (i + 1, reps) if reps > 1 else ""
|
||||
return False, msg + suffix
|
||||
return True, ""
|
||||
|
||||
|
||||
def build_sanitize(repo):
|
||||
cc = shutil.which("gcc") or shutil.which("clang")
|
||||
if cc is None:
|
||||
return None, "no ASan-capable compiler (gcc/clang) found"
|
||||
cmd = [cc, "-std=c89", "-O1", "-g",
|
||||
"-fsanitize=address,undefined", "-fno-omit-frame-pointer",
|
||||
os.path.join(repo, "ipvarch.c"), "-o", SAN_BIN]
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if proc.returncode != 0:
|
||||
return None, "sanitized build failed:\n%s" % proc.stderr.strip()
|
||||
return SAN_BIN, None
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="IPVarch test runner")
|
||||
ap.add_argument("--bin", default=os.path.join(REPO, "ipvarch"))
|
||||
ap.add_argument("--sanitize", action="store_true",
|
||||
help="rebuild with ASan+UBSan (gcc/clang) and rerun matrix")
|
||||
ap.add_argument("--filter", default=None,
|
||||
help="only run groups/cases whose name contains this")
|
||||
args = ap.parse_args()
|
||||
|
||||
os.makedirs(os.path.dirname(SAN_BIN), exist_ok=True)
|
||||
memory = "not instrumented (run 'make test-sanitize' to enable)"
|
||||
|
||||
if args.sanitize:
|
||||
bin_path, err = build_sanitize(REPO)
|
||||
if bin_path is None:
|
||||
print("sanitize: SKIPPED (%s)" % err)
|
||||
return 0
|
||||
memory = "ASan+UBSan instrumentation active"
|
||||
else:
|
||||
bin_path = args.bin
|
||||
|
||||
if not os.path.exists(bin_path):
|
||||
print("error: binary not found: %s (run 'make' first)" % bin_path,
|
||||
file=sys.stderr)
|
||||
return 1
|
||||
|
||||
passed = failed = 0
|
||||
failures = []
|
||||
ran_any = False
|
||||
|
||||
for gname, cases in GROUPS:
|
||||
if args.filter and args.filter not in gname:
|
||||
continue
|
||||
print("== %s ==" % gname)
|
||||
for case in cases:
|
||||
if args.filter and args.filter not in case["name"]:
|
||||
continue
|
||||
ran_any = True
|
||||
ok, msg = run_case(bin_path, case)
|
||||
if ok:
|
||||
passed += 1
|
||||
print(" PASS %s" % case["name"])
|
||||
else:
|
||||
failed += 1
|
||||
failures.append((gname, case["name"], msg))
|
||||
print(" FAIL %s\n %s" % (case["name"], msg))
|
||||
print()
|
||||
|
||||
if not ran_any:
|
||||
print("error: filter %r matched nothing" % args.filter, file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print("Summary: %d passed, %d failed [binary: %s]" %
|
||||
(passed, failed, bin_path))
|
||||
print(" memory safety: %s" % memory)
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Loading…
Add table
Add a link
Reference in a new issue