diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..e385563 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ + +*.BAT -text whitespace=cr-at-eol diff --git a/.gitignore b/.gitignore index 9d54087..d655ddf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,3 @@ -cat > .gitignore <<'EOF' # Build /build/ /upstream/build/ @@ -45,4 +44,7 @@ nwserv.conf .idea/ .vscode/ .DS_Store -EOF + +/.toolchains/ +/upstream/patched/ +/*.7z diff --git a/AUTOSETUP.md b/AUTOSETUP.md new file mode 100644 index 0000000..e0b84a9 --- /dev/null +++ b/AUTOSETUP.md @@ -0,0 +1,74 @@ +# MARS_NWE-PCAP 0.5.1 – automatische IPXPKT-Einrichtung und mTCP-Verteilung + +## Upgrade einer laufenden 0.4/0.5-Installation + +Im neuen Quellcodeverzeichnis: + +```sh +sudo apt install build-essential pkg-config libjson-c-dev libssl-dev libcivetweb-dev iproute2 nftables curl unzip +make all native check check-gateway check-gateway-auto +sudo ./install-gateway.sh +sudo systemctl start mars_vme.service +``` + +Der Upgrade-Installer sichert die bisherigen Binärdateien und die Webdateien und lässt `nwserv.conf`, Bindery, Login-Skripte, Web-Kennwort und `ipxpkt.json` unverändert. Kein erneutes Patchen des Originalservers. Für eine Neuinstallation gilt `./build.sh && sudo ./install.sh` mit den vollständigen Abhängigkeiten des bisherigen Guides. Der einzige MARS-Dienst bleibt `mars_vme.service`. + +## Automatische Netzwerkkonfiguration + +1. In **Server & IPX** mindestens ein externes IPX-Netz konfigurieren und speichern. +2. In **Internet & Gateway** werden bei der erstmaligen Einrichtung automatisch Vorschläge geladen. Bei einer vorhandenen Konfiguration **Netzwerk automatisch erkennen** wählen. Änderungen werden nicht automatisch gespeichert oder aktiviert. +3. Das Backend ermittelt die tatsächlich ausgewählte IPv4-Route zu 1.1.1.1 (kein Netzwerkpaket), den Uplink und seine Adresse/Netzmaske sowie den Next Hop. Es prüft das virtuelle /24 gegen die vorhandenen IPv4-Routen aller Tabellen. Bevorzugt wird 10.250.0.0/24, alternativ weitere 10.250.x.0/24-, 172.31.x.0/24- oder 192.168.x.0/24-Netze. Der bestehende Gateway-Adressbereich wird erhalten, sofern er frei ist; bestehende Reservierungen werden nicht automatisch umadressiert. +4. Nur öffentliche IPv4-Resolver sind für den Tunnel erlaubt. Ein passender öffentlicher Host-Resolver wird aus `/run/systemd/resolve/resolv.conf` bzw. `/etc/resolv.conf` übernommen, sonst bleibt der bisherige öffentliche DNS (initial 1.1.1.1). Private DNS-Server, systemd-resolved-Stub 127.0.0.53 und das Administrations-LAN bleiben für Tunnel-Clients gesperrt. Ein DNS-Proxy ist nicht enthalten. +5. Prüfen, ob `sysctl net.ipv4.ip_forward` den Wert 1 liefert. Falls nötig nach Prüfung der Host-Firewall bewusst per `sudo sysctl -w net.ipv4.ip_forward=1` aktivieren. Das Modul ändert den globalen Parameter nicht selbst. Auf Docker/Kubernetes-Hosts ist eine separate VM für Tests vorzuziehen. +6. Gateway aktivieren, speichern und **NetWare neu starten / anwenden**. Ein leeres Freigabeverzeichnis ist erlaubt: Erkennung läuft, kein Client erhält Internetzugriff. Ein einziges externes IPX-Netz wird unterstützt. Neustart trennt NetWare-Sitzungen. +7. Auf dem DOS-Client IPXPKT starten und einen DHCP-Versuch auslösen. Im Webmodal **Erkannte IPXPKT-Geräte aktualisieren** auswählen. Beobachtungen sind auf 64 Einträge und fünf Minuten begrenzt. MAC/IPX-Node muss mit der inneren Ethernet-MAC übereinstimmen. +8. **Freigeben / IP reservieren** erstellt eine freie Adresse ab .10 bis .254 im ausgewählten /24 und trägt sie in den Entwurf ein. Maximal 64 Reservierungen. Die Servervalidierung verhindert doppelte IPs und MACs. Speichern und erneut anwenden; danach DHCP auf dem DOS-Client wiederholen. Keine automatische Freigabe unbekannter Geräte. + +Die persistente Zuordnung bleibt in `/usr/local/etc/mars_nwe/ipxpkt.json`. Der DHCP-Server im Dispatcher beantwortet DISCOVER/REQUEST ausschließlich für freigegebene MACs. Er vergibt eine feste Reservierung mit 24-Stunden-Lease, Gateway, /24-Maske und DNS. Es existiert kein dynamischer Pool und keine separate Lease-Datei; die Reservierung selbst bleibt persistent. Andere DHCP-Nachrichten werden nicht weitergeleitet; das Modul bindet keinen UDP-Port im physischen LAN. DHCP ist ein Teil des IPXPKT-Datenpfads und benötigt keinen zusätzlichen Dienst. Die in 0.5 noch geforderte statische mTCP-Konfiguration ist optional weiterhin möglich. + +## mTCP zentral auf SYS:PUBLIC bereitstellen + +`mars-publish-mtcp` wird mit der Installation bereitgestellt. Sobald das Original-SYS-Volume und dessen PUBLIC-Verzeichnis existieren: + +```sh +sudo /usr/local/sbin/mars-publish-mtcp --download +``` + +Dies bezieht mTCP 2025-01-10 und Crynwr aus den FreeDOS-Repositories über HTTPS und vergleicht die publizierten SHA1-Checksummen zur Versions-/Integritätskontrolle (keine Signaturprüfung). Alternativ vertrauenswürdige Original-ZIP-Dateien bereitstellen: + +```sh +sudo /usr/local/sbin/mars-publish-mtcp /pfad/mtcp.zip /pfad/crynwr.zip +``` + +Quellen: https://ibiblio.org/pub/micro/pc-stuff/freedos/files/repositories/latest/html/en/net/mtcp/20250604.0/index.html ; https://ibiblio.org/pub/micro/pc-stuff/freedos/files/repositories/latest/html/en/net/crynwr/20250409.8/index.html ; https://github.com/mbbrutman/mTCP ; https://github.com/fragglet/crynwr_mirror . Lizenz- und Quellcodepflichten der Drittprogramme bleiben bestehen. Die Originalarchive werden unverändert mit abgelegt. Das Paket enthält keine Drittanbieter-DOS-Binärdateien; diese werden beim Publizieren bezogen. Die Downloadfunktion ist hier wegen fehlendem Netzwerkzugriff nicht real ausgeführt worden. + +Der Publisher liest das SYS-Volume aus `nwserv.conf`, erkennt PUBLIC/public, prüft Root-Eigentümer und Schreibrechte und legt ausschließlich ein neues MTCP-Verzeichnis an. Er verweigert bestehende Verzeichnisse und fehlende oder mehrdeutige ZIP-Einträge. Dateien sind 0644, das Verzeichnis 0755. Die tatsächlichen NetWare-Trustee-Rechte zusätzlich prüfen: gewünschte Benutzer/Gruppe benötigen Lesen und File Scan, keinen Schreibzugriff. NetWare-SUPERVISOR bleibt privilegiert. Die SYS-Trustee-Bearbeitung ist im bisherigen MARS-Webfrontend absichtlich geschützt; gegebenenfalls originale NetWare-Verwaltungswerkzeuge verwenden. Kein automatisches Ändern von ACLs oder Login-Skripten. + +Im Login-Skripteditor System- oder Gruppenskript bearbeiten. Für eine Gruppe (Laufwerksbuchstaben bei Bedarf wählen): + +```text +IF MEMBER OF "INTERNET_USERS" THEN + MAP ROOT T:=SYS:PUBLIC\MTCP +END +``` + +Bei einem Gruppenskript im MARS-Editor nur die MAP-Zeile einfügen, der Editor erzeugt den IF-Rahmen. Diese Zuordnung steuert nur die Verteilung der Programme, nicht die Gateway-Berechtigung. Der Gateway-Admin muss die MAC explizit freigeben. Die Gruppe muss vorher existieren. + +Nach dem NetWare-Login an der DOS-Eingabeaufforderung (nicht innerhalb eines separaten LOGIN-Kindprozesses): + +```bat +CALL T:\SETUP.BAT +T:\DHCP.EXE +T:\PING.EXE 1.1.1.1 +T:\PING.EXE example.com +``` + +SETUP kopiert die Konfigurationsvorlage nur, wenn `C:\MTCP\MTCP.CFG` noch nicht existiert, setzt `MTCPCFG` in der aufrufenden DOS-Shell und lädt den IPXPKT-Treiber mit Softwareinterrupt 0x60. Einmal pro Boot ausführen; andere Packet Driver am Interrupt vorher ausschließen. Falls die Netzwerkfreigabe erst noch durch den Administrator erfolgen muss, danach nur DHCP wiederholen. Nach Freigabe kann `CALL T:\START.BAT` in einer lokalen Batchdatei **nach** erfolgreichem LOGIN verwendet werden; START ruft SETUP und DHCP auf. Für einen anderen Netzlaufwerksbuchstaben müssen SETUP.BAT/START.BAT angepasst werden. mTCP verwendet die lokale Konfiguration; kein Client darf eine gemeinsame Konfigurationsdatei überschreiben. Der historische DOS-IPX-Stack und NetWare-Client müssen bereits lokal installiert sein. + +## Abnahme und bekannte Grenzen + +- `make all check check-gateway check-gateway-auto check-native check-supervisor`. +- `sudo cat /run/mars-pcap/gateway`; DHCP-Antwortzähler, `sudo cat /run/mars-pcap/gateway-peers.json` für beobachtete Geräte. +- `ip addr show marsipx0`, `sudo nft list table inet mars_ipxpkt`, `sudo journalctl -u mars_vme -f`. +- In einer isolierten Retro-VM: unbekannter Client (kein DHCP-OFFER), dann Freigabe und DHCP, IP/Mask/Gateway/DNS in lokaler CFG kontrollieren; zweiter Client erhält eine andere IP. Prüfen, dass lokale LAN- und Hostadressen blockiert bleiben, sowie Neustart und stabile Reservierung. +- DHCP- und Route-Tests, GCC-Build des Dispatchers, alte IPX-Tests und Test-ZIP-Publikation wurden lokal ausgeführt. Tatsächlicher CivetWeb-Link, Browser-/TAP-/nftables-/DOS-End-to-End-Test, echte FreeDOS-Downloads und NetWare-Trustees müssen auf dem Zielsystem geprüft werden. MAC-ACLs sind keine Benutzeranmeldung und können nachgeahmt werden. Nicht in untrusted LANs aktivieren. diff --git a/CROSS-BUILD.md b/CROSS-BUILD.md new file mode 100644 index 0000000..5d40c55 --- /dev/null +++ b/CROSS-BUILD.md @@ -0,0 +1,56 @@ +# MARS_NWE-PCAP 0.7 – Linux cross-build preview + +This extends the 0.6 preview without changing the Linux server protocol or creating any additional service. This is a build-enablement release, **not** a complete or certified Windows network driver release. + +## Debian / Ubuntu (x86-64 Linux recommended) + +From the project directory, preferably as a normal user with sudo: + +```sh +./build-windows.sh +``` + +The script installs Clang/LLVM/LLD, i686 MinGW-w64 (including the free DDK-compatible headers and import libraries), and supporting tools via apt. Then it automatically obtains the official Open Watcom snapshot from GitHub and extracts it to `.toolchains/watcom`. No downloaded installer is executed. `make windows-all` does the same. To install dependencies only: `make windows-tools`. + +Open Watcom release URL: https://github.com/open-watcom/open-watcom-v2/releases . The release API selects either `owsnapshot.tar.xz` or `ow-snapshot.tar.xz`. GitHub's published asset SHA-256 is checked if supplied; otherwise the observed digest is recorded, not independently authenticated. Set `WATCOM_SHA256` to enforce a known digest. `WATCOM_TAG` can select a dated official release rather than the mutable `Current-build`. `WATCOM_URL` may select a custom HTTPS mirror, but requires `WATCOM_SHA256`. The URL, tag and digest are recorded in `.toolchains/watcom/ORIGIN.txt`; the cache is reused until manually moved aside. For reproducible builds record the apt package versions and use a pinned Watcom tag and digest. The scripts never download proprietary Microsoft DDK packages or vendor driver binaries. `MARS_TOOLCHAIN_DIR` overrides the cache location. `WATCOM` can reference a preinstalled compiler. On other Linux distributions install equivalent dependencies manually. + +## Build again without network access + +```sh +./build-windows.sh --no-install +make windows95 +make windows98 +make windowsme +make windowsnt4 +make windows2000 +make windowsxp +``` + +Individual targets assume tools have already been installed. `make windows-diag` builds only the freestanding x86 diagnostic. `make windows-watcom` compiles the existing shared IPXPKT C sources into Win32 objects. `make windows-nt5` attempts the native and TAP user-mode bridges and NDIS5 miniport via MinGW-w64. The MinGW DDK include path defaults to `/usr/i686-w64-mingw32/include/ddk`; override via `MINGW_DDK_INCLUDE`. The compiler commands can be overridden via `MINGW_CC`, `MINGW_CXX`, `MINGW_OBJDUMP`. + +## Results + +`build/cross/STATUS.txt` and `build/cross/*.log` show the outcome of each build. Failed builds are not exported as complete driver packages. `build/cross/packages/WIN95`, `WIN98`, `WINME`, `WINNT40`, `WIN2000`, `WINXP` contain the available binaries. `IPXDIAG.EXE` queries the local Winsock IPX provider; no CRT is used. This executable was cross-compiled and checked for PE32/x86 and imports from KERNEL32/WSOCK32 only. It has not been executed on actual Windows. It does not provide Internet access. Run `IPXDIAG.EXE` in a command prompt after installing IPX/SPX and the appropriate Winsock provider. On NT5 the script attempts `MARSNDIS.SYS`, `MARSNDIS.INF`, `MARSIPX.EXE` and `MARSTAP.EXE`. TAP requires an external compatible TAP driver. The native driver source is unchanged except for the kernel include order. MinGW compile/link has not been verified here, and successful linking would not certify old-Windows API compatibility. Review `*.imports.txt` in `build/cross/nt5` and compare against the actual target OS exports; use a VM snapshot before any installation. The modern MinGW CRT may import newer functions than Windows 2000/XP provide. The original VC6/DDK path remains available (see WINDOWS.md). + +Win95/98/ME/NT4: only diagnostic and common protocol code, no own miniport or VxD yet. The older external-filter bridge source remains in `clients/windows/marsnet.cpp` and the original VC6 build script, requiring separately obtained version-matched external SDK/driver. No third-party driver redistribution or unverified SDK download. The source of the NT5 driver is not portable as-is to Win9x/NT4. No automated driver installation or publication takes place by default. + +## Publish + +After verifying the client build and configuring a running MARS gateway, use the existing publisher. For the diagnostic alone: + +```sh +sudo ./publish-winclient.sh build/cross/diag +``` + +This publishes IPXDIAG.EXE for all six systems and generates GATEWAY.INI. For a complete **tested on your target** NT5 candidate, prepare a clean staging folder containing MARSNDIS.SYS, MARSNDIS.INF, MARSIPX.EXE and optionally IPXDIAG.EXE; then pass that directory to the publisher. Existing CLIENTS directories are never overwritten automatically. Verify the NetWare read-only trustees. See WINDOWS.md. Do not publish the untested kernel driver to production users. + +## Linux server + +The previous `./build.sh` and installation workflow remain separate. To build the Linux server from scratch on Debian/Ubuntu: + +```sh +sudo apt install build-essential cmake git pkg-config libpcap-dev libgdbm-dev libcrypt-dev libssl-dev libcivetweb-dev libjson-c-dev cups-client libcups2-dev iproute2 nftables +./build.sh +``` + +The original MARS sources are still fetched and patched by `build.sh`. For an existing 0.6 installation, no server reinstall is needed solely for cross-building Windows clients. The package keeps the existing `mars_vme.service` architecture. diff --git a/DRIVER-RELEASE.md b/DRIVER-RELEASE.md new file mode 100644 index 0000000..7c3c74e --- /dev/null +++ b/DRIVER-RELEASE.md @@ -0,0 +1,68 @@ +# MARS VME 0.8.1: Installation und Treiberfreigaben + +## Fertiges Linux-Paket + +`releases/deb/mars-vme_0.8.1-1_amd64.deb` ist ein nativer Build fuer +**Ubuntu 26.04 amd64**, nicht pauschal fuer alte Debian-/Ubuntu-Versionen. +Die ELF-Abhaengigkeiten werden beim Paketbau aus der Build-Umgebung ermittelt. + +``` +sudo apt install ./releases/deb/mars-vme_0.8.1-1_amd64.deb +``` + +Danach `http://SERVER:8787` im vertrauenswuerdigen LAN oeffnen, mit admin/admin +anmelden und das Kennwort aendern. Vorhandene Kennwoerter und nwserv.conf bleiben +bei Updates erhalten. Zunaechst startet nur das Webfrontend; der NetWare-Server +wird erst nach Einrichtung im Frontend gestartet. Ein vorhandener lokaler +systemd-Override kann Vorrang vor der Paket-Unit haben. + +## Freigabe pro Betriebssystem + +Im Gateway-Dialog **Windows-Clientsoftware / Bereitstellung und Einrichtung** +oeffnen. Betriebssysteme markieren und **Treiberbereitstellung aktivieren**. +Ein bestehendes SYS-Volume mit PUBLIC/public-Verzeichnis ist Voraussetzung; +das DEB legt das Basisvolume fuer Neuinstallationen an. + +Der Button verifiziert ZIPs und enthaltene Dateien anhand SHA-256 und erstellt +`SYS:PUBLIC/DRIVERS//`. Der konkrete MAP-Befehl wird +im Modal angezeigt. Nur ausgewaehlte Plattformen sind per Web-Download freigegeben. +Alte versionierte Laufwerkskopien bleiben als Sicherung bestehen; die Auswahl +ist keine NetWare-ACL und entzieht keine Rechte an alten Versionen. Vorhandene +Volume-Konfiguration und Trustee-Rechte werden nicht automatisch veraendert. +Clients brauchen Read/File-Scan-Rechte, keine Schreibrechte. + +Alle sechs ZIPs liegen auch in `releases/windows/`, mit `SHA256SUMS` und +`manifest.json`. Vor der Installation das OS-Verzeichnis lokal kopieren. +Win95/98/ME/NT4 enthalten INSTALL.BAT und den Original-WinPcap-3.1-Installer. +Windows 2000/XP verwenden den eigenen NDIS5-Pfad ohne WinPcap. +Die echte physische IPX-Node/MAC und die eigene Gateway-Konfiguration sind +weiterhin erforderlich. Details stehen im HTML-Modal und in den ZIPs. + +## Reproduzieren + +``` +./build-windows.sh --with-legacy-ddk +python3 cross/package-drivers.py +./build.sh +python3 packaging/build-deb.py +``` + +Bei vorhandenem upstream/patched/build nicht blind rebuild.sh aufrufen: +eigene Aenderungen zuerst sichern. Ein versehentlich eingecheckter Gitlink +auf den generierten Upstream-Baum wurde entfernt; build.sh erzeugt ihn neu. +Originalquellen werden ueber den dokumentierten GitHub-Upstream bezogen. +Toolchain-Caches und lokale DDK-Archive werden nicht zusaetzlich veroeffentlicht. +Bereits zuvor im Remote vorhandene windll-Archive bleiben unveraendert. + +## Pruefstatus + +Cross-Build aller sechs Ziele, PE-Strukturpruefungen, Linux-Kerntests, +CivetWeb-HTTP-Tests einschliesslich Login/CSRF und freigegebener/gesperrter +Downloads sowie isolierter ZIP-Publisher-Test bestanden. +Alle sechs verwendeten HTTP-Quellendpunkte antworteten bei der Linkpruefung +am 2026-11-27 mit HTTP 200. WinPcap-Pruefsummen sind lokal gemessene Pins vom +offiziellen HTTPS-Wireshark-Archiv, keine unabhaengige Herstellersignatur. +Chromium-Test mit simulierter API: Auswahl zweier Betriebssysteme, Aktivierung, +Downloadfilter und MAP-Anzeige bestanden. +Windows-Installation, Paketinstallation auf einem zweiten Linux-Rechner und +realer IPX-/NetWare-Netzwerkbetrieb sind noch nicht abgenommen. diff --git a/GATEWAY.md b/GATEWAY.md new file mode 100644 index 0000000..718e626 --- /dev/null +++ b/GATEWAY.md @@ -0,0 +1,120 @@ +# MARS_NWE-PCAP 0.5.1 – IPXPKT / TAP Gateway + +**Update 0.5.1:** [Automatische Netzwerkerkennung, DHCP-Reservierungen und mTCP-Verteilung](AUTOSETUP.md). Die neue Anleitung ersetzt ältere Aussagen über fehlendes DHCP und ausschließlich manuelle IP-Konfiguration. + +## Stand und Ziel + +Dieses Update basiert auf dem 0.4-Quellpaket. IPXPKT läuft direkt im bestehenden nativen `mars-pcapd`, die Konfiguration über das in `mars_vme` eingebettete CivetWeb. Ein zusätzlicher Gateway-, DNS- oder Web-Dienst ist nicht erforderlich. Linux übernimmt IPv4-Routing/NAT; das kurzlebige Hilfsskript nutzt iproute2 und nftables. Es wird kein IPX-Kernelmodul benötigt. Der NetWare-Teil von 0.4 bleibt unverändert. + +Der Gateway ist standardmäßig aus. Implementiert sind IPXPKT-Frames mit und ohne 32-Byte-Trailer (Sockets 0x6181/0x6180), bis zu drei Fragmente pro Ethernetframe, zeitlich begrenzte Reassemblierung, lokale TAP-Kopplung, IPv4/ARP-Prüfung, statische Client-Zuweisungen, NAT, Web-/DNS-/ICMP-Firewall und Webkonfiguration. Ein reales DOS-System wurde hier noch nicht getestet. Kein DHCP, keine Bindery-basierte Gateway-Authentifizierung, kein eigener DNS-Proxy, keine Novell-Winsock-Gateway-/RFC-1791-Implementierung. IPXPKT ist nicht der Novell IPX/IP Gateway Client. + +## 1. Bestehende 0.4-Installation aktualisieren + +Unter Debian/Ubuntu im neuen Quellverzeichnis (nicht über das bestehende Projekt entpacken): + +```sh +sudo apt install build-essential pkg-config libjson-c-dev libssl-dev libcivetweb-dev iproute2 nftables +make all native check check-gateway check-native check-supervisor +sudo ./install-gateway.sh +sudo systemctl start mars_vme.service +``` + +Das Upgrade stoppt `mars_vme.service`, sichert die beiden alten Programme und Webdateien unter `/var/lib/mars-vme/pre-gateway-*`, installiert die neuen Programme und das Hilfsskript. `nwserv`, `nwserv.conf`, Volumes, Bindery, Druckadapter, Kennwort und Login-Skripte bleiben erhalten. Der bestehende Original-MARS-Build muss nicht wiederholt werden. Der ausgegebene Sicherungspfad dient zum Rollback (Dienst stoppen; aus der Sicherung `mars_vme` und `mars-pcapd` nach `/usr/local/sbin/` und Inhalt von `www/` nach `/usr/local/share/mars-vme/www/` zurückkopieren; Dienst starten). Die Gateway-Konfiguration bleibt beim Rollback liegen, wird aber von 0.4 nicht gelesen. + +Für Neuinstallation zusätzlich die Pakete aus GUIDE.md installieren und `./build.sh`, `sudo ./install.sh`, `sudo systemctl enable --now mars_vme.service` verwenden. Bei einem System ohne Gateway-Funktion braucht nftables nicht aktiv zu sein. `libcivetweb-dev` muss verfügbar sein, auch wenn der Server bisher installiert war. `build.sh` prüft die wesentlichen Build-Abhängigkeiten vorab. + +## 2. Host vorbereiten + +Vorzugsweise eine dedizierte Linux-VM in einem isolierten Retro-LAN verwenden. Auf gemeinsam genutzten Hosts (z. B. Kubernetes) können CNI, Policy-Routing, bestehende Firewalls und globale Forwarding-Einstellungen kollidieren. Keine unüberlegte Firewall- oder Netzkonfigurationsänderung auf dem Produktionshost. + +```sh +ip -br link +ip -4 route show table all +ls -l /dev/net/tun +sysctl net.ipv4.ip_forward +sudo nft list ruleset +``` + +Falls `/dev/net/tun` fehlt und der Host dies unterstützt: `sudo modprobe tun`. Der Dienst benötigt root, CAP_NET_ADMIN und CAP_NET_RAW; ein eingeschränkter Container braucht zusätzlich Zugriff auf `/dev/net/tun`. Der Gateway schaltet das globale Forwarding **nicht** selbst um. Falls erforderlich, nach Prüfung der gesamten Host-Firewall bewusst aktivieren: + +```sh +sudo sysctl -w net.ipv4.ip_forward=1 +``` + +Die Einstellung ist global und betrifft nicht nur MARS. Bestehende Forwarding- und Firewallregeln nicht überschreiben. Falls dauerhaft gewünscht, auf einem dafür vorgesehenen Router/VM über dessen bestehende sysctl-Verwaltung konfigurieren. Auf einem Host, der vorher nicht routete, nach dem Test die ursprüngliche Einstellung wiederherstellen. Der Dienst verändert keine globale sysctl-Konfiguration. + +## 3. Webfrontend + +`http://SERVER-IP:8787` öffnen, anmelden (vorheriges Kennwort bleibt erhalten). Dashboard → **Internet & Gateway**. + +- Gateway aktivieren, ein gespeichertes externes IPX-Netz (Abschnitt 4 in `nwserv.conf`) auswählen; nur direkt angeschlossene Ethernet-IPX-Clients in diesem Netz. +- Uplink auswählen, z. B. `enp4s0`. Er kann mit der physischen IPX-Schnittstelle identisch sein, getrennte Netzsegmente sind jedoch empfehlenswert. +- Gateway-Adresse `10.250.0.1`, Netzmaske `/24`. Andere freie RFC1918-/24-Netze mit Gateway .1 sind möglich. Die Schnittstelle `marsipx0` wird vom Dispatcher beim Start erzeugt. Überlappende bestehende IPv4-Routen werden abgelehnt; ein CNI-/Policy-Routing-Setup dennoch separat prüfen. +- Öffentlicher DNS, z. B. `1.1.1.1`, TCP/UDP 53 nur zu dieser Adresse; TCP 80/443 und ICMP Echo optional. Kein FTP (Port 21), SMTP, Telnet oder SMB in diesem Stand. DNS direkt zum Resolver über NAT, kein DNS-Dienst im MARS-Prozess. +- Clientliste: je Zeile MAC/NetWare-Node (12 Hex-Zeichen, auch Eingabe mit Doppelpunkt möglich), Leerzeichen, feste Client-IP. Beispiel `001122334455 10.250.0.10` (durch die tatsächliche Client-MAC ersetzen). Kein DHCP, maximal 64 Zuweisungen. Die IPX-Node, äußere Quell-MAC und emulierte Ethernet-Quell-MAC müssen übereinstimmen. Die IPX-Netznummer muss zum ausgewählten Frame-Typ des Clients passen. Keine gerouteten oder ARCNET-artigen IPX-Nodes. +- Speichern. Änderungen werden erst nach explizitem **NetWare neu starten / anwenden** wirksam. Die Webadministration bleibt erreichbar. Status aktualisieren. + +Die neue Konfiguration wird getrennt von `nwserv.conf` als `/usr/local/etc/mars_nwe/ipxpkt.json` gespeichert (0600), die vorherige Version als `ipxpkt.json.previous`. Sie sollte in Git ignoriert werden. Beispiel `ipxpkt.json.example` ist als Vorlage enthalten. Fehlende Datei bedeutet deaktiviert. + +## 4. DOS-Client + +Benötigt eine funktionierende IPX-Umgebung (z. B. LSL, Netzwerkkartentreiber, IPXODI sowie optional den NetWare-Client) und die dazu passende `IPXPKT.COM`-Version. Die DOS-Software nutzt einen virtuellen Packet Driver. Quellen: https://github.com/fragglet/crynwr_mirror/blob/main/ipxpkt.asm ; Referenz: https://github.com/fragglet/ipxbox/blob/trunk/BRIDGE-HOWTO.md . Die Clientdateien sind aus Lizenz-/Vertriebsgründen nicht im Archiv enthalten. + +Auf dem Client im echten DOS, nachdem IPX funktioniert: + +```bat +IPXPKT -i 0x60 +``` + +Die ausgegebene Ethernet-MAC mit der NetWare-Node bzw. physischen MAC vergleichen und im Webfrontend freigeben. Die virtuelle MAC muss identisch sein, keinen -n-Modus mit verändertem MAC-Suffix nutzen. `0x60` ist ein Beispiel; einen freien Software-Interrupt verwenden. Der Treiber muss volle Ethernetframes fragmentieren können. Windows-Winsock wird hierdurch nicht ersetzt; insbesondere ist ein Windows-9x-DOS-Fenster nicht als kompatibel vorausgesetzt. + +Für mTCP (https://www.brutman.com/mTCP/) z. B. `C:\MTCP\MTCP.CFG` anlegen: + +```text +PACKETINT 0x60 +HOSTNAME DOSCLIENT +IPADDR 10.250.0.10 +NETMASK 255.255.255.0 +GATEWAY 10.250.0.1 +NAMESERVER 1.1.1.1 +MTU 1500 +``` + +```bat +SET MTCPCFG=C:\MTCP\MTCP.CFG +C:\MTCP\PING.EXE 1.1.1.1 +C:\MTCP\PING.EXE example.com +``` + +Nicht `DHCP.EXE` verwenden. Ping zum Gateway `10.250.0.1` selbst ist absichtlich gesperrt (Host-Firewall); der ARP-Austausch ist hingegen erforderlich und erlaubt. Externe Server können ICMP ebenfalls sperren, deshalb bei Bedarf ein HTTP-Client-Programm testen. Moderne TLS-Anwendungen können auf DOS trotz TCP-Verbindung scheitern. Der Gateway macht alte Browser nicht TLS-kompatibel. + +## 5. Diagnose und Abnahme auf dem Zielsystem + +```sh +sudo systemctl status mars_vme +sudo journalctl -u mars_vme -n 100 --no-pager +ip -br addr show marsipx0 +sudo cat /run/mars-pcap/gateway +sudo nft list table inet mars_ipxpkt +ip -4 neigh show dev marsipx0 +``` + +Bei realem DOS-Traffic RX fragments, RX frames, TX frames und rejected/dropped beobachten. Optional `tcpdump -ni marsipx0 'arp or ip'` und `tcpdump -ni enp3s0 'ether proto 0x8137 or ether[12:2] <= 1500'` verwenden (zweiter Filter umfasst auch Nicht-IPX-802.3-Frames; `enp3s0` ersetzen). Erwartet: ARP-Anfrage des Clients auf TAP, ARP-Antwort, anschließende IP-Pakete über TAP, NAT am Uplink, Antwort zurück zum DOS-Client. Tests: korrekte MAC/IP funktioniert; unfreigegebene oder falsche MAC/IP nicht; DNS nur zur konfigurierten Adresse; private Zieladresse bzw. Linux-Webport 8787 über TAP nicht erreichbar; bestehender NCP-Dateizugriff funktioniert weiter. Prüfen, dass kein anderer Firewallmanager die MARS-Tabelle entfernt bzw. widersprechende NAT-/DNAT-Regeln einsetzt. `nft`-Accept in einer Base Chain setzt keine späteren Drop-Regeln außer Kraft. + +Bei `TAP/firewall setup failed`: Journal prüfen. Mögliche Gründe: fehlendes nft/ip, fehlende Rechte, vorhandene virtuelle Schnittstelle, überlappendes Netz, deaktiviertes Forwarding, verbliebene Firewalltabelle. Die Einrichtung lässt die TAP-Schnittstelle erst nach installierter Firewall hochgehen. Fehlschlag deaktiviert nur Gateway, nicht NetWare. Bei ordentlichem Stopp verschwindet die nichtpersistente TAP-Schnittstelle; die eigene nftables-Tabelle wird gelöscht. Nach einem harten Prozessabbruch kann die Tabelle übrig bleiben. Erst `mars_vme` stoppen, `ip link show marsipx0` prüfen (soll nicht existieren) und eigene Tabelle inspizieren; nur wenn sie nachweislich verwaist ist: `sudo nft delete table inet mars_ipxpkt`. Keine globale Firewall leeren. Dann Dienst starten. + +Gateway deaktivieren: Schalter im Modal aus → speichern → NetWare neu starten. Bei Notfall gesamten `mars_vme.service` stoppen. Der globale Forwarding-Wert bleibt unverändert. + +## 6. Sicherheits- und Protokollgrenzen + +IPXPKT ist unverschlüsselt und nicht authentifiziert. Die Gerätefreigabe prüft MAC, IPX-Node und feste IP gegen Spoofing-Fehler, schützt aber nicht gegen einen Angreifer, der alle drei Werte fälscht. Sie ersetzt keine Benutzer-/Gruppenrechte. Keine vertraulichen Anmeldungen und keine öffentliche Freigabe. Die nftables-Regeln blockieren Host-Zugriff, private/reservierte Zielnetze und nicht erlaubte Ports, sind aber kein vollständiger Sicherheitsperimeter für intern geroutete öffentliche Adressräume. Für solche Netze zusätzliche Egress-Regeln und Segmentierung vorsehen. Keine direkte TAP-Bridge in das LAN. Der Dienst beansprucht eine eigene Tabelle `inet mars_ipxpkt`, verändert keine fremden Tabellen und setzt keinen globalen Forwarding-Wert. Die übliche Paketfilterung und die tatsächliche Client-Kompatibilität müssen auf dem Zielsystem abgenommen werden. + +## 7. Tests und Quellen + +`make check-gateway` prüft beide IPXPKT-Formate, little-endian Fragment-ID, Fragmentierung, Reassemblierung in anderer Reihenfolge, doppelte Fragmente, Timeout, 500 aufeinanderfolgende Pakete, fehlerhafte Pakete, Konfigurations- und MAC/IP-/ARP-Regeln. Frame- und Offline-IPC-Tests wurden wiederholt; der Gateway-Modal-Test nutzt eine simulierte API. Der echte CivetWeb-Link und TAP/nftables-Betrieb sowie die originalen NetWare-Clients waren in der Entwicklungsumgebung nicht verfügbar. Siehe TEST-RESULTS.txt. + +Protokollreferenzen (eigene C-Implementierung, keine Go-Runtime): +- Crynwr IPXPKT ASM: https://github.com/fragglet/crynwr_mirror/blob/main/ipxpkt.asm +- ipxbox IPXPKT Router, Header, Fragmentierung: https://github.com/fragglet/ipxbox/tree/trunk/module/ipxpkt +- Linux TUN/TAP: https://docs.kernel.org/networking/tuntap.html +- mTCP: https://www.brutman.com/mTCP/ diff --git a/GUIDE.md b/GUIDE.md index d41476b..b4ea1da 100644 --- a/GUIDE.md +++ b/GUIDE.md @@ -1,4 +1,8 @@ -# MARS_NWE-PCAP 0.4 – Einrichtungs- und Abnahmeguide +# MARS_NWE-PCAP 0.5.1 – Einrichtungs- und Abnahmeguide + +**Update 0.5.1:** [Automatische Netzwerkerkennung, DHCP-Reservierungen und mTCP-Verteilung](AUTOSETUP.md). Die neue Anleitung ersetzt ältere Aussagen über fehlendes DHCP und ausschließlich manuelle IP-Konfiguration. + +**Neu in 0.5:** natives IPXPKT/TAP-Gateway im Dispatcher und Webmodal. Anleitung, Upgrade ohne Original-MARS-Neubuild und Grenzen siehe [GATEWAY.md](GATEWAY.md). Gateway ist standardmäßig deaktiviert. Entwicklungsstand: 26.11.2026. Native Edition mit CivetWeb im einzigen Dienst `mars_vme.service`. Die Portierung ist ein Quellcode-/Integrationspaket, noch kein abgenommener NetWare-Server. Siehe TEST-RESULTS.txt. @@ -9,7 +13,7 @@ Debian/Ubuntu (Paketnamen können je Distribution abweichen): ```sh sudo apt update sudo apt install build-essential cmake git pkg-config libpcap-dev \ - libgdbm-dev libcrypt-dev libssl-dev libcivetweb-dev libjson-c-dev cups-client + libgdbm-dev libcrypt-dev libssl-dev libcivetweb-dev libjson-c-dev libcups2-dev cups-client iproute2 nftables # Optional lokaler CUPS-Scheduler: # sudo apt install cups # Optional HTTP-Abnahmetest: diff --git a/LEGACY-BUILD.md b/LEGACY-BUILD.md new file mode 100644 index 0000000..6951e2e --- /dev/null +++ b/LEGACY-BUILD.md @@ -0,0 +1,159 @@ +# MARS_NWE-PCAP 0.8 – Legacy NDIS preview + +## Stand und Zweck + +Fortsetzung des vollständigen Quellpakets 0.7. Der Linux-Server und sein einziger Dienst `mars_vme.service` bleiben unverändert. Diese Ausgabe ist KEIN fertig installierbares Windows-Treiberrelease. Es gibt einen neuen eigenen NDIS-3.0-Miniport-Quellcode (serialized Ethernet adapter), gemeinsamen Frame-Kern, einen Win9x-INF-Entwurf und eine tatsächlich unter Linux erzeugte CRT-freie Windows-Bridge. Der NDIS3-Miniport und der bisherige NDIS5-Miniport konnten hier nicht mit den echten DDKs gelinkt oder unter Windows getestet werden. + +## Ein Befehl (Debian/Ubuntu, vorzugsweise normaler Benutzer auf Build-VM) + +Nach Prüfung der Rechte und Herkunft der historischen DDK-Archive: + +```sh +./build-windows.sh --with-legacy-ddk +``` + +Dieser explizite Schalter erlaubt den automatischen Bezug inoffizieller DDK-Archivkopien; es wird kein Windows-Installer unter Linux ausgeführt. APT wird über sudo aufgerufen, der übrige Build sollte unprivilegiert laufen. Downloads können erheblich sein. Alte Archive sind keine vertrauenswürdigen, aktuell signierten Softwarepakete. Die Checksumme eines Archivbetreibers sichert nur den konkreten Bezug, nicht die Malwarefreiheit oder Lizenz. Die DDKs bleiben lokal unter `.toolchains/legacy` und dürfen nicht automatisch mit dem eigenen Git-Projekt oder SYS-Volume veröffentlicht werden. + +Einzelne Schritte: + +```sh +./cross/install-tools.sh +./cross/fetch-legacy.sh --accept-archive +./cross/extract-nt4.sh +make windows-legacy +./build-windows.sh --no-install WIN95 +./build-windows.sh --no-install WIN98 +./build-windows.sh --no-install WINME +./build-windows.sh --no-install WINNT40 +./build-windows.sh --no-install WIN2000 +./build-windows.sh --no-install WINXP +``` + +`make windows-all-legacy` ist gleichwertig zum ersten Befehl. `make windows-legacy-bridge` baut MARSNET.EXE unabhängig vom DDK. `make check-legacy` prüft den gemeinsamen C-Kern. + +## Quellen + +- Windows NT 4.0 DDK: `https://github.com/KunYi/WDK_DDKArchive/releases/tag/NT4_DDK`, Asset `winnt40.ddk.iso` (inoffizielles, laut Herausgeber nicht geprüftes Archiv). Dient als historische NDIS-Header-/x86-Importbibliotheksbasis für den NDIS3-Build. +- Windows 98 DDK: `https://github.com/KunYi/WDK_DDKArchive/releases/tag/Win98DDK`, Asset `win98ddk.exe`. Archiv wird geladen, derzeit nur als Referenz vorgehalten, nicht ausgeführt oder als aktiver Build-Input benutzt. +- Windows 95 DDK: `https://winworldpc.com/download/3d026713-18c3-9a11-c3a4-e284a2c3a570`. Mirror mit dort veröffentlichter SHA-512. Referenzarchiv, nicht aktiver Build-Input. +- WinPcap 3.1: `https://github.com/wireshark/winpcap/releases/tag/WINPCAP_3_1`. Open-source-Referenz für die Packet.dll-OID-Schnittstelle. Insbesondere `Common/Packet32.h`, `Packet9x/DLL/Packet32.c`. Wird per Git-Tag bezogen; Commit wird protokolliert. Die neue Bridge nutzt die öffentliche API dynamisch, nicht kopierten WinPcap-Quellcode. Der WinPcap-VxD/NT-Protokolltreiber wird in diesem Projekt noch nicht aus Quellen gebaut. +- NDIS3 Miniport Referenz: `https://techshelps.github.io/MSDN/WIN95DDK/HTML/S2D14.HTM` und `https://learn.microsoft.com/en-us/windows-hardware/drivers/network/overview-of-ndis-versions`. +- Open Watcom 2: vorhandenes 0.7-Skript, automatischer Bezug. Der neue NDIS3-SYS-Build benutzt Clang-CL/LLD statt Watcom (COFF/PE und Microsoft-Deklarationen). Watcom wird für die gemeinsame Protokollbasis eingesetzt. NT5 nutzt MinGW. + +SHA-256-Overrides: `NT4_DDK_SHA256`, `WIN98_DDK_SHA256`. Wenn keine unabhängig bekannte bzw. vom GitHub-Asset bereitgestellte Prüfsumme vorhanden ist, wird der Bezug als UNVERIFIED gekennzeichnet. Bei vorgegebenem Hash wird ein Mismatch abgelehnt. Keine DDK-/WinPcap-Binärdateien liegen im ausgelieferten Source-Tarball. + +## Abweichende DDK-Layoutvarianten + +Das Extraktionsskript versucht ISO/CAB/Einzeldatei-Extraktion mit 7z und cabextract. Das konkrete historische Archiv konnte hier nicht heruntergeladen werden. Bei nicht unterstützten Archivlayouts können bereits legal beschaffte, extrahierte x86-Dateien explizit gesetzt werden: + +```sh +NT4_DDK_INCLUDE=/opt/ddk4/inc:/opt/ddk4/inc/ddk \ +NT4_NDIS_LIB=/opt/ddk4/lib/i386/ndis.lib \ +make windows-legacy +``` + +Pfade sind Beispiele. Das Skript erzeugt eine temporäre case-insensitive Include-Kopie durch Original-/Klein-/Großschreibungs-Aliase. Mehrdeutige Dateien werden abgelehnt. Bei weiteren Include-Unterordnern oder alten Compiler-Erweiterungen kann eine Anpassung nötig sein. Der Linker akzeptiert hier nur NDIS.SYS-Imports, keine NTOSKRNL- oder CRT-Importbibliotheken. Das ist notwendig, aber nicht hinreichend für Win9x-Ladefähigkeit. Keine Aussage über genaue NDIS-Miniport-Block-Offsets zwischen Win95 und NT4 ohne VM-Test. + +## Treiberpfad für alte Clients + +Windows TCP/IP -> MARSNET3.SYS (eigener NDIS3-Miniport) -> private OIDs über den vorhandenen WinPcap 3.1-Protokolltreiber (NPF.VXD bzw. NPF.SYS) -> MARSNET.EXE (eigene Win32-IPXPKT-Bridge) -> physischer IPX-Stack -> MARS-Gateway. + +Der NDIS3-Kern enthält Initialize/Halt, Send, TransferData, Query/SetInformation, Reset, Empfang über Miniport-Timer, Frame-Queue, Ethernet-Filter und eine Bridge-Lease. Der alte NDIS3-Sende-/Empfangspfad ersetzt NDIS5-Paket-Callbacks. Ein separater NDIS4-Miniport ist zunächst nicht vorgesehen; NDIS3 ist das Kompatibilitätsziel, nicht ein bewiesenes Ergebnis. Das Win9x-INF ist ein Entwurf und NT4-OEMSETUP.INF fehlt. Kein selbst entwickelter VxD oder NT4-IOCTL-Treiber vorhanden. WinPcap ist deshalb eine ausdrücklich vorläufige Fremdabhängigkeit, kein Bestandteil des Linux-Servers. + +Die Bridge prüft die MARS-Kennung und die konfigurierte MAC vor ihren privaten OID-Schreiboperationen. Das ist keine Authentifizierung gegen andere lokale NDIS-Protokolle. WinPcap selbst kann rohe Frames austauschen; alte Windows-Systeme bieten nur schwache lokale Sicherheit. Nur isolierte Retro-LANs/VMs, keine produktiven Netzwerke. Ein VM-Snapshot ist vor Treibertests erforderlich; insbesondere Timer-Abbau, Miniport-ABI, INF-Installationsmechanik und Reboot/Deinstallation sind noch ungeprüft. Die vorhandene TCP/IP-Bindung der physischen Karte wird nicht automatisch entfernt. + +WinPcap 3.1 muss separat installiert sein. Optional kann die historische Wireshark-Distribution (0.99.4 enthält laut historischer Dokumentation WinPcap 3.1) heruntergeladen und mit 7z nur entpackt werden, wenn eine aus vertrauenswürdiger Quelle bezogene SHA-256 vorliegt: + +```sh +MARS_FETCH_WINPCAP_BINARY=1 WINPCAP_BUNDLE_SHA256=<64-hex> \ +./cross/fetch-legacy.sh --accept-archive +``` + +Das Skript sucht anschließend den enthaltenen WinPcap-Installer, führt ihn aber nicht aus. Falls 7z die NSIS-Datei nicht unterstützt oder das Paket anders aufgebaut ist, muss der kompatible WinPcap-Treiber separat beschafft werden. WinPcap ist nicht mehr gepflegt. + +## Ausgaben und Start (erst nach Treiber-Abnahme) + +`build/cross/STATUS.txt`, `legacy.log`, `legacy-bridge.log`, `nt5.log` sowie `packages/WIN95`, `WIN98`, `WINME`, `WINNT40`, `WIN2000`, `WINXP`. Nicht vollständig gebaute Treiber werden nicht als fertige Installationspakete bezeichnet. NT4 wird ohne OEMSETUP nicht als erfolgreicher vollständiger Build gewertet. + +Nur in isolierter VM mit kompatiblem installiertem WinPcap und manuell eingerichtetem virtuellen Adapter: MAC `NetworkAddress` muss exakt der physischen IPX-Node entsprechen (12 Hexzeichen); TCP/IP ausschließlich an den virtuellen Adapter binden, IPX auf der physischen Karte belassen. GATEWAY.INI stammt vom vorhandenen Publisher. Kein automatischer Treiberinstaller enthalten. + +```bat +IPXDIAG.EXE +MARSNET.EXE --list +MARSNET.EXE --discover 001122334455 GATEWAY.INI +MARSNET.EXE --run "" 001122334455 GATEWAY.INI --confirm-virtual +``` + +Danach Gerät am MARS-Gateway freigeben, DHCP für den virtuellen Adapter erneuern und Ping/DNS/HTTP testen. IPXDIAG und Discovery allein beweisen keine Tunnelverbindung. MARSNET.EXE kann für die Discovery bereits ohne Miniport verwendet werden. + +Optionaler Vorschau-Publisher für Win9x (erst nach erfolgreichem Build und Prüfung in VM, bestehende CLIENTS-Freigabe vorher sichern): + +```sh +sudo env MARS_ALLOW_PREVIEW=1 ./publish-winclient.sh build/cross/legacy +``` + +Keine NT4-Installation und keine Drittanbieterpakete werden mit diesem Aufruf verteilt. NT5 weiterhin über den bisherigen Publisher mit `build/cross/nt5` (nicht gleichzeitig in bestehende CLIENTS-Freigabe schreiben). Alle MARS-Komponenten bleiben unter dem bisherigen Serverdienst; für reine Windows-Client-Entwicklung muss der Linux-Dienst nicht neu gebaut werden. + +## Was hier tatsächlich getestet wurde + +- CRT-freier MARSNET.EXE Cross-Build mit Clang/LLD (PE32 x86, Subsystem 4.0; statische Imports KERNEL32.DLL/WSOCK32.DLL, Packet.dll dynamisch). Keine Windows-Ausführung. +- IPXDIAG.EXE Cross-Build. +- C89-Linux-Tests des gemeinsamen Legacy-Kerns und bestehende Gateway/IPXPKT/DHCP/Frame-Tests. +- Shell-Syntaxprüfung, Python-Syntaxprüfung, Publisher mit Testdateien. +- Der echte NDIS3-Build scheitert hier an fehlendem NT4-DDK, der NT5-Build an fehlendem MinGW. Der Downloadversuch scheitert an DNS/Netzwerkzugriff. Historische Win9x-/NT4-Installer, VxD-Ersatz, WinPcap-Cross-Build und alle VM-Tests bleiben offen. + +## Build-Reparatur 2026-11-27 + +Auf diesem Host wurden NDIS3 und NDIS5 sowie die Bridges und IPXDIAG erfolgreich +kompiliert, gelinkt und mit verify-pe.py strukturell geprüft. `make check-legacy` +besteht. Die älteren Angaben zu fehlenden Downloads oben beschreiben den vorherigen Stand. + +Korrekturen: Windows-95-DDK über Gitea-Raw-Link (SHA-512 geprüft), bevorzugte +NT4-i386/free-Importbibliothek, ergänzende MinGW-CRT-Includes für Clang und +kein vorangestelltes ntddk.h im BINARY_COMPATIBLE-NDIS3-Pfad. +`cross/prepare-mingw-ddk.py` korrigiert die MinGW-DDK-Header ausschließlich in +build/cross/nt5/ddk: Vista-Versionsmakro, doppelte NDIS_REQUEST_TYPE-Definition +und fehlendes Komma in NdisMWanIndicateReceiveComplete. Systemheader und +Originalarchive bleiben unverändert. + +Aufruf: `./build-windows.sh --no-install`. Binärdateien stehen unter +`build/cross/packages//`. Der Gesamtlauf liefert weiterhin Exit 1, +weil das NT4-OEMSETUP-Installationspaket noch fehlt; dies ist kein Compilerfehler. +Die einzelnen übrigen Ziel-Builds sind davon unabhängig. Keine Windows-Laufzeittests +oder Treiberinstallation durchgeführt; die Pakete bleiben Entwicklungskandidaten. + + +## NT4-OEMSETUP-Generator (2026-11-27) + +`cross/generate-nt4-inf.py` erzeugt nun beim WINNT40-Build eine +`build/cross/packages/WINNT40/OEMSETUP.INF` aus dem lokalen DDK-Ethernetbeispiel. +Damit entfaellt der bisherige Fehlerstatus allein wegen fehlender OEMSETUP. +Das ist ein **ungetesteter Installationskandidat**, keine NT4-Abnahme. +Die frueheren Hinweise auf die fehlende Datei beschreiben den vorherigen Stand. + +Vor Installation muss `NetworkAddress` unter `[FileConstants]` auf die echte +physische IPX-Node gesetzt werden. Ohne Adresse bricht das Setup explizit ab. +Alternativ vor dem Build `MARS_NT4_NETWORK_ADDRESS` (12 Hexzeichen, Unicast) +setzen. Details: `clients/windows/ndis3/NT4-INSTALL.txt` und Kopie im Paket. +Der Generator entfernt ISA-Ressourcenerkennung und verwendet Internal-Bus, +NDIS-Dienst sowie Ethernet-Bindings. NT4-eigene Setup-Hilfsdateien bleiben +Voraussetzung. Generierte Dateien sind vom lokal bereitgestellten DDK-Beispiel +abgeleitet; das DDK selbst wird nicht in den Quellen mitgeliefert. + + +## WinPcap-Installer im Legacy-Paket + +`cross/fetch-winpcap.sh` bezieht Wireshark 0.99.4 vom offiziellen HTTPS-Archiv +und extrahiert ausschliesslich den unveraenderten WinPcap-3.1-Installer. +Die SHA-256-Pins wurden am 2026-11-27 am Download gemessen (keine unabhaengige +Herstellersignatur). Die Herkunft steht im Paket in WPCAP31.TXT. +WIN95/WIN98/WINME/WINNT40 erhalten WPCAP31.EXE und INSTALL.BAT. Kopiere das +komplette Verzeichnis lokal, wechsle hinein und starte INSTALL.BAT. +Der Original-Wizard zeigt seine Lizenz und installiert die OS-spezifischen +Komponenten. Kein Silent-Install und keine automatische Netzwerkumbindung. +MARS-Adapter danach manuell installieren; NT4 siehe NT4-INSTALL.txt. +Windows-2000/XP-Pakete nutzen den eigenen NDIS5-Pfad und erhalten keinen +unnoetigen WinPcap-Installer. Der Publisher publish-winclient.sh wurde nicht +ausgefuehrt; es erfolgte keine Veroeffentlichung auf SYS:PUBLIC. +Offline-Builds benoetigen den zuvor gefuellten Cache; Online-Vorbereitung: +`./cross/fetch-winpcap.sh`. Windows-Ausfuehrung bleibt ungetestet. diff --git a/Makefile b/Makefile index f975f69..12b33dc 100644 --- a/Makefile +++ b/Makefile @@ -5,8 +5,8 @@ CPPFLAGS += -D_DEFAULT_SOURCE all: build/mars-pcapd build/libmarspcap.a build: mkdir -p $@ -build/mars-pcapd: src/broker.c src/wire.c src/pcap_dyn.c src/wire.h src/pcap_dyn.h | build - $(CC) $(CPPFLAGS) $(CFLAGS) -std=c11 src/broker.c src/wire.c src/pcap_dyn.c -ldl -o $@ +build/mars-pcapd: src/broker.c src/wire.c src/pcap_dyn.c src/ipxpkt.c src/gateway.c src/dhcp.c src/gateway_config.c src/gateway.h src/ipxpkt.h src/wire.h src/pcap_dyn.h | build + $(CC) $(CPPFLAGS) $(CFLAGS) -std=c11 src/broker.c src/wire.c src/pcap_dyn.c src/ipxpkt.c src/gateway.c src/dhcp.c src/gateway_config.c $(shell pkg-config --cflags --libs json-c) -ldl -o $@ build/shim.o: src/shim.c src/shim.h src/wire.h | build $(CC) $(CPPFLAGS) $(CFLAGS) -std=c11 -c $< -o $@ build/libmarspcap.a: build/shim.o @@ -27,8 +27,8 @@ NATIVE_FLAGS = $(shell pkg-config --cflags json-c openssl) NATIVE_LIBS = $(shell pkg-config --libs json-c openssl) -pthread .PHONY: native check-native native: build/mars_vme build/mars-print -build/mars_vme: native/main.c native/core.c native/supervisor.c native/admin.c native/printing.c native/core.h native/supervisor.h native/admin.h | build - $(CC) $(CFLAGS) -std=c11 $(NATIVE_FLAGS) $(CIVET_CFLAGS) native/main.c native/core.c native/supervisor.c native/admin.c native/printing.c -o $@ $(CIVET_LIBS) $(NATIVE_LIBS) -ldl +build/mars_vme: native/main.c native/core.c native/supervisor.c native/admin.c native/printing.c native/gateway_auto.c src/gateway_config.c src/gateway.h native/gateway_auto.h native/core.h native/supervisor.h native/admin.h | build + $(CC) $(CFLAGS) -std=c11 $(NATIVE_FLAGS) $(CIVET_CFLAGS) native/main.c native/core.c native/supervisor.c native/admin.c native/printing.c native/gateway_auto.c src/gateway_config.c -o $@ $(CIVET_LIBS) $(NATIVE_LIBS) -ldl build/test-native: tests/test_native.c native/core.c native/core.h | build $(CC) $(CFLAGS) -std=c11 -Inative $(NATIVE_FLAGS) tests/test_native.c native/core.c -o $@ $(NATIVE_LIBS) check-native: build/test-native @@ -64,3 +64,62 @@ check-trustee: build/test-trustee ./build/test-trustee build/test-trustee: tests/test_trustee.c upstream-adapter/mars_trustee.inc | build $(CC) $(CFLAGS) -std=c11 tests/test_trustee.c -o $@ + +.PHONY: check-gateway +check-gateway: build/test-gateway + ./build/test-gateway +build/test-gateway: tests/test_gateway.c src/ipxpkt.c src/gateway_config.c src/gateway.h src/ipxpkt.h | build + $(CC) $(CPPFLAGS) $(CFLAGS) -std=c11 -Isrc tests/test_gateway.c src/ipxpkt.c src/gateway_config.c -o $@ $(shell pkg-config --cflags --libs json-c) + +.PHONY: check-gateway-auto +check-gateway-auto: build/test-gateway-auto + ./build/test-gateway-auto +build/test-gateway-auto: tests/test_gateway_auto.c native/gateway_auto.c native/gateway_auto.h native/core.c src/dhcp.c src/gateway_config.c src/gateway.h | build + $(CC) $(CPPFLAGS) $(CFLAGS) -std=c11 -Isrc $(NATIVE_FLAGS) tests/test_gateway_auto.c native/gateway_auto.c native/core.c src/dhcp.c src/gateway_config.c -o $@ $(NATIVE_LIBS) + +.PHONY: check-winclient +check-winclient: build/test-winclient + ./build/test-winclient +build/test-winclient: tests/test_winclient.c clients/windows/client_core.c clients/windows/client_core.h clients/windows/ndis5/frame_queue.c clients/windows/ndis5/frame_queue.h src/ipxpkt.c src/ipxpkt.h src/dhcp.c src/gateway.h | build + $(CC) $(CPPFLAGS) $(CFLAGS) -std=c11 -Isrc -Iclients/windows -Iclients/windows/ndis5 tests/test_winclient.c clients/windows/client_core.c clients/windows/ndis5/frame_queue.c src/ipxpkt.c src/dhcp.c -o $@ $(shell pkg-config --cflags --libs json-c) + +# Cross targets are explicitly development candidates, not validated Windows packages. +.PHONY: windows-tools windows-all windows95 windows98 windowsme windowsnt4 windows2000 windowsxp windows-diag windows-watcom windows-nt5 +windows-tools: + ./cross/install-tools.sh +windows-all: + ./build-windows.sh +windows95: + ./build-windows.sh --no-install WIN95 +windows98: + ./build-windows.sh --no-install WIN98 +windowsme: + ./build-windows.sh --no-install WINME +windowsnt4: + ./build-windows.sh --no-install WINNT40 +windows2000: + ./build-windows.sh --no-install WIN2000 +windowsxp: + ./build-windows.sh --no-install WINXP +windows-diag: + ./cross/build-diag.sh +windows-watcom: + ./cross/watcom-check.sh +windows-nt5: + ./cross/build-nt5.sh + +.PHONY: windows-legacy-tools windows-legacy check-legacy +windows-legacy-tools: + ./cross/fetch-legacy.sh --accept-archive +windows-legacy: + ./cross/build-legacy.sh +build/test-legacy: tests/test_legacy.c clients/windows/ndis3/legacy_core.c clients/windows/ndis3/legacy_core.h clients/windows/ndis5/frame_queue.c | build + $(CC) $(CFLAGS) -std=c89 -pedantic -DMARS_LEGACY_KERNEL -Iclients/windows/ndis3 tests/test_legacy.c clients/windows/ndis3/legacy_core.c clients/windows/ndis5/frame_queue.c -o $@ +check-legacy: build/test-legacy + ./build/test-legacy + +.PHONY: windows-all-legacy windows-legacy-bridge +windows-all-legacy: + ./build-windows.sh --with-legacy-ddk +windows-legacy-bridge: + ./cross/build-legacy-bridge.sh diff --git a/README.md b/README.md index 373dd46..74392c0 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,13 @@ -# MARS_NWE-PCAP 0.4 – Administration, Print & Login Edition +> **Aktueller Paketstand 0.8.1:** [DEB, ZIPs und Freigabe im Webfrontend](DRIVER-RELEASE.md). Binaerdateien unter `releases/`; Windows-Laufzeittests stehen aus. Aeltere Preview-Hinweise unten beschreiben den vorherigen Stand. + +> **0.8 Legacy Preview:** siehe [LEGACY-BUILD.md](LEGACY-BUILD.md). Kein vollständig installierbares Windows-Release. + +# MARS_NWE-PCAP 0.6 Preview – Windows IPXPKT clients + +**0.6 Preview:** [Windows client source, build and distribution guide](WINDOWS.md). Shared tested IPXPKT codec; experimental native NDIS5 driver for 2000/XP; older Windows compatibility path uses external drivers. No Windows binaries or validated Windows installation. +**Update 0.5.1:** [Automatische Netzwerkerkennung, DHCP-Reservierungen und mTCP-Verteilung](AUTOSETUP.md). Die neue Anleitung ersetzt ältere Aussagen über fehlendes DHCP und ausschließlich manuelle IP-Konfiguration. + +**Neu in 0.5:** natives IPXPKT/TAP-Gateway im Dispatcher und Webmodal. Anleitung, Upgrade ohne Original-MARS-Neubuild und Grenzen siehe [GATEWAY.md](GATEWAY.md). Gateway ist standardmäßig deaktiviert. Portierungs- und Integrationspaket für den historischen MARS_NWE NetWare-Emulator, mit Userspace-IPX über libpcap und nativer Webverwaltung (CivetWeb als C-Bibliothek). **Entwicklungsstand, kein vollständig abgenommener NetWare-Server.** Lizenz für den hier entwickelten Code: GPL-2.0-or-later, siehe COPYING. Original-MARS_NWE und Abhängigkeiten behalten ihre eigenen Lizenzen. @@ -24,7 +33,7 @@ Ziel: Debian 12/13 bzw. Ubuntu mit verfügbaren Entwicklungspaketen, glibc >=2.3 ```sh sudo apt update sudo apt install build-essential cmake git pkg-config libpcap-dev \ - libgdbm-dev libcrypt-dev libssl-dev libcivetweb-dev libjson-c-dev cups-client + libgdbm-dev libcrypt-dev libssl-dev libcivetweb-dev libjson-c-dev libcups2-dev cups-client iproute2 nftables # Optional für den HTTP-Abnahmetest: sudo apt install curl jq @@ -140,3 +149,6 @@ Nach erfolgreichem Build auf dem Zielsystem: Server starten, SAP-Erkennung mit e Siehe [GUIDE.md](GUIDE.md) für den Ablauf, Beispiele und Abnahmetests. Die iOS-artige Browseroberfläche zeigt ein Dashboard mit modalen Arbeitsbereichen. Für Live-Funktionen muss nwbind laufen und das neue Webkennwort gesetzt sein. Die Originalprozesse bleiben im einzigen systemd-Dienst `mars_vme.service`. Ein CUPS-Scheduler darf lokal oder auf einem anderen Rechner laufen; RAW TCP 9100 benötigt keinen CUPS-Scheduler. Keine neue MARS-systemd-Unit. Der lokale root-only IPC-Socket `/run/mars-pcap/admin.sock` wird durch den gepatchten nwbind geöffnet. Der Adapter benutzt originalen Bindery-Code im serialisierten Ereignisloop, nicht parallelen direkten DBM-Dateizugriff. Für Verzeichnis-Trustees benutzt er ein erweitertes Originalprogramm `ftrustee` als kurzlebigen Kindprozess (kein separater Dienst). Er verweigert ACL-Änderungen bei aktiven Verbindungen, geändertem Konfigurationshash, unsicheren Verzeichnissen, SYS oder nicht unterstützten Volumes. Siehe Guide und TEST-RESULTS. Spool-Adapter, Bindery, Login-Dateien und Trustee-Integration mit realem MARS sind noch nicht end-to-end abgenommen. Der Build-Quellbaum wird nicht in diesem Archiv vendort; `MARS_SOURCE_DIR` ermöglicht Offline-Build mit lokalem Originalbaum. Der Git-Branch ist nicht auf einen Commit festgeschrieben, Patch-Anker stoppen bei inkompatiblem Layout. + +## 0.7 cross-build preview +See [CROSS-BUILD.md](CROSS-BUILD.md). Run `./build-windows.sh` on Debian/Ubuntu for automatic tool downloads and cross-build attempts. This is not a complete Windows driver release. diff --git a/TEST-RESULTS-0.8.txt b/TEST-RESULTS-0.8.txt new file mode 100644 index 0000000..83ee603 --- /dev/null +++ b/TEST-RESULTS-0.8.txt @@ -0,0 +1,31 @@ +MARS 0.8 legacy preview – verified in Linux build environment +./build/test-legacy +legacy core: queue, MAC, packet filter, invalid frames, lease expiry passed +./build/test-winclient +PASS: Windows client core + actual server codec/DHCP; peer validation, fragments, queue +./build/test-gateway +PASS: IPXPKT both sockets, little-endian IDs, fragmentation, out-of-order, duplicates, expiry, throughput, malformed data, config validation, static MAC/IP and ARP policy +./build/test-gateway-auto +PASS: overlapping routes, DHCP OFFER/ACK/NAK, malformed and spoofed packets +./build/test-wire +PASS: 4 frame types, addresses, padding, lengths, malformed frames and MTU +MARSNET.EXE: PE32 x86, subsystem 3, OS 4.0, subsystem version 4.0 +CRT-free MARSNET.EXE built; still requires an NDIS3 miniport and WinPcap 3.1 at runtime. +IPXDIAG.EXE: PE32 x86, subsystem 3, OS 4.0, subsystem version 4.0 +Diagnostic built: /mnt/data/work08/mars-nwe-pcap-0.8-legacy/build/cross/diag/IPXDIAG.EXE +Published SYS:PUBLIC/CLIENTS (IPX 00000101, node 020908070605, gateway 10.250.0.1). Verify read/file-scan trustees; deny writes. +Windows clients: CLIENTS already exists; back up and move it aside before republishing +Windows clients: MARSNET.EXE is not a PE/DOS executable +Windows clients: native client requires EXE, SYS and INF together +Published SYS:PUBLIC/CLIENTS (IPX 00000101, node 020908070605, gateway 10.250.0.1). Verify read/file-scan trustees; deny writes. +PASS: publisher network config, six folders, no overwrite, reject invalid/incomplete input, target selection (fixtures only) +Windows clients: Legacy driver is experimental; use MARS_ALLOW_PREVIEW=1 only for isolated VM testing +Published SYS:PUBLIC/CLIENTS (IPX 00000101, node 020908070605, gateway 10.250.0.1). Verify read/file-scan trustees; deny writes. +PASS: legacy preview gate and Win9x target routing + +Shell syntax: PASS +No NT4 ISO; run cross/fetch-legacy.sh --accept-archive +NDIS3 real build exit=1 (historical DDK unavailable) +Missing i686-w64-mingw32-gcc; run cross/install-tools.sh --apt-only +NDIS5 real build exit=1 (MinGW unavailable) +legacy core: queue, MAC, packet filter, invalid frames, lease expiry passed diff --git a/TEST-RESULTS.txt b/TEST-RESULTS.txt index 7a5dee0..24ac516 100644 --- a/TEST-RESULTS.txt +++ b/TEST-RESULTS.txt @@ -32,3 +32,45 @@ PASS: ftrustee-Adapter mit simulierten Original-Trustee-Routinen: Pfad-/Rechtepr PASS: Chromium mit simulierten HTTP-APIs: Dashboard, modale Ansichten, Sitzungsnachricht, Gruppenanlage, Queue-Entwurf, Vorschau, mobile Kennwortseite, Gruppenskript und MAP-Assistent, Erhalt bestehendes Systemskript, Benutzerskript, ACL laden/setzen/entfernen. Screenshots zeigen diese Testdaten. PASS: Shell- und JavaScript-Syntax, native HTTP-C-Datei gegen CivetWeb-API-Signaturprobe (nicht echtes Linken). OFFEN: Kompilierung/Link aller originalen Upstream-Adapter mit vollständigem MARS-Quellbaum; realer CivetWeb-Link und HTTP/TLS-Abnahme; tatsächlicher IPX-Verkehr und NetWare-Client; Live-Bindery-/Sitzungs-/Trustee-/Login-Skript-/Druck-Integration. Die Originalquellen und CivetWeb-Entwicklungsbibliothek waren hier nicht lokal verfügbar. Keine behauptete Gesamtserver-Abnahme. + +MARS_NWE-PCAP 0.5 – erneut bzw. zusätzlich ausgeführte Tests +PASS: make all check (GCC-Dispatcher, Shim, 4 Frame-Formate). +PASS: make check-gateway – 0x6180/0x6181, little-endian IDs, Fragmentierung, + Out-of-order, Duplikate während Reassemblierung, Timeout, Durchsatztest + mit 500 vollständigen Frames je Variante, ungültige Frames, + Konfigurationsprüfung, statische MAC/IP- und ARP-Regeln. +PASS: derselbe Gateway-Test mit AddressSanitizer/UndefinedBehaviorSanitizer. +PASS: make check-native check-supervisor check-print check-raw check-scripts + check-trustee; CUPS nur Bibliotheksprobe, Trustee simuliert. +PASS: run-ipc-test.sh mit offline Broker; kein echter Ethernet-Verkehr. +PASS: C-Webbackend Syntaxprüfung mit lokaler CivetWeb-API-Signaturprobe; + keine echte CivetWeb-Bibliothek/ABI-/HTTP-Abnahme. +PASS: Shell-Syntax, Node.js-Syntax und Chromium-Gateway-Modal mit Mock-API + (Auswahl, Clientliste, Speichern, Dirty-Guard, Restart, Status). +NICHT AUSGEFÜHRT: tatsächlicher CivetWeb-Link (fehlender civetweb.h), + echte /dev/net/tun- und nftables-Konfiguration (kein Gerät/nft und + keine CAP_NET_ADMIN), echte IPXPKT.COM-Clients und Internetverkehr, + vollständiger Original-MARS-Build/Systemd-Installation auf Zielsystem. +Keine Laufzeit- oder Durchsatzmessung auf echter Hardware. + +MARS_NWE-PCAP 0.5.1 – zusätzliche Tests +PASS: GCC-Build des Dispatchers mit DHCP; make all check check-gateway. +PASS: make check-gateway-auto – überlappende Routen, eigene TAP-Route, + DHCP OFFER/ACK/NAK, falsche MAC, unvollständige Optionen und Paketlängen. +PASS: make check-native check-supervisor; Shell-/JavaScript-Syntax. +PASS: Publisher mit lokalen synthetischen ZIPs, SYS/PUBLIC-Auflösung, + DOS-Batchdateien, 0644-Dateirechte, bestehendes MTCP nicht überschrieben. +PASS: Web-C-Quelltext Syntaxprüfung mit CivetWeb-Signaturprobe, kein Link. +NICHT GETESTET: reale FreeDOS-Downloads (DNS im Arbeitscontainer fehlt), + tatsächliche CivetWeb-ABI, HTTP-Integration, TAP/NAT/NetWare/DOS. +PASS: run-ipc-test.sh – Offline-Broker, interne/externe Registrierung, + Routen, Socket-Konflikte, dynamische Ports und fork/exec. +PASS: neue DHCP-/Route-Tests zusätzlich mit ASan/UBSan. + +0.6 Windows preview: Linux make check/check-gateway/check-gateway-auto/check-winclient PASS; common C89 source gcc -std=c89 -pedantic-errors -Wall -Wextra -Werror PASS; ASan+UBSan client/server codec/DHCP/queue PASS; publisher fixture test PASS; shell and app.js syntax PASS. No actual Windows SDK/DDK build, no Windows binaries or VM tests. No actual CivetWeb link or live TAP/NAT qualification in this environment. External driver integration remains experimental. + +0.7 CROSS-BUILD PREVIEW (additional tests): +- Clang/LLD x86 freestanding IPXDIAG.EXE compiled; PE32 console subsystem 4.0, imports KERNEL32.dll and WSOCK32.dll only. No Windows runtime test. +- make check-winclient check-gateway check-gateway-auto check: PASS (Linux). +- Shell syntax: PASS. Individual build script diagnostic export: PASS. Missing MinGW/Watcom produces failure status, not a claimed driver build. +- Real apt and Watcom download blocked by network/DNS in this environment. MinGW and Watcom builds not verified. Full server build unchanged, not revalidated. Win9x/NT4 own adapter not implemented. diff --git a/WINDOWS.md b/WINDOWS.md new file mode 100644 index 0000000..97b3b88 --- /dev/null +++ b/WINDOWS.md @@ -0,0 +1,103 @@ +# MARS 0.6 Preview – Windows IPXPKT clients (x86) + +**Development preview, not a Windows-tested release.** No compiled Windows driver or EXE is supplied. The portable client protocol, the server DHCP interoperability and the frame ring have passed Linux tests. Neither the Windows SDK/DDK nor historical Windows installations were available. Kernel code may fail to build or load and can crash the OS. Use isolated VMs with snapshots first. + +## Architecture + +Windows TCP/IP -> virtual Ethernet adapter -> MARS Win32 bridge -> Winsock AF_IPX -> physical NIC -> MARS IPXPKT / TAP / DHCP / NAT. mTCP is not needed for Windows. The bridge transports IPv4 and ARP only. The existing Linux service remains `mars_vme.service`; no additional daemon. DOS mTCP remains unchanged. The bridge must stay running on the Windows client. + +| OS | Native NDIS level | Implementation in this package | +|---|---|---| +| Windows 95 / OSR2 | 3.1 / 4.0 | Experimental Win32 bridge with external VirtNet and compatible WinpkFilter | +| Windows 98 / SE | 4.1 / 5.0 | Same external compatibility bridge | +| Windows ME | 5.0 | Same bridge; no real-mode DOS required | +| Windows NT 4.0 | 4.0 / 4.1 SP3 | Same bridge, NT-specific external driver installation | +| Windows 2000 | 5.0 | Own experimental NDIS5 miniport source + bridge; external alternatives | +| Windows XP 32-bit | 5.1 | Same NDIS5.0 miniport source + bridge; external alternatives | + +The native 9x VxD and NT4 control/miniport implementations are NOT present. NDIS5 control-device APIs are not a drop-in substitute. The external bridge is not verified on any target. XP x64 is out of scope. References: [Microsoft NDIS versions](https://learn.microsoft.com/en-us/windows-hardware/drivers/network/ndis-versions-in-windows), [VirtNet](https://www.ntkernel.com/virtnet/), [WinpkFilter](https://www.ntkernel.com/windows-packet-filter/). VirtNet is freeware for private/educational use per vendor; check license for any business deployment. Obtain the historical drivers, version-matched SDK and DLL legally from the vendor; no external binaries are redistributed here. Current releases may not support the old systems. + +## 1. Linux server + +Upgrade the 0.5.1 server (preserves nwserv and existing settings): + +```sh +make all native check check-gateway check-gateway-auto check-winclient +sudo ./install-gateway.sh +sudo systemctl start mars_vme.service +``` + +Enable gateway in the Web UI, auto-detect network, save and apply. Choose the actual IPX network of the clients. The virtual /24, public DNS, device approval, fixed DHCP reservations and host firewall behavior are the same as 0.5.1. Verify `/run/mars-pcap/gateway`, `ip addr show marsipx0` and `sysctl net.ipv4.ip_forward`. No changes to the global forwarding setting are automatic. + +## 2. Build Windows programs + +Use a licensed x86 Visual C++ 6 build environment (NT command shell) and period SDK containing `winsock.h`, `wsipx.h`, `wsnwlink.h`, `wsock32.lib`. Run from `clients\windows`: + +```bat +build-vc6.bat native +build-vc6.bat filter C:\LEGACYSDK\include +build-vc6.bat tap +``` + +These are alternative build targets. Native -> MARSIPX.EXE (2000/XP). Filter -> MARSNET.EXE (legacy targets, external WinpkFilter Common.h SDK required). TAP -> MARSTAP.EXE (2000/XP, requires separate compatible historical TAP-Win32 driver). No need to build all three. The filter DLL must match the driver and SDK and be supplied separately in the same local directory as MARSNET.EXE. + +Native driver: in a Windows 2000 DDK x86 build environment, change directory to `clients\windows\ndis5`, run `build -cZ`, locate MARSNDIS.SYS in the target object directory. Copy it with MARSNDIS.INF and MARSIPX.EXE into a staging directory. The provided INF is experimental and unsigned. Build scripts and Windows code have not been tested against actual SDK/DDK; API/INF fixes may be required. No signed drivers are supplied. Old DDKs are not included. + +## 3. Central distribution + +Install jq on Linux. When the desired IPX network is present in dispatcher state, publish either config only, or locally compiled files: + +```sh +sudo apt install jq +sudo mars-publish-winclient /path/to/trusted/build-output +# OR, for configuration export only (no drivers or executable files): +sudo mars-publish-winclient --config-only +``` + +The publisher reads `nwserv.conf`, `ipxpkt.json` and `/run/mars-pcap/ipx_interface`; it creates GATEWAY.INI for each OS with the selected external network, gateway node, IP and socket 6181. Requires root-owned SYS and PUBLIC not writable by group/others. Six subfolders: WIN95, WIN98, WINME, WINNT40, WIN2000, WINXP. The native SYS/INF/EXE trio is copied only to 2000/XP. Existing CLIENTS directories are never overwritten. Back up and move aside the previous directory before republishing (including after network/gateway changes). No automatic update of already copied local INIs. The publisher checks basic file signatures, not authenticity; use only trusted builds. Keep original licenses and source offers with any distributed software; verify NetWare read/file-scan trustees and deny writes. Do not automatically execute driver installers from a NetWare login script. + +NetWare login script for intended users: + +```text +IF MEMBER OF "INTERNET_USERS" THEN + MAP ROOT T:=SYS:PUBLIC\CLIENTS +END +``` + +Copy the appropriate directory to `C:\MARSNET` locally, rather than loading kernel drivers or depending on a live network drive. The Web UI includes a new Gateway -> Windows-Clientsoftware modal with the publication instructions and clear preview status. It is not a remote installer. + +## 4. Windows 2000/XP: experimental own miniport + +1. Install IPX/SPX (NWLink or a compatible Winsock IPX provider) on the physical NIC. Check physical node and IPX network with `MARSIPX.EXE --ipx`. IPX frame type must match server. Providers differ; explicit binding may fail. Do not change the NetWare working settings unnecessarily. +2. Add new hardware manually, network adapter, Have Disk, choose MARSNDIS.INF; use snapshots and admin rights. The INF needs matching SYS beside it. Set advanced `Physical IPX Node` (12 hex digits, exactly the physical node, NOT the server node). Only one MARS miniport per OS is supported. The bridge refuses mismatches. +3. Configure the virtual adapter for automatic IPv4/DNS; unbind IPX, file/printer sharing, Client for Microsoft Networks and NetWare from virtual adapter where applicable. Bind IPX to physical NIC; unbind TCP/IP from it if only IPX should travel over the wire. Disable NetBIOS over TCP/IP on the virtual adapter where possible. Keep the NetWare client on physical IPX. Reboot if required. +4. Open administrator command prompt in local C:\MARSNET. Example physical node (replace with actual): + +```bat +MARSIPX.EXE --ipx +MARSIPX.EXE --discover 020102030405 GATEWAY.INI +MARSIPX.EXE --run MARS 020102030405 GATEWAY.INI --confirm-virtual +``` + +Discover only sends an ARP probe; the Linux UI must actually show the device. Approve device, reserve IP, save and apply server changes. The run command must stay active; use another command prompt for `ipconfig /all`, DHCP renewal (`ipconfig /renew`, specify virtual adapter if needed), and test external DNS/HTTP/ping if allowed. Gateway itself does not answer ICMP from clients by policy. Windows 2000/XP does not need MTCP.CFG. The native control device is restricted to an administrator with SeLoadDriverPrivilege. If link doesn't come up, do not use production systems; inspect DDK build/driver status and bridge output. + +## 5. Windows 95/98/ME/NT4: external compatibility path + +Install vendor's historical VirtNet virtual adapter and matching legacy WinpkFilter driver for the OS, following vendor installation instructions (NT4 uses its legacy networking installer; Win9x/ME uses its own INF and may reboot). Use only trusted packages, verify licenses. Configure virtual MAC to equal physical IPX node, TCP/IP with DHCP bound only to the virtual adapter, IPX only on physical NIC. No mTCP or real-mode packet driver is required for this architecture. Copy matching SDK's ndisapi.dll to local executable directory. Use: + +```bat +MARSNET.EXE --ipx +MARSNET.EXE --list +MARSNET.EXE --discover 020102030405 GATEWAY.INI +MARSNET.EXE --run "EXACT_VIRTUAL_ADAPTER_NAME" 020102030405 GATEWAY.INI --confirm-virtual +``` + +Do NOT select a physical adapter. Filter mode intercepts all selected adapter traffic. Check adapter description, MAC, and internal name. The bridge refuses non-Ethernet or an already configured filter mode. After approval and saving on Linux, use `winipcfg` on Win9x/ME or `ipconfig` on NT4 to renew virtual DHCP; external drivers and provider may not support these exact operations. Stop with Ctrl-C to restore mode; if process crashes, reset filter mode/reboot in VM. NT4/Win9x native replacement still requires development of OS-specific kernel control and install path. + +## 6. Optional historical TAP-Win32 path (2000/XP) + +Install a trusted, licensed TAP-Win32 driver specifically compatible with the target. Use the driver-supported MAC override (may be named MAC instead of NetworkAddress), equal physical node. Bind native TCP/IP to TAP only. Run `MARSTAP.EXE --run "{ADAPTER-GUID}" 020102030405 GATEWAY.INI --confirm-virtual`. The executable opens the old TAP device interface; exact compatibility is not verified. Reference: https://github.com/OpenVPN/tap-windows . No TAP binaries included. + +## 7. Validation and security + +Linux: `make check-winclient` checks both ports, reassembly, source validation and real server DHCP OFFER/ACK through the client codec plus bounded NDIS frame queue. `sudo ./tests/test_publish_winclient.sh` tests publisher with temporary fixtures. Linux C89 build and sanitizer checks have passed. A real Windows build, driver install, NDIS binding, virtual DHCP, physical packet trace (only IPX, no native IPv4), reconnect and unload tests are still required for each target. Also test DOS regression. Native miniport has no completed power/PnP/Driver Verifier qualification. The existing server TAP/NAT still needs real end-to-end tests. IPXPKT is unencrypted, MAC ACLs are spoofable, and obsolete Windows/TLS must be isolated from productive networks. Do not expose old clients directly to inbound internet traffic. Existing Linux policy permits configured services only; HTTPS transport does not make old browsers compatible with modern websites. diff --git a/build-windows.sh b/build-windows.sh new file mode 100755 index 0000000..1f30485 --- /dev/null +++ b/build-windows.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# One-command download + cross-build. Run as ordinary user where possible. +set -euo pipefail +cd "$(dirname "$0")" +download_failed=0; legacy=0; if [[ ${1:-} == --with-legacy-ddk ]]; then legacy=1; shift; fi +if [[ ${1:-} == --no-install ]]; then shift; else + # A failed optional Watcom download must not prevent independent MinGW/Clang attempts. + ./cross/install-tools.sh --apt-only + if ! ./cross/fetch-watcom.sh; then echo 'Watcom download failed; other builds will still be attempted.' >&2; fi +fi +if (( legacy )); then + if ! ./cross/fetch-legacy.sh --accept-archive; then echo "Legacy download incomplete; other builds still attempted." >&2; download_failed=1; fi +fi +case ${1:-all} in + all|WIN95|WIN98|WINME|WINNT40) + ./cross/fetch-winpcap.sh || download_failed=1;; +esac +export MARS_OFFLINE=1 +rc=0; ./cross/build-windows.sh "${1:-all}" || rc=$? +if (( download_failed )); then exit 1; fi +exit "$rc" diff --git a/build.sh b/build.sh index d8e4062..d744eb6 100755 --- a/build.sh +++ b/build.sh @@ -5,7 +5,12 @@ base=$PWD source_dir=${MARS_SOURCE_DIR:-} prefix=${PREFIX:-/usr/local} [[ $prefix = /usr/local ]] || { echo 'PREFIX must be /usr/local for native service' >&2; exit 2; } -make all check native check-native check-supervisor +for tool in cc make cmake git pkg-config; do + command -v "$tool" >/dev/null || { echo "Missing build tool: $tool. See GUIDE.md." >&2; exit 1; } +done +pkg-config --exists json-c openssl || { echo 'Install libjson-c-dev and libssl-dev.' >&2; exit 1; } +printf '#include \n' | cc -E -x c - >/dev/null || { echo 'Install libcivetweb-dev.' >&2; exit 1; } +make all check native check-native check-supervisor check-gateway check-gateway-auto check-winclient mkdir -p upstream if [[ ! -d upstream/original ]]; then if [[ -n $source_dir ]]; then diff --git a/clients/windows/build-vc6.bat b/clients/windows/build-vc6.bat new file mode 100644 index 0000000..91da358 --- /dev/null +++ b/clients/windows/build-vc6.bat @@ -0,0 +1,23 @@ +@echo off +rem Run from clients\windows with VC6 (x86) environment and period SDK. +if "%1"=="tap" goto tap +if "%1"=="native" goto native +if "%1"=="filter" goto filter +echo Usage: build-vc6 filter [legacy WinpkFilter include directory] OR build-vc6 tap OR build-vc6 native +exit /b 2 +:filter +if "%2"=="" goto bad +cl /nologo /W3 /O2 /MT /DWIN32 /D_WINDOWS /D_WIN32_WINNT=0x0400 /DMARS_FILTER /I..\..\src /I"%~2" marsnet.cpp client_core.c ..\..\src\ipxpkt.c /FeMARSNET.EXE /link wsock32.lib kernel32.lib /SUBSYSTEM:CONSOLE,4.0 +if errorlevel 1 exit /b 1 +exit /b 0 +:tap +cl /nologo /W3 /O2 /MT /DWIN32 /D_WIN32_WINNT=0x0500 /DMARS_TAP /I..\..\src marsnet.cpp client_core.c ..\..\src\ipxpkt.c /FeMARSTAP.EXE /link wsock32.lib kernel32.lib /SUBSYSTEM:CONSOLE,5.0 +if errorlevel 1 exit /b 1 +exit /b 0 +:native +cl /nologo /W3 /O2 /MT /DWIN32 /D_WIN32_WINNT=0x0500 /DMARS_NATIVE /I..\..\src marsnet.cpp client_core.c ..\..\src\ipxpkt.c /FeMARSIPX.EXE /link wsock32.lib kernel32.lib advapi32.lib /SUBSYSTEM:CONSOLE,5.0 +if errorlevel 1 exit /b 1 +exit /b 0 +:bad +echo Supply the include path containing Common.h from the matching legacy SDK. +exit /b 2 diff --git a/clients/windows/client_core.c b/clients/windows/client_core.c new file mode 100644 index 0000000..6132f43 --- /dev/null +++ b/clients/windows/client_core.c @@ -0,0 +1,14 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#include "client_core.h" +#include +static const uint8_t bc[6]={255,255,255,255,255,255},zero[6]={0}; +static int unicast(const uint8_t*p){return !(p[0]&1)&&memcmp(p,zero,6)!=0;} +static int allowed_type(const uint8_t*f,size_t n){unsigned h,total;if(n<14||n>PKT_FRAME)return 0;if(f[12]==8&&f[13]==0){if(n<34||(f[14]>>4)!=4)return 0;h=(f[14]&15)*4;total=((unsigned)f[16]<<8)|f[17];return h>=20&&total>=h&&total<=n-14;}return n>=42&&f[12]==8&&f[13]==6&&f[14]==0&&f[15]==1&&f[16]==8&&f[17]==0&&f[18]==6&&f[19]==4&&f[20]==0&&(f[21]==1||f[21]==2);} +int client_init(struct client_core*c,uint32_t net,const uint8_t*node,const uint8_t*server,uint16_t port){if(!c||!node||!server||!net||net==0xffffffffUL||!unicast(node)||!unicast(server)||!memcmp(node,server,6)||(port!=PKT_PLAIN&&port!=PKT_TRAIL))return -1;memset(c,0,sizeof *c);memcpy(c->node,node,6);memcpy(c->server,server,6);c->net=net;c->port=port;return 0;} +int client_tx(struct client_core*c,const uint8_t*f,size_t n,pkt_emit emit,void*ctx){if(!allowed_type(f,n)||memcmp(f+6,c->node,6)||(memcmp(f,c->server,6)&&memcmp(f,bc,6))||(f[13]==6&&memcmp(f+22,c->node,6))){c->dropped++;return -1;}if(pkt_send(c->port,++c->seq,f,n,emit,ctx)){c->dropped++;return -1;}c->tx++;return 0;} +int client_rx(struct client_core*c,uint32_t net,const uint8_t*node,uint16_t port,const uint8_t*p,size_t n,time_t now,uint8_t*out){int rc;if(net!=c->net||memcmp(node,c->server,6)||port!=c->port){c->dropped++;return -1;}if(nowlast)memset(&c->rx,0,sizeof c->rx);c->last=now;rc=pkt_receive(&c->rx,net,node,port,p,n,now,out);if(rc==0)return 0;if(rc<0||!allowed_type(out,(size_t)rc)||memcmp(out+6,c->server,6)||(memcmp(out,c->node,6)&&memcmp(out,bc,6))||(out[13]==6&&memcmp(out+22,c->server,6))){c->dropped++;return -1;}c->received++;return rc;} +static int nibble(char c){if(c>='0'&&c<='9')return c-'0';if(c>='A'&&c<='F')return c-'A'+10;if(c>='a'&&c<='f')return c-'a'+10;return -1;} +int client_hex(const char*s,uint8_t*out,size_t n){size_t i;int a,b;if(!s||strlen(s)!=2*n)return -1;for(i=0;inode,6);out[12]=8;out[13]=6;out[15]=1;out[16]=8;out[18]=6;out[19]=4;out[21]=1;memcpy(out+22,c->node,6);memcpy(out+38,gw,4);} diff --git a/clients/windows/client_core.h b/clients/windows/client_core.h new file mode 100644 index 0000000..0f49dce --- /dev/null +++ b/clients/windows/client_core.h @@ -0,0 +1,17 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef MARS_CLIENT_CORE_H +#define MARS_CLIENT_CORE_H +#include "ipxpkt.h" +#ifdef __cplusplus +extern "C" { +#endif +struct client_core { uint8_t node[6],server[6]; uint32_t net;uint16_t port,seq;struct pkt_rx rx;time_t last;unsigned long tx,received,dropped;}; +int client_init(struct client_core*,uint32_t,const uint8_t*,const uint8_t*,uint16_t); +int client_tx(struct client_core*,const uint8_t*,size_t,pkt_emit,void*); +int client_rx(struct client_core*,uint32_t,const uint8_t*,uint16_t,const uint8_t*,size_t,time_t,uint8_t*); +int client_hex(const char*,uint8_t*,size_t); +void client_probe(struct client_core*,const uint8_t gateway[4],uint8_t out[60]); +#ifdef __cplusplus +} +#endif +#endif diff --git a/clients/windows/diag/ipxdiag.c b/clients/windows/diag/ipxdiag.c new file mode 100644 index 0000000..a878bb0 --- /dev/null +++ b/clients/windows/diag/ipxdiag.c @@ -0,0 +1,37 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later + * Freestanding x86 Win32 Winsock 1.1 diagnostic. No CRT, no driver install. + * IPX_ADDRESS ABI per public Winsock API. Only queries local provider. + */ +typedef unsigned long U32; +typedef unsigned short U16; +typedef unsigned char U8; +#define IMPORT __declspec(dllimport) +#define CALL __stdcall +IMPORT void CALL ExitProcess(U32); +IMPORT void* CALL GetStdHandle(U32); +IMPORT int CALL WriteFile(void*,const void*,U32,U32*,void*); +IMPORT int CALL WSAStartup(U16,void*); +IMPORT int CALL WSACleanup(void); +IMPORT int CALL WSAGetLastError(void); +IMPORT U32 CALL socket(int,int,int); +IMPORT int CALL closesocket(U32); +IMPORT int CALL getsockopt(U32,int,int,char*,int*); +IMPORT int CALL bind(U32,const void*,int); +IMPORT int CALL getsockname(U32,void*,int*); +struct address {int adapter; U8 net[4],node[6],wan,status; int maxpkt; U32 speed;}; +struct ipxaddr {U16 family; U8 net[4],node[6]; U16 port;}; +typedef char check_a[sizeof(struct address)==24?1:-1]; +typedef char check_b[sizeof(struct ipxaddr)==14?1:-1]; +static union {U32 align; U8 bytes[512];} wsadata; +static void *out; +static void text(const char*s){U32 n=0,w;while(s[n])n++;WriteFile(out,s,n,&w,0);} +static void hex(const U8*p,unsigned n){static const char h[]="0123456789ABCDEF";char b[3];unsigned i; b[2]=0;for(i=0;i>4];b[1]=h[p[i]&15];text(b);}} +static void number(U32 v){char b[11];unsigned i=10;b[i]=0;do{b[--i]=(char)('0'+v%10);v/=10;}while(v);text(b+i);} +static void clear(void*p,unsigned n){volatile U8*b=(volatile U8*)p;while(n--)*b++=0;} +static void err(const char*s,int e){text(s);text(": ");number((U32)e);text("\r\n");} +void start(void){U32 s;int rc,i,n,count=0;struct address a;struct ipxaddr local;out=GetStdHandle((U32)-11);text("MARS IPX diagnostic (Winsock 1.1)\r\n");rc=WSAStartup(0x0101,wsadata.bytes);if(rc){err("WSAStartup",rc);ExitProcess(1);return;} + s=socket(6,2,1000);if(s==0xffffffffUL){err("AF_IPX socket",WSAGetLastError());WSACleanup();ExitProcess(2);return;} + for(i=0;i<64;i++){clear(&a,sizeof a);a.adapter=i;n=sizeof a;if(getsockopt(s,1000,0x4007,(char*)&a,&n)||n<(int)sizeof a)continue;count++;text("Adapter ");number(i);text(" network=");hex(a.net,4);text(" node=");hex(a.node,6);text(" maxpkt=");number(a.maxpkt);text("\r\n");} + if(!count)text("IPX_ADDRESS enumeration unavailable; trying wildcard bind.\r\n"); + clear(&local,sizeof local);local.family=6;rc=bind(s,&local,sizeof local);if(rc){err("IPX bind",WSAGetLastError());}else{n=sizeof local;rc=getsockname(s,&local,&n);if(rc)err("getsockname",WSAGetLastError());else if(n<(int)sizeof local){text("Short IPX address\r\n");rc=-1;}else{text("Bound network=");hex(local.net,4);text(" node=");hex(local.node,6);text("\r\n");}} + closesocket(s);WSACleanup();text("Local IPX test only; not a gateway or Internet test.\r\n");ExitProcess(rc?3:0);} diff --git a/clients/windows/marsnet.cpp b/clients/windows/marsnet.cpp new file mode 100644 index 0000000..6eb15ca --- /dev/null +++ b/clients/windows/marsnet.cpp @@ -0,0 +1,133 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later + * Legacy Win32 IPXPKT bridge. No TCP/IP socket is opened by this program. + * Build with VC6 + legacy SDK. Filter and TAP builds use separate backends. + */ +#define WIN32_LEAN_AND_MEAN +#include +#include +#include +#include +#include +#include +#include +#include "client_core.h" +#if defined(MARS_FILTER) +#include +#include +/* Use the vendor's version-matched SDK structures, not guessed IOCTL layouts. */ +#include "Common.h" +#elif defined(MARS_TAP) || defined(MARS_NATIVE) || defined(MARS_LEGACY) +#include +#ifdef MARS_NATIVE +#include "ndis5/control.h" +#endif +#else +#error Choose MARS_FILTER, MARS_TAP, MARS_NATIVE or MARS_LEGACY +#endif +static struct client_core core; +static SOCKET ipx=INVALID_SOCKET; +static SOCKADDR_IPX peer; +static volatile LONG stop_requested; +static unsigned long io_errors; +static int winsock_started; +static BOOL WINAPI on_ctrl(DWORD code){if(code==CTRL_C_EVENT||code==CTRL_BREAK_EVENT||code==CTRL_CLOSE_EVENT||code==CTRL_LOGOFF_EVENT||code==CTRL_SHUTDOWN_EVENT){InterlockedExchange((LONG*)&stop_requested,1);return TRUE;}return FALSE;} +static int stopping(void){return stop_requested!=0;} +static void print_hex(const uint8_t*p,size_t n){size_t i;for(i=0;i>24);p[1]=(char)(n>>16);p[2]=(char)(n>>8);p[3]=(char)n;} +static int ip4(const char*s,uint8_t*out){unsigned a,b,c,d;char rest;if(sscanf(s,"%u.%u.%u.%u%c",&a,&b,&c,&d,&rest)!=4||a>255||b>255||c>255||d>255)return -1;out[0]=(uint8_t)a;out[1]=(uint8_t)b;out[2]=(uint8_t)c;out[3]=(uint8_t)d;return 0;} +static int read_ini(const char*file,const uint8_t*node,uint8_t*gw){char n[64],m[64],p[64],a[64],path[MAX_PATH],*filepart;uint8_t net[4],server[6];uint16_t port;DWORD len=GetFullPathNameA(file,MAX_PATH,path,&filepart);if(!len||len>=MAX_PATH)return -1; + GetPrivateProfileStringA("gateway","network","",n,sizeof n,path);GetPrivateProfileStringA("gateway","server","",m,sizeof m,path);GetPrivateProfileStringA("gateway","port","6181",p,sizeof p,path);GetPrivateProfileStringA("gateway","ip","",a,sizeof a,path); + if(!strcmp(p,"6180"))port=PKT_PLAIN;else if(!strcmp(p,"6181"))port=PKT_TRAIL;else return -1; + if(client_hex(n,net,4)||client_hex(m,server,6)||ip4(a,gw))return -1;return client_init(&core,network_number(net),node,server,port);} +static int init_winsock(void){WSADATA w;if(WSAStartup(MAKEWORD(1,1),&w)){fprintf(stderr,"Winsock 1.1 unavailable.\n");return -1;}winsock_started=1;return 0;} +static int open_ipx(void){SOCKADDR_IPX local,actual;int l=sizeof actual,type=4;u_long nb=1;ipx=socket(AF_IPX,SOCK_DGRAM,NSPROTO_IPX);if(ipx==INVALID_SOCKET){fprintf(stderr,"AF_IPX unavailable (%d). Install IPX/SPX and its Winsock provider.\n",WSAGetLastError());return -1;} + memset(&local,0,sizeof local);local.sa_family=AF_IPX;net_bytes(core.net,local.sa_netnum);memcpy(local.sa_nodenum,core.node,6);local.sa_socket=htons(core.port); + if(setsockopt(ipx,NSPROTO_IPX,IPX_PTYPE,(char*)&type,sizeof type)||bind(ipx,(SOCKADDR*)&local,sizeof local)||getsockname(ipx,(SOCKADDR*)&actual,&l)||ioctlsocket(ipx,FIONBIO,&nb)){fprintf(stderr,"IPX setup failed (%d). Check frame/network/node and socket availability.\n",WSAGetLastError());return -1;} + if(l<(int)sizeof actual||memcmp(actual.sa_netnum,local.sa_netnum,4)||memcmp(actual.sa_nodenum,local.sa_nodenum,6)||actual.sa_socket!=local.sa_socket){fprintf(stderr,"IPX provider returned a different binding. Refusing ambiguous source.\n");return -1;} + peer=local;memcpy(peer.sa_nodenum,core.server,6);printf("Bound IPX network %08lX, node ",(unsigned long)core.net);print_hex(core.node,6);printf(", socket %04X\n",core.port);return 0;} +static int emit_ipx(void*,const uint8_t*p,size_t n){int rc=sendto(ipx,(const char*)p,(int)n,0,(SOCKADDR*)&peer,sizeof peer);if(rc!=(int)n){if(io_errors++<5)fprintf(stderr,"IPX send failed (%d)\n",WSAGetLastError());return -1;}return 0;} +static int list_ipx(void){SOCKET s;int i,found=0,l;IPX_ADDRESS_DATA a;s=socket(AF_IPX,SOCK_DGRAM,NSPROTO_IPX);if(s==INVALID_SOCKET){fprintf(stderr,"IPX socket failed: %d\n",WSAGetLastError());return -1;}for(i=0;i<64;i++){memset(&a,0,sizeof a);a.adapternum=i;l=sizeof a;if(getsockopt(s,NSPROTO_IPX,IPX_ADDRESS,(char*)&a,&l))continue;printf("IPX %d: network=",i);print_hex(a.netnum,4);printf(" node=");print_hex(a.nodenum,6);printf(" max=%d\n",a.maxpkt);found++;}closesocket(s);if(!found)fprintf(stderr,"Provider did not enumerate IPX adapters; use physical MAC and known IPX network.\n");return found?0:-1;} +/* Return a frame only after complete reassembly and strict server/inner MAC checks. */ +static int receive_ipx(uint8_t*f){SOCKADDR_IPX src;int l=sizeof src,n;uint8_t buf[547];n=recvfrom(ipx,(char*)buf,sizeof buf,0,(SOCKADDR*)&src,&l);if(n==SOCKET_ERROR){int e=WSAGetLastError();if(e==WSAEWOULDBLOCK)return -2;if(e==WSAEMSGSIZE){core.dropped++;return 0;}if(io_errors++<5)fprintf(stderr,"IPX receive failed (%d)\n",e);return -3;}if(l<(int)sizeof src||src.sa_family!=AF_IPX){core.dropped++;return 0;}return client_rx(&core,network_number((const uint8_t*)src.sa_netnum),(const uint8_t*)src.sa_nodenum,ntohs(src.sa_socket),buf,(size_t)n,(time_t)(GetTickCount()/1000UL),f);} +#if defined(MARS_FILTER) +/* A licensed, legacy WinpkFilter driver + version-matched ndisapi.dll is external. + * Only the explicitly selected dummy adapter is ever placed into tunnel mode. */ +typedef HANDLE (WINAPI *open_fn)(const TCHAR*); +typedef VOID (WINAPI *close_fn)(HANDLE); +typedef BOOL (WINAPI *loaded_fn)(HANDLE); +typedef BOOL (WINAPI *list_fn)(HANDLE,PTCP_AdapterList); +typedef BOOL (WINAPI *mode_fn)(HANDLE,PADAPTER_MODE); +typedef BOOL (WINAPI *packet_fn)(HANDLE,PETH_REQUEST); +typedef BOOL (WINAPI *flush_fn)(HANDLE,HANDLE); +typedef BOOL (WINAPI *event_fn)(HANDLE,HANDLE,HANDLE); +static open_fn Open;static close_fn Close;static loaded_fn Loaded;static list_fn List;static mode_fn GetMode,SetMode;static packet_fn Read,Inject;static flush_fn Flush;static event_fn SetEventFor; +static HMODULE dll;static HANDLE driver,adapter,packet_event;static TCP_AdapterList adapters;static ADAPTER_MODE oldmode;static int tunnel_mode,event_set; +#define RESOLVE(var,type,name) do{var=(type)GetProcAddress(dll,name);if(!var){fprintf(stderr,"Missing legacy ndisapi export %s\n",name);return -1;}}while(0) +static int filter_open(void){char path[MAX_PATH],*tail;DWORD len=GetModuleFileNameA(NULL,path,sizeof path);if(!len||len>=sizeof path)return -1;tail=strrchr(path,'\\');if(!tail||tail-path+13>=MAX_PATH)return -1;strcpy(tail+1,"ndisapi.dll");dll=LoadLibraryA(path);if(!dll){fprintf(stderr,"Install matching legacy ndisapi.dll beside MARSNET.EXE.\n");return -1;} + RESOLVE(Open,open_fn,"OpenFilterDriver");RESOLVE(Close,close_fn,"CloseFilterDriver");RESOLVE(Loaded,loaded_fn,"IsDriverLoaded");RESOLVE(List,list_fn,"GetTcpipBoundAdaptersInfo");RESOLVE(GetMode,mode_fn,"GetAdapterMode");RESOLVE(SetMode,mode_fn,"SetAdapterMode");RESOLVE(Read,packet_fn,"ReadPacket");RESOLVE(Inject,packet_fn,"SendPacketToMstcp");RESOLVE(Flush,flush_fn,"FlushAdapterPacketQueue");RESOLVE(SetEventFor,event_fn,"SetPacketEvent"); + driver=Open(TEXT("NDISRD"));if(!driver||driver==INVALID_HANDLE_VALUE||!Loaded(driver)){fprintf(stderr,"Legacy packet filter driver not loaded.\n");return -1;}memset(&adapters,0,sizeof adapters);if(!List(driver,&adapters)||adapters.m_nAdapterCount>ADAPTER_LIST_SIZE)return -1;return 0;} +static int list_filter(void){DWORD i;if(filter_open())return -1;for(i=0;iPKT_FRAME||b.m_Length<14){core.dropped++;return -1;}memcpy(f,b.m_IBuffer,b.m_Length);return (int)b.m_Length;} +static int virtual_in(const uint8_t*f,int n){ETH_REQUEST q;INTERMEDIATE_BUFFER b;memset(&q,0,sizeof q);memset(&b,0,sizeof b);q.hAdapterHandle=adapter;q.EthPacket.Buffer=&b;b.m_hAdapter=adapter;b.m_dwDeviceFlags=PACKET_FLAG_ON_RECEIVE;b.m_Length=(DWORD)n;memcpy(b.m_IBuffer,f,n);return Inject(driver,&q)?0:-1;} +static void virtual_idle(void){WaitForSingleObject(packet_event,20);ResetEvent(packet_event);} +static void close_virtual(void){if(driver&&driver!=INVALID_HANDLE_VALUE){if(tunnel_mode){if(!SetMode(driver,&oldmode))fprintf(stderr,"Failed to restore adapter mode; reboot before reuse.\n");Flush(driver,adapter);}if(event_set)SetEventFor(driver,adapter,NULL);Close(driver);}if(packet_event)CloseHandle(packet_event);if(dll)FreeLibrary(dll);} +#elif defined(MARS_LEGACY) +#include "ndis3/packet_backend.inc" +#elif defined(MARS_NATIVE) +/* Own NDIS5 miniport data path, no external packet filter or TAP driver. */ +static HANDLE device=INVALID_HANDLE_VALUE; +static int enable_privilege(void){HANDLE token;TOKEN_PRIVILEGES tp;LUID id;DWORD err;BOOL ok;if(!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,&token))return -1;if(!LookupPrivilegeValueA(NULL,"SeLoadDriverPrivilege",&id)){CloseHandle(token);return -1;}tp.PrivilegeCount=1;tp.Privileges[0].Luid=id;tp.Privileges[0].Attributes=SE_PRIVILEGE_ENABLED;SetLastError(ERROR_SUCCESS);ok=AdjustTokenPrivileges(token,FALSE,&tp,0,NULL,NULL);err=GetLastError();CloseHandle(token);return ok&&err==ERROR_SUCCESS?0:-1;} +static int open_virtual(const char*name){uint8_t mac[6];DWORD n=0;if(strcmp(name,"MARS"))return -1;if(enable_privilege()){fprintf(stderr,"Administrator token with SeLoadDriverPrivilege required.\n");return -1;}device=CreateFileA(MARS_CTL_NAME,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);if(device==INVALID_HANDLE_VALUE){fprintf(stderr,"Own MARS NDIS driver unavailable (%lu).\n",GetLastError());return -1;}if(!DeviceIoControl(device,MARS_CTL_MAC,NULL,0,mac,sizeof mac,&n,NULL)||n!=6||memcmp(mac,core.node,6)){fprintf(stderr,"MARS adapter NetworkAddress must equal physical IPX node.\n");return -1;}return 0;} +static int virtual_out(uint8_t*f){DWORD n=0;if(!DeviceIoControl(device,MARS_CTL_POP,NULL,0,f,PKT_FRAME,&n,NULL))return -2;if(n>PKT_FRAME||(n&&n<14))return -2;return (int)n;} +static int virtual_in(const uint8_t*f,int n){DWORD bytes=0;return DeviceIoControl(device,MARS_CTL_PUSH,(void*)f,(DWORD)n,NULL,0,&bytes,NULL)?0:-1;} +static void virtual_idle(void){Sleep(10);} +static void close_virtual(void){if(device!=INVALID_HANDLE_VALUE)CloseHandle(device);} +#else +/* TAP-Win32 8/9 historical adapter, only Windows 2000/XP builds. */ +#define TAPCTL(n) CTL_CODE(FILE_DEVICE_UNKNOWN,n,METHOD_BUFFERED,FILE_ANY_ACCESS) +static HANDLE tap=INVALID_HANDLE_VALUE,read_event,write_event;static OVERLAPPED rd,wr;static int pending;static uint8_t tap_buffer[PKT_FRAME+4]; +static int open_virtual(const char*guid){char name[128];DWORD len=0,media=1;uint8_t mac[6];size_t i;if(strlen(guid)!=38||guid[0]!='{'||guid[37]!='}')return -1;for(i=1;i<37;i++)if(!strchr("0123456789abcdefABCDEF-",guid[i]))return -1;sprintf(name,"\\\\.\\Global\\%s.tap",guid);tap=CreateFileA(name,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM|FILE_FLAG_OVERLAPPED,NULL);if(tap==INVALID_HANDLE_VALUE){fprintf(stderr,"Cannot open TAP adapter (%lu)\n",GetLastError());return -1;} + /* Opened overlapped: use an event for IOCTL completion as well. */ + read_event=CreateEvent(NULL,TRUE,FALSE,NULL);write_event=CreateEvent(NULL,TRUE,FALSE,NULL);if(!read_event||!write_event)return -1;rd.hEvent=read_event;wr.hEvent=write_event; + if(!DeviceIoControl(tap,TAPCTL(1),mac,sizeof mac,mac,sizeof mac,&len,&wr)){if(GetLastError()!=ERROR_IO_PENDING||!GetOverlappedResult(tap,&wr,&len,TRUE))return -1;} + if(len!=6||memcmp(mac,core.node,6)){fprintf(stderr,"TAP MAC must match physical IPX node.\n");return -1;} + ResetEvent(write_event);if(!DeviceIoControl(tap,TAPCTL(6),&media,sizeof media,&media,sizeof media,&len,&wr)){if(GetLastError()!=ERROR_IO_PENDING||!GetOverlappedResult(tap,&wr,&len,TRUE))return -1;}return 0;} +static int virtual_out(uint8_t*f){DWORD len=0;if(pending){if(!GetOverlappedResult(tap,&rd,&len,FALSE)){if(GetLastError()==ERROR_IO_INCOMPLETE)return 0;pending=0;return -2;}pending=0;}else{ResetEvent(read_event);if(!ReadFile(tap,tap_buffer,sizeof tap_buffer,&len,&rd)){if(GetLastError()==ERROR_IO_PENDING){pending=1;return 0;}return -2;}}if(len<14||len>PKT_FRAME){core.dropped++;return -1;}memcpy(f,tap_buffer,len);return (int)len;} +static int virtual_in(const uint8_t*f,int n){DWORD len=0;ResetEvent(write_event);if(!WriteFile(tap,f,(DWORD)n,&len,&wr)){if(GetLastError()!=ERROR_IO_PENDING)return -1;if(WaitForSingleObject(write_event,1000)!=WAIT_OBJECT_0){CancelIo(tap);/* All I/O started by this same thread is cancelled. Drain before buffer lifetime ends. */GetOverlappedResult(tap,&wr,&len,TRUE);if(pending){GetOverlappedResult(tap,&rd,&len,TRUE);pending=0;}return -1;}if(!GetOverlappedResult(tap,&wr,&len,FALSE))return -1;}return len==(DWORD)n?0:-1;} +static void virtual_idle(void){if(pending)WaitForSingleObject(read_event,20);else Sleep(10);} +static void close_virtual(void){DWORD len;if(tap!=INVALID_HANDLE_VALUE){CancelIo(tap);if(pending)GetOverlappedResult(tap,&rd,&len,TRUE);CloseHandle(tap);}if(read_event)CloseHandle(read_event);if(write_event)CloseHandle(write_event);} +#endif +static int bridge(void){int i,n;uint8_t f[PKT_FRAME];DWORD last=GetTickCount();printf("Bridge active. Renew DHCP on the virtual adapter. Ctrl+C to stop.\n");while(!stopping()){ + for(i=0;i<64&&!stopping();i++){n=virtual_out(f);if(!n)break;if(n==-2)return -1;if(n>0)client_tx(&core,f,(size_t)n,emit_ipx,NULL);} + for(i=0;i<64&&!stopping();i++){n=receive_ipx(f);if(n==-2)break;if(n==-3)return -1;if(n>0&&virtual_in(f,n)){fprintf(stderr,"Virtual receive injection failed.\n");return -1;}} + if(GetTickCount()-last>=10000UL){printf("TX %lu RX %lu dropped %lu I/O errors %lu\n",core.tx,core.received,core.dropped,io_errors);last=GetTickCount();}virtual_idle();}return 0;} +int main(int argc,char**argv){int rc=1;uint8_t node[6],gw[4],probe[60];HANDLE lock=NULL;if(init_winsock())return 1; + if(argc==2&&!strcmp(argv[1],"--ipx")){rc=list_ipx()!=0;goto done;} +#if defined(MARS_FILTER) + if(argc==2&&!strcmp(argv[1],"--list")){rc=list_filter()!=0;goto done;} +#elif defined(MARS_LEGACY) + if(argc==2&&!strcmp(argv[1],"--list")){rc=list_legacy()!=0;goto done;} +#endif + if(argc==4&&!strcmp(argv[1],"--discover")){if(client_hex(argv[2],node,6)||read_ini(argv[3],node,gw)||open_ipx())goto done;client_probe(&core,gw,probe);if(client_tx(&core,probe,sizeof probe,emit_ipx,NULL))goto done;puts("Discovery probe sent. Check MARS Gateway / observed devices; this does not prove receipt.");rc=0;goto done;} + if(argc!=6||strcmp(argv[1],"--run")||strcmp(argv[5],"--confirm-virtual")||client_hex(argv[3],node,6)||read_ini(argv[4],node,gw)){fprintf(stderr,"Usage: --ipx | --discover NODE GATEWAY.INI | --run VIRTUAL_ADAPTER NODE GATEWAY.INI --confirm-virtual\n" +#if defined(MARS_FILTER) + "--list shows exact virtual adapter device names.\n" +#elif defined(MARS_NATIVE) + "VIRTUAL_ADAPTER must be MARS (own NDIS5 driver).\n" +#elif defined(MARS_LEGACY) + "--list shows Packet.dll adapters. Use the exact MARS NDIS3 adapter name.\n" +#else + "VIRTUAL_ADAPTER is the TAP device GUID {....}.\n" +#endif + "NODE is 12 hex digits, the physical IPX node.\n");goto done;} + lock=CreateMutexA(NULL,FALSE,"MARSNET-IPXPKT-ONE-INSTANCE");if(!lock||GetLastError()==ERROR_ALREADY_EXISTS){fprintf(stderr,"Another MARSNET instance is active.\n");goto done;} + if(open_ipx()||!SetConsoleCtrlHandler(on_ctrl,TRUE)||open_virtual(argv[2]))goto done; + client_probe(&core,gw,probe);client_tx(&core,probe,sizeof probe,emit_ipx,NULL);rc=bridge()!=0; + done:close_virtual();if(ipx!=INVALID_SOCKET)closesocket(ipx);if(lock)CloseHandle(lock);if(winsock_started)WSACleanup();return rc;} diff --git a/clients/windows/ndis3/INSTALL.BAT b/clients/windows/ndis3/INSTALL.BAT new file mode 100644 index 0000000..25f9bf0 --- /dev/null +++ b/clients/windows/ndis3/INSTALL.BAT @@ -0,0 +1,29 @@ +@echo off +rem Run from the copied local package directory (also supports COMMAND.COM). +if not exist WPCAP31.EXE goto missing +if not exist MARSNET3.SYS goto missing +echo MARS Legacy Setup - Win95/98/ME or NT4 x86 +echo The original WinPcap 3.1 wizard will start now. +echo If another WinPcap version is installed, cancel and review it first. +echo Complete the wizard. Do not enable remote capture unless needed. +pause +start /wait WPCAP31.EXE +echo. +echo Continue only if WinPcap setup succeeded. Reboot if requested. +echo MARS adapter installation is a separate manual step: +if exist OEMSETUP.INF goto nt4 +echo Add New Hardware - Have Disk - select MARSNET.INF. +echo Set NetworkAddress to your physical IPX node (12 hex digits). +goto done +:nt4 +echo Read NT4-INSTALL.txt and set NetworkAddress in OEMSETUP.INF first. +echo Network - Adapters - Add - Have Disk - select this directory. +:done +echo After installation and reboot, use MARSNET.EXE --list. +echo This script does not change network bindings or claim setup success. +pause +goto end +:missing +echo Run INSTALL.BAT from the complete local WIN95/98/ME/NT40 directory. +pause +:end diff --git a/clients/windows/ndis3/MARSNET.INF b/clients/windows/ndis3/MARSNET.INF new file mode 100644 index 0000000..840813f --- /dev/null +++ b/clients/windows/ndis3/MARSNET.INF @@ -0,0 +1,37 @@ +; Experimental Win9x network class INF. Manual installation in isolated VM only. +[Version] +Signature="$CHICAGO$" +Class=Net +Provider=%Provider% +[Manufacturer] +%Provider%=MARSModels +[MARSModels] +%Adapter%=MARSInstall,ROOT\MARSNET3 +[MARSInstall] +CopyFiles=MARSFiles +AddReg=MARSReg +[MARSReg] +HKR,,DeviceVxDs,,"MARSNET3.SYS" +HKR,,DevLoader,,"*ndis" +HKR,,NDISVersion,1,03,00 +HKR,,DriverDesc,,%Adapter% +HKR,Ndi,DeviceID,,"ROOT\MARSNET3" +HKR,Ndi\Interfaces,UpperRange,,"ndis3" +HKR,Ndi\Interfaces,LowerRange,,"ethernet" +HKR,Ndi\params\NetworkAddress,ParamDesc,,"Physical IPX node (12 hex digits)" +HKR,Ndi\params\NetworkAddress,type,,"edit" +HKR,Ndi\params\NetworkAddress,LimitText,,"12" +HKR,Ndi\params\NetworkAddress,Optional,,"1" +; No default MAC: the operator must set the IPX node before using it. +[MARSFiles] +MARSNET3.SYS +[DestinationDirs] +MARSFiles=11 +[SourceDisksNames] +1=%Disk%,,, +[SourceDisksFiles] +MARSNET3.SYS=1 +[Strings] +Provider="MARS VME" +Adapter="MARS Virtual IPX Ethernet NDIS3 (experimental)" +Disk="MARS NDIS3 driver" diff --git a/clients/windows/ndis3/NT4-INSTALL.txt b/clients/windows/ndis3/NT4-INSTALL.txt new file mode 100644 index 0000000..d0d3b8b --- /dev/null +++ b/clients/windows/ndis3/NT4-INSTALL.txt @@ -0,0 +1,26 @@ +MARS NDIS3 - Windows NT 4.0 x86 development candidate + +OEMSETUP.INF uses the NT4 Network Control Panel scripting format, not a +Windows 2000 INF. It is generated from the locally supplied NT4 DDK sample. +No installer or driver runtime validation on NT4 has been performed. + +1. Set NetworkAddress in OEMSETUP.INF (in [FileConstants]) to the physical + IPX node: exactly 12 hex digits, no separators, nonzero unicast address. + Do NOT use a made-up address. Leaving it empty makes setup fail explicitly. + Alternatively generate the package on Linux with: + MARS_NT4_NETWORK_ADDRESS= ./build-windows.sh --no-install WINNT40 +2. Copy the entire WINNT40 directory to the NT4 x86 test VM. +3. Control Panel -> Network -> Adapters -> Add -> Have Disk, select this + directory and MARS Virtual IPX Ethernet NDIS3. + NT4's UTILITY.INF and SUBROUTN.INF are required from the installed OS. +4. In Network bindings, bind TCP/IP to the virtual adapter; retain the + physical adapter's IPX stack. Do not migrate bindings on a production host. +5. Reboot. Verify service/adapter startup and the configured NetworkAddress + in HKLM\SYSTEM\CurrentControlSet\Services\MARSNET3\Parameters. +6. A compatible NT4 WinPcap/Packet.dll installation is required separately. + MARSNET.EXE --list must show the adapter. Continue with LEGACY-BUILD.md. + +Removal: Network -> Adapters -> select MARS adapter -> Remove -> reboot. +Use a VM snapshot before testing installation, bindings, and removal. +A generated INF is not proof of successful NT4 installation or connectivity. +Only ENG/GER setup language IDs are currently included (English text). diff --git a/clients/windows/ndis3/freestanding/string.h b/clients/windows/ndis3/freestanding/string.h new file mode 100644 index 0000000..020c174 --- /dev/null +++ b/clients/windows/ndis3/freestanding/string.h @@ -0,0 +1,8 @@ +#ifndef MARS_LOCAL_STRING_H +#define MARS_LOCAL_STRING_H +#include +void *memcpy(void *,const void *,size_t); +void *memset(void *,int,size_t); +int memcmp(const void *,const void *,size_t); +size_t strlen(const char *); +#endif diff --git a/clients/windows/ndis3/freestanding/time.h b/clients/windows/ndis3/freestanding/time.h new file mode 100644 index 0000000..72c4dcb --- /dev/null +++ b/clients/windows/ndis3/freestanding/time.h @@ -0,0 +1,5 @@ +/* Minimal build-only Windows x86 time type for IPXPKT. Monotonic seconds from GetTickCount. */ +#ifndef MARS_LOCAL_TIME_H +#define MARS_LOCAL_TIME_H +typedef long time_t; +#endif diff --git a/clients/windows/ndis3/legacy_bridge.c b/clients/windows/ndis3/legacy_bridge.c new file mode 100644 index 0000000..bb7b281 --- /dev/null +++ b/clients/windows/ndis3/legacy_bridge.c @@ -0,0 +1,106 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later + * CRT-free x86 Win32 transport for MARS NDIS3. Winsock 1.1 + WinPcap 3.1 + * Packet.dll OID API. Not a packet sniffer; writes only to verified virtual NIC. + * Historical Windows kernel/driver compatibility not established by PE build. + */ +#include "../client_core.h" +#include "legacy_core.h" +#include +typedef unsigned long U32; +typedef unsigned short U16; +typedef unsigned char U8; +#define I __declspec(dllimport) +#define S __stdcall +I void S ExitProcess(U32); +I void* S GetStdHandle(U32); +I int S WriteFile(void*,const void*,U32,U32*,void*); +I char* S GetCommandLineA(void); +I U32 S GetFullPathNameA(const char*,U32,char*,char**); +I U32 S GetPrivateProfileStringA(const char*,const char*,const char*,char*,U32,const char*); +I unsigned S GetSystemDirectoryA(char*,unsigned); +I void* S LoadLibraryA(const char*); +I void* S GetProcAddress(void*,const char*); +I int S FreeLibrary(void*); +I U32 S GetTickCount(void); +I void S Sleep(U32); +I int S SetConsoleCtrlHandler(int (S *)(U32),int); +I void* S CreateMutexA(void*,int,const char*); +I int S CloseHandle(void*); +I U32 S GetLastError(void); +I int S WSAStartup(U16,void*); +I int S WSACleanup(void); +I int S WSAGetLastError(void); +I U32 S socket(int,int,int); +I int S closesocket(U32); +I int S setsockopt(U32,int,int,const char*,int); +I int S bind(U32,const void*,int); +I int S getsockname(U32,void*,int*); +I int S ioctlsocket(U32,long,U32*); +I int S sendto(U32,const char*,int,int,const void*,int); +I int S recvfrom(U32,char*,int,int,void*,int*); +/* No CRT; volatile copy/clear prevents optimizer replacement by recursive calls. */ +void *memcpy(void*d,const void*s,size_t n){volatile U8*a=d;const U8*b=s;while(n--)*a++=*b++;return d;} +void *memset(void*d,int v,size_t n){volatile U8*a=d;while(n--)*a++=(U8)v;return d;} +int memcmp(const void*a,const void*b,size_t n){const U8*x=a,*y=b;while(n--){if(*x!=*y)return (int)*x-(int)*y;x++;y++;}return 0;} +size_t strlen(const char*s){size_t n=0;while(s[n])n++;return n;} +static int eq(const char*a,const char*b){size_t n=strlen(a);return n==strlen(b)&&!memcmp(a,b,n);} +struct ipxaddr {U16 family;U8 net[4],node[6];U16 port;}; +struct oid {U32 oid,length;U8 data[MARS_OID_FRAME_SIZE];}; +typedef void* (__cdecl *openfn)(char*); +typedef void (__cdecl *closefn)(void*); +typedef U8 (__cdecl *requestfn)(void*,U8,struct oid*); +typedef U8 (__cdecl *namesfn)(char*,U32*); +typedef char* (__cdecl *versionfn)(void); +typedef char addr_check[sizeof(struct ipxaddr)==14?1:-1]; +typedef char oid_check[offsetof(struct oid,data)==8?1:-1]; +static struct client_core core; +static struct ipxaddr peer; +static U32 sock=0xffffffffUL; +static int wsa,linked; +static volatile int stopping; +static void *console,*dll,*adapter,*mutex; +static closefn closep;static openfn openp;static requestfn requestp;static namesfn namesp;static versionfn versionp; +static union {U32 align;U8 bytes[512];} wsadata; +static char cmd[2048],names[32768],path[260]; +static U8 frame[PKT_FRAME],packet[546],gw[4]; +static struct oid request; +static void text(const char*s){U32 w;WriteFile(console,s,(U32)strlen(s),&w,0);} +static void number(U32 v){char b[11];unsigned i=10;b[i]=0;do{b[--i]=(char)('0'+v%10);v/=10;}while(v);text(b+i);} +static U32 netnum(const U8*n){return ((U32)n[0]<<24)|((U32)n[1]<<16)|((U32)n[2]<<8)|n[3];} +static U16 swap(U16 x){return (U16)((x<<8)|(x>>8));} +/* Simple bounded command line: quoted path or adapter name, no embedded quotes. */ +static int args(char**v,int cap){const char*p=GetCommandLineA();char*w=cmd;int n=0,q;while(*p){while(*p==' '||*p=='\t')p++;if(!*p)break;if(n==cap)return -1;v[n++]=w;q=0;while(*p){if(*p=='"'){q=!q;p++;continue;}if(!q&&(*p==' '||*p=='\t'))break;if(w>=cmd+sizeof cmd-1)return -1;*w++=*p++;}if(q||w>=cmd+sizeof cmd)return -1;*w++=0;}return n;} +static int ip4(const char*s,U8*out){unsigned i,v,n;for(i=0;i<4;i++){v=0;n=0;while(*s>='0'&&*s<='9'){v=v*10+(*s++-'0');if(++n>3||v>255)return -1;}if(!n)return -1;out[i]=(U8)v;if(i<3&&*s++!='.')return -1;}return *s?-1:0;} +static int config(const char*file,const char*node){char n[32],m[32],p[16],ip[32],*last;U8 net[4],mac[6],server[6];U16 port;U32 l=GetFullPathNameA(file,sizeof path,path,&last);if(!l||l>=sizeof path)return -1; + GetPrivateProfileStringA("gateway","network","",n,sizeof n,path);GetPrivateProfileStringA("gateway","server","",m,sizeof m,path);GetPrivateProfileStringA("gateway","port","6181",p,sizeof p,path);GetPrivateProfileStringA("gateway","ip","",ip,sizeof ip,path); + port=eq(p,"6181")?PKT_TRAIL:eq(p,"6180")?PKT_PLAIN:0;if(!port||client_hex(n,net,4)||client_hex(m,server,6)||client_hex(node,mac,6)||ip4(ip,gw))return -1; + return client_init(&core,netnum(net),mac,server,port); +} +static int load_packet(void){unsigned n=GetSystemDirectoryA(path,sizeof path);const char*version;if(!n||n>=sizeof path-12)return -1;memcpy(path+n,"\\Packet.dll",12);dll=LoadLibraryA(path);if(!dll)return -1; + openp=(openfn)GetProcAddress(dll,"PacketOpenAdapter");closep=(closefn)GetProcAddress(dll,"PacketCloseAdapter");requestp=(requestfn)GetProcAddress(dll,"PacketRequest");namesp=(namesfn)GetProcAddress(dll,"PacketGetAdapterNames");versionp=(versionfn)GetProcAddress(dll,"PacketGetVersion");if(!openp||!closep||!requestp||!namesp||!versionp)return -1; + version=versionp();if(!version||strlen(version)<3||memcmp(version,"3.1",3))return -1;return 0; +} +static int oid(U32 id,int set,U8*d,U32 n){if(!adapter||n>sizeof request.data)return -1;memset(&request,0,sizeof request);request.oid=id;request.length=n;if(set)memcpy(request.data,d,n);if(!requestp(adapter,(U8)set,&request)||request.length!=n)return -1;if(!set)memcpy(d,request.data,n);return 0;} +static int list(void){U32 n=sizeof names;char*p,*q,*end;if(load_packet()||!namesp(names,&n)||!n||n>sizeof names)return -1;end=names+n;for(p=names;p1023)return -1;adapter=openp(name);if(!adapter)return -1; + if(oid(MARS_OID_IDENT,0,ident,8)||memcmp(ident,MARS_IDENT,8)||oid(0x01010102UL,0,mac,6)||memcmp(mac,core.node,6)){text("Not the requested MARS virtual adapter / MAC. No MARS tunnel enabled.\r\n");return -1;} + if(oid(MARS_OID_LINK,1,&up,1))return -1;linked=1;return 0;} +static int ipx_open(void){struct ipxaddr a,b;int t=4,len=sizeof b;U32 nb=1;if(WSAStartup(0x0101,wsadata.bytes))return -1;wsa=1;sock=socket(6,2,1000);if(sock==0xffffffffUL)return -1;memset(&a,0,sizeof a);a.family=6;a.net[0]=(U8)(core.net>>24);a.net[1]=(U8)(core.net>>16);a.net[2]=(U8)(core.net>>8);a.net[3]=(U8)core.net;memcpy(a.node,core.node,6);a.port=swap(core.port); + if(setsockopt(sock,1000,0x4000,(const char*)&t,sizeof t)||bind(sock,&a,sizeof a)||getsockname(sock,&b,&len)||len!=(int)sizeof b||memcmp(&a,&b,sizeof a)||ioctlsocket(sock,0x8004667eUL,&nb))return -1; + memcpy(&peer,&a,sizeof peer);memcpy(peer.node,core.server,6);return 0;} +static int emit(void*unused,const U8*p,size_t n){(void)unused;return sendto(sock,(const char*)p,(int)n,0,&peer,sizeof peer)==(int)n?0:-1;} +static int S signal_stop(U32 code){if(code<=2||code==5||code==6){stopping=1;return 1;}return 0;} +static int run(void){U8 b[MARS_OID_FRAME_SIZE];int i,n,l,err;U32 last=GetTickCount();struct ipxaddr src; + client_probe(&core,gw,frame);if(client_tx(&core,frame,60,emit,0))text("Initial discovery probe failed.\r\n"); + text("Bridge active; renew DHCP on virtual adapter. Ctrl+C stops.\r\n"); + while(!stopping){for(i=0;i<32&&!stopping;i++){if(oid(MARS_OID_POP,0,b,sizeof b))return -1;n=b[0]|((unsigned)b[1]<<8);if(!n)break;if(n<14||n>PKT_FRAME)return -1;client_tx(&core,b+2,(size_t)n,emit,0);} + for(i=0;i<32&&!stopping;i++){l=sizeof src;n=recvfrom(sock,(char*)packet,sizeof packet,0,&src,&l);if(n<0){err=WSAGetLastError();if(err==10035)break;if(err==10040)continue;return -1;}if(l!=(int)sizeof src||src.family!=6)continue;n=client_rx(&core,netnum(src.net),src.node,swap(src.port),packet,(size_t)n,(time_t)(GetTickCount()/1000UL),frame);if(n>0){memset(b,0,sizeof b);b[0]=(U8)n;b[1]=(U8)(n>>8);memcpy(b+2,frame,n);if(oid(MARS_OID_PUSH,1,b,sizeof b))return -1;}} + if(GetTickCount()-last>=10000UL){text("TX ");number(core.tx);text(" RX ");number(core.received);text(" dropped ");number(core.dropped);text("\r\n");last=GetTickCount();}Sleep(10);} + return 0;} +void start(void){char*v[6];int n,rc=1;U8 down=0;console=GetStdHandle((U32)-11);n=args(v,6); + if(n==2&&eq(v[1],"--list")){rc=list()!=0;goto done;} + if(n==4&&eq(v[1],"--discover")){if(!config(v[3],v[2])&&!ipx_open()){client_probe(&core,gw,frame);rc=client_tx(&core,frame,60,emit,0)!=0;if(!rc)text("Probe sent. Check the server gateway devices.\r\n");}goto done;} + if(n!=6||!eq(v[1],"--run")||!eq(v[5],"--confirm-virtual")){text("Usage: MARSNET --list | --discover NODE GATEWAY.INI | --run ADAPTER NODE GATEWAY.INI --confirm-virtual\r\n");goto done;} + mutex=CreateMutexA(0,0,"MARSNET-IPXPKT-ONE-INSTANCE");if(!mutex||GetLastError()==183)goto done; + if(config(v[4],v[3])||ipx_open()||!SetConsoleCtrlHandler(signal_stop,1)||attach(v[2]))goto done;rc=run()!=0; + done:if(rc)text("MARSNET failed. Check IPX binding, Packet.dll 3.1, adapter and GATEWAY.INI.\r\n");if(linked)oid(MARS_OID_LINK,1,&down,1);if(adapter&&closep)closep(adapter);if(dll)FreeLibrary(dll);if(sock!=0xffffffffUL)closesocket(sock);if(wsa)WSACleanup();if(mutex)CloseHandle(mutex);ExitProcess((U32)rc);} diff --git a/clients/windows/ndis3/legacy_core.c b/clients/windows/ndis3/legacy_core.c new file mode 100644 index 0000000..5857e3d --- /dev/null +++ b/clients/windows/ndis3/legacy_core.c @@ -0,0 +1,17 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later + * Shared serialized miniport core; no OS API, no malloc, no CRT dependency. + */ +#include "legacy_core.h" +void lc_copy(void *d,const void *s,unsigned n){unsigned char *a=d;const unsigned char *b=s;while(n--)*a++=*b++;} +void lc_zero(void *d,unsigned n){unsigned char *a=d;while(n--)*a++=0;} +int lc_mac_equal(const unsigned char*a,const unsigned char*b){unsigned i;for(i=0;i<6;i++)if(a[i]!=b[i])return 0;return 1;} +int lc_valid_mac(const unsigned char*a){static const unsigned char z[6]={0};return !(a[0]&1)&&!lc_mac_equal(a,z);} +int lc_frame(const unsigned char*f,unsigned n){return n>=14&&n<=MARS_FRAME_MAX&&f[12]==8&&(f[13]==0||f[13]==6);} +void lc_init(struct legacy_core*c,const unsigned char*mac){lc_zero(c,sizeof *c);lc_copy(c->mac,mac,6);c->lookahead=1500;} +int lc_receive_allowed(const struct legacy_core*c,const unsigned char*f,unsigned n){static const unsigned char bc[6]={255,255,255,255,255,255};unsigned i;if(!lc_frame(f,n))return 0;if(c->filter&MF_PROMISC)return 1;if(lc_mac_equal(f,bc))return (c->filter&MF_BROADCAST)!=0;if(lc_mac_equal(f,c->mac))return (c->filter&MF_DIRECTED)!=0;if(f[0]&1){if(c->filter&MF_ALLMULTI)return 1;if(c->filter&MF_MULTICAST)for(i=0;imulticount;i++)if(lc_mac_equal(f,c->multicast[i]))return 1;}return 0;} +void lc_link(struct legacy_core*c,unsigned up){if(!up||!c->lease){mars_ring_clear(&c->tx);mars_ring_clear(&c->rx);}c->lease=up?MARS_LEASE_TICKS:0;} +void lc_tick(struct legacy_core*c){if(c->lease&&!--c->lease)lc_link(c,0);} +int lc_send(struct legacy_core*c,const unsigned char*f,unsigned n){if(!c->lease||!lc_frame(f,n)||!lc_mac_equal(f+6,c->mac)||mars_ring_push(&c->tx,f,n)){c->tx_bad++;return -1;}c->tx_ok++;return 0;} +int lc_push(struct legacy_core*c,const unsigned char*f,unsigned n){if(!c->lease||!lc_frame(f,n)){c->rx_bad++;return -1;}if(!lc_receive_allowed(c,f,n))return 0;if(mars_ring_push(&c->rx,f,n)){c->rx_full++;return -1;}return 0;} +int lc_pop(struct legacy_core*c,unsigned char*f,unsigned cap){if(!c->lease)return -1;c->lease=MARS_LEASE_TICKS;return mars_ring_pop(&c->tx,f,cap);} +int lc_rx(struct legacy_core*c,unsigned char*f,unsigned cap){int n=mars_ring_pop(&c->rx,f,cap);if(n>0)c->rx_ok++;return n;} diff --git a/clients/windows/ndis3/legacy_core.h b/clients/windows/ndis3/legacy_core.h new file mode 100644 index 0000000..98222f0 --- /dev/null +++ b/clients/windows/ndis3/legacy_core.h @@ -0,0 +1,38 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef MARS_LEGACY_CORE_H +#define MARS_LEGACY_CORE_H +#include "../ndis5/frame_queue.h" +/* Fixed little-endian wire layout for Win32 PacketRequest. No native pointer. */ +#define MARS_OID_IDENT 0xFF4D4101UL +#define MARS_OID_POP 0xFF4D4102UL +#define MARS_OID_PUSH 0xFF4D4103UL +#define MARS_OID_LINK 0xFF4D4104UL +#define MARS_IDENT "MARSIPX3" +#define MARS_OID_FRAME_SIZE (2+MARS_FRAME_MAX) +#define MF_DIRECTED 1U +#define MF_MULTICAST 2U +#define MF_ALLMULTI 4U +#define MF_BROADCAST 8U +#define MF_PROMISC 32U +#define MF_ALLOWED (MF_DIRECTED|MF_MULTICAST|MF_ALLMULTI|MF_BROADCAST|MF_PROMISC) +#define MARS_LEASE_TICKS 50 /* 5 seconds if timer period 100 ms */ +struct legacy_core { + struct mars_ring tx, rx; + unsigned char mac[6], multicast[32][6]; + unsigned filter, lookahead, multicount, lease; + unsigned long tx_ok, rx_ok, tx_bad, rx_bad, rx_full; +}; +void lc_init(struct legacy_core *, const unsigned char *); +int lc_mac_equal(const unsigned char *, const unsigned char *); +int lc_valid_mac(const unsigned char *); +int lc_frame(const unsigned char *, unsigned); +int lc_receive_allowed(const struct legacy_core *,const unsigned char *,unsigned); +int lc_send(struct legacy_core *,const unsigned char *,unsigned); +int lc_push(struct legacy_core *,const unsigned char *,unsigned); +int lc_pop(struct legacy_core *,unsigned char *,unsigned); +int lc_rx(struct legacy_core *,unsigned char *,unsigned); +void lc_link(struct legacy_core *,unsigned); +void lc_tick(struct legacy_core *); +void lc_copy(void *,const void *,unsigned); +void lc_zero(void *,unsigned); +#endif diff --git a/clients/windows/ndis3/miniport.c b/clients/windows/ndis3/miniport.c new file mode 100644 index 0000000..52634b0 --- /dev/null +++ b/clients/windows/ndis3/miniport.c @@ -0,0 +1,110 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later + * NDIS 3.0 serialized software-only Ethernet adapter. Historical DDK candidate. + * Private OID interface is intended for a LOCAL protocol driver (PacketRequest). + * All callbacks serialized by NDIS; RX is indicated from miniport timer, not OID. + * No NT IRP API, NDIS5 registration, physical NIC or TCP sockets in this driver. + */ +/* ndis.h supplies the binary-compatible Win9x types itself. */ +#include +#include "legacy_core.h" +typedef struct _MARS_ADAPTER { + NDIS_HANDLE mini; + NDIS_MINIPORT_TIMER timer; + struct legacy_core core; + UCHAR receive[MARS_FRAME_MAX]; + UINT receive_len; + BOOLEAN receiving, armed; +} MARS_ADAPTER; +static NDIS_HANDLE wrapper; +static const NDIS_OID oids[]={ + OID_GEN_SUPPORTED_LIST,OID_GEN_HARDWARE_STATUS,OID_GEN_MEDIA_SUPPORTED,OID_GEN_MEDIA_IN_USE, + OID_GEN_MAXIMUM_LOOKAHEAD,OID_GEN_MAXIMUM_FRAME_SIZE,OID_GEN_LINK_SPEED, + OID_GEN_TRANSMIT_BUFFER_SPACE,OID_GEN_RECEIVE_BUFFER_SPACE,OID_GEN_TRANSMIT_BLOCK_SIZE,OID_GEN_RECEIVE_BLOCK_SIZE, + OID_GEN_VENDOR_ID,OID_GEN_VENDOR_DESCRIPTION,OID_GEN_CURRENT_PACKET_FILTER,OID_GEN_CURRENT_LOOKAHEAD, + OID_GEN_DRIVER_VERSION,OID_GEN_MAXIMUM_TOTAL_SIZE,OID_GEN_PROTOCOL_OPTIONS,OID_GEN_MAC_OPTIONS, + OID_GEN_XMIT_OK,OID_GEN_RCV_OK,OID_GEN_XMIT_ERROR,OID_GEN_RCV_ERROR,OID_GEN_RCV_NO_BUFFER, + OID_802_3_PERMANENT_ADDRESS,OID_802_3_CURRENT_ADDRESS,OID_802_3_MULTICAST_LIST,OID_802_3_MAXIMUM_LIST_SIZE, + OID_802_3_RCV_ERROR_ALIGNMENT,OID_802_3_XMIT_ONE_COLLISION,OID_802_3_XMIT_MORE_COLLISIONS, + MARS_OID_IDENT,MARS_OID_POP,MARS_OID_PUSH,MARS_OID_LINK +}; +static VOID arm(MARS_ADAPTER*a){if(!a->armed){a->armed=TRUE;NdisMSetTimer(&a->timer,100);}} +static VOID NTAPI timer_cb(PVOID one,PVOID ctx,PVOID two,PVOID three){MARS_ADAPTER*a=ctx;int n,i,indicated=0;UINT look; (void)one;(void)two;(void)three; + a->armed=FALSE;lc_tick(&a->core);if(!a->core.lease)return; + for(i=0;i<8;i++){ + n=lc_rx(&a->core,a->receive,sizeof a->receive);if(n<=0)break; + if(!lc_receive_allowed(&a->core,a->receive,(unsigned)n))continue; + a->receive_len=(UINT)n;a->receiving=TRUE;look=(UINT)n-14;if(look>a->core.lookahead)look=a->core.lookahead; + NdisMEthIndicateReceive(a->mini,a,a->receive,14,a->receive+14,look,(UINT)n-14); + a->receiving=FALSE;a->receive_len=0;indicated=1; + } + if(indicated)NdisMEthIndicateReceiveComplete(a->mini);arm(a); +} +static NDIS_STATUS NTAPI mp_init(PNDIS_STATUS error,PUINT selected,PNDIS_MEDIUM media,UINT count,NDIS_HANDLE mini,NDIS_HANDLE cfgctx){ + MARS_ADAPTER*a=NULL;NDIS_STATUS s;NDIS_HANDLE cfg;PVOID mac=NULL;UINT len=0,i;NDIS_PHYSICAL_ADDRESS high;UCHAR node[6]={0}; + *error=NDIS_STATUS_FAILURE;for(i=0;imini=mini;lc_init(&a->core,node); + NdisMSetAttributes(mini,a,FALSE,NdisInterfaceInternal);NdisMInitializeTimer(&a->timer,mini,timer_cb,a); + *error=NDIS_STATUS_SUCCESS;return NDIS_STATUS_SUCCESS; +} +static VOID NTAPI mp_halt(NDIS_HANDLE ctx){MARS_ADAPTER*a=ctx;BOOLEAN cancelled;lc_link(&a->core,0);NdisMCancelTimer(&a->timer,&cancelled);NdisFreeMemory(a,sizeof *a,0);} +static NDIS_STATUS NTAPI mp_send(NDIS_HANDLE ctx,PNDIS_PACKET packet,UINT flags){MARS_ADAPTER*a=ctx;PNDIS_BUFFER b;UINT total,part,pos=0;PVOID p;UCHAR frame[MARS_FRAME_MAX];(void)flags; + NdisQueryPacket(packet,NULL,NULL,&b,&total);if(total<14||total>sizeof frame)return NDIS_STATUS_INVALID_LENGTH; + while(b&&postotal-pos)return NDIS_STATUS_FAILURE;lc_copy(frame+pos,p,part);pos+=part;NdisGetNextBuffer(b,&b);} + if(pos!=total||lc_send(&a->core,frame,total))return NDIS_STATUS_FAILURE;return NDIS_STATUS_SUCCESS; +} +static NDIS_STATUS NTAPI mp_transfer(PNDIS_PACKET packet,PUINT moved,NDIS_HANDLE ctx,NDIS_HANDLE rxctx,UINT offset,UINT n){MARS_ADAPTER*a=ctx;PNDIS_BUFFER b;UINT part,total,want,pos=0;PVOID p;*moved=0; + if(!a->receiving||rxctx!=a||offset>a->receive_len-14)return NDIS_STATUS_FAILURE; + want=a->receive_len-14-offset;if(n>want)n=want;NdisQueryPacket(packet,NULL,NULL,&b,&total);if(n>total)n=total; + while(b&&posn-pos)part=n-pos;lc_copy(p,a->receive+14+offset+pos,part);pos+=part;NdisGetNextBuffer(b,&b);} + *moved=pos;return pos==n?NDIS_STATUS_SUCCESS:NDIS_STATUS_FAILURE; +} +static BOOLEAN NTAPI mp_hang(NDIS_HANDLE ctx){(void)ctx;return FALSE;} +static NDIS_STATUS NTAPI mp_reset(PBOOLEAN addr,NDIS_HANDLE ctx){MARS_ADAPTER*a=ctx;lc_link(&a->core,0);*addr=FALSE;return NDIS_STATUS_SUCCESS;} +static NDIS_STATUS NTAPI mp_query(NDIS_HANDLE ctx,NDIS_OID oid,PVOID out,ULONG cap,PULONG written,PULONG needed){MARS_ADAPTER*a=ctx;struct legacy_core*c=&a->core;ULONG val=0,n=4;USHORT ver=0x0300;const VOID*p=&val;int got;UCHAR*buf=out;static const CHAR name[]="MARS Virtual IPX Ethernet NDIS3";*written=*needed=0; + switch(oid){ + case MARS_OID_IDENT:p=MARS_IDENT;n=8;break; + case MARS_OID_POP: + if(cap>8);*written=MARS_OID_FRAME_SIZE;return NDIS_STATUS_SUCCESS; + case OID_GEN_SUPPORTED_LIST:p=oids;n=sizeof oids;break; + case OID_GEN_HARDWARE_STATUS:val=NdisHardwareStatusReady;break; + case OID_GEN_MEDIA_SUPPORTED:case OID_GEN_MEDIA_IN_USE:val=NdisMedium802_3;break; + case OID_GEN_MAXIMUM_LOOKAHEAD:case OID_GEN_MAXIMUM_FRAME_SIZE:val=1500;break; + case OID_GEN_LINK_SPEED:val=100000;break; + case OID_GEN_TRANSMIT_BUFFER_SPACE:case OID_GEN_RECEIVE_BUFFER_SPACE:val=MARS_RING_SIZE*MARS_FRAME_MAX;break; + case OID_GEN_TRANSMIT_BLOCK_SIZE:case OID_GEN_RECEIVE_BLOCK_SIZE:case OID_GEN_MAXIMUM_TOTAL_SIZE:val=MARS_FRAME_MAX;break; + case OID_GEN_VENDOR_ID:val=0x00ffffff;break; + case OID_GEN_VENDOR_DESCRIPTION:p=name;n=sizeof name;break; + case OID_GEN_CURRENT_PACKET_FILTER:val=c->filter;break; + case OID_GEN_CURRENT_LOOKAHEAD:val=c->lookahead;break; + case OID_GEN_DRIVER_VERSION:p=&ver;n=sizeof ver;break; + case OID_GEN_PROTOCOL_OPTIONS:val=0;break; + case OID_GEN_MAC_OPTIONS:val=NDIS_MAC_OPTION_NO_LOOPBACK|NDIS_MAC_OPTION_TRANSFERS_NOT_PEND;break; + case OID_GEN_XMIT_OK:val=c->tx_ok;break;case OID_GEN_RCV_OK:val=c->rx_ok;break; + case OID_GEN_XMIT_ERROR:val=c->tx_bad;break;case OID_GEN_RCV_ERROR:val=c->rx_bad;break;case OID_GEN_RCV_NO_BUFFER:val=c->rx_full;break; + case OID_802_3_PERMANENT_ADDRESS:case OID_802_3_CURRENT_ADDRESS:p=c->mac;n=6;break; + case OID_802_3_MULTICAST_LIST:p=c->multicast;n=c->multicount*6;break;case OID_802_3_MAXIMUM_LIST_SIZE:val=32;break; + case OID_802_3_RCV_ERROR_ALIGNMENT:case OID_802_3_XMIT_ONE_COLLISION:case OID_802_3_XMIT_MORE_COLLISIONS:val=0;break; + default:return NDIS_STATUS_NOT_SUPPORTED;} + if(capcore;ULONG val;const UCHAR*b=in;unsigned len;*read=*needed=0; + if(oid==MARS_OID_PUSH){if(n!=MARS_OID_FRAME_SIZE){*needed=MARS_OID_FRAME_SIZE;return NDIS_STATUS_INVALID_LENGTH;}len=b[0]|((unsigned)b[1]<<8);if(lc_push(c,b+2,len))return NDIS_STATUS_FAILURE;arm(a);*read=n;return NDIS_STATUS_SUCCESS;} + if(oid==MARS_OID_LINK){if(n!=1){*needed=1;return NDIS_STATUS_INVALID_LENGTH;}if(b[0]>1)return NDIS_STATUS_INVALID_DATA;lc_link(c,b[0]);if(b[0])arm(a);*read=n;return NDIS_STATUS_SUCCESS;} + if(oid==OID_802_3_MULTICAST_LIST){if(n%6||n>sizeof c->multicast)return NDIS_STATUS_INVALID_LENGTH;c->multicount=(unsigned)n/6;if(n)lc_copy(c->multicast,in,n);*read=n;return NDIS_STATUS_SUCCESS;} + if(oid!=OID_GEN_CURRENT_PACKET_FILTER&&oid!=OID_GEN_CURRENT_LOOKAHEAD&&oid!=OID_GEN_PROTOCOL_OPTIONS)return NDIS_STATUS_NOT_SUPPORTED; + if(n!=4){*needed=4;return NDIS_STATUS_INVALID_LENGTH;}lc_copy(&val,in,4); + if(oid==OID_GEN_CURRENT_PACKET_FILTER){if(val&~(ULONG)MF_ALLOWED)return NDIS_STATUS_NOT_SUPPORTED;c->filter=(unsigned)val;} + else if(oid==OID_GEN_CURRENT_LOOKAHEAD){if(val>1500)return NDIS_STATUS_INVALID_DATA;c->lookahead=(unsigned)val;} + *read=n;return NDIS_STATUS_SUCCESS; +} +NTSTATUS NTAPI DriverEntry(PDRIVER_OBJECT obj,PUNICODE_STRING path){NDIS_MINIPORT_CHARACTERISTICS c;NDIS_STATUS s; + NdisMInitializeWrapper(&wrapper,obj,path,NULL);if(!wrapper)return STATUS_UNSUCCESSFUL; + lc_zero(&c,sizeof c);c.MajorNdisVersion=3;c.MinorNdisVersion=0;c.InitializeHandler=mp_init;c.HaltHandler=mp_halt;c.QueryInformationHandler=mp_query;c.SetInformationHandler=mp_set;c.ResetHandler=mp_reset;c.CheckForHangHandler=mp_hang;c.SendHandler=mp_send;c.TransferDataHandler=mp_transfer; + s=NdisMRegisterMiniport(wrapper,&c,sizeof c);if(s!=NDIS_STATUS_SUCCESS){NdisTerminateWrapper(wrapper,NULL);return STATUS_UNSUCCESSFUL;}return STATUS_SUCCESS; +} diff --git a/clients/windows/ndis3/packet_backend.inc b/clients/windows/ndis3/packet_backend.inc new file mode 100644 index 0000000..77fa0da --- /dev/null +++ b/clients/windows/ndis3/packet_backend.inc @@ -0,0 +1,31 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later + * WinPcap 3.1 Packet.dll ABI: opaque ADAPTER, cdecl, BOOLEAN (one byte). + * Only private MARS OIDs, plus MAC query. No raw physical adapter capture. + * Requires a separately installed, OS-compatible WinPcap protocol driver. + */ +#include "legacy_core.h" +struct mars_oid_data { ULONG oid, length; unsigned char data[MARS_OID_FRAME_SIZE]; }; +typedef void* (__cdecl *packet_open_fn)(char*); +typedef void (__cdecl *packet_close_fn)(void*); +typedef BOOLEAN (__cdecl *packet_request_fn)(void*,BOOLEAN,struct mars_oid_data*); +typedef BOOLEAN (__cdecl *packet_names_fn)(char*,ULONG*); +static HMODULE packet_lib; +static void *packet_adapter; +static packet_open_fn packet_open; +static packet_close_fn packet_close; +static packet_request_fn packet_request; +static packet_names_fn packet_names; +static int legacy_link; +static int load_packet(void){char path[MAX_PATH];UINT n=GetSystemDirectoryA(path,sizeof path);if(packet_lib)return 0;if(!n||n>=sizeof path-12)return -1;strcat(path,"\\Packet.dll");packet_lib=LoadLibraryA(path);if(!packet_lib){fprintf(stderr,"Install WinPcap 3.1 for this historical OS (Packet.dll).\n");return -1;} + packet_open=(packet_open_fn)GetProcAddress(packet_lib,"PacketOpenAdapter");packet_close=(packet_close_fn)GetProcAddress(packet_lib,"PacketCloseAdapter");packet_request=(packet_request_fn)GetProcAddress(packet_lib,"PacketRequest");packet_names=(packet_names_fn)GetProcAddress(packet_lib,"PacketGetAdapterNames"); + if(!packet_open||!packet_close||!packet_request||!packet_names){FreeLibrary(packet_lib);packet_lib=NULL;return -1;}return 0;} +static int oid_call(ULONG oid,int set,unsigned char*data,ULONG n){struct mars_oid_data r;if(!packet_adapter||n>sizeof r.data)return -1;memset(&r,0,sizeof r);r.oid=oid;r.length=n;if(set&&n)memcpy(r.data,data,n);if(!packet_request(packet_adapter,(BOOLEAN)set,&r)||r.length!=n)return -1;if(!set&&n)memcpy(data,r.data,n);return 0;} +static int list_legacy(void){static char names[32768];ULONG n=sizeof names;char*p,*end,*q;if(load_packet()||!packet_names(names,&n)||!n||n>sizeof names)return -1;end=names+n;for(p=names;p1023)return -1;packet_adapter=packet_open((char*)name);if(!packet_adapter)return -1; + if(oid_call(MARS_OID_IDENT,0,ident,sizeof ident)||memcmp(ident,MARS_IDENT,8)){fprintf(stderr,"Not a MARS NDIS3 adapter; no MARS tunnel enabled.\n");return -1;} + if(oid_call(0x01010102UL,0,mac,6)||memcmp(mac,core.node,6)){fprintf(stderr,"Adapter MAC must match the physical IPX node.\n");return -1;} + if(oid_call(MARS_OID_LINK,1,&up,1))return -1;legacy_link=1;return 0;} +static int virtual_out(uint8_t*f){unsigned char b[MARS_OID_FRAME_SIZE];unsigned n;if(oid_call(MARS_OID_POP,0,b,sizeof b))return -2;n=b[0]|((unsigned)b[1]<<8);if(n>PKT_FRAME||(n&&n<14))return -2;if(n)memcpy(f,b+2,n);return (int)n;} +static int virtual_in(const uint8_t*f,int n){unsigned char b[MARS_OID_FRAME_SIZE];if(n<14||n>PKT_FRAME)return -1;memset(b,0,sizeof b);b[0]=(unsigned char)n;b[1]=(unsigned char)(n>>8);memcpy(b+2,f,n);return oid_call(MARS_OID_PUSH,1,b,sizeof b);} +static void virtual_idle(void){Sleep(10);} +static void close_virtual(void){unsigned char down=0;if(legacy_link)oid_call(MARS_OID_LINK,1,&down,1);if(packet_adapter)packet_close(packet_adapter);if(packet_lib)FreeLibrary(packet_lib);packet_adapter=NULL;packet_lib=NULL;legacy_link=0;} diff --git a/clients/windows/ndis5/MARSNDIS.INF b/clients/windows/ndis5/MARSNDIS.INF new file mode 100644 index 0000000..463e876 --- /dev/null +++ b/clients/windows/ndis5/MARSNDIS.INF @@ -0,0 +1,47 @@ +; Experimental Windows 2000/XP x86 NDIS 5.0 miniport. Not signed or DDK-tested. +[Version] +Signature="$Windows NT$" +Class=Net +ClassGuid={4D36E972-E325-11CE-BFC1-08002BE10318} +Provider=%Provider% +DriverVer=11/27/2026,0.6.0.0 + +[Manufacturer] +%Provider%=MARSModels +[MARSModels] +%Adapter%=Install,ROOT\MARSNDIS +[Install] +Characteristics=0x1 +BusType=15 +CopyFiles=DriverCopy +AddReg=AdapterReg +[Install.Services] +AddService=MARSNDIS,2,ServiceInstall +[ServiceInstall] +DisplayName=%Adapter% +ServiceType=1 +StartType=3 +ErrorControl=1 +ServiceBinary=%12%\MARSNDIS.SYS +LoadOrderGroup=NDIS +[AdapterReg] +HKR,Ndi,Service,0,"MARSNDIS" +HKR,Ndi\Interfaces,UpperRange,0,"ndis5_ip" +HKR,Ndi\Interfaces,LowerRange,0,"ethernet" +HKR,Ndi\params\NetworkAddress,ParamDesc,0,"Physical IPX Node (12 hex digits)" +HKR,Ndi\params\NetworkAddress,type,0,"edit" +HKR,Ndi\params\NetworkAddress,LimitText,0,"12" +HKR,Ndi\params\NetworkAddress,Optional,0,"1" +HKR,NetworkAddress,0,0,"020000000001" +[DriverCopy] +MARSNDIS.SYS +[DestinationDirs] +DriverCopy=12 +[SourceDisksNames] +1=%Disk%,,, +[SourceDisksFiles] +MARSNDIS.SYS=1 +[Strings] +Provider="MARS VME" +Adapter="MARS Virtual IPX Ethernet (experimental)" +Disk="MARS NDIS driver" diff --git a/clients/windows/ndis5/control.h b/clients/windows/ndis5/control.h new file mode 100644 index 0000000..8383d70 --- /dev/null +++ b/clients/windows/ndis5/control.h @@ -0,0 +1,9 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef MARS_NDIS_CONTROL_H +#define MARS_NDIS_CONTROL_H +/* Include ntddk.h or winioctl.h before this file. */ +#define MARS_CTL_NAME "\\\\.\\MarsNet" +#define MARS_CTL_MAC CTL_CODE(FILE_DEVICE_UNKNOWN,0x810,METHOD_BUFFERED,FILE_READ_ACCESS) +#define MARS_CTL_POP CTL_CODE(FILE_DEVICE_UNKNOWN,0x811,METHOD_BUFFERED,FILE_READ_ACCESS) +#define MARS_CTL_PUSH CTL_CODE(FILE_DEVICE_UNKNOWN,0x812,METHOD_BUFFERED,FILE_WRITE_ACCESS) +#endif diff --git a/clients/windows/ndis5/frame_queue.c b/clients/windows/ndis5/frame_queue.c new file mode 100644 index 0000000..6f57e4d --- /dev/null +++ b/clients/windows/ndis5/frame_queue.c @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#include "frame_queue.h" +#ifdef MARS_LEGACY_KERNEL +#include "../ndis3/legacy_core.h" +#define COPY(d,s,n) lc_copy(d,s,n) +#elif defined(MARS_KERNEL) +#include +#include +#define COPY(d,s,n) NdisMoveMemory(d,s,n) +#else +#include +#define COPY(d,s,n) memcpy(d,s,n) +#endif +int mars_ring_push(struct mars_ring*r,const unsigned char*f,unsigned n){struct mars_slot*s;if(n<14||n>MARS_FRAME_MAX||r->count>=MARS_RING_SIZE)return -1;s=&r->slot[(r->head+r->count)%MARS_RING_SIZE];s->len=(unsigned short)n;COPY(s->bytes,f,n);r->count++;return 0;} +int mars_ring_pop(struct mars_ring*r,unsigned char*f,unsigned cap){struct mars_slot*s;unsigned n;if(!r->count)return 0;s=&r->slot[r->head];n=s->len;if(capbytes,n);r->head=(r->head+1)%MARS_RING_SIZE;r->count--;return (int)n;} +void mars_ring_clear(struct mars_ring*r){r->head=r->count=0;} diff --git a/clients/windows/ndis5/frame_queue.h b/clients/windows/ndis5/frame_queue.h new file mode 100644 index 0000000..9e46b4e --- /dev/null +++ b/clients/windows/ndis5/frame_queue.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef MARS_FRAME_QUEUE_H +#define MARS_FRAME_QUEUE_H +#define MARS_RING_SIZE 64 +#define MARS_FRAME_MAX 1514 +struct mars_slot {unsigned short len;unsigned char bytes[MARS_FRAME_MAX];}; +struct mars_ring {unsigned head,count;struct mars_slot slot[MARS_RING_SIZE];}; +/* Caller serializes all access. No allocation, no overwrite, no partial pop. */ +int mars_ring_push(struct mars_ring*,const unsigned char*,unsigned); +int mars_ring_pop(struct mars_ring*,unsigned char*,unsigned); +void mars_ring_clear(struct mars_ring*); +#endif diff --git a/clients/windows/ndis5/makefile b/clients/windows/ndis5/makefile new file mode 100644 index 0000000..5acbbd2 --- /dev/null +++ b/clients/windows/ndis5/makefile @@ -0,0 +1 @@ +!INCLUDE $(NTMAKEENV)\makefile.def diff --git a/clients/windows/ndis5/miniport.c b/clients/windows/ndis5/miniport.c new file mode 100644 index 0000000..2061be3 --- /dev/null +++ b/clients/windows/ndis5/miniport.c @@ -0,0 +1,71 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later + * Experimental NDIS 5.0 software-only Ethernet miniport (x86 NT5). + * One instance, one privileged Win32 transport owner, bounded TX queue. + * No physical NIC or Winsock calls in kernel mode. Build and validate in VM. + */ +#include +#include +#include "control.h" +#include "frame_queue.h" +#define TAG 'sraM' +#define ALLOWED_FILTER (NDIS_PACKET_TYPE_DIRECTED|NDIS_PACKET_TYPE_MULTICAST|NDIS_PACKET_TYPE_ALL_MULTICAST|NDIS_PACKET_TYPE_BROADCAST|NDIS_PACKET_TYPE_PROMISCUOUS) +typedef struct _ADAPTER {NDIS_HANDLE mini,packets,buffers;UCHAR mac[6];ULONG filter,lookahead,options,multicount;UCHAR multicast[32][6];LONG refs;KEVENT idle;PFILE_OBJECT owner;BOOLEAN closing;struct mars_ring tx;LONG sent,recv,txerr,rxerr,nobuf;} ADAPTER; +static ADAPTER *active;static KSPIN_LOCK state_lock;static NDIS_HANDLE wrapper,control_handle;static PDRIVER_DISPATCH dispatch_table[IRP_MJ_MAXIMUM_FUNCTION+1]; +static const UCHAR bc[6]={255,255,255,255,255,255},zero[6]={0}; +static BOOLEAN equal(const UCHAR*a,const UCHAR*b){return RtlCompareMemory(a,b,6)==6;} +static BOOLEAN ethertype(const UCHAR*f,ULONG n){return n>=14&&n<=MARS_FRAME_MAX&&f[12]==8&&(f[13]==0||f[13]==6);} +static const NDIS_OID oids[]={OID_GEN_SUPPORTED_LIST,OID_GEN_HARDWARE_STATUS,OID_GEN_MEDIA_SUPPORTED,OID_GEN_MEDIA_IN_USE,OID_GEN_MAXIMUM_LOOKAHEAD,OID_GEN_MAXIMUM_FRAME_SIZE,OID_GEN_LINK_SPEED,OID_GEN_TRANSMIT_BUFFER_SPACE,OID_GEN_RECEIVE_BUFFER_SPACE,OID_GEN_TRANSMIT_BLOCK_SIZE,OID_GEN_RECEIVE_BLOCK_SIZE,OID_GEN_VENDOR_ID,OID_GEN_VENDOR_DESCRIPTION,OID_GEN_CURRENT_PACKET_FILTER,OID_GEN_CURRENT_LOOKAHEAD,OID_GEN_DRIVER_VERSION,OID_GEN_MAXIMUM_TOTAL_SIZE,OID_GEN_PROTOCOL_OPTIONS,OID_GEN_MAC_OPTIONS,OID_GEN_MEDIA_CONNECT_STATUS,OID_GEN_VENDOR_DRIVER_VERSION,OID_GEN_MAXIMUM_SEND_PACKETS,OID_GEN_XMIT_OK,OID_GEN_RCV_OK,OID_GEN_XMIT_ERROR,OID_GEN_RCV_ERROR,OID_GEN_RCV_NO_BUFFER,OID_802_3_PERMANENT_ADDRESS,OID_802_3_CURRENT_ADDRESS,OID_802_3_MULTICAST_LIST,OID_802_3_MAXIMUM_LIST_SIZE,OID_802_3_RCV_ERROR_ALIGNMENT,OID_802_3_XMIT_ONE_COLLISION,OID_802_3_XMIT_MORE_COLLISIONS}; +static VOID media(ADAPTER*a,BOOLEAN up){NdisMIndicateStatus(a->mini,up?NDIS_STATUS_MEDIA_CONNECT:NDIS_STATUS_MEDIA_DISCONNECT,NULL,0);NdisMIndicateStatusComplete(a->mini);} +static ADAPTER* get_owner(PFILE_OBJECT file){KIRQL irql;ADAPTER*a;KeAcquireSpinLock(&state_lock,&irql);a=active;if(!a||a->owner!=file||a->closing)a=NULL;else{if(!a->refs)KeClearEvent(&a->idle);a->refs++;}KeReleaseSpinLock(&state_lock,irql);return a;} +static VOID put_ref(ADAPTER*a){KIRQL irql;KeAcquireSpinLock(&state_lock,&irql);if(!--a->refs)KeSetEvent(&a->idle,IO_NO_INCREMENT,FALSE);KeReleaseSpinLock(&state_lock,irql);} +static NTSTATUS complete(PIRP irp,NTSTATUS status,ULONG info){irp->IoStatus.Status=status;irp->IoStatus.Information=info;IoCompleteRequest(irp,IO_NO_INCREMENT);return status;} +static BOOLEAN receive_allowed(ADAPTER*a,const UCHAR*f,ULONG n){BOOLEAN ok=FALSE;KIRQL irql;ULONG i;if(!ethertype(f,n))return FALSE;KeAcquireSpinLock(&state_lock,&irql);if(a->filter&NDIS_PACKET_TYPE_PROMISCUOUS)ok=TRUE;else if(equal(f,bc))ok=(a->filter&NDIS_PACKET_TYPE_BROADCAST)!=0;else if(equal(f,a->mac))ok=(a->filter&NDIS_PACKET_TYPE_DIRECTED)!=0;else if(f[0]&1){if(a->filter&NDIS_PACKET_TYPE_ALL_MULTICAST)ok=TRUE;else if(a->filter&NDIS_PACKET_TYPE_MULTICAST)for(i=0;imulticount;i++)if(equal(f,a->multicast[i])){ok=TRUE;break;}}KeReleaseSpinLock(&state_lock,irql);return ok;} +static NTSTATUS inject(ADAPTER*a,PUCHAR data,ULONG n){PNDIS_PACKET packet=NULL;PNDIS_BUFFER buffer=NULL;NDIS_STATUS s;if(!ethertype(data,n))return STATUS_INVALID_PARAMETER;if(!receive_allowed(a,data,n)){InterlockedIncrement(&a->rxerr);return STATUS_SUCCESS;}NdisAllocatePacket(&s,&packet,a->packets);if(s!=NDIS_STATUS_SUCCESS){InterlockedIncrement(&a->nobuf);return STATUS_INSUFFICIENT_RESOURCES;}NdisAllocateBuffer(&s,&buffer,a->buffers,data,n);if(s!=NDIS_STATUS_SUCCESS){NdisFreePacket(packet);InterlockedIncrement(&a->nobuf);return STATUS_INSUFFICIENT_RESOURCES;} + NdisChainBufferAtFront(packet,buffer);NDIS_SET_PACKET_HEADER_SIZE(packet,14);NDIS_SET_PACKET_STATUS(packet,NDIS_STATUS_RESOURCES); + /* Deserialized NDIS5: <=DISPATCH_LEVEL, no lock held, full packet, RESOURCES + * forces synchronous copy. Buffered IRP storage stays live until return. */ + NdisMIndicateReceivePacket(a->mini,&packet,1);NdisUnchainBufferAtFront(packet,&buffer);NdisFreeBuffer(buffer);NdisFreePacket(packet);InterlockedIncrement(&a->recv);return STATUS_SUCCESS;} +static NTSTATUS NTAPI control(PDEVICE_OBJECT obj,PIRP irp){PIO_STACK_LOCATION sp=IoGetCurrentIrpStackLocation(irp);KIRQL irql;ADAPTER*a;NTSTATUS status=STATUS_INVALID_DEVICE_REQUEST;ULONG info=0,code,n;LUID priv;PVOID buf;int got;UNREFERENCED_PARAMETER(obj); + switch(sp->MajorFunction){case IRP_MJ_CREATE: + /* Only a token with explicitly enabled SeLoadDriverPrivilege can open the + * raw frame endpoint; device name alone is not a security boundary. */ + priv.LowPart=SE_LOAD_DRIVER_PRIVILEGE;priv.HighPart=0; + if(KeGetCurrentIrql()!=PASSIVE_LEVEL||!SeSinglePrivilegeCheck(priv,irp->RequestorMode))return complete(irp,STATUS_ACCESS_DENIED,0); + KeAcquireSpinLock(&state_lock,&irql);a=active;if(!a)status=STATUS_DEVICE_NOT_READY;else if(a->owner)status=STATUS_SHARING_VIOLATION;else{a->owner=sp->FileObject;a->closing=FALSE;mars_ring_clear(&a->tx);if(!a->refs)KeClearEvent(&a->idle);a->refs++;status=STATUS_SUCCESS;}KeReleaseSpinLock(&state_lock,irql); + if(NT_SUCCESS(status)){media(a,TRUE);put_ref(a);}return complete(irp,status,0); + case IRP_MJ_CLEANUP: + KeAcquireSpinLock(&state_lock,&irql);a=active;if(a&&a->owner==sp->FileObject&&!a->closing){a->closing=TRUE;mars_ring_clear(&a->tx);if(!a->refs)KeClearEvent(&a->idle);a->refs++;}else a=NULL;KeReleaseSpinLock(&state_lock,irql);if(a){media(a,FALSE);KeAcquireSpinLock(&state_lock,&irql);a->owner=NULL;a->closing=FALSE;KeReleaseSpinLock(&state_lock,irql);put_ref(a);}return complete(irp,STATUS_SUCCESS,0); + case IRP_MJ_CLOSE:return complete(irp,STATUS_SUCCESS,0); + case IRP_MJ_DEVICE_CONTROL:break;default:return complete(irp,status,0);} + a=get_owner(sp->FileObject);if(!a)return complete(irp,STATUS_DEVICE_NOT_READY,0);code=sp->Parameters.DeviceIoControl.IoControlCode;buf=irp->AssociatedIrp.SystemBuffer; + if(code==MARS_CTL_MAC){if(buf&&sp->Parameters.DeviceIoControl.OutputBufferLength>=6){NdisMoveMemory(buf,a->mac,6);info=6;status=STATUS_SUCCESS;}else status=STATUS_BUFFER_TOO_SMALL;} + else if(code==MARS_CTL_POP){if(!buf||sp->Parameters.DeviceIoControl.OutputBufferLengthtx,buf,MARS_FRAME_MAX);KeReleaseSpinLock(&state_lock,irql);if(got<0)status=STATUS_UNSUCCESSFUL;else{info=(ULONG)got;status=STATUS_SUCCESS;}}} + else if(code==MARS_CTL_PUSH){n=sp->Parameters.DeviceIoControl.InputBufferLength;if(!buf||n<14||n>MARS_FRAME_MAX)status=STATUS_INVALID_PARAMETER;else status=inject(a,buf,n);} + put_ref(a);return complete(irp,status,info);} +static NDIS_STATUS NTAPI mp_init(PNDIS_STATUS error,PUINT selected,PNDIS_MEDIUM media_list,UINT count,NDIS_HANDLE mini,NDIS_HANDLE cfgctx){ADAPTER*a;NDIS_STATUS s;NDIS_HANDLE cfg;PVOID addr=NULL;UINT len=0,i;KIRQL irql;*error=NDIS_STATUS_FAILURE;for(i=0;imini=mini;a->lookahead=1500;KeInitializeEvent(&a->idle,NotificationEvent,TRUE); + /* Explicit MAC required: physical IPX node must match virtual NIC. */ + NdisOpenConfiguration(&s,&cfg,cfgctx);if(s!=NDIS_STATUS_SUCCESS)goto fail;NdisReadNetworkAddress(&s,&addr,&len,cfg);if(s==NDIS_STATUS_SUCCESS&&len==6&&addr)NdisMoveMemory(a->mac,addr,6);NdisCloseConfiguration(cfg);if(s!=NDIS_STATUS_SUCCESS||len!=6||(a->mac[0]&1)||equal(a->mac,zero)){s=NDIS_STATUS_INVALID_DATA;goto fail;} + NdisMSetAttributesEx(mini,a,0,NDIS_ATTRIBUTE_DESERIALIZE,NdisInterfaceInternal); + NdisAllocatePacketPool(&s,&a->packets,16,4*sizeof(PVOID));if(s!=NDIS_STATUS_SUCCESS)goto fail;NdisAllocateBufferPool(&s,&a->buffers,16);if(s!=NDIS_STATUS_SUCCESS)goto fail; + KeAcquireSpinLock(&state_lock,&irql);if(active){KeReleaseSpinLock(&state_lock,irql);s=NDIS_STATUS_FAILURE;goto fail;}active=a;KeReleaseSpinLock(&state_lock,irql);*error=NDIS_STATUS_SUCCESS;return NDIS_STATUS_SUCCESS; + fail:if(a->buffers)NdisFreeBufferPool(a->buffers);if(a->packets)NdisFreePacketPool(a->packets);ExFreePool(a);*error=s;return s;} +static VOID NTAPI mp_halt(NDIS_HANDLE ctx){ADAPTER*a=ctx;KIRQL irql;KeAcquireSpinLock(&state_lock,&irql);if(active==a)active=NULL;a->owner=NULL;KeReleaseSpinLock(&state_lock,irql);/* Deserialized miniport: wait only for outstanding control calls, never hold state lock. */KeWaitForSingleObject(&a->idle,Executive,KernelMode,FALSE,NULL);NdisFreeBufferPool(a->buffers);NdisFreePacketPool(a->packets);ExFreePool(a);} +static VOID NTAPI mp_send(NDIS_HANDLE ctx,PPNDIS_PACKET packets,UINT count){ADAPTER*a=ctx;UINT i,total,part,pos;PNDIS_BUFFER b;PVOID ptr;UCHAR frame[MARS_FRAME_MAX];KIRQL irql;NDIS_STATUS s; + for(i=0;i=14&&total<=MARS_FRAME_MAX){while(b&&postotal-pos)break;if(part)NdisMoveMemory(frame+pos,ptr,part);pos+=part;NdisGetNextBuffer(b,&b);}if(pos==total&ðertype(frame,total)&&equal(frame+6,a->mac)){KeAcquireSpinLock(&state_lock,&irql);if(a->owner&&!a->closing&&!mars_ring_push(&a->tx,frame,total))s=NDIS_STATUS_SUCCESS;KeReleaseSpinLock(&state_lock,irql);}} + if(s==NDIS_STATUS_SUCCESS)InterlockedIncrement(&a->sent);else InterlockedIncrement(&a->txerr);NdisMSendComplete(a->mini,packets[i],s);}} +/* All indicated RX packets use RESOURCES so NDIS must not call this callback. */ +static VOID NTAPI mp_return(NDIS_HANDLE ctx,PNDIS_PACKET p){UNREFERENCED_PARAMETER(ctx);UNREFERENCED_PARAMETER(p);} +static BOOLEAN NTAPI mp_hang(NDIS_HANDLE ctx){UNREFERENCED_PARAMETER(ctx);return FALSE;} +static NDIS_STATUS NTAPI mp_reset(PBOOLEAN addr_reset,NDIS_HANDLE ctx){ADAPTER*a=ctx;KIRQL irql;*addr_reset=FALSE;KeAcquireSpinLock(&state_lock,&irql);mars_ring_clear(&a->tx);KeReleaseSpinLock(&state_lock,irql);return NDIS_STATUS_SUCCESS;} +static NDIS_STATUS NTAPI mp_query(NDIS_HANDLE ctx,NDIS_OID oid,PVOID out,ULONG cap,PULONG written,PULONG needed){ADAPTER*a=ctx;ULONG val=0,n=sizeof val;USHORT ver=0x0500;const VOID*p=&val;KIRQL irql;UCHAR mc[192];static const CHAR name[]="MARS Virtual IPX Ethernet";*written=*needed=0; + KeAcquireSpinLock(&state_lock,&irql);switch(oid){case OID_GEN_SUPPORTED_LIST:p=oids;n=sizeof oids;break;case OID_GEN_HARDWARE_STATUS:val=NdisHardwareStatusReady;break;case OID_GEN_MEDIA_SUPPORTED:case OID_GEN_MEDIA_IN_USE:val=NdisMedium802_3;break;case OID_GEN_MAXIMUM_LOOKAHEAD:case OID_GEN_MAXIMUM_FRAME_SIZE:val=1500;break;case OID_GEN_MAXIMUM_TOTAL_SIZE:case OID_GEN_TRANSMIT_BLOCK_SIZE:case OID_GEN_RECEIVE_BLOCK_SIZE:val=MARS_FRAME_MAX;break;case OID_GEN_LINK_SPEED:val=100000;break;case OID_GEN_TRANSMIT_BUFFER_SPACE:val=MARS_RING_SIZE*MARS_FRAME_MAX;break;case OID_GEN_RECEIVE_BUFFER_SPACE:val=16*MARS_FRAME_MAX;break;case OID_GEN_VENDOR_ID:val=0x00ffffff;break;case OID_GEN_VENDOR_DESCRIPTION:p=name;n=sizeof name;break;case OID_GEN_CURRENT_PACKET_FILTER:val=a->filter;break;case OID_GEN_CURRENT_LOOKAHEAD:val=a->lookahead;break;case OID_GEN_PROTOCOL_OPTIONS:val=a->options;break;case OID_GEN_DRIVER_VERSION:p=&ver;n=sizeof ver;break;case OID_GEN_VENDOR_DRIVER_VERSION:val=0x00010000;break;case OID_GEN_MAC_OPTIONS:val=NDIS_MAC_OPTION_NO_LOOPBACK|NDIS_MAC_OPTION_TRANSFERS_NOT_PEND;break;case OID_GEN_MEDIA_CONNECT_STATUS:val=(a->owner&&!a->closing)?NdisMediaStateConnected:NdisMediaStateDisconnected;break;case OID_GEN_MAXIMUM_SEND_PACKETS:val=16;break;case OID_GEN_XMIT_OK:val=(ULONG)a->sent;break;case OID_GEN_RCV_OK:val=(ULONG)a->recv;break;case OID_GEN_XMIT_ERROR:val=(ULONG)a->txerr;break;case OID_GEN_RCV_ERROR:val=(ULONG)a->rxerr;break;case OID_GEN_RCV_NO_BUFFER:val=(ULONG)a->nobuf;break;case OID_802_3_PERMANENT_ADDRESS:case OID_802_3_CURRENT_ADDRESS:p=a->mac;n=6;break;case OID_802_3_MAXIMUM_LIST_SIZE:val=32;break;case OID_802_3_MULTICAST_LIST:n=a->multicount*6;NdisMoveMemory(mc,a->multicast,n);p=mc;break;case OID_802_3_RCV_ERROR_ALIGNMENT:case OID_802_3_XMIT_ONE_COLLISION:case OID_802_3_XMIT_MORE_COLLISIONS:val=0;break;default:KeReleaseSpinLock(&state_lock,irql);return NDIS_STATUS_NOT_SUPPORTED;} + KeReleaseSpinLock(&state_lock,irql);if(capsizeof a->multicast)return NDIS_STATUS_INVALID_LENGTH;KeAcquireSpinLock(&state_lock,&irql);a->multicount=n/6;if(n)NdisMoveMemory(a->multicast,data,n);KeReleaseSpinLock(&state_lock,irql);*read=n;return NDIS_STATUS_SUCCESS;} + if(oid!=OID_GEN_CURRENT_PACKET_FILTER&&oid!=OID_GEN_CURRENT_LOOKAHEAD&&oid!=OID_GEN_PROTOCOL_OPTIONS)return NDIS_STATUS_NOT_SUPPORTED;if(n!=sizeof val){*needed=sizeof val;return NDIS_STATUS_INVALID_LENGTH;}NdisMoveMemory(&val,data,sizeof val);if((oid==OID_GEN_CURRENT_PACKET_FILTER&&(val&~ALLOWED_FILTER))||(oid==OID_GEN_CURRENT_LOOKAHEAD&&val>1500))return NDIS_STATUS_INVALID_DATA; + KeAcquireSpinLock(&state_lock,&irql);if(oid==OID_GEN_CURRENT_PACKET_FILTER)a->filter=val;else if(oid==OID_GEN_CURRENT_LOOKAHEAD)a->lookahead=val;else a->options=val;KeReleaseSpinLock(&state_lock,irql);*read=sizeof val;return NDIS_STATUS_SUCCESS;} +static VOID NTAPI unload(PDRIVER_OBJECT obj){UNREFERENCED_PARAMETER(obj);if(control_handle)NdisMDeregisterDevice(control_handle);} +NTSTATUS NTAPI DriverEntry(PDRIVER_OBJECT obj,PUNICODE_STRING path){NDIS_MINIPORT_CHARACTERISTICS c;NDIS_STATUS s;NDIS_STRING dev,link;PDEVICE_OBJECT control_obj=NULL; + RtlInitUnicodeString(&dev,L"\\Device\\MarsNet");RtlInitUnicodeString(&link,L"\\DosDevices\\MarsNet");KeInitializeSpinLock(&state_lock);NdisMInitializeWrapper(&wrapper,obj,path,NULL);if(!wrapper)return STATUS_UNSUCCESSFUL;NdisZeroMemory(&c,sizeof c);c.MajorNdisVersion=5;c.MinorNdisVersion=0;c.InitializeHandler=mp_init;c.HaltHandler=mp_halt;c.QueryInformationHandler=mp_query;c.SetInformationHandler=mp_set;c.ResetHandler=mp_reset;c.CheckForHangHandler=mp_hang;c.SendPacketsHandler=mp_send;c.ReturnPacketHandler=mp_return; + s=NdisMRegisterMiniport(wrapper,&c,sizeof c);if(s!=NDIS_STATUS_SUCCESS){NdisTerminateWrapper(wrapper,NULL);return STATUS_UNSUCCESSFUL;}dispatch_table[IRP_MJ_CREATE]=control;dispatch_table[IRP_MJ_CLEANUP]=control;dispatch_table[IRP_MJ_CLOSE]=control;dispatch_table[IRP_MJ_DEVICE_CONTROL]=control; + s=NdisMRegisterDevice(wrapper,&dev,&link,dispatch_table,&control_obj,&control_handle);if(s!=NDIS_STATUS_SUCCESS){NdisTerminateWrapper(wrapper,NULL);return STATUS_UNSUCCESSFUL;}NdisMRegisterUnloadHandler(wrapper,unload);return STATUS_SUCCESS;} diff --git a/clients/windows/ndis5/sources b/clients/windows/ndis5/sources new file mode 100644 index 0000000..c47845f --- /dev/null +++ b/clients/windows/ndis5/sources @@ -0,0 +1,6 @@ +TARGETNAME=MARSNDIS +TARGETTYPE=DRIVER +TARGETPATH=obj +C_DEFINES=$(C_DEFINES) -DNDIS_MINIPORT_DRIVER -DNDIS50_MINIPORT -DMARS_KERNEL +TARGETLIBS=$(DDK_LIB_PATH)\ndis.lib +SOURCES=miniport.c frame_queue.c diff --git a/cross/build-diag.sh b/cross/build-diag.sh new file mode 100755 index 0000000..e98c1e3 --- /dev/null +++ b/cross/build-diag.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +for t in clang lld-link llvm-ar python3 objdump; do command -v "$t" >/dev/null || { echo "Missing $t" >&2; exit 1; }; done +mkdir -p build/cross/diag +rm -f build/cross/diag/IPXDIAG.EXE +out=$PWD/build/cross/diag +# COFF short import records, IMPORT_NAME_UNDECORATE strips x86 stdcall decoration. +python3 - "$out" <<'PY' +import pathlib,struct,sys +p=pathlib.Path(sys.argv[1]); +for dll, exports in {'KERNEL32.dll':{'ExitProcess':4,'GetStdHandle':4,'WriteFile':20},'WSOCK32.dll':{'WSAStartup':8,'WSACleanup':0,'WSAGetLastError':0,'socket':12,'closesocket':4,'getsockopt':20,'bind':12,'getsockname':12}}.items(): + for name, n in exports.items(): + data=f'_{name}@{n}\0{dll}\0'.encode('ascii') + (p/(name+'.imp.obj')).write_bytes(struct.pack(' "$out/imports.txt" +python3 cross/verify-pe.py "$out/IPXDIAG.EXE" exe +printf 'Diagnostic built: %s\n' "$out/IPXDIAG.EXE" diff --git a/cross/build-legacy-bridge.sh b/cross/build-legacy-bridge.sh new file mode 100755 index 0000000..7b374d0 --- /dev/null +++ b/cross/build-legacy-bridge.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# CRT-free x86 executable. No historical Microsoft headers required for usermode. +set -euo pipefail +cd "$(dirname "$0")/.." +for t in clang lld-link llvm-ar python3 objdump; do command -v "$t" >/dev/null; done +out=$PWD/build/cross/legacy-bridge; mkdir -p "$out"; rm -f "$out"/{MARSNET.EXE,imports.lib} +python3 - "$out" <<'PY' +import pathlib,struct,sys +p=pathlib.Path(sys.argv[1]); +exports={'KERNEL32.dll':{'ExitProcess':4,'GetStdHandle':4,'WriteFile':20,'GetCommandLineA':0,'GetFullPathNameA':16,'GetPrivateProfileStringA':24,'GetSystemDirectoryA':8,'LoadLibraryA':4,'GetProcAddress':8,'FreeLibrary':4,'GetTickCount':0,'Sleep':4,'SetConsoleCtrlHandler':8,'CreateMutexA':12,'CloseHandle':4,'GetLastError':0},'WSOCK32.dll':{'WSAStartup':8,'WSACleanup':0,'WSAGetLastError':0,'socket':12,'closesocket':4,'setsockopt':20,'bind':12,'getsockname':12,'ioctlsocket':12,'sendto':24,'recvfrom':24}} +for dll, funcs in exports.items(): + for name,n in funcs.items(): + data=f'_{name}@{n}\0{dll}\0'.encode('ascii');(p/(name+'.imp.obj')).write_bytes(struct.pack(' "$out/MARSNET.imports.txt" +echo 'CRT-free MARSNET.EXE built; still requires an NDIS3 miniport and WinPcap 3.1 at runtime.' diff --git a/cross/build-legacy.sh b/cross/build-legacy.sh new file mode 100755 index 0000000..ce56c82 --- /dev/null +++ b/cross/build-legacy.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# NDIS 3 binary candidate using historical NT4 x86 DDK, not modern NDIS block layout. +set -euo pipefail +cd "$(dirname "$0")/.." +out=$PWD/build/cross/legacy; mkdir -p "$out"; rm -f "$out"/{MARSNET3.SYS,MARSNET.EXE,MARSNET.INF} +dump=${MINGW_OBJDUMP:-objdump} +for t in "$dump" clang-cl lld-link python3; do command -v "$t" >/dev/null || { echo "Missing $t" >&2; exit 1; }; done +cache=${MARS_TOOLCHAIN_DIR:-$PWD/.toolchains}; root=$cache/legacy/nt4-extracted +if [[ -z ${NT4_DDK_INCLUDE:-} || -z ${NT4_NDIS_LIB:-} ]]; then [[ -f $root/READY ]] || ./cross/extract-nt4.sh; fi +rm -rf "$out/include"; lib=$(python3 cross/prepare-nt4.py "$root" "$out/include") +# Build without modern NTOSKRNL or CRT import libraries. Win9x NDIS loader only +# supports a subset of NT imports; structural checks don't prove loader compatibility. +for f in clients/windows/ndis3/miniport.c clients/windows/ndis3/legacy_core.c clients/windows/ndis5/frame_queue.c; do + clang-cl --target=i686-pc-windows-msvc /nologo /c /TC /Gz /GS- /Zl /O1 /Oi- /clang:-ffreestanding /clang:-fno-builtin /D_X86_=1 /Di386=1 /DNDIS_MINIPORT_DRIVER /DNDIS30_MINIPORT /DMARS_LEGACY_KERNEL /I"$out/include" /imsvc/usr/i686-w64-mingw32/include /Fo"$out/$(basename "$f" .c).obj" "$f" +done +lld-link /nologo /driver /subsystem:native,4.0 /osversion:4.0 /entry:DriverEntry@8 /nodefaultlib /machine:x86 /base:0x10000 /dynamicbase:no /nxcompat:no /safeseh:no /out:"$out/MARSNET3.SYS" "$out/miniport.obj" "$out/legacy_core.obj" "$out/frame_queue.obj" "$lib" +python3 cross/verify-pe.py "$out/MARSNET3.SYS" sys +"$dump" -p "$out/MARSNET3.SYS" > "$out/MARSNET3.imports.txt" +# Refuse unexpected DLL imports; older loaders cannot resolve newer kernel APIs. +if grep 'DLL Name:' "$out/MARSNET3.imports.txt" | grep -Eiv 'DLL Name:[[:space:]]+ndis\.sys[[:space:]]*$'; then echo 'Unexpected legacy kernel import' >&2; exit 1; fi +./cross/build-legacy-bridge.sh +cp build/cross/legacy-bridge/{MARSNET.EXE,MARSNET.imports.txt} "$out/" +cp clients/windows/ndis3/MARSNET.INF "$out/" +echo 'NDIS3 build candidate. Requires OS-specific Packet.dll/driver and VM validation. NT4 OEMSETUP not included.' diff --git a/cross/build-nt5.sh b/cross/build-nt5.sh new file mode 100755 index 0000000..1c96d6e --- /dev/null +++ b/cross/build-nt5.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +cc=${MINGW_CC:-i686-w64-mingw32-gcc}; cxx=${MINGW_CXX:-i686-w64-mingw32-g++}; dump=${MINGW_OBJDUMP:-i686-w64-mingw32-objdump} +for t in "$cc" "$cxx" "$dump" python3; do command -v "$t" >/dev/null || { echo "Missing $t; run cross/install-tools.sh --apt-only" >&2; exit 1; }; done +out=$PWD/build/cross/nt5; mkdir -p "$out"; rm -f "$out"/{MARSIPX.EXE,MARSTAP.EXE,MARSNDIS.SYS,MARSNDIS.INF} +common=(-O2 -march=i386 -mno-sse -mno-sse2 -D_WIN32_WINNT=0x0500 -DWINVER=0x0500 -D_USE_32BIT_TIME_T -Isrc -Iclients/windows) +"$cc" "${common[@]}" -c src/ipxpkt.c -o "$out/ipxpkt.o" +"$cc" "${common[@]}" -c clients/windows/client_core.c -o "$out/client_core.o" +for backend in NATIVE TAP; do + name=MARSIPX; [[ $backend != TAP ]] || name=MARSTAP + "$cxx" "${common[@]}" -DMARS_$backend -fno-exceptions -fno-rtti -c clients/windows/marsnet.cpp -o "$out/$name.o" + "$cxx" -static -static-libgcc -static-libstdc++ -Wl,--subsystem,console:5.0,--major-os-version,5,--minor-os-version,0,--disable-dynamicbase,--disable-nxcompat -o "$out/$name.EXE" "$out/$name.o" "$out/ipxpkt.o" "$out/client_core.o" -lwsock32 -ladvapi32 + python3 cross/verify-pe.py "$out/$name.EXE" exe + "$dump" -p "$out/$name.EXE" > "$out/$name.imports.txt" +done +# The free MinGW-w64 DDK headers and import libraries are included in the Debian dev package. +ddk=${MINGW_DDK_INCLUDE:-/usr/i686-w64-mingw32/include/ddk} +[[ -f $ddk/ndis.h && -f $ddk/ntddk.h ]] || { echo "Missing DDK headers in $ddk" >&2; exit 1; } +# Work around known defects in the packaged MinGW DDK in a local copy. +compat="$out/ddk"; mkdir -p "$compat" +python3 cross/prepare-mingw-ddk.py "$ddk" "$compat" +ddk=$compat +kflags=(-O2 -march=i386 -mno-sse -mno-sse2 -ffreestanding -fno-builtin -fno-stack-protector -fno-asynchronous-unwind-tables -D_X86_=1 -Di386=1 -DNDIS_MINIPORT_DRIVER -DNDIS50_MINIPORT -DMARS_KERNEL -D_WIN32_WINNT=0x0500 -DNTDDI_VERSION=0x05000000 -I"$ddk" -Werror=incompatible-pointer-types) +for f in miniport frame_queue; do "$cc" "${kflags[@]}" -c "clients/windows/ndis5/$f.c" -o "$out/$f.o"; done +"$cc" -nostdlib -Wl,--entry,_DriverEntry@8,--subsystem,native:5.0,--major-os-version,5,--minor-os-version,0,--image-base,0x10000,--disable-dynamicbase,--disable-nxcompat,--disable-stdcall-fixup -o "$out/MARSNDIS.SYS" "$out/miniport.o" "$out/frame_queue.o" -lndis -lntoskrnl -lhal -lgcc +python3 cross/verify-pe.py "$out/MARSNDIS.SYS" sys +"$dump" -p "$out/MARSNDIS.SYS" > "$out/MARSNDIS.imports.txt" +cp clients/windows/ndis5/MARSNDIS.INF "$out/" +echo 'NT5 candidate built. Unsigned; imports and Windows VM tests still required.' diff --git a/cross/build-windows.sh b/cross/build-windows.sh new file mode 100755 index 0000000..fca5dda --- /dev/null +++ b/cross/build-windows.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# Build what is available and write explicit per-platform status. No driver installation. +set -euo pipefail +cd "$(dirname "$0")/.." +mode=${1:-all}; case $mode in all|WIN95|WIN98|WINME|WINNT40|WIN2000|WINXP) ;; *) echo 'Usage: cross/build-windows.sh [all|WIN95|WIN98|WINME|WINNT40|WIN2000|WINXP]' >&2; exit 2;; esac +mkdir -p build/cross +report=$PWD/build/cross/STATUS.txt +: > "$report" +log(){ printf '%s\n' "$*" | tee -a "$report"; } +rc=0 +oses=(WIN95 WIN98 WINME WINNT40 WIN2000 WINXP); [[ $mode == all ]] || oses=("$mode") +for os in "${oses[@]}"; do rm -rf -- "build/cross/packages/$os"; done +if ./cross/build-diag.sh > build/cross/diag.log 2>&1; then + for os in "${oses[@]}"; do mkdir -p "build/cross/packages/$os"; cp build/cross/diag/IPXDIAG.EXE "build/cross/packages/$os/"; done + log 'IPXDIAG: built and structurally checked (all requested targets, runtime untested)' +else log 'IPXDIAG: FAILED; see build/cross/diag.log'; rc=1; fi +if [[ $mode == all ]]; then + if ./cross/watcom-check.sh > build/cross/watcom.log 2>&1; then log 'Open Watcom: shared protocol objects built'; else log 'Open Watcom: FAILED; see build/cross/watcom.log'; rc=1; fi +fi +if [[ $mode == all || $mode == WIN2000 || $mode == WINXP ]]; then + if ./cross/build-nt5.sh > build/cross/nt5.log 2>&1; then + for os in "${oses[@]}"; do if [[ $os == WIN2000 || $os == WINXP ]]; then + mkdir -p "build/cross/packages/$os"; cp build/cross/nt5/{MARSIPX.EXE,MARSTAP.EXE,MARSNDIS.SYS,MARSNDIS.INF} "build/cross/packages/$os/" + log "$os: native candidate built; unsigned and VM-UNTESTED" + fi; done + else log 'NT5: FAILED; see build/cross/nt5.log; no native package exported'; rc=1; fi +fi +if [[ $mode == all || $mode == WIN95 || $mode == WIN98 || $mode == WINME || $mode == WINNT40 ]]; then + winpcap_ok=0 + if ./cross/fetch-winpcap.sh > build/cross/winpcap.log 2>&1; then winpcap_ok=1; else log "WinPcap: FAILED; see build/cross/winpcap.log"; rc=1; fi + if ./cross/build-legacy-bridge.sh > build/cross/legacy-bridge.log 2>&1; then log "NDIS3 user-mode bridge: PE32 candidate built (runtime UNTESTED)"; else log "Legacy bridge FAILED; see legacy-bridge.log"; rc=1; fi + if ./cross/build-legacy.sh > build/cross/legacy.log 2>&1; then + for os in "${oses[@]}"; do + case $os in WIN95|WIN98|WINME|WINNT40) + mkdir -p "build/cross/packages/$os" + if (( winpcap_ok )); then + cache=${MARS_TOOLCHAIN_DIR:-$PWD/.toolchains} + cp "$cache/legacy/WinPcap_3_1.exe" "build/cross/packages/$os/WPCAP31.EXE" + cp "$cache/legacy/WinPcap_3_1.exe.origin" "build/cross/packages/$os/WPCAP31.TXT" + cp clients/windows/ndis3/INSTALL.BAT "build/cross/packages/$os/" + fi + cp build/cross/legacy/{MARSNET3.SYS,MARSNET.EXE,MARSNET3.imports.txt,MARSNET.imports.txt} "build/cross/packages/$os/" + if [[ $os != WINNT40 ]]; then cp build/cross/legacy/MARSNET.INF "build/cross/packages/$os/"; else + cache=${MARS_TOOLCHAIN_DIR:-$PWD/.toolchains} + if python3 cross/generate-nt4-inf.py "$cache/legacy/nt4-extracted" "build/cross/packages/$os/OEMSETUP.INF"; then + cp clients/windows/ndis3/NT4-INSTALL.txt "build/cross/packages/$os/" + else rc=1; fi + fi + log "$os: NDIS3 candidate; WinPcap driver required, OS compatibility UNTESTED (NT4 OEMSETUP generated separately; installation UNTESTED)";; + esac + done + else log 'NDIS3: FAILED; see build/cross/legacy.log; no legacy adapter exported'; rc=1; fi +fi +for os in "${oses[@]}"; do + d=build/cross/packages/$os + if [[ -d $d ]]; then printf '%s\r\n' 'MARS VME development preview. NOT a validated driver release.' 'See LEGACY-BUILD.md, CROSS-BUILD.md and WINDOWS.md. Use an isolated VM. IPXDIAG.EXE checks only local IPX.' > "$d/README.TXT"; fi +done +log "Result: $report (not an OS compatibility certification)" +exit "$rc" diff --git a/cross/extract-nt4.sh b/cross/extract-nt4.sh new file mode 100755 index 0000000..19fd637 --- /dev/null +++ b/cross/extract-nt4.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +cache=${MARS_TOOLCHAIN_DIR:-$PWD/.toolchains}; cache=$(realpath -m "$cache/legacy") +[[ -f $cache/winnt40.ddk.iso ]] || { echo 'No NT4 ISO; run cross/fetch-legacy.sh --accept-archive' >&2; exit 1; } +(cd "$cache"; sha256sum -c winnt40.ddk.iso.sha256) +if [[ -e $cache/nt4-extracted/READY ]]; then echo "Cached NT4 files: $cache/nt4-extracted"; exit 0; fi +[[ ! -e $cache/nt4-extracted ]] || { echo 'Incomplete extraction; move it aside first.' >&2; exit 1; } +work=$(mktemp -d "$cache/.nt4.XXXXXX"); trap 'rm -rf -- "$work"' EXIT +mkdir "$work/iso" "$work/expanded"; 7z x -y -o"$work/iso" "$cache/winnt40.ddk.iso" >/dev/null +# Extract any cabinet groups without running setup.exe; keep paths separate. +i=0 +while IFS= read -r -d '' f; do i=$((i+1)); mkdir "$work/expanded/$i"; cabextract -q -d "$work/expanded/$i" "$f" || echo "Cannot extract CAB: $f" >&2; done < <(find "$work/iso" -type f -iname '*.cab' -print0) +# Some old DDKs store individual compressed files (NDIS.H_, etc.). +while IFS= read -r -d '' f; do i=$((i+1)); mkdir "$work/expanded/$i"; 7z x -y -o"$work/expanded/$i" "$f" >/dev/null 2>&1 || true; done < <(find "$work/iso" -type f \( -iname '*.h_' -o -iname '*.li_' -o -iname '*.in_' \) -print0) +find "$work" -type f \( -iname 'ndis.h' -o -iname 'ntddk.h' -o -iname 'ndis.lib' \) -printf '%P\n' | tee "$work/DDK-FILES.txt" +if ! find "$work" -type f -iname ndis.h -print -quit | grep -q . || ! find "$work" -type f -iname ntddk.h -print -quit | grep -q . || ! find "$work" -type f -iname ndis.lib -print -quit | grep -q .; then + echo 'Cannot find DDK components in this layout. Set NT4_DDK_INCLUDE and NT4_NDIS_LIB from your own extracted x86 DDK.' >&2; exit 1 +fi +touch "$work/READY"; mv "$work" "$cache/nt4-extracted"; trap - EXIT diff --git a/cross/fetch-legacy.sh b/cross/fetch-legacy.sh new file mode 100755 index 0000000..275b04f --- /dev/null +++ b/cross/fetch-legacy.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# Downloads only. No Windows executable is run; caches stay outside source packages. +set -euo pipefail +cd "$(dirname "$0")/.." +[[ ${1:-} == --accept-archive ]] || { echo 'Review DDK archive licensing and provenance, then use --accept-archive. See LEGACY-BUILD.md.' >&2; exit 2; } +cache=${MARS_TOOLCHAIN_DIR:-$PWD/.toolchains}; mkdir -p "$cache/legacy"; cache=$(realpath "$cache/legacy") +for t in curl jq sha256sum sha512sum git; do + command -v "$t" >/dev/null || { echo "Missing dependency: $t" >&2; exit 2; } +done +fetch(){ curl --fail --silent --show-error --location --retry 2 --connect-timeout 15 --max-time 1800 --proto '=https' --proto-redir '=https' "$@"; } +asset(){ + local tag=$1 name=$2 key=$3 url digest actual meta tmp + local envsha="${key}_SHA256"; digest=${!envsha:-} + url="https://github.com/KunYi/WDK_DDKArchive/releases/download/$tag/$name" + if [[ -z $digest ]]; then + if meta=$(fetch "https://api.github.com/repos/KunYi/WDK_DDKArchive/releases/tags/$tag"); then + digest=$(jq -r --arg name "$name" '.assets[]|select(.name==$name)|(.digest // "")|sub("^sha256:";"")' <<<"$meta") + fi + fi + if [[ -e $cache/$name && -e $cache/$name.sha256 ]]; then (cd "$cache"; sha256sum -c "$name.sha256") || return 1; else + tmp=$(mktemp "$cache/.download.XXXXXX"); if ! fetch "$url" -o "$tmp"; then rm -f "$tmp"; return 1; fi + actual=$(sha256sum "$tmp" | cut -d' ' -f1) + if [[ -n $digest && ${digest,,} != "$actual" ]]; then rm -f "$tmp"; echo "Hash mismatch: $name" >&2; return 1; fi + mv "$tmp" "$cache/$name" || return 1; printf '%s %s\n' "$actual" "$name" > "$cache/$name.sha256" + fi + actual=$(sha256sum "$cache/$name"|cut -d' ' -f1) + if [[ -n $digest && ${digest,,} != "$actual" ]]; then echo "Hash mismatch: $name" >&2; return 1; fi + printf 'url=%s\nsha256=%s\nexpected=%s\n' "$url" "$actual" "${digest:-UNVERIFIED}" > "$cache/$name.origin" + [[ -n $digest ]] || echo "WARNING $name: archive not independently verified; SHA256 records bytes only." >&2 +} +rc=0 +asset NT4_DDK winnt40.ddk.iso NT4_DDK || rc=1 +asset Win98DDK win98ddk.exe WIN98_DDK || rc=1 +# WinWorld publishes this SHA-512 on the Windows 95 DDK download page. +# Unofficial archival copy, not a signed Microsoft distribution. +name=win95ddk.7z +mirror2='https://git.iiot-factory.com/chris/mars_nwe_pcab/raw/branch/main/windll/Microsoft%20Windows%2095%20DDK.7z' +mirror1='https://dl.winworldpc.com/Abandonware%20SDKs/Microsoft%20Windows%2095%20DDK.7z' +sha512=${WIN95_DDK_SHA512:-119ed8a4361805ec8b36f227da741a864cad77586ff7f87c696a74d7d438b3253b643c97765414867575f1d20e65c9cd70762c7d8481108778a0af0c4c0061bf} +if [[ ! $sha512 =~ ^[a-fA-F0-9]{128}$ ]]; then + echo 'Invalid WIN95_DDK_SHA512' >&2; exit 2 +fi +if [[ ${MARS_SKIP_WIN95_DDK:-0} == 1 && ${MARS_REQUIRE_WIN95_DDK:-0} == 1 ]]; then + echo 'MARS_SKIP_WIN95_DDK and MARS_REQUIRE_WIN95_DDK conflict.' >&2; exit 2 +fi +fetch_win95(){ + local url tmp mismatch=0 + local -a urls=() + [[ -z ${WIN95_DDK_URL:-} ]] || urls+=("$WIN95_DDK_URL") + [[ ${WIN95_DDK_URL:-} == "$mirror2" ]] || urls+=("$mirror2") + [[ ${WIN95_DDK_URL:-} == "$mirror1" ]] || urls+=("$mirror1") + if [[ -f $cache/$name ]]; then + printf '%s %s\n' "$sha512" "$cache/$name" | sha512sum -c - || return 1 + echo "Using cached $cache/$name" + [[ -f $cache/$name.origin ]] || printf 'url=LOCAL_CACHE\nsha512=%s\n' "$sha512" > "$cache/$name.origin" + return 0 + fi + for url in "${urls[@]}"; do + echo "Trying Windows 95 DDK: $url" + tmp=$(mktemp "$cache/.win95.XXXXXX") || return 1 + if fetch "$url" -o "$tmp"; then + if printf '%s %s\n' "$sha512" "$tmp" | sha512sum -c -; then + mv -- "$tmp" "$cache/$name" || { rm -f -- "$tmp"; return 1; } + printf 'url=%s\nsha512=%s\n' "$url" "$sha512" > "$cache/$name.origin" || return 1 + echo "Downloaded and verified: $cache/$name" + return 0 + fi + mismatch=1 + echo 'WARNING: Windows 95 archive hash mismatch; trying next mirror.' >&2 + fi + rm -f -- "$tmp" + done + if (( mismatch )); then + echo 'ERROR: No mirror supplied a valid Windows 95 archive.' >&2; return 1 + fi + echo 'WARNING: All Windows 95 DDK mirrors unavailable.' >&2 + if [[ ${MARS_REQUIRE_WIN95_DDK:-0} == 1 ]]; then return 1; fi + echo 'Optional Windows 95 reference DDK skipped; NT4-based build can continue.' >&2 + return 0 +} +if [[ ${MARS_SKIP_WIN95_DDK:-0} == 1 ]]; then + echo 'Skipping optional Windows 95 reference DDK.' +else + fetch_win95 || rc=1 +fi +# WinPcap is an open source reference and optional compatibility transport. +if [[ ! -d $cache/winpcap31/.git ]]; then + git clone --depth 1 --branch WINPCAP_3_1 https://github.com/wireshark/winpcap.git "$cache/winpcap31" || rc=1 +fi +if [[ -d $cache/winpcap31/.git ]]; then git -C "$cache/winpcap31" rev-parse HEAD > "$cache/winpcap31.commit"; fi +./cross/fetch-winpcap.sh || rc=1 +exit "$rc" diff --git a/cross/fetch-watcom.sh b/cross/fetch-watcom.sh new file mode 100755 index 0000000..2538096 --- /dev/null +++ b/cross/fetch-watcom.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Download official Open Watcom snapshot; no installer executed, local project cache. +set -euo pipefail +cd "$(dirname "$0")/.." +for t in curl jq tar xz sha256sum; do command -v "$t" >/dev/null || { echo "Missing $t; run cross/install-tools.sh --apt-only" >&2; exit 1; }; done +cache=${MARS_TOOLCHAIN_DIR:-$PWD/.toolchains}; mkdir -p "$cache"; cache=$(realpath "$cache") +if [[ -f $cache/watcom/ROOT ]]; then + root=$(cat "$cache/watcom/ROOT"); if [[ -x $cache/watcom/$root/binl64/wcc386 || -x $cache/watcom/$root/binl/wcc386 ]]; then echo "Using cached Open Watcom: $cache/watcom/$root"; exit 0; fi + echo 'Incomplete cache; move the watcom directory aside first.' >&2; exit 1 +fi +[[ ! -e $cache/watcom ]] || { echo 'Incomplete Watcom cache; move it aside first.' >&2; exit 1; } +work=$(mktemp -d "$cache/.watcom.XXXXXXXX"); trap 'rm -rf -- "$work"' EXIT +fetch(){ curl --fail --show-error --silent --location --retry 3 --connect-timeout 15 --max-time 1800 --proto '=https' --proto-redir '=https' "$@"; } +tag=${WATCOM_TAG:-Current-build} +[[ $tag =~ ^[A-Za-z0-9._-]+$ ]] || exit 2 +if [[ -n ${WATCOM_URL:-} ]]; then + [[ ${WATCOM_SHA256:-} =~ ^[a-fA-F0-9]{64}$ ]] || { echo 'Custom WATCOM_URL requires WATCOM_SHA256.' >&2; exit 2; } + url=$WATCOM_URL; digest=$WATCOM_SHA256 +else + fetch "https://api.github.com/repos/open-watcom/open-watcom-v2/releases/tags/$tag" -o "$work/release.json" + asset=$(jq -ce '[.assets[] | select(.name=="owsnapshot.tar.xz" or .name=="ow-snapshot.tar.xz")][0] // error("No snapshot for this release")' "$work/release.json") + url=$(jq -er '.browser_download_url' <<<"$asset") + [[ $url == https://github.com/open-watcom/open-watcom-v2/releases/download/* ]] || exit 2 + digest=${WATCOM_SHA256:-$(jq -r '(.digest // "") | sub("^sha256:"; "")' <<<"$asset")} +fi +fetch "$url" -o "$work/snapshot.tar.xz" +actual=$(sha256sum "$work/snapshot.tar.xz" | cut -d' ' -f1) +if [[ -n $digest ]]; then [[ ${digest,,} == "$actual" ]] || { echo 'Watcom SHA256 mismatch' >&2; exit 1; }; else echo 'WARNING: upstream supplied no digest. HTTPS transport only; recorded SHA256 is not independent verification.' >&2; fi +mkdir "$work/extract" +tar -xJf "$work/snapshot.tar.xz" --no-same-owner --no-same-permissions -C "$work/extract" +root=''; for d in "$work/extract" "$work/extract"/*; do + if [[ -d $d/h && ( -x $d/binl64/wcc386 || -x $d/binl/wcc386 ) ]]; then root=$d; break; fi +done +[[ -n $root ]] || { echo 'Open Watcom snapshot layout not recognized.' >&2; exit 1; } +relative=${root#"$work/extract"}; relative=${relative#/}; printf '%s\n' "${relative:-.}" > "$work/extract/ROOT" +printf 'url=%s\nsha256=%s\ntag=%s\n' "$url" "$actual" "$tag" > "$work/extract/ORIGIN.txt" +mv -T "$work/extract" "$cache/watcom" +echo "Open Watcom available in $cache/watcom/${relative:-.}" diff --git a/cross/fetch-winpcap.sh b/cross/fetch-winpcap.sh new file mode 100755 index 0000000..f6982ec --- /dev/null +++ b/cross/fetch-winpcap.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Extract the unmodified WinPcap 3.1 installer from the official Wireshark archive. +set -euo pipefail +cd "$(dirname "$0")/.." +cache=${MARS_TOOLCHAIN_DIR:-$PWD/.toolchains}/legacy +mkdir -p "$cache" +url=https://www.wireshark.org/download/win32/all-versions/wireshark-setup-0.99.4.exe +bundle=wireshark-setup-0.99.4.exe +bundle_sha=c9afd4c81103b62ad95cbe12a30f81f18b847f95136267ca9af3b87c12abd50f +installer_sha=cc3840c1b87fb73ce0f5612403d1fc0bbf192bde8639c81388133d80db59000d +# SHA256 pins measured from the official HTTPS download on 2026-11-27; +# reproducibility checks, not independently published vendor signatures. +verify(){ printf '%s %s\n' "$1" "$2" | sha256sum -c -; } +if [[ ! -f $cache/WinPcap_3_1.exe ]]; then + if [[ ! -f $cache/$bundle ]]; then + [[ ${MARS_OFFLINE:-0} != 1 ]] || { echo 'WinPcap missing: run cross/fetch-winpcap.sh online first' >&2; exit 1; } + tmp=$(mktemp "$cache/.winpcap.XXXXXX"); trap 'rm -f "$tmp"' EXIT + curl --fail --location --show-error --retry 2 --connect-timeout 15 --max-time 300 --proto '=https' --proto-redir '=https' "$url" -o "$tmp" + verify "$bundle_sha" "$tmp" + mv "$tmp" "$cache/$bundle"; trap - EXIT + fi + verify "$bundle_sha" "$cache/$bundle" + 7z e -y "-o$cache" "$cache/$bundle" WinPcap_3_1.exe >/dev/null +fi +verify "$installer_sha" "$cache/WinPcap_3_1.exe" +printf 'source=%s\nbundle_sha256=%s\ninstaller_sha256=%s\nVerification=locally measured pins from official HTTPS archive; not vendor signature\n' "$url" "$bundle_sha" "$installer_sha" > "$cache/WinPcap_3_1.exe.origin" diff --git a/cross/generate-nt4-inf.py b/cross/generate-nt4-inf.py new file mode 100644 index 0000000..f8d7b13 --- /dev/null +++ b/cross/generate-nt4-inf.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Generate a local NT4 installer from the operator's NT4 DDK sample. +No DDK source is bundled with this generator. Output requires NT4 VM validation. +""" +import argparse, os, pathlib, re +p=argparse.ArgumentParser() +p.add_argument('ddk', type=pathlib.Path) +p.add_argument('output', type=pathlib.Path) +a=p.parse_args() +mac=os.environ.get('MARS_NT4_NETWORK_ADDRESS', '') +if mac and (not re.fullmatch(r'[0-9a-fA-F]{12}', mac) or int(mac[:2],16)&1 or int(mac,16)==0): + p.error('MARS_NT4_NETWORK_ADDRESS must be a nonzero unicast MAC: 12 hex digits') +paths=list(a.ddk.rglob('OEMNADE2.INF')) +if len(paths)!=1: p.error('Expected one NT4 Ethernet installer sample OEMNADE2.INF') +s=paths[0].read_text(encoding='latin1').replace('\x1a','') +# Strip comments from template; retain a provenance notice for the generated file. +s='\n'.join(line for line in s.splitlines() if not line.lstrip().startswith(';')) +# No bus/resource detection for a software-only adapter. +start=s.index(' Debug-Output "OEMNADE2.INF: ====') +end=s.index('installadapter = +',start) +s=s[:start]+' Goto $(StartLabel)\n\n'+s[end:] +start=s.index(' Set CurrParamSettings = {}') +end=s.index('configureadapter = +',start) +s=s[:start]+' goto adaptersetup\n\n'+s[end:] +start=s.index(' set ValueName = ""',s.index('configureadapter = +')) +end=s.index('skipoptions =+',start) +s=s[:start]+''' CloseRegKey $(KeyParameters) + CloseRegKey $(KeyProduct) + goto successful + +adaptersetup = + + Ifstr $(NetworkAddress) == "" + set Error = "Set NetworkAddress in OEMSETUP.INF to the physical IPX node (12 hex digits), then install again." + goto fatal + endif + goto skipoptions + +'''+s[end:] +start=s.index(' Set NewValueList = {{Transceiver',s.index('writeparameters = +')) +end=s.index(' Shell $(UtilityInf), AddValueList',start) +s=s[:start]+''' Set NewValueList = {{BusType,$(NoTitle),$(!REG_VT_DWORD),0},+ + {BusNumber,$(NoTitle),$(!REG_VT_DWORD),0},+ + {NetworkAddress,$(NoTitle),$(!REG_VT_SZ),$(NetworkAddress)}} + +'''+s[end:] +# Bindings are handled by NCPA's NetRules engine, not an ISA setup dialog. +s=s.replace(' set Error = "Binding: Sorry, not yet implemented."\n goto fatal',' goto successful') +start=s.index('[DebugConfiguration]'); end=s.index('[Install-Option]',start) +s=s[:start]+s[end:] +s=re.sub(r'\[PlatformsSupported\].*?\[Options\]', '[PlatformsSupported]\n ISA\n EISA\n PCI\n Internal\n\n[Options]',s,flags=re.S) +s=re.sub('elnkii', 'MARSNET3',s,flags=re.I).replace('OEMNADE2.INF','OEMSETUP.INF').replace('Elink II','MARS Virtual Ethernet') +s=s.replace('Manufacturer = "Microsoft"','Manufacturer = "MARS VME"') +s=s.replace('ProductOpSupport = 134', 'ProductOpSupport = 130') # display/remove; no resource properties +s=s.replace('NetRuleHardwareClass = {"MARSNET3Adapter basic"}', 'NetRuleHardwareClass = {"MARSNET3Adapter basic", "ndisEthernet basic"}') +s=s.replace('[FileConstants]', '[FileConstants]\nNetworkAddress = "'+mac.upper()+'"') +s=s.replace('ifstr(i) !(NTN_RegBase)', 'ifstr(i) $(!NTN_RegBase)') +s=s.replace('successful = +\n goto end','successful = +\n set CommonStatus = STATUS_REBOOT\n goto end') +s+=''' +[ProductType] + STF_PRODUCT = Winnt + STF_PLATFORM = I386 +[Source Media Descriptions] + 1 = "MARS NDIS3 NT4 driver", TAGFILE = MARSNET3.SYS +[Files-MARSNET3] + 1, MARSNET3.SYS, SIZE=65536 +[LanguagesSupported] + ENG, GER +''' +for lang in ('ENG','GER'): + s+=''' +[OptionsTextLANG] + MARSNET3 = "MARS Virtual IPX Ethernet NDIS3 (experimental)" +[FileConstantsLANG] + FunctionTitle = "MARS NDIS3 NT4 Setup" + ProductSoftwareDescription = "MARS virtual Ethernet driver" + ProductSoftwareTitle = "MARS NDIS3 driver" + ProductHardwareMARSNET3Description = "MARS virtual Ethernet" + ProductHardwareMARSNET3Title = "MARS virtual Ethernet adapter" + ShellCodeErrorTitle = "MARS NT4 Setup error" + ShellCodeErrorText = "NT4 setup helper failed. See setup log." + ProCaption = "MARS NT4 Setup" + ProCancel = "Cancel" + ProCancelMsg = "Cancel driver setup?" + ProCancelCap = "MARS NT4 Setup" + ProText1 = "Copying:" + ProText2 = "To:" +[DialogConstantsLANG] + OK = "OK" + Continue = "Continue" + Cancel = "Cancel" +'''.replace('LANG',lang) +s='; MARS NT4 x86 experimental installer. Runtime UNTESTED.\n; Adapted locally from Microsoft NT4 DDK OEMNADE2.INF.\n; Original sample provenance: Microsoft NT4 DDK, Ethernet setup example.\n'+s +# Catch dangling static branches left by template surgery. +labels={m.lower() for m in re.findall(r'^([A-Za-z][A-Za-z0-9_]*)\s*=\s*\+',s,re.M)} +for target in re.findall(r'^\s*goto\s+([A-Za-z][A-Za-z0-9_]*)\s*$',s,re.M|re.I): + if target.lower() not in labels: p.error('Unresolved branch: '+target) +a.output.parent.mkdir(parents=True,exist_ok=True) +a.output.write_bytes(s.replace('\n','\r\n').encode('ascii')) +print(str(a.output)+': generated; NT4 installation/binding not runtime tested') diff --git a/cross/install-tools.sh b/cross/install-tools.sh new file mode 100755 index 0000000..5a87f2b --- /dev/null +++ b/cross/install-tools.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Debian/Ubuntu. apt verifies its signed repository metadata. +set -euo pipefail +cd "$(dirname "$0")/.." +mode=${1:---all} +case "$mode" in --all|--apt-only|--watcom-only) ;; *) echo 'Usage: cross/install-tools.sh [--all|--apt-only|--watcom-only]' >&2; exit 2;; esac +if [[ $mode != --watcom-only ]]; then + command -v apt-get >/dev/null || { echo 'Install equivalent packages manually on non-Debian systems.' >&2; exit 1; } + elevate=(); if (( EUID != 0 )); then elevate=(sudo); fi + "${elevate[@]}" apt-get update + "${elevate[@]}" apt-get install -y build-essential cmake git pkg-config curl ca-certificates jq xz-utils p7zip-full cabextract python3 clang lld llvm binutils gcc-mingw-w64-i686 g++-mingw-w64-i686 binutils-mingw-w64-i686 mingw-w64-i686-dev +fi +if [[ $mode != --apt-only ]]; then ./cross/fetch-watcom.sh; fi diff --git a/cross/package-drivers.py b/cross/package-drivers.py new file mode 100644 index 0000000..f9e6ece --- /dev/null +++ b/cross/package-drivers.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +"""Package existing validated cross-builds using Python's standard ZIP library.""" +from pathlib import Path +import hashlib, json, zipfile +root=Path(__file__).resolve().parents[1] +out=root/'releases/windows';out.mkdir(parents=True,exist_ok=True) +manifest={} +for os in ('WIN95','WIN98','WINME','WINNT40','WIN2000','WINXP'): + src=root/'build/cross/packages'/os + required=['IPXDIAG.EXE']+(['MARSNDIS.SYS','MARSNDIS.INF','MARSIPX.EXE','MARSTAP.EXE'] if os in ('WIN2000','WINXP') else ['MARSNET3.SYS','MARSNET.EXE','WPCAP31.EXE','INSTALL.BAT','OEMSETUP.INF' if os=='WINNT40' else 'MARSNET.INF']) + for name in required: + if not (src/name).is_file():raise SystemExit(f'Missing {os}/{name}; run build-windows.sh first') + files={p.name:p for p in src.iterdir() if p.is_file()} + for name in ('WINDOWS.md','LEGACY-BUILD.md','COPYING'):files[name]=root/name + hashes={name:hashlib.sha256(p.read_bytes()).hexdigest() for name,p in sorted(files.items())} + dest=out/(os+'.zip') + with zipfile.ZipFile(dest,'w',zipfile.ZIP_DEFLATED) as z: + for name,p in sorted(files.items()): + info=zipfile.ZipInfo(os+'/'+name,(2026,11,27,0,0,0));info.external_attr=0o100644<<16;info.compress_type=zipfile.ZIP_DEFLATED;z.writestr(info,p.read_bytes()) + manifest[os]={'sha256':hashlib.sha256(dest.read_bytes()).hexdigest(),'files':hashes} +(out/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n') +(out/'SHA256SUMS').write_text(''.join(f'{v["sha256"]} {k}.zip\n' for k,v in manifest.items())) +print('Packaged 6 OS ZIPs with file hashes') diff --git a/cross/prepare-mingw-ddk.py b/cross/prepare-mingw-ddk.py new file mode 100644 index 0000000..90edb8f --- /dev/null +++ b/cross/prepare-mingw-ddk.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python3 +"""Patch packaged DDK header defects locally, preserving the NT5 target ABI.""" +import pathlib, sys, shutil, re +src, dst = map(pathlib.Path, sys.argv[1:]) +shutil.copytree(src, dst, dirs_exist_ok=True) +p = dst / 'wdm.h' +s = p.read_text().replace('NTDDI_WINVISTA', 'NTDDI_VISTA') +p.write_text(s) +p = dst / 'ndis.h' +s = p.read_text() +# Modern ntddndis.h already declares the request enum. +public = src.parent / 'ntddndis.h' +if 'enum _NDIS_REQUEST_TYPE' in public.read_text(): + s = re.sub(r'typedef enum _NDIS_REQUEST_TYPE \{.*?\} NDIS_REQUEST_TYPE, \*PNDIS_REQUEST_TYPE;', '', s, flags=re.S) +s = s.replace('IN NDIS_HANDLE MiniportAdapterHandle\n\tIN NDIS_HANDLE NdisLinkContext);', 'IN NDIS_HANDLE MiniportAdapterHandle,\n\tIN NDIS_HANDLE NdisLinkContext);') +p.write_text(s) diff --git a/cross/prepare-nt4.py b/cross/prepare-nt4.py new file mode 100755 index 0000000..b520b71 --- /dev/null +++ b/cross/prepare-nt4.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +"""Prepare historical DDK includes. Refuse ambiguous header/library choices.""" +import os, pathlib, sys, shutil +root, out = map(pathlib.Path,sys.argv[1:3]); out.mkdir(parents=True, exist_ok=True) +inc=os.environ.get('NT4_DDK_INCLUDE'); lib=os.environ.get('NT4_NDIS_LIB') +if inc: + dirs=[pathlib.Path(p) for p in inc.split(':')] +else: + dirs=[] + for name in ('ndis.h','ntddk.h'): + matches=[p for p in root.rglob('*') if p.is_file() and p.name.lower()==name] + if len(matches)!=1: sys.exit(f'{name}: ambiguous/missing {matches}; set NT4_DDK_INCLUDE (colon-separated directories)') + if matches[0].parent not in dirs: dirs.append(matches[0].parent) +# Lowercase aliases plus original basename, reject different contents for same name. +for d in dirs: + for p in d.iterdir(): + if not p.is_file() or p.suffix.lower() not in ('.h','.inc'): continue + for name in {p.name,p.name.lower(),p.name.upper()}: + dest=out/name + if dest.exists() and dest.read_bytes()!=p.read_bytes(): sys.exit(f'Header conflict: {p} / {dest}') + if not dest.exists(): shutil.copyfile(p,dest) +if not lib: + paths=[p for p in root.rglob('*') if p.is_file() and p.name.lower()=='ndis.lib'] + x86=[p for p in paths if any(s.lower() in ('i386','x86','386') for s in p.parts)] + # Prefer the retail x86 library over checked/debug and other CPUs. + free=[p for p in x86 if "free" in [s.lower() for s in p.parts]] + paths=free if free else x86 + if len(paths)!=1: sys.exit(f'NDIS.LIB ambiguous/missing {paths}; set NT4_NDIS_LIB to x86 library') + lib=str(paths[0]) +if not pathlib.Path(lib).is_file(): sys.exit('NDIS.LIB not found') +print(str(pathlib.Path(lib).resolve())) diff --git a/cross/verify-pe.py b/cross/verify-pe.py new file mode 100755 index 0000000..bd82103 --- /dev/null +++ b/cross/verify-pe.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +"""Structural PE32 check; not a Windows ABI or execution test.""" +import pathlib, struct, sys +p=pathlib.Path(sys.argv[1]); b=p.read_bytes(); kind=sys.argv[2] +def u16(o): return struct.unpack_from('0, 'no entry point' + sub=u16(h+68); assert sub==(1 if kind=='sys' else 3), 'unexpected subsystem' + assert not u16(o+22)&0x2000, 'DLL rather than executable/driver' + print(f'{p.name}: PE32 x86, subsystem {sub}, OS {u16(h+40)}.{u16(h+42)}, subsystem version {u16(h+48)}.{u16(h+50)}') +except (AssertionError,struct.error) as e: + sys.exit(f'{p}: invalid PE: {e}') diff --git a/cross/watcom-check.sh b/cross/watcom-check.sh new file mode 100755 index 0000000..8af9f49 --- /dev/null +++ b/cross/watcom-check.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +cache=${MARS_TOOLCHAIN_DIR:-$PWD/.toolchains} +if [[ -z ${WATCOM:-} ]]; then + if [[ ! -f $cache/watcom/ROOT ]]; then + [[ ${MARS_OFFLINE:-0} != 1 ]] || { echo "No cached Open Watcom; run make windows-tools" >&2; exit 1; } + ./cross/fetch-watcom.sh + fi + WATCOM=$(realpath "$cache/watcom/$(cat "$cache/watcom/ROOT")") +fi +export WATCOM PATH="$WATCOM/binl64:$WATCOM/binl:$PATH" INCLUDE="$WATCOM/h:$WATCOM/h/nt" +mkdir -p build/cross/watcom +# Compile actual shared IPXPKT sources as 32-bit Windows objects, not a driver. +wcc386 -q -bt=nt -3 -i=src -fo=build/cross/watcom/ipxpkt.obj src/ipxpkt.c +wcc386 -q -bt=nt -3 -i=src -i=clients/windows -fo=build/cross/watcom/client_core.obj clients/windows/client_core.c +echo 'Watcom protocol objects built; not an installable adapter.' diff --git a/install-driver-packages.py b/install-driver-packages.py new file mode 100755 index 0000000..caf6f05 --- /dev/null +++ b/install-driver-packages.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Install verified ZIP downloads and a versioned NetWare mapping directory.""" +import argparse, hashlib, json, pathlib, shutil, tempfile, zipfile +p=argparse.ArgumentParser() +p.add_argument('--config',default='/usr/local/etc/mars_nwe/nwserv.conf') +p.add_argument('--www',default='/usr/local/share/mars-vme/www') +p.add_argument('--packages',default=str(pathlib.Path(__file__).resolve().parent/'releases/windows')) +p.add_argument('--os', action='append', choices=['WIN95','WIN98','WINME','WINNT40','WIN2000','WINXP']) +a=p.parse_args();src=pathlib.Path(a.packages) +raw=(src/'manifest.json').read_bytes();manifest=json.loads(raw) +oses=('WIN95','WIN98','WINME','WINNT40','WIN2000','WINXP') +selected=tuple(x for x in oses if x in (a.os or oses)) +if set(manifest)!=set(oses):raise SystemExit('Unexpected package manifest') +roots=[] +for line in pathlib.Path(a.config).read_text().splitlines(): + cols=line.split('#',1)[0].split() + if len(cols)>=3 and cols[0]=='1' and cols[1].upper()=='SYS':roots.append(pathlib.Path(cols[2])) +if len(roots)!=1 or not roots[0].is_absolute() or not roots[0].is_dir():raise SystemExit('Exactly one existing absolute SYS volume required') +publics=[roots[0]/n for n in ('PUBLIC','public') if (roots[0]/n).is_dir()] +if len(publics)!=1:raise SystemExit('Exactly one existing PUBLIC directory required') +public=publics[0] +if public.is_symlink():raise SystemExit('PUBLIC must not be a symlink') +base=public/'DRIVERS' +if base.is_symlink():raise SystemExit('DRIVERS must not be a symlink') +base.mkdir(exist_ok=True,mode=0o755) +release=hashlib.sha256(raw+','.join(selected).encode()).hexdigest()[:12].upper();dest=base/release +# Validate every archive before changing web downloads. +with tempfile.TemporaryDirectory(prefix='.drivers-',dir=base) as tmp: + stage=pathlib.Path(tmp) + for os in selected: + data=(src/(os+'.zip')).read_bytes() + if hashlib.sha256(data).hexdigest()!=manifest[os]['sha256']:raise SystemExit('ZIP checksum mismatch: '+os) + with zipfile.ZipFile(src/(os+'.zip')) as z: + if len(z.namelist())!=len(set(z.namelist())):raise SystemExit('Duplicate ZIP members') + expected={os+'/'+n for n in manifest[os]['files']} + if set(z.namelist())!=expected:raise SystemExit('ZIP file list mismatch') + for name in z.namelist(): + path=pathlib.PurePosixPath(name) + if path.is_absolute() or '..' in path.parts or len(path.parts)!=2:raise SystemExit('Unsafe ZIP path') + content=z.read(name) + if hashlib.sha256(content).hexdigest()!=manifest[os]['files'][path.name]:raise SystemExit('File hash mismatch') + target=stage/path;target.parent.mkdir(exist_ok=True);target.write_bytes(content);target.chmod(0o644) + if dest.exists(): + for f in stage.rglob('*'): + if f.is_file() and (dest/f.relative_to(stage)).read_bytes()!=f.read_bytes():raise SystemExit('Existing release differs; refusing overwrite') + else: + shutil.copytree(stage,dest) + for d in [dest,*[x for x in dest.rglob('*') if x.is_dir()]]:d.chmod(0o755) +www=pathlib.Path(a.www)/'drivers' +if www.is_symlink():raise SystemExit('Web drivers directory must not be a symlink') +www.mkdir(parents=True,exist_ok=True) +backup=www/('previous-'+release) +for name in [*(os+'.zip' for os in oses),'manifest.json','SHA256SUMS']: + target=www/name + if target.is_symlink():raise SystemExit('Refusing symlink: '+str(target)) + if target.exists() and target.read_bytes()!=(src/name).read_bytes(): + backup.mkdir(exist_ok=True);shutil.copy2(target,backup/name) + with tempfile.NamedTemporaryFile(dir=www,delete=False) as f:f.write((src/name).read_bytes());temp=pathlib.Path(f.name) + temp.chmod(0o644);temp.replace(target) +(www/'enabled.json').write_text(json.dumps({'platforms':selected,'map':'MAP ROOT T:=SYS:PUBLIC/DRIVERS/'+release})+'\n') +(www/'enabled.json').chmod(0o644) +print('Web downloads installed: '+str(www)) +print('MAP ROOT T:=SYS:PUBLIC/DRIVERS/'+release) +print('Grant NetWare read/file-scan rights only. Copy the OS directory locally before installation.') diff --git a/install-gateway.sh b/install-gateway.sh new file mode 100755 index 0000000..73d9595 --- /dev/null +++ b/install-gateway.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")" +[[ $EUID == 0 ]] || { echo 'Use sudo ./install-gateway.sh' >&2; exit 1; } +[[ -x build/mars_vme && -x build/mars-pcapd ]] || { echo 'First run make all native check-gateway' >&2; exit 1; } +[[ -x /usr/local/sbin/nwserv && -f /usr/local/etc/mars_nwe/nwserv.conf && -f /etc/systemd/system/mars_vme.service ]] || { echo 'Requires existing installed 0.4 server; otherwise run build.sh + install.sh.' >&2; exit 1; } +command -v nft >/dev/null && command -v ip >/dev/null || { echo 'Install nftables and iproute2 first' >&2; exit 1; } +systemctl stop mars_vme.service +backup="/var/lib/mars-vme/pre-gateway-$(date +%Y%m%d-%H%M%S)-$$" +install -d -m 0700 "$backup" +cp -a /usr/local/sbin/mars_vme /usr/local/sbin/mars-pcapd /usr/local/share/mars-vme/www "$backup/" +install -D -m 0755 packaging/mars-ipxpkt-net /usr/local/libexec/mars-ipxpkt-net +install -D -m 0755 publish-mtcp.sh /usr/local/sbin/mars-publish-mtcp +install -D -m 0755 publish-winclient.sh /usr/local/sbin/mars-publish-winclient +install -m 0755 build/mars_vme build/mars-pcapd /usr/local/sbin/ +for f in index.html app.js style.css login.html login.js; do install -m 0644 "websetup/$f" "/usr/local/share/mars-vme/www/$f"; done +printf 'Gateway upgrade installed. Old executables/assets: %s\nStart: systemctl start mars_vme.service\n' "$backup" diff --git a/install.sh b/install.sh index f05ff88..3a38177 100755 --- a/install.sh +++ b/install.sh @@ -24,12 +24,20 @@ fi if [[ -n $backup ]]; then install -m 0600 "$backup" "$conf"; fi [[ -f $conf ]] || { echo "Missing $conf after original installation" >&2; exit 1; } chmod 0600 "$conf" +install -D -m 0755 packaging/mars-ipxpkt-net "$prefix/libexec/mars-ipxpkt-net" +install -D -m 0755 publish-mtcp.sh "$prefix/sbin/mars-publish-mtcp" +install -D -m 0755 publish-winclient.sh "$prefix/sbin/mars-publish-winclient" install -D -m 0755 build/mars-pcapd "$prefix/sbin/mars-pcapd" install -D -m 0755 build/mars-print "$prefix/sbin/mars-print" install -D -m 0755 build/mars_vme "$prefix/sbin/mars_vme" install -d -m 0700 /var/lib/mars-vme /var/lib/mars-vme/bindery-backups /var/lib/mars-vme/script-backups install -d -m 0755 "$prefix/share/mars-vme/www" for f in index.html app.js style.css login.html login.js; do install -m 0644 "websetup/$f" "$prefix/share/mars-vme/www/$f"; done +install -D -m 0755 install-driver-packages.py "$prefix/libexec/mars-install-drivers" +if [[ -f releases/windows/manifest.json ]]; then + install -d -m 0755 "$prefix/share/mars-vme/driver-packages" + install -m 0644 releases/windows/* "$prefix/share/mars-vme/driver-packages/" +fi if [[ -d /etc/systemd/system ]]; then install -m 0644 mars_vme.service /etc/systemd/system/mars_vme.service if [[ -d /run/systemd/system ]]; then systemctl daemon-reload; fi diff --git a/ipxpkt.json.example b/ipxpkt.json.example new file mode 100644 index 0000000..89c17eb --- /dev/null +++ b/ipxpkt.json.example @@ -0,0 +1,12 @@ +{ + "enabled": false, + "network": "0x101", + "gateway": "10.250.0.1", + "dns": "1.1.1.1", + "uplink": "enp4s0", + "web": true, + "ping": true, + "clients": [ + { "mac": "001122334455", "ip": "10.250.0.10" } + ] +} diff --git a/native/core.c b/native/core.c index d1fdcf4..7eecdf8 100644 --- a/native/core.c +++ b/native/core.c @@ -44,7 +44,7 @@ static void msg(json_object*a,const char*s){json_object_array_add(a,json_object_ static size_t count(json_object*g,const char*k){return json_object_array_length(get(g,k));} static const char*at(json_object*g,const char*k,size_t i){return json_object_get_string(json_object_array_get_idx(get(g,k),i));} static char *netprop(const char*n,const char*k){char p[PATH_MAX];snprintf(p,sizeof p,"/sys/class/net/%s/%s",n,k);/* sysfs regular attributes can report 4096 size */char*s=read_file(p,4096,0);if(s)s[strcspn(s,"\r\n")]=0;return s;} -json_object *devices(void){json_object*a=json_object_new_array();struct if_nameindex *ifs=if_nameindex();if(!ifs)return a;for(struct if_nameindex*p=ifs;p->if_index;p++){char *t=netprop(p->if_name,"type");char w[PATH_MAX],phy[PATH_MAX];snprintf(w,sizeof w,"/sys/class/net/%s/wireless",p->if_name);snprintf(phy,sizeof phy,"/sys/class/net/%s/phy80211",p->if_name);if(t&&!strcmp(t,"1")&&access(w,F_OK)&&access(phy,F_OK)){json_object*o=json_object_new_object();char*m=netprop(p->if_name,"address"),*s=netprop(p->if_name,"operstate");addstr(o,"name",p->if_name);addstr(o,"mac",m);addstr(o,"state",s);free(m);free(s);json_object_array_add(a,o);}free(t);}if_freenameindex(ifs);return a;} +json_object *devices(void){json_object*a=json_object_new_array();struct if_nameindex *ifs=if_nameindex();if(!ifs)return a;for(struct if_nameindex*p=ifs;p->if_index;p++){char *t=netprop(p->if_name,"type");char w[PATH_MAX],phy[PATH_MAX];snprintf(w,sizeof w,"/sys/class/net/%s/wireless",p->if_name);snprintf(phy,sizeof phy,"/sys/class/net/%s/phy80211",p->if_name);if(t&&!strcmp(t,"1")&&strcmp(p->if_name,"marsipx0")&&access(w,F_OK)&&access(phy,F_OK)){json_object*o=json_object_new_object();char*m=netprop(p->if_name,"address"),*s=netprop(p->if_name,"operstate");addstr(o,"name",p->if_name);addstr(o,"mac",m);addstr(o,"state",s);free(m);free(s);json_object_array_add(a,o);}free(t);}if_freenameindex(ifs);return a;} static int dev_exists(json_object*d,const char*s){for(size_t i=0;i47||strspn(a[0],"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-")!=strlen(a[0]))msg(err,"Abschnitt 2: Servername ungültig.");free(copy);} diff --git a/native/gateway_auto.c b/native/gateway_auto.c new file mode 100644 index 0000000..75c7e69 --- /dev/null +++ b/native/gateway_auto.c @@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#define _GNU_SOURCE +#include "gateway_auto.h" +#include "core.h" +#include "../src/gateway.h" +#include +#include +#include +#include +#include +#include +#include +#include +static const char *sget(json_object *o,const char*k){const char*s=js(o,k);return s?s:"";} +/* Fixed commands, never interpolate configuration or client input. */ +static json_object *command_json(const char *command){FILE*f=popen(command,"r");if(!f)return NULL;char *s=malloc(MAX_CONF+1);if(!s){pclose(f);return NULL;}size_t n=fread(s,1,MAX_CONF,f);int more=fgetc(f),bad=ferror(f);int rc=pclose(f);s[n]=0;json_object*o=NULL;if(!bad&&more==EOF&&rc==0)o=json_tokener_parse(s);free(s);if(!json_object_is_type(o,json_type_array)){json_object_put(o);return NULL;}return o;} +static int prefix(const char *str,uint32_t *net,uint32_t *mask){char b[64];if(strlen(str)>=sizeof b)return -1;strcpy(b,str);char *p=strchr(b,'/');long bits=32;if(p){*p++=0;char*end;bits=strtol(p,&end,10);if(end==p||*end||bits<0||bits>32)return -1;}struct in_addr a;if(inet_pton(AF_INET,b,&a)!=1)return -1;*mask=bits?UINT32_MAX<<(32-bits):0;*net=ntohl(a.s_addr)&*mask;return 0;} +int ga_free(json_object *routes,uint32_t ip){if(!json_object_is_type(routes,json_type_array))return 0;uint32_t subnet=ntohl(ip)&0xffffff00u;for(size_t i=0;i=0xffffff00u)continue;uint32_t common=mask&0xffffff00u;if((subnet&common)==(net&common))return 0;}return 1;} +uint32_t ga_choose(json_object *routes){/* deterministic private /24 choices, including alternate RFC1918 ranges */for(unsigned group=0;group<3;group++){uint32_t base=group==0?0x0afa0000u:group==1?0xac1f0000u:0xc0a80000u;for(unsigned i=0;i<256;i++){uint32_t ip=htonl(base+(i<<8)+1);if(ga_free(routes,ip))return ip;}}return 0;} +static void address(json_object*r,const char*k,uint32_t ip){char a[INET_ADDRSTRLEN];if(inet_ntop(AF_INET,&ip,a,sizeof a))addstr(r,k,a);} +static int dns_find(const char*path,uint32_t*out){FILE*f=fopen(path,"r");if(!f)return 0;char line[512],key[32],val[128];int ok=0;while(fgets(line,sizeof line,f))if(sscanf(line,"%31s %127s",key,val)==2&&!strcmp(key,"nameserver")&&inet_pton(AF_INET,val,out)==1&&gw_public_ip(*out)){ok=1;break;}fclose(f);return ok;} +json_object *ga_detect(const char*conf,json_object*current,char*err,size_t n){json_object *routes=command_json("PATH=/usr/sbin:/usr/bin:/sbin:/bin ip -4 -j route show table all"),*route=command_json("PATH=/usr/sbin:/usr/bin:/sbin:/bin ip -4 -j route get 1.1.1.1");json_object *out=NULL,*g=NULL;struct gw_config cfg;char why[256];if(gw_parse(current,&cfg,why,sizeof why)){snprintf(err,n,"Gespeicherte Gateway-Konfiguration ungültig: %s",why);goto done;}if(!routes||!route||!json_object_array_length(route)){snprintf(err,n,"Keine auswertbare IPv4-Route; iproute2 und Internetroute prüfen.");goto done;}json_object*r=json_object_array_get_idx(route,0);const char *dev=sget(r,"dev");if(!*dev||!strcmp(dev,GW_TAP)||!strcmp(dev,"lo")||!if_nametoindex(dev)){snprintf(err,n,"Kein geeigneter TCP/IP-Uplink gefunden.");goto done;}g=groups(conf);json_object*a=get(g,"4");unsigned long first=0,selected=0;for(size_t i=0;i=UINT32_MAX)continue;if(!first)first=num;if(num==ntohl(cfg.net))selected=num;}if(!first){snprintf(err,n,"Zuerst ein externes IPX-Netz in nwserv.conf speichern.");goto done;}if(cfg.count&&!selected){snprintf(err,n,"Reservierungen vorhanden, aber ihr IPX-Netz fehlt. Manuell prüfen.");goto done;}uint32_t ip=cfg.ip;if(!ga_free(routes,ip)){if(cfg.count){snprintf(err,n,"Reserviertes TAP-Netz überschneidet sich mit einer Route. Clients nicht automatisch umadressieren.");goto done;}ip=ga_choose(routes);}if(!ip){snprintf(err,n,"Kein konfliktfreies /24 aus den Vorschlagsbereichen gefunden.");goto done;}uint32_t dns=0;int local=dns_find("/run/systemd/resolve/resolv.conf",&dns)||dns_find("/etc/resolv.conf",&dns);if(!local)dns=cfg.dns;out=json_object_new_object();char net[16];snprintf(net,sizeof net,"0x%X",(unsigned)(selected?selected:first));addstr(out,"network",net);addstr(out,"uplink",dev);addstr(out,"localIP",sget(r,"prefsrc"));addstr(out,"localGateway",sget(r,"gateway"));address(out,"gateway",ip);address(out,"dns",dns);addstr(out,"dnsSource",local?"Öffentlicher IPv4-Resolver des Hosts":"Vorhandener öffentlicher DNS (lokale/private Resolver sind gesperrt)"); + struct ifaddrs*ifs;if(!getifaddrs(&ifs)){for(struct ifaddrs*p=ifs;p;p=p->ifa_next)if(p->ifa_addr&&p->ifa_netmask&&p->ifa_addr->sa_family==AF_INET&&!strcmp(p->ifa_name,dev)){struct sockaddr_in *sa=(void*)p->ifa_addr,*m=(void*)p->ifa_netmask;struct in_addr wanted;if(inet_pton(AF_INET,sget(r,"prefsrc"),&wanted)==1&&sa->sin_addr.s_addr!=wanted.s_addr)continue;address(out,"localIP",sa->sin_addr.s_addr);address(out,"localMask",m->sin_addr.s_addr);break;}freeifaddrs(ifs);} + FILE*f=fopen("/proc/sys/net/ipv4/ip_forward","r");int v=0;if(f){if(fscanf(f,"%d",&v)!=1)v=0;fclose(f);}json_object_object_add(out,"forwarding",json_object_new_boolean(v==1)); + done:json_object_put(g);json_object_put(routes);json_object_put(route);return out;} diff --git a/native/gateway_auto.h b/native/gateway_auto.h new file mode 100644 index 0000000..b33794c --- /dev/null +++ b/native/gateway_auto.h @@ -0,0 +1,10 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef MARS_GATEWAY_AUTO_H +#define MARS_GATEWAY_AUTO_H +#include +#include +/* Routes are ip -4 -j route show table all objects. Network byte order. */ +int ga_free(json_object *routes,uint32_t ip); +uint32_t ga_choose(json_object *routes); +json_object *ga_detect(const char *conf,json_object *current,char *err,size_t n); +#endif diff --git a/native/main.c b/native/main.c index 5c2821b..fc11ca2 100644 --- a/native/main.c +++ b/native/main.c @@ -3,14 +3,20 @@ #include "core.h" #include "supervisor.h" #include "admin.h" +#include "../src/gateway.h" +#include "gateway_auto.h" #include #include #include #include #include +#include #include #include #include +#include +#include +extern char **environ; #include #include #include @@ -46,12 +52,77 @@ static json_object *state(struct session*s,const char*current){json_object*o=jso static char *comparison(const char*a,const char*b){if(!strcmp(a,b))return strdup("");char*s=NULL;if(asprintf(&s,"--- Aktuell (vollständig) ---\n%s\n+++ Entwurf (vollständig) +++\n%s",a,b)<0)return NULL;return s;} static int confirm(json_object*r){json_object*v=get(r,"confirm");return json_object_is_type(v,json_type_boolean)&&json_object_get_boolean(v);} static int config_valid(const char*s){json_object*v=validate(s);int ok=json_object_array_length(get(v,"errors"))==0;json_object_put(v);return ok;} +/* Gateway configuration is independent of nwserv.conf, but references its saved IPX network. */ +static int gateway_network_exists(uint32_t net){char*conf=read_file(config_path,MAX_CONF,0);if(!conf)return 0;json_object*g=groups(conf);free(conf);json_object*a=get(g,"4");int found=0;for(size_t i=0;i16384){snprintf(msg,sizeof msg,"Konfiguration zu groß.");code=400;}else if(atomic_write(GW_CONFIG ".previous",old,strlen(old),0600)||atomic_write(GW_CONFIG,text,strlen(text),0600)){snprintf(msg,sizeof msg,"Gateway-Konfiguration konnte nicht gesichert/geschrieben werden.");code=500;}} + free(old);json_object_put(current);if(code)return error(c,code,msg);return ok(c,NULL); + } + json_object*result=json_object_new_object();json_object_object_add(result,"config",current);json_object_object_add(result,"configured",json_object_new_boolean(configured));addstr(result,"revision",rev);free(old); + char *snapshot=read_file(GW_STATUS,16384,1);struct stat st;int fresh=snapshot&&!stat(GW_STATUS,&st)&&time(NULL)-st.st_mtime>=0&&time(NULL)-st.st_mtime<4; + char *seen=read_file(GW_DISCOVERY,16384,1);struct stat ds;json_object*peers=seen&&!stat(GW_DISCOVERY,&ds)&&time(NULL)-ds.st_mtime>=0&&time(NULL)-ds.st_mtime<4?json_tokener_parse(seen):NULL;free(seen);if(!json_object_is_type(peers,json_type_array)){json_object_put(peers);peers=json_object_new_array();}json_object_object_add(result,"observed",peers); + addstr(result,"status",fresh?snapshot:"Kein aktueller Gateway-Status. Dateiserver/Dispatcher starten oder Journal prüfen.");free(snapshot); + return reply(c,200,result,NULL); +} static int process(struct mg_connection*c,const struct mg_request_info*r,json_object*req){const char*u=r->local_uri;int post=!strcmp(r->request_method,"POST");struct session*s=session_get(c);char cookie[256];if(post&&!strcmp(u,"/api/login")){struct attempt*a=rate(r->remote_addr);if(!a||a->count>=5)return error(c,429,"Zu viele Versuche. Eine Minute warten.");const char*user=js(req,"user");if(!user||strcmp(user,"admin")||!auth_verify(js(req,"password"))){a->count++;return error(c,401,"Anmeldung fehlgeschlagen.");}a->count=0;if(!(s=new_session()))return error(c,429,"Zu viele aktive Sitzungen.");cookie_str(cookie,s->token);return ok(c,cookie);} const char*file=NULL,*type=NULL;if(!post){if(!strcmp(u,"/login")){file="login.html";type="text/html";}else if(!strcmp(u,"/login.js")){file="login.js";type="text/javascript";}else if(!strcmp(u,"/style.css")){file="style.css";type="text/css";}} if(!file&&!s){if(!strcmp(u,"/"))return send_data(c,303,"text/plain","",0,NULL,"/login");return error(c,401,"Anmeldung erforderlich.");} if(post){const char*csrf=mg_get_header(c,"X-Mars-CSRF");if(!csrf||strlen(csrf)!=64||CRYPTO_memcmp(csrf,s->csrf,64))return error(c,403,"CSRF-Prüfung fehlgeschlagen.");if(!strcmp(u,"/api/logout")){memset(s,0,sizeof *s);cookie_str(cookie,"");return ok(c,cookie);}if(!strcmp(u,"/api/password")){const char*next=js(req,"new"),*rep=js(req,"repeat");if(!auth_verify(js(req,"current"))||!next||!rep||strcmp(next,rep)||auth_set(next,0))return error(c,400,"Aktuelles Kennwort prüfen; neues Kennwort 10–256 Zeichen, zweimal identisch.");memset(sessions,0,sizeof sessions);cookie_str(cookie,"");return ok(c,cookie);}if(auth_default())return error(c,403,"Zuerst das Web-Standardkennwort ändern.");} if(!post&&!file){if(!strcmp(u,"/")){file="index.html";type="text/html";}else if(!strcmp(u,"/app.js")){file="app.js";type="text/javascript";}} if(file){char*p=NULL;asprintf(&p,"%s/%s",assets,file);char*d=p?read_file(p,MAX_CONF,0):NULL;free(p);if(!d)return error(c,404,"Datei fehlt.");char mime[64];snprintf(mime,sizeof mime,"%s; charset=utf-8",type);int code=send_data(c,200,mime,d,strlen(d),NULL,NULL);free(d);return code;} + if(post&&!strcmp(u,"/api/drivers/activate")){ + if(no_services||!confirm(req))return error(c,400,"Dienstmodus und Bestätigung erforderlich."); + json_object *platforms=get(req,"platforms"); + if(!json_object_is_type(platforms,json_type_array)||json_object_array_length(platforms)<1||json_object_array_length(platforms)>6)return error(c,400,"Mindestens ein Betriebssystem wählen."); + pid_t pid;int status;char *args[18]={"/usr/local/libexec/mars-install-drivers","--packages","/usr/local/share/mars-vme/driver-packages"};int ac=3; + for(size_t i=0;i=(int)sizeof path||lstat(path,&st)||!S_ISREG(st.st_mode))return error(c,404,"Treiberpaket nicht installiert."); + mg_send_file(c,path);return 200; + } + return error(c,404,"Unbekanntes Treiberpaket."); + } + if(!strcmp(u,"/api/gateway"))return gateway_api(c,post,req,0); + if(!post&&!strcmp(u,"/api/gateway/detect"))return gateway_api(c,0,NULL,1); if(!post&&!strcmp(u,"/api/status"))return reply(c,200,supervisor_status(),NULL); if(!post&&!strcmp(u,"/api/monitor")){if(auth_default())return error(c,403,"Kennwort ändern.");return reply(c,200,monitor_data(),NULL);} if(!strcmp(u,"/api/bindery")||!strcmp(u,"/api/print")){if(auth_default()||no_services)return error(c,403,"Kennwort ändern oder Dienstmodus verwenden.");if(!post)return error(c,405,"POST erforderlich.");const char *op=js(req,"op");if(!op)return error(c,400,"Aktion fehlt.");if(!strncmp(op,"trustee-",8)&&!supervisor_config_matches())return error(c,409,"Konfiguration seit Serverstart geändert. Dateiserver neu starten.");int readonly=!strcmp(op,"sessions")||!strcmp(op,"objects")||!strcmp(op,"properties")||!strcmp(op,"list")||!strcmp(op,"script-get")||!strcmp(op,"trustee-get")||!strcmp(op,"group-members");if(!readonly&&!confirm(req))return error(c,400,"Aktion bestätigen.");json_object *res=!strcmp(u,"/api/bindery")?bindery_call(req):print_call(req);return reply(c,get(res,"error")?400:200,res,NULL);} diff --git a/packaging/build-deb.py b/packaging/build-deb.py new file mode 100644 index 0000000..f387343 --- /dev/null +++ b/packaging/build-deb.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Build a host-native Ubuntu/Debian DEB without installing or starting services.""" +import os,pathlib,subprocess,shutil,tempfile,hashlib +root=pathlib.Path(__file__).resolve().parents[1];out=root/'releases/deb';out.mkdir(parents=True,exist_ok=True) +def run(*cmd,**kw):return subprocess.check_output(cmd,text=True,**kw) +arch=run('dpkg','--print-architecture').strip() +with tempfile.TemporaryDirectory(prefix='mars-deb-') as tmp: + stage=pathlib.Path(tmp)/'pkg';stage.mkdir() + run('cmake','--install',str(root/'upstream/build'),env={**os.environ,'DESTDIR':str(stage)}) + def copy(src,dst,mode=0o644): + target=stage/dst;target.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(root/src,target);target.chmod(mode) + for name in ('mars_vme','mars-pcapd','mars-print'):copy('build/'+name,'usr/local/sbin/'+name,0o755) + copy('packaging/mars-ipxpkt-net','usr/local/libexec/mars-ipxpkt-net',0o755) + copy('install-driver-packages.py','usr/local/libexec/mars-install-drivers',0o755) + for name in ('publish-mtcp.sh','publish-winclient.sh'):copy(name,'usr/local/sbin/mars-'+name.removesuffix('.sh'),0o755) + for f in (root/'websetup').iterdir(): + if f.is_file():copy(str(f.relative_to(root)),'usr/local/share/mars-vme/www/'+f.name) + for f in (root/'releases/windows').iterdir():copy(str(f.relative_to(root)),'usr/local/share/mars-vme/driver-packages/'+f.name) + # Runtime state/config is created only if absent by postinst, never shipped over existing configuration. + conf=stage/'usr/local/etc/mars_nwe/nwserv.conf' + if conf.exists():conf.unlink() + service=(root/'mars_vme.service').read_text().replace('--port 8787','--port 8787 --no-autostart') + target=stage/'lib/systemd/system/mars_vme.service';target.parent.mkdir(parents=True,exist_ok=True);target.write_text(service) + deb=stage/'DEBIAN';deb.mkdir() + # Derive exact ELF runtime dependencies from the host shlibs database. + control=pathlib.Path(tmp)/'debian';control.mkdir();(control/'control').write_text('Source: mars-vme\nMaintainer: MARS VME \n\nPackage: mars-vme\nArchitecture: any\nDescription: MARS VME\n') + elfs=[p for p in stage.rglob('*') if p.is_file() and p.read_bytes()[:4]==b'\x7fELF'] + deps=run('dpkg-shlibdeps','-O',*[str(p) for p in elfs],cwd=tmp).strip().split('shlibs:Depends=',1)[1] + (deb/'control').write_text(f'Package: mars-vme\nVersion: 0.8.1-1\nArchitecture: {arch}\nMaintainer: MARS VME \nDepends: {deps}, python3, jq, iproute2, nftables, libpcap0.8t64\nSection: net\nPriority: optional\nDescription: MARS VME server with web administration and Windows driver packages\n Host-native Ubuntu 26.04 build. Windows drivers are experimental.\n') + (deb/'postinst').write_text('''#!/bin/sh +set -e +if [ "$1" = configure ]; then + install -d -m 0755 /usr/local/etc/mars_nwe /var/mars_nwe/SYS/public + install -d -m 0700 /var/lib/mars-vme + if [ ! -f /usr/local/etc/mars_nwe/nwserv.conf ]; then + umask 077 + printf '2 MARS\\n3 0x12345678 1\\n1 SYS /var/mars_nwe/SYS\\n5 0\\n200 0\\n' > /usr/local/etc/mars_nwe/nwserv.conf + fi + if [ -d /run/systemd/system ]; then + systemctl daemon-reload + systemctl enable mars_vme.service + systemctl start mars_vme.service + fi + echo 'Web setup: http://SERVER:8787 — initial admin/admin, change password first.' + echo 'Configure IPX/network and SYS volume in the web UI before starting NetWare.' +fi +''') + (deb/'prerm').write_text('''#!/bin/sh +set -e +if [ "$1" = remove ] && [ -d /run/systemd/system ]; then + systemctl stop mars_vme.service + systemctl disable mars_vme.service +fi +''') + (deb/'conffiles').write_text(''.join('/'+str(f.relative_to(stage))+'\n' for f in (stage/'usr/local/etc').rglob('*') if f.is_file())) + for name in ('postinst','prerm'):(deb/name).chmod(0o755) + for name in ('COPYING','LEGACY-BUILD.md','WINDOWS.md','DRIVER-RELEASE.md'):copy(name,'usr/share/doc/mars-vme/'+name) + package=out/f'mars-vme_0.8.1-1_{arch}.deb';run('dpkg-deb','--root-owner-group','--build',str(stage),str(package)) + (out/'SHA256SUMS').write_text(hashlib.sha256(package.read_bytes()).hexdigest()+' '+package.name+'\n') + print(package) diff --git a/packaging/mars-ipxpkt-net b/packaging/mars-ipxpkt-net new file mode 100755 index 0000000..911a487 --- /dev/null +++ b/packaging/mars-ipxpkt-net @@ -0,0 +1,62 @@ +#!/bin/sh +# Called only by mars-pcapd. Own TAP, own nft table. Never change host forwarding. +set -eu +PATH=/usr/sbin:/usr/bin:/sbin:/bin +export PATH +[ "$(id -u)" = 0 ] || exit 1 +case "$1" in + down) nft delete table inet mars_ipxpkt; exit;; + up) ;; + *) exit 2;; +esac +uplink=$2; gateway=$3; dns=$4; mac=$5; web=$6; ping=$7 +# Defense in depth; caller already validates full address ranges and interface names. +case "$uplink" in ''|-*|*[!a-zA-Z0-9_.-]*|lo|marsipx0) exit 2;; esac +case "$gateway:$dns" in *[!0-9.:]*) exit 2;; esac +case "$mac" in *[!0-9a-f:]*) exit 2;; esac +[ "$web" = 0 ] || [ "$web" = 1 ] || exit 2 +[ "$ping" = 0 ] || [ "$ping" = 1 ] || exit 2 +[ "$(cat /proc/sys/net/ipv4/ip_forward)" = 1 ] || { echo 'IPXPKT: Enable IPv4 forwarding deliberately before use' >&2; exit 1; } +# Refuse existing containing or more-specific routes in any table (except default). +subnet=${gateway%.*}.0/24 +cover=$(ip -4 route show table all match "$subnet") || exit 1 +inside=$(ip -4 route show table all root "$subnet") || exit 1 +if [ -n "$inside" ] || printf '%s\n' "$cover" | grep -Ev '^(default([[:space:]]|$)|[[:space:]]*$)' >/dev/null; then + echo "IPXPKT: virtual network overlaps an existing route: $subnet" >&2; exit 1 +fi +# Never replace an existing table (including stale table after a crash). +if nft list table inet mars_ipxpkt >/dev/null 2>&1; then echo 'IPXPKT: nft table mars_ipxpkt already exists; inspect before removing' >&2; exit 1; fi + +# Forwards only IPv4 Internet traffic on the selected uplink; no access to local host. +# IPv4 non-public ranges blocked. Sites with internally routed public space must add restrictions. +web_rule=''; ping_rule='' +[ "$web" = 0 ] || web_rule='iifname "marsipx0" tcp dport { 80, 443 } ct state new,established accept' +[ "$ping" = 0 ] || ping_rule='iifname "marsipx0" icmp type echo-request ct state new,established accept' +nft -f - < /proc/sys/net/ipv6/conf/marsipx0/disable_ipv6; fi +ip -4 addr add "$gateway/24" dev marsipx0 +ip link set dev marsipx0 up +trap - EXIT diff --git a/patch-upstream.sh b/patch-upstream.sh index 3e3481c..2cbe1e5 100755 --- a/patch-upstream.sh +++ b/patch-upstream.sh @@ -12,7 +12,7 @@ done grep -Fq '#include "config.h"' "$root/include/net.h" || exit 1 sed -i '0,/#include "config.h"/s//#include "config.h"\n#undef SIOCIPXNCPCONN\n#undef CALL_NWCONN_OVER_SOCKET\n#define CALL_NWCONN_OVER_SOCKET 0/' "$root/include/net.h" find "$root/src" "$root/include" -type f \( -name '*.c' -o -name '*.h' \) -exec sed -Ei 's@/proc/net/ipx(_interface|_route)?(["\x27])@/run/mars-pcap/ipx\1\2@g' {} + -if grep -En '\bsocket[[:space:]]*\([[:space:]]*(AF|PF)_IPX\b' "$root"/src/*.c; then echo 'Unported direct IPX socket call' >&2; exit 1; fi +if grep -En '\bsocket[[:space:]]*\([[:space:]]*(AF|PF)_IPX\b' "$root"/src/emutli.c "$root"/src/emutli1.c; then echo 'Unported direct IPX socket call' >&2; exit 1; fi cp "$here/src/shim.h" "$root/include/mars_pcap_shim.h" cat >> "$root/src/CMakeLists.txt" <<'CMAKE' # MARS_PCAP_PORT_V1 @@ -58,3 +58,20 @@ f="$root/src/ftrustee.c" cp "$here/upstream-adapter/mars_trustee.inc" "$root/src/" sed -i '/^int main(int argc, char \*argv\[\])/i #include "mars_trustee.inc"' "$f" sed -i '/^ localinit();/a\ if (argc > 1 \&\& !strcmp(argv[1], "--mars-admin")) return mt_admin(argc, argv);' "$f" + +# Modern glibc removed sys_errlist/sys_nerr; strerror preserves error text. +sed -i -e 's/errnum > 0 \&\& errnum < _sys_nerr/errnum > 0/g' -e 's/errnum >= 0 \&\& errnum < _sys_nerr/errnum >= 0/g' -e 's/_sys_errlist\[errnum\]/strerror(errnum)/g' "$root/src/tools.c" +# Use libc poll declarations with the native admin adapter; retain the old +# select-based helper under a private name instead of interposing libc poll. +python3 - "$root" <<'PY' +import pathlib,sys,re +root=pathlib.Path(sys.argv[1]) +p=root/'include/emutli.h';s=p.read_text();s=re.sub(r'struct pollfd \{.*?#define POLLPRI[^\n]*', '#include ', s, flags=re.S);s=re.sub(r'extern int poll\([^;]+;', '',s);p.write_text(s) +p=root/'src/emutli.c';s=p.read_text().replace('int poll(', 'int mars_legacy_poll(');p.write_text(s) +PY + +# LOCALSTATEDIR is absolute in our build; avoid //var (network-path DESTDIR error). +sed -i 's@"/${CMAKE_INSTALL_LOCALSTATEDIR}/@"${CMAKE_INSTALL_LOCALSTATEDIR}/@g' "$root/cmake/modules/MarsNweInstallDirs.cmake" + +# Upstream renamed the printer helper to _prn without updating installation. +sed -i 's@install(FILES prn DESTINATION ${MARS_NWE_INSTALL_FULL_LIBEXECDIR})@install(FILES _prn DESTINATION ${MARS_NWE_INSTALL_FULL_LIBEXECDIR} RENAME prn)@' "$root/opt/CMakeLists.txt" diff --git a/publish-mtcp.sh b/publish-mtcp.sh new file mode 100755 index 0000000..70c9855 --- /dev/null +++ b/publish-mtcp.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Publish trusted FreeDOS mTCP and Crynwr ZIPs, preserving their original archives. +# No client-supplied paths, no ZIP extraction into live SYS, no overwrite. +set -euo pipefail +export PATH=/usr/sbin:/usr/bin:/sbin:/bin +umask 077 +fail(){ echo "mTCP: $*" >&2; exit 1; } +[[ $EUID == 0 ]] || fail 'run as root' +conf=${MARS_CONF:-/usr/local/etc/mars_nwe/nwserv.conf} +[[ -f $conf ]] || fail 'nwserv.conf missing' +mapfile -t roots < <(awk '$1==1 && toupper($2)=="SYS" {print $3}' "$conf") +[[ ${#roots[@]} == 1 && ${roots[0]} == /* ]] || fail 'exactly one SYS with absolute path required' +sys=$(realpath -e -- "${roots[0]}") || fail 'SYS path missing' +[[ $sys != / ]] || fail 'SYS cannot be /' +secure_dir(){ [[ -d $1 && ! -L $1 && $(stat -c %u -- "$1") == 0 ]] && (( (8#$(stat -c %a -- "$1") & 022) == 0 )); } +secure_dir "$sys" || fail 'SYS must be root-owned and not group/world writable' +public=; for d in "$sys/PUBLIC" "$sys/public"; do if [[ -e $d || -L $d ]]; then [[ -z $public ]] || fail 'ambiguous PUBLIC case'; public=$d; fi; done +[[ -n $public ]] && secure_dir "$public" || fail 'initialize root-owned SYS:PUBLIC first' +[[ ! -e $public/MTCP && ! -L $public/MTCP && ! -e $public/mtcp && ! -L $public/mtcp ]] || fail 'MTCP already exists; preserve existing installation, move it aside deliberately before updating' +command -v unzip >/dev/null || fail 'install unzip' +work=$(mktemp -d); stage=''; trap 'rm -rf -- "$work"; if [[ -n $stage ]]; then rm -rf -- "$stage"; fi' EXIT +if [[ $# == 1 && $1 == --download ]]; then + command -v curl >/dev/null || fail 'install curl' + base=https://ibiblio.org/pub/micro/pc-stuff/freedos/files/repositories/latest/net + curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' --max-time 120 "$base/mtcp/20250604.0/mtcp.zip" -o "$work/MTCP.ZIP" + curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' --max-time 120 "$base/crynwr.zip" -o "$work/CRYNWR.ZIP" + # Published FreeDOS checksums (integrity/version pin, not a digital signature). + (cd "$work"; printf '%s\n' 'bb747d0163519a946c5808bd38a49a6680db39c1 MTCP.ZIP' 'c72d97e1cdc05ca6bf9910d01bda54ba661a34c6 CRYNWR.ZIP' | sha1sum -c -) || fail 'archive hash changed; review upstream before manual import' +elif [[ $# == 2 ]]; then + [[ -f $1 && -f $2 ]] || fail 'supply two trusted ZIP files' + cp -- "$1" "$work/MTCP.ZIP"; cp -- "$2" "$work/CRYNWR.ZIP" +else fail 'usage: sudo ./publish-mtcp.sh --download OR mtcp.zip crynwr.zip'; fi +stage=$(mktemp -d "$public/.mtcp-stage-XXXXXXXX") +# Select unique basename, extract only exact safe paths. Archive never unpacked wholesale. +extract(){ local zip=$1 name=$2 required=$3; local -a matches; mapfile -t matches < <(unzip -Z1 "$zip" | awk -F/ -v name="$name" 'toupper($NF)==name {print}'); if (( ${#matches[@]} == 0 )) && [[ $required == optional ]]; then return; fi; (( ${#matches[@]} == 1 )) || fail "missing or ambiguous $name"; local ent=${matches[0]}; [[ $ent =~ ^[A-Za-z0-9_./+-]+$ && $ent != /* && $ent != *..* ]] || fail "unsafe ZIP member $ent"; unzip -p "$zip" "$ent" > "$stage/$name" || fail "cannot extract $name"; [[ -s $stage/$name ]] || fail "empty $name"; } +extract "$work/CRYNWR.ZIP" IPXPKT.COM required +for name in DHCP.EXE PING.EXE; do extract "$work/MTCP.ZIP" "$name" required; done +for name in FTP.EXE FTPSRV.EXE TELNET.EXE HTGET.EXE SNTP.EXE NC.EXE IRCJR.EXE NETDRIVE.EXE; do extract "$work/MTCP.ZIP" "$name" optional; done +cp "$work/MTCP.ZIP" "$work/CRYNWR.ZIP" "$stage/" +printf 'PACKETINT 0x60\r\nHOSTNAME DOSCLIENT\r\n' > "$stage/MTCP.CFG" +# Run in the actual DOS command interpreter after LOGIN; environment survives CALL. +printf '%s\r\n' '@ECHO OFF' 'IF EXIST C:\MTCP\MTCP.CFG GOTO READY' 'IF NOT EXIST C:\MTCP\NUL MD C:\MTCP' 'COPY T:\MTCP.CFG C:\MTCP\MTCP.CFG' ':READY' 'SET MTCPCFG=C:\MTCP\MTCP.CFG' 'T:\IPXPKT.COM -i 0x60' 'ECHO Run T:\DHCP.EXE after the server approves this MAC.' > "$stage/SETUP.BAT" +printf '%s\r\n' '@ECHO OFF' 'CALL T:\SETUP.BAT' 'T:\DHCP.EXE' > "$stage/START.BAT" +printf '%s\r\n' 'MAP ROOT T:=SYS:PUBLIC\MTCP' > "$stage/MAP.TXT" +printf '%s\r\n' 'MARS NetWare mTCP distribution' 'Map T: to SYS:PUBLIC\MTCP in the NetWare login script.' 'Run CALL T:\SETUP.BAT once per boot, then T:\DHCP.EXE.' 'Change PACKETINT if 0x60 is already in use.' 'Keep C:\MTCP\MTCP.CFG local, never share writable configuration.' 'Original FreeDOS archives preserved. See their licensing and sources.' 'mTCP: https://github.com/mbbrutman/mTCP' 'Crynwr: https://github.com/fragglet/crynwr_mirror' > "$stage/README.TXT" +# Match volume case convention used by the original server. +name=MTCP +if [[ $public == */public ]]; then name=mtcp; for f in "$stage"/*; do b=${f##*/}; mv -- "$f" "$stage/${b,,}"; done; fi +chmod 644 "$stage"/*; chmod 755 "$stage"; mv -T -- "$stage" "$public/$name"; stage='' +printf 'Published %s (SYS:PUBLIC/MTCP). Add MAP ROOT T:=SYS:PUBLIC\\MTCP to login script. Verify NetWare read/file-scan trustees and deny write.\n' "$public/$name" diff --git a/publish-winclient.sh b/publish-winclient.sh new file mode 100755 index 0000000..def104b --- /dev/null +++ b/publish-winclient.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# Publish locally built MARS clients and the active gateway's address. No vendor binaries. +set -euo pipefail +export PATH=/usr/sbin:/usr/bin:/sbin:/bin +umask 077 +fail(){ echo "Windows clients: $*" >&2; exit 1; } +[[ $EUID == 0 ]] || fail 'run as root' +[[ $# == 1 ]] || fail 'usage: mars-publish-winclient --config-only OR /path/to/trusted/build-output' +conf=${MARS_CONF:-/usr/local/etc/mars_nwe/nwserv.conf} +gw=${MARS_GATEWAY_CONFIG:-/usr/local/etc/mars_nwe/ipxpkt.json} +interfaces=${MARS_IPX_INTERFACES:-/run/mars-pcap/ipx_interface} +command -v jq >/dev/null || fail 'install jq' +[[ -f $conf && -f $gw && -f $interfaces ]] || fail 'configure/start the gateway first' +mapfile -t roots < <(awk '$1==1 && toupper($2)=="SYS" {print $3}' "$conf") +[[ ${#roots[@]} == 1 && ${roots[0]} == /* ]] || fail 'exactly one SYS volume required' +sys=$(realpath -e -- "${roots[0]}") || fail 'missing SYS' +secure(){ [[ -d $1 && ! -L $1 && $(stat -c %u -- "$1") == 0 ]] && (( (8#$(stat -c %a -- "$1") & 022) == 0 )); } +[[ $sys != / ]] && secure "$sys" || fail 'unsafe SYS directory' +public=''; for d in "$sys/PUBLIC" "$sys/public"; do if [[ -e $d || -L $d ]]; then [[ -z $public ]] || fail 'ambiguous PUBLIC case'; public=$d; fi; done +[[ -n $public ]] && secure "$public" || fail 'initialize root-owned PUBLIC first' +for d in "$public/CLIENTS" "$public/clients"; do [[ ! -e $d && ! -L $d ]] || fail 'CLIENTS already exists; back up and move it aside before republishing'; done +net=$(jq -er 'select(.enabled == true) | .network | strings' "$gw") || fail 'gateway disabled or invalid configuration' +[[ $net =~ ^0[xX]([0-9a-fA-F]{1,8})$ ]] || fail 'invalid IPX network' +hex=${BASH_REMATCH[1]}; net=$(printf '%08X' "$((16#$hex))") +ip=$(jq -er '.gateway | strings' "$gw") +[[ $ip =~ ^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.1$ ]] || fail 'invalid gateway IPv4' +for x in "${BASH_REMATCH[@]:1}"; do ((10#$x <= 255)) || fail 'invalid gateway IPv4'; done +mapfile -t macs < <(awk -v n="$net" 'toupper($1)==n && $5~/^(Ethernet_II|802\.3|802\.2|SNAP)$/ {print toupper($2)}' "$interfaces") +[[ ${#macs[@]} == 1 ]] || fail 'selected IPX network is not uniquely present in dispatcher state' +mac=${macs[0]}; [[ $mac =~ ^[0-9A-F]{12}$ && $mac != 000000000000 ]] && (( (16#${mac:0:2} & 1) == 0 )) || fail 'invalid gateway MAC' +files=(); if [[ $1 != --config-only ]]; then + [[ -d $1 ]] || fail 'supply a trusted local build-output directory' + for f in IPXDIAG.EXE MARSNET.EXE MARSTAP.EXE MARSIPX.EXE MARSNDIS.SYS; do + if [[ -f $1/$f ]]; then [[ $(head -c2 "$1/$f") == MZ ]] || fail "$f is not a PE/DOS executable"; files+=("$f"); fi + done + (( ${#files[@]} > 0 )) || fail 'no compiled client binaries found' + if [[ -f $1/MARSIPX.EXE || -f $1/MARSNDIS.SYS || -f $1/MARSNDIS.INF ]]; then + [[ -f $1/MARSIPX.EXE && -f $1/MARSNDIS.SYS && -f $1/MARSNDIS.INF ]] || fail 'native client requires EXE, SYS and INF together' + files+=(MARSNDIS.INF) + fi + if [[ -f $1/MARSNET3.SYS || -f $1/MARSNET.INF ]]; then + [[ ${MARS_ALLOW_PREVIEW:-0} == 1 ]] || fail "Legacy driver is experimental; use MARS_ALLOW_PREVIEW=1 only for isolated VM testing" + [[ -f $1/MARSNET.EXE && -f $1/MARSNET3.SYS && -f $1/MARSNET.INF ]] || fail "legacy client requires EXE, SYS and INF together" + [[ $(head -c2 "$1/MARSNET3.SYS") == MZ ]] || fail "invalid legacy SYS" + files+=(MARSNET3.SYS MARSNET.INF) + fi +fi +stage=$(mktemp -d "$public/.clients-stage-XXXXXXXX"); trap 'rm -rf -- "$stage"' EXIT +for os in WIN95 WIN98 WINME WINNT40 WIN2000 WINXP; do + d="$stage/$os"; mkdir "$d" + printf '[gateway]\r\nnetwork=%s\r\nserver=%s\r\nport=6181\r\nip=%s\r\n' "$net" "$mac" "$ip" > "$d/GATEWAY.INI" + printf '%s\r\n' 'Experimental MARS Windows IPXPKT client.' 'Copy files to a local directory before installing or running.' 'No Windows driver compatibility has been validated.' 'External legacy drivers are not supplied.' 'Read WINDOWS.md in the source package. Do not run against a physical adapter.' > "$d/README.TXT" + for f in "${files[@]}"; do + case $f in + MARSNET3.SYS|MARSNET.INF) [[ $os == WIN95 || $os == WIN98 || $os == WINME ]] || continue;; + MARSNET.EXE) if [[ -f $1/MARSNET3.SYS ]]; then [[ $os == WIN95 || $os == WIN98 || $os == WINME ]] || continue; fi;; + IPXDIAG.EXE) ;; + *) [[ $os == WIN2000 || $os == WINXP ]] || continue;; + esac + install -m 0644 -- "$1/$f" "$d/$f" + done + done +name=CLIENTS +if [[ $public == */public ]]; then name=clients; while IFS= read -r -d '' p; do b=${p##*/}; mv -- "$p" "${p%/*}/${b,,}"; done < <(find "$stage" -mindepth 1 -depth -print0); fi +find "$stage" -type f -exec chmod 644 {} +; find "$stage" -type d -exec chmod 755 {} + +mv -T -- "$stage" "$public/$name"; trap - EXIT +printf 'Published SYS:PUBLIC/CLIENTS (IPX %s, node %s, gateway %s). Verify read/file-scan trustees; deny writes.\n' "$net" "$mac" "$ip" diff --git a/releases/BUILD.json b/releases/BUILD.json new file mode 100644 index 0000000..7ee169b --- /dev/null +++ b/releases/BUILD.json @@ -0,0 +1,147 @@ +{ + "build_platform": "Ubuntu 26.04 amd64", + "date": "2026-11-27", + "source_sha256": { + ".gitattributes": "7734ec2a17b5253c392ed5124244446992717cb886bbbfb1a2d0b6438069bf37", + ".gitignore": "431673804ed1721e8a879e3769b467bea977bbb6341607860fb17342086ed9ad", + "AUTOSETUP.md": "0362ca7a853c398787ab2dda50cf1253026902c8833e80462890726cad3d8d3a", + "COPYING": "edaef632cbb643e4e7a221717a6c441a4c1a7c918e6e4d56debc3d8739b233f6", + "CROSS-BUILD.md": "8ca18f6dab297cb19c43021d6144f2183939b18b76c41dfe9ed0dc3cc0947dcc", + "DRIVER-RELEASE.md": "5f7c161c56d6a2b3ccfac723c45633b7ffde0ae4c951b4fc2ec049082e5e4cc8", + "GATEWAY.md": "30017a328ec885f941ba07519c04bf051307310ec8200cae997176fc18bb3ea6", + "GUIDE.md": "5da996702fe03f859dadcb06e82e253d22d74815c955da1c0b1d3b33aaa8207d", + "LEGACY-BUILD.md": "24b1d3fc19356f3b6657b4cedb17e39c07aa3a857e07cc5f615c4dc7aace2ac9", + "Makefile": "34bf670a8f4ec213bc8b29540ee9e9c5af10f9dcb29217fa0075ae6b6d0ea1cd", + "README.md": "7fc16ba46ab04bc053121b1f44c5d37e14ff9eb31296ce2ce29c4dff2ca98ac9", + "TEST-RESULTS-0.8.txt": "d73273d7424c247df7cb514d14e725629a3964b4216e87765922bc60d0c69f06", + "TEST-RESULTS.txt": "eb4605893e4611d552258b4302ae32eac95bf4d3aff62f5e1619ca179b20f1cc", + "WINDOWS.md": "4490c13c8c6d5868cc8d3f95b5c7c43ca8e15d31df86da2228d90037c329b19d", + "build-windows.sh": "1c3336d5f5a389026696ea11ebf928e2021657d0b74473da29652e796685d3a4", + "build.sh": "0eb605cc4a05afe40697a5e3f250bb476896651f4491b7412b720d55fb07d016", + "clients/windows/build-vc6.bat": "83542711b29467413d0491cb394fe2cd93db3c24bdd0fb75614b8f2da034ec6b", + "clients/windows/client_core.c": "32b34ecb9d87d754c753999e88d508824ebe1df2795cc5c8ad8c92e4d25af71c", + "clients/windows/client_core.h": "06924f07bcae4d301a0ecd14ddd1b466154aaed309423b88592d8f7925c36c03", + "clients/windows/diag/ipxdiag.c": "cd2f572339e463639873b4327b4b177fb4ba6fc387b0bcf3302c88157c6dbca5", + "clients/windows/marsnet.cpp": "3874a7b559f65ea1a0a22c21e9d78b48017334c74b3759f8e9b00e6f0fdf7d27", + "clients/windows/ndis3/INSTALL.BAT": "2d7bde591af070663498a00f39dda9f180182357dbe8338ba5ad50535b1eeda0", + "clients/windows/ndis3/MARSNET.INF": "07d9fba75a1606b17f68e38c0afb7fb50e7e650bc975b1bba05e23bc2a84b491", + "clients/windows/ndis3/NT4-INSTALL.txt": "89a3338c1d261fab14cc6267ab51991993961b26984da2a2764f8aa38ad11926", + "clients/windows/ndis3/freestanding/string.h": "e34ae372ee21781e1695c6236f34989aaba517f1f4c5b5df3b0e8eb961d8029c", + "clients/windows/ndis3/freestanding/time.h": "dc4380c76d4f73e7eb3d2afec40caa0b62e590648928bc2fa7d955cfcfaac728", + "clients/windows/ndis3/legacy_bridge.c": "4343d3198e7fcf46c9fc4b0cd868a0b6b59ed4204a224ceda40b696a6a5cec79", + "clients/windows/ndis3/legacy_core.c": "c6314b0ea640a0fd2c51a9e1c2fbd4556ae70a9556ad4ba67a4586e761eaebf0", + "clients/windows/ndis3/legacy_core.h": "5ba44051eb4a47692f8fb9fe21ad523f19d2f988df23cb2d6eb2d76e02d9bd23", + "clients/windows/ndis3/miniport.c": "503dd96d5bd6ce83aa916b3f3547142406de0212129477632f7962138272c8c4", + "clients/windows/ndis3/packet_backend.inc": "bd2e81e18d2dc211f511a5387e1ba4014d3e2c358b503c20ca4e83de1c752188", + "clients/windows/ndis5/MARSNDIS.INF": "882cd70df028799769afdbb09850e633d0002707b00ad860f2871e07e61fb828", + "clients/windows/ndis5/control.h": "384671fd47a3733b20bed7de84000c7fac7d0f99409f40fb770d72d35abcca07", + "clients/windows/ndis5/frame_queue.c": "f19759563dc583a69e7cd3784e230bafc5c7c656edef99483c17e9cb9c06603d", + "clients/windows/ndis5/frame_queue.h": "8555692034a6a3acee52158a4f32d31fa7698b561a14bd2e92079224d973cf43", + "clients/windows/ndis5/makefile": "7289517c7028ff031a48cc84f6308a437c3abe6e046c93f3132255221842d433", + "clients/windows/ndis5/miniport.c": "05f8bfd8023fc888a00401987530a76f96170ec6f64725891a694cd8c7fe2c98", + "clients/windows/ndis5/sources": "145a9a943e83563130df5195952766f7a1e87f643c7d8976a678fbc7c28678a5", + "cross/build-diag.sh": "bc9a38a17ec6a73052c9881488b1e8dd18ec3c625353fc3252b563cfdeacdb6e", + "cross/build-legacy-bridge.sh": "bfeef5fd53c1d9793641716a5a645d2290e5d5757779a3884457506229482c33", + "cross/build-legacy.sh": "2b2ded521c100729bf6ac72f51d0de576d27a4f768e702c27e3dda2d2f513a89", + "cross/build-nt5.sh": "cf5734fcc5425937a1e9078b700debd034c5748664e0ce52de5b723f1ffe497b", + "cross/build-windows.sh": "cce9717170b9633fab03d9da669e8196ea27c6d5c3f42d4a69f4b68c43ba4a48", + "cross/extract-nt4.sh": "4565a8cf2127909372b56fc0cc9b57e6e71f42364117da37909e9200a92cfb43", + "cross/fetch-legacy.sh": "5109013cbce2e747e5256f920ebb290906578e1820eb915d9782585a5bea201e", + "cross/fetch-watcom.sh": "faaa332ea915fcca576478daa75c6f6e403b1670a26a75b94726205224fe733e", + "cross/fetch-winpcap.sh": "12d2c55a2fce62eb0acfe122ce3c6d8b9ff86f385dd34b6afb49906560929fab", + "cross/generate-nt4-inf.py": "2fbdd694095da3114848e7edc21807265d412e8d4fade52e1a028f9040f256bf", + "cross/install-tools.sh": "e8fe4036cff23c27d1d43c3004d48befba6345f001c35e3377dc5a980b6d16bb", + "cross/package-drivers.py": "e7c611374b2bdb9a255770d5ab763e39dc59513f972279389446904128844804", + "cross/prepare-mingw-ddk.py": "4e6460a6f14ec48e5dca995a747c1d4ea491e1342b314118ad7350d965a40eb5", + "cross/prepare-nt4.py": "197b83eb74e4a36fd03b636c3fbdf8c230ae4242ad1ea2044ce371a1f66fc929", + "cross/verify-pe.py": "d51d50bebd69beaccef3bbbdec3819183bfaa544e8e49731b1033dfe3feabd52", + "cross/watcom-check.sh": "98f7ecf361640994404020795633aace2573184a4d2be31045aeac382caab45e", + "install-driver-packages.py": "7d2d4bf795af9dde3b2db0a373bdff961fb2c0601d307ddbdccb17b0214b224d", + "install-gateway.sh": "e1a67014f5c07432c0d6bab10ee07f527502e89e04fc3fb0dd7734754a23b91a", + "install.sh": "1e8202d4e0999b314091c25763c89b74e616e9d892e4eac0f31501f249fc0263", + "ipxpkt.json.example": "345e7a3960a3348459c234649bd84c0545ea5fe1af790f43fcfc953470451572", + "mars_vme.service": "7781a5181db734a2de5e5376c7363cdc8e9438ff5371fd617865cbef122b0c23", + "native/admin.c": "131b201ced62d3fc21e9e6957a8906c97e97d43c415f91daed7096e6bca690f2", + "native/admin.h": "2c33a7821ec4a19d0546e50c9071f1afddf344202ec95df07385e78233bbca87", + "native/core.c": "bbd81db2c667b3edd6c7b604f0870f5e260ce7c01d1941c115ad2ed55cc2edc2", + "native/core.h": "dae8c86e6207a843e015a90c621e5a0cf529548a84d7b8cff45e55c7a2ccb08e", + "native/gateway_auto.c": "9d4dcce581a766422b1156b789a7816200bf5a70d5a4ca2f822a707016bd77aa", + "native/gateway_auto.h": "ab9ff76a9295b7e551faf125b01050d27d7577260eee250b84803b55231f505d", + "native/main.c": "85022bfe7408fa257b5d79eefe26f3947084d43581ddbfb9fdfadec5f764a9a1", + "native/print_stdin.c": "a5eddc478d382b5dd169b6f92fbf407730883405521d77f3c551b4410a9f43ee", + "native/printing.c": "188a309f1980d6a30284aa4366618dfc3ebc87dd312468b0b8cd2bf77ebae28a", + "native/rawprint.c": "47081a2c51b3579b5f233cfe9471ee0395361417c2c4eb01d8bb1aca59e004db", + "native/supervisor.c": "782c74d14ac1a7b1296d5cb02d4961a40089e96491b838d61f188177d0568df5", + "native/supervisor.h": "848ffc75251a213dd241b68db0d7dc73e46624fe2cb5d4904e4c116e5bb9a719", + "nwserv-pcap.conf.example": "a8b55e29856ffb588f62551af3ddad53a6aec63a693500fc109947cbe4e021b9", + "packaging/build-deb.py": "32935dff3d22ce1accbb10ac3e31c7a74d8f73f9a4cfe8deac783b1eb3973c98", + "packaging/mars-ipxpkt-net": "121ac27be8b3a0602218ef21ffe9281bfe115b0f8a558d813634f47e83095fe3", + "patch-upstream.sh": "3991edfebb985b696a21d8b9e8187b007eb6bf35bb20b1475e9400bbae1d97f6", + "publish-mtcp.sh": "a7f8edc1df683bbcd79dd0c9556dbb00541fbd2ee253e389a248a6b38222b88b", + "publish-winclient.sh": "96a441e55926a4406b2c885ed71105a60abc36d3b883340393ddf1b2fec52165", + "rebuild.sh": "97570ca8b73a99322c888f8f7458469ec8023203a2ebf4e6c2ae1ebd2b0c6c68", + "run-ipc-test.sh": "319e82cd7ac84efff5ba34dffe19a24d5be32b73e450f53279ad5b112fdc7578", + "src/broker.c": "8f4b3c4bbb958fa018653ecec88bf77bcf104ffd6185c9017590124388589395", + "src/dhcp.c": "27bfd310e8aa23164f1c72ea060adb752974d753892e1f0f86e5570f733e73b0", + "src/gateway.c": "c9745da0f5fb5006911b6a4edb38de8e0a081d41340a50131db4b560c38a1d50", + "src/gateway.h": "dc97094913ca2f3f688dfc556ad143a979e0ce718c2bea41eb4d615b0216be9e", + "src/gateway_config.c": "5404d4630d011c1519bfb4fd990ce722da0f1e8593899f680f9b9def482ea952", + "src/ipxpkt.c": "3f521df25785ba41c8d2d317f46006124b7990e6fd4d25e5867c2460e1dc1b78", + "src/ipxpkt.h": "47d875b9320b1cc6c7668339acba08062e5e8aa66f63a9558c35f59198dcc1e5", + "src/pcap_dyn.c": "b8e46328d3df6a565c868b3a61d69591dffcc7ee09323eba36c5a010e8cf2149", + "src/pcap_dyn.h": "cb51b1941961b37c913a8f5b732e1ed9335e6ee0e5fffd199a448571366030e7", + "src/shim.c": "1289b80797e06a5d66bd6a601949bb6e55aaa51f29d6023ad916d4b8a22b66c0", + "src/shim.h": "96c62a09a073b3a7508388084f79a1976c566c61b4feb286b8ee9e365edd58ce", + "src/wire.c": "05f7828a084f1650c0a5374f33c2af2f2effa35a7c73e361a8b627ff10462fdd", + "src/wire.h": "611f12e165cc09297a7de3462488baf435ef8203ac9b410a4eaa05799285844d", + "tests/test_driver_ui.cjs": "9a890cd6f832cdd057f45f70918e77c9662dfd1bbb541d1ad11c9247f2139d6a", + "tests/test_gateway.c": "032bc5ab4d8a07557d4a48268a6cc04ae9ea16786f04104dbadb6472fb6c103d", + "tests/test_gateway_auto.c": "6b997b232733a2df3436c39a65a58878188de392844e0ac74f7d5822176f8332", + "tests/test_gateway_browser.py": "e999418dcc2c3aa416818ee5f92ad46fdf32e47fb2931dc8644e307c65a640f1", + "tests/test_ipc.c": "95f4f8eccbb8adc0575b5376a2a6334abbaa5ed19e6bb12143a07de81ac6d00c", + "tests/test_legacy.c": "00be3ce55a89e46f51702e4b438a6102c4a2a0f1a0ca45c5923a9c40a8a2dd67", + "tests/test_native.c": "75832aaa6ddc2518631abdfc709fc21e0d2513b27f5477327870c4e83fb226cb", + "tests/test_print.c": "f9a7dec922205ce0ab926542dcd62f51cdb5d370c49ec5428e8c9b545414ff52", + "tests/test_publish_winclient.sh": "571ef8a2f2d98046414611b0e4bdc20cbea3881709690d6ef20de050dfc6a164", + "tests/test_raw.c": "7c9a46ec34826cec2dc20e29cedd7e10f44369a9b1f6ca1c03a153af22c0a72e", + "tests/test_scripts.c": "a5107a1af8ab3b78967fa1e01a39f94da0863042ee56a35488cda47566f54d8b", + "tests/test_scripts_browser.py": "5a32cd91bfa1f369c8e360308ac98cecf4fc60f9229786ffcfd8922dee6f0f7d", + "tests/test_supervisor.c": "c443d01464ca102e2ac61eb22bd3714275765fa7541a69d69f12e7397c69d916", + "tests/test_trustee.c": "7977218fa84b9ce327e415957846d36371f00f6a4d1f2098741edd172c7559ac", + "tests/test_web.sh": "3b601ef644734bf5e29671a9ffd8f0ee1315dffa851639a167c5f38f51776613", + "tests/test_winclient.c": "8c70b7a8ddb2374362fcec16bb9bbb2d48a1cfe993620e45da1666e37fc289be", + "tests/test_wire.c": "9ddebde76967f6a47b6ce8cabc73dbb1d0cc6f0e7f55214dabc95a1d3e7194f2", + "upstream-adapter/mars_acl.inc": "e0242f3c3b73aa6e9bec3f9411f940105234c0b6d437a742d216944a3beb0075", + "upstream-adapter/mars_admin.inc": "f0ba853a7fa6013c734a40a2e6aa8e699803dd647110275dd38ed46877c4ba66", + "upstream-adapter/mars_scripts.inc": "9ce05080ed78f408dabef7706ff8c459ab44e10956cb33bdd30be805f72cbc02", + "upstream-adapter/mars_trustee.inc": "3b137e252fcb7f862294987dd181e32a120d1a926e6aac6d3d4bffca840ffafd", + "upstream/source-revision.txt": "c4f507776412305617be744a3cb5d603d8728d2960ee97584c43f41c7e3de0d1", + "websetup/app.js": "e1ce82b6064fc66022d40fba028aa6618e011806446cb57dcf9759db0912d969", + "websetup/index.html": "d629e69fe959ab63ac6010ef94d0c31c7b661fa052ce8268dd5d236c019bb92d", + "websetup/login.html": "380028a244d607ad3f902cb7bcd721c600c700162bdfd56db32ec14dc3438683", + "websetup/login.js": "d231007ad915ce01170577b39e6a8ab555eae4980d3cc017b9912cbb1bbfd98f", + "websetup/style.css": "ea44e51387124701b5db2877f9f05a550b16609d13b42e47293d9147a6d227a7" + }, + "artifact_sha256": { + "releases/windows/WINME.zip": "79fb9dfa5a13ded5eb8a5d14f96015cba8011f0bd53b0c5a2a914c13025f293b", + "releases/windows/WINXP.zip": "3c4e2da87db5acd2d852cc319b29faca4dfc48c3d1d80eac324a9f29a5a210ea", + "releases/windows/WIN2000.zip": "03889e20e1ac5a488a753c1a64a0164457aeff9e1f7688505a9ecab1fcce76ec", + "releases/windows/WIN98.zip": "a8bc510f3b7ec189ba755b635df485741e34a1d4e53cfa4a480d98a46cde9b1d", + "releases/windows/WINNT40.zip": "3b3bcf1f9527bfd4da6fc35ef2655690ddad8174233182b642efc50b6b77cb6a", + "releases/windows/WIN95.zip": "61a30559021b1a5d9c7f33b9475385baff05b1561a8af2c43d34a7acf3907621", + "releases/deb/mars-vme_0.8.1-1_amd64.deb": "4cfb0f64673b409e1c5371267d4bd28e5678bc89e4473202020c3eb6b27aa390" + }, + "checks": [ + "all six cross-targets and PE checks", + "native core/supervisor/gateway/client tests", + "CivetWeb authentication and download allowlist", + "Chromium UI with mock API", + "isolated selected-platform publication", + "DEB extraction and payload byte comparison" + ], + "runtime_unverified": [ + "Windows drivers and installers", + "DEB install on a separate host", + "real NetWare/IPX transport" + ] +} diff --git a/releases/README.md b/releases/README.md new file mode 100644 index 0000000..95a3cbd --- /dev/null +++ b/releases/README.md @@ -0,0 +1,13 @@ +# Fertige Pakete + +- [Linux DEB – Ubuntu 26.04 amd64](deb/mars-vme_0.8.1-1_amd64.deb) +- [Windows 95](windows/WIN95.zip) +- [Windows 98](windows/WIN98.zip) +- [Windows ME](windows/WINME.zip) +- [Windows NT 4.0](windows/WINNT40.zip) +- [Windows 2000](windows/WIN2000.zip) +- [Windows XP](windows/WINXP.zip) + +[Installation und Web-Freigaben](../DRIVER-RELEASE.md). +SHA256SUMS liegen in den jeweiligen Unterordnern. +Windows-Treiber sind gebaute, noch nicht unter Windows abgenommene Kandidaten. diff --git a/releases/deb/SHA256SUMS b/releases/deb/SHA256SUMS new file mode 100644 index 0000000..4876edb --- /dev/null +++ b/releases/deb/SHA256SUMS @@ -0,0 +1 @@ +4cfb0f64673b409e1c5371267d4bd28e5678bc89e4473202020c3eb6b27aa390 mars-vme_0.8.1-1_amd64.deb diff --git a/releases/deb/mars-vme_0.8.1-1_amd64.deb b/releases/deb/mars-vme_0.8.1-1_amd64.deb new file mode 100644 index 0000000..cde60c6 Binary files /dev/null and b/releases/deb/mars-vme_0.8.1-1_amd64.deb differ diff --git a/releases/windows/SHA256SUMS b/releases/windows/SHA256SUMS new file mode 100644 index 0000000..ec765b3 --- /dev/null +++ b/releases/windows/SHA256SUMS @@ -0,0 +1,6 @@ +61a30559021b1a5d9c7f33b9475385baff05b1561a8af2c43d34a7acf3907621 WIN95.zip +a8bc510f3b7ec189ba755b635df485741e34a1d4e53cfa4a480d98a46cde9b1d WIN98.zip +79fb9dfa5a13ded5eb8a5d14f96015cba8011f0bd53b0c5a2a914c13025f293b WINME.zip +3b3bcf1f9527bfd4da6fc35ef2655690ddad8174233182b642efc50b6b77cb6a WINNT40.zip +03889e20e1ac5a488a753c1a64a0164457aeff9e1f7688505a9ecab1fcce76ec WIN2000.zip +3c4e2da87db5acd2d852cc319b29faca4dfc48c3d1d80eac324a9f29a5a210ea WINXP.zip diff --git a/releases/windows/WIN2000.zip b/releases/windows/WIN2000.zip new file mode 100644 index 0000000..40866d8 Binary files /dev/null and b/releases/windows/WIN2000.zip differ diff --git a/releases/windows/WIN95.zip b/releases/windows/WIN95.zip new file mode 100644 index 0000000..1ee30a8 Binary files /dev/null and b/releases/windows/WIN95.zip differ diff --git a/releases/windows/WIN98.zip b/releases/windows/WIN98.zip new file mode 100644 index 0000000..e8a3923 Binary files /dev/null and b/releases/windows/WIN98.zip differ diff --git a/releases/windows/WINME.zip b/releases/windows/WINME.zip new file mode 100644 index 0000000..c096438 Binary files /dev/null and b/releases/windows/WINME.zip differ diff --git a/releases/windows/WINNT40.zip b/releases/windows/WINNT40.zip new file mode 100644 index 0000000..cdd2949 Binary files /dev/null and b/releases/windows/WINNT40.zip differ diff --git a/releases/windows/WINXP.zip b/releases/windows/WINXP.zip new file mode 100644 index 0000000..8220652 Binary files /dev/null and b/releases/windows/WINXP.zip differ diff --git a/releases/windows/manifest.json b/releases/windows/manifest.json new file mode 100644 index 0000000..b90e18c --- /dev/null +++ b/releases/windows/manifest.json @@ -0,0 +1,103 @@ +{ + "WIN95": { + "sha256": "61a30559021b1a5d9c7f33b9475385baff05b1561a8af2c43d34a7acf3907621", + "files": { + "COPYING": "edaef632cbb643e4e7a221717a6c441a4c1a7c918e6e4d56debc3d8739b233f6", + "INSTALL.BAT": "2d7bde591af070663498a00f39dda9f180182357dbe8338ba5ad50535b1eeda0", + "IPXDIAG.EXE": "a12dc58710f9855773c0fb0a8c6b14da7ec091299549c4938835649092fc5bfb", + "LEGACY-BUILD.md": "24b1d3fc19356f3b6657b4cedb17e39c07aa3a857e07cc5f615c4dc7aace2ac9", + "MARSNET.EXE": "74b3b035909261a9730ecff10036f57ed74a2b38f03daa0a17895e2741dc2a19", + "MARSNET.INF": "07d9fba75a1606b17f68e38c0afb7fb50e7e650bc975b1bba05e23bc2a84b491", + "MARSNET.imports.txt": "6a9d50273a3b7e23afda6f058f963cf9c665a82457db15135084b2aba218061d", + "MARSNET3.SYS": "412779fc4ef1b4b76d79c1ec04807f0c818d8fa0e027345c12c46f5e32a66f07", + "MARSNET3.imports.txt": "5198352604352f9be43cfe738ce42cd29b5a602c506be36ecf4c5396522e56b6", + "README.TXT": "45b1333c5fabd1f94c887c50f8de9c79b7257ccb184ad9e3ac56ca31fd697ce2", + "WINDOWS.md": "4490c13c8c6d5868cc8d3f95b5c7c43ca8e15d31df86da2228d90037c329b19d", + "WPCAP31.EXE": "cc3840c1b87fb73ce0f5612403d1fc0bbf192bde8639c81388133d80db59000d", + "WPCAP31.TXT": "49f26cf8a47577dcbe041e9dc392bd2b210cd6b496c37ab93cf3b0ea51ebe9d0" + } + }, + "WIN98": { + "sha256": "a8bc510f3b7ec189ba755b635df485741e34a1d4e53cfa4a480d98a46cde9b1d", + "files": { + "COPYING": "edaef632cbb643e4e7a221717a6c441a4c1a7c918e6e4d56debc3d8739b233f6", + "INSTALL.BAT": "2d7bde591af070663498a00f39dda9f180182357dbe8338ba5ad50535b1eeda0", + "IPXDIAG.EXE": "a12dc58710f9855773c0fb0a8c6b14da7ec091299549c4938835649092fc5bfb", + "LEGACY-BUILD.md": "24b1d3fc19356f3b6657b4cedb17e39c07aa3a857e07cc5f615c4dc7aace2ac9", + "MARSNET.EXE": "74b3b035909261a9730ecff10036f57ed74a2b38f03daa0a17895e2741dc2a19", + "MARSNET.INF": "07d9fba75a1606b17f68e38c0afb7fb50e7e650bc975b1bba05e23bc2a84b491", + "MARSNET.imports.txt": "6a9d50273a3b7e23afda6f058f963cf9c665a82457db15135084b2aba218061d", + "MARSNET3.SYS": "412779fc4ef1b4b76d79c1ec04807f0c818d8fa0e027345c12c46f5e32a66f07", + "MARSNET3.imports.txt": "5198352604352f9be43cfe738ce42cd29b5a602c506be36ecf4c5396522e56b6", + "README.TXT": "45b1333c5fabd1f94c887c50f8de9c79b7257ccb184ad9e3ac56ca31fd697ce2", + "WINDOWS.md": "4490c13c8c6d5868cc8d3f95b5c7c43ca8e15d31df86da2228d90037c329b19d", + "WPCAP31.EXE": "cc3840c1b87fb73ce0f5612403d1fc0bbf192bde8639c81388133d80db59000d", + "WPCAP31.TXT": "49f26cf8a47577dcbe041e9dc392bd2b210cd6b496c37ab93cf3b0ea51ebe9d0" + } + }, + "WINME": { + "sha256": "79fb9dfa5a13ded5eb8a5d14f96015cba8011f0bd53b0c5a2a914c13025f293b", + "files": { + "COPYING": "edaef632cbb643e4e7a221717a6c441a4c1a7c918e6e4d56debc3d8739b233f6", + "INSTALL.BAT": "2d7bde591af070663498a00f39dda9f180182357dbe8338ba5ad50535b1eeda0", + "IPXDIAG.EXE": "a12dc58710f9855773c0fb0a8c6b14da7ec091299549c4938835649092fc5bfb", + "LEGACY-BUILD.md": "24b1d3fc19356f3b6657b4cedb17e39c07aa3a857e07cc5f615c4dc7aace2ac9", + "MARSNET.EXE": "74b3b035909261a9730ecff10036f57ed74a2b38f03daa0a17895e2741dc2a19", + "MARSNET.INF": "07d9fba75a1606b17f68e38c0afb7fb50e7e650bc975b1bba05e23bc2a84b491", + "MARSNET.imports.txt": "6a9d50273a3b7e23afda6f058f963cf9c665a82457db15135084b2aba218061d", + "MARSNET3.SYS": "412779fc4ef1b4b76d79c1ec04807f0c818d8fa0e027345c12c46f5e32a66f07", + "MARSNET3.imports.txt": "5198352604352f9be43cfe738ce42cd29b5a602c506be36ecf4c5396522e56b6", + "README.TXT": "45b1333c5fabd1f94c887c50f8de9c79b7257ccb184ad9e3ac56ca31fd697ce2", + "WINDOWS.md": "4490c13c8c6d5868cc8d3f95b5c7c43ca8e15d31df86da2228d90037c329b19d", + "WPCAP31.EXE": "cc3840c1b87fb73ce0f5612403d1fc0bbf192bde8639c81388133d80db59000d", + "WPCAP31.TXT": "49f26cf8a47577dcbe041e9dc392bd2b210cd6b496c37ab93cf3b0ea51ebe9d0" + } + }, + "WINNT40": { + "sha256": "3b3bcf1f9527bfd4da6fc35ef2655690ddad8174233182b642efc50b6b77cb6a", + "files": { + "COPYING": "edaef632cbb643e4e7a221717a6c441a4c1a7c918e6e4d56debc3d8739b233f6", + "INSTALL.BAT": "2d7bde591af070663498a00f39dda9f180182357dbe8338ba5ad50535b1eeda0", + "IPXDIAG.EXE": "a12dc58710f9855773c0fb0a8c6b14da7ec091299549c4938835649092fc5bfb", + "LEGACY-BUILD.md": "24b1d3fc19356f3b6657b4cedb17e39c07aa3a857e07cc5f615c4dc7aace2ac9", + "MARSNET.EXE": "74b3b035909261a9730ecff10036f57ed74a2b38f03daa0a17895e2741dc2a19", + "MARSNET.imports.txt": "6a9d50273a3b7e23afda6f058f963cf9c665a82457db15135084b2aba218061d", + "MARSNET3.SYS": "412779fc4ef1b4b76d79c1ec04807f0c818d8fa0e027345c12c46f5e32a66f07", + "MARSNET3.imports.txt": "5198352604352f9be43cfe738ce42cd29b5a602c506be36ecf4c5396522e56b6", + "NT4-INSTALL.txt": "89a3338c1d261fab14cc6267ab51991993961b26984da2a2764f8aa38ad11926", + "OEMSETUP.INF": "b33f816e8bf285179ca2ce87ad7baf5c9cafd6bbcf448832af158762f2177ce8", + "README.TXT": "45b1333c5fabd1f94c887c50f8de9c79b7257ccb184ad9e3ac56ca31fd697ce2", + "WINDOWS.md": "4490c13c8c6d5868cc8d3f95b5c7c43ca8e15d31df86da2228d90037c329b19d", + "WPCAP31.EXE": "cc3840c1b87fb73ce0f5612403d1fc0bbf192bde8639c81388133d80db59000d", + "WPCAP31.TXT": "49f26cf8a47577dcbe041e9dc392bd2b210cd6b496c37ab93cf3b0ea51ebe9d0" + } + }, + "WIN2000": { + "sha256": "03889e20e1ac5a488a753c1a64a0164457aeff9e1f7688505a9ecab1fcce76ec", + "files": { + "COPYING": "edaef632cbb643e4e7a221717a6c441a4c1a7c918e6e4d56debc3d8739b233f6", + "IPXDIAG.EXE": "a12dc58710f9855773c0fb0a8c6b14da7ec091299549c4938835649092fc5bfb", + "LEGACY-BUILD.md": "24b1d3fc19356f3b6657b4cedb17e39c07aa3a857e07cc5f615c4dc7aace2ac9", + "MARSIPX.EXE": "e9183736c5ae249422aa6ad2d6b017dcdcbc322d2e0d9254c39014cc84d9abc3", + "MARSNDIS.INF": "882cd70df028799769afdbb09850e633d0002707b00ad860f2871e07e61fb828", + "MARSNDIS.SYS": "22ac82da3b1e46884994a98738426fbea4b9e4a3d02d2d6b8f604eb43b55f1a3", + "MARSTAP.EXE": "6858bb1d5db6e1e1730c330f56b35a2029638eb4b7498490b682aa07e7ab2c11", + "README.TXT": "45b1333c5fabd1f94c887c50f8de9c79b7257ccb184ad9e3ac56ca31fd697ce2", + "WINDOWS.md": "4490c13c8c6d5868cc8d3f95b5c7c43ca8e15d31df86da2228d90037c329b19d" + } + }, + "WINXP": { + "sha256": "3c4e2da87db5acd2d852cc319b29faca4dfc48c3d1d80eac324a9f29a5a210ea", + "files": { + "COPYING": "edaef632cbb643e4e7a221717a6c441a4c1a7c918e6e4d56debc3d8739b233f6", + "IPXDIAG.EXE": "a12dc58710f9855773c0fb0a8c6b14da7ec091299549c4938835649092fc5bfb", + "LEGACY-BUILD.md": "24b1d3fc19356f3b6657b4cedb17e39c07aa3a857e07cc5f615c4dc7aace2ac9", + "MARSIPX.EXE": "e9183736c5ae249422aa6ad2d6b017dcdcbc322d2e0d9254c39014cc84d9abc3", + "MARSNDIS.INF": "882cd70df028799769afdbb09850e633d0002707b00ad860f2871e07e61fb828", + "MARSNDIS.SYS": "22ac82da3b1e46884994a98738426fbea4b9e4a3d02d2d6b8f604eb43b55f1a3", + "MARSTAP.EXE": "6858bb1d5db6e1e1730c330f56b35a2029638eb4b7498490b682aa07e7ab2c11", + "README.TXT": "45b1333c5fabd1f94c887c50f8de9c79b7257ccb184ad9e3ac56ca31fd697ce2", + "WINDOWS.md": "4490c13c8c6d5868cc8d3f95b5c7c43ca8e15d31df86da2228d90037c329b19d" + } + } +} diff --git a/src/broker.c b/src/broker.c index d866986..8f3fbfe 100644 --- a/src/broker.c +++ b/src/broker.c @@ -1,6 +1,7 @@ /* SPDX-License-Identifier: GPL-2.0-or-later */ #define _GNU_SOURCE #include "wire.h" +#include "gateway.h" #include "pcap_dyn.h" #include #include @@ -44,7 +45,7 @@ static void reap(void){for(int i=0;i=0){struct pollfd p static int emit(int fd,struct msg *m){m->magic=IPC_MAGIC;ssize_t n=send(fd,m,MSG_HEAD+m->len,MSG_DONTWAIT|MSG_NOSIGNAL);if(n!=(ssize_t)(MSG_HEAD+m->len)){dropped++;return -1;}return 0;} static void deliver(uint16_t port,const struct sockaddr_ipx *src,const uint8_t *payload,size_t n){int i=port_owner(port);if(i<0)return;struct msg m={.op=M_DATA,.len=n,.addr=*src};if(n)memcpy(m.data,payload,n);emit(clients[i].fd,&m);} static void addr_for(struct sockaddr_ipx *a,struct iface *p,uint16_t port){memset(a,0,sizeof *a);a->sipx_family=AF_IPX;a->sipx_network=p->net;memcpy(a->sipx_node,p->mac,6);a->sipx_port=htons(port);} -static void close_iface(struct iface *a){if(a->pc)pc.close(a->pc);for(int i=0;inet)routes[i].dst=0;memset(a,0,sizeof *a);a->fd=-1;} +static void close_iface(struct iface *a){gw_detach(a->net);if(a->pc)pc.close(a->pc);for(int i=0;inet)routes[i].dst=0;memset(a,0,sizeof *a);a->fd=-1;} static int configure(struct msg *m){struct sockaddr_ipx *a=&m->addr;struct iface *p=NULL;if(a->sipx_special==IPX_INTERNAL){for(int i=0;isipx_special==IPX_PRIMARY&&!*m->dev)p=primary();else p=by_dev(m->dev,a->sipx_type); if(a->sipx_action==IPX_DLTITF){if(p)close_iface(p);write_state();return 0;}if(a->sipx_action!=IPX_CRTITF||!a->sipx_network||a->sipx_network==UINT32_MAX)return EINVAL; if(p||by_net(a->sipx_network))return EEXIST; @@ -54,27 +55,30 @@ static int configure(struct msg *m){struct sockaddr_ipx *a=&m->addr;struct iface if(q.special==IPX_INTERNAL){strcpy(q.dev,"Internal");memcpy(q.mac,a->sipx_node,6);if(iszero(q.mac))q.mac[5]=1;} else{if(!*m->dev||!memchr(m->dev,0,sizeof m->dev)||!strcmp(frname(q.kind),"None"))return EINVAL;strcpy(q.dev,m->dev); if(offline){q.mac[0]=2;q.mac[5]=1;}else{int fd=socket(AF_INET,SOCK_DGRAM,0);struct ifreq r={0};strcpy(r.ifr_name,q.dev);if(fd<0)return errno;if(ioctl(fd,SIOCGIFHWADDR,&r)<0){int e=errno;close(fd);return e;}close(fd);if(r.ifr_hwaddr.sa_family!=ARPHRD_ETHER)return EPROTONOSUPPORT;memcpy(q.mac,r.ifr_hwaddr.sa_data,6);char err[256]={0};q.pc=pc.open_live(q.dev,65535,1,20,err);if(!q.pc){fprintf(stderr,"pcap open %s: %s\n",q.dev,err);return EIO;}if(pc.datalink(q.pc)!=1||pc.setnonblock(q.pc,1,err)<0){fprintf(stderr,"pcap datalink/nonblock %s: %s\n",q.dev,err);pc.close(q.pc);return EIO;}if(pc.setdirection(q.pc,1)<0)fprintf(stderr,"pcap %s: direction unavailable; self MAC filter active\n",q.dev);q.fd=pc.get_selectable_fd(q.pc);}} - *p=q;write_state();fprintf(stderr,"IPX interface %08X %s %s\n",ntohl(q.net),q.dev,frname(q.kind));return 0;} + *p=q;if(!offline&&q.pc)gw_attach(q.net,q.dev,q.mac);write_state();fprintf(stderr,"IPX interface %08X %s %s\n",ntohl(q.net),q.dev,frname(q.kind));return 0;} static int route_set(struct msg *m){if(!m->net||m->net==UINT32_MAX)return EINVAL;int slot=-1;for(int i=0;inet){slot=i;break;}if(slot<0&&(!routes[i].dst||routes[i].expires<=time(NULL)))slot=i;}if(m->addr.sipx_family==0){if(slot>=0&&routes[slot].dst==m->net)routes[slot].dst=0;write_state();return 0;}struct iface *via=by_net(m->addr.sipx_network);if(!via||via->special==IPX_INTERNAL||iszero(m->addr.sipx_node)||isbc(m->addr.sipx_node))return ENETUNREACH;if(by_net(m->net))return EEXIST;if(slot<0)return ENOSPC;routes[slot]=(struct route){.dst=m->net,.via=via->net,.expires=time(NULL)+180};memcpy(routes[slot].mac,m->addr.sipx_node,6);write_state();return 0;} static struct iface *route_for(uint32_t net,const uint8_t *node,uint8_t *mac){struct iface *a=by_net(net);if(a&&a->special!=IPX_INTERNAL){memcpy(mac,node,6);return a;}for(int i=0;itime(NULL)){a=by_net(routes[i].via);if(a){memcpy(mac,routes[i].mac,6);return a;}}return NULL;} static int transmit(struct iface *out,const uint8_t *mac,const uint8_t *p,size_t n){uint8_t frame[1514];int len=frame_encode(frame,sizeof frame,out->kind,mac,out->mac,p,n);if(len<0){dropped++;return -1;}if(offline){tx_frames[out->kind]++;return 0;}if(pc.inject(out->pc,frame,len)!=len){fprintf(stderr,"pcap inject %s: %s\n",out->dev,pc.geterr(out->pc));dropped++;return -1;}tx_frames[out->kind]++;return 0;} +static int gw_transmit(uint32_t net,const uint8_t mac[6],const uint8_t*p,size_t n){struct iface*out=by_net(net);return out&&out->pc?transmit(out,mac,p,n):-1;} static int private_data(const uint8_t *p,size_t n){return n>=2&&((p[0]==0xee&&p[1]==0xee)||(p[0]==0xef&&p[1]==0xef));} static void outbound(int idx,struct msg *m){struct iface *p=primary();if(!p||!clients[idx].port){dropped++;return;}if(clients[idx].port==0x452)observe_sap(m->data,m->len);struct sockaddr_ipx dst=m->addr,src;addr_for(&src,p,clients[idx].port);src.sipx_type=dst.sipx_type;struct iface *local=by_net(dst.sipx_network);int bc=isbc(dst.sipx_node);if(local&&(!memcmp(local->mac,dst.sipx_node,6)|| (bc&&local->special==IPX_INTERNAL))){deliver(ntohs(dst.sipx_port),&src,m->data,m->len);return;} if(private_data(m->data,m->len)){dropped++;return;}uint8_t packet[IPX_MAX],mac[6];if(!dst.sipx_network||dst.sipx_network==UINT32_MAX){if(!bc){dropped++;return;}for(int i=0;idata,m->len);if(n>0)transmit(&ifs[i],d.sipx_node,packet,n);}return;} struct iface *out=route_for(dst.sipx_network,dst.sipx_node,mac);if(!out){dropped++;return;}/* RIP/SAP must announce from the external network, NCP retains its internal identity. */if(ntohs(src.sipx_port)==0x453||ntohs(src.sipx_port)==0x452)addr_for(&src,out,clients[idx].port);int n=ipx_make(packet,sizeof packet,&src,&dst,m->data,m->len);if(n>0)transmit(out,mac,packet,n);} -static void inbound(struct iface *in,const uint8_t *frame,size_t size){const uint8_t *p;size_t n;int kind;if(frame_decode(frame,size,&kind,&p,&n)<0||kind!=in->kind)return;if(memcmp(frame,in->mac,6)&&!isbc(frame))return;if(!memcmp(frame+6,in->mac,6))return;struct sockaddr_ipx src,dst;read_addr(&dst,p+6,p[5]);read_addr(&src,p+18,p[5]);if(!src.sipx_network)src.sipx_network=in->net;if(!dst.sipx_network)dst.sipx_network=in->net;if(isbc(src.sipx_node)||iszero(src.sipx_node)||!src.sipx_port||!dst.sipx_port||private_data(p+30,n-30))return;struct iface *s=by_net(src.sipx_network);if(s&&(s->special==IPX_INTERNAL||!memcmp(s->mac,src.sipx_node,6)))return;rx_frames[kind]++;observe_peer(&src);if(ntohs(src.sipx_port)==0x452)observe_sap(p+30,n-30); +static void inbound(struct iface *in,const uint8_t *frame,size_t size){const uint8_t *p;size_t n;int kind;if(frame_decode(frame,size,&kind,&p,&n)<0||kind!=in->kind)return;if(memcmp(frame,in->mac,6)&&!isbc(frame))return;if(!memcmp(frame+6,in->mac,6))return;struct sockaddr_ipx src,dst;read_addr(&dst,p+6,p[5]);read_addr(&src,p+18,p[5]);if(!src.sipx_network)src.sipx_network=in->net;if(!dst.sipx_network)dst.sipx_network=in->net;if(isbc(src.sipx_node)||iszero(src.sipx_node)||!src.sipx_port||!dst.sipx_port)return;if(gw_reserved(ntohs(dst.sipx_port))&&(dst.sipx_network==in->net||dst.sipx_network==UINT32_MAX)&&(!memcmp(dst.sipx_node,in->mac,6)||isbc(dst.sipx_node))){if(p[4]==0)gw_input(in->net,frame+6,frame,&src,&dst,p+30,n-30,gw_transmit);return;}if(private_data(p+30,n-30))return;struct iface *s=by_net(src.sipx_network);if(s&&(s->special==IPX_INTERNAL||!memcmp(s->mac,src.sipx_node,6)))return;rx_frames[kind]++;observe_peer(&src);if(ntohs(src.sipx_port)==0x452)observe_sap(p+30,n-30); struct iface *d=by_net(dst.sipx_network);if(d&&(!memcmp(d->mac,dst.sipx_node,6)||(d==in&&isbc(dst.sipx_node)))){deliver(ntohs(dst.sipx_port),&src,p+30,n-30);return;} if(!forwarding||isbc(dst.sipx_node)||isbc(frame)||p[4]>=15)return; uint8_t mac[6],buf[IPX_MAX];struct iface *out=route_for(dst.sipx_network,dst.sipx_node,mac);if(!out||out==in)return;memcpy(buf,p,n);buf[4]++;write_addr(buf+18,&src);write_addr(buf+6,&dst);transmit(out,mac,buf,n);} -static void command(int i){struct msg m;ssize_t n=recv(clients[i].fd,&m,sizeof m,MSG_DONTWAIT|MSG_TRUNC);if(n<=0){if(n==0||(errno!=EAGAIN&&errno!=EINTR))drop_client(i);return;}if(n<(ssize_t)MSG_HEAD||n>(ssize_t)sizeof m||m.magic!=IPC_MAGIC||m.len>IPX_MAX||(size_t)n!=MSG_HEAD+m.len){drop_client(i);return;}int e=0;struct iface *p=primary();switch(m.op){case M_SEND:outbound(i,&m);return;case M_BIND:{if(clients[i].port){e=EINVAL;break;}if(!p){e=EADDRNOTAVAIL;break;}reap();uint16_t port=ntohs(m.addr.sipx_port);if(port&&port_owner(port)>=0){e=EADDRINUSE;break;}if(!port){for(unsigned j=0;j<0xbfff;j++){port=nextport++;if(nextport<0x4000||nextport==0xffff)nextport=0x4000;if(port_owner(port)<0)break;port=0;}if(!port){e=EADDRINUSE;break;}}clients[i].port=port;addr_for(&m.addr,p,port);write_state();break;}case M_IFACE:m.dev[15]=0;e=configure(&m);break;case M_ROUTE:e=route_set(&m);break;case M_AUTO:/* explicit configuration only */if(m.net)e=EOPNOTSUPP;break;case M_CFG:break;default:e=EINVAL;break;}m.op=M_REPLY;m.status=e;m.len=0;if(emit(clients[i].fd,&m)<0)drop_client(i);} +static void command(int i){struct msg m;ssize_t n=recv(clients[i].fd,&m,sizeof m,MSG_DONTWAIT|MSG_TRUNC);if(n<=0){if(n==0||(errno!=EAGAIN&&errno!=EINTR))drop_client(i);return;}if(n<(ssize_t)MSG_HEAD||n>(ssize_t)sizeof m||m.magic!=IPC_MAGIC||m.len>IPX_MAX||(size_t)n!=MSG_HEAD+m.len){drop_client(i);return;}int e=0;struct iface *p=primary();switch(m.op){case M_SEND:outbound(i,&m);return;case M_BIND:{if(clients[i].port){e=EINVAL;break;}if(!p){e=EADDRNOTAVAIL;break;}reap();uint16_t port=ntohs(m.addr.sipx_port);if(port&&(port_owner(port)>=0||gw_reserved(port))){e=EADDRINUSE;break;}if(!port){for(unsigned j=0;j<0xbfff;j++){port=nextport++;if(nextport<0x4000||nextport==0xffff)nextport=0x4000;if(port_owner(port)<0&&!gw_reserved(port))break;port=0;}if(!port){e=EADDRINUSE;break;}}clients[i].port=port;addr_for(&m.addr,p,port);write_state();break;}case M_IFACE:m.dev[15]=0;e=configure(&m);break;case M_ROUTE:e=route_set(&m);break;case M_AUTO:/* explicit configuration only */if(m.net)e=EOPNOTSUPP;break;case M_CFG:break;default:e=EINVAL;break;}m.op=M_REPLY;m.status=e;m.len=0;if(emit(clients[i].fd,&m)<0)drop_client(i);} static void capture(struct iface *in){if(!in->pc)return;for(int j=0;j<64;j++){struct pcap_pkthdr *h;const unsigned char *b;int r=pc.next_ex(in->pc,&h,&b);if(r==0)break;if(r<0){fprintf(stderr,"pcap read %s: %s\n",in->dev,pc.geterr(in->pc));stop=1;break;}inbound(in,b,h->caplen);}} static void on_signal(int s){(void)s;stop=1;} -int main(int argc,char **argv){for(int i=1;i=0){f[count]=(struct pollfd){clients[i].fd,POLLIN,0};type[count]=1;index[count++]=i;}for(int i=0;i=0){f[count]=(struct pollfd){ifs[i].fd,POLLIN,0};type[count]=2;index[count++]=i;}int r=poll(f,count,20);if(r<0){if(errno==EINTR)continue;perror("poll");break;} +int main(int argc,char **argv){for(int i=1;i=0){f[count]=(struct pollfd){clients[i].fd,POLLIN,0};type[count]=1;index[count++]=i;}for(int i=0;i=0){f[count]=(struct pollfd){ifs[i].fd,POLLIN,0};type[count]=2;index[count++]=i;}int r=poll(f,count,20);if(r<0){if(errno==EINTR)continue;perror("poll");break;} /* Process capture before commands which may close/reopen interfaces. */for(int k=1;k=0)close(clients[i].fd); for(int i=0;i +/* DHCP server with permanent per-MAC reservations. No dynamic pool, no relay. + * Return 0 for other traffic, -1 for consumed/no reply, >0 reply length. */ +static uint16_t checksum(const uint8_t*p,size_t n){unsigned s=0;for(size_t i=0;i>16)s=(s&65535)+(s>>16);return (uint16_t)~s;} +static void opt(uint8_t **p,uint8_t k,const void*v,unsigned n){*(*p)++=k;*(*p)++=n;memcpy(*p,v,n);*p+=n;} +int gw_dhcp(const struct gw_config*c,const struct gw_peer*q,const uint8_t mac[6],const uint8_t*f,size_t n,uint8_t out[600]){ + if(n<42||get16(f+12)!=0x0800||(f[14]>>4)!=4)return 0; + unsigned ihl=(f[14]&15)*4;if(ihl<20||n<14+ihl+8||f[23]!=17)return 0; + const uint8_t*u=f+14+ihl;if(get16(u)!=68||get16(u+2)!=67)return 0; + unsigned total=get16(f+16),ul=get16(u+4);if((get16(f+20)&0x3fff)||totaln-14||ul!=total-ihl||ul<248)return -1; + const uint8_t*b=u+8;size_t bn=ul-8; + if(memcmp(f+6,q->mac,6)||(!isbc(f)&&memcmp(f,mac,6))||b[0]!=1||b[1]!=1||b[2]!=6||b[3]||memcmp(b+28,q->mac,6)||get32(b+24)||get32(b+236)!=0x63825363)return -1; + uint32_t src,dst,ci;memcpy(&src,f+26,4);memcpy(&dst,f+30,4);memcpy(&ci,b+12,4); + if((src&&src!=q->ip)||(ci&&ci!=q->ip)||(dst!=UINT32_MAX&&dst!=c->ip))return -1; + int type=0,ended=0;uint32_t requested=0,server=0; + for(size_t i=240;i=bn)return -1;unsigned len=b[i++];if(len>bn-i)return -1;if(k==53){if(len!=1||type)return -1;type=b[i];}else if(k==50){if(len!=4)return -1;memcpy(&requested,b+i,4);}else if(k==54){if(len!=4)return -1;memcpy(&server,b+i,4);}i+=len;} + if(!ended||(server&&server!=c->ip))return -1; + uint8_t answer;if(type==1)answer=2;else if(type==3){uint32_t want=requested?requested:ci;if(!want)return -1;answer=want==q->ip?5:6;}else return -1; + memset(out,0,600);memset(out,255,6);memcpy(out+6,mac,6);put16(out+12,0x0800); + uint8_t *ip=out+14,*udp=ip+20,*r=udp+8;ip[0]=0x45;ip[8]=64;ip[9]=17;memcpy(ip+12,&c->ip,4);memset(ip+16,255,4);put16(udp,67);put16(udp+2,68); + if(ci&&answer==5&&!(get16(b+10)&0x8000)){memcpy(out,q->mac,6);memcpy(ip+16,&ci,4);} + r[0]=2;r[1]=1;r[2]=6;memcpy(r+4,b+4,4);memcpy(r+10,b+10,2);if(answer!=6)memcpy(r+16,&q->ip,4);memcpy(r+28,q->mac,6);put32(r+236,0x63825363); + uint8_t*p=r+240;opt(&p,53,&answer,1);opt(&p,54,&c->ip,4); + if(answer!=6){uint32_t lease=htonl(86400),mask=htonl(0xffffff00);opt(&p,51,&lease,4);opt(&p,1,&mask,4);opt(&p,3,&c->ip,4);opt(&p,6,&c->dns,4);} + *p++=255;size_t payload=p-r;if(payload<300)payload=300;put16(udp+4,payload+8);put16(ip+2,payload+28);put16(ip+10,checksum(ip,20));return (int)(payload+42); +} diff --git a/src/gateway.c b/src/gateway.c new file mode 100644 index 0000000..8b20f04 --- /dev/null +++ b/src/gateway.c @@ -0,0 +1,47 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#define _GNU_SOURCE +#include "gateway.h" +#include "ipxpkt.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define GW_HELPER "/usr/local/libexec/mars-ipxpkt-net" +static struct gw_config cfg; +static struct pkt_rx rx; +static int tap=-1, firewall; +static uint8_t gateway_mac[6]; +static uint16_t seq; +static unsigned long frames_in,frames_out,denied,fragments; +static char status[256]="Disabled"; +static time_t last_seen[GW_MAX]; +static struct {uint8_t mac[6]; time_t seen;} observed[GW_MAX]; +static unsigned long dhcp_replies; +static int send_frame(const struct gw_peer*,const uint8_t*,size_t,gw_tx); +static time_t monotonic(void); +static void observe(const uint8_t mac[6]){time_t now=monotonic();int oldest=0;for(int i=0;i300)continue;char mac[13];for(int j=0;j<6;j++)snprintf(mac+j*2,3,"%02X",observed[i].mac[j]);json_object*o=json_object_new_object();json_object_object_add(o,"mac",json_object_new_string(mac));char net[16];snprintf(net,sizeof net,"0x%X",ntohl(cfg.net));json_object_object_add(o,"network",json_object_new_string(net));json_object_object_add(o,"age",json_object_new_int64(now-observed[i].seen));json_object_array_add(a,o);}char tmp[]=GW_DISCOVERY ".tmp";FILE*f=fopen(tmp,"w");if(f){fputs(json_object_to_json_string_ext(a,JSON_C_TO_STRING_PLAIN),f);if(!fclose(f))rename(tmp,GW_DISCOVERY);else unlink(tmp);}json_object_put(a);} + +static time_t monotonic(void){struct timespec t;clock_gettime(CLOCK_MONOTONIC,&t);return t.tv_sec;} +static void set_status(const char*s){snprintf(status,sizeof status,"%s",s);fprintf(stderr,"IPXPKT: %s\n",s);} +static int run_helper(const char*action){char ip[INET_ADDRSTRLEN],dns[INET_ADDRSTRLEN],mac[18];inet_ntop(AF_INET,&cfg.ip,ip,sizeof ip);inet_ntop(AF_INET,&cfg.dns,dns,sizeof dns);snprintf(mac,sizeof mac,"%02x:%02x:%02x:%02x:%02x:%02x",gateway_mac[0],gateway_mac[1],gateway_mac[2],gateway_mac[3],gateway_mac[4],gateway_mac[5]);pid_t p=fork();if(p==0){execl(GW_HELPER,GW_HELPER,action,cfg.uplink,ip,dns,mac,cfg.web?"1":"0",cfg.ping?"1":"0",(char*)NULL);_exit(127);}if(p<0)return -1;int st;while(waitpid(p,&st,0)<0){if(errno!=EINTR)return -1;}return WIFEXITED(st)&&WEXITSTATUS(st)==0?0:-1;} +void gw_init(void){memset(&cfg,0,sizeof cfg);unlink(GW_STATUS);unlink(GW_DISCOVERY);int f=open(GW_CONFIG,O_RDONLY|O_CLOEXEC|O_NOFOLLOW);if(f<0){if(errno!=ENOENT)set_status("Configuration unreadable; gateway disabled");return;}struct stat st;char buf[16385];if(fstat(f,&st)||!S_ISREG(st.st_mode)||st.st_uid!=0||(st.st_mode&022)||st.st_size<1||st.st_size>16384){close(f);set_status("Unsafe gateway configuration; disabled");return;}size_t used=0;while(used=0)return;if(!strcmp(dev,GW_TAP)||!if_nametoindex(cfg.uplink)||if_nametoindex(GW_TAP)){set_status("Invalid uplink or marsipx0 already exists");return;}for(unsigned i=0;i=0){close(tap);tap=-1;}if(firewall){if(run_helper("down"))set_status("Firewall cleanup failed; inspect nft table");else set_status(cfg.enabled?"Stopped":"Disabled");firewall=0;}} +void gw_detach(uint32_t net){if(net==cfg.net&&tap>=0)gw_close();} +int gw_reserved(uint16_t port){return cfg.enabled&&(port==PKT_TRAIL||port==PKT_PLAIN);} +void gw_input(uint32_t net,const uint8_t outer_src[6],const uint8_t outer_dst[6],const struct sockaddr_ipx*src,const struct sockaddr_ipx*dst,const uint8_t*p,size_t n,gw_tx send){uint16_t port=ntohs(dst->sipx_port);if(tap<0||net!=cfg.net||src->sipx_network!=net||src->sipx_port!=dst->sipx_port||memcmp(src->sipx_node,outer_src,6)||(!isbc(dst->sipx_node)&&memcmp(dst->sipx_node,gateway_mac,6))||(!isbc(outer_dst)&&memcmp(outer_dst,gateway_mac,6))||(dst->sipx_network!=net&&!(dst->sipx_network==UINT32_MAX&&isbc(dst->sipx_node)))){denied++;return;}unsigned i;for(i=0;isipx_node,6))break;uint8_t frame[PKT_FRAME];int len=pkt_receive(&rx,net,src->sipx_node,port,p,n,monotonic(),frame);fragments++;if(len<0){denied++;return;}if(!len)return;if(memcmp(frame+6,src->sipx_node,6)||(src->sipx_node[0]&1)){denied++;return;}observe(src->sipx_node);if(i==cfg.count){denied++;return;}uint8_t reply[600];int dh=gw_dhcp(&cfg,&cfg.peers[i],gateway_mac,frame,len,reply);if(dh){if(dh>0){cfg.peers[i].port=port;last_seen[i]=time(NULL);if(!send_frame(&cfg.peers[i],reply,dh,send))dhcp_replies++;else denied++;}return;}if(!gw_frame_allowed(&cfg,&cfg.peers[i],gateway_mac,frame,len)){denied++;return;}cfg.peers[i].port=port;last_seen[i]=time(NULL);if(write(tap,frame,len)!=len){denied++;return;}frames_in++;} +struct tx_ctx {const struct gw_peer*peer;gw_tx send;}; +static int send_fragment(void*ptr,const uint8_t*p,size_t n){struct tx_ctx*c=ptr;struct sockaddr_ipx src={0},dst={0};src.sipx_family=dst.sipx_family=AF_IPX;src.sipx_network=dst.sipx_network=cfg.net;src.sipx_port=dst.sipx_port=htons(c->peer->port);src.sipx_type=dst.sipx_type=4;memcpy(src.sipx_node,gateway_mac,6);memcpy(dst.sipx_node,c->peer->mac,6);uint8_t packet[576];int len=ipx_make(packet,sizeof packet,&src,&dst,p,n);return len<0?-1:c->send(cfg.net,dst.sipx_node,packet,len);} +static int send_frame(const struct gw_peer*q,const uint8_t*f,size_t n,gw_tx send){struct tx_ctx c={q,send};return pkt_send(q->port,++seq,f,n,send_fragment,&c);} +void gw_drain(gw_tx send){if(tap<0)return;for(int k=0;k<64;k++){uint8_t f[2048];ssize_t n=read(tap,f,sizeof f);if(n<0&&(errno==EAGAIN||errno==EWOULDBLOCK||errno==EINTR))return;if(n<=0){gw_close();set_status("TAP read failed; gateway stopped");return;}if(n<14||n>PKT_FRAME){denied++;continue;}uint16_t type=get16(f+12);if(type!=0x0800&&type!=0x0806)continue;for(unsigned i=0;iport)continue;int target=!memcmp(f,q->mac,6);if(type==0x0800&&(n<34||memcmp(f+30,&q->ip,4)))target=0;if(type==0x0806&&n>=42&&isbc(f)&&!memcmp(f+38,&q->ip,4))target=1;if(!target)continue;struct tx_ctx c={q,send};if(pkt_send(q->port,++seq,f,n,send_fragment,&c))denied++;else frames_out++;}}} +void gw_snapshot(void){discovery_snapshot();char temp[]=GW_STATUS ".tmp";FILE*f=fopen(temp,"w");if(!f)return;fprintf(f,"%s\nTAP: %s\nRX frames: %lu\nTX frames: %lu\nRX fragments: %lu\nRejected/dropped: %lu\n",status,tap>=0?GW_TAP:"-",frames_in,frames_out,fragments,denied);fprintf(f,"DHCP replies: %lu\n",dhcp_replies);for(unsigned i=0;i +#define GW_CONFIG "/usr/local/etc/mars_nwe/ipxpkt.json" +#define GW_STATUS IPC_DIR "/gateway" +#define GW_DISCOVERY IPC_DIR "/gateway-peers.json" +#define GW_TAP "marsipx0" +#define GW_MAX 64 +struct gw_peer {uint8_t mac[6]; uint32_t ip; uint16_t port;}; +struct gw_config {int enabled; uint32_t net,ip,dns; char uplink[16]; int web,ping; unsigned count; struct gw_peer peers[GW_MAX];}; +int gw_public_ip(uint32_t); +json_object *gw_default(void); +int gw_parse(json_object*,struct gw_config*,char*,size_t); +/* Data plane policy; valid Ethernet IPv4 or ARP from an assigned client only. */ +int gw_dhcp(const struct gw_config*,const struct gw_peer*,const uint8_t[6],const uint8_t*,size_t,uint8_t[600]); +int gw_frame_allowed(const struct gw_config*,const struct gw_peer*,const uint8_t[6],const uint8_t*,size_t); +void gw_init(void); +void gw_attach(uint32_t,const char*,const uint8_t[6]); +void gw_detach(uint32_t); +void gw_close(void); +void gw_snapshot(void); +int gw_reserved(uint16_t); +typedef int (*gw_tx)(uint32_t,const uint8_t[6],const uint8_t*,size_t); +void gw_input(uint32_t,const uint8_t[6],const uint8_t[6],const struct sockaddr_ipx*,const struct sockaddr_ipx*,const uint8_t*,size_t,gw_tx); +void gw_drain(gw_tx); +#endif diff --git a/src/gateway_config.c b/src/gateway_config.c new file mode 100644 index 0000000..86e277b --- /dev/null +++ b/src/gateway_config.c @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#include "gateway.h" +#include +#include +#include +#include +static json_object *field(json_object*o,const char*k){json_object*v=NULL;return o&&json_object_object_get_ex(o,k,&v)?v:NULL;} +static const char *str(json_object*o,const char*k){json_object*v=field(o,k);const char*s=json_object_is_type(v,json_type_string)?json_object_get_string(v):NULL;return s&&strlen(s)==(size_t)json_object_get_string_len(v)?s:NULL;} +static int boolean(json_object*o,const char*k,int*out){json_object*v=field(o,k);if(!json_object_is_type(v,json_type_boolean))return -1;*out=json_object_get_boolean(v);return 0;} +static int fail(char*e,size_t n,const char*s){snprintf(e,n,"%s",s);return -1;} +static int mac_parse(const char*s,uint8_t*p){if(!s||strlen(s)!=12)return -1;for(int i=0;i<6;i++){if(!isxdigit((unsigned char)s[2*i])||!isxdigit((unsigned char)s[2*i+1]))return -1;char a[3]={s[2*i],s[2*i+1],0};p[i]=strtoul(a,NULL,16);}return (p[0]&1)||iszero(p)?-1:0;} +static int private24(uint32_t ip){uint32_t h=ntohl(ip);return (h>>24)==10||(h>>20)==0xac1||(h>>16)==0xc0a8;} +int gw_public_ip(uint32_t ip){uint32_t h=ntohl(ip);return (h>>24)>0&&(h>>24)<224&&(h>>24)!=127&&!private24(ip)&&(h>>16)!=0xa9fe&&(h>>22)!=0x191&&(h>>8)!=0xc00000&&(h>>8)!=0xc00002&&(h&0xfffe0000u)!=0xc6120000u&&(h>>8)!=0xc63364&&(h>>8)!=0xcb0071&&h!=0xffffffff;} +json_object *gw_default(void){return json_tokener_parse("{\"enabled\":false,\"network\":\"0x101\",\"gateway\":\"10.250.0.1\",\"dns\":\"1.1.1.1\",\"uplink\":\"\",\"web\":true,\"ping\":true,\"clients\":[]}");} +int gw_parse(json_object*o,struct gw_config*c,char*e,size_t n){memset(c,0,sizeof *c);if(!json_object_is_type(o,json_type_object)||boolean(o,"enabled",&c->enabled)||boolean(o,"web",&c->web)||boolean(o,"ping",&c->ping))return fail(e,n,"Gateway: Boolesche Felder fehlen.");const char*net=str(o,"network"),*up=str(o,"uplink"),*ip=str(o,"gateway"),*dns=str(o,"dns");if(!net||strlen(net)<3||strlen(net)>10||net[0]!='0'||(net[1]!='x'&&net[1]!='X')||strspn(net+2,"0123456789abcdefABCDEF")!=strlen(net+2))return fail(e,n,"Externe IPX-Netznummer in Hex (0x...).");unsigned long v=strtoul(net+2,NULL,16);if(!v||v>=0xfffffffful)return fail(e,n,"IPX-Netznummer ungueltig.");c->net=htonl(v);if(!up||strlen(up)>=sizeof c->uplink||strspn(up,"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-")!=strlen(up)||!strcmp(up,"lo")||!strcmp(up,GW_TAP)||(c->enabled&&(!*up||up[0]=='-')))return fail(e,n,"Gueltige Uplink-Schnittstelle waehlen.");strcpy(c->uplink,up);if(!ip||inet_pton(AF_INET,ip,&c->ip)!=1||!private24(c->ip)||(ntohl(c->ip)&255)!=1)return fail(e,n,"Gateway muss private IPv4 .1 in einem /24 sein.");if(!dns||inet_pton(AF_INET,dns,&c->dns)!=1||!gw_public_ip(c->dns))return fail(e,n,"Oeffentlichen IPv4-DNS angeben.");json_object*a=field(o,"clients");if(!json_object_is_type(a,json_type_array)||json_object_array_length(a)>GW_MAX)return fail(e,n,"Clientliste fehlt oder zu lang (max. 64).");c->count=json_object_array_length(a);/* Empty allowlist is valid: discovery only, no forwarding. */for(unsigned i=0;icount;i++){json_object*p=json_object_array_get_idx(a,i);struct gw_peer*q=&c->peers[i];const char*addr=str(p,"ip");if(mac_parse(str(p,"mac"),q->mac)||!addr||inet_pton(AF_INET,addr,&q->ip)!=1||(ntohl(q->ip)&0xffffff00)!=(ntohl(c->ip)&0xffffff00)||(ntohl(q->ip)&255)<2||(ntohl(q->ip)&255)==255)return fail(e,n,"Client: 12 Hex-MAC und freie IP .2-.254 im Gateway-Netz.");for(unsigned j=0;jip==c->peers[j].ip||!memcmp(q->mac,c->peers[j].mac,6))return fail(e,n,"Doppelte Client-IP oder MAC.");}return 0;} +int gw_frame_allowed(const struct gw_config*c,const struct gw_peer*q,const uint8_t mac[6],const uint8_t*f,size_t n){if(n<14||n>1514||memcmp(f+6,q->mac,6))return 0;uint16_t type=get16(f+12);if(type==0x0800){if(memcmp(f,mac,6)||n<34||(f[14]>>4)!=4)return 0;unsigned ihl=(f[14]&15)*4;unsigned total=get16(f+16);return ihl>=20&&total>=ihl&&total<=n-14&&!memcmp(f+26,&q->ip,4);}if(type==0x0806){if((memcmp(f,mac,6)&&!isbc(f))||n<42||get16(f+14)!=1||get16(f+16)!=0x0800||f[18]!=6||f[19]!=4)return 0;unsigned op=get16(f+20);return (op==1||op==2)&&!memcmp(f+22,q->mac,6)&&!memcmp(f+28,&q->ip,4)&&!memcmp(f+38,&c->ip,4)&&(op==1||!memcmp(f+32,mac,6));}return 0;} diff --git a/src/ipxpkt.c b/src/ipxpkt.c new file mode 100644 index 0000000..bc99276 --- /dev/null +++ b/src/ipxpkt.c @@ -0,0 +1,22 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* Wire format independently implemented from Crynwr IPXPKT.ASM and + * ipxbox protocol reference: https://github.com/fragglet/ipxbox/tree/trunk/module/ipxpkt + * Shared by the Linux server and the legacy Win32 client; C89 compatible. */ +#include "ipxpkt.h" +#include +static int offset(uint16_t port){return port==PKT_TRAIL?32:port==PKT_PLAIN?0:-1;} +int pkt_receive(struct pkt_rx*r,uint32_t net,const uint8_t node[6],uint16_t port,const uint8_t*p,size_t n,time_t now,uint8_t out[PKT_FRAME]){ + int off=offset(port),i; unsigned num,total,bit;uint16_t id;size_t len;struct pkt_slot *s=NULL,*free_slot=NULL,*q;struct pkt_piece*f; + if(!r||!node||!p||!out||off<0||n<=(size_t)off+4||n>546)return -1; + p+=off;n-=off;num=p[0];total=p[1];id=(uint16_t)p[2]|((uint16_t)p[3]<<8);p+=4;n-=4; + if(!num||num>total||total>3)return -1; + for(i=0;islots[i];if(q->until<=now){if(!free_slot)free_slot=q;continue;}if(q->net==net&&q->port==port&&q->id==id&&!memcmp(q->node,node,6)){s=q;break;}} + if(!s){if(!free_slot)return -1;s=free_slot;memset(s,0,sizeof *s);s->net=net;s->port=port;s->id=id;s->total=(uint8_t)total;s->until=now+3;memcpy(s->node,node,6);} + if(s->total!=total)return -1; + f=&s->part[num-1];bit=1u<<(num-1);if(s->mask&bit)return f->len==n&&!memcmp(f->bytes,p,n)?0:-1; + memcpy(f->bytes,p,n);f->len=(uint16_t)n;s->mask=(uint8_t)(s->mask|bit); + if(s->mask!=((1u<part[i].len>PKT_FRAME){s->until=0;return -1;}memcpy(out+len,s->part[i].bytes,s->part[i].len);len+=s->part[i].len;} + s->until=0;return len>=14?(int)len:-1; +} +int pkt_send(uint16_t port,uint16_t id,const uint8_t*frame,size_t n,pkt_emit emit,void*ctx){int off=offset(port);size_t max,total,i,len;uint8_t p[546];if(!frame||!emit||off<0||n<14||n>PKT_FRAME)return -1;max=542-off;total=(n+max-1)/max;for(i=0;imax?max:n;p[off]=(uint8_t)(i+1);p[off+1]=(uint8_t)total;p[off+2]=(uint8_t)(id&255);p[off+3]=(uint8_t)(id>>8);memcpy(p+off+4,frame,len);if(emit(ctx,p,off+4+len))return -1;frame+=len;n-=len;}return 0;} diff --git a/src/ipxpkt.h b/src/ipxpkt.h new file mode 100644 index 0000000..0844205 --- /dev/null +++ b/src/ipxpkt.h @@ -0,0 +1,30 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef MARS_IPXPKT_H +#define MARS_IPXPKT_H +/* Visual C++ 6 (Windows 95 / NT4) has no stdint.h. */ +#if defined(_MSC_VER) && _MSC_VER < 1600 +typedef unsigned char uint8_t; +typedef unsigned short uint16_t; +typedef unsigned long uint32_t; +#else +#include +#endif +#include +#include +#ifdef __cplusplus +extern "C" { +#endif +#define PKT_TRAIL 0x6181 +#define PKT_PLAIN 0x6180 +#define PKT_FRAME 1514 +#define PKT_SLOTS 32 +struct pkt_piece { uint16_t len; uint8_t bytes[542]; }; +struct pkt_slot { uint8_t node[6], total, mask; uint32_t net; uint16_t port,id; time_t until; struct pkt_piece part[3]; }; +struct pkt_rx { struct pkt_slot slots[PKT_SLOTS]; }; +int pkt_receive(struct pkt_rx *,uint32_t,const uint8_t[6],uint16_t,const uint8_t*,size_t,time_t,uint8_t[PKT_FRAME]); +typedef int (*pkt_emit)(void*,const uint8_t*,size_t); +int pkt_send(uint16_t,uint16_t,const uint8_t*,size_t,pkt_emit,void*); +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/test_driver_ui.cjs b/tests/test_driver_ui.cjs new file mode 100644 index 0000000..5a57164 --- /dev/null +++ b/tests/test_driver_ui.cjs @@ -0,0 +1,25 @@ +// Optional UI test: npm install --prefix build/ui playwright; playwright install chromium +const {chromium}=require('../build/ui/node_modules/playwright'); +const fs=require('fs'),path=require('path'),assert=require('assert'); +(async()=>{ + const browser=await chromium.launch({args:['--no-sandbox']}); + const page=await browser.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message)); + let platforms=[],activated=false; + const state={defaultPassword:false,groups:Object.fromEntries(['1','2','3','4','5','12','13','17','21','45','200'].map(x=>[x,[]])),text:'',revision:'test',csrf:'test',validation:{errors:[]},devices:[],backups:[],path:'/test',services:true}; + await page.route('**/*',async route=>{const u=new URL(route.request().url()).pathname;let body; + if(u==='/api/state')body=state; + else if(u==='/api/status')body={'mars-nwe-pcap.service':'ActiveState=inactive','mars-pcapd.service':'ActiveState=inactive'}; + else if(u==='/api/drivers')body={platforms,map:activated?'MAP ROOT T:=SYS:PUBLIC/DRIVERS/TEST':''}; + else if(u==='/api/drivers/activate'){const data=route.request().postDataJSON();assert.equal(data.confirm,true);assert.deepEqual(data.platforms,['WIN95','WINXP']);platforms=data.platforms;activated=true;body={ok:true};} + else if(u==='/api/gateway')body={config:{enabled:false,network:'0x101',gateway:'10.250.0.1',dns:'1.1.1.1',uplink:'',clients:[]},revision:'r',status:'Disabled'}; + else {const file=path.join(__dirname,'../websetup',u==='/'?'index.html':u.slice(1));return route.fulfill({body:fs.readFileSync(file),contentType:u.endsWith('.js')?'text/javascript':u.endsWith('.css')?'text/css':'text/html'});} + return route.fulfill({json:body});}); + await page.goto('http://127.0.0.1:18889/'); + await page.locator('#gatewayOpen').click();await page.locator('#gwWinClients').click(); + await page.waitForFunction(()=>document.querySelector('#driverStatus').textContent.includes('Noch keine')); + assert.equal(await page.locator('a[href^="/drivers/"]:visible').count(),0); + await page.locator('[name=driverOS][value=WIN95]').check();await page.locator('[name=driverOS][value=WINXP]').check(); + await page.locator('#activateDrivers').click();await page.waitForFunction(()=>document.querySelector('#driverStatus').textContent.startsWith('MAP ROOT')); + assert.equal(await page.locator('a[href^="/drivers/"]:visible').count(),2);assert(activated);assert.deepEqual(errors,[]); + await page.screenshot({path:path.join(__dirname,'../build/driver-modal.png'),fullPage:true});await browser.close();console.log('PASS Chromium: OS selection, activation, filtered downloads, MAP instruction, modal'); +})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/tests/test_gateway.c b/tests/test_gateway.c new file mode 100644 index 0000000..70c0417 --- /dev/null +++ b/tests/test_gateway.c @@ -0,0 +1,11 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#include "gateway.h" +#include "ipxpkt.h" +#include +#include +#include +struct packets {size_t len[3];uint8_t data[3][546];int count;}; +static int store(void*ctx,const uint8_t*p,size_t n){struct packets*a=ctx;assert(a->count<3&&n<=546);a->len[a->count]=n;memcpy(a->data[a->count++],p,n);return 0;} +static void protocol(void){uint8_t frame[1514],out[1514],node[6]={2,1,2,3,4,5};for(size_t i=0;i +#include +#include +static void subnets(void){json_object*r=json_tokener_parse("[{\"dst\":\"default\"},{\"dst\":\"10.250.0.0/23\",\"dev\":\"cni0\"},{\"dst\":\"10.250.2.10\",\"dev\":\"vpn0\"},{\"dst\":\"192.168.1.0/24\"}]");assert(!ga_free(r,inet_addr("10.250.0.1")));assert(!ga_free(r,inet_addr("10.250.1.1")));assert(!ga_free(r,inet_addr("10.250.2.1")));assert(ga_choose(r)==inet_addr("10.250.3.1"));json_object_put(r);r=json_tokener_parse("[{\"dst\":\"10.250.0.0/24\",\"dev\":\"marsipx0\"},{\"dst\":\"10.250.0.1\",\"dev\":\"marsipx0\"}]");assert(ga_free(r,inet_addr("10.250.0.1")));json_object_put(r);assert(!ga_free(NULL,inet_addr("10.250.0.1")));} +static unsigned request(uint8_t*f,struct gw_peer*q,struct gw_config*c,int type,int wrong){memset(f,0,600);memset(f,255,6);memcpy(f+6,q->mac,6);put16(f+12,0x800);f[14]=0x45;f[23]=17;memset(f+30,255,4);put16(f+34,68);put16(f+36,67);uint8_t*b=f+42;b[0]=1;b[1]=1;b[2]=6;put32(b+4,123456);memcpy(b+28,q->mac,6);put32(b+236,0x63825363);uint8_t*p=b+240;*p++=53;*p++=1;*p++=type;if(type==3){*p++=50;*p++=4;uint32_t ip=wrong?inet_addr("10.250.0.19"):q->ip;memcpy(p,&ip,4);p+=4;*p++=54;*p++=4;memcpy(p,&c->ip,4);p+=4;}*p++=255;unsigned len=p-b;put16(f+16,len+28);put16(f+38,len+8);return len+42;} +static void dhcp(void){struct gw_config c={.ip=0,.dns=0};c.ip=inet_addr("10.250.0.1");c.dns=inet_addr("1.1.1.1");struct gw_peer q={.mac={2,1,2,3,4,5},.ip=0};q.ip=inet_addr("10.250.0.10");uint8_t mac[]={2,9,8,7,6,5},f[600],out[600];unsigned n=request(f,&q,&c,1,0);assert(gw_dhcp(&c,&q,mac,f,n,out)==342);assert(out[284]==2&&get32(out+46)==123456&&!memcmp(out+58,&q.ip,4));n=request(f,&q,&c,3,0);assert(gw_dhcp(&c,&q,mac,f,n,out)>0&&out[284]==5);n=request(f,&q,&c,3,1);assert(gw_dhcp(&c,&q,mac,f,n,out)>0&&out[284]==6&&get32(out+58)==0);f[70]^=1;assert(gw_dhcp(&c,&q,mac,f,n,out)==-1);n=request(f,&q,&c,1,0);f[n-1]=50;assert(gw_dhcp(&c,&q,mac,f,n,out)==-1);n=request(f,&q,&c,1,0);assert(gw_dhcp(&c,&q,mac,f,n-1,out)==-1);} +int main(void){subnets();dhcp();puts("PASS: overlapping routes, DHCP OFFER/ACK/NAK, malformed and spoofed packets");} diff --git a/tests/test_gateway_browser.py b/tests/test_gateway_browser.py new file mode 100644 index 0000000..0729166 --- /dev/null +++ b/tests/test_gateway_browser.py @@ -0,0 +1,26 @@ +"""Optional dev-only Chromium test with mock API; not a server dependency.""" +from pathlib import Path +import os +from playwright.sync_api import sync_playwright +root=Path(__file__).resolve().parents[1]/'websetup' +screen=Path(os.environ.get('MARS_GATEWAY_SCREENSHOT',str(root.parent/'build/gateway.png'))) +state=dict(defaultPassword=False,groups={k:[] for k in ['1','2','3','4','5','12','13','17','21','45','200']},text='',revision='a',csrf='b',validation={'errors':[]},devices=[{'name':'enp3s0','mac':'02:01:02:03:04:05','state':'up'},{'name':'enp4s0','mac':'02:01:02:03:04:06','state':'up'}],backups=[],path='/usr/local/etc/mars_nwe/nwserv.conf',services=True) +state['groups']['4']=['0x101 enp3s0 802.3 1','0x102 enp3s0 802.2 1'] +gw=dict(enabled=False,network='0x101',gateway='10.250.0.1',dns='1.1.1.1',uplink='',web=True,ping=True,clients=[]) +rev='r1'; actions=[] +def fixture(source,path,body): + global gw,rev + if path=='/api/state':return state + if path=='/api/status':return {'mars-nwe-pcap.service':'ActiveState=active','mars-pcapd.service':'ActiveState=active'} + if path=='/api/gateway': + if body: + assert body['revision']==rev and body['confirm'];gw=body['config'];rev='r2';actions.append('save');return {'ok':True} + return {'config':gw,'revision':rev,'status':'Disabled (simulierte API)'} + if path=='/api/service':assert body['action']=='restart' and body['revision']=='a';actions.append('restart');return {'ok':True} + raise AssertionError(path) +with sync_playwright() as p: + b=p.chromium.launch(executable_path='/usr/bin/chromium',args=['--no-sandbox']);page=b.new_page(viewport={'width':1280,'height':1050});errors=[];page.on('pageerror',lambda e:errors.append(str(e)));page.on('dialog',lambda d:d.accept());page.expose_binding('fixture',fixture);page.evaluate("window.fetch=async(path,opts)=>({ok:true,status:200,json:()=>window.fixture(path,opts?.body?JSON.parse(opts.body):null)})") + html=(root/'index.html').read_text().replace('','').replace('','');page.set_content(html);page.add_script_tag(content=(root/'app.js').read_text());page.wait_for_function("document.getElementById('serverStatus').textContent==='active'") + page.locator('#gatewayOpen').click();page.locator('#gwEnabled').check();page.locator('#gwNetwork').select_option('0x102');page.locator('#gwUplink').select_option('enp4s0');page.locator('#gwClients').fill('02:01:02:03:04:07 10.250.0.10');page.locator('#gwRestart').click();page.wait_for_function("document.getElementById('gwMessage').textContent.includes('zuerst speichern')");assert not actions + page.locator('#gatewayForm button[type=submit]').click();page.wait_for_function("document.getElementById('gwMessage').textContent.includes('Gespeichert')");assert gw['enabled'] and gw['network']=='0x102' and gw['clients']==[{'mac':'020102030407','ip':'10.250.0.10'}] and gw['uplink']=='enp4s0' + page.locator('#gwRestart').click();page.wait_for_function("document.getElementById('gwMessage').textContent.includes('Neustart angefordert')");assert actions==['save','restart'];page.locator('#gwRefresh').click();page.wait_for_function("!document.getElementById('gwRefresh').disabled");page.locator('#gatewayDialog').evaluate('(el)=>el.scrollTop=0');page.screenshot(path=str(screen));page.locator('#gatewayClose').click();assert not errors,errors;print('PASS: mock API Chromium Gateway modal, discovered interface selection, MAC/IP entries, save, dirty guard, restart, status');b.close() diff --git a/tests/test_legacy.c b/tests/test_legacy.c new file mode 100644 index 0000000..5de75f0 --- /dev/null +++ b/tests/test_legacy.c @@ -0,0 +1,13 @@ +#include "legacy_core.h" +#include +#include +#include +static struct legacy_core c; +int main(void){unsigned char mac[6]={2,1,2,3,4,5},f[MARS_FRAME_MAX]={0},out[MARS_FRAME_MAX];unsigned i; + assert(lc_valid_mac(mac));lc_init(&c,mac);memcpy(f+6,mac,6);f[12]=8;f[13]=6; + assert(lc_send(&c,f,60)<0);lc_link(&c,1);assert(!lc_send(&c,f,60));assert(lc_pop(&c,out,60)==60&&!memcmp(f,out,60));assert(lc_pop(&c,out,sizeof out)==0); + for(i=0;i "$MARS_CONF" +printf '%s\n' '{"enabled":true,"network":"0x101","gateway":"10.250.0.1"}' > "$MARS_GATEWAY_CONFIG" +printf '%s\n' 'Network Node_Address Primary Device Frame_Type' '00000101 020908070605 No eth0 802.2' > "$MARS_IPX_INTERFACES" +./publish-winclient.sh --config-only +for os in win95 win98 winme winnt40 win2000 winxp; do + f=$t/sys/public/clients/$os/gateway.ini + test -f "$f"; tr -d '\r' < "$f" | grep -qx 'network=00000101'; tr -d '\r' < "$f" | grep -qx 'server=020908070605'; tr -d '\r' < "$f" | grep -qx 'ip=10.250.0.1' +done +if ./publish-winclient.sh --config-only; then echo 'FAIL overwrite'; exit 1; fi +rm -r "$t/sys/public/clients" +mkdir "$t/binaries"; echo NOT-EXE > "$t/binaries/MARSNET.EXE" +if ./publish-winclient.sh "$t/binaries"; then echo 'FAIL invalid EXE'; exit 1; fi +[[ ! -e $t/sys/public/clients ]] +# Test fixture only; the MZ check is a format sanity check, NOT code authentication. +printf MZfixture > "$t/binaries/MARSNET.EXE" +printf MZfixture > "$t/binaries/MARSIPX.EXE" +if ./publish-winclient.sh "$t/binaries"; then echo 'FAIL incomplete native package'; exit 1; fi +printf MZfixture > "$t/binaries/MARSNDIS.SYS"; printf 'fixture\n' > "$t/binaries/MARSNDIS.INF" +./publish-winclient.sh "$t/binaries" +[[ -f $t/sys/public/clients/winxp/marsndis.sys && -f $t/sys/public/clients/win95/marsnet.exe && ! -e $t/sys/public/clients/win95/marsndis.sys ]] +echo 'PASS: publisher network config, six folders, no overwrite, reject invalid/incomplete input, target selection (fixtures only)' +rm -r "$t/sys/public/clients" +mkdir "$t/legacy"; printf MZfixture > "$t/legacy/MARSNET.EXE"; printf MZfixture > "$t/legacy/MARSNET3.SYS"; printf 'fixture\n' > "$t/legacy/MARSNET.INF" +if ./publish-winclient.sh "$t/legacy"; then echo 'FAIL preview gate'; exit 1; fi +MARS_ALLOW_PREVIEW=1 ./publish-winclient.sh "$t/legacy" +[[ -f $t/sys/public/clients/win95/marsnet3.sys && -f $t/sys/public/clients/winme/marsnet.inf && ! -e $t/sys/public/clients/winnt40/marsnet3.sys && ! -e $t/sys/public/clients/winxp/marsnet.exe ]] +echo 'PASS: legacy preview gate and Win9x target routing' diff --git a/tests/test_web.sh b/tests/test_web.sh index e2449d5..ef9c815 100755 --- a/tests/test_web.sh +++ b/tests/test_web.sh @@ -18,12 +18,17 @@ cat > "$cfg" <<'CONF' 99 PRESERVE CONF chmod 600 "$cfg" -start(){ ./build/mars_vme --config "$cfg" --www "$PWD/websetup" --bind 127.0.0.1 --port "$port" --no-services >"$d/log" 2>&1 & pid=$!; for i in $(seq 1 70); do if curl -fsS "$base/login" >/dev/null 2>&1 && kill -0 "$pid"; then return; fi; sleep .1; done; cat "$d/log" >&2; return 1; } +mkdir -p "$d/www/drivers" +cp websetup/* "$d/www/" +printf 'ZIP fixture bytes' > "$d/www/drivers/WIN95.zip" +printf '{"platforms":["WIN95"],"map":"test"}' > "$d/www/drivers/enabled.json" +start(){ ./build/mars_vme --config "$cfg" --www "$d/www" --bind 127.0.0.1 --port "$port" --no-services >"$d/log" 2>&1 & pid=$!; for i in $(seq 1 70); do if curl -fsS "$base/login" >/dev/null 2>&1 && kill -0 "$pid"; then return; fi; sleep .1; done; cat "$d/log" >&2; return 1; } get(){ curl -fsS -b "$d/cookie" "$base/$1"; } post(){ curl -fsS -b "$d/cookie" -c "$d/cookie" -H "Origin: $base" -H 'Content-Type: application/json' -H "X-Mars-CSRF: ${csrf:-}" -d "$2" "$base/$1"; } status(){ curl -sS -o "$d/response" -w '%{http_code}' "$@"; } start [[ $(status "$base/api/state") == 401 ]] +[[ $(status "$base/drivers/WIN95.zip") == 401 ]] [[ $(status -H 'Host: evil.example' "$base/login") == 403 ]] [[ $(status -H 'Content-Type: application/json' -d '{"user":"admin","password":"admin"}' "$base/api/login") == 403 ]] post api/login '{"user":"admin","password":"admin"}' | jq -e .ok >/dev/null @@ -34,6 +39,10 @@ post api/password '{"current":"admin","new":"NativeTestPassword123","repeat":"Na [[ $(status -b "$d/old-cookie" "$base/api/state") == 401 ]] post api/login '{"user":"admin","password":"NativeTestPassword123"}' | jq -e .ok >/dev/null s=$(get api/state); jq -e '(.defaultPassword|not) and (.text|contains("99 PRESERVE"))' <<<"$s" >/dev/null +get drivers/WIN95.zip > "$d/download.zip" +cmp "$d/download.zip" "$d/www/drivers/WIN95.zip" +[[ $(status -b "$d/cookie" "$base/drivers/WINXP.zip") == 404 ]] +get api/drivers | jq -e '.platforms==["WIN95"]' >/dev/null csrf=$(jq -r .csrf <<<"$s"); rev=$(jq -r .revision <<<"$s"); dev=$(jq -r '.devices[0].name // empty' <<<"$s") if [[ -n $dev ]]; then request=$(jq -nc --arg rev "$rev" --arg dev "$dev" '{revision:$rev,mode:"guided",groups:{"2":["NEW"],"4":[("0x101 "+$dev+" 802.3 1")]}}') diff --git a/tests/test_winclient.c b/tests/test_winclient.c new file mode 100644 index 0000000..5737a4c --- /dev/null +++ b/tests/test_winclient.c @@ -0,0 +1,16 @@ +#include "client_core.h" +#include "frame_queue.h" +#include "gateway.h" +#include +#include +#include +struct pieces {uint8_t p[3][546];size_t len[3];int count;}; +static int emit(void*v,const uint8_t*p,size_t n){struct pieces*q=v;assert(q->count<3&&n<=546);memcpy(q->p[q->count],p,n);q->len[q->count++]=n;return 0;} +static const uint8_t node[]={2,1,2,3,4,5},server[]={2,9,8,7,6,5}; +static void test(uint16_t port){struct client_core c;struct pkt_rx r={0};struct pieces p={0};uint8_t f[1514]={0},out[1514],gw[]={10,250,0,1};int rc=0;assert(!client_init(&c,0x101,node,server,port));client_probe(&c,gw,f);assert(!client_tx(&c,f,60,emit,&p));assert(pkt_receive(&r,0x101,node,port,p.p[0],p.len[0],1,out)==60&&!memcmp(f,out,60)); +memcpy(f,server,6);memcpy(f+6,node,6);f[12]=8;f[13]=0;f[14]=0x45;put16(f+16,1500);p.count=0;assert(!client_tx(&c,f,1514,emit,&p)&&p.count==3);for(int i=2;i>=0;i--)rc=pkt_receive(&r,0x101,node,port,p.p[i],p.len[i],2,out);assert(rc==1514&&!memcmp(f,out,1514));f[6]^=1;assert(client_tx(&c,f,1514,emit,&p)<0);f[6]^=1;f[12]=0x86;assert(client_tx(&c,f,1514,emit,&p)<0); +f[12]=8;memcpy(f,node,6);memcpy(f+6,server,6);p.count=0;assert(!pkt_send(port,77,f,1514,emit,&p));assert(client_rx(&c,0x102,server,port,p.p[0],p.len[0],3,out)<0);assert(client_rx(&c,0x101,node,port,p.p[0],p.len[0],3,out)<0);assert(client_rx(&c,0x101,server,port==PKT_PLAIN?PKT_TRAIL:PKT_PLAIN,p.p[0],p.len[0],3,out)<0);for(int i=2;i>=0;i--)rc=client_rx(&c,0x101,server,port,p.p[i],p.len[i],4,out);assert(rc==1514&&!memcmp(f,out,1514));assert(client_rx(&c,0x101,server,port,p.p[0],p.len[0],5,out)==0);assert(client_rx(&c,0x101,server,port,p.p[1],p.len[1],9,out)==0);assert(client_rx(&c,0x101,server,port,p.p[2],p.len[2],9,out)==0); +struct gw_config cfg={0};struct gw_peer peer={0};cfg.ip=inet_addr("10.250.0.1");cfg.dns=inet_addr("1.1.1.1");peer.ip=inet_addr("10.250.0.10");memcpy(peer.mac,node,6); +for(int type=1;type<=3;type+=2){memset(f,0,sizeof f);memset(f,255,6);memcpy(f+6,node,6);put16(f+12,0x800);f[14]=0x45;f[23]=17;memset(f+30,255,4);put16(f+34,68);put16(f+36,67);uint8_t*b=f+42,*o=b+240;b[0]=1;b[1]=1;b[2]=6;put32(b+4,123456);memcpy(b+28,node,6);put32(b+236,0x63825363);*o++=53;*o++=1;*o++=type;if(type==3){*o++=50;*o++=4;memcpy(o,&peer.ip,4);o+=4;*o++=54;*o++=4;memcpy(o,&cfg.ip,4);o+=4;}*o++=255;unsigned n=o-b;put16(f+16,n+28);put16(f+38,n+8);p.count=0;assert(!client_tx(&c,f,n+42,emit,&p));rc=pkt_receive(&r,0x101,node,port,p.p[0],p.len[0],10,out);assert(rc==(int)n+42);rc=gw_dhcp(&cfg,&peer,server,out,rc,f);assert(rc==342);p.count=0;assert(!pkt_send(port,90+type,f,rc,emit,&p));assert(client_rx(&c,0x101,server,port,p.p[0],p.len[0],11,out)==342);assert(out[284]==(type==1?2:5)&&!memcmp(out+58,&peer.ip,4));}} +static void queue(void){static struct mars_ring r;uint8_t f[1514]={0},out[1514];assert(!mars_ring_pop(&r,out,sizeof out));for(int i=0;i<64;i++){f[0]=i;assert(!mars_ring_push(&r,f,sizeof f));}assert(mars_ring_push(&r,f,60)<0&&mars_ring_pop(&r,out,20)<0);for(int i=0;i<32;i++)assert(mars_ring_pop(&r,out,sizeof out)==1514&&out[0]==i);for(int i=0;i<32;i++){f[0]=i+64;assert(!mars_ring_push(&r,f,60));}for(int i=32;i<96;i++)assert(mars_ring_pop(&r,out,sizeof out)==(i<64?1514:60)&&out[0]==i);mars_ring_clear(&r);assert(!r.count&&!r.head);} +int main(void){test(PKT_PLAIN);test(PKT_TRAIL);queue();puts("PASS: Windows client core + actual server codec/DHCP; peer validation, fragments, queue");} diff --git a/upstream/patched b/upstream/patched deleted file mode 160000 index ecde9c5..0000000 --- a/upstream/patched +++ /dev/null @@ -1 +0,0 @@ -Subproject commit ecde9c5a8a0dd1f3b60faeeee76cc6eda1273866 diff --git a/websetup/app.js b/websetup/app.js index decb25f..5149b23 100644 --- a/websetup/app.js +++ b/websetup/app.js @@ -131,3 +131,27 @@ $('aclLoad').onclick=()=>aclTask(async()=>{const params=aclParams();const r=awai $('aclRead').onclick=()=>aclSetMask(0x41);$('aclModify').onclick=()=>aclSetMask(0xdb); async function aclWrite(op){if(!aclDoc)return;if(!confirm('Direkte Trustee-Zuweisung ändern? Alle Clients müssen getrennt sein.'))return;await aclTask(async()=>{const r=await liveAPI(op,{...aclDoc.params,previous:aclDoc.mask,mask:aclMask()});aclRender(r.mask);$('aclError').textContent='Gespeichert. Effektive Rechte nach neuer Client-Anmeldung prüfen.';});} $('aclSave').onclick=()=>aclWrite('trustee-set');$('aclRemove').onclick=()=>aclWrite('trustee-remove'); + +// IPXPKT gateway: settings are separate from the NetWare configuration draft. +let gatewayRevision=null, gatewayDirty=false; +function gwOptions(select, entries, selected){select.replaceChildren();for(const [value,label] of entries)option(select,value,label);if(selected&&!entries.some(([v])=>v===selected))option(select,selected,selected+' (nicht in aktueller Konfiguration)');if(selected)select.value=selected;} +function gatewayTask(fn){if(busy)return;busy=true;updateControls();$('gwMessage').textContent='';Promise.resolve().then(fn).catch(e=>{$('gwMessage').textContent=e.message;notice(e.message,'error');}).finally(()=>{busy=false;updateControls();});} +function gwLoad(r){const c=r.config;gatewayRevision=r.revision;gatewayDirty=false;$('gwEnabled').checked=c.enabled;$('gwWeb').checked=c.web;$('gwPing').checked=c.ping;$('gwIP').value=c.gateway;$('gwDNS').value=c.dns;const nets=(state.groups['4']||[]).map(line=>{const [n,dev,frame]=line.trim().split(/\s+/);let v=Number(n);return ['0x'+v.toString(16),n+' · '+dev+' · '+frame];});const net='0x'+Number(c.network).toString(16);gwOptions($('gwNetwork'),nets,net);gwOptions($('gwUplink'),[['','Bitte wählen'],...state.devices.filter(d=>d.name!=='marsipx0').map(d=>[d.name,d.name+' · '+d.state])],c.uplink);$('gwClients').value=c.clients.map(p=>p.mac+' '+p.ip).join('\n');$('gwStatus').textContent=r.status;gwPeers(r.observed||[]);} +function openGateway(){if(!state||state.defaultPassword||!state.services){notice('Zuerst Standardkennwort ändern und Dienstmodus verwenden.','error');return;}gatewayTask(async()=>{const r=await api('/api/gateway');gwLoad(r);$('gwDetected').textContent='';$('gatewayDialog').showModal();if(r.configured===false){try{await gwDetect();}catch(e){$('gwDetected').textContent=e.message;}}});} +$('gatewayOpen').onclick=$('gatewayNav').onclick=openGateway; +$('gatewayForm').addEventListener('input',()=>{gatewayDirty=true;}); +$('gatewayClose').onclick=()=>{if(!busy&&(!gatewayDirty||confirm('Ungespeicherte Gateway-Änderungen verwerfen?'))) $('gatewayDialog').close();}; +$('gatewayDialog').addEventListener('cancel',e=>{if(busy||(gatewayDirty&&!confirm('Ungespeicherte Gateway-Änderungen verwerfen?')))e.preventDefault();}); +$('gwRefresh').onclick=$('gwScan').onclick=()=>gatewayTask(async()=>{const r=await api('/api/gateway');$('gwStatus').textContent=r.status;gwPeers(r.observed||[]);}); +$('gatewayForm').onsubmit=e=>{e.preventDefault();gatewayTask(async()=>{const clients=$('gwClients').value.split(/\r?\n/).filter(x=>x.trim()).map(x=>{const t=x.trim().split(/\s+/);if(t.length!==2)throw Error('Clientliste: MAC und IPv4 je Zeile.');return {mac:t[0].replace(/[:-]/g,'').toUpperCase(),ip:t[1]};});const config={enabled:$('gwEnabled').checked,network:$('gwNetwork').value,gateway:$('gwIP').value.trim(),dns:$('gwDNS').value.trim(),uplink:$('gwUplink').value,web:$('gwWeb').checked,ping:$('gwPing').checked,clients};if(!confirm('Gateway-Einstellungen speichern? Sie werden erst nach Neustart aktiv.'))return;await api('/api/gateway',{config,revision:gatewayRevision,confirm:true});gwLoad(await api('/api/gateway'));$('gwMessage').textContent='Gespeichert. NetWare neu starten, um die Änderungen anzuwenden.';});}; +$('gwRestart').onclick=()=>gatewayTask(async()=>{if(gatewayDirty||dirty)throw Error('Gateway- und NetWare-Konfigurationsentwürfe zuerst speichern oder verwerfen.');if(!confirm('NetWare neu starten? Aktive Verbindungen werden getrennt.'))return;await api('/api/service',{revision:state.revision,action:'restart',confirm:true});$('gwMessage').textContent='Neustart angefordert. Status nach einigen Sekunden aktualisieren.';}); + +// The detected network is a suggestion only; save explicitly after review. +async function gwDetect(){const r=await api('/api/gateway/detect');const prev=$('gwIP').value;if($('gwClients').value.trim()&&prev!==r.gateway)throw Error('Vorhandene Clientreservierungen nicht automatisch umadressieren.');$('gwIP').value=r.gateway;$('gwDNS').value=r.dns;$('gwNetwork').value='0x'+Number(r.network).toString(16);if(![...$('gwUplink').options].some(o=>o.value===r.uplink))option($('gwUplink'),r.uplink,r.uplink+' · erkannte Route');$('gwUplink').value=r.uplink;$('gwDetected').textContent=`LAN: ${r.localIP||'–'} / ${r.localMask||'–'} · Router ${r.localGateway||'direkt'} · ${r.dnsSource} · IPv4-Forwarding ${r.forwarding?'aktiv':'deaktiviert (Linux-Konsole)'}`;gatewayDirty=true;} +$('gwAuto').onclick=()=>gatewayTask(async()=>{if(gatewayDirty&&!confirm('Netzwerkparameter des Entwurfs durch neue Vorschläge ersetzen?'))return;await gwDetect();}); +function gwPeers(peers){const box=$('gwPeers');box.replaceChildren();if(!peers.length){const p=document.createElement('p');p.className='hint';p.textContent='Keine IPXPKT-Geräte in den letzten fünf Minuten erkannt.';box.append(p);return;}for(const p of peers){const line=document.createElement('div');line.className='actions';const name=document.createElement('span');name.textContent=p.mac+' · IPX '+p.network+' · '+p.age+' s';const b=document.createElement('button');b.type='button';b.textContent='Freigeben / IP reservieren';b.onclick=()=>gatewayTask(()=>{if(Number(p.network)!==Number($('gwNetwork').value))throw Error('Gerät gehört nicht zum ausgewählten IPX-Netz.');if(!/^[0-9a-f]{12}$/i.test(p.mac))throw Error('Ungültige Geräteadresse.');const rows=$('gwClients').value.trim().split(/\r?\n/).filter(Boolean).map(x=>x.trim().split(/\s+/));if(rows.some(x=>x[0].replace(/[:-]/g,'').toUpperCase()===p.mac.toUpperCase()))throw Error('Gerät bereits reserviert.');if(rows.length>=64)throw Error('Maximal 64 Geräte.');const m=$('gwIP').value.trim().match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.)1$/);if(!m)throw Error('Zuerst gültiges virtuelles /24 konfigurieren.');const used=new Set(rows.map(x=>x[1]));let address='';for(let i=10;i<=254;i++){const ip=m[1]+i;if(!used.has(ip)){address=ip;break;}}if(!address)throw Error('Keine freie Adresse.');$('gwClients').value+=($('gwClients').value.trim()?'\n':'')+p.mac+' '+address;gatewayDirty=true;$('gwMessage').textContent='Reservierung '+address+' im Entwurf. Speichern und anwenden.';});line.append(name,b);box.append(line);}} + +async function driverState(){const d=await api('/api/drivers');document.querySelectorAll('[name=driverOS]').forEach(el=>el.checked=d.platforms.includes(el.value));document.querySelectorAll('a[href^="/drivers/"]').forEach(el=>{el.hidden=!d.platforms.some(os=>el.getAttribute('href')==='/drivers/'+os+'.zip');});$('driverStatus').textContent=d.map||'Noch keine Treiber freigegeben.';} +$('gwWinClients').onclick=()=>{ $('winClientDialog').showModal();driverState().catch(e=>$('driverStatus').textContent=e.message);}; +$('activateDrivers').onclick=async()=>{const b=$('activateDrivers');b.disabled=true;try{const platforms=Array.from(document.querySelectorAll('[name=driverOS]:checked'),el=>el.value);if(!platforms.length)throw Error('Mindestens ein Betriebssystem wählen.');await api('/api/drivers/activate',{confirm:true,platforms});await driverState();}catch(e){$('driverStatus').textContent=e.message;}finally{b.disabled=false;}}; +$('winClientClose').onclick=()=> $('winClientDialog').close(); diff --git a/websetup/index.html b/websetup/index.html index dd9d636..27d55bd 100644 --- a/websetup/index.html +++ b/websetup/index.html @@ -1,10 +1,10 @@ MARS NWE · Setup
MARS NWEPCAP / SERVER ADMINISTRATION
● Administrator
-
+

ERSTE SCHRITTE

Server einrichten

Konfigurieren Sie MARS NWE in wenigen Schritten. Bestehende Einstellungen außerhalb der gewählten Abschnitte bleiben erhalten.

Konfiguration–

Ethernet-Interfaces–

Auf dem Linux-Host erkannt

Dienste–

–

-
Einrichtungsreihenfolge & Sicherheit

Einrichtungsreihenfolge

  1. Ein separates Retro-LAN und eine Ethernet-Schnittstelle vorbereiten.
  2. Servername, interne Netznummer und mindestens einen externen Frame konfigurieren.
  3. SYS-Volume und gegebenenfalls weitere Datenvolumes einrichten.
  4. SUPERVISOR-Zuordnung und Initialpasswort prüfen.
  5. Änderungen validieren, Vorschau kontrollieren und speichern.
  6. Server starten, SAP-Erkennung und Dateioperationen am Client testen.
Historische NetWare-Dienste sind nicht für ungeschützte Netze geeignet. Diese Oberfläche hat Administratorrechte. Nur in einem vertrauenswürdigen Administrationsnetz freigeben, niemals im Internet.
+
Einrichtungsreihenfolge & Sicherheit

Einrichtungsreihenfolge

  1. Ein separates Retro-LAN und eine Ethernet-Schnittstelle vorbereiten.
  2. Servername, interne Netznummer und mindestens einen externen Frame konfigurieren.
  3. SYS-Volume und gegebenenfalls weitere Datenvolumes einrichten.
  4. SUPERVISOR-Zuordnung und Initialpasswort prüfen.
  5. Änderungen validieren, Vorschau kontrollieren und speichern.
  6. Server starten, SAP-Erkennung und Dateioperationen am Client testen.
Historische NetWare-Dienste sind nicht für ungeschützte Netze geeignet. Diese Oberfläche hat Administratorrechte. Nur in einem vertrauenswürdigen Administrationsnetz freigeben, niemals im Internet.
@@ -20,5 +20,9 @@
Freigaberechte

Originale Trustee-Rechte für einen Benutzer oder eine Gruppe. Alle NetWare-Verbindungen vor Änderungen trennen. Kein SYS, keine Home- oder Wechselvolumes.

Entfernen einer direkten Zuweisung ist kein explizites Verbot: vererbte Rechte und Unix-Rechte können weiterhin gelten.

Login-Skript

Aktion

-
MARS NWE · Administration
-
MARS_NWE-PCAP 0.4 · Setup Console · Nur für vertrauenswürdige Administratoren
+
Internet & Gateway

IPXPKT Gateway

TCP/IP über natives IPX. Kein zusätzlicher Web- oder Gateway-Dienst.

Nur im isolierten Retro-LAN aktivieren. IPXPKT ist unverschlüsselt und MAC/IP-Zuordnungen sind keine Benutzeranmeldung. Keine Verbindung zum Administrationsnetz herstellen.

Netzwerk

TAP: marsipx0 · IPv4 · feste DHCP-Reservierungen.

Internetdienste

DNS nur zum angegebenen Server. Private Zielnetze und der Linux-Host bleiben gesperrt. Bestehende Firewallregeln können den Zugriff weiter einschränken.

Freigegebene Geräte

Erkannte Geräte freigeben; eine freie IP wird vorgeschlagen. Nur freigegebene Geräte erhalten DHCP-Antworten. Je Zeile: 12-stellige MAC und feste IPv4-Adresse.

Gateway kann ohne freigegebene Clients gestartet werden. Die Freigabe bleibt manuell; Änderungen speichern und anwenden.

DOS-Clientsoftware

mTCP und IPXPKT zentral auf SYS:PUBLIC/MTCP bereitstellen. Der Administrator installiert die Originaldateien mit publish-mtcp.sh. Jeder Client nutzt eine eigene lokale Konfigurationsdatei.

MAP ROOT T:=SYS:PUBLIC/MTCP
+T:\SETUP.BAT
+T:\DHCP.EXE

MAP gehört ins NetWare-Login-Skript; SETUP.BAT und DHCP.EXE werden an der DOS-Eingabeaufforderung ausgeführt. Kein gemeinsam beschreibbares MTCP.CFG.

Windows-Clientsoftware

Windows 95, 98, ME, NT 4.0, 2000 und XP (Entwicklungsvorschau).

Laufzeitstatus

–

Linux muss IPv4-Forwarding explizit erlauben; siehe Gateway-Guide. Änderungen werden erst beim Neustart der NetWare-Kindprozesse aktiv.

Windows-Treiber und Installation
+

1. Lokal vorbereiten

Passendes ZIP herunterladen, komplett in einen lokalen Ordner entpacken. Vor Treibertests einen VM-Snapshot anlegen. IPX muss an der physischen Netzwerkkarte eingerichtet sein.

2. Windows 95 / 98 / ME

Im Paketordner INSTALL.BAT starten. Der enthaltene Original-WinPcap-3.1-Installer führt durch die Installation. Danach über „Neue Hardware / Datenträger“ MARSNET.INF auswählen. Keine automatische Änderung vorhandener Netzwerkbindungen.

3. Windows NT 4.0

INSTALL.BAT startet WinPcap. Vor der Adapterinstallation in OEMSETUP.INF unter [FileConstants] NetworkAddress auf die echte physische IPX-Node setzen: 12 Hexzeichen ohne Trennzeichen. Danach Netzwerk → Netzwerkkarten → Hinzufügen → Diskette. Details: NT4-INSTALL.txt.

4. Windows 2000 / XP

Hardware-Assistent → Netzwerkadapter → Datenträger → MARSNDIS.INF. Eigener NDIS5-Treiber; WinPcap ist für diesen Pfad nicht erforderlich. NetworkAddress auf die physische IPX-Node setzen.

5. Netzwerk und Start

TCP/IP an den virtuellen Adapter binden, IPX auf der physischen Karte belassen. Neustarten, Client im Gateway freigeben und DHCP erneuern. GATEWAY.INI muss die Werte des eigenen Servers enthalten – keine Beispielwerte übernehmen. Die Bridge-Befehle stehen in der beigelegten WINDOWS.md und LEGACY-BUILD.md.

+

Als NetWare-Laufwerk bereitstellen

Freigegebene Betriebssysteme

Nach dem Speichern eines SYS-Volumes mit PUBLIC-Verzeichnis aktiviert diese Schaltfläche Downloads und die Laufwerkskopie. Alternativ auf dem VME-Server im Repository ausführen:

sudo ./install-driver-packages.py

Das Skript installiert die Web-ZIPs und legt eine versionierte, nicht überschreibende Kopie auf SYS:PUBLIC/DRIVERS an. Es gibt den konkreten MAP-Befehl aus, zum Beispiel:

MAP ROOT T:=SYS:PUBLIC/DRIVERS/<Release-ID>

Den Betriebssystemordner von T: zunächst auf die lokale Festplatte kopieren. Auf NetWare nur Lese-/Dateiscan-Rechte vergeben, keine Schreibrechte. Vorhandene Volumes und Freigaben bleiben unverändert.

MARS NWE · Administration
+