feat(core): event queue, Ethernet, switch, ARP, IPv4, ICMP, routing and firewall
First slice of the TypeScript port of the filius-ipad runtime engine, with 29 tests ported from the Swift suite. Parts not ported yet throw NotPortedError instead of guessing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+4
-11
@@ -1,14 +1,7 @@
|
||||
# ---> VisualStudioCode
|
||||
node_modules/
|
||||
dist/
|
||||
coverage/
|
||||
*.tsbuildinfo
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
!.vscode/*.code-snippets
|
||||
|
||||
# Local History for Visual Studio Code
|
||||
.history/
|
||||
|
||||
# Built Visual Studio Code Extensions
|
||||
*.vsix
|
||||
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
# Herkunft und Änderungen
|
||||
|
||||
Nach GPL §5a: was aus welcher Quelle übertragen und wie es verändert wurde.
|
||||
Swift-Pfade relativ zu `filius-ipad/ios/FiliusPad/TopologyEditor/` (Stand
|
||||
`3b5ded0`, 27.08.2026), Tests relativ zu `filius-ipad/ios/FiliusPadTests/`.
|
||||
|
||||
## packages/core
|
||||
|
||||
| Datei | Quelle | Art der Übertragung |
|
||||
| --- | --- | --- |
|
||||
| `src/ids.ts` | Swift-Sortierung nach `UUID.uuidString` | neu, bildet die Swift-Ordnung nach |
|
||||
| `src/model/node.ts` | `Model/TopologyNode.swift` | übertragen; Standard-Ports und -Namen wie Java |
|
||||
| `src/runtime/config.ts` | `State/TopologyEditorState.swift` (Laufzeit-Konfigurationen, Firewall) | übertragen; Java-Beschriftungen der Oberfläche weggelassen |
|
||||
| `src/runtime/engine.ts` | `State/TopologyNetworkRuntimeEngine.swift` Z. ~313–3585, ~4753–4850 | übertragen: Warteschlange, Uhr, Ethernet, Switch, ARP, IPv4, ICMP, Routing, Firewall. Klasse statt Werttyp. Noch nicht übertragen (wirft `NotPortedError`): Gateway-NAT, UDP, TCP, DHCP, DNS, RIP, Remote Link, WLAN |
|
||||
| `src/runtime/ipv4.ts` | Engine `parseIPv4`/`sameSubnet` | übertragen |
|
||||
| `src/runtime/packets.ts` | Engine, Paketmodelle | übertragen; `Data` → `Uint8Array` |
|
||||
| `src/runtime/random.ts` | Engine, `TopologyJavaCompatibleRandom` | übertragen; BigInt für die 48-Bit-Arithmetik |
|
||||
| `src/runtime/routeTable.ts` | `State/TopologyJavaRouteTable.swift` | übertragen ohne Tabellengeometrie (gehört in den Editor) |
|
||||
| `src/runtime/snapshot.ts` | Engine, `TopologyNetworkRuntimeTopologySnapshot` | übertragen, bisher mit den Feldern der übertragenen Schichten |
|
||||
| `src/runtime/speed.ts` | Engine, `TopologyNetworkRuntimeSpeed` | übertragen |
|
||||
| `src/runtime/trace.ts` | Engine, Paketspur-Modell | übertragen |
|
||||
| `src/util/equal.ts` | — | neu (Ersatz für Swifts `Equatable`) |
|
||||
| `test/engine.test.ts` | `TopologyNetworkRuntimeEngineTests.swift` (21 von 72 Tests) | übertragen; `nextInt`-Referenzwerte an OpenJDK 21 gemessen |
|
||||
| `test/routeTable.test.ts` | `TopologyJavaRouteTableTests.swift` (8 von 12 Tests) | übertragen; Geometrie- und Reducer-Tests folgen mit Editor und Dokument |
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
@@ -1,2 +1,45 @@
|
||||
# mdg-filius
|
||||
|
||||
Netzwerksimulation nach [FILIUS](https://www.lernsoftware-filius.de) für den
|
||||
Browser — als App „Filius" im MDG-Dashboard, gemeinsam bearbeitbar.
|
||||
|
||||
> Based on Filius by Dr. Stefan Freischlad and the Filius project.
|
||||
>
|
||||
> Dieses Projekt ist unabhängig. Es wird weder vom ursprünglichen
|
||||
> Filius-Projekt (Universität Siegen) noch von `filius-project`
|
||||
> (Filius on iPad) herausgegeben, betrieben oder unterstützt.
|
||||
|
||||
## Herkunft
|
||||
|
||||
Der Simulationskern ist eine Übertragung nach TypeScript aus
|
||||
|
||||
* [`filius-project/filius-ipad`](https://github.com/filius-project/filius-ipad)
|
||||
(Swift, GPLv2 oder GPLv3) — Vorlage für Kern, `.fls`-Codec und Tests,
|
||||
* [`filius1/filius`](https://gitlab.com/filius1/filius) (Java, GPLv2 oder
|
||||
GPLv3) — Referenz für Dateiformat und Verhalten.
|
||||
|
||||
Jede übertragene Datei nennt in ihrem Kopf die Quelldatei. `CHANGES.md` führt
|
||||
die Herkunft je Paket. Lizenz dieses Repos: **GPL-3.0** (`LICENSE`).
|
||||
|
||||
## Aufbau
|
||||
|
||||
| Pfad | Inhalt |
|
||||
| --- | --- |
|
||||
| `packages/core` | Simulationskern: Modell, Ereignis-Warteschlange, Protokolle, Anwendungen — ohne DOM, ohne Node |
|
||||
| `packages/fls` | `.fls` lesen, schreiben, Unbekanntes bewahren *(folgt)* |
|
||||
| `packages/doc` | gemeinsames Dokument (Yjs) *(folgt)* |
|
||||
| `packages/editor` | Oberfläche im Iframe des Dashboards *(folgt)* |
|
||||
| `server` | Filius-Dienst auf Server F *(folgt)* |
|
||||
|
||||
Plan und Entscheidungen: `knowledge/plans/FILIUS_WEB_PLAN.md` im Dashboard.
|
||||
|
||||
## Entwickeln
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run hooks # Sprachprüfung vor jedem Commit (braucht das Dashboard drumherum)
|
||||
npm run check # Typprüfung + Tests
|
||||
```
|
||||
|
||||
Code, Kommentare und Testnamen sind englisch; sichtbare Texte stehen hinter
|
||||
i18n-Schlüsseln (Deutsch/Englisch).
|
||||
|
||||
Generated
+1650
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "mdg-filius",
|
||||
"private": true,
|
||||
"license": "GPL-3.0-only",
|
||||
"type": "module",
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"typecheck": "tsc -b",
|
||||
"check": "npm run typecheck && npm run test",
|
||||
"hooks": "git config core.hooksPath scripts/hooks"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.19.0",
|
||||
"typescript": "^5.9.0",
|
||||
"vitest": "^3.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"name": "@mdg-filius/core",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"license": "GPL-3.0-only",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3), ios/FiliusPad/TopologyEditor.
|
||||
// Swift orders identifiers by `UUID.uuidString`, which is upper case. Every
|
||||
// deterministic ordering in the runtime depends on it, so identifiers are
|
||||
// compared the same way here whatever case they were written in.
|
||||
|
||||
/** A node, port, link or socket identifier: a UUID string. */
|
||||
export type Id = string;
|
||||
|
||||
/** `lhs.uuidString < rhs.uuidString` in Swift. */
|
||||
export function idLess(lhs: Id, rhs: Id): boolean {
|
||||
return lhs.toUpperCase() < rhs.toUpperCase();
|
||||
}
|
||||
|
||||
/** Comparator for `Array.prototype.sort` with the Swift ordering. */
|
||||
export function compareIds(lhs: Id, rhs: Id): number {
|
||||
const left = lhs.toUpperCase();
|
||||
const right = rhs.toUpperCase();
|
||||
return left < right ? -1 : left > right ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Public surface of the simulation core.
|
||||
export * from './ids.js';
|
||||
export * from './model/node.js';
|
||||
export * from './runtime/config.js';
|
||||
export * from './runtime/engine.js';
|
||||
export * from './runtime/ipv4.js';
|
||||
export * from './runtime/packets.js';
|
||||
export * from './runtime/random.js';
|
||||
export * from './runtime/routeTable.js';
|
||||
export * from './runtime/snapshot.js';
|
||||
export * from './runtime/speed.js';
|
||||
export * from './runtime/trace.js';
|
||||
export * from './util/equal.js';
|
||||
@@ -0,0 +1,102 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3):
|
||||
// ios/FiliusPad/TopologyEditor/Model/TopologyNode.swift
|
||||
// Java counterpart: filius.hardware.knoten.* (port counts per device kind).
|
||||
|
||||
import type { Id } from '../ids.js';
|
||||
|
||||
export type NodeKind =
|
||||
| 'pc'
|
||||
| 'notebook'
|
||||
| 'networkSwitch'
|
||||
| 'router'
|
||||
| 'gateway'
|
||||
| 'remoteLink'
|
||||
| 'unsupported';
|
||||
|
||||
export function isPcClassEndpoint(kind: NodeKind): boolean {
|
||||
return kind === 'pc' || kind === 'notebook';
|
||||
}
|
||||
|
||||
export type HostLabelPolicy = 'manual' | 'ipAddress' | 'macAddress' | 'ipAndMAC';
|
||||
|
||||
export interface PortMetadata {
|
||||
readonly id: Id;
|
||||
label: string;
|
||||
isOccupied: boolean;
|
||||
/** Canonical (upper case, colon separated) or undefined. */
|
||||
readonly importedMacAddress?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The MAC address of a port nobody gave one: `02:` followed by the last ten
|
||||
* hex digits of the port's UUID — stable across saves, locally administered.
|
||||
*/
|
||||
export function stableGeneratedMacAddress(portId: Id): string {
|
||||
const compact = portId.toUpperCase().replaceAll('-', '');
|
||||
const suffix = compact.slice(-10);
|
||||
const octets = ['02'];
|
||||
for (let offset = 0; offset < suffix.length; offset += 2) {
|
||||
octets.push(suffix.slice(offset, offset + 2).toUpperCase());
|
||||
}
|
||||
return octets.join(':');
|
||||
}
|
||||
|
||||
/** Six colon-separated pairs of hex digits, upper-cased; anything else is undefined. */
|
||||
export function canonicalMacAddress(value: string | undefined | null): string | undefined {
|
||||
if (value === undefined || value === null) return undefined;
|
||||
const segments = value.trim().split(':');
|
||||
if (segments.length !== 6) return undefined;
|
||||
if (!segments.every((segment) => /^[0-9A-Fa-f]{2}$/.test(segment))) return undefined;
|
||||
return segments.map((segment) => segment.toUpperCase()).join(':');
|
||||
}
|
||||
|
||||
export function effectiveMacAddress(port: PortMetadata): string {
|
||||
return port.importedMacAddress ?? stableGeneratedMacAddress(port.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* The name a new device gets. These are the Java FILIUS device names; the
|
||||
* editor shows them translated (packages/editor i18n), the model keeps them
|
||||
* as they appear in a Java .fls file.
|
||||
*/
|
||||
export function defaultDisplayName(kind: NodeKind): string {
|
||||
switch (kind) {
|
||||
case 'pc':
|
||||
return 'Rechner';
|
||||
case 'notebook':
|
||||
return 'Notebook';
|
||||
case 'networkSwitch':
|
||||
return 'Switch';
|
||||
case 'router':
|
||||
return 'Vermittlungsrechner';
|
||||
case 'gateway':
|
||||
return 'Gateway';
|
||||
case 'remoteLink':
|
||||
return 'Remote Link';
|
||||
case 'unsupported':
|
||||
return 'Unbekanntes Gerät';
|
||||
}
|
||||
}
|
||||
|
||||
/** Labels of the ports a new device of this kind has, in order. */
|
||||
export function defaultPortLabels(kind: NodeKind): string[] {
|
||||
switch (kind) {
|
||||
case 'pc':
|
||||
case 'notebook':
|
||||
return ['eth0'];
|
||||
case 'networkSwitch':
|
||||
// Java Switch constructs exactly 24 physical ports.
|
||||
return Array.from({ length: 24 }, (_, index) => `sw${index + 1}`);
|
||||
case 'router':
|
||||
// Java Vermittlungsrechner starts with one configurable network interface.
|
||||
return ['rt1'];
|
||||
case 'gateway':
|
||||
// Java Gateway has fixed WAN (index 0) and LAN (index 1) interfaces.
|
||||
return ['wan0', 'lan0'];
|
||||
case 'remoteLink':
|
||||
// One local physical attachment, matching the Java Modem.
|
||||
return ['remote0'];
|
||||
case 'unsupported':
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3):
|
||||
// State/TopologyEditorState.swift (runtime configuration value types)
|
||||
|
||||
import type { Id } from '../ids.js';
|
||||
import { maskAddress, parseIPv4 } from './ipv4.js';
|
||||
|
||||
/** The IP settings of a PC or notebook (its single interface) — and a router's gateway. */
|
||||
export interface DeviceConfiguration {
|
||||
readonly ipAddress: string;
|
||||
readonly subnetMask: string;
|
||||
readonly defaultGateway: string;
|
||||
readonly dnsServer: string;
|
||||
}
|
||||
|
||||
export function deviceConfiguration(
|
||||
ipAddress: string,
|
||||
subnetMask: string,
|
||||
defaultGateway = '',
|
||||
dnsServer = '',
|
||||
): DeviceConfiguration {
|
||||
return { ipAddress, subnetMask, defaultGateway, dnsServer };
|
||||
}
|
||||
|
||||
/** One interface of a router or gateway. */
|
||||
export interface InterfaceConfiguration {
|
||||
readonly ipAddress: string;
|
||||
readonly subnetMask: string;
|
||||
}
|
||||
|
||||
/** Map key for an interface: node and port. */
|
||||
export type InterfaceKey = string;
|
||||
|
||||
export function interfaceKey(nodeId: Id, portId: Id): InterfaceKey {
|
||||
return `${nodeId}/${portId}`;
|
||||
}
|
||||
|
||||
/** A row of the manual routing table (Java `Weiterleitungstabelle`). */
|
||||
export interface ManualRoute {
|
||||
readonly destinationNetwork: string;
|
||||
readonly subnetMask: string;
|
||||
readonly gateway: string;
|
||||
readonly interfaceIPAddress: string;
|
||||
}
|
||||
|
||||
/** Longest numeric mask wins; on a tie the first row stays. */
|
||||
export function bestMatchingManualRoute(
|
||||
targetIPAddress: string,
|
||||
routes: readonly ManualRoute[],
|
||||
): ManualRoute | undefined {
|
||||
const target = parseIPv4(targetIPAddress);
|
||||
if (target === undefined) return undefined;
|
||||
let best: ManualRoute | undefined;
|
||||
let bestMask: number | undefined;
|
||||
for (const route of routes) {
|
||||
const destination = parseIPv4(route.destinationNetwork);
|
||||
const mask = parseIPv4(route.subnetMask);
|
||||
if (destination === undefined || mask === undefined) continue;
|
||||
if (destination !== maskAddress(target, mask)) continue;
|
||||
if (bestMask !== undefined && mask <= bestMask) continue;
|
||||
bestMask = mask;
|
||||
best = route;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
export interface SwitchConfiguration {
|
||||
readonly ssid: string;
|
||||
readonly retentionTimeMilliseconds: number;
|
||||
}
|
||||
|
||||
/** Java SwitchFirmware keeps a learned MAC address for five minutes. */
|
||||
export const DEFAULT_SWITCH_RETENTION_MILLISECONDS = 300_000;
|
||||
|
||||
export function switchConfiguration(
|
||||
ssid: string,
|
||||
retentionTimeMilliseconds = DEFAULT_SWITCH_RETENTION_MILLISECONDS,
|
||||
): SwitchConfiguration {
|
||||
return { ssid, retentionTimeMilliseconds };
|
||||
}
|
||||
|
||||
/** The first six hex digits of the node's UUID, lower case. */
|
||||
export function defaultSwitchConfiguration(nodeId: Id): SwitchConfiguration {
|
||||
const compact = nodeId.replaceAll('-', '').toLowerCase();
|
||||
return switchConfiguration(compact.slice(0, 6));
|
||||
}
|
||||
|
||||
// ── Firewall (Java filius.software.firewall.Firewall, FirewallRule) ─────────
|
||||
|
||||
export const FIREWALL_PROTOCOL = { all: -1, icmp: 1, tcp: 6, udp: 17 } as const;
|
||||
export type FirewallProtocol = keyof typeof FIREWALL_PROTOCOL;
|
||||
|
||||
export type FirewallAction = 'drop' | 'accept';
|
||||
|
||||
/** Java writes this as the source of a rule that means "any directly connected network". */
|
||||
export const DIRECTLY_CONNECTED_SOURCE_MARKER = '999.999.999.999';
|
||||
export const ALL_PORTS = -1;
|
||||
|
||||
export interface FirewallRule {
|
||||
readonly sourceIPAddress: string;
|
||||
readonly sourceSubnetMask: string;
|
||||
readonly destinationIPAddress: string;
|
||||
readonly destinationSubnetMask: string;
|
||||
/** A port number or ALL_PORTS. */
|
||||
readonly port: number;
|
||||
readonly protocol: FirewallProtocol;
|
||||
readonly action: FirewallAction;
|
||||
}
|
||||
|
||||
export function firewallRule(fields: Partial<FirewallRule> = {}): FirewallRule {
|
||||
return {
|
||||
sourceIPAddress: fields.sourceIPAddress ?? '',
|
||||
sourceSubnetMask: fields.sourceSubnetMask ?? '',
|
||||
destinationIPAddress: fields.destinationIPAddress ?? '',
|
||||
destinationSubnetMask: fields.destinationSubnetMask ?? '',
|
||||
port: fields.port ?? ALL_PORTS,
|
||||
protocol: fields.protocol ?? 'tcp',
|
||||
action: fields.action ?? 'drop',
|
||||
};
|
||||
}
|
||||
|
||||
export interface FirewallConfiguration {
|
||||
readonly isActive: boolean;
|
||||
readonly defaultPolicy: FirewallAction;
|
||||
readonly dropIcmp: boolean;
|
||||
readonly filterSynSegmentsOnly: boolean;
|
||||
readonly filterUdp: boolean;
|
||||
readonly rules: readonly FirewallRule[];
|
||||
}
|
||||
|
||||
/** What a router or gateway has without a firewall configured: inactive. */
|
||||
export function firewallConfiguration(fields: Partial<FirewallConfiguration> = {}): FirewallConfiguration {
|
||||
return {
|
||||
isActive: fields.isActive ?? false,
|
||||
defaultPolicy: fields.defaultPolicy ?? 'drop',
|
||||
dropIcmp: fields.dropIcmp ?? false,
|
||||
filterSynSegmentsOnly: fields.filterSynSegmentsOnly ?? true,
|
||||
filterUdp: fields.filterUdp ?? true,
|
||||
rules: fields.rules ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
/** What Java installs as the personal firewall of a PC: active, drop by default. */
|
||||
export const JAVA_PERSONAL_FIREWALL_DEFAULTS: FirewallConfiguration = firewallConfiguration({
|
||||
isActive: true,
|
||||
defaultPolicy: 'drop',
|
||||
dropIcmp: false,
|
||||
filterSynSegmentsOnly: true,
|
||||
filterUdp: true,
|
||||
rules: [],
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,48 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3):
|
||||
// State/TopologyNetworkRuntimeEngine.swift (parseIPv4, sameSubnet)
|
||||
// State/TopologyEditorState.swift (TopologyRuntimeManualRoute.parseIPv4)
|
||||
//
|
||||
// Two parsers exist on purpose, as in the Swift source: the runtime reads an
|
||||
// octet the way Swift's `UInt8(String)` does, the route editor the way Java
|
||||
// FILIUS validates its table cells (see routeTable.ts).
|
||||
|
||||
/**
|
||||
* Swift `UInt8(segment)`: an optional sign, then decimal digits, value 0…255.
|
||||
* Leading zeros are allowed ("007" is 7), whitespace is not.
|
||||
*/
|
||||
function parseSwiftOctet(segment: string): number | undefined {
|
||||
if (!/^[+-]?[0-9]+$/.test(segment)) return undefined;
|
||||
const value = Number(segment);
|
||||
if (!Number.isInteger(value) || value < 0 || value > 255) return undefined;
|
||||
return Object.is(value, -0) ? 0 : value;
|
||||
}
|
||||
|
||||
/** Dotted quad to an unsigned 32-bit number, or undefined. */
|
||||
export function parseIPv4(value: string): number | undefined {
|
||||
const segments = value.split('.');
|
||||
if (segments.length !== 4) return undefined;
|
||||
let address = 0;
|
||||
for (const segment of segments) {
|
||||
const octet = parseSwiftOctet(segment);
|
||||
if (octet === undefined) return undefined;
|
||||
address = ((address << 8) | octet) >>> 0;
|
||||
}
|
||||
return address;
|
||||
}
|
||||
|
||||
export function formatIPv4(address: number): string {
|
||||
return [24, 16, 8, 0].map((shift) => String((address >>> shift) & 0xff)).join('.');
|
||||
}
|
||||
|
||||
export function sameSubnet(lhs: string, rhs: string, mask: string): boolean {
|
||||
const left = parseIPv4(lhs);
|
||||
const right = parseIPv4(rhs);
|
||||
const netmask = parseIPv4(mask);
|
||||
if (left === undefined || right === undefined || netmask === undefined) return false;
|
||||
return ((left & netmask) >>> 0) === ((right & netmask) >>> 0);
|
||||
}
|
||||
|
||||
/** `address & mask` as an unsigned number. */
|
||||
export function maskAddress(address: number, mask: number): number {
|
||||
return (address & mask) >>> 0;
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3):
|
||||
// State/TopologyNetworkRuntimeEngine.swift ("Java-observable packet and route models")
|
||||
// Frames and packets are typed values, not bytes — what the Java packet viewer
|
||||
// shows, not what a real wire would carry.
|
||||
|
||||
export interface EthernetFrame {
|
||||
readonly identity: number;
|
||||
readonly sourceMacAddress: string;
|
||||
readonly destinationMacAddress: string;
|
||||
readonly payload: EthernetPayload;
|
||||
}
|
||||
|
||||
export type EthernetPayload =
|
||||
| { readonly kind: 'arp'; readonly packet: ArpPacket }
|
||||
| { readonly kind: 'ipv4'; readonly packet: IPv4Packet };
|
||||
|
||||
export type ArpOperation = 'request' | 'reply';
|
||||
|
||||
export interface ArpPacket {
|
||||
readonly operation: ArpOperation;
|
||||
readonly senderMacAddress: string;
|
||||
readonly senderIPAddress: string;
|
||||
readonly targetMacAddress: string;
|
||||
readonly targetIPAddress: string;
|
||||
}
|
||||
|
||||
export const IPV4_PROTOCOL = { icmp: 1, tcp: 6, udp: 17 } as const;
|
||||
export type IPv4Protocol = keyof typeof IPV4_PROTOCOL;
|
||||
|
||||
export interface IPv4Packet {
|
||||
readonly identity: number;
|
||||
readonly senderIPAddress: string;
|
||||
readonly receiverIPAddress: string;
|
||||
/** 0…255 */
|
||||
readonly timeToLive: number;
|
||||
readonly protocol: IPv4Protocol;
|
||||
readonly payload: IPv4Payload;
|
||||
}
|
||||
|
||||
export type IPv4Payload =
|
||||
| { readonly kind: 'icmp'; readonly message: IcmpMessage }
|
||||
| { readonly kind: 'tcp'; readonly segment: TcpSegment }
|
||||
| { readonly kind: 'udp'; readonly datagram: UdpDatagram };
|
||||
|
||||
/** The same packet one hop further: identity kept, TTL lowered, never below 0. */
|
||||
export function forwardingClone(packet: IPv4Packet, decrementingTtlBy = 1): IPv4Packet {
|
||||
return {
|
||||
...packet,
|
||||
timeToLive: decrementingTtlBy >= packet.timeToLive ? 0 : packet.timeToLive - decrementingTtlBy,
|
||||
};
|
||||
}
|
||||
|
||||
export type IcmpMessageKind =
|
||||
| 'echoRequest'
|
||||
| 'echoReply'
|
||||
| 'destinationNetworkUnreachable'
|
||||
| 'destinationHostUnreachable'
|
||||
| 'timeExceeded';
|
||||
|
||||
export interface IcmpMessage {
|
||||
readonly kind: IcmpMessageKind;
|
||||
/** 0…65535 */
|
||||
readonly identifier: number;
|
||||
/** 0…65535 */
|
||||
readonly sequenceNumber: number;
|
||||
readonly data: Uint8Array;
|
||||
readonly embeddedOriginalPacket?: IPv4Packet;
|
||||
}
|
||||
|
||||
export function icmpMessage(
|
||||
kind: IcmpMessageKind,
|
||||
fields: Partial<Omit<IcmpMessage, 'kind'>> = {},
|
||||
): IcmpMessage {
|
||||
const message: IcmpMessage = {
|
||||
kind,
|
||||
identifier: fields.identifier ?? 0,
|
||||
sequenceNumber: fields.sequenceNumber ?? 0,
|
||||
data: fields.data ?? new Uint8Array(),
|
||||
};
|
||||
return fields.embeddedOriginalPacket === undefined
|
||||
? message
|
||||
: { ...message, embeddedOriginalPacket: fields.embeddedOriginalPacket };
|
||||
}
|
||||
|
||||
export const TCP_FLAG = {
|
||||
finish: 1 << 0,
|
||||
synchronize: 1 << 1,
|
||||
reset: 1 << 2,
|
||||
push: 1 << 3,
|
||||
acknowledgement: 1 << 4,
|
||||
} as const;
|
||||
|
||||
export type TcpSocketState =
|
||||
| 'CLOSED'
|
||||
| 'LISTEN'
|
||||
| 'SYN_RCVD'
|
||||
| 'SYN_SENT'
|
||||
| 'ESTABLISHED'
|
||||
| 'CLOSE_WAIT'
|
||||
| 'LAST_ACK'
|
||||
| 'FIN_WAIT_1'
|
||||
| 'FIN_WAIT_2'
|
||||
| 'CLOSING'
|
||||
| 'TIME_WAIT';
|
||||
|
||||
export interface TcpSegment {
|
||||
readonly sourcePort: number;
|
||||
readonly destinationPort: number;
|
||||
readonly sequenceNumber: number;
|
||||
readonly acknowledgementNumber: number;
|
||||
/** Bit set of TCP_FLAG values. */
|
||||
readonly flags: number;
|
||||
readonly payload: Uint8Array;
|
||||
}
|
||||
|
||||
export interface UdpDatagram {
|
||||
readonly sourcePort: number;
|
||||
readonly destinationPort: number;
|
||||
readonly payload: Uint8Array;
|
||||
}
|
||||
|
||||
export function packetIdentityInFrame(frame: EthernetFrame): number | undefined {
|
||||
return frame.payload.kind === 'ipv4' ? frame.payload.packet.identity : undefined;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3):
|
||||
// State/TopologyNetworkRuntimeEngine.swift (TopologyJavaCompatibleRandom)
|
||||
// A bit-exact java.util.Random: the 48-bit linear congruential generator
|
||||
// Java FILIUS draws its RIP beacon jitter and ephemeral ports from. BigInt
|
||||
// keeps the 48-bit arithmetic exact; a double would lose the low bits.
|
||||
|
||||
const MULTIPLIER = 0x5deece66dn;
|
||||
const ADDEND = 0xbn;
|
||||
const MASK = (1n << 48n) - 1n;
|
||||
const INT32_MAX = 2147483647n;
|
||||
|
||||
export class JavaCompatibleRandom {
|
||||
private state: bigint;
|
||||
|
||||
constructor(seed: bigint | number) {
|
||||
this.state = (BigInt.asUintN(64, BigInt(seed)) ^ MULTIPLIER) & MASK;
|
||||
}
|
||||
|
||||
/** The internal 48-bit state, for tests and for copying a generator. */
|
||||
get seed(): bigint {
|
||||
return this.state;
|
||||
}
|
||||
|
||||
clone(): JavaCompatibleRandom {
|
||||
const copy = new JavaCompatibleRandom(0);
|
||||
copy.state = this.state;
|
||||
return copy;
|
||||
}
|
||||
|
||||
next(bits: number): number {
|
||||
if (!(bits > 0 && bits <= 32)) throw new RangeError(`bits out of range: ${bits}`);
|
||||
this.state = (this.state * MULTIPLIER + ADDEND) & MASK;
|
||||
return Number(this.state >> BigInt(48 - bits));
|
||||
}
|
||||
|
||||
nextInt(upperBound: number): number {
|
||||
if (!(upperBound > 0)) throw new RangeError(`upperBound must be positive: ${upperBound}`);
|
||||
const bound = BigInt(upperBound);
|
||||
if ((upperBound & -upperBound) === upperBound) {
|
||||
return Number((bound * BigInt(this.next(31))) >> 31n);
|
||||
}
|
||||
for (;;) {
|
||||
const bits = BigInt(this.next(31));
|
||||
const value = bits % bound;
|
||||
if (bits - value + (bound - 1n) <= INT32_MAX) return Number(value);
|
||||
}
|
||||
}
|
||||
|
||||
nextFloat(): number {
|
||||
return Math.fround(this.next(24) / (1 << 24));
|
||||
}
|
||||
|
||||
/** Java RIP: 30 s · (f/3 + 0.84), truncated — somewhere between 25.2 s and 35.2 s. */
|
||||
nextRipJitterMilliseconds(): number {
|
||||
const javaFloat = this.nextFloat();
|
||||
return Math.trunc(30_000.0 * (javaFloat / 3.0 + 0.84));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3):
|
||||
// State/TopologyJavaRouteTable.swift (row projection, validation, drafts)
|
||||
// Java counterpart: filius.software.vermittlungsschicht.Weiterleitungstabelle
|
||||
// (holeTabelle: the order of the generated rows).
|
||||
// The Swift file also carries table geometry for SwiftUI; that belongs to the
|
||||
// editor and is not ported here.
|
||||
|
||||
import { formatIPv4, maskAddress } from './ipv4.js';
|
||||
import type { InterfaceConfiguration, ManualRoute } from './config.js';
|
||||
|
||||
export type RouteOrigin = 'localHost' | 'connected' | 'localhost' | 'manual' | 'defaultGateway' | 'rip';
|
||||
|
||||
export interface RouteRow {
|
||||
readonly destinationNetwork: string;
|
||||
readonly subnetMask: string;
|
||||
readonly nextHop: string;
|
||||
readonly interfaceIPAddress: string;
|
||||
readonly origin: RouteOrigin;
|
||||
readonly isEditable: boolean;
|
||||
readonly metric?: number;
|
||||
readonly expiresAtMilliseconds?: number;
|
||||
}
|
||||
|
||||
export type RouteTableColumn = 'destination' | 'subnetMask' | 'nextGateway' | 'interface';
|
||||
|
||||
/**
|
||||
* A Java table octet: digits only, leading zeros allowed, at most three
|
||||
* significant digits, 0…255 ("001" is valid, " 1" and "+1" are not).
|
||||
*/
|
||||
function parseJavaOctet(segment: string): number | undefined {
|
||||
if (segment.length === 0 || !/^[0-9]+$/.test(segment)) return undefined;
|
||||
const significant = segment.replace(/^0+/, '');
|
||||
if (significant.length === 0) return 0;
|
||||
if (significant.length > 3) return undefined;
|
||||
const value = Number(significant);
|
||||
return value <= 255 ? value : undefined;
|
||||
}
|
||||
|
||||
function parseJavaIPv4(value: string): number | undefined {
|
||||
const segments = value.split('.');
|
||||
if (segments.length !== 4) return undefined;
|
||||
let address = 0;
|
||||
for (const segment of segments) {
|
||||
const octet = parseJavaOctet(segment);
|
||||
if (octet === undefined) return undefined;
|
||||
address = ((address << 8) | octet) >>> 0;
|
||||
}
|
||||
return address;
|
||||
}
|
||||
|
||||
export function isValidJavaIPAddress(value: string): boolean {
|
||||
return parseJavaIPv4(value) !== undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* FILIUS uses `musterSubNetz`, a dotted-decimal syntax check. It deliberately
|
||||
* accepts non-contiguous masks in the route editor.
|
||||
*/
|
||||
export function isValidJavaSubnetMask(value: string): boolean {
|
||||
return parseJavaIPv4(value) !== undefined;
|
||||
}
|
||||
|
||||
export function isValidRouteCell(value: string, column: RouteTableColumn): boolean {
|
||||
return column === 'subnetMask' ? isValidJavaSubnetMask(value) : isValidJavaIPAddress(value);
|
||||
}
|
||||
|
||||
function sameNetwork(lhs: string, rhs: string, mask: string): boolean {
|
||||
const left = parseJavaIPv4(lhs);
|
||||
const right = parseJavaIPv4(rhs);
|
||||
const netmask = parseJavaIPv4(mask);
|
||||
if (left === undefined || right === undefined || netmask === undefined) return false;
|
||||
return maskAddress(left, netmask) === maskAddress(right, netmask);
|
||||
}
|
||||
|
||||
function networkAddress(ipAddress: string, subnetMask: string): string | undefined {
|
||||
const address = parseJavaIPv4(ipAddress);
|
||||
const mask = parseJavaIPv4(subnetMask);
|
||||
if (address === undefined || mask === undefined) return undefined;
|
||||
return formatIPv4(maskAddress(address, mask));
|
||||
}
|
||||
|
||||
/**
|
||||
* The static table as Java shows it: the interfaces' own addresses (newest
|
||||
* first), their networks, loopback, the manual rows, then the default route.
|
||||
*/
|
||||
export function routeTableRows(
|
||||
interfaceConfigurations: readonly InterfaceConfiguration[],
|
||||
manualRoutes: readonly ManualRoute[],
|
||||
defaultGateway: string | undefined,
|
||||
): RouteRow[] {
|
||||
const validInterfaces = interfaceConfigurations.filter(
|
||||
(configuration) =>
|
||||
parseJavaIPv4(configuration.ipAddress) !== undefined &&
|
||||
parseJavaIPv4(configuration.subnetMask) !== undefined,
|
||||
);
|
||||
|
||||
const result: RouteRow[] = manualRoutes.map((route) => ({
|
||||
destinationNetwork: route.destinationNetwork,
|
||||
subnetMask: route.subnetMask,
|
||||
nextHop: route.gateway,
|
||||
interfaceIPAddress: route.interfaceIPAddress,
|
||||
origin: 'manual',
|
||||
isEditable: true,
|
||||
}));
|
||||
|
||||
result.unshift({
|
||||
destinationNetwork: '127.0.0.0',
|
||||
subnetMask: '255.0.0.0',
|
||||
nextHop: '127.0.0.1',
|
||||
interfaceIPAddress: '127.0.0.1',
|
||||
origin: 'localhost',
|
||||
isEditable: false,
|
||||
});
|
||||
|
||||
for (const configuration of validInterfaces) {
|
||||
const network = networkAddress(configuration.ipAddress, configuration.subnetMask);
|
||||
if (network === undefined) continue;
|
||||
result.unshift({
|
||||
destinationNetwork: network,
|
||||
subnetMask: configuration.subnetMask,
|
||||
nextHop: configuration.ipAddress,
|
||||
interfaceIPAddress: configuration.ipAddress,
|
||||
origin: 'connected',
|
||||
isEditable: false,
|
||||
});
|
||||
}
|
||||
|
||||
for (const configuration of validInterfaces) {
|
||||
result.unshift({
|
||||
destinationNetwork: configuration.ipAddress,
|
||||
subnetMask: '255.255.255.255',
|
||||
nextHop: '127.0.0.1',
|
||||
interfaceIPAddress: '127.0.0.1',
|
||||
origin: 'localHost',
|
||||
isEditable: false,
|
||||
});
|
||||
}
|
||||
|
||||
const trimmedGateway = defaultGateway?.trim() ?? '';
|
||||
const primaryInterface = validInterfaces[0];
|
||||
if (parseJavaIPv4(trimmedGateway) !== undefined && primaryInterface !== undefined) {
|
||||
let selectedInterface = primaryInterface.ipAddress;
|
||||
for (const configuration of validInterfaces) {
|
||||
if (sameNetwork(trimmedGateway, configuration.ipAddress, configuration.subnetMask)) {
|
||||
selectedInterface = configuration.ipAddress;
|
||||
}
|
||||
}
|
||||
result.push({
|
||||
destinationNetwork: '0.0.0.0',
|
||||
subnetMask: '0.0.0.0',
|
||||
nextHop: trimmedGateway,
|
||||
interfaceIPAddress: selectedInterface,
|
||||
origin: 'defaultGateway',
|
||||
isEditable: false,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function visibleRouteRows(rows: readonly RouteRow[], showAllEntries: boolean): RouteRow[] {
|
||||
return showAllEntries ? [...rows] : rows.filter((row) => row.isEditable);
|
||||
}
|
||||
|
||||
/** One row being edited in the route editor. */
|
||||
export interface RouteDraft {
|
||||
readonly id: string;
|
||||
destinationNetwork: string;
|
||||
subnetMask: string;
|
||||
nextGateway: string;
|
||||
interfaceIPAddress: string;
|
||||
isPendingInsertion: boolean;
|
||||
}
|
||||
|
||||
export function blankRouteDraft(id: string): RouteDraft {
|
||||
return {
|
||||
id,
|
||||
destinationNetwork: '',
|
||||
subnetMask: '',
|
||||
nextGateway: '',
|
||||
interfaceIPAddress: '',
|
||||
isPendingInsertion: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function routeDraftFromRoute(id: string, route: ManualRoute): RouteDraft {
|
||||
return {
|
||||
id,
|
||||
destinationNetwork: route.destinationNetwork,
|
||||
subnetMask: route.subnetMask,
|
||||
nextGateway: route.gateway,
|
||||
interfaceIPAddress: route.interfaceIPAddress,
|
||||
isPendingInsertion: false,
|
||||
};
|
||||
}
|
||||
|
||||
/** The route a draft stands for — only once all four cells are valid. */
|
||||
export function manualRouteFromDraft(draft: RouteDraft): ManualRoute | undefined {
|
||||
if (
|
||||
!isValidRouteCell(draft.destinationNetwork, 'destination') ||
|
||||
!isValidRouteCell(draft.subnetMask, 'subnetMask') ||
|
||||
!isValidRouteCell(draft.nextGateway, 'nextGateway') ||
|
||||
!isValidRouteCell(draft.interfaceIPAddress, 'interface')
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
destinationNetwork: draft.destinationNetwork,
|
||||
subnetMask: draft.subnetMask,
|
||||
gateway: draft.nextGateway,
|
||||
interfaceIPAddress: draft.interfaceIPAddress,
|
||||
};
|
||||
}
|
||||
|
||||
/** At most one blank row waits at the end of the editor. */
|
||||
export function appendingBlankDraftIfNeeded(
|
||||
drafts: readonly RouteDraft[],
|
||||
newId: () => string,
|
||||
): RouteDraft[] {
|
||||
if (drafts.some((draft) => draft.isPendingInsertion)) return [...drafts];
|
||||
return [...drafts, blankRouteDraft(newId())];
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3):
|
||||
// State/TopologyNetworkRuntimeEngine.swift (TopologyNetworkRuntimeTopologySnapshot)
|
||||
// What the runtime starts from: the topology and every configuration, frozen
|
||||
// at the moment the simulation starts. Later protocol slices add their
|
||||
// configuration maps here (DHCP, NAT, remote link, wireless).
|
||||
|
||||
import { compareIds, type Id } from '../ids.js';
|
||||
import type { NodeKind } from '../model/node.js';
|
||||
import { canonicalMacAddress } from '../model/node.js';
|
||||
import type {
|
||||
DeviceConfiguration,
|
||||
FirewallConfiguration,
|
||||
InterfaceConfiguration,
|
||||
InterfaceKey,
|
||||
ManualRoute,
|
||||
SwitchConfiguration,
|
||||
} from './config.js';
|
||||
|
||||
export interface PortSnapshot {
|
||||
readonly id: Id;
|
||||
readonly label: string;
|
||||
/** Canonical, or undefined for a port whose MAC address is derived from its id. */
|
||||
readonly macAddress?: string;
|
||||
}
|
||||
|
||||
export function portSnapshot(id: Id, label: string, macAddress?: string): PortSnapshot {
|
||||
const canonical = canonicalMacAddress(macAddress);
|
||||
return canonical === undefined ? { id, label } : { id, label, macAddress: canonical };
|
||||
}
|
||||
|
||||
export interface NodeSnapshot {
|
||||
readonly id: Id;
|
||||
readonly kind: NodeKind;
|
||||
readonly ports: readonly PortSnapshot[];
|
||||
}
|
||||
|
||||
export interface LinkSnapshot {
|
||||
readonly id: Id;
|
||||
readonly sourceNodeId: Id;
|
||||
readonly sourcePortId: Id;
|
||||
readonly targetNodeId: Id;
|
||||
readonly targetPortId: Id;
|
||||
}
|
||||
|
||||
export interface TopologySnapshot {
|
||||
/** Sorted by id (Swift `uuidString` order). */
|
||||
readonly nodes: readonly NodeSnapshot[];
|
||||
/** Sorted by id (Swift `uuidString` order). */
|
||||
readonly links: readonly LinkSnapshot[];
|
||||
readonly deviceConfigurations: ReadonlyMap<Id, DeviceConfiguration>;
|
||||
readonly interfaceConfigurations: ReadonlyMap<InterfaceKey, InterfaceConfiguration>;
|
||||
readonly manualRoutesByNodeId: ReadonlyMap<Id, readonly ManualRoute[]>;
|
||||
readonly ripEnabledByNodeId: ReadonlyMap<Id, boolean>;
|
||||
readonly firewallConfigurationsByNodeId: ReadonlyMap<Id, FirewallConfiguration>;
|
||||
readonly switchConfigurationsByNodeId: ReadonlyMap<Id, SwitchConfiguration>;
|
||||
}
|
||||
|
||||
export interface TopologySnapshotInput {
|
||||
nodes: readonly NodeSnapshot[];
|
||||
links: readonly LinkSnapshot[];
|
||||
deviceConfigurations?: ReadonlyMap<Id, DeviceConfiguration>;
|
||||
interfaceConfigurations?: ReadonlyMap<InterfaceKey, InterfaceConfiguration>;
|
||||
manualRoutesByNodeId?: ReadonlyMap<Id, readonly ManualRoute[]>;
|
||||
ripEnabledByNodeId?: ReadonlyMap<Id, boolean>;
|
||||
firewallConfigurationsByNodeId?: ReadonlyMap<Id, FirewallConfiguration>;
|
||||
switchConfigurationsByNodeId?: ReadonlyMap<Id, SwitchConfiguration>;
|
||||
}
|
||||
|
||||
export function topologySnapshot(input: TopologySnapshotInput): TopologySnapshot {
|
||||
return {
|
||||
nodes: [...input.nodes].sort((lhs, rhs) => compareIds(lhs.id, rhs.id)),
|
||||
links: [...input.links].sort((lhs, rhs) => compareIds(lhs.id, rhs.id)),
|
||||
deviceConfigurations: input.deviceConfigurations ?? new Map(),
|
||||
interfaceConfigurations: input.interfaceConfigurations ?? new Map(),
|
||||
manualRoutesByNodeId: input.manualRoutesByNodeId ?? new Map(),
|
||||
ripEnabledByNodeId: input.ripEnabledByNodeId ?? new Map(),
|
||||
firewallConfigurationsByNodeId: input.firewallConfigurationsByNodeId ?? new Map(),
|
||||
switchConfigurationsByNodeId: input.switchConfigurationsByNodeId ?? new Map(),
|
||||
};
|
||||
}
|
||||
|
||||
/** The same snapshot with some fields replaced (Swift rebuilds it field by field). */
|
||||
export function withSnapshot(
|
||||
snapshot: TopologySnapshot,
|
||||
changes: Partial<TopologySnapshotInput>,
|
||||
): TopologySnapshot {
|
||||
return topologySnapshot({ ...snapshot, ...changes });
|
||||
}
|
||||
|
||||
export const EMPTY_TOPOLOGY_SNAPSHOT: TopologySnapshot = topologySnapshot({ nodes: [], links: [] });
|
||||
@@ -0,0 +1,33 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3):
|
||||
// State/TopologyNetworkRuntimeEngine.swift (TopologyNetworkRuntimeSpeed)
|
||||
// Java counterpart: filius.hardware.Verbindung (MIN_VERZOEGERUNG_IN_MILLIS,
|
||||
// verzoegerungsFaktor) and GUIMainMenu.updateLatency.
|
||||
|
||||
export const MINIMUM_SPEED_PERCENT = 1;
|
||||
export const MAXIMUM_SPEED_PERCENT = 100;
|
||||
export const DEFAULT_SPEED_PERCENT = 90;
|
||||
export const JAVA_MINIMUM_LINK_DELAY_MILLISECONDS = 5;
|
||||
|
||||
export class RuntimeSpeed {
|
||||
readonly percent: number;
|
||||
|
||||
constructor(percent: number = DEFAULT_SPEED_PERCENT) {
|
||||
this.percent = Math.min(MAXIMUM_SPEED_PERCENT, Math.max(MINIMUM_SPEED_PERCENT, Math.trunc(percent)));
|
||||
}
|
||||
|
||||
/** Java's delay factor: 1 at full speed, 100 at the slowest. */
|
||||
get javaDelayFactor(): number {
|
||||
return MAXIMUM_SPEED_PERCENT - this.percent + 1;
|
||||
}
|
||||
|
||||
/** How long a frame travels over one cable. */
|
||||
get linkTransmissionDelayMilliseconds(): number {
|
||||
return JAVA_MINIMUM_LINK_DELAY_MILLISECONDS * this.javaDelayFactor;
|
||||
}
|
||||
|
||||
/** A base delay scaled like a cable, or undefined past the safe integer range. */
|
||||
scaledLinkDelay(baseMilliseconds: number): number | undefined {
|
||||
const delay = baseMilliseconds * this.javaDelayFactor;
|
||||
return Number.isSafeInteger(delay) ? delay : undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// Ported from filius-ipad (GPLv2/GPLv3):
|
||||
// State/TopologyNetworkRuntimeEngine.swift (packet trace model)
|
||||
// Java counterpart: filius.rahmenprogramm.nachrichten.Lauscher — here every
|
||||
// step a frame or packet takes is one trace event; the packet viewer groups them.
|
||||
|
||||
import type { Id } from '../ids.js';
|
||||
|
||||
export type TraceDirection = 'inbound' | 'outbound' | 'local';
|
||||
|
||||
export type TraceLayer = 'application' | 'transport' | 'network' | 'dataLink' | 'physical';
|
||||
|
||||
export type TraceOperation =
|
||||
| 'created'
|
||||
| 'sent'
|
||||
| 'received'
|
||||
| 'forwarded'
|
||||
| 'accepted'
|
||||
| 'dropped'
|
||||
| 'rewritten'
|
||||
| 'retransmitted'
|
||||
| 'compatibilityAdapter';
|
||||
|
||||
export interface HeaderField {
|
||||
readonly name: string;
|
||||
readonly value: string;
|
||||
}
|
||||
|
||||
export interface TraceEvent {
|
||||
readonly id: number;
|
||||
readonly timeMilliseconds: number;
|
||||
readonly frameIdentity?: number;
|
||||
readonly packetIdentity?: number;
|
||||
readonly nodeId: Id;
|
||||
readonly interfaceId?: Id;
|
||||
readonly direction: TraceDirection;
|
||||
readonly layer: TraceLayer;
|
||||
readonly operation: TraceOperation;
|
||||
readonly beforeHeaders: readonly HeaderField[];
|
||||
readonly afterHeaders: readonly HeaderField[];
|
||||
readonly detail?: string;
|
||||
}
|
||||
|
||||
/** How many trace events the runtime keeps, and how many it drops at once when full. */
|
||||
export interface TraceRetentionPolicy {
|
||||
readonly maximumEventCount: number;
|
||||
readonly evictionBatchSize: number;
|
||||
}
|
||||
|
||||
export function traceRetentionPolicy(maximumEventCount: number, evictionBatchSize: number): TraceRetentionPolicy {
|
||||
if (!(maximumEventCount > 0)) throw new RangeError('Packet-trace retention must keep at least one event');
|
||||
if (!(evictionBatchSize > 0)) throw new RangeError('Packet-trace eviction must remove at least one event');
|
||||
if (evictionBatchSize > maximumEventCount) {
|
||||
throw new RangeError('Packet-trace eviction cannot exceed the retention limit');
|
||||
}
|
||||
return { maximumEventCount, evictionBatchSize };
|
||||
}
|
||||
|
||||
export const PRODUCTION_TRACE_RETENTION = traceRetentionPolicy(10_000, 1_000);
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Structural equality for the runtime's value types — what Swift's synthesized
|
||||
* `Equatable` gives a struct or enum for free. Handles plain objects, arrays,
|
||||
* `Uint8Array`, `Map` and `Set`; everything else is compared with `Object.is`.
|
||||
*/
|
||||
export function deepEqual(lhs: unknown, rhs: unknown): boolean {
|
||||
if (Object.is(lhs, rhs)) return true;
|
||||
if (typeof lhs !== 'object' || typeof rhs !== 'object' || lhs === null || rhs === null) {
|
||||
return false;
|
||||
}
|
||||
if (lhs instanceof Uint8Array || rhs instanceof Uint8Array) {
|
||||
if (!(lhs instanceof Uint8Array && rhs instanceof Uint8Array)) return false;
|
||||
return lhs.length === rhs.length && lhs.every((byte, index) => byte === rhs[index]);
|
||||
}
|
||||
if (Array.isArray(lhs) || Array.isArray(rhs)) {
|
||||
if (!(Array.isArray(lhs) && Array.isArray(rhs)) || lhs.length !== rhs.length) return false;
|
||||
return lhs.every((item, index) => deepEqual(item, rhs[index]));
|
||||
}
|
||||
if (lhs instanceof Map || rhs instanceof Map) {
|
||||
if (!(lhs instanceof Map && rhs instanceof Map) || lhs.size !== rhs.size) return false;
|
||||
for (const [key, value] of lhs) {
|
||||
if (!rhs.has(key) || !deepEqual(value, rhs.get(key))) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (lhs instanceof Set || rhs instanceof Set) {
|
||||
if (!(lhs instanceof Set && rhs instanceof Set) || lhs.size !== rhs.size) return false;
|
||||
for (const value of lhs) if (!rhs.has(value)) return false;
|
||||
return true;
|
||||
}
|
||||
const leftKeys = Object.keys(lhs).filter((key) => (lhs as Record<string, unknown>)[key] !== undefined);
|
||||
const rightKeys = Object.keys(rhs).filter((key) => (rhs as Record<string, unknown>)[key] !== undefined);
|
||||
if (leftKeys.length !== rightKeys.length) return false;
|
||||
return leftKeys.every((key) =>
|
||||
deepEqual((lhs as Record<string, unknown>)[key], (rhs as Record<string, unknown>)[key]),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,631 @@
|
||||
// Ported from filius-ipad ios/FiliusPadTests/TopologyNetworkRuntimeEngineTests.swift:
|
||||
// the event queue, the virtual clock, Java-compatible randomness, restart,
|
||||
// Ethernet/switch/ARP/IPv4/ICMP, routing errors, the firewall, packet loss
|
||||
// and trace retention. The remaining Swift tests (UDP, TCP, DHCP, DNS, RIP,
|
||||
// NAT, remote link, packet viewer) follow with their protocol slices.
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
EMPTY_TOPOLOGY_SNAPSHOT,
|
||||
ETHERNET_BROADCAST_MAC_ADDRESS,
|
||||
firewallConfiguration,
|
||||
firewallRule,
|
||||
DIRECTLY_CONNECTED_SOURCE_MARKER,
|
||||
forwardingClone,
|
||||
icmpMessage,
|
||||
interfaceKey,
|
||||
JavaCompatibleRandom,
|
||||
NetworkRuntimeEngine,
|
||||
portSnapshot,
|
||||
stableMacAddress,
|
||||
switchConfiguration,
|
||||
TCP_FLAG,
|
||||
topologySnapshot,
|
||||
traceRetentionPolicy,
|
||||
UNSPECIFIED_MAC_ADDRESS,
|
||||
type EthernetFrame,
|
||||
type EthernetPayload,
|
||||
type FirewallConfiguration,
|
||||
type IPv4Packet,
|
||||
type NodeSnapshot,
|
||||
type RuntimeOutput,
|
||||
type ScheduledEventKind,
|
||||
} from '../src/index.js';
|
||||
import { device, link, pc, startedEngine, uuid } from './fixtures.js';
|
||||
|
||||
const marker = (label: string): ScheduledEventKind => ({ kind: 'parityMarker', label });
|
||||
|
||||
function firedKinds(outputs: RuntimeOutput[]): ScheduledEventKind[] {
|
||||
return outputs.flatMap((output) => (output.kind.type === 'fired' ? [output.kind.event.kind] : []));
|
||||
}
|
||||
|
||||
function routedTopology() {
|
||||
const sourceNodeId = uuid(0x1451);
|
||||
const sourcePortId = uuid(0x1461);
|
||||
const routerNodeId = uuid(0x1452);
|
||||
const routerPortA = uuid(0x1462);
|
||||
const routerPortB = uuid(0x1463);
|
||||
const targetNodeId = uuid(0x1453);
|
||||
const targetPortId = uuid(0x1464);
|
||||
const router: NodeSnapshot = {
|
||||
id: routerNodeId,
|
||||
kind: 'router',
|
||||
ports: [portSnapshot(routerPortA, 'rt1'), portSnapshot(routerPortB, 'rt2')],
|
||||
};
|
||||
const snapshot = topologySnapshot({
|
||||
nodes: [pc(sourceNodeId, sourcePortId), router, pc(targetNodeId, targetPortId)],
|
||||
links: [
|
||||
link(sourceNodeId, sourcePortId, routerNodeId, routerPortA),
|
||||
link(routerNodeId, routerPortB, targetNodeId, targetPortId),
|
||||
],
|
||||
deviceConfigurations: new Map([
|
||||
[sourceNodeId, device('10.0.0.2', { gateway: '10.0.0.1' })],
|
||||
[routerNodeId, device('10.0.0.1')],
|
||||
[targetNodeId, device('20.0.0.2', { gateway: '20.0.0.1' })],
|
||||
]),
|
||||
interfaceConfigurations: new Map([
|
||||
[interfaceKey(routerNodeId, routerPortA), { ipAddress: '10.0.0.1', subnetMask: '255.255.255.0' }],
|
||||
[interfaceKey(routerNodeId, routerPortB), { ipAddress: '20.0.0.1', subnetMask: '255.255.255.0' }],
|
||||
]),
|
||||
});
|
||||
const engine = new NetworkRuntimeEngine(14);
|
||||
engine.handle({ type: 'start', snapshot, seed: 14, initialTimeMilliseconds: 0 });
|
||||
return { engine, sourceNodeId, routerNodeId };
|
||||
}
|
||||
|
||||
function firewallEngine(configuration: FirewallConfiguration) {
|
||||
const routerId = uuid(0x1802);
|
||||
const portId = uuid(0x1812);
|
||||
const engine = startedEngine(
|
||||
{
|
||||
nodes: [{ id: routerId, kind: 'router', ports: [portSnapshot(portId, 'rt1')] }],
|
||||
links: [],
|
||||
interfaceConfigurations: new Map([
|
||||
[interfaceKey(routerId, portId), { ipAddress: '10.0.0.1', subnetMask: '255.255.255.0' }],
|
||||
]),
|
||||
firewallConfigurationsByNodeId: new Map([[routerId, configuration]]),
|
||||
},
|
||||
18,
|
||||
);
|
||||
return { engine, routerId };
|
||||
}
|
||||
|
||||
function tcpPacket(identity: number, destinationPort: number, flags: number): IPv4Packet {
|
||||
return {
|
||||
identity,
|
||||
senderIPAddress: '203.0.113.10',
|
||||
receiverIPAddress: '10.0.0.1',
|
||||
timeToLive: 64,
|
||||
protocol: 'tcp',
|
||||
payload: {
|
||||
kind: 'tcp',
|
||||
segment: {
|
||||
sourcePort: 50_000,
|
||||
destinationPort,
|
||||
sequenceNumber: identity,
|
||||
acknowledgementNumber: 0,
|
||||
flags,
|
||||
payload: new Uint8Array(),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('event queue and virtual clock', () => {
|
||||
it('orders events by deadline, then by insertion sequence', () => {
|
||||
const engine = new NetworkRuntimeEngine(42);
|
||||
engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 42, initialTimeMilliseconds: 0 });
|
||||
engine.handle({ type: 'schedule', deadlineMilliseconds: 100, kind: marker('first-at-100') });
|
||||
engine.handle({ type: 'schedule', deadlineMilliseconds: 50, kind: marker('at-50') });
|
||||
engine.handle({ type: 'schedule', deadlineMilliseconds: 100, kind: marker('second-at-100') });
|
||||
|
||||
const outputs = engine.handle({ type: 'advance', toMilliseconds: 100 });
|
||||
|
||||
expect(firedKinds(outputs)).toEqual([marker('at-50'), marker('first-at-100'), marker('second-at-100')]);
|
||||
expect(engine.state.currentTimeMilliseconds).toBe(100);
|
||||
expect(engine.state.pendingEvents).toEqual([]);
|
||||
});
|
||||
|
||||
it('rejects a past time without changing the clock', () => {
|
||||
const engine = new NetworkRuntimeEngine(7);
|
||||
engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 7, initialTimeMilliseconds: 10 });
|
||||
engine.handle({ type: 'advance', toMilliseconds: 25 });
|
||||
|
||||
const outputs = engine.handle({ type: 'advance', toMilliseconds: 24 });
|
||||
|
||||
expect(outputs.map((output) => output.kind)).toEqual([{ type: 'advanceRejectedPastTime' }]);
|
||||
expect(engine.state.currentTimeMilliseconds).toBe(25);
|
||||
});
|
||||
|
||||
it('rejects a past deadline without using up a sequence number', () => {
|
||||
const engine = new NetworkRuntimeEngine(8);
|
||||
engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 8, initialTimeMilliseconds: 25 });
|
||||
|
||||
const outputs = engine.handle({ type: 'schedule', deadlineMilliseconds: 24, kind: marker('past') });
|
||||
|
||||
expect(outputs.map((output) => output.kind)).toEqual([
|
||||
{ type: 'scheduleRejectedPastTime', deadlineMilliseconds: 24 },
|
||||
]);
|
||||
expect(engine.state.pendingEvents).toEqual([]);
|
||||
expect(engine.state.nextEventSequenceNumber).toBe(0);
|
||||
expect(engine.state.currentTimeMilliseconds).toBe(25);
|
||||
});
|
||||
|
||||
it('replays a named scenario straight to a stable state', () => {
|
||||
const finalState = NetworkRuntimeEngine.run({
|
||||
name: 'equal-deadline-order',
|
||||
seed: 1,
|
||||
advanceToMilliseconds: 1_000,
|
||||
scheduledEvents: [
|
||||
{ deadlineMilliseconds: 500, kind: marker('a') },
|
||||
{ deadlineMilliseconds: 500, kind: marker('b') },
|
||||
],
|
||||
});
|
||||
|
||||
expect(finalState.currentTimeMilliseconds).toBe(1_000);
|
||||
expect(finalState.pendingEvents).toEqual([]);
|
||||
expect(finalState.seed).toBe(1n);
|
||||
});
|
||||
|
||||
it('clears transient state on restart and numbers packets from one again', () => {
|
||||
const nodeId = uuid(0x12);
|
||||
const engine = new NetworkRuntimeEngine(12);
|
||||
engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 12, initialTimeMilliseconds: 0 });
|
||||
engine.handle({ type: 'schedule', deadlineMilliseconds: 40, kind: marker('stale') });
|
||||
expect(engine.allocateFrameIdentity()).toBe(1);
|
||||
expect(engine.allocatePacketIdentity()).toBe(1);
|
||||
engine.recordTrace({ packetIdentity: 1, nodeId, direction: 'local', layer: 'application', operation: 'created' });
|
||||
engine.handle({ type: 'stop' });
|
||||
|
||||
engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 12, initialTimeMilliseconds: 0 });
|
||||
|
||||
const state = engine.state;
|
||||
expect(state.pendingEvents).toEqual([]);
|
||||
expect(state.packetTraces).toEqual([]);
|
||||
expect(state.arpCachesByNodeId.size).toBe(0);
|
||||
expect(state.switchForwardingTablesByNodeId.size).toBe(0);
|
||||
expect(state.switchSeenFrameIdentitiesByNodeId.size).toBe(0);
|
||||
expect(state.deliveredIPv4PacketsByNodeId.size).toBe(0);
|
||||
expect(state.icmpObservationsByNodeId.size).toBe(0);
|
||||
expect(state.firewallDecisions).toEqual([]);
|
||||
expect(engine.allocateFrameIdentity()).toBe(1);
|
||||
expect(engine.allocatePacketIdentity()).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Java-compatible randomness', () => {
|
||||
it('draws the same RIP jitter as java.util.Random', () => {
|
||||
const random = new JavaCompatibleRandom(42);
|
||||
|
||||
expect(Array.from({ length: 5 }, () => random.nextRipJitterMilliseconds())).toEqual([
|
||||
32_475, 25_746, 32_032, 25_679, 28_287,
|
||||
]);
|
||||
});
|
||||
|
||||
it('matches java.util.Random.nextInt for bounded and power-of-two ranges', () => {
|
||||
// Measured on OpenJDK 21 (29.09.2026): new java.util.Random(42),
|
||||
// nextInt(100) three times, then nextInt(16) three times.
|
||||
const random = new JavaCompatibleRandom(42);
|
||||
|
||||
expect([random.nextInt(100), random.nextInt(100), random.nextInt(100)]).toEqual([30, 63, 48]);
|
||||
expect([random.nextInt(16), random.nextInt(16), random.nextInt(16)]).toEqual([0, 4, 15]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('IPv4 packets', () => {
|
||||
it('keeps the identity and lowers the TTL when forwarding', () => {
|
||||
const packet: IPv4Packet = {
|
||||
identity: 99,
|
||||
senderIPAddress: '192.168.0.10',
|
||||
receiverIPAddress: '192.168.1.20',
|
||||
timeToLive: 2,
|
||||
protocol: 'icmp',
|
||||
payload: { kind: 'icmp', message: icmpMessage('echoRequest', { identifier: 3, sequenceNumber: 4 }) },
|
||||
};
|
||||
|
||||
const forwarded = forwardingClone(packet);
|
||||
const expired = forwardingClone(forwarded);
|
||||
|
||||
expect(forwarded).toMatchObject({ identity: 99, timeToLive: 1 });
|
||||
expect(expired).toMatchObject({ identity: 99, timeToLive: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('Ethernet, ARP and ICMP', () => {
|
||||
it('fills both ARP caches with one request and reply over a direct cable', () => {
|
||||
const sourceNodeId = uuid(0x1401);
|
||||
const sourcePortId = uuid(0x1411);
|
||||
const targetNodeId = uuid(0x1402);
|
||||
const targetPortId = uuid(0x1412);
|
||||
const engine = startedEngine({
|
||||
nodes: [pc(sourceNodeId, sourcePortId), pc(targetNodeId, targetPortId)],
|
||||
links: [link(sourceNodeId, sourcePortId, targetNodeId, targetPortId)],
|
||||
deviceConfigurations: new Map([
|
||||
[sourceNodeId, device('192.168.0.10')],
|
||||
[targetNodeId, device('192.168.0.20')],
|
||||
]),
|
||||
});
|
||||
|
||||
const resolved = engine.resolveMacAddress(sourceNodeId, '192.168.0.20');
|
||||
|
||||
expect(resolved).toBe(stableMacAddress(targetPortId));
|
||||
expect(engine.state.arpCachesByNodeId.get(sourceNodeId)?.get('192.168.0.20')?.macAddress).toBe(resolved);
|
||||
expect(engine.state.arpCachesByNodeId.get(targetNodeId)?.get('192.168.0.10')?.macAddress).toBe(
|
||||
stableMacAddress(sourcePortId),
|
||||
);
|
||||
});
|
||||
|
||||
it('pings across a switch with Ethernet, ARP and ICMP packets', () => {
|
||||
const sourceNodeId = uuid(0x1421);
|
||||
const sourcePortId = uuid(0x1431);
|
||||
const switchNodeId = uuid(0x1422);
|
||||
const switchPortA = uuid(0x1432);
|
||||
const switchPortB = uuid(0x1433);
|
||||
const targetNodeId = uuid(0x1423);
|
||||
const targetPortId = uuid(0x1434);
|
||||
const switchNode: NodeSnapshot = {
|
||||
id: switchNodeId,
|
||||
kind: 'networkSwitch',
|
||||
ports: [portSnapshot(switchPortA, 'sw1'), portSnapshot(switchPortB, 'sw2')],
|
||||
};
|
||||
const engine = startedEngine({
|
||||
nodes: [pc(sourceNodeId, sourcePortId), switchNode, pc(targetNodeId, targetPortId)],
|
||||
links: [
|
||||
link(sourceNodeId, sourcePortId, switchNodeId, switchPortA),
|
||||
link(switchNodeId, switchPortB, targetNodeId, targetPortId),
|
||||
],
|
||||
deviceConfigurations: new Map([
|
||||
[sourceNodeId, device('192.168.0.10')],
|
||||
[targetNodeId, device('192.168.0.20')],
|
||||
]),
|
||||
});
|
||||
|
||||
const result = engine.sendIcmpEcho(sourceNodeId, '192.168.0.20', { identifier: 14, sequenceNumber: 1 });
|
||||
|
||||
expect(result.type).toBe('delivered');
|
||||
expect(engine.state.icmpObservationsByNodeId.get(sourceNodeId)?.at(-1)?.message.kind).toBe('echoReply');
|
||||
expect(engine.state.switchForwardingTablesByNodeId.get(switchNodeId)?.size).toBe(2);
|
||||
expect(engine.state.packetTraces.some((trace) => trace.detail === 'ARP request for 192.168.0.20')).toBe(true);
|
||||
expect(
|
||||
engine.state.packetTraces.some((trace) => trace.packetIdentity !== undefined && trace.layer === 'network'),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('answers an expired TTL at the router with time exceeded and the original packet', () => {
|
||||
const topology = routedTopology();
|
||||
|
||||
const result = topology.engine.sendIcmpEcho(topology.sourceNodeId, '20.0.0.2', {
|
||||
timeToLive: 1,
|
||||
identifier: 140,
|
||||
sequenceNumber: 1,
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({ type: 'icmpError', kind: 'timeExceeded' });
|
||||
const observation = topology.engine.state.icmpObservationsByNodeId.get(topology.sourceNodeId)?.at(-1);
|
||||
expect(observation?.message.kind).toBe('timeExceeded');
|
||||
expect(observation?.message.embeddedOriginalPacket?.timeToLive).toBe(1);
|
||||
expect(observation?.message.embeddedOriginalPacket?.receiverIPAddress).toBe('20.0.0.2');
|
||||
});
|
||||
|
||||
it('keeps the packet identity and lowers the TTL when a router forwards', () => {
|
||||
const topology = routedTopology();
|
||||
|
||||
const result = topology.engine.sendIcmpEcho(topology.sourceNodeId, '20.0.0.2', {
|
||||
timeToLive: 8,
|
||||
identifier: 141,
|
||||
sequenceNumber: 1,
|
||||
});
|
||||
|
||||
expect(result.type).toBe('delivered');
|
||||
const forwardingTrace = topology.engine.state.packetTraces.find(
|
||||
(trace) =>
|
||||
trace.nodeId === topology.routerNodeId && trace.operation === 'forwarded' && trace.detail === 'TTL decremented',
|
||||
);
|
||||
expect(forwardingTrace?.packetIdentity).toBeDefined();
|
||||
expect(forwardingTrace?.beforeHeaders.find((field) => field.name === 'ttl')?.value).toBe('8');
|
||||
expect(forwardingTrace?.afterHeaders.find((field) => field.name === 'ttl')?.value).toBe('7');
|
||||
});
|
||||
|
||||
it('reports network unreachable when the router has no route', () => {
|
||||
const topology = routedTopology();
|
||||
const snapshot = topology.engine.state.topologySnapshot;
|
||||
const sourceToRouter = snapshot.links.find(
|
||||
(candidate) => candidate.sourceNodeId === topology.sourceNodeId || candidate.targetNodeId === topology.sourceNodeId,
|
||||
);
|
||||
const engine = new NetworkRuntimeEngine(14);
|
||||
engine.handle({
|
||||
type: 'start',
|
||||
snapshot: topologySnapshot({
|
||||
nodes: snapshot.nodes,
|
||||
links: sourceToRouter === undefined ? [] : [sourceToRouter],
|
||||
deviceConfigurations: snapshot.deviceConfigurations,
|
||||
interfaceConfigurations: snapshot.interfaceConfigurations,
|
||||
manualRoutesByNodeId: snapshot.manualRoutesByNodeId,
|
||||
}),
|
||||
seed: 14,
|
||||
initialTimeMilliseconds: 0,
|
||||
});
|
||||
|
||||
const result = engine.sendIcmpEcho(topology.sourceNodeId, '30.0.0.2', { identifier: 142, sequenceNumber: 1 });
|
||||
|
||||
expect(result).toMatchObject({ type: 'icmpError', kind: 'destinationNetworkUnreachable' });
|
||||
});
|
||||
|
||||
it('reports host unreachable when a connected target never answers ARP', () => {
|
||||
const sourceNodeId = uuid(0x1481);
|
||||
const sourcePortId = uuid(0x1491);
|
||||
const engine = startedEngine({
|
||||
nodes: [pc(sourceNodeId, sourcePortId)],
|
||||
links: [],
|
||||
deviceConfigurations: new Map([[sourceNodeId, device('192.168.50.10')]]),
|
||||
});
|
||||
|
||||
const result = engine.sendIcmpEcho(sourceNodeId, '192.168.50.99', { identifier: 143, sequenceNumber: 1 });
|
||||
|
||||
expect(result).toMatchObject({ type: 'icmpError', kind: 'destinationHostUnreachable' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('switch', () => {
|
||||
it('learns, floods, forwards, filters and ages its address table', () => {
|
||||
const hostAId = uuid(0x1a01);
|
||||
const hostAPortId = uuid(0x1a11);
|
||||
const hostBId = uuid(0x1a02);
|
||||
const hostBPortId = uuid(0x1a12);
|
||||
const hostCId = uuid(0x1a03);
|
||||
const hostCPortId = uuid(0x1a13);
|
||||
const switchId = uuid(0x1a04);
|
||||
const switchPorts = [1, 2, 3].map((index) => portSnapshot(uuid(0x1a20 + index), `sw${index}`));
|
||||
const engine = startedEngine(
|
||||
{
|
||||
nodes: [
|
||||
pc(hostAId, hostAPortId),
|
||||
pc(hostBId, hostBPortId),
|
||||
pc(hostCId, hostCPortId),
|
||||
{ id: switchId, kind: 'networkSwitch', ports: switchPorts },
|
||||
],
|
||||
links: [
|
||||
link(hostAId, hostAPortId, switchId, switchPorts[0]!.id),
|
||||
link(hostBId, hostBPortId, switchId, switchPorts[1]!.id),
|
||||
link(hostCId, hostCPortId, switchId, switchPorts[2]!.id),
|
||||
],
|
||||
switchConfigurationsByNodeId: new Map([[switchId, switchConfiguration('Classroom', 1_000)]]),
|
||||
},
|
||||
20,
|
||||
);
|
||||
const macA = stableMacAddress(hostAPortId);
|
||||
const macB = stableMacAddress(hostBPortId);
|
||||
const payload: EthernetPayload = {
|
||||
kind: 'arp',
|
||||
packet: {
|
||||
operation: 'request',
|
||||
senderMacAddress: macA,
|
||||
senderIPAddress: '192.0.2.1',
|
||||
targetMacAddress: UNSPECIFIED_MAC_ADDRESS,
|
||||
targetIPAddress: '192.0.2.200',
|
||||
},
|
||||
};
|
||||
const frame = (sourceMacAddress: string, destinationMacAddress: string): EthernetFrame => ({
|
||||
identity: engine.allocateFrameIdentity(),
|
||||
sourceMacAddress,
|
||||
destinationMacAddress,
|
||||
payload,
|
||||
});
|
||||
const switchTraces = (detail: string) =>
|
||||
engine.state.packetTraces.filter((trace) => trace.nodeId === switchId && trace.detail === detail);
|
||||
|
||||
engine.sendEthernetFrame(hostAId, hostAPortId, frame(macA, '02:00:00:00:00:FE'));
|
||||
expect(switchTraces('switch unknown unicast flooding')).toHaveLength(2);
|
||||
|
||||
engine.sendEthernetFrame(hostBId, hostBPortId, frame(macB, macA));
|
||||
expect(switchTraces('switch learned unicast forwarding')).toHaveLength(1);
|
||||
|
||||
engine.sendEthernetFrame(hostAId, hostAPortId, frame(macA, macA));
|
||||
expect(switchTraces('switch filtered destination on incoming port').length).toBeGreaterThan(0);
|
||||
expect(engine.switchSatEntries(switchId)).toHaveLength(2);
|
||||
|
||||
const retention = 1_000;
|
||||
const updateTimes = [...engine.state.switchForwardingUpdatedAtMillisecondsByNodeId.get(switchId)!.values()];
|
||||
const expirationDeadlines = updateTimes.map((time) => time + retention);
|
||||
const firstExpiration = Math.min(...expirationDeadlines);
|
||||
const lastExpiration = Math.max(...expirationDeadlines);
|
||||
|
||||
engine.handle({ type: 'advance', toMilliseconds: firstExpiration - 1 });
|
||||
expect(engine.switchSatEntries(switchId)).toHaveLength(2);
|
||||
engine.handle({ type: 'advance', toMilliseconds: lastExpiration });
|
||||
expect(engine.switchSatEntries(switchId)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('firewall', () => {
|
||||
it('accepts when inactive, and an active ICMP drop bypasses the ordered rules', () => {
|
||||
const routerId = uuid(0x1801);
|
||||
const portId = uuid(0x1811);
|
||||
const router: NodeSnapshot = { id: routerId, kind: 'router', ports: [portSnapshot(portId, 'rt1')] };
|
||||
const packet: IPv4Packet = {
|
||||
identity: 18,
|
||||
senderIPAddress: '203.0.113.10',
|
||||
receiverIPAddress: '10.0.0.1',
|
||||
timeToLive: 64,
|
||||
protocol: 'icmp',
|
||||
payload: { kind: 'icmp', message: icmpMessage('echoRequest') },
|
||||
};
|
||||
const interfaces = new Map([
|
||||
[interfaceKey(routerId, portId), { ipAddress: '10.0.0.1', subnetMask: '255.255.255.0' }],
|
||||
]);
|
||||
|
||||
const inactive = startedEngine(
|
||||
{
|
||||
nodes: [router],
|
||||
links: [],
|
||||
interfaceConfigurations: interfaces,
|
||||
firewallConfigurationsByNodeId: new Map([[routerId, firewallConfiguration()]]),
|
||||
},
|
||||
18,
|
||||
);
|
||||
expect(inactive.evaluateFirewall(packet, routerId).accepted).toBe(true);
|
||||
|
||||
const active = startedEngine(
|
||||
{
|
||||
nodes: [router],
|
||||
links: [],
|
||||
interfaceConfigurations: interfaces,
|
||||
firewallConfigurationsByNodeId: new Map([
|
||||
[
|
||||
routerId,
|
||||
firewallConfiguration({
|
||||
isActive: true,
|
||||
defaultPolicy: 'accept',
|
||||
dropIcmp: true,
|
||||
rules: [firewallRule({ protocol: 'icmp', action: 'accept' })],
|
||||
}),
|
||||
],
|
||||
]),
|
||||
},
|
||||
18,
|
||||
);
|
||||
expect(active.evaluateFirewall(packet, routerId).accepted).toBe(false);
|
||||
expect(active.state.firewallDecisions.at(-1)?.ruleIndex).toBeUndefined();
|
||||
expect(active.state.packetTraces.at(-1)?.operation).toBe('dropped');
|
||||
});
|
||||
|
||||
it('lets the first matching TCP rule win, and established traffic bypasses SYN-only rules', () => {
|
||||
const { engine, routerId } = firewallEngine(
|
||||
firewallConfiguration({
|
||||
isActive: true,
|
||||
defaultPolicy: 'drop',
|
||||
filterSynSegmentsOnly: true,
|
||||
rules: [
|
||||
firewallRule({ port: 443, protocol: 'tcp', action: 'accept' }),
|
||||
firewallRule({ port: 443, protocol: 'tcp', action: 'drop' }),
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const synDecision = engine.evaluateFirewall(tcpPacket(181, 443, TCP_FLAG.synchronize), routerId);
|
||||
expect(synDecision.accepted).toBe(true);
|
||||
expect(synDecision.ruleIndex).toBe(0);
|
||||
expect(engine.evaluateFirewall(tcpPacket(182, 22, TCP_FLAG.acknowledgement), routerId).accepted).toBe(true);
|
||||
});
|
||||
|
||||
it('matches a UDP response by its explicit source port and the direct-network marker', () => {
|
||||
const { engine, routerId } = firewallEngine(
|
||||
firewallConfiguration({
|
||||
isActive: true,
|
||||
defaultPolicy: 'drop',
|
||||
rules: [
|
||||
firewallRule({
|
||||
sourceIPAddress: DIRECTLY_CONNECTED_SOURCE_MARKER,
|
||||
destinationIPAddress: '8.8.8.8',
|
||||
destinationSubnetMask: '255.255.255.255',
|
||||
port: 53,
|
||||
protocol: 'udp',
|
||||
action: 'accept',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
);
|
||||
const udp = (identity: number, sender: string, receiver: string, sourcePort: number, destinationPort: number): IPv4Packet => ({
|
||||
identity,
|
||||
senderIPAddress: sender,
|
||||
receiverIPAddress: receiver,
|
||||
timeToLive: 64,
|
||||
protocol: 'udp',
|
||||
payload: { kind: 'udp', datagram: { sourcePort, destinationPort, payload: new Uint8Array() } },
|
||||
});
|
||||
|
||||
expect(engine.evaluateFirewall(udp(183, '10.0.0.20', '8.8.8.8', 50_001, 53), routerId).accepted).toBe(true);
|
||||
expect(engine.evaluateFirewall(udp(184, '8.8.8.8', '10.0.0.20', 53, 50_001), routerId).accepted).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('packet loss and trace retention', () => {
|
||||
it('drops every physical delivery while global packet loss is on', () => {
|
||||
const firstNodeId = uuid(0x101);
|
||||
const firstPortId = uuid(0x102);
|
||||
const secondNodeId = uuid(0x103);
|
||||
const secondPortId = uuid(0x104);
|
||||
const engine = startedEngine({
|
||||
nodes: [pc(firstNodeId, firstPortId), pc(secondNodeId, secondPortId)],
|
||||
links: [link(firstNodeId, firstPortId, secondNodeId, secondPortId)],
|
||||
deviceConfigurations: new Map([
|
||||
[firstNodeId, device('10.0.0.1')],
|
||||
[secondNodeId, device('10.0.0.2')],
|
||||
]),
|
||||
});
|
||||
const frame: EthernetFrame = {
|
||||
identity: engine.allocateFrameIdentity(),
|
||||
sourceMacAddress: stableMacAddress(firstPortId),
|
||||
destinationMacAddress: ETHERNET_BROADCAST_MAC_ADDRESS,
|
||||
payload: {
|
||||
kind: 'arp',
|
||||
packet: {
|
||||
operation: 'request',
|
||||
senderMacAddress: stableMacAddress(firstPortId),
|
||||
senderIPAddress: '10.0.0.1',
|
||||
targetMacAddress: UNSPECIFIED_MAC_ADDRESS,
|
||||
targetIPAddress: '10.0.0.2',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
engine.setGlobalPacketLossEnabled(true);
|
||||
engine.sendEthernetFrame(firstNodeId, firstPortId, frame);
|
||||
|
||||
expect(engine.state.globalPacketLossEnabled).toBe(true);
|
||||
expect(engine.state.arpCachesByNodeId.get(secondNodeId)?.size ?? 0).toBe(0);
|
||||
expect(
|
||||
engine.state.packetTraces.some(
|
||||
(trace) =>
|
||||
trace.frameIdentity === frame.identity &&
|
||||
trace.nodeId === secondNodeId &&
|
||||
trace.operation === 'dropped' &&
|
||||
trace.detail === 'global packet-loss simulation',
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
engine.setGlobalPacketLossEnabled(false);
|
||||
engine.sendEthernetFrame(firstNodeId, firstPortId, frame);
|
||||
|
||||
expect(engine.state.globalPacketLossEnabled).toBe(false);
|
||||
expect(engine.state.arpCachesByNodeId.get(secondNodeId)?.get('10.0.0.1')?.macAddress).toBe(
|
||||
stableMacAddress(firstPortId),
|
||||
);
|
||||
});
|
||||
|
||||
it('resets packet loss across stop and restart', () => {
|
||||
const engine = new NetworkRuntimeEngine(42);
|
||||
engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 42, initialTimeMilliseconds: 0 });
|
||||
engine.setGlobalPacketLossEnabled(true);
|
||||
expect(engine.state.globalPacketLossEnabled).toBe(true);
|
||||
|
||||
engine.handle({ type: 'stop' });
|
||||
expect(engine.state.globalPacketLossEnabled).toBe(false);
|
||||
|
||||
engine.handle({ type: 'start', snapshot: EMPTY_TOPOLOGY_SNAPSHOT, seed: 42, initialTimeMilliseconds: 0 });
|
||||
expect(engine.state.globalPacketLossEnabled).toBe(false);
|
||||
});
|
||||
|
||||
it('evicts the oldest trace events in configured batches', () => {
|
||||
const nodeId = uuid(0x2001);
|
||||
const interfaceId = uuid(0x2002);
|
||||
const engine = new NetworkRuntimeEngine(20, traceRetentionPolicy(3, 2));
|
||||
|
||||
for (let identity = 1; identity <= 6; identity += 1) {
|
||||
engine.recordTrace({
|
||||
frameIdentity: identity,
|
||||
nodeId,
|
||||
interfaceId,
|
||||
direction: 'outbound',
|
||||
layer: 'dataLink',
|
||||
operation: 'sent',
|
||||
detail: `trace-${identity}`,
|
||||
});
|
||||
}
|
||||
|
||||
expect(engine.state.packetTraces.map((trace) => trace.id)).toEqual([5, 6]);
|
||||
expect(engine.state.packetTraces.map((trace) => trace.detail)).toEqual(['trace-5', 'trace-6']);
|
||||
expect(engine.state.discardedPacketTraceCount).toBe(4);
|
||||
expect(engine.state.nextTraceIdentity).toBe(7);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
// Test fixtures, ported from the private helpers of
|
||||
// filius-ipad ios/FiliusPadTests/TopologyNetworkRuntimeEngineTests.swift.
|
||||
|
||||
import {
|
||||
deviceConfiguration,
|
||||
NetworkRuntimeEngine,
|
||||
portSnapshot,
|
||||
topologySnapshot,
|
||||
type DeviceConfiguration,
|
||||
type Id,
|
||||
type LinkSnapshot,
|
||||
type NodeSnapshot,
|
||||
type TopologySnapshotInput,
|
||||
} from '../src/index.js';
|
||||
|
||||
let linkCounter = 0;
|
||||
|
||||
/** Swift uses a fresh `UUID()` per link; a counter keeps runs reproducible. */
|
||||
export function link(sourceNodeId: Id, sourcePortId: Id, targetNodeId: Id, targetPortId: Id): LinkSnapshot {
|
||||
linkCounter += 1;
|
||||
return {
|
||||
id: `ffffffff-0000-0000-0000-${linkCounter.toString(16).padStart(12, '0')}`,
|
||||
sourceNodeId,
|
||||
sourcePortId,
|
||||
targetNodeId,
|
||||
targetPortId,
|
||||
};
|
||||
}
|
||||
|
||||
export function pc(nodeId: Id, portId: Id): NodeSnapshot {
|
||||
return { id: nodeId, kind: 'pc', ports: [portSnapshot(portId, 'eth0')] };
|
||||
}
|
||||
|
||||
export function device(ipAddress: string, options: { mask?: string; gateway?: string } = {}): DeviceConfiguration {
|
||||
return deviceConfiguration(ipAddress, options.mask ?? '255.255.255.0', options.gateway ?? '');
|
||||
}
|
||||
|
||||
export function startedEngine(
|
||||
input: TopologySnapshotInput,
|
||||
seed: number = 14,
|
||||
): NetworkRuntimeEngine {
|
||||
const engine = new NetworkRuntimeEngine(seed);
|
||||
engine.handle({ type: 'start', snapshot: topologySnapshot(input), seed, initialTimeMilliseconds: 0 });
|
||||
return engine;
|
||||
}
|
||||
|
||||
/** `00000000-0000-0000-0000-` followed by twelve hex digits. */
|
||||
export function uuid(suffix: number): Id {
|
||||
return `00000000-0000-0000-0000-${suffix.toString(16).toUpperCase().padStart(12, '0')}`;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// Ported from filius-ipad ios/FiliusPadTests/TopologyJavaRouteTableTests.swift.
|
||||
// Left out: column titles and geometry (editor), and the reducer tests
|
||||
// (they move with the document layer, packages/doc).
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
appendingBlankDraftIfNeeded,
|
||||
bestMatchingManualRoute,
|
||||
blankRouteDraft,
|
||||
isValidJavaIPAddress,
|
||||
isValidJavaSubnetMask,
|
||||
manualRouteFromDraft,
|
||||
routeTableRows,
|
||||
visibleRouteRows,
|
||||
type ManualRoute,
|
||||
} from '../src/index.js';
|
||||
|
||||
function route(destinationNetwork: string, subnetMask: string, gateway: string, interfaceIPAddress: string): ManualRoute {
|
||||
return { destinationNetwork, subnetMask, gateway, interfaceIPAddress };
|
||||
}
|
||||
|
||||
describe('Java route table', () => {
|
||||
it('projects multiple interfaces in Java order with Java values', () => {
|
||||
const rows = routeTableRows(
|
||||
[
|
||||
{ ipAddress: '10.0.0.1', subnetMask: '255.255.255.0' },
|
||||
{ ipAddress: '192.168.0.1', subnetMask: '255.255.255.0' },
|
||||
],
|
||||
[
|
||||
route('172.16.0.0', '255.255.0.0', '10.0.0.2', '10.0.0.1'),
|
||||
route('203.0.113.0', '255.255.255.0', '192.168.0.2', '192.168.0.1'),
|
||||
],
|
||||
'10.0.0.254',
|
||||
);
|
||||
|
||||
expect(rows.map((row) => row.destinationNetwork)).toEqual([
|
||||
'192.168.0.1', '10.0.0.1',
|
||||
'192.168.0.0', '10.0.0.0',
|
||||
'127.0.0.0',
|
||||
'172.16.0.0', '203.0.113.0',
|
||||
'0.0.0.0',
|
||||
]);
|
||||
expect(rows.map((row) => row.origin)).toEqual([
|
||||
'localHost', 'localHost', 'connected', 'connected', 'localhost', 'manual', 'manual', 'defaultGateway',
|
||||
]);
|
||||
expect(rows.map((row) => row.isEditable)).toEqual([false, false, false, false, false, true, true, false]);
|
||||
expect(rows[0]).toMatchObject({ subnetMask: '255.255.255.255', nextHop: '127.0.0.1', interfaceIPAddress: '127.0.0.1' });
|
||||
expect(rows[2]?.nextHop).toBe('192.168.0.1');
|
||||
expect(rows[4]?.nextHop).toBe('127.0.0.1');
|
||||
expect(rows.at(-1)).toMatchObject({ nextHop: '10.0.0.254', interfaceIPAddress: '10.0.0.1' });
|
||||
});
|
||||
|
||||
it('puts the default route on the last matching interface and falls back to the primary one', () => {
|
||||
const interfaces = [
|
||||
{ ipAddress: '10.0.0.1', subnetMask: '255.0.0.0' },
|
||||
{ ipAddress: '10.1.0.1', subnetMask: '255.0.0.0' },
|
||||
];
|
||||
|
||||
const matching = routeTableRows(interfaces, [], '10.2.0.1');
|
||||
expect(matching.at(-1)).toMatchObject({ origin: 'defaultGateway', interfaceIPAddress: '10.1.0.1' });
|
||||
|
||||
const fallback = routeTableRows(interfaces, [], '192.168.0.1');
|
||||
expect(fallback.at(-1)?.interfaceIPAddress).toBe('10.0.0.1');
|
||||
});
|
||||
|
||||
it('shows only manual rows when generated rows are hidden', () => {
|
||||
const rows = routeTableRows(
|
||||
[{ ipAddress: '10.0.0.1', subnetMask: '255.255.255.0' }],
|
||||
[route('172.16.0.0', '255.255.0.0', '10.0.0.2', '10.0.0.1')],
|
||||
'10.0.0.254',
|
||||
);
|
||||
|
||||
expect(visibleRouteRows(rows, false).map((row) => row.origin)).toEqual(['manual']);
|
||||
expect(visibleRouteRows(rows, true)).toEqual(rows);
|
||||
});
|
||||
|
||||
it('accepts leading zeros and non-contiguous masks like Java', () => {
|
||||
expect(isValidJavaIPAddress('001.002.003.004')).toBe(true);
|
||||
expect(isValidJavaSubnetMask('255.0.255.0')).toBe(true);
|
||||
expect(isValidJavaIPAddress('256.0.0.1')).toBe(false);
|
||||
expect(isValidJavaSubnetMask('255.255.255')).toBe(false);
|
||||
expect(isValidJavaIPAddress(' 10.0.0.1')).toBe(false);
|
||||
});
|
||||
|
||||
it('commits a draft only when all four cells are valid', () => {
|
||||
const draft = blankRouteDraft('00000000-0000-0000-0000-000000000013');
|
||||
draft.destinationNetwork = '10.0.0.0';
|
||||
draft.subnetMask = '255.0.255.0';
|
||||
draft.nextGateway = '10.0.0.2';
|
||||
|
||||
expect(manualRouteFromDraft(draft)).toBeUndefined();
|
||||
|
||||
draft.interfaceIPAddress = '10.0.0.1';
|
||||
expect(manualRouteFromDraft(draft)).toEqual(route('10.0.0.0', '255.0.255.0', '10.0.0.2', '10.0.0.1'));
|
||||
});
|
||||
|
||||
it('keeps at most one pending blank draft', () => {
|
||||
let counter = 0;
|
||||
const newId = () => `draft-${(counter += 1)}`;
|
||||
const first = appendingBlankDraftIfNeeded([], newId);
|
||||
const second = appendingBlankDraftIfNeeded(first, newId);
|
||||
|
||||
expect(first).toHaveLength(1);
|
||||
expect(second).toEqual(first);
|
||||
expect(second[0]?.isPendingInsertion).toBe(true);
|
||||
});
|
||||
|
||||
it('picks the greatest numeric mask and keeps the first row on a tie', () => {
|
||||
const broad = route('10.0.0.0', '255.0.0.0', '1.1.1.1', '10.0.0.1');
|
||||
const firstSpecific = route('10.1.0.0', '255.255.0.0', '2.2.2.2', '10.0.0.1');
|
||||
const tiedSpecific = route('10.1.0.0', '255.255.0.0', '3.3.3.3', '10.0.0.1');
|
||||
|
||||
expect(bestMatchingManualRoute('10.1.2.3', [broad, firstSpecific, tiedSpecific])).toBe(firstSpecific);
|
||||
});
|
||||
|
||||
it('never includes learned RIP rows in the static projection', () => {
|
||||
const rows = routeTableRows([{ ipAddress: '10.0.0.1', subnetMask: '255.255.255.0' }], [], undefined);
|
||||
|
||||
expect(rows.some((row) => row.origin === 'rip')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".",
|
||||
"outDir": "dist",
|
||||
"types": []
|
||||
},
|
||||
"include": ["src", "test"]
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
# Words only this repository may use, in addition to the dashboard's
|
||||
# scripts/code_language_allow.txt. Format: `path::word` (bound to one path or
|
||||
# path prefix) or a bare word (anywhere). Each entry says why.
|
||||
#
|
||||
# The .fls format is Java's XMLEncoder output: its class and property names
|
||||
# (filius.hardware.knoten.Vermittlungsrechner, GUIKnotenItem, ipAdresse …)
|
||||
# are fields of a foreign API and keep their German names — in packages/fls
|
||||
# only.
|
||||
#
|
||||
# Java FILIUS class and package names, cited in the provenance header of each
|
||||
# ported file and in comments that point at the Java behaviour they copy.
|
||||
vermittlungsrechner
|
||||
verbindung
|
||||
netzzugangsschicht
|
||||
vermittlungsschicht
|
||||
Executable
+22
@@ -0,0 +1,22 @@
|
||||
#!/bin/sh
|
||||
# Keeps German code out of this repository — the same rule as in the dashboard
|
||||
# (its CLAUDE.md). The checker is borrowed from the dashboard this repository is
|
||||
# a submodule of; CODE_LANGUAGE_ROOT points it at our files, and words only we
|
||||
# may use (the Java class names of the .fls format) stand in
|
||||
# scripts/code_language_allow.txt.
|
||||
#
|
||||
# Enable: npm run hooks
|
||||
# Bypass: git commit --no-verify
|
||||
top="$(git rev-parse --show-toplevel)"
|
||||
super="$(git rev-parse --show-superproject-working-tree 2>/dev/null)"
|
||||
checker="$super/scripts/check_code_language.py"
|
||||
if [ -z "$super" ] || [ ! -f "$checker" ]; then
|
||||
echo "pre-commit: not inside the dashboard checkout, language check skipped"
|
||||
exit 0
|
||||
fi
|
||||
CODE_LANGUAGE_ROOT="$top" python3 "$checker" --changed HEAD || {
|
||||
echo
|
||||
echo "German code in the commit. Glossary: knowledge/plans/CODE_ENGLISH_REFACTOR.md §3 (dashboard)"
|
||||
echo "Commit anyway: git commit --no-verify"
|
||||
exit 1
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitOverride": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"exactOptionalPropertyTypes": true,
|
||||
"isolatedModules": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"declaration": true,
|
||||
"sourceMap": true,
|
||||
"composite": true,
|
||||
"skipLibCheck": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [{ "path": "packages/core" }]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['packages/*/test/**/*.test.ts'],
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user