{"slug": "show-hn-scapy-for-the-agentic-sre", "title": "Show HN: Scapy for the Agentic SRE", "summary": "A developer released Crafty, a packet-crafting and network-testing tool modeled on Scapy, in which traffic is sent from a real interface and the program reacts to returning packets. Crafty lets users build packets bit by bit or from its own protocol stacks, with internals exposed through a script language: stacks are written as slash-separated layers like /IP(dst=192.0.2.10)/UDP(dst=7), terminal layers such as Raw, Request, Reply, Query and Answer end a stack and send the message, and blocks support repeat loops, expect with timeouts, try/retry error handling and catchable errors including Timeout, Closed, CannotConnect, NoRoute, NoPort, Unset, Invalid, Unresolved and Assertion. In the posted example, a script sends three UDP datagrams to an echo server at 192.0.2.10 port 7 and reports \"3 answers out of 3: all back\" after 0.3s with status OK, run via sudo crafty --udp 40000-40010 --fw intro.cfty.", "body_md": "Crafty sends traffic from a real interface and reacts to what comes back, Packets can be crafted to the bit or built by crafty's own stacks, which internals are accessible.\n\n```\n# Three datagrams to a UDP echo server: how many come back?\n# \"IP\", \"UDP\" and \"Raw\" are layers of a protocol stack. Every stack\n# starts at the interface, with an \"Eth\" layer that can be left out:\n# /IP(dst=192.0.2.10)/UDP(dst=7) is /Eth/IP(dst=192.0.2.10)/UDP(dst=7).\n# Followed by a block, a stack is the current stack of that block:\n/IP(dst=192.0.2.10)/UDP(dst=7) {\n  answers = 0                     # \"answers\" is a variable holding integers\n  # Repeats the block 3 times, \"I\" being the loop counter, from 0:\n  repeat var=I count=3 every=100ms {\n    # Raw is a terminal layer: it sends the message made from\n    # /IP(dst=192.0.2.10)/UDP(dst=7)/Raw(\"ping ${I}\")\n    # Unset options will be filled in automatically.\n    Raw(\"ping ${I}\")\n    # expect waits for a packet that matches a pattern; here, any Raw\n    # layer on top of the current stack, coming back:\n    expect timeout=1s Raw {\n      answers += 1\n      print(MATCH[Raw].data)  # MATCH is the packet that matched\n    } else {}                 # after the timeout: a lost answer is no error\n  }\n  # An \"if\", as a block, is worth the value of the branch it runs:\n  verdict = if answers == 3 { \"all back\" } else { \"some lost\" }\n  print(\"${answers} answers out of 3: ${verdict}\")\n}\n% sudo crafty --udp 40000-40010 --fw intro.cfty\n...\nping 0\nping 1\nping 2\n3 answers out of 3: all back\nDone after 0.3s, status: OK.\n```\n\nA stack is layers and their options, separated by slashes, like file paths.  An\nabsolute stack starts with `/IP` (with an `Eth` layer implied).  A relative\nstack goes on top of the current one.\n\nSome layers are terminal (`Raw`, `Request`, `Reply`, `Query`, `Answer`): they\nend the stack and send the message. An incomplete stack is followed instead, on\nthe same line, by a block of further instructions. A few layers can be both\n(`HttpRequest`, `HttpAnswer`, `WebSocket`), and are terminal unless followed by\na block or a layer. So `X/Y { Z }` is not `X/Y` then `{ Z }` on the next line:\nthat sends `X/Y` (or fails, if `Y` cannot end a message), then runs `Z` apart.\n\nThe layers of a stack are streams: `UDP` picks its source port once (from\n`--udp`), and every message sent and every pattern on top of it belong to that\nstream.\n\nAn error leaves the enclosing blocks one after the other until an enclosing\n`try` handles it or a `retry` runs its block again; uncaught errors end the\nprogram.\n\nOnly these errors can be caught: `Timeout` (of `expect` or `on`), `Closed` (a\nTCP connection), `CannotConnect` (writing to a TCP connection refused or timed\nout), `NoRoute`, `NoPort` (no source port left to pick), `Unset` (`getenv`,\n`arg`, a missing map key or packet layer), `Invalid` (converting a string or\nbytes), `Unresolved` (`resolve`, `hostname`) and `Assertion` (`assert`). In a handler, `ERROR` is the message\nand `MATCH` the packet that caused the error (the RST or ICMP error refusing a\nconnection), else empty.\n\n```\nn = 1\ntry {\n  n := int(arg(0))\n} Unset {}                         # no argument: keep 1\n  | Invalid { print_err(ERROR) }   # ERROR is the message\nretry Timeout|Closed max=2 {       # retries on these errors only\n  /IP(dst=192.0.2.10)/TCP(dst=7) {\n    Raw(\"hello\")\n    expect timeout=1s Raw { print(MATCH[Raw].data) }\n  }\n}\n# Is anyone listening on UDP port 7?\ntarget = ip_addr(getenv(\"TARGET\"))  # Read the envvar and cast to an IP, or fail\n/IP(dst=target)/UDP(dst=7) {\n  Raw(\"hello\")      # two messages on top of the same stack:\n  Raw(\"world\")      # the same stream, from the same port\n  # Waits for the first packet that matches either pattern: a datagram\n  # back, or the ICMP error a closed port answers with. \"../\" goes back to\n  # /IP(dst=target), and ICMP goes on top of that IP stream instead of\n  # UDP: these are the ICMP errors about it, whoever sends them (a router).\n  expect timeout=1s Raw { print(MATCH[Raw].data) }\n    | ../ICMP/DestUnreachable(code == PORT_UNREACHABLE) { print(\"closed\") }\n}\nhello\n```\n\nWith `dst=8`, where nothing listens, it prints `closed`.\n\nEach leading `../` goes one layer down the current stack: here, `../` is\n`/IP(dst=target)` and `../../` is `/Eth`.  Relative stacks reuse opened\nstreams, whereas absolute stacks create new streams: `/IP/ICMP/DestUnreachable`\nmatches any Dest-Unreachable packet whereas `../ICMP` matches only those about\nthe packets of `/IP(dst=target)`.\n\nLike relative patterns, relative stacks can go back with `../` and modify upper\nlayers' options while reusing the stream:\n\n```\n# The same stream, but for one datagram with a TTL of 1:\n/IP(dst=192.0.2.10)/TCP(dst=7) {\n  Raw(\"ttl 64\")\n  print(\"Sent from port ${LAST[TCP].src}\")   # LAST is the last packet sent\n  # ../../ goes back to /Eth, where IP and TCP land on the IP and TCP of\n  # the current stack. They overlay them: the same streams, with their\n  # options (dst, the ports, TCP internal state) unless overwritten.\n  # ttl=1 is for this message only.\n  ../../IP(ttl=1)/TCP/Raw(\"ttl 1\")\n  print(\"Also sent from port ${LAST[TCP].src}\")\n  repeat count=2 {\n    # Wait for Raw in the same stream (unlike with /IP/TCP/Raw that would\n    # match even outside this stream)\n    expect timeout=1s Raw { print(MATCH[Raw].data) }\n  }\n}\nSent from port 40000\nAlso sent from port 40000\nttl 64\nttl 1\n```\n\nThe rule, for stacks and patterns alike: relative ones stay on the streams\nof the current stack (`../` overlaying some of its layers); absolute ones\nstart anew from `Eth`. Overlaying can set a temporary value for an earlier\noption.\n\nSo far, streams were *self-driven*: crafty resolves addresses, connects,\nretransmits, fragments and reassembles. A bang makes a layer *manual*, for\npackets as on the wire: `TCP!(flags=SYN, ack_num=0)` is a SYN packet with this\nsequence number regardless of the state of the TCP connection.  On reception,\n`IP!` sees each fragment and `TCP!` each segment, even without data.\n\n```\n# A SYN of our own, and the SYN-ACK that answers it:\ntarget = 192.0.2.10\n{\n  # \"on\" runs its block for each matching packet, while the enclosing\n  # block goes on; here, for one SYN-ACK at most, until 1s after the block:\n  on max=1 linger=1s /IP(src == target)/TCP!(src == 7 && flags & SYN &&\n                                               ack_num > 1000 && ack_num <= 2000) {\n    print(\"SYN-ACK: seq ${MATCH[TCP].seq_num}, ack ${MATCH[TCP].ack_num}\")\n  }\n  # Sends the segment, and waits until it is seen leaving: \"seg\" is the\n  # packet as captured.\n  seg = /IP!(dst=target)/TCP!(src=40000, dst=7, flags=SYN, seq_num=1000)/Raw()\n  print(\"SYN of seq ${seg[TCP].seq_num} sent\")\n}\n% sudo crafty --tcp 40000 --fw syn.cfty\nSYN of seq 1000 sent\nSYN-ACK: seq 1969569245, ack 1001\n```\n\n`encode(STACK)` is the bytes of the layers of `STACK`, all manual, as if sent.\nAn `IP` or `IP6` right below them fills in the checksum of what they carry.\nThis is how to fragment by hand, since no fragment has what the checksum covers:\n\n```\n# A datagram in two fragments, the last first:\n/IP!(dst=target, id=1234, proto=17) {\n  d = encode(UDP(src=4000, dst=7)/Raw(randbytes(100)))\n  ../IP!(frag_offset=8)/Raw(d[64:])\n  ../IP!(more_frags=true)/Raw(d[:64])\n}\n```\n\n`crafty [options] file [arg...]` or `crafty [options] -e program [arg...]`,\nwhere file `-` is stdin.\n\nWhat follow the file are the program's own arguments (that are returned by\n`arg(n)`.  With `-e`, every argument that's not an option is a program's\nargument, and `--` ends the options.\n\nOptions:\n\n- `-e PROG` : the program itself, rather than a file.\n- `-i IFACE` : the interface to send from and capture on, rather than that of\nthe default route. Crafty needs root, or`setcap cap_net_raw,cap_net_admin=ep` .\n- `--routing kernel|manual` :`kernel` (default) uses kernel routes.`manual` takes gateway from the interface and then does ARP etc.\n- `--tcp LO-HI` ,`--udp LO-HI` (repeatable): the ranges to pick source ports\nfrom (see also[Budget, ports and permissions](#budget-ports-and-permissions) ).\n- `--fw` : crafty shares the interface's address with the host, whose kernel\nwould answer what crafty receives with TCP resets and ICMP port\nunreachables.`--fw` keeps the kernel off the ports of`--tcp` and`--udp` .\n- `--ip ADDR` : an address of crafty's own instead, on the interface's network,\nfor which crafty answers ARP. Then`--fw` is not needed.\n- `-p [/PATTERN]` (or`--print-packets` ): prints the packets à la tcpdump.\n- `--format csv|json` : change the output format to csv or json (json makes -p\nprint all available details of every packet).\n- `--stats` : prints the stats of each stream (see`stats()` ) as it ends.\n- `--check` : check the program and quit.\n- `--max-duration` (default: 10m),`--max-packets` ,`--max-bytes` ,`--max-packets-per-secs` ,`--max-bytes-per-secs` ,`--max-syns` ,`--max-syns-per-secs` ,`--max-ram` : self-imposed budget.\n- `--local-ip accept|deny:CIDR` ,`--remote-ip accept|deny:CIDR` (repeatable),`--mac-spoofing BOOL` ,`--exfiltration BOOL` ,`--promiscuous BOOL` :\npermissions (see[Budget, ports and permissions](#budget-ports-and-permissions) ).\n- `--reference` : prints the reference manual.\n- `--examples` : prints many examples of use.\n- `--cliref` : exhaustive list of options including seldom used ones.\n\nExit status: 0 when the program completes, 1 when an error ends it, 2 when it does not compile, 3 when a budget stops it, 4 when it sends what its permissions deny, 130 when interrupted.\n\n- Use `resolve(\"hostname\")` to resolve a hostname\n- Errors and warnings go to stderr, all else to stdout: filter stdout as\nyou like, but not stderr (`crafty x.cfty | grep ...` , not`2>&1 | grep` )\n- Quote programs as `-e '...'` or`- <<'EOF'` , lest the shell expand`${}`\n- Parameterize your programs with arguments (`crafty x.cfty 10.0.0.1 5` ,\nread with`arg(0)` ,`arg(1)` ) or environment variables (`TARGET=10.0.0.1 crafty x.cfty` , read with`getenv(\"TARGET\")` ) then cast.\n- When unsure, use --max-duration\n- Crafty is not Python, despite `for x in a` and comprehensions: only the\nfunctions of the reference exist.\n\n- A statement ends at the end of its line or at a `;` .  Within parentheses,\nbrackets and braces, after a binary operator, or before an`else` ,`elsif` or`|` , a new line is plain white space.\n- Comments run from a `#` to the end of the line. A`#` followed by a\nhexadecimal digit is a byte literal instead.\n- Names of layers, fields, functions and keywords are case insensitive.\nConstants, `MATCH` ,`LAST` ,`OWN_IP` and`OWN_IPS` are upper case.\nVariables and constructors are case sensitive.\n\n- `bool` :`true` ,`false` .\n- `int` :`42` ,`-1` ,`0x1f` ,`0o17` ,`0b101` .\n- `float` :`1.5` ,`2e-3` .\n- `byte` :`#1f` .\n- bytes: `#deadbeef` (an even number of digits). An array of bytes.\n- `string` :`\"text ${expr}\"` .\n- `interval` :`5s` ,`10ms` ,`1m30s` ,`1.5ms` ,`-2s` . Units:`d` ,`h` ,`m` ,`s` ,`ms` ,`us` (or`µs` ),`ns` ,`ps` . Printed in one unit up to`s` :`157.949ms` ,`8.85159µs` ,`3725.5s` .\n- `time` :`2026-10-20T22:02:45.25Z` ,`2026-10-20T22:02+02:00` ,`2026-10-20T22:02` (local time). Printed in UTC.`int(t)` and`float(t)` give its unix timestamp,`time(secs)` the reverse.\n- `ip` :`192.0.2.1` ,`2001:db8::1` .\n- `mac` :`aa:bb:cc:dd:ee:ff` .\n- `cidr` :`10.0.0.0/8` ,`2001:db8::/32` , no bit set beyond the mask.`ip in net` tells whether an address is in it.\n- arrays: `[1, 2, 3]` . Items of one type, typed lazily (when that fails:`[0s] * 0` ).\n- maps: `[192.0.2.1: \"gw\", ::1: \"lo\"]` , a`string[ip]` , in no\nparticular order.`map(key=k, default=v)` is an empty map with keys of the\ntype of`k` , where missing keys have the value`v` .\n- comprehensions: `[e for x in a if c]` ,`[k: v for x in a if c]` ,`x` being\nan item of the array or map`a` (as`{key: k, value: v}` ).\n- records: `{name: \"gw\", ip: 192.0.2.1}` .`{}` is an empty block, not a\nrecord.\n- variants: `Ok(42)` ,`Failed(\"timeout\")` ,`Pending` . A constructor starts\nwith a capital letter; a bare name that is a variable is the variable. The\nlayers of a packet are variants too, of constructors`IP` ,`UDP` ...\n\nLiterals are whole words: `1.2.3.4` is an IP address, `5s` an interval.\n\nStrings interpolate any expression: `\"ttl ${MATCH[IP].ttl - 1}\"`. Escapes:\n`\\n`, `\\r`, `\\t`, `\\0`, `\\\\`, `\\\"`, `\\$`, `\\xHH`. Interpolated bytes are\nwritten in hexadecimal (`#68656c6c6f`); bytes passed where a string is\nexpected, as to `print`, are text, as `string(b)` makes them.\n\n**Conversions** happen where that make sense: an int to a float, a byte to an\nint, an IP address or a MAC address to bytes and back, an int to a bool...\nBytes compare with the others as bytes. Others use the functions `int`,\n`float`, `bool`, `byte`, `interval`, `time`, `ip_addr`, `mac_addr` and `cidr`,\nwhich also read a string as a literal: `ip_addr(getenv(\"SERVER\"))`.  An IPv4\naddress converts to an int: `ip_addr(int(a) + 1)`.  `+` can concatenate\nstrings and bytes.\n\n**Variants** need no declaration. Where variants meet (items of an array,\nbranches of an `if`, values assigned to a variable...), they make one variant\nwith the constructors of all, which `case` tells apart:\n\n```\nresult = Pending   # of type (Failed string | Got int | Pending)\nexpect Raw(\"pong\") { result := Got(length(MATCH)) }\n  | ../ICMP { result := Failed(\"unreachable\") }\nprint(case result Got { \"${I} layers\" } else { \"${result}\" })\n```\n\n- `x = expr` declares`x` in the current block, with the type of`expr` .\nAn inner block may shadow it.\n- `x := expr` assigns it, and`x += expr` (also`-=` ,`*=` , etc.) updates it.\n- Predefined: `MATCH` (in the block of an`expect` or`on` , or a handler of`try` ),`ERROR` (in a handler of`try` ),`LAST` (the last packet sent, once a block has sent one),`I` , the counter of\na`repeat` ,`BUDGET` ,`PORTS` ,`PERMISSIONS` ,`OWN_IPS` , the addresses of the interface (or`--ip` 's), IPv4 ones first, and`OWN_IP` , the first of them.\n- `LAST` is the packet as given, not as it left: reading a field that only\nthe wire knows (`LAST[Eth].ts` , or`IP.id` ,`UDP.checksum` ... under a\nself-driven`IP` ) is an error. In contrast,`p = MESSAGE` captures the packet\nas it leaves (see[Self-driven vs manual stacks](#self-driven-vs-manual-stacks) ).\n\nA program may declare them, once each, at its top level, with literals only:\n\n```\nBUDGET = {max_duration: 30s, max_syns: 30}\nPORTS = {tcp: [[40000, 40100]], udp: [[5000, 5000]]}\nPERMISSIONS = {local_ips: [Accept(10.20.4.1)],  # spoofs 10.20.4.1\n               remote_ips: [Deny(192.0.2.66), Accept(192.0.2.0/24)]}\n```\n\n- `BUDGET` 's fields are the budget options of crafty, named alike.\n- `max_ram` , in bytes.\n- `PORTS` has ranges`[first, last]` by protocol; default to no port.\n- crafty runs with what both the program and the command line allow.\n- `PERMISSIONS` :\n  - `local_ips` ,`remote_ips` : rules`Accept(x)` or`Deny(x)` ,`x` being a\nCIDR or`OWN_IP(S)` ; the first that matches an address decides, and none matching denies.`local_ips` always ends\nwith`Accept(OWN_IPS)` ; unset,`remote_ips` accepts any. Sending from an address\ntakes`local_ips` accepting it.\n  - `mac_spoofing` : allows sending from another MAC than the interface's.\n  - `exfiltration` : allows sending a payload made of the payload of a received\npacket or of`getenv` .\n  - `promiscuous` : receives the frames for other addresses too, unless`local_ips` denies them.\n  - A sent packet denied by the above rules stops the program. A received one that is denied is dropped. Received ICMP errors are judged by the packet they quote, not by the router that sent it.\n\nOperators, from the tightest binding to the loosest:\n\n1. `!x` ,`-x` .\n2. `*` ,`/` ,`%` : on numbers. An array, a byte or a string\ntimes an int repeats it.\n3. `+` ,`-` : on numbers; a time minus a time is an interval, a time plus an\ninterval (or a number of seconds) is a time.`+` also concatenates arrays\n(`[1] + [2, 3]` ) and appends or prepends an item\n(`[1, 2] + 3` ,`0 + [1, 2]` ). To`+` , a byte is one-element bytes:`#41 + #42` is`#4142` . A string plus a string or bytes is a string;\nuse`string(b)` for bytes as text.\n4. `<<` ,`>>` : shift an int or a byte by an int;`>>` keeps the sign of an\nint, and a byte stays 8 bits.\n5. `&` , then`^` , then`|` : bitwise, on ints or bytes.\n6. `==` ,`!=` ,`<` ,`<=` ,`>` ,`>=` , and`in` (an IP address in a CIDR).\n7. `&&` , then`||` .\n8. `c ? a : b` :`a` if`c` , else`b` , computing only that one.\n\nAlso: `r.field`, `a[i]` (`a[-1]` is the last item), `m[k]`, `f(arg, name=arg)`,\nand the layer selectors of [Patterns](#patterns). Arrays, bytes and strings\nslice as in Python.  `a[i] := v` and `m[k] += 1` change an item, adding the key\nto a map if need be.\n\n**Blocks, `if`, `case`, `expect` and `try` are expressions**:\n\n```\ny = if cond 1 else 2\nttl = case var=h MATCH[1] IP { h.ttl } else { 0 }\nresp = expect timeout=1s Raw { Got(MATCH[Raw].data) } else { Lost }\nrtt = { t0 = now() ; Request(\"ping\") ; expect Reply {} ; now() - t0 }\ncode = try { MATCH[DestUnreachable].code } Unset { -1 }\n```\n\nSent messages can be assigned to a variable:\n\n`p = /IP!(dst=target)/TCP!(src=1, dst=2, flags=SYN)/Raw()`\n\nThis sends a packet and waits until it is recaptured on its way out.\nIts timestamp `p[Eth].ts` is therefore accurate. Through self-driven layers, `p`\nis the first frame that carries some of the message.\n\nSelf-driven and manual layers can be mixed with some restrictions: a manual\nlayer cannot carry a self-driven one: `IP/TCP!` is fine, `IP!/TCP` is not.\n\n- `/IP/UDP(dst == 7)/Raw` :*absolute* , matched from the interface up.\n- `Raw(\"pong\")` :*relative* , on top of the current stack.\n- `../ICMP/DestUnreachable` : relative to a layer below the top of the current\nstack.\n- `Raw(\"pong\") | ../ICMP` : alternatives.\n- `UDP(src == port)` : conditions in parentheses are boolean expressions.\n- `IP.src` is the field of the innermost IP layer, this one included. A path\nnames the layers below the one meant,`_` being any one:`/IP.src` is the\nfirst IP's`src` ,`ICMP/_/IP.src` the one on top of any ICMP error.\n- A condition that is not a bool compares the default field:\n`Raw(\"pong\")` is`Raw(data == \"pong\")` .\n- The fields that can be read depend on the mode (see [Layers](#layers) ): a\nself-driven`TCP` shows its ports, a manual`TCP!` each segment's header.\n\n**`MATCH`** is the packet that matched, as an array of layers: `MATCH[IP].src`,\n`MATCH[Raw].data`, with paths as in conditions (` MATCH[/IP]`,\n`MATCH[ICMP/_/IP]`). `MATCH[1]` and `MATCH[ICMP/_]` are layers of any allowed kinds,\nwhich `case` tells apart:\n\n```\nfor l in MATCH {\n  print(case l IP { \"IP from ${I.src}\" } | UDP { \"UDP to ${I.dst}\" } else { \"other\" })\n}\n```\n\n**`LAST`**, likewise, is the last packet sent. Self-driven layers show their\noptions, what crafty picked (source ports) and their defaults (`ttl`), but not\nwhat their engine computes (checksums).\n\n- `repeat var=v count=n every=d for=d { ... }` : runs the block`count` times,\nor while`for` has not elapsed. An iteration starts`every` after the previous\none started.`v` (default`I` ) counts from 0.\n- `for v in a every=d for=d { ... }` : a`repeat` over the items`v` of the\narray or map`a` (as`{key: k, value: v}` ).\n- `retry E|E max=n { ... }` : runs the block again, up to`n` times\n(default 3), while it fails with one of these errors. The last error escapes.\n- `try { ... } E|E { ... } | E { ... } else { ... }` : runs the block of the\nfirst handler naming the error, or else that of`else` (any error that can\nbe caught). Other errors escape.\n- `if COND STMT [elsif COND STMT] else STMT` : conditionals.\n- `case var=v X C { ... } | C { ... } else { ... }` : runs the block of the\nconstructor of`X` , where`v` (default`I` ) is what that constructor holds.\n- `break n` : leaves the`n` (default 1) innermost`repeat` ,`for` ,`on` or`spawn` .\n- `continue n` : likewise, but goes on with the next iteration of the`n` th\n(or, for an`on` , waits for its next match).\n- `exit` : ends the program successfully, from anywhere.\n- `wait d` (or`sleep d` ): pauses.\n- `expect timeout=d PATTERN { ... } | PATTERN { ... } else { ... }` : waits for\nthe first packet that matches any pattern, then runs its block; after the\ntimeout (none by default), runs`else` , or without one fails with`Timeout` .\nIts value is that of the block it ran.\n- `on for=d linger=d timeout=d max=n PATTERN { ... } | PATTERN { ... }` : the\nenclosing block goes on; each matching packet runs the block of its pattern,\nrepeatedly (`max` times or unlimited) until its lifetime or that of the\nenclosing blocks are over.`linger` (default 0) instructs that enclosing\nblock to wait further.\n- `spawn for=d { ... }` : runs the block alongside the enclosing one, which goes\non. With`for` , the enclosing block waits for at the end, cancelling it after`d` ; without, it ends with the statements of the enclosing block.\n- `{ ... }` : a block. Ends once its statements are done, its`linger` s\nwaited and its`on` s and`spawn` s with a`for` ended.\nLeaving a block, normally or on an error, cancels what it still had\ngoing.\n\n- `print(x)` ,`print_err(x)` : to stdout, to stderr, as`\"${x}\"` (bytes as\ntext).\n- `string(x)` :`x` as`\"${x}\"` (bytes as text).\n- `format(x)` : any value as a string, in the format of`--format` . CSV takes a\nscalar, or a record, array or map of scalars.\n- `summary(x)` : return`{count, min, mean, stddev, p50, p95, p99, max}` from\nall values in`x` (key by key if`x` is a map or a record).\n- `report(x, name=s)` : prints the summary of`x` according to`--format` .\n- `assert(cond, msg=s)` : fails if`cond` is false.\n- `now()` : the current time.\n- `stats()` : the stats so far of the streams of the current stack. Every stream counts`packets_out` ,`packets_in` ,`bytes_out` ,`bytes_in` (the payloads at that\nlayer). A self-driven TCP connection counts its segments, retransmissions\nincluded, and adds, as Linux's`tcp_info` :`bytes_acked` ,`bytes_received` (in order),`retrans` ,`dupacks` ,`timeouts` ,`holes_in` (gaps opened in\nwhat was received),`ooo_in` (segments filling a gap within`min_rtt` of\nthe one beyond it),`dup_in` (segments with only data already receiveds),`srtt` ,`rttvar` ,`min_rtt` ,`rtt_samples` ,`rto` ,`snd_mss` ,`rcv_mss` ,`cwnd` ,`ssthresh` (2^31-1 before any loss),`snd_wnd` (the peer's window),`rcv_wnd` ,`snd_wscale` and`rcv_wscale` (the window shifts the peer and\nwe offered, -1 if none) and`established` . An IP or IP6 stream adds`fragmented` ,`frags_out` ,`frags_in` ,`reassembled` and`reasm_timeouts` (incomplete after 30s, or 60s for IP6).\n- `getenv(name, default=s)`\n- `arg(n, default=s)` : the n-th argument after the program, from 0.`nargs()` :\nhow many there are.\n- `resolve(name)` : the addresses of a name, IPv4 first, as an array, from the\nsystem's resolver. Blocking.\n- `hostname(ip, default=s)` : the name of an address. Blocking.\n- `is_ip4(ip)` ,`is_ip6(ip)`\n- `rand(max)` : an int or a float in`[0, max)` (or a bool if`max` is`true` )\n- `randbytes(len)` : random bytes.\n- `int(x)` ,`float(x)` ,`bool(x)` ,`byte(x)` (the low 8 bits): of intervals, times,\nor numbers\n- `interval(secs)` .\n- `exp(x)` ,`ln(x)` ,`log(x)` (base 10).`log2(n)` .\n- `split(s, by)` : the parts of`s` between the occurrences of`by` .\n- `array(init=v, len=n)` ,`length(a)` (or`count(a)` , of an array, a map or a\nstring),`concat(a, b)` ,`append(a, x)` ,`prepend(x, a)` .\n- `range(n)` ,`range(a, b)` : the ints from 0 (or`a` ) up to, excluding,`n` (or`b` ).\n- `sorted(a)` : a sorted copy.\n- `sort(a)` : in place.\n- `has(m, k)` ,`remove(m, k)` (a copy),`keys(m)` ,`values(m)` on map`m` .\n- `any(a)` ,`all(a)` : of an array of bools or ints, or the values of a map.\n- `sum(a)` ,`min(a)` ,`max(a)` ,`mean(a)` ,`stddev(a)` ,`percentile(a, p)` :\nof an array, or the values of a map.\n- `histogram(a, bucket=b)` : the values counted in buckets of width`b` from\n0, as an array of`{min, count, max}` ,`min` and`max` being observed values.\n- `checksum(b)` : the 2 bytes of the Internet checksum of`b` (RFC 1071)\n- `be16(x)` ,`le16(x)` , all the way to 64: the bytes of an int, big and little endian.\n\nEach field has the modes in which it can be *set* as an option\nand *read* in a condition or in `MATCH`: **M** manual, **S** self-driven. A\nlayer with a single mode is manual. *(key)* fields tell streams apart.\n\nEvery layer but the terminal ones has also `length`: int; read M;\nthe bytes it carries (`TCP!(length > 0)`: segments with data). `Raw` has it\ntoo: the bytes of its data. Exception: `UDP.length` is the `length` field of the\nheader.\n\n- `src` : mac; set M; read M, S. Default: the interface's.\n- `dst` : mac; set M; read M, S. Default: what the interface knows of the\nnext hop of the route (neighbors, gateway), without asking.\n- `proto` : int; set M; read M, S. Default: the layer on top.\n- `ts` : time; read M, S. When the frame was captured; for what is\nreassembled, the frame that completed it. Unset in`LAST` .\n\nSelf-driven, it carries `IP` and `IP6`, and finds next hops with ARP and\nneighbor discovery (or ask the kernel).  `Eth!` frames go out as they are.\n\n- `src` (key): ip; set M, S; read M, S. Default: the interface's address\n(that reaches`dst` ).\n- `dst` (key): ip; set M, S; read M, S. Required.\n- `proto` : int; set M, S; read M, S. Default: the layer on top.\n- `tos` : int; set M, S; read M, S.\n- `ttl` : int; set M, S; read M, S. Default 64.\n- `dont_frag` : bool; set M, S; read M, S. Default false.\n- `id` : int; set M; read M, S. Default: the stream's counter, from a random\nvalue.\n- `more_frags` : bool; set M; read M.\n- `frag_offset` : int; set M; read M. In blocks of 8 bytes.\n- `tot_len` : int; set M; read M. Default: computed.\n- `options` : bytes; set M, S; read M, S.\n- `rr_slots` : int; set M, S; read M, S. The slots of the record route\noption, up to 9, or -1 without one.\n- `record_route` : ip[]; set M, S; read M, S. The addresses recorded in it.\nGiven, they fill its first slots;`rr_slots` is then their number unless\ngiven.\n- `is_fragment` : bool; read M.\n\nSelf-driven IP fragments to the MTU and reassembles. `tos`, `ttl`,\n`dont_frag` and `options` apply to what it sends, but for the segments of a\nself-driven TCP connection. `IP!` sends the header as given, but for the\nchecksum.\n\n- `src` (key): ip; set M, S; read M, S. Default: the interface's address\nthat reaches`dst` .\n- `dst` (key): ip; set M, S; read M, S. Required.\n- `proto` : int; set M, S; read M, S. Default: the layer on top. Received,\nthat past the extension headers.\n- `traffic_class` : int; set M, S; read M, S. Default 0.\n- `hop_limit` : int; set M, S; read M, S. Default 64.\n- `flow_label` : int; set M; read M, S. Default 0.\n- `frag_id` : int; set M; read M. Default 0.\n- `frag_offset` : int; set M; read M. In blocks of 8 bytes. Default 0.\n- `more_frags` : bool; set M; read M. Default false.\n- `is_fragment` : bool; read M.\n\nThe `frag_` fields and `more_frags` are those of the fragment header: 0 and\nfalse without one.\n\nSelf-driven IP6 fragments to the MTU and reassembles, as `IP`.\n\n- `src` (key): int; set M, S; read M, S. Default: a port of`--tcp` .\n- `dst` (key): int; set M, S; read M, S. Required.\n- `seq_num` : int; set M; read M.\n- `ack_num` : int; set M; read M.\n- `flags` : int; set M; read M. Constants`FIN` ,`SYN` ,`RST` ,`PSH` ,`ACK` ,`URG` ,`ECE` ,`CWR` .\n- `win_size` : int; set M; read M.\n- `urg_ptr` : int; set M; read M.\n- `checksum` : int; set M; read M. Default: computed, as when 0, but in a\nfragment (see`encode` ).\n- `options` : bytes; set M; read M. Default: none.\n- `mss` ,`wscale` : int; set M, S; read M. The first option of each kind,\nor -1.\n- `ts_val` ,`ts_ecr` : int; set M; read M. Those of the timestamps option, or\n-1.\n- `sack_ok` : bool; set M; read M. Whether SACK is permitted.\n\nThe fields of the options cannot be given with `options`. A missing `ts_val` or\n`ts_ecr` is 0. Given -1 they leave it out. Self-driven, `mss` and `wscale` are\nwhat the connection offers (-1 offers no window scaling, which caps its window\nat 64KiB).\n\nSelf-driven, the first message sent connects, and what follows waits for the connection. A TCP stream created by a pattern accepts the connection instead.\n\n`TCP!` segments take the sequence and ack numbers, the window and the ACK|PSH\nflags of the stream's connection when not given, and update them.\n\n- `src` (key): int; set M; read M. Default: a port of`--udp` .\n- `dst` (key): int; set M; read M. Required, unless told by the layer on\ntop.\n- `length` : int; set M; read M. Default: computed.\n- `checksum` : int; set M; read M. Default: computed, as when 0, but in a\nfragment (see`encode` ).\n\n- `type` ,`code` : int; set M; read M. Set by the message on top, but for`Raw` :`ICMP(type=13)/Raw(...)` needs a`type` (`code` defaults to 0).\n\n- `type` ,`code` : int; set M; read M. As those of`ICMP` . On top:`Echo` (128, 129),`DestUnreachable` (1),`PacketTooBig` (2),`TimeExceeded` (3),`RouterSolicit` (133),`RouterAdvert` (134),`Redirect` (137), else`Raw` .`IP6` computes the checksum.\n\n- `id` (key): int; set M; read M. Default: a free random id.\n\nThe stream of an echo id, for `Request` and `Reply` messages, which count\ntheir sequence numbers per stream.\n\n- `seq` : int; set M; read M. Default: the stream's counter, from 1.\n- `payload` : bytes; set M; read M. Default field.\n\n- `code` : int; set M; read M. Default 0. Constants:`NET_UNREACHABLE` ,`TTL_EXCEEDED` ,`PORT_UNREACHABLE6` etc.\n- `mtu` : int; set M; read M. Not in`TimeExceeded` ; default 0. Always 0 in\na`DestUnreachable` of`ICMP6` .\n\nOn top is the quoted `IP` (`IP6` under `ICMP6`) the error is about, or `Raw`.\n\n`RouterSolicit`:\n\n- `src_lla` : mac; set M; read M. Default: the interface's.\n\n`RouterAdvert`:\n\n- `hop_limit` : int; set M; read M. Default 64.\n- `managed` ,`other_config` : bool; set M; read M. Default false.\n- `flags` : int; set M; read M. The 6 other bits. Default 0.\n- `lifetime` : int; set M; read M. Seconds. Default 1800.\n- `reachable` ,`retrans` : int; set M; read M. Milliseconds. Default 0.\n- `src_lla` : mac; set M; read M. Default: the interface's.\n- `mtu` : int; set M; read M. Default -1.\n- `prefixes` : records; set M; read M. Default none. Each is`{prefix: cidr, on_link: bool, autonomous: bool, valid: int, preferred: int}` .\n\n`Redirect`:\n\n- `target` ,`dst` : ip; set M; read M. Required.\n- `target_lla` : mac; set M; read M. Default 00:00:00:00:00:00.\n\nAll have `options`: bytes; set M; read M.\nOn top of `Redirect` is the start of the packet redirected, a quoted `IP6` or\n`Raw`, cut to a multiple of 8 bytes.\n\n```\np = {prefix: 2001:db8:1::/64, on_link: true, autonomous: true, valid: 86400, preferred: 14400}\n/IP6(dst=ff02::1)/ICMP6/RouterAdvert(mtu=1400, prefixes=[p])\n```\n\nThey have the fields of `IP`, `IP6`, `UDP` and `TCP` (but `is_fragment`), all\nreadable and settable. They are no streams: a quoted TCP segment is no part\nof a connection. Errors print them as `IP?`, `IP6?`, `UDP?`, `TCP?`.\n\n```\non for=5s /IP/ICMP/TimeExceeded/IP(dst == target)/UDP(dst == 33434) {\n  print(\"from ${MATCH[/IP].src}, ttl ${MATCH[TimeExceeded/IP].ttl}\")\n}\n```\n\n`MATCH[TimeExceeded/IP]` is the quoted packet, `MATCH[/IP]` the error's.\nA quote is often cut 8 bytes after the IP header: absent fields will read 0.\nA quoted first fragment has its `UDP` or `TCP` on top; a later one, `Raw`.\nSent, a quoted `IP` or `IP6` needs a `src` and a `dst`; lengths and checksums\nare managed.\n\n```\n/IP6(dst=2001:db8::2)/UDP(src=4000, dst=9)/Raw(\"anyone?\")\nexpect timeout=1s /IP6/ICMP6/DestUnreachable(code == PORT_UNREACHABLE6)/IP6/UDP(src == 4000) {\n  print(\"closed, says ${MATCH[/IP6].src}\")\n}\n```\n\n- `id` (key): int; set M; read M. Default: a free random id.\n\nThe stream of a DNS id, for `Query` and `Answer` messages.\n\n- `name` : string; set M; read M. Default field; required. Without the\ntrailing dot (`\"example.com\"` ), but for the root (`\".\"` ).\n- `type` : int; set M; read M. Default`TYPE_A` . Constants`TYPE_A` ,`TYPE_NS` , etc.\n- `class` : int; set M; read M. Default`CLASS_IN` .\n- `opcode` : int; set M; read M. Default 0.\n- `authoritative` ,`truncated` ,`rec_avail` ,`authentic_data` ,`checking_disabled` : bool; set M; read M. Default false.\n- `rec_desired` : bool; set M; read M. Default true.\n- `status` : int; set M; read M. Default`NOERROR` . Constants`NOERROR` ,`FORMERR` ,`SERVFAIL` , etc.\n- `answers` ,`authority` ,`additional` : records; set M; read M. Default\nnone. Each is`{name: string, type: int, class: int, ttl: int, data: bytes}` ; the data of an A record converts to an IP address.\n\nA message has one question (`name`, `type`, `class`): the first, of a\nreceived message with several.\n\nThe stream of the HTTP/1.x messages of a TCP connection, then, after a 101\nanswer received or sent, of its WebSocket frames. On `TCP`, each is seen\nonce complete; on `TCP!`, those that fill a segment.\nAn answer without a length ends with the connection (or the segment's FIN).\nNot seen: the answer to a `HEAD` (it waits for a body).\n\n- `method` : string; set M; read M. Of`HttpRequest` . Default`\"GET\"` .\n- `url` : string; set M; read M. Of`HttpRequest` . Default field; default`\"/\"` .\n- `code` : int; set M; read M. Of`HttpAnswer` . Default field; required.\n- `version` : string; set M; read M. Default`\"HTTP/1.1\"` .\n- `headers` : records; set M; read M. Default none. Each is`{name: string, value: string}` , sent in order, as given: give a`Host` .\n\nAlone, a message has no body; `Raw` on top is its body, sent as given.\n`Content-Length` is added unless a length or `Transfer-Encoding` header is\ngiven. Received, `MATCH[Raw].data` is the body, dechunked. A 101 answer to a\nrequest with a `Sec-WebSocket-Key` gets its `Sec-WebSocket-Accept`, unless\ngiven.\n\n```\n/IP(dst=192.0.2.10)/TCP(dst=80)/HTTP {\n  HttpRequest(\"/upload\", method=\"POST\", headers=[{name: \"Host\", value: \"example.com\"}])/Raw(\"data\")\n  expect timeout=1s HttpAnswer(code >= 400) { print(\"refused: ${MATCH[HttpAnswer].code}\") }\n}\n```\n\n- `url` : string; set M. Default field; required. Gives the request line and\nthe`Host` ; the stack gives the destination. No`wss` or`https` : no TLS.\n- `version` : string; set M. Default`\"HTTP/1.1\"` .\n- `headers` : records; set M. Default none. Added last, replacing those of the\nsame name. Must give a`Host` if`url` has no host.\n\nThe `GET` asking for a WebSocket.  Only sent: it is received, matched and read\nback (`p[HttpRequest]`) as an `HttpRequest`.\n\n- `opcode` : int; set M, S; read M, S. Default field; default`WS_BINARY` .\nConstants`WS_CONTINUATION` ,`WS_TEXT` ,`WS_BINARY` ,`WS_CLOSE` , etc.\n- `final` : bool; set M; read M. Default true.\n- `masked` : bool; set M; read M. Default: whether this side sent the\nrequest.\n- `mask` : int; set M; read M. As on the wire (0 if not masked). Default:\nrandom.\n\n`Raw` on top is the payload, unmasked. `WebSocket!` is each frame, sent as\ngiven. `WebSocket` is each message, its fragments joined, and each close;\nonce a self-driven stack or pattern uses the stream, it answers pings\n(which it does not show) and a close it did not send.\n\n```\n/IP(dst=192.0.2.10)/TCP(dst=80)/HTTP {\n  HttpUpgrade(\"ws://example.com/chat\")\n  expect timeout=1s HttpAnswer(101) {}\n  WebSocket(WS_TEXT)/Raw(\"hello\")\n  expect timeout=1s WebSocket(WS_TEXT) { print(MATCH[Raw].data) }\n  WebSocket(WS_CLOSE)\n}\n```\n\n#### `Raw` (on `Eth`, `IP`, `TCP`, `UDP`, `ICMP`, the ICMP errors, the quoted layers, `HttpRequest`, `HttpAnswer` and `WebSocket`, terminal)\n\n- `data` : bytes; set M; read M. Default field.\n\nWhat a layer carries when not decoded further. Sent as given.\n\n```\n/IP(dst=192.0.2.53)/UDP/DNS {\n  Query(\"www.example.com\")\n  expect timeout=2s Answer(status == NOERROR) {\n    a = MATCH[Answer].answers\n    assert(length(a) > 0 && a[0].type == TYPE_A, msg=\"no address\")\n    /IP(dst=a[0].data)/ICMP/Echo {\n      received = 0\n      repeat count=5 every=200ms {\n        Request(\"hi\")\n        expect timeout=1s Reply {\n          received += 1\n          print(\"reply from ${MATCH[IP].src}: seq=${MATCH[Reply].seq} ttl=${MATCH[IP].ttl}\")\n        } else {}\n      }\n      print(\"${received} replies out of 5\")\n    }\n  } | Answer {\n    assert(false, msg=\"DNS error ${MATCH[Answer].status}\")\n  }\n}\n% sudo crafty --ip 192.0.2.5 ping.cfty\nreply from 192.0.2.10: seq=1 ttl=64\n...\n5 replies out of 5\n```\n\nThe replies come back to the `Echo` stream of the requests, whatever its id.\n\n```\n# Every 10s, the round trip times of the last 10s\n/IP!(dst=192.0.2.10)/UDP(dst=7) {\n  rtts = []\n  spawn { repeat every=10s { report(rtts, name=\"rtt\") ; rtts := [] } }\n  repeat count=6000 every=10ms {\n    p = Raw(\"probe ${I}\")\n    expect timeout=500ms Raw(\"probe ${I}\") { rtts += MATCH[Eth].ts - p[Eth].ts } else {}\n  }\n}\n```\n\nWith `--format json`, each report is a line such as\n`{\"type\":\"report\",\"ts\":10.0,\"name\":\"rtt\",\"value\":{\"count\":998,\"max\":0.0021,\"mean\":0.0012,...}}`\n(intervals in seconds). The first one, at 0s, has only a `count` of 0.\n\n```\n# 100 probes to a UDP echo server: how many come back, and how fast?\n/IP!(dst=192.0.2.10)/UDP(dst=7) {\n  rtts = []\n  repeat count=100 every=10ms {\n    p = Raw(\"probe ${I}\")\n    expect timeout=500ms Raw(\"probe ${I}\") { rtts += MATCH[Eth].ts - p[Eth].ts } else {}\n  }\n  print(\"${length(rtts)}/100 echoed, rtt min ${min(rtts)} median ${percentile(rtts, 50)} p99 ${percentile(rtts, 99)} max ${max(rtts)}\")\n  for b in histogram(rtts, bucket=1ms) { print(\"${b.min} to ${b.max}: ${b.count}\") }\n}\n% sudo crafty --ip 192.0.2.5 --udp 40000-40010 rtt.cfty\n100/100 echoed, rtt min 4.34351ms median 7.94053ms p99 10.2825ms max 10.6628ms\n4.34351ms to 4.77314ms: 8\n...\n```\n\nThe times are those of the captures, of the probe going out and of its echo coming in. Each probe expects its own echo, so that a late one is not taken for the next.\n\n```\nBUDGET = {max_duration: 61m}\non for=1h /IP/TCP(dst == 80)/HTTP/HttpRequest {\n  /IP(dst=MATCH[IP].src)/TCP(src=80, dst=MATCH[TCP].src)/HTTP {\n    if MATCH[HttpRequest].url == \"/\" { HttpAnswer(200)/Raw(\"hello\\n\") }\n    else { HttpAnswer(404) }\n  }\n}\n% sudo crafty --tcp 80 --fw server.cfty\nPERMISSIONS = {exfiltration: true}  # it sends what's sniffed\nBUDGET = {max_duration: 61m}\non for=1h /IP/UDP(dst == 7)/Raw {\n  /IP(dst=MATCH[IP].src)/UDP(src=7, dst=MATCH[UDP].src)/Raw(MATCH[Raw].data)\n}\n% sudo crafty --udp 7 --fw server.cfty\n# 4 flows of 25 datagrams to the UDP echo server: how many get no echo?\ntarget = ip_addr(arg(0))\nlost = array(init=25, len=4)\n{\n  on linger=1s /IP(src == target)/UDP(src == 7, dst >= 40000, dst < 40004) {\n    lost[MATCH[UDP].dst - 40000] -= 1\n  }\n  repeat count=100 every=10ms {\n    /IP(dst=target)/UDP(src=40000 + I % 4, dst=7)/Raw(\"ping\")\n  }\n}\nrepeat var=f count=4 { print(\"flow ${f}: ${lost[f]} lost\") }\n% sudo crafty --udp 40000-40003 --fw losses.cfty\nflow 0: 0 lost\n...\n```\n\nThe `on` starts listening before the datagrams go out, and goes on 1s after\nthe last one.\n\n```\n/IP(dst=192.0.2.10)/TCP(src=40001, dst=22) {\n  Raw(\"hello\")\n  expect timeout=1s ../TCP!(flags & RST) { print(\"reset by ${MATCH[IP].src}\") }\n}\n```\n\nA reset carries no data, so a pattern on top of `TCP` never sees it; `../TCP!`\nsees each segment of the connection.\n\n```\n/IP(dst=192.0.2.10)/UDP(dst=7) {\n  p = Raw(\"ping\")\n  expect timeout=1s Raw { print(\"rtt: ${MATCH[Eth].ts - p[Eth].ts}\") }\n}\n/IP(dst=192.0.2.10)/TCP(dst=7) {\n  Raw(\"hello\")\n  expect timeout=1s Raw {\n    s = stats()\n    print(\"srtt ${s.srtt}, mss ${s.snd_mss}, peer window ${s.snd_wnd}\")\n  }\n}\n# 10s of data, as fast as the connection takes it:\n/IP(dst=192.0.2.10)/TCP(dst=7) {\n  repeat for=10s { Raw(randbytes(1000)) }\n  wait 1s             # for what is still buffered or in flight\n  s = stats()\n  print(\"${s.bytes_acked} bytes acked, ${s.retrans} retransmitted, srtt ${s.srtt}, cwnd ${s.cwnd}\")\n}\n```\n\nA write waits while TCP's send buffer is full, so the connection sets the rate;\n`every=10ms` would set it to 100 writes per second instead.\n\n```\n/Eth!(dst=ff:ff:ff:ff:ff:ff, proto=0x88b5)/Raw(\"hello\")\n/IP!(dst=192.0.2.10, ttl=1, id=1234, dont_frag=true)/UDP(src=40000, dst=9)/Raw(#deadbeef)\n```\n\nWhole programs\n\n```\n# Every probe goes from the same UDP port to the same port, so that routers\n# that balance per flow send them all the same way: where a hop still shows\n# several routers, they balance per packet.\n# usage: lbtrace.cfty TARGET [PROBES] [MAX_HOPS] [PORT]\ntarget = resolve(arg(0))[0]\nprobes = int(arg(1, default=\"5\"))      # per hop\nmax_hops = int(arg(2, default=\"30\"))\nport = int(arg(3, default=\"33434\"))\n/IP!(dst=target)/UDP(dst=port) {\n  probe = 0                       # the IP id, that tells the probes apart\n  repeat var=hop count=max_hops {\n    rtts = map(key=0.0.0.0, default=[])\n    reached = false\n    repeat count=probes {\n      probe += 1\n      p = ../../IP!(ttl=hop + 1, id=probe)/UDP/Raw(\"probe\")\n      if probe == 1 { print(\"to ${target} from UDP port ${p[UDP].src} to ${port}\") }\n      expect timeout=1s /IP/ICMP/TimeExceeded/IP(id == probe, dst == target)/UDP {\n        rtts[MATCH[/IP].src] += MATCH[Eth].ts - p[Eth].ts\n      } | /IP/ICMP/DestUnreachable/IP(id == probe, dst == target)/UDP {\n        rtts[MATCH[/IP].src] += MATCH[Eth].ts - p[Eth].ts\n        reached := true\n      } else {}\n    }\n    head = \"${hop + 1}\"\n    answered = 0\n    for r in rtts {\n      answered += length(r.value)\n      ms = float(int(float(min(r.value)) * 100000.0)) / 100.0\n      print(\"${head}\\t${r.key}\\t${length(r.value)}/${probes}\\tmin ${ms}ms\")\n      head := \"\"\n    }\n    if answered < probes { print(\"${head}\\t*\\t${probes - answered}/${probes}\") }\n    if reached { break }\n  }\n}\n% sudo crafty --udp 40000 --fw lbtrace.cfty 10.2.1.3 8\nto 10.2.1.3 from UDP port 40000 to 33434\n1\t10.1.1.1\t8/8\tmin 0.04ms\n2\t10.1.0.5\t4/8\tmin 37.67ms\n\t10.1.0.6\t4/8\tmin 34.92ms\n3\t10.2.0.1\t2/8\tmin 89.71ms\n\t10.2.0.2\t6/8\tmin 90.97ms\n4\t10.2.0.6\t8/8\tmin 117.6ms\n5\t10.2.1.3\t8/8\tmin 110.92ms\n```\n\nHops 2 and 3 balance per packet. Behind routers that balance per flow, each\nhop shows one router, and another port may show another path. A `*` line\ncounts the probes without an answer.\n\n```\n# Echo requests that must not be fragmented, to find the path MTU in each direction:\n# - echoed whole: the size fits both ways;\n# - echoed in fragments: it fits the way out, and the largest fragment bounds the\n#   MTU of the way back (fragments carry multiples of 8 bytes, so within 7 bytes);\n# - Frag-Needed: a router on the way out tells its next hop MTU;\n# - nothing: dropped silently, on the way out or, if the reply had DF, on the way back.\n# usage: pmtu.cfty TARGET [MTU]\ntarget = resolve(arg(0))[0]\nlo = 68                                         # fits any IPv4 path\nhi = int(arg(1, default=\"1500\"))\nfrag_max = 0                                    # largest fragment of the last reply\nret_mtu = 0                                     # the way back fragmented at this size\n{\n  # Raw fragments from the target, alongside the self-driven stream that reassembles them\n  on /IP!(src == target && is_fragment) {\n    if MATCH[IP].tot_len > frag_max { frag_max := MATCH[IP].tot_len }\n  }\n  /IP(dst=target, dont_frag=true)/ICMP/Echo {\n    size = hi\n    repeat count=32 {\n      told = 0\n      answered = false\n      frag_max := 0\n      Request(seq=size, payload=#00 * (size - 28))\n      expect timeout=1s Reply(seq == size) {\n        answered := true\n        lo := size\n        if frag_max > 0 {\n          print(\"${size}: echoed in fragments of up to ${frag_max} bytes\")\n          ret_mtu := frag_max\n        } else { print(\"${size}: echoed whole\") }\n      } | /IP(src != target)/ICMP/DestUnreachable(code == FRAG_NEEDED)/IP(dst == target, tot_len == size) {\n        told := MATCH[DestUnreachable].mtu\n        answered := true\n        print(\"${size}: too big for ${MATCH[/IP].src}, next hop MTU ${told}\")\n      } else {}\n      if !answered { print(\"${size}: no answer (dropped one way or the other)\") }\n      if told > lo && told < size {\n        hi := told\n        size := told\n      } else {\n        if !answered || told > 0 { hi := size - 1 }\n        if lo >= hi { break }\n        size := (lo + hi + 1) / 2\n      }\n    }\n  }\n}\nprint(\"way out: ${lo} bytes get through\")\nif ret_mtu > 0 { print(\"way back: fragmented, MTU about ${ret_mtu} bytes\") }\n% sudo crafty pmtu.cfty 10.2.1.3\n1500: too big for 10.1.0.5, next hop MTU 1400\n1400: no answer (dropped one way or the other)\n734: echoed whole\n1067: echoed whole\n1233: echoed whole\n1316: no answer (dropped one way or the other)\n1274: echoed whole\n1295: no answer (dropped one way or the other)\n1284: no answer (dropped one way or the other)\n1279: echoed whole\n1281: no answer (dropped one way or the other)\n1280: echoed whole\nway out: 1280 bytes get through\n```\n\n10.1.0.5 reports its MTU of 1400, but a router further on drops what exceeds 1280 without a word.\n\n```\n# Probes every hop once per round, on one flow as the traceroute does, and\n# reports each hop's losses and round trips every REPORT rounds.\n# usage: mtr.cfty TARGET [ROUNDS] [REPORT] [INTERVAL] [MAX_HOPS] [PORT]\ntarget = resolve(arg(0))[0]\nrounds = int(arg(1, default=\"60\"))\nper_report = int(arg(2, default=\"10\"))   # rounds per report\npace = interval(arg(3, default=\"1s\"))\nmax_hops = int(arg(4, default=\"30\"))   # less than 64\nport = int(arg(5, default=\"33434\"))\nlast = max_hops - 1               # the target's hop, from 0, once known\nsent = array(init=0, len=max_hops)\nrtts = array(init=[], len=max_hops)\nhosts = array(init=map(key=0.0.0.0, default=0), len=max_hops)\nsent_at = map(key=0, default=now())     # by IP id: round * 64 + hop\n/IP!(dst=target)/UDP(dst=port) {\n  on /IP/ICMP/TimeExceeded/IP(dst == target)/UDP(dst == port) |\n     /IP/ICMP/DestUnreachable(code == PORT_UNREACHABLE)/IP(dst == target)/UDP(dst == port) {\n    id = MATCH[ICMP/_/IP].id\n    if has(sent_at, id) {\n      hop = id % 64\n      rtts[hop] += MATCH[Eth].ts - sent_at[id]\n      hosts[hop][MATCH[/IP].src] += 1\n      if MATCH[/IP].src == target && hop < last { last := hop }\n      sent_at := remove(sent_at, id)\n    }\n  }\n  repeat var=r count=rounds + 1 every=pace {\n    if r > 0 && r % per_report == 0 {\n      print(\"after ${r} rounds:\")\n      repeat var=hop count=last + 1 {\n        s = sent[hop]\n        n = length(rtts[hop])\n        line = \"${hop + 1}\\t${keys(hosts[hop])}\\tloss ${(s - n) * 100 / s}%\"\n        if n > 0 {\n          avg = float(int(float(mean(rtts[hop])) * 100000.0)) / 100.0\n          best = float(int(float(min(rtts[hop])) * 100000.0)) / 100.0\n          worst = float(int(float(max(rtts[hop])) * 100000.0)) / 100.0\n          line := \"${line}\\tavg ${avg}ms\\tbest ${best}ms\\tworst ${worst}ms\"\n        }\n        print(line)\n        sent[hop] := 0\n        rtts[hop] := []\n        hosts[hop] := map(key=0.0.0.0, default=0)\n      }\n      sent_at := map(key=0, default=now())    # too late for the next report\n    }\n    if r < rounds {\n      repeat var=hop count=last + 1 {\n        id = (r * 64 + hop) % 65536\n        p = ../../IP!(ttl=hop + 1, id=id)/UDP/Raw(\"probe\")\n        sent_at[id] := p[Eth].ts\n        sent[hop] += 1\n      }\n    }\n  }\n}\n% sudo crafty --udp 40000 --fw mtr.cfty 10.2.1.3 40 20 200ms\nafter 20 rounds:\n1\t[10.1.1.1]\tloss 0%\tavg 0.33ms\tbest 0.11ms\tworst 0.48ms\n2\t[10.1.0.5]\tloss 50%\tavg 37.81ms\tbest 37.6ms\tworst 38.1ms\n3\t[10.2.0.2]\tloss 0%\tavg 90.91ms\tbest 90.69ms\tworst 91.07ms\n4\t[10.2.0.6]\tloss 10%\tavg 114.42ms\tbest 114.18ms\tworst 115.02ms\n5\t[10.2.1.3]\tloss 5%\tavg 114.23ms\tbest 114.09ms\tworst 114.73ms\nafter 40 rounds:\n1\t[10.1.1.1]\tloss 0%\tavg 0.33ms\tbest 0.09ms\tworst 0.6ms\n2\t[10.1.0.5]\tloss 45%\tavg 37.81ms\tbest 37.6ms\tworst 37.97ms\n3\t[10.2.0.2]\tloss 0%\tavg 90.87ms\tbest 90.68ms\tworst 91.3ms\n4\t[10.2.0.6]\tloss 20%\tavg 114.47ms\tbest 114.1ms\tworst 116.44ms\n5\t[10.2.1.3]\tloss 15%\tavg 114.37ms\tbest 114.02ms\tworst 116.14ms\n```\n\nHop 2 only answers half of its probes: hop 3 losing none, what is lost is the answers, not the traffic. The losses start between hops 3 and 4, and go on to the target.", "url": "https://wpnews.pro/news/show-hn-scapy-for-the-agentic-sre", "canonical_source": "https://github.com/rixed/robinet/blob/master/docs/crafty.md", "published_at": "2026-11-24 10:42:46+00:00", "updated_at": "2026-11-24 11:12:42.333672+00:00", "lang": "en", "topics": ["developer-tools"], "entities": ["Crafty", "Scapy"], "also_reported_by": [], "takeaway": "Crafty scripts send packets from a real interface and match replies with expect blocks, letting a three-datagram UDP echo test at 192.0.2.10 port 7 report \"3 answers out of 3: all back\" in 0.3s.", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/show-hn-scapy-for-the-agentic-sre", "markdown": "https://wpnews.pro/news/show-hn-scapy-for-the-agentic-sre.md", "text": "https://wpnews.pro/news/show-hn-scapy-for-the-agentic-sre.txt", "jsonld": "https://wpnews.pro/news/show-hn-scapy-for-the-agentic-sre.jsonld"}}