From 7ba7f59b086cf7ba5bcefd8731d23379d8ebfdbd Mon Sep 17 00:00:00 2001 From: Chris Date: Thu, 26 Nov 2026 20:22:04 +0000 Subject: [PATCH] Initial release MARS_NWE-PCAP 0.4 - Native Administration, Print and Login Edition --- .gitignore | 48 +++++ COPYING | 338 ++++++++++++++++++++++++++++++ GUIDE.md | 110 ++++++++++ Makefile | 66 ++++++ README.md | 142 +++++++++++++ TEST-RESULTS.txt | 34 +++ build.sh | 31 +++ install.sh | 37 ++++ mars_vme.service | 20 ++ native/admin.c | 20 ++ native/admin.h | 8 + native/core.c | 65 ++++++ native/core.h | 30 +++ native/main.c | 73 +++++++ native/print_stdin.c | 9 + native/printing.c | 31 +++ native/rawprint.c | 12 ++ native/supervisor.c | 56 +++++ native/supervisor.h | 13 ++ nwserv-pcap.conf.example | 12 ++ patch-upstream.sh | 60 ++++++ rebuild.sh | 5 + run-ipc-test.sh | 10 + src/broker.c | 80 +++++++ src/pcap_dyn.c | 9 + src/pcap_dyn.h | 12 ++ src/shim.c | 28 +++ src/shim.h | 13 ++ src/wire.c | 29 +++ src/wire.h | 29 +++ tests/test_ipc.c | 19 ++ tests/test_native.c | 16 ++ tests/test_print.c | 4 + tests/test_raw.c | 12 ++ tests/test_scripts.c | 24 +++ tests/test_scripts_browser.py | 38 ++++ tests/test_supervisor.c | 20 ++ tests/test_trustee.c | 26 +++ tests/test_web.sh | 51 +++++ tests/test_wire.c | 8 + upstream-adapter/mars_acl.inc | 18 ++ upstream-adapter/mars_admin.inc | 51 +++++ upstream-adapter/mars_scripts.inc | 32 +++ upstream-adapter/mars_trustee.inc | 41 ++++ upstream/patched | 1 + upstream/source-revision.txt | 1 + websetup/app.js | 133 ++++++++++++ websetup/index.html | 24 +++ websetup/login.html | 1 + websetup/login.js | 3 + websetup/style.css | 13 ++ 51 files changed, 1966 insertions(+) create mode 100644 .gitignore create mode 100644 COPYING create mode 100644 GUIDE.md create mode 100644 Makefile create mode 100644 README.md create mode 100644 TEST-RESULTS.txt create mode 100755 build.sh create mode 100755 install.sh create mode 100644 mars_vme.service create mode 100644 native/admin.c create mode 100644 native/admin.h create mode 100644 native/core.c create mode 100644 native/core.h create mode 100644 native/main.c create mode 100644 native/print_stdin.c create mode 100644 native/printing.c create mode 100644 native/rawprint.c create mode 100644 native/supervisor.c create mode 100644 native/supervisor.h create mode 100644 nwserv-pcap.conf.example create mode 100755 patch-upstream.sh create mode 100755 rebuild.sh create mode 100755 run-ipc-test.sh create mode 100644 src/broker.c create mode 100644 src/pcap_dyn.c create mode 100644 src/pcap_dyn.h create mode 100644 src/shim.c create mode 100644 src/shim.h create mode 100644 src/wire.c create mode 100644 src/wire.h create mode 100644 tests/test_ipc.c create mode 100644 tests/test_native.c create mode 100644 tests/test_print.c create mode 100644 tests/test_raw.c create mode 100644 tests/test_scripts.c create mode 100644 tests/test_scripts_browser.py create mode 100644 tests/test_supervisor.c create mode 100644 tests/test_trustee.c create mode 100755 tests/test_web.sh create mode 100644 tests/test_wire.c create mode 100644 upstream-adapter/mars_acl.inc create mode 100644 upstream-adapter/mars_admin.inc create mode 100644 upstream-adapter/mars_scripts.inc create mode 100644 upstream-adapter/mars_trustee.inc create mode 160000 upstream/patched create mode 100644 upstream/source-revision.txt create mode 100644 websetup/app.js create mode 100644 websetup/index.html create mode 100644 websetup/login.html create mode 100644 websetup/login.js create mode 100644 websetup/style.css diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9d54087 --- /dev/null +++ b/.gitignore @@ -0,0 +1,48 @@ +cat > .gitignore <<'EOF' +# Build +/build/ +/upstream/build/ +/upstream/original/ +CMakeFiles/ +CMakeCache.txt +cmake_install.cmake +compile_commands.json + +# Compiler +*.o +*.a +*.so +*.so.* +*.exe +*.obj + +# Logs +*.log +*.pid +*.sock + +# Temporary files +*.tmp +*.bak +*.swp +*~ + +# Runtime +/run/ +/runtime/ +/backups/ + +# Credentials and local configuration +.env +*.pem +*.key +*.crt +auth.json +credentials.json +nwserv.conf + +# IDE +.idea/ +.vscode/ +.DS_Store +EOF diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..9efa6fb --- /dev/null +++ b/COPYING @@ -0,0 +1,338 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Moe Ghoul, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/GUIDE.md b/GUIDE.md new file mode 100644 index 0000000..d41476b --- /dev/null +++ b/GUIDE.md @@ -0,0 +1,110 @@ +# MARS_NWE-PCAP 0.4 – Einrichtungs- und Abnahmeguide + +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. + +## 1. Build und Installation + +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 +# Optional lokaler CUPS-Scheduler: +# sudo apt install cups +# Optional HTTP-Abnahmetest: +# sudo apt install curl jq + +tar -xzf mars-nwe-pcap-0.4.tar.gz +cd mars-nwe-pcap-0.4 +./build.sh +sudo ./install.sh +sudo systemctl enable --now mars_vme.service +``` + +`build.sh` bezieht den originalen MARS_NWE-Quellbaum von GitHub (davidrg/mars_nwe, Branch main, nicht auf Commit gepinnt). Bei einem lokal bereitgestellten Quellbaum stattdessen `MARS_SOURCE_DIR=/pfad/zum/original ./build.sh`. Git-Revision unter `upstream/source-revision.txt`. Bei einem Patch-Abbruch keine Anker blind entfernen; Fehler samt Revision dokumentieren. Bei einem Update vorhandene Konfiguration und Bindery vorab separat sichern; der Installer erhält nwserv.conf und Webkennwort, aber ein vollständiges Backup aller NetWare-Daten ist Aufgabe des Administrators. Python ist keine Build- oder Serverlaufzeitabhängigkeit; der optionale Browser-Entwicklertest benutzt Python/Playwright. + +Web: `http://SERVER-IP:8787`, initial `admin / admin`, Kennwort sofort ändern. Nur vertrauenswürdiges Management-LAN; HTTP ist unverschlüsselt, HTTPS optional wie in README. Serverstatus `systemctl status mars_vme`, Protokolle `journalctl -u mars_vme -f`. Kein weiterer MARS-Dienst. Die Web-Stop-/Restart-Aktionen betreffen die NetWare-Kindprozesse, nicht CivetWeb. + +## 2. Einrichtung im Dashboard + +1. Servername und IPX-Interface/Frame-Typ passend zum Client setzen. +2. SYS und Datenvolumes konfigurieren. Beispiel (Verzeichnisse vorher auf Linux anlegen): + +```ini +1 SYS /var/mars/sys/ kt 711 600 +1 DATA /var/mars/data/ kt 711 600 +``` + +`k`: Kleinschreibung auf Unix-Seite; `t`: originale Trustee-Funktion. Die Linux-Verzeichnisse für Datenfreigaben bewusst auswählen, kein `/`, keine sensiblen Systemverzeichnisse, keine Symlinks. Dateirechte sind nicht nur Trustee-Rechte, auch Unix- und Vererbungsrechte können gelten. Bei `t` allein können Unix-Rechte zusätzliche Zugriffe erlauben. Vor einer echten Freigabe mit Testbenutzer und Nichtmitglied testen. + +3. Supervisor und existierende Linux-Benutzer zuordnen. Änderungen an nwserv.conf prüfen, speichern und Server (Kindprozesse) neu starten. +4. Im Modal „Live-Bindery“ Benutzer/Gruppen anlegen, Gruppenzugehörigkeit bearbeiten. Ein Linux-Konto muss bereits existieren; kein root-Mapping für neue Benutzer. Supervisor/EVERYONE sind teilweise geschützt. Änderungen in der Bindery werden nicht in nwserv.conf zurückgeschrieben; alte Initialisierungseinträge können beim Neustart erneut wirksam werden. Persönliche Skripte benötigen die von MARS initialisierte MAIL-Struktur. Bei nicht verfügbarem Verzeichnis Zuordnung prüfen und Originalinitialisierung durchführen. + +## 3. Login-Skripte und automatische Laufwerke + +Dashboard → Login-Skripte → Geltungsbereich → Skripteditor öffnen. Alternativ direkt aus dem Benutzer-/Gruppenobjekt in der Bindery. Der Editor hat Zeilennummern, TAB-Einrückung, Laufwerksassistent, Begrüßungsvorlage, Grundprüfung, Bytezähler, Schutz vor Verlust ungespeicherter Änderungen und Revisionserkennung. + +- Alle Benutzer: `SYS:PUBLIC/NET$LOG.DAT`. +- Gruppe: ein vom Frontend verwalteter IF-MEMBER-OF-Block im Systemskript. NetWare 3.x hat keine NDS-Profilskripte. Mehrere Gruppen können verschiedene Blöcke erhalten. Die Reihenfolge ist die Reihenfolge im Systemskript; eine spätere Zuordnung desselben Laufwerks kann eine vorherige überschreiben. +- Benutzer: `SYS:MAIL//LOGIN`. Die Objekt-ID und Groß-/Kleinschreibung werden aus der laufenden Originalsoftware ermittelt. Benutzer muss für die Bearbeitung seines Skripts abgemeldet sein. + +Beispiel Systemskript: + +```text +MAP DISPLAY OFF +WRITE "Welcome to MARS" +MAP ROOT P:=SYS:PUBLIC +MAP ROOT S:=DATA:SHARED +IF MEMBER OF "PRODUCTION" THEN + MAP ROOT M:=DATA:PRODUCTION +END +IF MEMBER OF "IT" THEN + MAP ROOT I:=DATA:IT +END +MAP DISPLAY ON +``` + +Der Gruppeneditor zeigt nur die Anweisungen innerhalb des IF-Blocks. Der äußere Rahmen wird beim Speichern automatisch ergänzt. Verzweigungen, EXIT, INCLUDE und verschachtelte verwaltete Markierungen im Gruppeneditor werden abgewiesen; komplexe Logik direkt im Systemskript schreiben. Leeren und Speichern eines Gruppeneditors entfernt den verwalteten Block. Die Gruppe selbst wird nicht gelöscht. Ein EXIT im bestehenden Systemskript kann nachfolgende Blöcke überspringen: Reihenfolge prüfen. + +Beispiel persönliches Skript: `MAP ROOT U:=DATA:USERS\DOSUSER`. Die zugeordneten Verzeichnisse müssen existieren; Rechte getrennt vergeben. Der Editor speichert ASCII mit DOS-CRLF und maximal 4096 Bytes pro vollständigem Skript (bewusst gewählte konservative Grenze). Bestehende Skripte mit anderen Codepages oder größeren Inhalten werden nicht stillschweigend überschrieben. Änderungen sichern die alte Version privat unter `/var/lib/mars-vme/script-backups/`; Wiederherstellung derzeit manuell durch Administrator. Beim Überschreiben bleibt die Datei-Inode erhalten, um die historische Trustee-Metadatenzuordnung zu erhalten. Bei Stromausfall während des In-place-Schreibens Backup prüfen. Ein fehlendes Skript wird nur nach Bestätigung erzeugt. + +Die Skripte sind normale NetWare-Dateien im SYS-Volume, keine HTTP-Skripte. Ein passender Novell-Client muss bei der Anmeldung seine Login-Skripte ausführen (DOS LOGIN.EXE bzw. Client 32). Die Original-Clientprogramme sind nicht Bestandteil des Archivs. Wenn kein persönliches Skript existiert, kann das im Client eingebaute Default-Skript nach dem Systemskript ausgeführt werden und Zuordnungen überschreiben. Bei geeigneten NetWare-3.12-Clients ggf. `NO_DEFAULT` im Systemskript verwenden oder ein bewusst leeres persönliches Skript speichern. Nicht global EXIT einsetzen, wenn persönliche Skripte weiterlaufen sollen. Clientversion testen. Referenz: https://support.novell.com/docs/Tids/Solutions/10012087.html + +## 4. Freigaben und Zugriffsrechte + +Dashboard → Login-Skripte & Freigaben → Freigaberechte bearbeiten. Datenvolume mit Trustee-Flag, optionalen Ordner und Benutzer oder Gruppe auswählen. „Direkte Rechte laden“, dann Rechte einzeln auswählen oder Vorlage „Nur Lesen“ (R+F) bzw. „Ändern“ (R,W,C,E,F,M), bestätigen. „Zuweisung entfernen“ entfernt nur die direkte Trustee-Zuweisung, nicht geerbte Rechte oder Unix-Berechtigungen. Der Adapter ändert keine Linux-ACLs und erstellt keine Verzeichnisse. Kein SYS, keine Supervisor-Rechte, keine Home-, Pipe-, Readonly-, Remount- oder No-Inode-Volumes. Alle NetWare-Verbindungen müssen für eine Änderung getrennt sein. Konfigurationsänderungen seit Serverstart erfordern Neustart. Pfad muss root-eigene, nicht gruppen-/weltbeschreibbare Verzeichnisse ohne Symlinks verwenden; keine Filesystemgrenzen und keine Inodes/Devices außerhalb des historischen 32-Bit-Bereichs. Das ist bewusst konservativ und kann moderne Dateisysteme/benutzereigene Unterverzeichnisse ausschließen. Keine rekursive Änderung; die Original-Trustee-Routinen verwalten Vererbung und Cache-Seriennummern. Effektive Rechte mit tatsächlichen Clients prüfen. Die alten Originalquellen weisen selbst auf Einschränkungen der Trustee-Implementierung hin: https://github.com/davidrg/mars_nwe/blob/main/doc/TRUSTEES + +Beispiel: Gruppe PRODUCTION anlegen; DOSUSER hinzufügen; Ordner DATA:PRODUCTION als root vorbereiten; direkte Gruppenrechte setzen; Gruppenskript `MAP ROOT M:=DATA:PRODUCTION` speichern; als Gruppenmitglied und Nichtmitglied neu anmelden und sowohl Laufwerkszuordnung als auch direkte Zugriffsmöglichkeit prüfen. Das bloße Nicht-Mappen ist keine Zugriffssperre. + +## 5. Druck + +CUPS 2.x wird zur Laufzeit über `libcups.so.2` angebunden; kein eigener MARS-Druckdienst. Für einen lokalen Drucker `lpstat -p -d` prüfen. Für einen bestehenden entfernten CUPS-Scheduler z. B. systemd-Override: + +```ini +[Service] +Environment=CUPS_SERVER=192.168.1.50:631 +``` + +IP ersetzen, `systemctl daemon-reload` und Neustart des Dienstes. Der Scheduler muss die ausgewählten Aufträge erlauben. Keine interaktiven CUPS-Passwortdialoge im Adapter. Druckverwaltung → CUPS aktualisieren → Testseite → NetWare-Queue hinzufügen → Konfiguration prüfen und speichern → NetWare-Server neu starten. Beispiel Abschnitt 21: + +```ini +21 LASER SYS:/PRINT/LASER /usr/local/sbin/mars-print HP_LaserJet filtered +21 LABEL SYS:/PRINT/LABEL /usr/local/sbin/mars-print Zebra raw +21 RAW SYS:/PRINT/RAW /usr/local/sbin/mars-print 192.168.1.60 jetdirect +``` + +CUPS-Queue-Namen und RAW-IP anpassen; Spoolverzeichnisse müssen existieren. CUPS-Jobstatus und Historie stammen vom Scheduler; dieser kann Aufträge entfernen, CUPS-Benutzer ist nicht automatisch der historische NetWare-Benutzer. Druckerzuordnung über CUPS oder native RAW-TCP-Übertragung an TCP 9100, kein physischer Drucknachweis bei RAW. Historische Clientdruckdaten benötigen einen kompatiblen Druckpfad. Bei fehlgeschlagener Übergabe soll der gepatchte Queue-Handler den Spool behalten; diese Originalintegration ist noch nicht real geprüft. Wiederholungsworkflow, eigene persistente Historie und Konvertierung sind noch offen. + +## 6. Abnahme auf Linux + +```sh +make all check check-native check-supervisor check-print check-raw check-scripts +sudo make check-trustee +# Offline IPC, nur wenn kein Server läuft: +sudo ./run-ipc-test.sh +make native +make check-web +``` + +`check-trustee` nutzt simulierte Originalroutinen; `check-scripts` nutzt echte Testdateien. Optionaler Browser-Entwicklertest `python3 tests/test_scripts_browser.py` benötigt Playwright und Chromium, verwendet simulierte HTTP-Antworten. Danach mit echter Installation: SAP, Bindery-Login, authentifizierte Sitzungen, Benutzer-/Gruppenänderung, SYS-Skripte, Windows-/DOS-Login, MAP und Dateioperationen, positive/negative Trustee-Tests, CUPS-/RAW-Druck, Neustart, Backup und TLS abnehmen. Reale Tests bisher nicht durchgeführt. SPX, Dateihandles/Dateisperren, vollständige Bindery-Wiederherstellung und effektive ACL-Berechnung sind weiterhin offen. Keine Internetfreigabe. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..f975f69 --- /dev/null +++ b/Makefile @@ -0,0 +1,66 @@ +CC ?= cc +CFLAGS ?= -O2 -g -Wall -Wextra +CPPFLAGS += -D_DEFAULT_SOURCE +.PHONY: all check clean +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/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 + $(AR) rcs $@ $< +build/test-wire: tests/test_wire.c src/wire.c src/wire.h | build + $(CC) $(CPPFLAGS) $(CFLAGS) -std=c11 -Isrc tests/test_wire.c src/wire.c -o $@ +build/test-ipc: tests/test_ipc.c build/libmarspcap.a | build + $(CC) $(CPPFLAGS) $(CFLAGS) -std=c11 -Isrc tests/test_ipc.c build/libmarspcap.a -o $@ +check: all build/test-wire build/test-ipc + ./build/test-wire +clean: + rm -rf build + +# Native service. CivetWeb is embedded as a library, not a stand-alone daemon. +CIVET_CFLAGS ?= +CIVET_LIBS ?= -lcivetweb +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/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 + ./build/test-native +build/test-supervisor: tests/test_supervisor.c native/supervisor.c native/core.c native/core.h native/supervisor.h | build + $(CC) $(CFLAGS) -std=c11 -DMARS_TESTING -Inative $(NATIVE_FLAGS) tests/test_supervisor.c native/supervisor.c native/core.c -o $@ $(NATIVE_LIBS) +.PHONY: check-supervisor check-web +check-supervisor: build/test-supervisor + ./build/test-supervisor +check-web: native + ./tests/test_web.sh + +build/mars-print: native/print_stdin.c native/rawprint.c native/printing.c native/core.c native/admin.h native/core.h | build + $(CC) $(CFLAGS) -std=c11 $(NATIVE_FLAGS) native/print_stdin.c native/rawprint.c native/printing.c native/core.c -o $@ $(NATIVE_LIBS) -ldl +.PHONY: check-print +check-print: build/test-print build/mars-print + ./build/test-print +build/test-print: tests/test_print.c native/printing.c native/core.c native/admin.h | build + $(CC) $(CFLAGS) -std=c11 -Inative $(NATIVE_FLAGS) tests/test_print.c native/printing.c native/core.c -o $@ $(NATIVE_LIBS) -ldl +.PHONY: check-raw +check-raw: build/test-raw + ./build/test-raw +build/test-raw: tests/test_raw.c native/rawprint.c | build + $(CC) $(CFLAGS) -std=c11 tests/test_raw.c native/rawprint.c -o $@ + +.PHONY: check-scripts +check-scripts: build/test-scripts + ./build/test-scripts +build/test-scripts: tests/test_scripts.c upstream-adapter/mars_scripts.inc | build + $(CC) $(CFLAGS) -std=c11 $(NATIVE_FLAGS) tests/test_scripts.c -o $@ $(NATIVE_LIBS) +.PHONY: check-trustee +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 $@ diff --git a/README.md b/README.md new file mode 100644 index 0000000..373dd46 --- /dev/null +++ b/README.md @@ -0,0 +1,142 @@ +# MARS_NWE-PCAP 0.4 – Administration, Print & Login Edition + +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. + +## Ein einziger Dienst + +``` +systemd: mars_vme.service + /usr/local/sbin/mars_vme (C + eingebettete CivetWeb-Bibliothek) + ├─ HTTP(S) :8787 / Auth / Config / Diagnose (Threads im Hauptprozess) + ├─ mars-pcapd (libpcap / IPX-Dispatcher, Kindprozess) + └─ nwserv (originale NetWare-Serverlogik, Kindprozess) + ├─ nwbind + ├─ ncpserv + └─ nwconn ... +``` + +Es gibt keinen eigenständigen CivetWeb-Prozess und keine zweite Web-systemd-Unit. Kein Python, .NET, Java, Node oder zusätzlicher Webserver für den Betrieb. Die Browser-Oberfläche bleibt HTML/CSS/JavaScript. Der originale MARS_NWE ist weiterhin multiprozessfähig; die Prozesse gehören zur selben systemd-Cgroup. Auf Stop/Restart im Web reagiert der Supervisor nur durch Stop/Restart seiner NetWare- und PCAP-Kindprozesse. `systemctl stop mars_vme` beendet alles einschließlich Webverwaltung. Der Supervisor verwendet `posix_spawn`, getrennte Prozessgruppen und begrenzte Wartezeiten. Abschnitt 200 muss 0 sein, damit nwserv nicht daemonisiert. + +## 1. Build und Installation + +Ziel: Debian 12/13 bzw. Ubuntu mit verfügbaren Entwicklungspaketen, glibc >=2.34 empfohlen. Standardprefix `/usr/local` (absichtlich fest für Dienste und Originalkonfigurationspfad). + +```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 +# Optional für den HTTP-Abnahmetest: +sudo apt install curl jq + +tar -xzf mars-nwe-pcap-0.4.tar.gz +cd mars-nwe-pcap-0.4 +./build.sh +sudo ./install.sh +sudo systemctl enable --now mars_vme.service +``` + +CivetWeb wird als native Bibliothek aus den Distributionspaketen gelinkt, **nicht** als Webserver-Dienst installiert. JSON wird mit der kleinen nativen json-c-Bibliothek verarbeitet (statt cJSON, um eine zusätzliche vendorte Abhängigkeit zu vermeiden). OpenSSL libcrypto liefert PBKDF2 und sichere Zufallszahlen. libpcap wird wie in 0.2 dynamisch geladen. + +Der Build bezieht den historischen MARS_NWE-Quellzweig `davidrg/mars_nwe` (0.99.pl23-Basis, Branch main) von GitHub und erzeugt `upstream/original`, `upstream/patched` und `upstream/build`. Die tatsächliche Git-Revision wird in `upstream/source-revision.txt` protokolliert. Der Build benötigt Internet für den erstmaligen Bezug oder einen lokal vorhandenen Originalquellbaum: + +```sh +MARS_SOURCE_DIR=/absoluter/pfad/zum/mars_nwe ./build.sh +``` + +`patch-upstream.sh` ersetzt den früheren Python-Patcher durch Bash/GNU sed. Er verweigert unbekannte Quellstrukturen und direkte, nicht umgeleitete IPX-Socket-Aufrufe. Bei bereits erzeugtem Patchbaum: + +```sh +./rebuild.sh +``` + +Der ursprüngliche Server wird nicht neu implementiert. Das Paket enthält die eigenen Transport- und Administrationsquellen, aber **nicht** den vollständigen originalen MARS_NWE-Baum oder CivetWeb-Quellcode. Der Bezug bzw. die Systembibliotheken sind Voraussetzung. Bei abweichenden CivetWeb-Pfaden können `CIVET_CFLAGS` und `CIVET_LIBS` beim make/Build als Umgebungsvariablen gesetzt werden. + +Installation sichert eine vorhandene nwserv.conf dauerhaft (`.pre-native-*`) und stellt sie nach der Originalinstallation wieder her. Das vorhandene Webkennwort und Web-Backups werden nicht zurückgesetzt. Frühere Units `mars-nwe-setup`, `mars-nwe-pcap`, `mars-pcapd` werden bei einer systemd-Installation gestoppt/deaktiviert, nicht gelöscht. Es wird ausschließlich die neue Unit installiert; vorhandene Drittanbieter-MARS-Units müssen ggf. manuell deaktiviert werden. Der Installer startet die neue Unit nicht automatisch. + +## 2. Webzugriff und Einrichtung + +``` +http://:8787 +Benutzer: admin +Initialkennwort: admin +``` + +Ziel-IP mit `hostname -I` ermitteln. Zugriff standardmäßig auf RFC1918-IPv4, Loopback und IPv4-Link-Local beschränkt; Host-Header muss eine lokale IPv4-Adresse mit Port bzw. localhost mit Port sein. Für einen eigenen DNS-Namen `--host mars.example.lan:8787` angeben. Nur an einem vertrauenswürdigen Management-Netz betreiben! HTTP ist unverschlüsselt. Das Standardkennwort ist öffentlich bekannt. Bei einem neuen System zuerst nur vom geschützten Management-Netz zugreifen und unmittelbar ändern; alternativ vor dem ersten Start über die Konsole ein Kennwort setzen. Bis dahin bleibt die vertrauliche Konfiguration in der Web-API verborgen und Änderungs-/Dienstaktionen sind gesperrt. + +Der Webassistent leitet durch Servername, internes IPX-Netz, externe Interface-/Frame-Kombinationen, SYS-/Datenvolumes, Supervisor, optionale Benutzer und Bindery-Einstellungen. Unbekannte Abschnitte bleiben beim geführten Bearbeiten erhalten. Der Experteneditor und Download enthalten ggf. historische Klartextkennwörter. Die Änderungsvorschau zeigt die vollständige alte/neue Konfiguration, nicht einen zeilenweisen Unified-Diff. Jede Änderung benötigt Revision, Vorschau-Hash und Bestätigung. Backups sind vor Wiederherstellung erst als Entwurf zu prüfen. Die Dateien sind root-only (0600), das Sicherungsverzeichnis 0700. + +Die Originalkonfiguration ist `/usr/local/etc/mars_nwe/nwserv.conf`. Beispiel-Einträge (nicht als komplette Datei verwenden): + +```ini +2 MARS_PCAP +3 0x12345678 1 +4 0x101 enp3s0 802.3 1 +4 0x102 enp3s0 802.2 1 +4 0x103 enp3s0 ETHERNET_II 1 +4 0x104 enp3s0 SNAP 1 +5 0 +200 0 +``` + +Netzwerknummern müssen eindeutig und an das bestehende Retro-Netz angepasst sein. Für den Ersttest ein einziges geeignetes Ethernet-Interface/Frame-Paar wählen. Abschnitt 1 benötigt SYS mit vorhandener Verzeichnisstruktur, Abschnitt 12 SUPERVISOR mit passender Linux-Zuordnung. Der Assistent erstellt keine Linux-Benutzer, Verzeichnisse oder Rechte. Original-SYS und Client-Programme (LOGIN, MAP etc.) separat bereitstellen. Kein NDS, kein Kernel-IPX-Modul. Abschnitt 13 verwaltet Benutzer-Zuordnungen der Originalkonfiguration; Abschnitt 17 die Bindery-Flags, Abschnitt 45 das Bindery-Verzeichnis. Keine Live-Bindery-Änderungen, kein Löschen oder Zurücksetzen vorhandener Bindery-Konten. Dafür die originalen NetWare-Werkzeuge (z. B. SYSCON) verwenden. Die Grundvalidierung ersetzt nicht den Originalparser. Konfiguration als UTF-8 bzw. ASCII speichern. + +Bei gültiger Konfiguration startet der Supervisor beim Dienststart die Kindprozesse automatisch. Ist die Konfiguration ungültig, bleibt nur die Webadministration erreichbar und der NetWare-Teil wartet auf die Einrichtung. Nach dem Speichern manuell in der Weboberfläche Start auswählen. Bei einem Prozessabsturz bleiben Webverwaltung und Diagnose verfügbar; kein automatisches endloses Neustarten der Kinder. Prozessstatus bedeutet nicht, dass der NCP-Server funktionsfähig ist. Status nach einer angeforderten Aktion erneut abrufen. + +## 3. Verwaltung + +```sh +sudo systemctl status mars_vme +sudo systemctl restart mars_vme +sudo systemctl stop mars_vme +sudo journalctl -u mars_vme -f +``` + +Passwort jederzeit im Web unter „Web-Kennwort ändern“ (mindestens 10, maximal 256 Bytes; alle Sitzungen werden ungültig). Speicherung in `.mars-web-auth.json` im Konfigurationsverzeichnis mit PBKDF2-HMAC-SHA256, 600000 Iterationen, 32 Byte Salt. Das Format ist mit Version 0.2 kompatibel. 30 Minuten Inaktivitätslimit, 8 Stunden absolute Sitzungsdauer, 128 Sitzungen, fünf Fehlversuche pro IP in 60 Sekunden, Origin- und CSRF-Prüfung. Für ein vergessenes Kennwort: + +```sh +sudo systemctl stop mars_vme +sudo /usr/local/sbin/mars_vme --reset-password +sudo systemctl start mars_vme +``` + +Für HTTPS einen privaten Schlüssel und Zertifikatskette als PEM-Datei (0600, root) bereitstellen. `sudo systemctl edit mars_vme`: + +```ini +[Service] +ExecStart= +ExecStart=/usr/local/sbin/mars_vme --bind 192.168.1.50 --port 8787 --pem /etc/mars-vme/server.pem +``` + +IP-Adresse des Management-Interfaces einsetzen. Danach `sudo systemctl daemon-reload && sudo systemctl restart mars_vme`. Die Oberfläche ist dann unter `https://:8787` erreichbar. TLS >=1.2, vorausgesetzt die CivetWeb-Systembibliothek unterstützt TLS. PEM muss Zertifikat und privaten Schlüssel enthalten; Zertifikat muss für den aufgerufenen Namen vertrauenswürdig sein. TLS wurde hier nicht ausgeführt. `--bind 127.0.0.1` erlaubt lokalen Zugriff/SSH-Tunnel; `--no-autostart` startet nur Administration bis zum manuellen Start des Dateiservers. `--no-services` ist der isolierte Testmodus (mit `--config` und `--www` für Testdateien). + +## 4. Diagnose + +Die Weboberfläche zeigt Linux-CPU-Auslastung zwischen zwei Messpunkten, RAM, Last, Journal-Auszug, IPX-Interfaces, Sockets, RIP-Routen, Frame-Zähler, beobachtete SAP-Antworten und IPX-Knoten. Der Broker schreibt atomare Snapshots nach `/run/mars-pcap/`. Die RX/TX-Werte sind akzeptierte/eingespeiste Frames im Broker, keine vollständige physische NIC-Statistik. Offline-Test zählt nur simulierten TX. Die Beobachtungstabellen sind begrenzt und zeitbasiert: 256 Knoten (300 s), 128 SAP-Anzeigen (180 s). Beobachtete IPX-Knoten sind **keine** authentifizierten NetWare-Sitzungen. SAP ist eine passive Beobachtung, keine direkte Abfrage der internen MARS-Bindery. Das Webfrontend lädt Diagnose auf Wunsch alle 5 s. Journal-Auszug ist auf 80 Zeilen und 32 KiB begrenzt. + +## 5. Tests / Abnahme + +```sh +make all check check-native check-supervisor +sudo ./run-ipc-test.sh # nur wenn kein Broker/Server läuft +make native # benötigt echte CivetWeb-Entwicklungsbibliothek +make check-web # curl + jq, isoliertes temporäres Konfigurationsverzeichnis +``` + +`check-web` ist ein realer HTTP-Test des eingebetteten Webservers; er prüft Login, Origin/Host, CSRF, Passwortwechsel, Sitzung, Vorschau, Backup, Revision und Neustart-Persistenz. Er startet keinen NetWare-Server. Der Test ist enthalten, konnte in der Erstellungsumgebung mangels CivetWeb noch nicht ausgeführt werden. Der Supervisor-Test nutzt simulierte Kindprozesse, nicht nwserv. Siehe TEST-RESULTS.txt für tatsächlich ausgeführte Tests. + +Nach erfolgreichem Build auf dem Zielsystem: Server starten, SAP-Erkennung mit einem DOS-/Windows-NetWare-Client, Anmeldung, Bindery, MAP, Datei erstellen/lesen/umbenennen/löschen, Abmelden. Alle Frame-Varianten nach Bedarf prüfen. Die vorhandene ursprüngliche NCP-/SAP-/RIP-Logik ist nicht vollständig integriert verifiziert; SPX-Zustandsmaschine und AUTO-IPX-Netzerkennung sind nicht implementiert. Routing ist im Broker vorhanden, Weiterleitung nur mit `--forward` (standardmäßig aus; der Supervisor startet ohne `--forward`). + +## 6. Projektstatus + +- Native C-Konfiguration, Passwortverwaltung, Session-/HTTP-Handler, Backups, Prozesssteuerung und Diagnose implementiert. +- Vier Ethernet-Frame-Codecs und Offline-IPC-Tests bestanden; native Konfigurations-/Authentifizierungstests bestanden; Supervisor mit Test-Kindprozessen bestanden. +- CivetWeb-HTTP-Code gegen eine lokal erstellte API-Signaturprobe syntaxkompiliert, **nicht** gegen die echte Bibliothek gelinkt. Kein CivetWeb-Download möglich. Echte HTTP-/TLS-/Browser-/systemd-Abnahme offen. +- Vollständiger Original-MARS_NWE-Quellbaum nicht lokal abrufbar; Upstream-Patchskript nur mit Fixture getestet. Vollständiger NetWare-Build, echte libpcap-Ethernet-Kommunikation und NCP-Client-Abnahme offen. +- Neu in 0.4: Live-Sitzungs-/Bindery-Adapter, CUPS/RAW-TCP, Login-Skripte und eingeschränkter Trustee-Adapter. Die Adapter zum historischen Originalquellbaum wurden noch nicht als Gesamtserver kompiliert oder am echten Client getestet. Kein gemessener Gesamt-RAM-/CPU-Vergleich zum Python-Frontend. + + +## 7. Native Administration, Druck, Login und Freigaben (0.4) + +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. diff --git a/TEST-RESULTS.txt b/TEST-RESULTS.txt new file mode 100644 index 0000000..7a5dee0 --- /dev/null +++ b/TEST-RESULTS.txt @@ -0,0 +1,34 @@ +MARS_NWE-PCAP 0.3 Native Edition – tatsächlich ausgeführte Tests +Umgebung: Linux Debian 13, C-Compiler, OpenSSL und json-c Entwicklungspakete. + +PASS: GCC -O2 -Wall -Wextra -Werror für Broker, Shim, Frame-/IPC-Test. +PASS: vier Ethernet-Frame-Typen, Adressen, Padding, Längen, Fehlerfälle, MTU. +PASS: offline Broker-IPC: interne/externe Interfaces, Routing add/delete, + bind conflict, dynamischer Port, fork/exec und erneutes Binden. +PASS: C-Konfigurationsparser, Merge, CRLF, Erhalt unbekannter Zeilen, + Ablehnung eingebetteter Zeilenumbrüche. +PASS: atomare Speicherung, Backup, Revision-Konflikt, Dateimodus, Pfadprüfung. +PASS: PBKDF2, admin/admin Initialisierung, Kennwortwechsel/Persistenz, + falsches Kennwort, schwaches neues Kennwort abgewiesen. +PASS: Grundvalidierung fehlerhafter Netz-/Serverkonfiguration. +PASS: Prozess-Supervisor mit simulierten Kindprozessen: Start, Restart, + Stop, Start nach Stop, Shutdown. +PASS: Shell-Syntax, JavaScript-Syntax; Upstream-Patch an synthetischer Fixture. +PASS: C-HTTP-Übersetzung gegen lokale CivetWeb-API-Signaturprobe + (-Wall -Wextra -Werror); NICHT der echte CivetWeb-Link oder HTTP-Test. + +NICHT AUSGEFÜHRT: echter CivetWeb-Build/HTTP/TLS, Browser/Systemd auf Zielhost, + MARS_NWE-Gesamtbuild, realer Ethernet-Verkehr, NCP-Clients, SPX. +Grund: Netzwerkzugriff zur Beschaffung der Quellbäume und libcivetweb-dev +fehlte in der isolierten Umgebung. tests/test_web.sh ist für den Zielhost +vorbereitet. Keine RAM-Messung des Gesamtservers. + +MARS_NWE-PCAP 0.4 – zusätzliche tatsächlich ausgeführte Tests +PASS: wiederholte Frame-, IPC-, Native-Core- und Supervisor-Tests. +PASS: CUPS 2-Bibliotheksprobe, ungültiger Druckername abgelehnt; kein erreichbarer Scheduler (Bad file descriptor), kein realer CUPS-Auftrag. +PASS: RAW TCP 9100 binär bytegenau an lokal simulierten TCP-Empfänger. +PASS: C-Login-Skript-Dateioperationen an temporären Verzeichnissen: System/Benutzer, DOS CRLF, Backup, Inode/Dateimodus, Revisionskonflikt, ASCII, Symlink-Ablehnung. +PASS: ftrustee-Adapter mit simulierten Original-Trustee-Routinen: Pfad-/Rechteprüfung, Laden/Setzen/Entfernen, Revisionskonflikt, Symlink-Ablehnung. Keine reale MARS-ACL-Datenbank verwendet. +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. diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..d8e4062 --- /dev/null +++ b/build.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")" +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 +mkdir -p upstream +if [[ ! -d upstream/original ]]; then + if [[ -n $source_dir ]]; then + cp -a -- "$source_dir" upstream/original + else + git clone --depth 1 --branch main https://github.com/davidrg/mars_nwe.git upstream/original + fi +fi +if [[ -d upstream/original/.git ]]; then git -C upstream/original rev-parse HEAD > upstream/source-revision.txt; else echo 'Locally supplied source tree' > upstream/source-revision.txt; fi +[[ ! -e upstream/patched ]] || { echo 'Remove upstream/patched and upstream/build to rebuild from original (or run ./rebuild.sh).' >&2; exit 2; } +cp -a upstream/original upstream/patched +./patch-upstream.sh upstream/patched +cmake_args=() +if cmake --version | head -1 | grep -q 'version 4\.'; then cmake_args+=(-DCMAKE_POLICY_VERSION_MINIMUM=3.5); fi +# Old C code needs legacy inline semantics, tentative definitions and GCC compatibility. +cmake -S upstream/patched -B upstream/build "${cmake_args[@]}" \ + -DCMAKE_INSTALL_PREFIX="$prefix" -DCMAKE_INSTALL_SBINDIR=sbin \ + -DCMAKE_INSTALL_LOCALSTATEDIR=/var -DENABLE_INTERNAL_RIP_SAP=ON \ + -DCMAKE_C_FLAGS="-std=gnu99 -fcommon -fgnu89-inline -Wno-error=incompatible-pointer-types -Wno-error=int-conversion -Wno-error=implicit-function-declaration" \ + -DMARS_PCAP_LIBRARY="$base/build/libmarspcap.a" +cmake --build upstream/build --parallel "${JOBS:-$(getconf _NPROCESSORS_ONLN)}" +printf '%s\n' "$prefix" > upstream/install-prefix.txt +printf '\nBuild finished. Run sudo ./install.sh (review configuration before starting).\n' diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..f05ff88 --- /dev/null +++ b/install.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")" +[[ $EUID == 0 ]] || { echo 'Use sudo ./install.sh' >&2; exit 1; } +[[ -f upstream/install-prefix.txt && -f upstream/build/CMakeCache.txt && -x build/mars-pcapd && -x build/mars_vme ]] || { echo 'Run ./build.sh successfully first' >&2; exit 1; } +prefix=$(cat upstream/install-prefix.txt) +[[ $prefix == /usr/local ]] || { echo 'Native service currently requires PREFIX=/usr/local' >&2; exit 1; } +if [[ -d /run/systemd/system ]]; then + for unit in mars_vme.service mars-nwe-setup.service mars-nwe-pcap.service mars-pcapd.service; do + if systemctl is-active --quiet "$unit"; then systemctl stop "$unit"; fi + done + for unit in mars-nwe-setup.service mars-nwe-pcap.service mars-pcapd.service; do + if systemctl is-enabled --quiet "$unit" 2>/dev/null; then systemctl disable "$unit"; fi + done +fi +conf="$prefix/etc/mars_nwe/nwserv.conf" +backup='' +if [[ -f $conf ]]; then backup="$conf.pre-native-$(date +%Y%m%d-%H%M%S)-$$"; install -m 0600 "$conf" "$backup"; fi +# Original installation may refresh its sample config. Restore existing config. +if ! cmake --install upstream/build; then + if [[ -n $backup ]]; then install -m 0600 "$backup" "$conf"; fi + echo "Original installation failed; review output. Existing config restored." >&2; exit 1 +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 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 +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 +fi +printf 'Installed. Start on trusted LAN: sudo systemctl enable --now mars_vme.service\nExisting web credentials retained. New installation: admin/admin, change before configuration.\n' diff --git a/mars_vme.service b/mars_vme.service new file mode 100644 index 0000000..25a3db3 --- /dev/null +++ b/mars_vme.service @@ -0,0 +1,20 @@ +[Unit] +Description=MARS NWE native IPX and CivetWeb administration +After=network-online.target +Wants=network-online.target +Conflicts=mars-pcapd.service mars-nwe-pcap.service mars-nwe-setup.service + +[Service] +Type=simple +ExecStart=/usr/local/sbin/mars_vme --bind 0.0.0.0 --port 8787 +Restart=on-failure +RestartSec=3 +RuntimeDirectory=mars-pcap +RuntimeDirectoryMode=0700 +UMask=0077 +KillMode=mixed +TimeoutStopSec=65s +PrivateTmp=true + +[Install] +WantedBy=multi-user.target diff --git a/native/admin.c b/native/admin.c new file mode 100644 index 0000000..c341938 --- /dev/null +++ b/native/admin.c @@ -0,0 +1,20 @@ +#define _GNU_SOURCE +#include "admin.h" +#include +#include +#include +#include +#include +#include +#include +#include +static json_object *failure(const char *s){json_object *o=json_object_new_object();addstr(o,"error",s);return o;} +json_object *bindery_call(json_object *req){ + int fd=socket(AF_UNIX,SOCK_SEQPACKET|SOCK_CLOEXEC,0); if(fd<0)return failure("IPC nicht verfügbar"); + struct timeval t={3,0};setsockopt(fd,SOL_SOCKET,SO_RCVTIMEO,&t,sizeof t);setsockopt(fd,SOL_SOCKET,SO_SNDTIMEO,&t,sizeof t); + struct sockaddr_un a={.sun_family=AF_UNIX,.sun_path=ADMIN_SOCK}; + if(connect(fd,(struct sockaddr*)&a,sizeof a)){close(fd);return failure("nwbind-Live-Schnittstelle nicht erreichbar. Server starten oder Build prüfen.");} + struct ucred peer; socklen_t z=sizeof peer;if(getsockopt(fd,SOL_SOCKET,SO_PEERCRED,&peer,&z)||peer.uid!=0){close(fd);return failure("Ungültiger IPC-Prozess");} + const char *s=json_object_to_json_string_ext(req,JSON_C_TO_STRING_PLAIN);size_t n=strlen(s);if(n>32768||send(fd,s,n,MSG_NOSIGNAL)!=(ssize_t)n){close(fd);return failure("IPC-Senden fehlgeschlagen");} + char *buf=malloc(200001);if(!buf){close(fd);return failure("Speicherfehler");}ssize_t r=recv(fd,buf,200000,MSG_TRUNC);close(fd);json_object *o=NULL;if(r>0&&r<200000){buf[r]=0;o=json_tokener_parse(buf);}free(buf);return o?o:failure("Keine gültige Antwort; bei Schreiboperationen Zustand neu prüfen."); +} diff --git a/native/admin.h b/native/admin.h new file mode 100644 index 0000000..fddc1f2 --- /dev/null +++ b/native/admin.h @@ -0,0 +1,8 @@ +#ifndef MARS_ADMIN_H +#define MARS_ADMIN_H +#include "core.h" +#define ADMIN_SOCK "/run/mars-pcap/admin.sock" +json_object *bindery_call(json_object *request); +json_object *print_call(json_object *request); +int print_submit(const char *dest,const char *mode,const char *file,const char *title); +#endif diff --git a/native/core.c b/native/core.c new file mode 100644 index 0000000..d1fdcf4 --- /dev/null +++ b/native/core.c @@ -0,0 +1,65 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#define _GNU_SOURCE +#include "core.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +const char *managed[]={"1","2","3","4","5","12","13","17","21","45","200",NULL}; +char config_path[PATH_MAX],auth_path[PATH_MAX],backup_dir[PATH_MAX]; +json_object *get(json_object *o,const char*k){json_object *v=NULL;return o&&json_object_object_get_ex(o,k,&v)?v:NULL;} +const char *js(json_object *o,const char*k){json_object *v=get(o,k);if(!v||!json_object_is_type(v,json_type_string))return NULL;const char *s=json_object_get_string(v);return strlen(s)==(size_t)json_object_get_string_len(v)?s:NULL;} +void addstr(json_object*o,const char*k,const char*v){json_object_object_add(o,k,json_object_new_string(v?v:""));} +char *read_file(const char *path,size_t max,int private){int fd=open(path,O_RDONLY|O_CLOEXEC|O_NOFOLLOW|O_NONBLOCK);if(fd<0)return NULL;struct stat st;if(fstat(fd,&st)||!S_ISREG(st.st_mode)||st.st_size>(off_t)max||(private&&(st.st_uid!=geteuid()||(st.st_mode&077)))){close(fd);errno=EINVAL;return NULL;}char *s=malloc(max+1);if(!s){close(fd);return NULL;}size_t n=0;while(n<=max){ssize_t r=read(fd,s+n,max+1-n);if(r<0&&errno==EINTR)continue;if(r<0){free(s);close(fd);return NULL;}if(!r)break;n+=r;}close(fd);if(n>max||memchr(s,0,n)){free(s);errno=EINVAL;return NULL;}s[n]=0;return s;} +static int writeall(int fd,const char*s,size_t n){while(n){ssize_t r=write(fd,s,n);if(r<0&&errno==EINTR)continue;if(r<=0)return -1;s+=r;n-=r;}return 0;} +static void sync_parent(const char*p){char *s=strdup(p);if(!s)return;char*q=strrchr(s,'/');if(q){*q=0;int fd=open(*s?s:"/",O_RDONLY|O_DIRECTORY|O_CLOEXEC);if(fd>=0){fsync(fd);close(fd);}}free(s);} +int atomic_write(const char*p,const char*s,size_t n,mode_t mode){char tmp[PATH_MAX];if(snprintf(tmp,sizeof tmp,"%s.tmp.XXXXXX",p)>=(int)sizeof tmp)return -1;int fd=mkstemp(tmp);if(fd<0)return -1;int r=fchmod(fd,mode)||writeall(fd,s,n)||fsync(fd);if(close(fd))r=-1;if(!r&&rename(tmp,p))r=-1;if(r)unlink(tmp);else sync_parent(p);return r?-1:0;} +static void hex(const unsigned char*s,size_t n,char*out){static const char h[]="0123456789abcdef";for(size_t i=0;i>4];out[2*i+1]=h[s[i]&15];}out[2*n]=0;} +static int unhex(const char*s,unsigned char*out,size_t n){if(!s||strlen(s)!=2*n)return -1;for(size_t i=0;isizeof v||RAND_bytes(v,(int)n)!=1)return -1;hex(v,n,out);return 0;} +static int group_idx(const char *s){for(int i=0;managed[i];i++)if(!strcmp(s,managed[i]))return i;return -1;} +/* Parse one line, without normalizing untouched bytes. */ +static int line_group(const char *s,size_t n,const char **body,size_t *bn){const char *e=s+n;while(s8)return -1;char k[9];memcpy(k,a,s-a);k[s-a]=0;while(ss&&(e[-1]=='\r'||e[-1]=='\n'))e--;*body=s;*bn=e-s;return group_idx(k);} +json_object *groups(const char *s){json_object *o=json_object_new_object();for(int i=0;managed[i];i++)json_object_object_add(o,managed[i],json_object_new_array());while(*s){const char *e=strchr(s,'\n');size_t n=e?(size_t)(e-s+1):strlen(s),bn=0;const char*b=NULL;int i=line_group(s,n,&b,&bn);if(i>=0)json_object_array_add(get(o,managed[i]),json_object_new_string_len(b,(int)bn));s+=n;}return o;} +char *merge(const char*s,json_object*changes){if(!changes||!json_object_is_type(changes,json_type_object))return NULL;json_object*old=groups(s);int changed[11]={0},ix[11]={0};json_object_object_foreach(changes,key,v){int i=group_idx(key);if(i<0||!json_object_is_type(v,json_type_array))goto bad;for(size_t j=0;j=0&&changed[i]){json_object*a=get(changes,managed[i]);if((size_t)ix[i]MAX_CONF){free(out);out=NULL;}json_object_put(old);return out; + bad:json_object_put(old);return NULL;} +static int tokens(const char *s,char **copy,char *a[],int max){*copy=strdup(s?s:"");if(!*copy)return 0;char*h=strchr(*copy,'#');if(h)*h=0;char*save=NULL;int n=0;for(char*t=strtok_r(*copy," \t\r\n",&save);t;t=strtok_r(NULL," \t\r\n",&save)){if(n==max)return max+1;a[n++]=t;}return n;} +static int number(const char*s,unsigned long long max,unsigned long long*v){if(!s||!*s||(!isdigit((unsigned char)*s)))return 0;int base=10;if(s[0]=='0'&&(s[1]=='x'||s[1]=='X')){base=16;if(!isxdigit((unsigned char)s[2]))return 0;}else if(s[0]=='0'&&s[1])return 0;char*end;errno=0;*v=strtoull(s,&end,base);return !errno&&!*end&&*v<=max&&*v>0;} +static void msg(json_object*a,const char*s){json_object_array_add(a,json_object_new_string(s));} +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;} +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);} + if(count(g,"3")!=1)msg(err,"Abschnitt 3: genau ein internes IPX-Netz erforderlich.");else{n=tokens(at(g,"3",0),©,a,12);if(n<1||n>2||!number(a[0],0xfffffffe,&x))msg(err,"Abschnitt 3: interne Netznummer ungültig.");else{nets[nn++]=x;if(n==2&&!number(a[1],0xffffffffffffULL,&x))msg(err,"Abschnitt 3: Node ungültig.");}free(copy);} + size_t nc=count(g,"4");if(!nc||nc>31)msg(err,"Abschnitt 4: 1–31 externe IPX-Netze erforderlich.");for(size_t i=0;i4){msg(err,"Abschnitt 4: Netz, Interface, Frame und optional Ticks.");free(copy);continue;}if(!number(a[0],0xfffffffe,&x))msg(err,"Abschnitt 4: Netznummer ungültig.");else{for(size_t j=0;j12)msg(err,"Abschnitt 1: Volume und Pfad erforderlich.");else{if(!strcasecmp(a[0],"SYS")){sys++;if(i)msg(warn,"SYS sollte das erste Volume sein.");if(a[1][0]!='/')msg(err,"SYS benötigt absoluten Pfad.");}for(size_t j=0;j8)msg(warn,"Volume-Namen maximal 8 Zeichen für historische Clients.");char*r=realpath(a[1],NULL);if(!strcmp(a[1],"/")||(r&&!strcmp(r,"/")))msg(err,"Root-Dateisystem nicht als Volume freigeben.");struct stat st;if(a[1][0]=='/'&&(stat(a[1],&st)||!S_ISDIR(st.st_mode)))msg(warn,"Volume-Verzeichnis fehlt oder ist kein Verzeichnis.");free(r);}free(copy);}if(sys!=1)msg(err,"Genau ein SYS-Volume erforderlich.");json_object_put(vol); + int sup=0;for(size_t i=0;i=1&&!strcasecmp(a[0],"SUPERVISOR")){sup++;if(n<2||!getpwnam(a[1]))msg(err,"SUPERVISOR: Linux-Benutzer fehlt.");else if(!strcmp(a[1],"root"))msg(warn,"SUPERVISOR ist root zugeordnet.");if(n<3||strlen(a[2])<8)msg(warn,"SUPERVISOR: Initialkennwort prüfen.");}free(copy);}if(sup!=1)msg(err,"Abschnitt 12: genau ein SUPERVISOR erforderlich.");json_object_put(g);json_object_put(d);return o;} +static int backup_ok(const char*n){if(!n||strlen(n)!=40||strncmp(n,"nwserv-",7)||strcmp(n+35,".conf")||n[15]!='-'||n[22]!='-')return 0;for(int i=7;i<35;i++)if(i!=15&&i!=22&&!(i>22?isxdigit((unsigned char)n[i]):isdigit((unsigned char)n[i])))return 0;return 1;} +static int backup_check(int create){if(create&&mkdir(backup_dir,0700)&&errno!=EEXIST)return -1;struct stat st;return lstat(backup_dir,&st)||!S_ISDIR(st.st_mode)||st.st_uid!=geteuid()||(st.st_mode&077)?-1:0;} +json_object *backups(void){json_object*a=json_object_new_array();if(backup_check(0))return a;struct dirent **list=NULL;int n=scandir(backup_dir,&list,NULL,alphasort),added=0;for(int i=n-1;i>=0;i--){if(added<100&&backup_ok(list[i]->d_name)){char*p=NULL;if(asprintf(&p,"%s/%s",backup_dir,list[i]->d_name)>=0){struct stat st;if(!lstat(p,&st)&&S_ISREG(st.st_mode)){msg(a,list[i]->d_name);added++;}free(p);}}free(list[i]);}free(list);return a;} +char *backup_read(const char*n){if(!backup_ok(n)||backup_check(0))return NULL;char*p=NULL;if(asprintf(&p,"%s/%s",backup_dir,n)<0)return NULL;char*s=read_file(p,MAX_CONF,1);free(p);return s;} +int save_conf(const char*old,const char*rev,const char*next,char name[64]){name[0]=0;char*now=read_file(config_path,MAX_CONF,0),h[65];if(!now)return -1;sha(now,h);free(now);if(strcmp(h,rev))return -2;if(!strcmp(old,next))return 0;if(backup_check(1))return -1;time_t t=time(NULL);struct tm tm;localtime_r(&t,&tm);char stamp[24],rnd[13];strftime(stamp,sizeof stamp,"%Y%m%d-%H%M%S",&tm);if(random_hex(rnd,6))return -1;snprintf(name,64,"nwserv-%s-%s.conf",stamp,rnd);char*p=NULL;if(asprintf(&p,"%s/%s",backup_dir,name)<0)return -1;int fd=open(p,O_WRONLY|O_CREAT|O_EXCL|O_NOFOLLOW|O_CLOEXEC,0600);if(fd<0){free(p);return -1;}int r=writeall(fd,old,strlen(old))||fsync(fd);if(close(fd))r=-1;if(r){unlink(p);free(p);return -1;}sync_parent(p);free(p);now=read_file(config_path,MAX_CONF,0);if(!now)return -1;sha(now,h);free(now);if(strcmp(h,rev))return -2;return atomic_write(config_path,next,strlen(next),0600);} +static json_object* auth_read(void){char*s=read_file(auth_path,8192,1);if(!s)return NULL;json_object*o=json_tokener_parse(s);free(s);unsigned char v[32];if(!o||json_object_get_int(get(o,"rounds"))!=ROUNDS||unhex(js(o,"salt"),v,32)||unhex(js(o,"hash"),v,32)||!json_object_is_type(get(o,"default"),json_type_boolean)){json_object_put(o);return NULL;}return o;} +int auth_verify(const char*pw){if(!pw||strlen(pw)>256)return 0;json_object*o=auth_read();if(!o)return 0;unsigned char salt[32],hash[32],v[32];unhex(js(o,"salt"),salt,32);unhex(js(o,"hash"),hash,32);int ok=PKCS5_PBKDF2_HMAC(pw,(int)strlen(pw),salt,32,ROUNDS,EVP_sha256(),32,v)==1&&!CRYPTO_memcmp(v,hash,32);OPENSSL_cleanse(v,32);json_object_put(o);return ok;} +int auth_default(void){json_object*o=auth_read();if(!o)return 1;int b=json_object_get_boolean(get(o,"default"));json_object_put(o);return b;} +int auth_set(const char*pw,int initial){if(!pw||strlen(pw)>256||(!initial&&(strlen(pw)<10||!strcmp(pw,"admin")||strspn(pw," \t\r\n")==strlen(pw))))return -1;unsigned char salt[32],v[32];char sh[65],vh[65];if(RAND_bytes(salt,32)!=1||PKCS5_PBKDF2_HMAC(pw,(int)strlen(pw),salt,32,ROUNDS,EVP_sha256(),32,v)!=1)return -1;hex(salt,32,sh);hex(v,32,vh);OPENSSL_cleanse(v,32);json_object*o=json_object_new_object();json_object_object_add(o,"rounds",json_object_new_int(ROUNDS));addstr(o,"salt",sh);addstr(o,"hash",vh);json_object_object_add(o,"default",json_object_new_boolean(initial));const char*s=json_object_to_json_string(o);int r=atomic_write(auth_path,s,strlen(s),0600);json_object_put(o);return r;} +int auth_init(void){struct stat st;if(lstat(auth_path,&st)){if(errno!=ENOENT||auth_set("admin",1))return -1;}json_object*o=auth_read();if(!o)return -1;json_object_put(o);return 0;} diff --git a/native/core.h b/native/core.h new file mode 100644 index 0000000..d3dfe7b --- /dev/null +++ b/native/core.h @@ -0,0 +1,30 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef MARS_CORE_H +#define MARS_CORE_H +#include +#include +#include +#include +#define MAX_CONF (1024*1024) +#define ROUNDS 600000 +extern const char *managed[]; +extern char config_path[PATH_MAX], auth_path[PATH_MAX], backup_dir[PATH_MAX]; +char *read_file(const char *,size_t,int); +int atomic_write(const char *,const char *,size_t,mode_t); +void sha(const char *,char out[65]); +int random_hex(char *,size_t); +const char *js(json_object *,const char *); +json_object *get(json_object *,const char *); +void addstr(json_object *,const char *,const char *); +json_object *groups(const char *); +char *merge(const char *,json_object *); +json_object *validate(const char *); +json_object *devices(void); +json_object *backups(void); +char *backup_read(const char *); +int save_conf(const char *,const char *,const char *,char name[64]); +int auth_init(void); +int auth_verify(const char *); +int auth_default(void); +int auth_set(const char *,int); +#endif diff --git a/native/main.c b/native/main.c new file mode 100644 index 0000000..5c2821b --- /dev/null +++ b/native/main.c @@ -0,0 +1,73 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#define _GNU_SOURCE +#include "core.h" +#include "supervisor.h" +#include "admin.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define SESSIONS 128 +#define MAX_BODY (MAX_CONF*6) +static pthread_mutex_t api_lock=PTHREAD_MUTEX_INITIALIZER; +static char assets[PATH_MAX]="/usr/local/share/mars-vme/www",port[8]="8787",bind_ip[64]="0.0.0.0",pem[PATH_MAX],extra_host[256]; +static int tls,initial_start=1; +static volatile sig_atomic_t quitting; +struct session {char token[65],csrf[65];time_t until,absolute;}; +struct attempt {char ip[48];int count;time_t until;}; +static struct session sessions[SESSIONS];static struct attempt attempts[256]; +static time_t mono(void){struct timespec t;clock_gettime(CLOCK_MONOTONIC,&t);return t.tv_sec;} +static const char *reason(int code){switch(code){case 200:return "OK";case 303:return "See Other";case 400:return "Bad Request";case 401:return "Unauthorized";case 403:return "Forbidden";case 404:return "Not Found";case 405:return "Method Not Allowed";case 409:return "Conflict";case 429:return "Too Many Requests";default:return "Internal Server Error";}} +static int send_data(struct mg_connection*c,int code,const char*type,const char*s,size_t n,const char*cookie,const char*location){mg_printf(c,"HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %zu\r\nConnection: close\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nX-Frame-Options: DENY\r\nReferrer-Policy: no-referrer\r\nContent-Security-Policy: default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'\r\n",code,reason(code),type,n);if(cookie)mg_printf(c,"Set-Cookie: %s\r\n",cookie);if(location)mg_printf(c,"Location: %s\r\n",location);mg_printf(c,"\r\n");if(n)mg_write(c,s,n);return code;} +static int reply(struct mg_connection*c,int code,json_object*o,const char*cookie){const char*s=json_object_to_json_string_ext(o,JSON_C_TO_STRING_PLAIN);int r=send_data(c,code,"application/json; charset=utf-8",s,strlen(s),cookie,NULL);json_object_put(o);return r;} +static int error(struct mg_connection*c,int code,const char*s){json_object*o=json_object_new_object();addstr(o,"error",s);return reply(c,code,o,NULL);} +static int ok(struct mg_connection*c,const char*cookie){json_object*o=json_object_new_object();json_object_object_add(o,"ok",json_object_new_boolean(1));return reply(c,200,o,cookie);} +static int private_ip(const char*s){struct in_addr a;if(inet_pton(AF_INET,s,&a)!=1)return 0;uint32_t x=ntohl(a.s_addr);return (x>>24)==127||(x>>24)==10||(x>>20)==0xac1||(x>>16)==0xc0a8||(x>>16)==0xa9fe;} +static int allowed_host(const char*h){if(!h)return 0;char b[256];if(*extra_host&&!strcmp(h,extra_host))return 1;snprintf(b,sizeof b,"localhost:%s",port);if(!strcmp(h,b))return 1;struct ifaddrs*ifs;if(getifaddrs(&ifs))return 0;int ok=0;for(struct ifaddrs*p=ifs;p;p=p->ifa_next){if(!p->ifa_addr||p->ifa_addr->sa_family!=AF_INET)continue;char ip[INET_ADDRSTRLEN];if(!inet_ntop(AF_INET,&((struct sockaddr_in*)p->ifa_addr)->sin_addr,ip,sizeof ip))continue;snprintf(b,sizeof b,"%s:%s",ip,port);if(!strcmp(h,b))ok=1;}freeifaddrs(ifs);return ok;} +static void cookie_str(char out[256],const char*token){snprintf(out,256,"mars_session=%s; Path=/; HttpOnly; SameSite=Strict; Max-Age=%d%s",token,*token?28800:0,tls?"; Secure":"");} +static struct session* session_get(struct mg_connection*c){const char*h=mg_get_header(c,"Cookie");if(!h)return NULL;char token[65];if(mg_get_cookie(h,"mars_session",token,sizeof token)!=64)return NULL;time_t t=mono();for(int i=0;iuntil<=t||s->absolute<=t){memset(s,0,sizeof *s);continue;}if(!CRYPTO_memcmp(s->token,token,64)){s->until=t+1800;return s;}}return NULL;} +static struct session* new_session(void){time_t t=mono();int slot=-1;for(int i=0;itoken,32)||random_hex(s->csrf,32)){memset(s,0,sizeof *s);return NULL;}s->until=t+1800;s->absolute=t+28800;return s;} +static struct attempt* rate(const char*ip){time_t t=mono();int slot=-1;for(int i=0;i<256;i++){if(attempts[i].until<=t){if(slot<0)slot=i;}else if(!strcmp(attempts[i].ip,ip))return &attempts[i];}if(slot<0)return NULL;struct attempt*a=&attempts[slot];memset(a,0,sizeof *a);snprintf(a->ip,sizeof a->ip,"%s",ip);a->until=t+60;return a;} +static json_object *read_json(struct mg_connection*c,long long n){if(n<=0||n>MAX_BODY)return NULL;const char*ct=mg_get_header(c,"Content-Type");if(!ct||strncmp(ct,"application/json",16)||(ct[16]&&ct[16]!=';'))return NULL;char*b=malloc((size_t)n+1);if(!b)return NULL;size_t off=0;while(off<(size_t)n){int k=mg_read(c,b+off,(size_t)n-off);if(k<=0){free(b);return NULL;}off+=k;}b[n]=0;struct json_tokener*t=json_tokener_new();if(!t){free(b);return NULL;}json_tokener_set_flags(t,JSON_TOKENER_STRICT|JSON_TOKENER_VALIDATE_UTF8);json_object*o=json_tokener_parse_ex(t,b,(int)n);if(json_tokener_get_error(t)!=json_tokener_success||json_tokener_get_parse_end(t)!=(size_t)n||!json_object_is_type(o,json_type_object)){json_object_put(o);o=NULL;}json_tokener_free(t);OPENSSL_cleanse(b,(size_t)n);free(b);return o;} +static json_object *state(struct session*s,const char*current){json_object*o=json_object_new_object();int initial=auth_default();char h[65];sha(current,h);addstr(o,"text",initial?"":current);addstr(o,"revision",h);json_object_object_add(o,"groups",groups(initial?"":current));json_object_object_add(o,"devices",devices());json_object_object_add(o,"validation",validate(initial?"":current));json_object_object_add(o,"backups",initial?json_object_new_array():backups());addstr(o,"path",config_path);json_object_object_add(o,"services",json_object_new_boolean(!no_services&&!initial));addstr(o,"csrf",s->csrf);json_object_object_add(o,"defaultPassword",json_object_new_boolean(initial));return o;} +/* Full before/after comparison. No external shell command or temporary cleartext diff file. */ +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;} +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/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);} + char*current=read_file(config_path,MAX_CONF,0);if(!current)return error(c,500,"nwserv.conf nicht lesbar.");char rev[65];sha(current,rev);int ret=404; + if(!post&&!strcmp(u,"/api/state")){ret=reply(c,200,state(s,current),NULL);goto done;}if(!post&&!strcmp(u,"/api/download")){if(auth_default())ret=error(c,403,"Kennwort ändern.");else ret=send_data(c,200,"text/plain; charset=utf-8",current,strlen(current),NULL,NULL);goto done;} + if(!post){ret=error(c,404,"Nicht gefunden.");goto done;}const char*given=js(req,"revision");if(!given||strcmp(given,rev)){ret=error(c,409,"Konfiguration geändert. Bitte neu laden.");goto done;} + if(!strcmp(u,"/api/service")){const char*a=js(req,"action");if(!confirm(req)||!a||no_services||((!strcmp(a,"start")||!strcmp(a,"restart"))&&!config_valid(current))||supervisor_request(a)){ret=error(c,400,"Aktion nicht erlaubt oder Konfiguration ungültig.");goto done;}ret=reply(c,200,supervisor_status(),NULL);goto done;} + if(strcmp(u,"/api/preview")&&strcmp(u,"/api/save")){ret=error(c,404,"Nicht gefunden.");goto done;}const char*mode=js(req,"mode");char*candidate=NULL;if(mode&&!strcmp(mode,"guided"))candidate=merge(current,get(req,"groups"));else if(mode&&!strcmp(mode,"raw")){const char*t=js(req,"text");if(t&&strlen(t)<=MAX_CONF)candidate=strdup(t);}else if(mode&&!strcmp(mode,"backup"))candidate=backup_read(js(req,"name"));if(!candidate){ret=error(c,400,"Ungültiger Entwurf oder Backup.");goto done;} + json_object*v=validate(candidate);char hash[65];sha(candidate,hash);if(!strcmp(u,"/api/preview")){char*d=comparison(current,candidate);if(!d){json_object_put(v);ret=error(c,500,"Vorschau fehlgeschlagen.");}else{addstr(v,"candidate",candidate);addstr(v,"candidateHash",hash);addstr(v,"diff",d);free(d);ret=reply(c,200,v,NULL);}}else{const char*h=js(req,"candidateHash");if(json_object_array_length(get(v,"errors"))||!confirm(req)||!h||strcmp(h,hash)){ret=error(c,400,"Entwurf zuerst prüfen und bestätigen.");}else{char name[64];int rc=save_conf(current,rev,candidate,name);if(rc)ret=error(c,rc==-2?409:500,"Speichern fehlgeschlagen; Datei oder Backup prüfen.");else{json_object*o=json_object_new_object();addstr(o,"backup",name);json_object_object_add(o,"state",state(s,candidate));ret=reply(c,200,o,NULL);}}json_object_put(v);}free(candidate); + done:free(current);return ret;} +static int handle(struct mg_connection*c,void*data){(void)data;const struct mg_request_info*r=mg_get_request_info(c);const char*h=mg_get_header(c,"Host");if(!r||!r->local_uri||!private_ip(r->remote_addr)||!allowed_host(h))return error(c,403,"Host oder Clientnetz nicht erlaubt.");int post=!strcmp(r->request_method,"POST");if(!post&&strcmp(r->request_method,"GET"))return error(c,405,"Methode nicht erlaubt.");json_object*req=NULL;if(post){char expected[300];snprintf(expected,sizeof expected,"%s://%s",tls?"https":"http",h);const char*origin=mg_get_header(c,"Origin");if(!origin||strcmp(origin,expected))return error(c,403,"Origin-Prüfung fehlgeschlagen.");req=read_json(c,r->content_length);if(!req)return error(c,400,"Ungültiges JSON oder Anfragegröße.");}pthread_mutex_lock(&api_lock);int result=process(c,r,req);pthread_mutex_unlock(&api_lock);json_object_put(req);return result;} +static int begin_request(struct mg_connection*c){return handle(c,NULL);} +static void on_signal(int s){(void)s;quitting=1;} +static int set_path(char*d,size_t cap,const char*s){if(!s||strlen(s)>=cap)return -1;strcpy(d,s);return 0;} +static void usage(void){fprintf(stderr,"mars_vme [--config PATH] [--www PATH] [--bind IPv4] [--port N] [--pem PATH] [--host HOST:PORT] [--no-autostart] [--no-services] [--reset-password]\n");} +int main(int argc,char**argv){strcpy(config_path,"/usr/local/etc/mars_nwe/nwserv.conf");int reset=0;for(int i=1;i65535||inet_pton(AF_INET,bind_ip,&addr)!=1||config_path[0]!='/'||assets[0]!='/'){usage();return 2;}if(!no_services&&(geteuid()!=0||strcmp(config_path,"/usr/local/etc/mars_nwe/nwserv.conf"))){fprintf(stderr,"NetWare-Dienststeuerung benötigt root und Standard-Konfigurationspfad. Für Tests --no-services.\n");return 1;}umask(0077);char*parent=strdup(config_path);char*slash=strrchr(parent,'/');*slash=0;if(snprintf(auth_path,sizeof auth_path,"%s/.mars-web-auth.json",parent)>=(int)sizeof auth_path||snprintf(backup_dir,sizeof backup_dir,"%s/.mars-web-backups",parent)>=(int)sizeof backup_dir){free(parent);return 2;}char*lockname=NULL;asprintf(&lockname,"%s/.mars-vme.lock",parent);free(parent);int lockfd=open(lockname,O_CREAT|O_RDWR|O_CLOEXEC|O_NOFOLLOW,0600);free(lockname);if(lockfd<0||flock(lockfd,LOCK_EX|LOCK_NB)){fprintf(stderr,"Andere mars_vme-Instanz aktiv oder Lock nicht zugänglich.\n");return 1;}char*conf=read_file(config_path,MAX_CONF,0);if(!conf||auth_init()){fprintf(stderr,"Konfiguration oder Kennwortdatei nicht lesbar.\n");free(conf);return 1;} + if(reset){char*pw=getpass("Neues Web-Kennwort: ");char*first=pw?strdup(pw):NULL;pw=getpass("Wiederholen: ");int rc=!first||!pw||strcmp(first,pw)||auth_set(first,0);if(first){OPENSSL_cleanse(first,strlen(first));free(first);}free(conf);return rc?1:0;} + tls=*pem!=0;char listen[128];snprintf(listen,sizeof listen,"%s:%s%s",bind_ip,port,tls?"s":"");const char*options[24];int k=0;options[k++]="listening_ports";options[k++]=listen;options[k++]="num_threads";options[k++]="4";options[k++]="request_timeout_ms";options[k++]="10000";options[k++]="enable_keep_alive";options[k++]="no";options[k++]="enable_directory_listing";options[k++]="no";/* no document_root: only explicitly mapped assets */if(tls){options[k++]="ssl_certificate";options[k++]=pem;options[k++]="ssl_protocol_version";options[k++]="4";}options[k]=NULL;signal(SIGINT,on_signal);signal(SIGTERM,on_signal);signal(SIGPIPE,SIG_IGN);if(tls&&!(mg_init_library(MG_FEATURES_TLS)&MG_FEATURES_TLS)){fprintf(stderr,"CivetWeb TLS nicht verfügbar.\n");free(conf);return 1;}if(!tls)mg_init_library(0);struct mg_callbacks cb={0};cb.begin_request=begin_request;struct mg_context*ctx=mg_start(&cb,NULL,options);if(!ctx){fprintf(stderr,"CivetWeb Start fehlgeschlagen.\n");free(conf);mg_exit_library();return 1;}fprintf(stderr,"mars_vme: %s://%s:%s (CivetWeb); %s\n",tls?"https":"http",bind_ip,port,auth_default()?"Initialkennwort aktiv":"Kennwort eingerichtet");if(initial_start&&config_valid(conf))supervisor_request("start");else if(initial_start)fprintf(stderr,"NetWare wartet auf gültige Einrichtung.\n");free(conf);while(!quitting){supervisor_tick();usleep(100000);}mg_stop(ctx);supervisor_shutdown();mg_exit_library();close(lockfd);return 0;} diff --git a/native/print_stdin.c b/native/print_stdin.c new file mode 100644 index 0000000..a02400f --- /dev/null +++ b/native/print_stdin.c @@ -0,0 +1,9 @@ +#define _GNU_SOURCE +#include "admin.h" +#include +#include +#include +#include +#include +int rawprint(const char *,const char *); +int main(int argc,char **argv){if(argc!=3){fprintf(stderr,"usage: mars-print DEST filtered|raw|jetdirect\n");return 2;}char p[]="/tmp/mars-print-XXXXXX";int fd=mkstemp(p);if(fd<0)return 1;char b[65536];size_t total=0;int ok=1;ssize_t n;while((n=read(0,b,sizeof b))>0){total+=(size_t)n;if(total>512UL*1024*1024){ok=0;break;}ssize_t off=0;while(off +#include +#include +#include +#include +#include +#include +/* Stable public CUPS 2 ABI, see cups/cups.h. */ +typedef struct {char *name,*value;} opt; +typedef struct {char *name,*instance;int is_default,num_options;opt *options;} dest; +typedef struct {int id;char *dest,*title,*user,*format;int state,size,priority;time_t completed_time,creation_time,processing_time;} job; +static struct {void *h;int (*dests)(dest**);void (*freed)(int,dest*);const char *(*option)(const char*,int,opt*);int (*jobs)(job**,const char*,int,int);void (*freej)(int,job*);int (*print)(const char*,const char*,const char*,int,opt*);int (*cancel)(void*,const char*,int,int);int (*add)(const char*,const char*,int,opt**);void (*freeo)(int,opt*);const char *(*err)(void);int (*status)(void);} c; +static const char *no_password(const char *prompt,void *http,const char *method,const char *resource,void *data){(void)prompt;(void)http;(void)method;(void)resource;(void)data;return NULL;} +static int init(void){if(c.h)return 0;c.h=dlopen("libcups.so.2",RTLD_NOW|RTLD_LOCAL);if(!c.h)return -1; +#define LOAD(field,sym) do{*(void **)(&c.field)=dlsym(c.h,sym);if(!c.field)goto bad;}while(0) + LOAD(dests,"cupsGetDests");LOAD(freed,"cupsFreeDests");LOAD(option,"cupsGetOption");LOAD(jobs,"cupsGetJobs");LOAD(freej,"cupsFreeJobs");LOAD(print,"cupsPrintFile");LOAD(cancel,"cupsCancelJob2");LOAD(add,"cupsAddOption");LOAD(freeo,"cupsFreeOptions");LOAD(err,"cupsLastErrorString");LOAD(status,"cupsLastError");void (*setcb)(const char *(*)(const char*,void*,const char*,const char*,void*),void*)=NULL;*(void **)(&setcb)=dlsym(c.h,"cupsSetPasswordCB2");if(setcb)setcb(no_password,NULL);return 0; + bad:dlclose(c.h);memset(&c,0,sizeof c);return -1; +} +static int name_ok(const char *s){return s&&*s&&strlen(s)<=127&&strspn(s,"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-")==strlen(s);} +static json_object *fail(const char *s){json_object *o=json_object_new_object();addstr(o,"error",s?s:"CUPS-Fehler");return o;} +static void num(json_object*o,const char*k,long long v){json_object_object_add(o,k,json_object_new_int64(v));} +int print_submit(const char *d,const char *m,const char *f,const char *title){if(init()||!name_ok(d)||!m|| (strcmp(m,"raw")&&strcmp(m,"filtered")))return -1;opt *opts=NULL;int n=0;if(!strcmp(m,"raw"))n=c.add("raw","true",n,&opts);int id=c.print(d,f,title,n,opts);c.freeo(n,opts);return id>0?id:-1;} +json_object *print_call(json_object *r){const char *op=js(r,"op"),*d=js(r,"dest");if(init())return fail("libcups.so.2 fehlt (CUPS 2.x installieren)");if(!op)return fail("Aktion fehlt"); + if(!strcmp(op,"list")){dest *ds=NULL;job *jsv=NULL;int n=c.dests(&ds);int ds_status=c.status();if(n<0||(!n&&ds_status>=0x400)){if(n>0)c.freed(n,ds);return fail(c.err());}json_object *o=json_object_new_object(),*a=json_object_new_array(),*b=json_object_new_array();json_object_object_add(o,"printers",a);json_object_object_add(o,"jobs",b);for(int i=0;i=0x400)){addstr(o,"jobsError",c.err());}else{for(int i=0;i=0x400)return fail(c.err());return json_object_new_object();} + if(!strcmp(op,"test")){char p[]="/tmp/mars-test-XXXXXX";int fd=mkstemp(p);if(fd<0)return fail("Testdatei konnte nicht erstellt werden");const char *text="MARS NWE - CUPS Testseite\nNetWare Druckintegration\n\f";ssize_t z=write(fd,text,strlen(text));close(fd);int id=z==(ssize_t)strlen(text)?print_submit(d,"filtered",p,"MARS NWE Testseite"):-1;unlink(p);if(id<0)return fail(c.err());json_object *o=json_object_new_object();num(o,"id",id);return o;}return fail("Unbekannte Druckaktion");} diff --git a/native/rawprint.c b/native/rawprint.c new file mode 100644 index 0000000..f990df0 --- /dev/null +++ b/native/rawprint.c @@ -0,0 +1,12 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +/* Raw transport only for an explicitly configured numeric IPv4 printer. */ +int rawprint(const char *host,const char *file){struct sockaddr_in a={.sin_family=AF_INET,.sin_port=htons(9100)};if(inet_pton(AF_INET,host,&a.sin_addr)!=1)return -1;int fd=socket(AF_INET,SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC,0);if(fd<0)return -1;int in=-1,rc=-1,err=0;socklen_t el=sizeof err;struct pollfd p={fd,POLLOUT,0};if(connect(fd,(struct sockaddr*)&a,sizeof a)&&errno!=EINPROGRESS)goto end;if(poll(&p,1,5000)<=0||getsockopt(fd,SOL_SOCKET,SO_ERROR,&err,&el)||err)goto end;in=open(file,O_RDONLY|O_CLOEXEC|O_NOFOLLOW);if(in<0)goto end;char b[65536];ssize_t n;time_t deadline=time(NULL)+120;while((n=read(in,b,sizeof b))>0){ssize_t off=0;while(offdeadline||poll(&p,1,5000)<=0)goto end;ssize_t w=send(fd,b+off,n-off,MSG_NOSIGNAL);if(w<0&&(errno==EAGAIN||errno==EINTR))continue;if(w<=0)goto end;off+=w;}}if(n==0&&shutdown(fd,SHUT_WR)==0)rc=0;end:if(in>=0)close(in);close(fd);return rc;} diff --git a/native/supervisor.c b/native/supervisor.c new file mode 100644 index 0000000..fda68d5 --- /dev/null +++ b/native/supervisor.c @@ -0,0 +1,56 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#define _GNU_SOURCE +#include "supervisor.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +extern char **environ; +char broker_path[PATH_MAX]="/usr/local/sbin/mars-pcapd",server_path[PATH_MAX]="/usr/local/sbin/nwserv"; +int no_services; +static pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER; +static pid_t broker,server,server_group; +static int desired,stopping,failed; +static char server_revision[65]; +static time_t deadline; +static char detail[256]="Dateiserver gestoppt"; +#ifndef MARS_TEST_SOCKET +#define MARS_TEST_SOCKET "/run/mars-pcap/transport.sock" +#endif +static const char *socket_path=MARS_TEST_SOCKET; +#ifdef MARS_TESTING +void supervisor_test_socket(const char *p){socket_path=p;} +#endif +static time_t now(void){struct timespec t;clock_gettime(CLOCK_MONOTONIC,&t);return t.tv_sec;} +static int live(pid_t *pid){if(!*pid)return 0;int status;pid_t p=waitpid(*pid,&status,WNOHANG);if(p==0||(p<0&&errno==EINTR))return 1;*pid=0;return 0;} +static pid_t launch(char*path){posix_spawnattr_t a;posix_spawn_file_actions_t fa;pid_t p=0;sigset_t empty,defs;sigemptyset(&empty);sigemptyset(&defs);sigaddset(&defs,SIGINT);sigaddset(&defs,SIGTERM);sigaddset(&defs,SIGPIPE);posix_spawnattr_init(&a);posix_spawn_file_actions_init(&fa);posix_spawnattr_setflags(&a,POSIX_SPAWN_SETPGROUP|POSIX_SPAWN_SETSIGMASK|POSIX_SPAWN_SETSIGDEF);posix_spawnattr_setpgroup(&a,0);posix_spawnattr_setsigmask(&a,&empty);posix_spawnattr_setsigdefault(&a,&defs); +#if defined(__GLIBC__) && __GLIBC_PREREQ(2,34) + posix_spawn_file_actions_addclosefrom_np(&fa,3); +#endif + char *argv[]={path,NULL};int r=posix_spawn(&p,path,&fa,&a,argv,environ);posix_spawn_file_actions_destroy(&fa);posix_spawnattr_destroy(&a);if(r){snprintf(detail,sizeof detail,"Start fehlgeschlagen: %s",strerror(r));return 0;}return p;} +static int ready(void){struct stat st;if(lstat(socket_path,&st)||!S_ISSOCK(st.st_mode)||st.st_uid!=geteuid())return 0;int fd=socket(AF_UNIX,SOCK_SEQPACKET|SOCK_CLOEXEC|SOCK_NONBLOCK,0);if(fd<0)return 0;struct sockaddr_un a={.sun_family=AF_UNIX};if(strlen(socket_path)>=sizeof a.sun_path){close(fd);return 0;}strcpy(a.sun_path,socket_path);int ok=connect(fd,(struct sockaddr*)&a,sizeof a)==0;close(fd);return ok;} +static void terminate(pid_t p,int sig){if(p>0)kill(p,sig);} +static void group_signal(pid_t p,int sig){if(p>0)kill(-p,sig);} +static void begin_stop(void){if(stopping)return;stopping=1;deadline=now()+30;if(server)terminate(server,SIGTERM);snprintf(detail,sizeof detail,"Dateiserver wird beendet");} +int supervisor_request(const char *s){if(no_services||!s)return -1;pthread_mutex_lock(&lock);int r=0;if(!strcmp(s,"start")){desired=1;failed=0;}else if(!strcmp(s,"stop")){desired=0;failed=0;if(server||broker)begin_stop();}else if(!strcmp(s,"restart")){desired=1;failed=0;if(server||broker)begin_stop();}else r=-1;pthread_mutex_unlock(&lock);return r;} +void supervisor_tick(void){pthread_mutex_lock(&lock);int oldb=broker!=0,olds=server!=0;live(&broker);live(&server);if(!stopping&&((oldb&&!broker)||(olds&&!server))){desired=0;failed=1;begin_stop();snprintf(detail,sizeof detail,"NetWare- oder PCAP-Prozess beendet; Log prüfen");} + if(stopping){if(server&&now()>=deadline){group_signal(server_group,SIGKILL);terminate(server,SIGKILL);}if(!server){/* Clean up surviving original MARS children after parent shut down. */if(server_group){group_signal(server_group,SIGKILL);server_group=0;}if(broker){terminate(broker,now()>deadline+5?SIGKILL:SIGTERM);}else{stopping=0;if(!failed)snprintf(detail,sizeof detail,"Dateiserver gestoppt");}}} + if(!stopping&&desired&&!broker){if(ready()){desired=0;failed=1;snprintf(detail,sizeof detail,"Vorhandener PCAP-Socket; alten Dienst zuerst stoppen");}else{broker=launch(broker_path);deadline=now()+10;if(!broker){desired=0;failed=1;}else snprintf(detail,sizeof detail,"PCAP startet");}} + if(!stopping&&desired&&broker&&!server){if(ready()){char *cfg=read_file(config_path,MAX_CONF,0);server_revision[0]=0;if(cfg){sha(cfg,server_revision);free(cfg);}server=launch(server_path);server_group=server;if(!server){desired=0;failed=1;begin_stop();}else snprintf(detail,sizeof detail,"NetWare-Prozess gestartet; Client-Test erforderlich");}else if(now()>=deadline){desired=0;failed=1;begin_stop();snprintf(detail,sizeof detail,"PCAP-Socket nicht bereit");}} + pthread_mutex_unlock(&lock);} +int supervisor_config_matches(void){char *cfg=read_file(config_path,MAX_CONF,0);char hash[65]={0};if(cfg){sha(cfg,hash);free(cfg);}pthread_mutex_lock(&lock);int ok=server&&!stopping&&*hash&&!strcmp(hash,server_revision);pthread_mutex_unlock(&lock);return ok;} +void supervisor_shutdown(void){if(no_services)return;supervisor_request("stop");for(int i=0;i<380;i++){supervisor_tick();pthread_mutex_lock(&lock);int done=!server&&!broker&&!stopping;pthread_mutex_unlock(&lock);if(done)return;usleep(100000);}pthread_mutex_lock(&lock);group_signal(server_group,SIGKILL);terminate(server,SIGKILL);terminate(broker,SIGKILL);pthread_mutex_unlock(&lock);} +json_object *supervisor_status(void){pthread_mutex_lock(&lock);json_object*o=json_object_new_object();char a[512],b[128];snprintf(a,sizeof a,"ActiveState=%s\nSubState=%s\nPID=%d\n%s",server?(stopping?"deactivating":"active"):(failed?"failed":(desired?"activating":"inactive")),server?"process-running":"dead",server,detail);snprintf(b,sizeof b,"ActiveState=%s\nPID=%d",broker?(stopping?"deactivating":(ready()?"active":"activating")):"inactive",broker);addstr(o,"mars-nwe-pcap.service",a);addstr(o,"mars-pcapd.service",b);addstr(o,"unit","mars_vme.service");pthread_mutex_unlock(&lock);return o;} +static void file_field(json_object*o,const char*k,const char*p){char*s=read_file(p,MAX_CONF,0);addstr(o,k,s?s:"Nicht verfügbar");free(s);} +static void utilization(json_object*o){static unsigned long long last_total,last_idle;unsigned long long v[8]={0};char*cpu=read_file("/proc/stat",MAX_CONF,0);if(cpu&&sscanf(cpu,"cpu %llu %llu %llu %llu %llu %llu %llu %llu",&v[0],&v[1],&v[2],&v[3],&v[4],&v[5],&v[6],&v[7])>=4){unsigned long long total=0,idle=v[3]+v[4];for(int i=0;i<8;i++)total+=v[i];if(last_total&&total>last_total&&idle>=last_idle&&idle-last_idle<=total-last_total){char b[64];snprintf(b,sizeof b,"%.1f %% (seit letzter Abfrage)",100.0*(1.0-(double)(idle-last_idle)/(double)(total-last_total)));addstr(o,"CPU-Auslastung",b);}else addstr(o,"CPU-Auslastung","Nächste Abfrage für Messwert abwarten");last_total=total;last_idle=idle;}free(cpu);char*m=read_file("/proc/meminfo",MAX_CONF,0);if(m){unsigned long long total=0,avail=0;const char*a=strstr(m,"MemAvailable:");sscanf(m,"MemTotal: %llu",&total);if(a)sscanf(a,"MemAvailable: %llu",&avail);if(a&&total&&avail<=total){char b[128];snprintf(b,sizeof b,"%.1f %% (%llu von %llu MiB)",100.0*(double)(total-avail)/total,(total-avail)/1024,total/1024);addstr(o,"RAM-Auslastung",b);}free(m);}} +static void journal_field(json_object*o){FILE*f=popen("/usr/bin/journalctl --no-pager -q -u mars_vme.service -n 80 -o short-iso 2>/dev/null","r");if(!f){addstr(o,"logs","Journal nicht verfügbar");return;}char buf[32769];size_t n=fread(buf,1,sizeof buf-1,f);buf[n]=0;/* drain bounded producer to avoid pipe blocking */char drain[4096];while(fread(drain,1,sizeof drain,f)>0){}pclose(f);addstr(o,"logs",n?buf:"Journal nicht verfügbar");} +json_object *monitor_data(void){json_object*o=supervisor_status();utilization(o);file_field(o,"memory","/proc/meminfo");file_field(o,"cpu","/proc/stat");file_field(o,"load","/proc/loadavg");journal_field(o);pthread_mutex_lock(&lock);int running=broker!=0;pthread_mutex_unlock(&lock);if(running){file_field(o,"interfaces","/run/mars-pcap/ipx_interface");file_field(o,"sockets","/run/mars-pcap/ipx");file_field(o,"routes","/run/mars-pcap/ipx_route");file_field(o,"packets","/run/mars-pcap/stats");file_field(o,"sap","/run/mars-pcap/sap");file_field(o,"nodes","/run/mars-pcap/nodes");}return o;} diff --git a/native/supervisor.h b/native/supervisor.h new file mode 100644 index 0000000..d7a71d1 --- /dev/null +++ b/native/supervisor.h @@ -0,0 +1,13 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef MARS_SUPERVISOR_H +#define MARS_SUPERVISOR_H +#include "core.h" +extern int no_services; +extern char broker_path[PATH_MAX], server_path[PATH_MAX]; +void supervisor_tick(void); +int supervisor_config_matches(void); +int supervisor_request(const char *); +void supervisor_shutdown(void); +json_object *supervisor_status(void); +json_object *monitor_data(void); +#endif diff --git a/nwserv-pcap.conf.example b/nwserv-pcap.conf.example new file mode 100644 index 0000000..78c525d --- /dev/null +++ b/nwserv-pcap.conf.example @@ -0,0 +1,12 @@ +# Replace corresponding entries in installed nwserv.conf, not the entire file! +# Use unique external IPX net numbers, and a real Ethernet interface name. +2 MARS_PCAP +3 0x12345678 1 +4 0x101 enp3s0 802.3 1 +4 0x102 enp3s0 802.2 1 +4 0x103 enp3s0 ETHERNET_II 1 +4 0x104 enp3s0 SNAP 1 +5 0 +200 0 +# Also configure section 12 supervisor password, volume section 1, users, paths, +# and station restrictions in the original configuration before starting. diff --git a/patch-upstream.sh b/patch-upstream.sh new file mode 100755 index 0000000..3e3481c --- /dev/null +++ b/patch-upstream.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +set -euo pipefail +root=$(realpath "$1") +here=$(cd "$(dirname "$0")" && pwd) +for f in src/emutli.c src/emutli1.c src/CMakeLists.txt include/emutli.h include/net.h; do test -f "$root/$f" || { echo "Unsupported source layout: $f" >&2; exit 1; }; done +if grep -q MARS_PCAP_PORT_V1 "$root/src/CMakeLists.txt"; then echo 'Already patched' >&2; exit 1; fi +for f in "$root/src/emutli.c" "$root/src/emutli1.c"; do + grep -Fq '#include "net.h"' "$f" && grep -Fq 'socket(AF_IPX' "$f" || { echo "Unexpected source version: $f" >&2; exit 1; } + sed -i '0,/#include "net.h"/s//#include "net.h"\n#include "mars_pcap_shim.h"/' "$f" + sed -Ei 's/\b(socket|bind|getsockname|setsockopt|sendto|recvfrom|ioctl)[[:space:]]*\(/mars_\1(/g' "$f" +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 +cp "$here/src/shim.h" "$root/include/mars_pcap_shim.h" +cat >> "$root/src/CMakeLists.txt" <<'CMAKE' +# MARS_PCAP_PORT_V1 +set(MARS_PCAP_LIBRARY "" CACHE FILEPATH "PCAP socket adapter") +if(NOT EXISTS "${MARS_PCAP_LIBRARY}") + message(FATAL_ERROR "MARS_PCAP_LIBRARY is required") +endif() +foreach(t nwserv nwconn ncpserv nwclient nwbind nwrouted dbmtool) + if(TARGET ${t}) + target_link_libraries(${t} "${MARS_PCAP_LIBRARY}") + endif() +endforeach() +CMAKE +printf 'Patched MARS_NWE transport.\n' +# Live admin adapter in nwbind's own serialized event loop. +f="$root/src/nwbind.c" +for anchor in 'int main(int argc, char *argv[])' ' set_sig();' 'if (t_rcvudata(ncp_fd, &ud, &rcv_flags) > -1)' ' nw_exit_dbm();'; do + [[ $(grep -Fc "$anchor" "$f") == 1 ]] || { echo "Unsupported nwbind anchor: $anchor" >&2; exit 1; } +done +cp "$here/upstream-adapter/"mars_{admin,scripts,acl}.inc "$root/src/" +sed -i '1i #ifndef _GNU_SOURCE\n#define _GNU_SOURCE\n#endif' "$f" +sed -i '/^int main(int argc, char \*argv\[\])/i #include "mars_admin.inc"' "$f" +sed -i '/^ set_sig();/a\ ma_init();' "$f" +sed -i 's/if (t_rcvudata(ncp_fd, \&ud, \&rcv_flags) > -1)/if (ma_wait(ncp_fd) \&\& t_rcvudata(ncp_fd, \&ud, \&rcv_flags) > -1)/' "$f" +sed -i '/^ nw_exit_dbm();/i\ ma_close();' "$f" +cat >> "$root/src/CMakeLists.txt" <<'CMAKE' +find_package(PkgConfig REQUIRED) +pkg_check_modules(MARS_JSON REQUIRED IMPORTED_TARGET json-c) +if(NOT TARGET nwbind) + message(FATAL_ERROR "nwbind target missing") +endif() +target_link_libraries(nwbind PkgConfig::MARS_JSON) +CMAKE +# Keep original spool file on a non-zero print subprocess exit. +f="$root/src/nwqconn.c" +[[ $(grep -Fc 'if (0 != (k=ext_pclose(fp))) {' "$f") == 1 ]] || { echo 'Unsupported nwqconn print hook' >&2; exit 1; } +sed -i '/if (0 != (k=ext_pclose(fp))) {/a\ is_ok=0; /* keep spool file on failed submission */' "$f" +printf 'Patched live Bindery administration and print error handling.\n' + +# Extend upstream ftrustee, using its own original volume/trustee routines. +f="$root/src/ftrustee.c" +[[ $(grep -Fc 'int main(int argc, char *argv[])' "$f") == 1 && $(grep -Fc ' localinit();' "$f") == 1 ]] || { echo 'Unsupported ftrustee layout' >&2; exit 1; } +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" diff --git a/rebuild.sh b/rebuild.sh new file mode 100755 index 0000000..8ee94fa --- /dev/null +++ b/rebuild.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")" +rm -rf -- upstream/patched upstream/build +exec ./build.sh "$@" diff --git a/run-ipc-test.sh b/run-ipc-test.sh new file mode 100755 index 0000000..1d12ecb --- /dev/null +++ b/run-ipc-test.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")" +[[ $EUID == 0 ]] || { echo 'Use sudo ./run-ipc-test.sh (no server running)' >&2; exit 1; } +[[ ! -S /run/mars-pcap/transport.sock ]] || { echo 'A broker socket exists; stop it before running the test' >&2; exit 1; } +[[ -x build/test-ipc && -x build/mars-pcapd ]] || { echo 'Run make check first as regular user' >&2; exit 1; } +./build/mars-pcapd --offline-test & pid=$! +trap 'kill "$pid" 2>/dev/null || true; wait "$pid" 2>/dev/null || true' EXIT +for i in $(seq 1 50); do [[ -S /run/mars-pcap/transport.sock ]] && break; sleep .1; done +./build/test-ipc diff --git a/src/broker.c b/src/broker.c new file mode 100644 index 0000000..d866986 --- /dev/null +++ b/src/broker.c @@ -0,0 +1,80 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#define _GNU_SOURCE +#include "wire.h" +#include "pcap_dyn.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define NC 1024 +#define NI 32 +#define NR 512 +struct client {int fd;uint16_t port;}; +struct iface {uint32_t net;int kind,special,fd;char dev[16];uint8_t mac[6];pcap_t *pc;}; +struct route {uint32_t dst,via;uint8_t mac[6];time_t expires;}; +static struct client clients[NC];static struct iface ifs[NI];static struct route routes[NR];static struct pcap_api pc;static int offline,forwarding;static volatile sig_atomic_t stop;static unsigned long dropped;static uint16_t nextport=0x4000; +/* Bounded monitoring: packet metadata only, not payload or login data. */ +struct observation {uint32_t net;uint8_t node[6];time_t last;unsigned long packets;}; +struct sap_observation {uint16_t type,port,hops;uint32_t net;uint8_t node[6];char name[49];time_t last;}; +static struct observation peers[256];static struct sap_observation sap_seen[128]; +static unsigned long rx_frames[256],tx_frames[256]; +static void observe_peer(const struct sockaddr_ipx *a){time_t t=time(NULL);int slot=0;for(int i=0;i<256;i++){if(peers[i].net==a->sipx_network&&!memcmp(peers[i].node,a->sipx_node,6)){slot=i;goto found;}if(peers[i].lastsipx_network};memcpy(peers[slot].node,a->sipx_node,6);found:peers[slot].last=t;peers[slot].packets++;} +static void observe_sap(const uint8_t*p,size_t n){if(n<2||((get16(p)!=2)&&(get16(p)!=4)))return;p+=2;n-=2;while(n>=64){struct sap_observation q={.type=get16(p),.port=get16(p+60),.hops=get16(p+62),.last=time(NULL)};memcpy(&q.net,p+50,4);memcpy(q.node,p+54,6);for(int j=0;j<48&&p[2+j];j++){unsigned c=p[2+j];q.name[j]=c>=32&&c<=126?(char)c:'?';}int slot=0;for(int i=0;i<128;i++){if(sap_seen[i].type==q.type&&sap_seen[i].net==q.net&&!memcmp(sap_seen[i].node,q.node,6)&&!strcmp(sap_seen[i].name,q.name)){slot=i;break;}if(sap_seen[i].lastlast||t-a->last>180)continue;fprintf(f,"%04X %s %08X ",a->type,a->name,ntohl(a->net));for(int j=0;j<6;j++)fprintf(f,"%02X",a->node[j]);fprintf(f," %04X %u %ld\n",a->port,a->hops,(long)(t-a->last));}}if(fclose(f)==0)rename(temp,files[k]);else unlink(temp);}} +static struct iface *primary(void){for(int i=0;inet){fprintf(f,"%08X ",ntohl(a->net));for(int j=0;j<6;j++)fprintf(f,"%02X",a->mac[j]);fprintf(f," %s %s %s\n",a==p?"Yes":"No",a->dev,frname(a->kind));}}}else if(k==1){fprintf(f,"Local_Address\n");for(int i=0;i=0&&clients[i].port)fprintf(f,"%08X:%04X\n",p?ntohl(p->net):0,clients[i].port);}else{fprintf(f,"Network Router_Net Router_Node\n");for(int i=0;itime(NULL)){fprintf(f,"%08X %08X ",ntohl(routes[i].dst),ntohl(routes[i].via));for(int j=0;j<6;j++)fprintf(f,"%02X",routes[i].mac[j]);fputc('\n',f);}}if(fclose(f)==0)rename(tmp,names[k]);else unlink(tmp);}} +static void drop_client(int i){if(clients[i].fd>=0){int bound=clients[i].port;close(clients[i].fd);clients[i].fd=-1;clients[i].port=0;if(bound)write_state();}} +static int port_owner(uint16_t p){for(int i=0;i=0&&clients[i].port==p)return i;return -1;} +static void reap(void){for(int i=0;i=0){struct pollfd p={clients[i].fd,POLLIN,0};if(poll(&p,1,0)>0&&(p.revents&(POLLHUP|POLLERR))&&!(p.revents&POLLIN))drop_client(i);else if(p.revents&POLLHUP){char c;if(recv(clients[i].fd,&c,1,MSG_PEEK|MSG_DONTWAIT)==0)drop_client(i);}}} +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 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; + for(int i=0;isipx_network,.kind=a->sipx_type,.special=a->sipx_special,.fd=-1}; + 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;} +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 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); + 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 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;} + /* Process capture before commands which may close/reopen interfaces. */for(int k=1;k=0)close(clients[i].fd); + for(int i=0;i +#include +int pcap_load(struct pcap_api *p){const char *names[]={"libpcap.so.1","libpcap.so.0.8","libpcap.so",NULL};for(int i=0;names[i]&&!p->lib;i++)p->lib=dlopen(names[i],RTLD_NOW|RTLD_LOCAL);if(!p->lib){fprintf(stderr,"libpcap: %s\n",dlerror());return -1;} +#define GET(x) do{*(void **)(&p->x)=dlsym(p->lib,"pcap_" #x);if(!p->x){fprintf(stderr,"Missing pcap_%s\n",#x);dlclose(p->lib);return -1;}}while(0) + GET(open_live);GET(datalink);GET(setnonblock);GET(setdirection);GET(get_selectable_fd);GET(next_ex);GET(inject);GET(geterr);GET(close);return 0; +#undef GET +} diff --git a/src/pcap_dyn.h b/src/pcap_dyn.h new file mode 100644 index 0000000..265aa19 --- /dev/null +++ b/src/pcap_dyn.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef PCAP_DYN_H +#define PCAP_DYN_H +#include +#include +#include +/* Public libpcap ABI subset. No private structs are accessed. */ +typedef struct pcap pcap_t; +struct pcap_pkthdr {struct timeval ts;uint32_t caplen,len;}; +struct pcap_api {void *lib;pcap_t *(*open_live)(const char *,int,int,int,char *);int (*datalink)(pcap_t *);int (*setnonblock)(pcap_t *,int,char *);int (*setdirection)(pcap_t *,int);int (*get_selectable_fd)(pcap_t *);int (*next_ex)(pcap_t *,struct pcap_pkthdr **,const unsigned char **);int (*inject)(pcap_t *,const void *,size_t);char *(*geterr)(pcap_t *);void (*close)(pcap_t *);}; +int pcap_load(struct pcap_api *); +#endif diff --git a/src/shim.c b/src/shim.c new file mode 100644 index 0000000..fcb59bd --- /dev/null +++ b/src/shim.c @@ -0,0 +1,28 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#define _GNU_SOURCE +#include "wire.h" +#include "shim.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +static int conn(void){int fd=socket(AF_UNIX,SOCK_SEQPACKET,0);if(fd<0)return -1;struct sockaddr_un u={.sun_family=AF_UNIX,.sun_path=IPC_PATH};if(connect(fd,(void*)&u,sizeof u)<0){int e=errno;close(fd);errno=e;return -1;}return fd;} +static int sendmsg0(int fd,struct msg *m){m->magic=IPC_MAGIC;ssize_t n=send(fd,m,MSG_HEAD+m->len,MSG_NOSIGNAL);return n==(ssize_t)(MSG_HEAD+m->len)?0:-1;} +static int recmsg0(int fd,struct msg *m,int flags){ssize_t n=recv(fd,m,sizeof *m,flags|MSG_TRUNC);if(n<0)return -1;if(!n){errno=ECONNRESET;return -1;}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){errno=EPROTO;return -1;}return 0;} +static int rpc(int fd,struct msg *m){if(sendmsg0(fd,m)<0)return -1;struct pollfd p={fd,POLLIN,0};int n;do{n=poll(&p,1,5000);}while(n<0&&errno==EINTR);if(n<=0){if(!n)errno=ETIMEDOUT;return -1;}if(recmsg0(fd,m,0)<0)return -1;if(m->op!=M_REPLY){errno=EPROTO;return -1;}if(m->status){errno=m->status;return -1;}return 0;} +/* Only t_bind's immediate getsockname needs this cache. Data I/O uses the fd + * itself, including descriptors inherited by fork/exec/dup2. */ +static struct {int fd; ino_t ino; struct sockaddr_ipx a;} last={.fd=-1}; +int mars_socket(int family,int type,int protocol){if(family!=AF_IPX)return socket(family,type,protocol);if((type&15)!=SOCK_DGRAM){errno=EPROTONOSUPPORT;return -1;}return conn();} +int mars_bind(int fd,const struct sockaddr *a,socklen_t l){if(!a||lsa_family!=AF_IPX){errno=EINVAL;return -1;}struct msg m={.op=M_BIND};memcpy(&m.addr,a,sizeof m.addr);if(rpc(fd,&m)<0)return -1;struct stat st;if(fstat(fd,&st)<0)return -1;last.fd=fd;last.ino=st.st_ino;last.a=m.addr;return 0;} +int mars_getsockname(int fd,struct sockaddr *a,void *l){socklen_t *n=l;struct stat st;if(!a||!n||*nsa_family!=AF_IPX){errno=EINVAL;return -1;}if(n>IPX_MAX-IPX_HDR){errno=EMSGSIZE;return -1;}struct msg m={.op=M_SEND,.len=n};memcpy(&m.addr,a,sizeof m.addr);if(n)memcpy(m.data,p,n);return sendmsg0(fd,&m)<0?-1:(ssize_t)n;} +ssize_t mars_recvfrom(int fd,void *p,size_t n,int flags,struct sockaddr *a,void *l){struct msg m;if(recmsg0(fd,&m,flags)<0)return -1;if(m.op!=M_DATA){errno=EPROTO;return -1;}if(a&&l){socklen_t *sz=l;size_t k=*szifr_name,sizeof m.dev);memcpy(&m.addr,&r->ifr_addr,sizeof m.addr);break;}case SIOCADDRT:case SIOCDELRT:{struct rtentry *r=arg;struct sockaddr_ipx dst;memcpy(&dst,&r->rt_dst,sizeof dst);m.op=M_ROUTE;m.net=dst.sipx_network;if(op==SIOCADDRT)memcpy(&m.addr,&r->rt_gateway,sizeof m.addr);break;}case SIOCIPXCFGDATA:m.op=M_CFG;break;case SIOCAIPXITFCRT:case SIOCAIPXPRISLT:m.op=M_AUTO;m.net=*(int*)arg;break;default:errno=ENOTTY;return -1;} + int c=conn();if(c<0)return -1;int ret=rpc(c,&m),e=errno;close(c);errno=e;if(!ret&&op==SIOCIPXCFGDATA){ipx_config_data *d=arg;d->ipxcfg_auto_create_interfaces=0;d->ipxcfg_auto_select_primary=0;}return ret;} diff --git a/src/shim.h b/src/shim.h new file mode 100644 index 0000000..f9bc691 --- /dev/null +++ b/src/shim.h @@ -0,0 +1,13 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef MARS_PCAP_SHIM_H +#define MARS_PCAP_SHIM_H +#include +#include +int mars_socket(int,int,int); +int mars_bind(int,const struct sockaddr *,socklen_t); +int mars_getsockname(int,struct sockaddr *,void *); +int mars_setsockopt(int,int,int,const void *,socklen_t); +ssize_t mars_sendto(int,const void *,size_t,int,const struct sockaddr *,socklen_t); +ssize_t mars_recvfrom(int,void *,size_t,int,struct sockaddr *,void *); +int mars_ioctl(int,unsigned long,void *); +#endif diff --git a/src/wire.c b/src/wire.c new file mode 100644 index 0000000..ac8b42f --- /dev/null +++ b/src/wire.c @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#include "wire.h" +static const uint8_t llc[]={0xe0,0xe0,3},snap[]={0xaa,0xaa,3,0,0,0,0x81,0x37}; +int frame_decode(const uint8_t *b,size_t n,int *kind,const uint8_t **p,size_t *len){ + if(n<14)return -1; + size_t off=14, avail=n-14; uint16_t t=get16(b+12); + if(t==0x8137)*kind=IPX_FRAME_ETHERII; + else if(t<=1500){if(t>avail)return -1;avail=t; + if(avail>=sizeof snap&&!memcmp(b+off,snap,sizeof snap)){*kind=IPX_FRAME_SNAP;off+=sizeof snap;avail-=sizeof snap;} + else if(avail>=sizeof llc&&!memcmp(b+off,llc,sizeof llc)){*kind=IPX_FRAME_8022;off+=sizeof llc;avail-=sizeof llc;} + else if(avail>=2&&get16(b+off)==0xffff)*kind=IPX_FRAME_8023;else return -1; + }else return -1; + if(availavail||l>IPX_MAX||b[off+4]>=16)return -1; + /* Classic NetWare uses disabled checksum (FFFF). Reject unsupported checksums. */ + if(get16(b+off)!=0xffff)return -1; + *p=b+off;*len=l;return 0; +} +int frame_encode(uint8_t *b,size_t cap,int k,const uint8_t *dm,const uint8_t *sm,const uint8_t *p,size_t n){ + size_t extra=0;const uint8_t *h=NULL; + switch(k){case IPX_FRAME_ETHERII:case IPX_FRAME_8023:break;case IPX_FRAME_8022:extra=sizeof llc;h=llc;break;case IPX_FRAME_SNAP:extra=sizeof snap;h=snap;break;default:return -1;} + if(n1500||get16(p+2)!=n)return -1; + size_t total=14+extra+n, padded=total<60?60:total;if(capIPX_MAX-IPX_HDR||capsipx_type;write_addr(b+6,dst);write_addr(b+18,src);if(n)memcpy(b+30,data,n);return n+30; +} diff --git a/src/wire.h b/src/wire.h new file mode 100644 index 0000000..dea4f06 --- /dev/null +++ b/src/wire.h @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#ifndef MARS_PCAP_WIRE_H +#define MARS_PCAP_WIRE_H +#include +#include +#include +#include +#include +#define IPX_HDR 30 +#define IPX_MAX 8192 +#define IPC_PATH "/run/mars-pcap/transport.sock" +#define IPC_DIR "/run/mars-pcap" +#define IPC_MAGIC 0x4d495058u +/* Local IPC only: same host ABI, never serialized directly to Ethernet. */ +enum { M_BIND=1, M_SEND, M_DATA, M_REPLY, M_IFACE, M_ROUTE, M_AUTO, M_CFG }; +struct msg { uint32_t magic, op; int32_t status; uint32_t len; struct sockaddr_ipx addr; uint32_t net; char dev[16]; uint8_t data[IPX_MAX]; }; +#define MSG_HEAD offsetof(struct msg,data) +static inline uint16_t get16(const uint8_t *p){return ((uint16_t)p[0]<<8)|p[1];} +static inline uint32_t get32(const uint8_t *p){return ((uint32_t)get16(p)<<16)|get16(p+2);} +static inline void put16(uint8_t *p,uint16_t n){p[0]=n>>8;p[1]=n;} +static inline void put32(uint8_t *p,uint32_t n){put16(p,n>>16);put16(p+2,n);} +static inline int isbc(const uint8_t *p){static const uint8_t bc[6]={255,255,255,255,255,255};return !memcmp(p,bc,6);} +static inline int iszero(const uint8_t *p){static const uint8_t z[6]={0};return !memcmp(p,z,6);} +static inline void read_addr(struct sockaddr_ipx *a,const uint8_t *p,uint8_t type){memset(a,0,sizeof *a);a->sipx_family=AF_IPX;memcpy(&a->sipx_network,p,4);memcpy(a->sipx_node,p+4,6);memcpy(&a->sipx_port,p+10,2);a->sipx_type=type;} +static inline void write_addr(uint8_t *p,const struct sockaddr_ipx *a){memcpy(p,&a->sipx_network,4);memcpy(p+4,a->sipx_node,6);memcpy(p+10,&a->sipx_port,2);} +int frame_decode(const uint8_t *,size_t,int *,const uint8_t **,size_t *); +int frame_encode(uint8_t *,size_t,int,const uint8_t *,const uint8_t *,const uint8_t *,size_t); +int ipx_make(uint8_t *,size_t,const struct sockaddr_ipx *,const struct sockaddr_ipx *,const void *,size_t); +#endif diff --git a/tests/test_ipc.c b/tests/test_ipc.c new file mode 100644 index 0000000..a57c322 --- /dev/null +++ b/tests/test_ipc.c @@ -0,0 +1,19 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#include "wire.h" +#include "shim.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +static int op(void){int fd=mars_socket(AF_IPX,SOCK_DGRAM,AF_IPX);assert(fd>=0);return fd;} +static int bindp(int fd,int port,struct sockaddr_ipx *a){memset(a,0,sizeof *a);a->sipx_family=AF_IPX;a->sipx_port=htons(port);int r=mars_bind(fd,(void*)a,sizeof *a);if(!r){socklen_t n=sizeof *a;assert(!mars_getsockname(fd,(void*)a,&n));}return r;} +int main(int argc,char **argv){if(argc==2){int fd=atoi(argv[1]);struct pollfd p={fd,POLLIN,0};assert(poll(&p,1,3000)==1);struct sockaddr_ipx a;socklen_t l=sizeof a;char buf[32];assert(mars_recvfrom(fd,buf,sizeof buf,0,(void*)&a,&l)==4);assert(!memcmp(buf,"ping",4)&&a.sipx_type==17);assert(mars_sendto(fd,"pong",4,0,(void*)&a,sizeof a)==4);return 0;} + int ctl=op();struct sockaddr_ipx a,b;assert(bindp(ctl,0x451,&a)<0&&errno==EADDRNOTAVAIL);struct ifreq r={0};struct sockaddr_ipx v={.sipx_family=AF_IPX,.sipx_network=htonl(0x12345678),.sipx_special=IPX_INTERNAL,.sipx_action=IPX_CRTITF,.sipx_node={0,0,0,0,0,1}};memcpy(&r.ifr_addr,&v,sizeof v);assert(!mars_ioctl(ctl,SIOCSIFADDR,&r));for(int k=1;k<=4;k++){memset(&r,0,sizeof r);strcpy(r.ifr_name,"test0");v.sipx_network=htonl(0x100+k);v.sipx_type=k;v.sipx_special=IPX_SPECIAL_NONE;memcpy(&r.ifr_addr,&v,sizeof v);assert(!mars_ioctl(ctl,SIOCSIFADDR,&r));}struct rtentry rt={0};v.sipx_network=htonl(0x200);memcpy(&rt.rt_dst,&v,sizeof v);v.sipx_network=htonl(0x101);v.sipx_node[0]=2;memcpy(&rt.rt_gateway,&v,sizeof v);assert(!mars_ioctl(ctl,SIOCADDRT,&rt));assert(!mars_ioctl(ctl,SIOCDELRT,&rt));close(ctl); + int x=op(),y=op(),z=op();assert(!bindp(x,0x451,&a));assert(a.sipx_network==htonl(0x12345678));assert(!bindp(y,0,&b));struct sockaddr_ipx tmp;assert(bindp(z,0x451,&tmp)<0&&errno==EADDRINUSE);close(z);pid_t pid=fork();assert(pid>=0);if(!pid){close(y);char arg[20];snprintf(arg,sizeof arg,"%d",x);execl(argv[0],argv[0],arg,NULL);_exit(1);}close(x);a.sipx_type=17;assert(mars_sendto(y,"ping",4,0,(void*)&a,sizeof a)==4);struct pollfd pp={y,POLLIN,0};assert(poll(&pp,1,4000)==1);char buf[16];socklen_t l=sizeof a;assert(mars_recvfrom(y,buf,sizeof buf,0,(void*)&a,&l)==4);assert(!memcmp(buf,"pong",4)&&ntohs(a.sipx_port)==0x451);int status;waitpid(pid,&status,0);assert(WIFEXITED(status)&&!WEXITSTATUS(status));close(y);int again=op();assert(!bindp(again,0x451,&tmp));close(again);puts("PASS: internal interface, all external interface registrations, route add/delete, bind conflict, ephemeral port, fork/exec and rebind");return 0;} diff --git a/tests/test_native.c b/tests/test_native.c new file mode 100644 index 0000000..dad7e37 --- /dev/null +++ b/tests/test_native.c @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#define _GNU_SOURCE +#include "core.h" +#include +#include +#include +#include +#include +#include +int main(void){char tmp[]="/tmp/mars-native-test-XXXXXX";assert(mkdtemp(tmp));snprintf(config_path,sizeof config_path,"%s/nwserv.conf",tmp);snprintf(auth_path,sizeof auth_path,"%s/.mars-web-auth.json",tmp);snprintf(backup_dir,sizeof backup_dir,"%s/.mars-web-backups",tmp); + const char*orig="# preserve\r\n2 OLD\r\n99 keep exactly\r\n12 SUPERVISOR root SecretPass\r\n200 0\r\n";assert(!atomic_write(config_path,orig,strlen(orig),0600));json_object*g=groups(orig);assert(!strcmp(json_object_get_string(json_object_array_get_idx(get(g,"2"),0)),"OLD"));char*unchanged=merge(orig,g);assert(unchanged&&!strcmp(unchanged,orig));free(unchanged);json_object_put(g); + g=json_tokener_parse("{\"2\":[\"NEW\"],\"13\":[\"TEST nobody TestPass123\"]}");char*next=merge(orig,g);assert(next&&strstr(next,"2 NEW\r\n")&&strstr(next,"99 keep exactly\r\n")&&strstr(next,"13 TEST nobody TestPass123\r\n"));json_object_put(g);g=json_tokener_parse("{\"2\":[\"BAD\\n4 invalid\"]}");assert(!merge(orig,g));json_object_put(g);puts("PASS merge, CRLF, unknown lines, injection rejection"); + char h[65],name[64];sha(orig,h);assert(!save_conf(orig,h,next,name));assert(*name);char*b=backup_read(name);assert(b&&!strcmp(b,orig));free(b);g=backups();assert(json_object_array_length(g)==1);json_object_put(g);assert(save_conf(orig,h,"stale",name)==-2);assert(!backup_read("../../etc/shadow"));char*cur=read_file(config_path,MAX_CONF,1);assert(cur&&!strcmp(cur,next));free(cur);free(next);puts("PASS backup, revision conflict, private file, traversal rejection"); + assert(!auth_init());assert(auth_default());assert(auth_verify("admin"));assert(!auth_verify("wrong"));assert(auth_set("short",0));assert(!auth_set("ChangedPassword123",0));assert(!auth_default());assert(auth_verify("ChangedPassword123"));assert(!auth_verify("admin"));assert(!auth_init());assert(auth_verify("ChangedPassword123"));puts("PASS PBKDF2, default, persistent password, wrong password"); + g=validate("2 SERVER\n3 0x1 1\n4 0x1 no-such-device 802.3 1\n5 1\n200 1\n1 SYS /\n12 SUPERVISOR not-a-real-user\n");assert(json_object_array_length(get(g,"errors"))>=5);json_object_put(g);g=devices();if(json_object_array_length(g)){const char*dev=js(json_object_array_get_idx(g,0),"name");char*conf=NULL;assert(asprintf(&conf,"2 SERVER\n3 0x1 1\n4 0x2 %s 802.3 1\n5 0\n200 0\n1 SYS /tmp\n12 SUPERVISOR root SecretPass\n",dev)>0);json_object*v=validate(conf);assert(json_object_array_length(get(v,"errors"))==0);json_object_put(v);free(conf);}json_object_put(g);puts("PASS validation invalid configuration and detected Ethernet interface"); + g=backups();const char*bn=json_object_get_string(json_object_array_get_idx(g,0));char*p=NULL;assert(asprintf(&p,"%s/%s",backup_dir,bn)>0);unlink(p);free(p);json_object_put(g);unlink(config_path);unlink(auth_path);rmdir(backup_dir);rmdir(tmp);return 0;} diff --git a/tests/test_print.c b/tests/test_print.c new file mode 100644 index 0000000..556a385 --- /dev/null +++ b/tests/test_print.c @@ -0,0 +1,4 @@ +#include "admin.h" +#include +#include +int main(void){json_object*r=json_tokener_parse("{\"op\":\"list\"}");json_object*o=print_call(r);assert(o);printf("CUPS probe (actual library): %s\n",json_object_to_json_string(o));assert(get(o,"error")||get(o,"printers"));json_object_put(o);json_object_put(r);assert(print_submit("bad;name","filtered","/not/a/file","test")<0);puts("PASS: invalid destination rejected");return 0;} diff --git a/tests/test_raw.c b/tests/test_raw.c new file mode 100644 index 0000000..7f64b3d --- /dev/null +++ b/tests/test_raw.c @@ -0,0 +1,12 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +int rawprint(const char *,const char *); +int main(void){assert(rawprint("invalid-host","/dev/null")<0);int fd=socket(AF_INET,SOCK_STREAM,0);assert(fd>=0);int one=1;setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&one,sizeof one);struct sockaddr_in a={.sin_family=AF_INET,.sin_port=htons(9100),.sin_addr.s_addr=htonl(INADDR_LOOPBACK)};if(bind(fd,(struct sockaddr*)&a,sizeof a)){perror("test requires unused local port 9100");return 77;}assert(!listen(fd,1));char p[]="/tmp/mars-raw-XXXXXX";int f=mkstemp(p);assert(f>=0);unsigned char data[]={0,1,27,255,65,10};assert(write(f,data,sizeof data)==sizeof data);close(f);pid_t child=fork();assert(child>=0);if(!child){close(fd);_exit(rawprint("127.0.0.1",p)?1:0);}int s=accept(fd,NULL,NULL);assert(s>=0);unsigned char buf[16];size_t off=0;ssize_t n;while((n=read(s,buf+off,sizeof buf-off))>0)off+=n;assert(off==sizeof data&&!memcmp(data,buf,off));close(s);close(fd);int status;assert(waitpid(child,&status,0)==child&&WIFEXITED(status)&&!WEXITSTATUS(status));unlink(p);puts("PASS: RAW TCP 9100 exact binary bytes over local TCP");return 0;} diff --git a/tests/test_scripts.c b/tests/test_scripts.c new file mode 100644 index 0000000..70bd680 --- /dev/null +++ b/tests/test_scripts.c @@ -0,0 +1,24 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +static json_object *ma_get(json_object *o,const char *k){json_object *v=NULL;json_object_object_get_ex(o,k,&v);return v;} +static const char *ma_s(json_object *o,const char *k){json_object *v=ma_get(o,k);if(!json_object_is_type(v,json_type_string))return NULL;const char *s=json_object_get_string(v);return strlen(s)==(size_t)json_object_get_string_len(v)?s:NULL;} +static void ma_text(json_object *o,const char*k,const char*v){json_object_object_add(o,k,json_object_new_string(v));} +static json_object *ma_err(const char*s,int rc){json_object *o=json_object_new_object();ma_text(o,"error",s);json_object_object_add(o,"code",json_object_new_int(rc));return o;} +#include "../upstream-adapter/mars_scripts.inc" +static json_object *req(const char *old,int exists,const char *text){json_object *r=json_object_new_object();ma_text(r,"previous",old);ma_text(r,"text",text);json_object_object_add(r,"exists",json_object_new_boolean(exists));return r;} +static void ok(json_object *o){if(ma_get(o,"error"))fprintf(stderr,"%s\n",json_object_to_json_string(o));assert(!ma_get(o,"error"));} +int main(void){char base[]="/tmp/mars-scripts-XXXXXX";assert(mkdtemp(base));char pub[512],mail[512],user[512],back[512],file[1024],ufile[1024];snprintf(pub,sizeof pub,"%s/PUBLIC",base);snprintf(mail,sizeof mail,"%s/MAIL",base);snprintf(user,sizeof user,"%s/MAIL/AB",base);snprintf(back,sizeof back,"%s/backups",base);assert(!mkdir(pub,0755)&&!mkdir(mail,0755)&&!mkdir(user,0700)&&!mkdir(back,0700));snprintf(file,sizeof file,"%s/NET$LOG.DAT",pub);snprintf(ufile,sizeof ufile,"%s/LOGIN",user); + json_object *r=req("",0,"MAP ROOT F:=DATA:\n"),*o=ms_file(base,0,0,0,back,r,1);ok(o);assert(!strcmp(ma_s(o,"text"),"MAP ROOT F:=DATA:\r\n"));json_object_put(r);json_object_put(o);struct stat a,b;assert(!stat(file,&a)); + r=req("MAP ROOT F:=DATA:\r\n",1,"WRITE \"Hi\"\n");o=ms_file(base,0,0,0,back,r,1);ok(o);const char *backup=ma_s(o,"backup");assert(backup&&*backup);char *bp=strdup(backup);assert(!stat(file,&b)&&a.st_ino==b.st_ino&&(b.st_mode&0777)==0644);json_object_put(r);json_object_put(o); + r=req("wrong",1,"bad");o=ms_file(base,0,0,0,back,r,1);assert(ma_get(o,"error"));json_object_put(r);json_object_put(o); + r=req("",0,"MAP G:=DATA:USER\n");o=ms_file(base,0,1,0xab,back,r,1);ok(o);assert(!stat(ufile,&a)&&(a.st_mode&0777)==0600);json_object_put(r);json_object_put(o); + r=req("MAP G:=DATA:USER\r\n",1,"\xc3\xa4");o=ms_file(base,0,1,0xab,back,r,1);assert(ma_get(o,"error"));json_object_put(r);json_object_put(o); + assert(!unlink(ufile)&&!symlink(file,ufile));o=ms_file(base,0,1,0xab,back,NULL,0);assert(ma_get(o,"error"));json_object_put(o);assert(!unlink(ufile)); + unlink(file);unlink(bp);free(bp);rmdir(user);rmdir(mail);rmdir(pub);rmdir(back);rmdir(base);puts("PASS system/personal scripts, CRLF, backup, inode/mode, stale revision, ASCII, symlink rejection");return 0;} diff --git a/tests/test_scripts_browser.py b/tests/test_scripts_browser.py new file mode 100644 index 0000000..187c491 --- /dev/null +++ b/tests/test_scripts_browser.py @@ -0,0 +1,38 @@ +"""Optional development-only Chromium UI test with mock API. Not a server runtime dependency.""" +from pathlib import Path +import os +from playwright.sync_api import sync_playwright +root=Path(__file__).resolve().parents[1]/'websetup' +screens=Path(os.environ.get('MARS_SCREENSHOT_DIR',str(root.parent/'build')));screens.mkdir(parents=True,exist_ok=True) +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=[],backups=[],path='/etc/nwserv.conf',services=True) +state['groups']['1']=['SYS /var/mars/sys kt 711 600','DATA /var/mars/data kt 711 600'] +scripts={('system',''):'REM existing\r\nMAP ROOT F:=DATA:\r\n',('user','DOSUSER'):'REM personal\r\n'} +requests=[] +rights=-1 +def fixture(source,path,body): + global rights + requests.append((path,body)) + if path=='/api/state':return state + if path=='/api/status':return {'mars-nwe-pcap.service':'ActiveState=active','mars-pcapd.service':'ActiveState=active'} + op=body['op'] + if op=='objects':return {'objects':[{'name':'DOSUSER','type':1,'id':2},{'name':'STAFF','type':2,'id':3}]} + if op.startswith('script-'): + key=(body['scope'],body.get('name','') if body['scope']=='user' else '') + if op=='script-save': + assert body['previous']==scripts.get(key,'') + scripts[key]=body['text'].replace('\r\n','\n').replace('\n','\r\n') + if scripts[key] and not scripts[key].endswith('\r\n'):scripts[key]+='\r\n' + return dict(text=scripts.get(key,''),exists=key in scripts,path='SYS:PUBLIC/NET$LOG.DAT' if key[0]=='system' else 'SYS:MAIL/2/LOGIN') + if op.startswith('trustee-'): + if op=='trustee-set':assert body['previous']==rights;rights=body['mask'] + if op=='trustee-remove':assert body['previous']==rights;rights=-1 + return {'mask':rights} + raise AssertionError(body) +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':850});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('.launchpad [data-go="11"]').click();page.wait_for_function("document.getElementById('scriptStatus').textContent.includes('1 Gruppen')") + page.locator('#scriptScope').select_option('group');page.locator('#scriptTarget').select_option('STAFF');page.locator('#scriptOpen').click();page.locator('#scriptText').wait_for();page.locator('#scriptMap').click();page.locator('[name=drive]').select_option('P');page.locator('[name=volume]').select_option('DATA');page.locator('[name=path]').fill('PROJECTS');page.locator('#actionSubmit').click();page.wait_for_function("!document.getElementById('actionDialog').open");assert 'MAP ROOT P:=DATA:PROJECTS' in page.locator('#scriptText').input_value();page.locator('#scriptSave').click();page.wait_for_function("document.getElementById('scriptInfo').textContent.includes('Gespeichert')");assert 'IF MEMBER OF "STAFF" THEN\r\nMAP ROOT P:=DATA:PROJECTS\r\nEND' in scripts['system',''];assert 'REM existing' in scripts['system','']; + page.screenshot(path=str(screens/'MARS-NWE-PCAP-0.4-Scripteditor.png'));page.locator('#scriptClose').click();page.locator('#scriptScope').select_option('user');page.locator('#scriptTarget').select_option('DOSUSER');page.locator('#scriptOpen').click();page.locator('#scriptText').fill('MAP ROOT U:=DATA:USER');page.locator('#scriptSave').click();page.wait_for_function("document.getElementById('scriptInfo').textContent.includes('Gespeichert')");assert scripts['user','DOSUSER']=='MAP ROOT U:=DATA:USER\r\n';page.locator('#scriptClose').click(); + page.locator('#aclOpen').click();page.locator('#aclTarget').select_option('2:STAFF');page.locator('#aclPath').fill('PROJECTS');page.locator('#aclLoad').click();page.locator('#aclRead').wait_for();page.locator('#aclRead').click();page.locator('#aclSave').click();page.wait_for_function("document.getElementById('aclError').textContent.includes('Gespeichert')");assert rights==65;page.screenshot(path=str(screens/'MARS-NWE-PCAP-0.4-Freigaben.png'));page.locator('#aclRemove').click();page.wait_for_function("document.getElementById('aclExisting').textContent==='Keine direkte Zuweisung'");assert rights==-1;page.locator('#aclClose').click(); + assert not errors,errors;print('PASS: mock API Chromium group script, mapping helper, preserved global script, personal script, ACL read/set/remove');b.close() diff --git a/tests/test_supervisor.c b/tests/test_supervisor.c new file mode 100644 index 0000000..3b6354b --- /dev/null +++ b/tests/test_supervisor.c @@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#define _GNU_SOURCE +#include "supervisor.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +extern void supervisor_test_socket(const char *); +static volatile sig_atomic_t stop; +static void on_signal(int s){(void)s;stop=1;} +static int mock_child(int broker){signal(SIGTERM,on_signal);int fd=-1;struct sockaddr_un a={.sun_family=AF_UNIX};if(broker){const char *p=getenv("MARS_TEST_BROKER_SOCKET");assert(p&&strlen(p)=0);assert(bind(fd,(struct sockaddr*)&a,sizeof a)==0);assert(listen(fd,8)==0);}while(!stop){if(fd>=0){int c=accept(fd,NULL,NULL);if(c>=0)close(c);}usleep(10000);}if(fd>=0){close(fd);unlink(a.sun_path);}return 0;} +static int server_pid(void){json_object*o=supervisor_status();const char*s=js(o,"mars-nwe-pcap.service");const char*p=strstr(s,"PID=");int v=p?atoi(p+4):0;json_object_put(o);return v;} +static int broker_pid(void){json_object*o=supervisor_status();const char*s=js(o,"mars-pcapd.service");const char*p=strstr(s,"PID=");int v=p?atoi(p+4):0;json_object_put(o);return v;} +static int await_running(int old){for(int i=0;i<200;i++){supervisor_tick();int p=server_pid();if(p&&p!=old&&broker_pid())return p;usleep(20000);}return 0;} +int main(int argc,char**argv){(void)argc;if(strstr(argv[0],"mock-broker"))return mock_child(1);if(strstr(argv[0],"mock-server"))return mock_child(0);char tmp[]="/tmp/mars-supervisor-XXXXXX";assert(mkdtemp(tmp));char socketfile[108];snprintf(socketfile,sizeof socketfile,"%s/transport.sock",tmp);supervisor_test_socket(socketfile);setenv("MARS_TEST_BROKER_SOCKET",socketfile,1);snprintf(broker_path,sizeof broker_path,"%s/mock-broker",tmp);snprintf(server_path,sizeof server_path,"%s/mock-server",tmp);char exe[PATH_MAX];ssize_t n=readlink("/proc/self/exe",exe,sizeof exe-1);assert(n>0);exe[n]=0;assert(symlink(exe,broker_path)==0);assert(symlink(exe,server_path)==0);assert(supervisor_request("start")==0);int first=await_running(0);assert(first>0);int firstb=broker_pid();usleep(100000);assert(supervisor_request("restart")==0);int second=await_running(first);assert(second>0&&second!=first&&broker_pid()!=firstb);usleep(100000);assert(supervisor_request("stop")==0);for(int i=0;i<200&&(server_pid()||broker_pid());i++){supervisor_tick();usleep(20000);}assert(!server_pid()&&!broker_pid());assert(supervisor_request("start")==0);assert(await_running(0));usleep(100000);supervisor_shutdown();assert(!server_pid()&&!broker_pid());unlink(socketfile);unlink(broker_path);unlink(server_path);rmdir(tmp);puts("PASS supervisor: start, restart, stop, restart after stop, shutdown (mock child processes)");return 0;} diff --git a/tests/test_trustee.c b/tests/test_trustee.c new file mode 100644 index 0000000..5b101a6 --- /dev/null +++ b/tests/test_trustee.c @@ -0,0 +1,26 @@ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +typedef unsigned char uint8;typedef uint32_t uint32; +typedef struct {uint32 id;int trustee;} NW_OIC; +typedef struct {uint8 *unixname;int options;} NW_VOL; +#define VOL_OPTION_TRUSTEES 0x100 +#define VOL_OPTION_IS_HOME 8 +#define VOL_OPTION_IS_PIPE 2 +#define VOL_OPTION_NO_INODES 128 +#define VOL_OPTION_REMOUNT 4 +#define VOL_OPTION_READONLY 32 +#define VOL_OPTION_DOWNSHIFT 1 +static NW_VOL v,*nw_volumes=&v;static int used_nw_volumes=1,act_obj_id,act_id_flags,act_uid,act_gid,rights=-1; +static int nw_get_volume_number(uint8 *name,int len){return len==4&&!memcmp(name,"DATA",4)?0:-1;} +static int tru_get_id_trustee(int vol,uint8 *p,struct stat *st,uint32 id){(void)vol;(void)p;(void)st;(void)id;return rights;} +static int tru_del_trustee(int vol,uint8 *p,struct stat *st,uint32 id){(void)vol;(void)p;(void)st;(void)id;rights=-1;return 0;} +static int tru_add_trustee_set(int vol,uint8 *p,struct stat *st,int n,NW_OIC *e){(void)vol;(void)p;(void)st;assert(n==1&&e->id==2);rights=e->trustee;return 0;} +static void tru_free_cache(int v){(void)v;} +#include "../upstream-adapter/mars_trustee.inc" +int main(void){assert(mt_relative("PROJECTS/TEAM")&&!mt_relative("../X")&&!mt_relative("A//B")&&!mt_relative("A/"));long n;assert(mt_num("255",0,255,&n)&&n==255&&!mt_num("256",0,255,&n));if(geteuid()){puts("SKIP root-only helper path tests (input checks passed)");return 0;}char dir[]="/run/mars-trustee-XXXXXX";assert(mkdtemp(dir));char root[256],sym[512];snprintf(root,sizeof root,"%s/DATA/",dir);assert(!mkdir(root,0711));v.unixname=(uint8*)root;v.options=VOL_OPTION_TRUSTEES;struct stat st;assert(!stat(root,&st));if(st.st_ino>UINT32_MAX||(uintmax_t)st.st_dev>UINT32_MAX){rmdir(root);rmdir(dir);puts("SKIP helper mutation test: fixture inode/device outside legacy 32-bit limits");return 0;}char *args[]={"ftrustee","--mars-admin","get","DATA",root,"","2","65","-1",NULL};assert(!mt_admin(9,args));args[2]="set";assert(!mt_admin(9,args)&&rights==65);assert(mt_admin(9,args)==7);args[8]="65";args[2]="remove";assert(!mt_admin(9,args)&&rights==-1);snprintf(sym,sizeof sym,"%sLINK",root);assert(!symlink("/",sym));args[2]="get";args[5]="LINK";assert(mt_admin(9,args)==5);assert(!unlink(sym));rmdir(root);rmdir(dir);puts("PASS trustee path/rights validation, mock get/set/remove, revision conflict, symlink rejection");return 0;} diff --git a/tests/test_web.sh b/tests/test_web.sh new file mode 100755 index 0000000..e2449d5 --- /dev/null +++ b/tests/test_web.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# Real CivetWeb HTTP smoke test. Run after make native. Never touches production config. +set -euo pipefail +cd "$(dirname "$0")/.." +command -v curl >/dev/null; command -v jq >/dev/null +[[ -x build/mars_vme ]] +d=$(mktemp -d); pid=''; trap 'if [[ -n $pid ]]; then kill "$pid" 2>/dev/null || true; wait "$pid" 2>/dev/null || true; fi; rm -rf "$d"' EXIT +port=${TEST_PORT:-18787}; base="http://127.0.0.1:$port"; cfg="$d/nwserv.conf" +# Fixture need not pass validation to test auth and preview. Real Ethernet name selected below. +cat > "$cfg" <<'CONF' +2 OLD +3 0x12345678 1 +4 0x101 placeholder 802.3 1 +1 SYS /tmp +5 0 +12 SUPERVISOR root DemoPass123 +200 0 +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; } +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 -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 +s=$(get api/state); jq -e '.defaultPassword and (.text=="")' <<<"$s" >/dev/null +csrf=$(jq -r .csrf <<<"$s"); cp "$d/cookie" "$d/old-cookie" +[[ $(status -b "$d/cookie" -H "Origin: $base" -H 'Content-Type: application/json' -d '{}' "$base/api/logout") == 403 ]] +post api/password '{"current":"admin","new":"NativeTestPassword123","repeat":"NativeTestPassword123"}' | jq -e .ok >/dev/null +[[ $(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 +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")]}}') + result=$(post api/preview "$request"); jq -e '.errors|length==0' <<<"$result" >/dev/null + hash=$(jq -r .candidateHash <<<"$result"); save=$(jq -c --arg hash "$hash" '.+{confirm:true,candidateHash:$hash}' <<<"$request") + post api/save "$save" | jq -e '.backup|length>0' >/dev/null; grep -q '99 PRESERVE' "$cfg"; grep -q '2 NEW' "$cfg" + [[ $(status -b "$d/cookie" -H "Origin: $base" -H 'Content-Type: application/json' -H "X-Mars-CSRF: $csrf" -d "$save" "$base/api/save") == 409 ]] + s=$(get api/state); rev=$(jq -r .revision <<<"$s"); bn=$(jq -r '.backups[0]' <<<"$s"); request=$(jq -nc --arg rev "$rev" --arg bn "$bn" '{revision:$rev,mode:"backup",name:$bn}'); post api/preview "$request" | jq -e '.candidate|contains("2 OLD")' >/dev/null +else echo 'SKIP save via HTTP: no Ethernet interface in test environment'; fi +get api/download | grep -q '99 PRESERVE' +post api/logout '{}' | jq -e .ok >/dev/null +[[ $(status -b "$d/cookie" "$base/api/state") == 401 ]] +kill "$pid"; wait "$pid"; pid=''; start +post api/login '{"user":"admin","password":"NativeTestPassword123"}' | jq -e .ok >/dev/null +printf 'PASS: real CivetWeb login, origin/host/CSRF, default-password guard, persistence, logout, preview/save/backup (when Ethernet exists).\n' diff --git a/tests/test_wire.c b/tests/test_wire.c new file mode 100644 index 0000000..967ebe1 --- /dev/null +++ b/tests/test_wire.c @@ -0,0 +1,8 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +#include "wire.h" +#include +#include +#include +int main(void){struct sockaddr_ipx s={.sipx_family=AF_IPX,.sipx_network=htonl(0x12345678),.sipx_port=htons(0x4001),.sipx_node={2,3,4,5,6,7}},d={.sipx_family=AF_IPX,.sipx_network=htonl(0x11223344),.sipx_port=htons(0x451),.sipx_node={0,0,0,0,0,1},.sipx_type=17};uint8_t p[8192],f[1514],data[]={0x11,0x11,0x22,0x33};int n=ipx_make(p,sizeof p,&s,&d,data,sizeof data);assert(n==34);assert(get32(p+6)==0x11223344&&get32(p+18)==0x12345678&&get16(p+16)==0x451&&get16(p+28)==0x4001&&p[5]==17); + int kinds[]={IPX_FRAME_ETHERII,IPX_FRAME_8023,IPX_FRAME_8022,IPX_FRAME_SNAP};for(unsigned i=0;i<4;i++){int l=frame_encode(f,sizeof f,kinds[i],d.sipx_node,s.sipx_node,p,n);assert(l==60);int k;size_t z;const uint8_t *r;assert(!frame_decode(f,l,&k,&r,&z));assert(k==kinds[i]&&z==(size_t)n&&!memcmp(r,p,n));for(int x=0;x<14;x++)assert(frame_decode(f,x,&k,&r,&z)<0);size_t off=r-f;f[off+2]=0;f[off+3]=0;assert(frame_decode(f,l,&k,&r,&z)<0);assert(frame_encode(f,sizeof f,kinds[i],d.sipx_node,s.sipx_node,p,n)>0);f[off+4]=16;assert(frame_decode(f,l,&k,&r,&z)<0);assert(frame_encode(f,sizeof f,kinds[i],d.sipx_node,s.sipx_node,p,n)>0);assert(frame_decode(f,off+n-1,&k,&r,&z)<0);} + memset(data,0,sizeof data);uint8_t big[1470]={0};n=ipx_make(p,sizeof p,&s,&d,big,sizeof big);assert(n==1500);assert(frame_encode(f,sizeof f,IPX_FRAME_ETHERII,d.sipx_node,s.sipx_node,p,n)==1514);assert(frame_encode(f,sizeof f,IPX_FRAME_SNAP,d.sipx_node,s.sipx_node,p,n)<0);puts("PASS: 4 frame types, addresses, padding, lengths, malformed frames and MTU");return 0;} diff --git a/upstream-adapter/mars_acl.inc b/upstream-adapter/mars_acl.inc new file mode 100644 index 0000000..2ea5ecf --- /dev/null +++ b/upstream-adapter/mars_acl.inc @@ -0,0 +1,18 @@ +#include +#include +static json_object *ma_acl(json_object *r,const char *op,NETOBJ *obj){ + const char *vol=ma_s(r,"volume"),*root=ma_s(r,"root"),*rel=ma_s(r,"path");int write=strcmp(op,"trustee-get")!=0; + if(!ma_name(vol)||!strcmp(vol,"SYS")||!root||root[0]!='/'||strlen(root)>240||!rel||strlen(rel)>240||obj->id<2)return ma_err("Invalid trustee volume/path/object (SYS protected)",-1); + if(write){int i;for(i=0;i1023||(!strcmp(op,"trustee-set")&&(!json_object_is_type(mv,json_type_int)||mask<0||mask>255))))return ma_err("Invalid rights or revision",-1); + char ids[24],ms[16],ps[16];snprintf(ids,sizeof ids,"%u",(unsigned)obj->id);snprintf(ms,sizeof ms,"%d",mask);snprintf(ps,sizeof ps,"%d",write?prev:-1); + int fd[2];if(pipe2(fd,O_CLOEXEC|O_NONBLOCK))return ma_err("Trustee helper pipe failed",errno); + pid_t pid=fork();if(pid==0){close(fd[0]);dup2(fd[1],STDOUT_FILENO);close(fd[1]);execl("/usr/local/sbin/ftrustee","ftrustee","--mars-admin",!strcmp(op,"trustee-get")?"get":!strcmp(op,"trustee-set")?"set":"remove",vol,root,rel,ids,ms,ps,(char*)NULL);_exit(127);}close(fd[1]);if(pid<0){close(fd[0]);return ma_err("Trustee helper fork failed",errno);} + char buf[8192];size_t used=0;int status=0,done=0;struct timespec begin,now;clock_gettime(CLOCK_MONOTONIC,&begin); + while(!done){char tmp[1024];ssize_t n;while((n=read(fd[0],tmp,sizeof tmp))>0){size_t take=(size_t)n;if(take>sizeof buf-1-used)take=sizeof buf-1-used;memcpy(buf+used,tmp,take);used+=take;}pid_t w=waitpid(pid,&status,WNOHANG);if(w==pid){done=1;break;}if(w<0&&errno!=EINTR)break;clock_gettime(CLOCK_MONOTONIC,&now);if((now.tv_sec-begin.tv_sec)*1000+(now.tv_nsec-begin.tv_nsec)/1000000>=2000)break;struct pollfd p={fd[0],POLLIN,0};poll(&p,1,20);} + if(done){ssize_t n;while(used0)used+=(size_t)n;}close(fd[0]);if(!done){kill(pid,SIGKILL);waitpid(pid,NULL,0);return ma_err("Trustee helper timeout; check actual rights before retry",-1);}buf[used]=0; + if(!WIFEXITED(status)||WEXITSTATUS(status)){int code=WIFEXITED(status)?WEXITSTATUS(status):-1;return ma_err(code==7?"Trustee changed; reload":code==5?"Directory unsafe, root mismatch, symlink, ownership, device or 32-bit inode limitation":code==4?"Trustee flag t required; unsupported volume type":"Original trustee operation failed; inspect actual rights",code);} + char *p=strstr(buf,"MARS-TRUSTEE ");int result;if(!p||sscanf(p,"MARS-TRUSTEE %d",&result)!=1||result< -1||result>1023)return ma_err("Trustee result missing; inspect actual rights",-1); + json_object *o=json_object_new_object();ma_num(o,"mask",result);return o; +} diff --git a/upstream-adapter/mars_admin.inc b/upstream-adapter/mars_admin.inc new file mode 100644 index 0000000..88e4942 --- /dev/null +++ b/upstream-adapter/mars_admin.inc @@ -0,0 +1,51 @@ +/* Included in nwbind.c after its internal definitions; runs only on its event loop. */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define MA_PATH "/run/mars-pcap/admin.sock" +static int ma_listener=-1; +static json_object *ma_get(json_object *o,const char *k){json_object *v=NULL;json_object_object_get_ex(o,k,&v);return v;} +static const char *ma_s(json_object *o,const char *k){json_object *v=ma_get(o,k);if(!json_object_is_type(v,json_type_string))return NULL;const char *s=json_object_get_string(v);return strlen(s)==(size_t)json_object_get_string_len(v)?s:NULL;} +static void ma_text(json_object *o,const char*k,const char*v){json_object_object_add(o,k,json_object_new_string(v?v:""));} +static void ma_num(json_object *o,const char*k,long long v){json_object_object_add(o,k,json_object_new_int64(v));} +static json_object *ma_err(const char*s,int rc){json_object *o=json_object_new_object();ma_text(o,"error",s);ma_num(o,"code",rc);return o;} +static int ma_name(const char*s){return s&&*s&&strlen(s)<48&&strspn(s,"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.-")==strlen(s);} +static int ma_find(NETOBJ *o,int type,const char *name){if(!ma_name(name))return -1;memset(o,0,sizeof *o);o->type=type;memcpy(o->name,name,strlen(name));return find_obj_id(o);} +static int ma_active(uint32 id){int i;for(i=0;i0){u[199]=0;ma_text(x,"unix",u);}if(!nw_get_login_control(n.id,&lc))json_object_object_add(x,"disabled",json_object_new_boolean(lc.accountExpired));}json_object_array_add(a,x);}json_object_object_add(o,"truncated",json_object_new_boolean(1));return o;} +static json_object *ma_sessions(void){json_object *o=json_object_new_object(),*a=json_object_new_array();json_object_object_add(o,"sessions",a);int i;for(i=0;iactive)continue;json_object *x=json_object_new_object();ma_num(x,"connection",i+1);ma_num(x,"object",c->object_id);ma_num(x,"pid",c->pid_nwconn);ma_num(x,"login",c->object_id?c->t_login:0);ma_num(x,"semaphores",c->count_semas);ma_text(x,"address",visable_ipx_adr(&c->client_adr));json_object_object_add(x,"authenticated",json_object_new_boolean(c->object_id!=0));if(c->object_id){NETOBJ n;memset(&n,0,sizeof n);n.id=c->object_id;if(!nw_get_obj(&n)){char name[49];memcpy(name,n.name,48);name[48]=0;ma_text(x,"name",name);}}json_object_array_add(a,x);}return o;} +static int ma_member(NETOBJ *u,NETOBJ *g,int add){/* use public routines; maintain all three NetWare membership properties */ + const char *props[]={"GROUPS_I'M_IN","SECURITY_EQUALS","GROUP_MEMBERS"};int i;for(i=0;i<3;i++){NETOBJ *owner=i==2?g:u,*member=i==2?u:g;const char*p=props[i];int has=nw_is_member_in_set(owner->id,(char*)p,member->id)==0;if(add&&has)continue;if(!add&&!has)continue;if(add){int cr=nw_create_prop(owner->type,owner->name,strlen((char*)owner->name),(uint8*)p,strlen(p),P_FL_SET,i==1?0x32:0x31);(void)cr;}int rc=add?nw_add_obj_to_set(owner->type,owner->name,strlen((char*)owner->name),(uint8*)p,strlen(p),member->type,member->name,strlen((char*)member->name)):nw_delete_obj_from_set(owner->type,owner->name,strlen((char*)owner->name),(uint8*)p,strlen(p),member->type,member->name,strlen((char*)member->name));if(rc)return rc;}return 0;} +static int ma_password(uint32 id,const char *p){if(!p||strlen(p)<8||strlen(p)>63||strspn(p,"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-=.,:;")!=strlen(p))return -1;return nw_set_passwd(id,(char*)p,0);} +#include "mars_scripts.inc" +#include "mars_acl.inc" +extern uint8 *sys_unixname; +extern int sys_downshift; +static json_object *ma_dispatch(json_object *r){const char *op=ma_s(r,"op"),*name=ma_s(r,"name");int rc=-1;NETOBJ n,g; if(!op)return ma_err("Missing operation",-1); + if(!strcmp(op,"script-get")||!strcmp(op,"script-save")){const char *scope=ma_s(r,"scope");int personal=scope&&!strcmp(scope,"user");if(!scope||(!personal&&strcmp(scope,"system")))return ma_err("Invalid script scope",-1);if(personal&&(ma_find(&n,1,name)||!n.id))return ma_err("NetWare user not found",-1);if(personal&&strcmp(op,"script-get")&&ma_active(n.id))return ma_err("Log user out before editing personal script",-1);return ms_file((char*)sys_unixname,sys_downshift,personal,personal?n.id:0,"/var/lib/mars-vme/script-backups",r,!strcmp(op,"script-save"));} + if(!strcmp(op,"trustee-get")||!strcmp(op,"trustee-set")||!strcmp(op,"trustee-remove")){int type=json_object_get_int(ma_get(r,"type"));if((type!=1&&type!=2)||ma_find(&n,type,name))return ma_err("Trustee object not found",-1);return ma_acl(r,op,&n);} + if(!strcmp(op,"group-members")){if(ma_find(&g,2,name))return ma_err("Group not found",-1);json_object *o=json_object_new_object(),*a=json_object_new_array();json_object_object_add(o,"members",a);uint32 last=0;int i;for(i=0;i<1000;i++){memset(&n,0,sizeof n);n.type=1;strcpy((char*)n.name,"*");int rr=scan_for_obj(&n,last,1);if(rr){if(rr==-0xfc)return o;json_object_put(o);return ma_err("User scan failed",rr);}if(last==n.id){json_object_put(o);return ma_err("Scan cursor failed",-1);}last=n.id;if(!nw_is_member_in_set(g.id,"GROUP_MEMBERS",n.id)){char uname[49];memcpy(uname,n.name,48);uname[48]=0;json_object_array_add(a,json_object_new_string(uname));}}json_object_object_add(o,"truncated",json_object_new_boolean(1));return o;} + if(!strcmp(op,"sessions"))return ma_sessions();if(!strcmp(op,"objects"))return ma_objects(); + if(!strcmp(op,"message")||!strcmp(op,"disconnect")){int i=json_object_get_int(ma_get(r,"connection"));const char *m=ma_s(r,"message");if(i<1||i>max_connections||!connections[i-1].active||!connections[i-1].object_id||(!strcmp(op,"message")&&(!m||!*m||strlen(m)>58)))return ma_err("Invalid connection or message",-1);if((long long)connections[i-1].object_id!=json_object_get_int64(ma_get(r,"object"))||(long long)connections[i-1].t_login!=json_object_get_int64(ma_get(r,"login")))return ma_err("Connection changed",-1);if(!strcmp(op,"disconnect")){int pid=connections[i-1].pid_nwconn;if(pid<=1||pid!=json_object_get_int(ma_get(r,"pid")))return ma_err("Connection process changed",-1);if(kill(pid,SIGTERM))return ma_err("Disconnect signal failed",errno);return json_object_new_object();}strmaxcpy(connections[i-1].message,(char*)m,58);nwserv_handle_msg(i);return json_object_new_object();} + if(!strcmp(op,"export")){const char *base="/var/lib/mars-vme/bindery-backups";struct stat st;if(lstat(base,&st)||!S_ISDIR(st.st_mode)||st.st_uid!=0||(st.st_mode&077))return ma_err("Private backup directory not available",-1);char path[200];snprintf(path,sizeof path,"%s/bindery-XXXXXX",base);if(!mkdtemp(path))return ma_err("Backup directory creation failed",errno);mode_t mask=umask(0077);rc=do_export_dbm(path);umask(mask);if(rc)return ma_err("Original Bindery export failed; inspect incomplete backup",rc);json_object *o=json_object_new_object();ma_text(o,"path",path);return o;} + if(!strcmp(op,"properties")){int type=json_object_get_int(ma_get(r,"type"));if(ma_find(&n,type,name))return ma_err("Object missing",-1);json_object *o=json_object_new_object(),*a=json_object_new_array();json_object_object_add(o,"properties",a);uint32 cursor=0xffffffff;int i;for(i=0;i<255;i++){NETPROP p;memset(&p,0,sizeof p);uint32 prev=cursor;int rr=nw_scan_property(&p,type,n.name,strlen(name),(uint8*)"*",1,&cursor);if(rr<0)break;if(i&&cursor==prev)break;char pn[17];memcpy(pn,p.name,16);pn[16]=0;json_object *x=json_object_new_object();ma_text(x,"name",pn);ma_num(x,"flags",p.flags);ma_num(x,"security",p.security);json_object_array_add(a,x);}return o;} + if(!strcmp(op,"queue-member")){int type=json_object_get_int(ma_get(r,"memberType"));const char *member=ma_s(r,"member"),*role=ma_s(r,"role");if((type!=1&&type!=2)||!role||(strcmp(role,"Q_USERS")&&strcmp(role,"Q_OPERATORS"))||ma_find(&n,3,name)||ma_find(&g,type,member))return ma_err("Queue or member invalid",-1);int add=json_object_get_boolean(ma_get(r,"add"));if(!add&&g.id==1)return ma_err("SUPERVISOR protected",-1);int has=nw_is_member_in_set(n.id,(char*)role,g.id)==0;if(has==add)return json_object_new_object();rc=add?nw_add_obj_to_set(3,n.name,strlen(name),(uint8*)role,strlen(role),type,g.name,strlen(member)):nw_delete_obj_from_set(3,n.name,strlen(name),(uint8*)role,strlen(role),type,g.name,strlen(member));sync_dbm();return rc?ma_err("Queue membership failed",rc):json_object_new_object();} + if(!strcmp(op,"map-user")){const char *u=ma_s(r,"unix");struct passwd *pw=u?getpwnam(u):NULL;if(ma_find(&n,1,name)||n.id==1||ma_active(n.id)||!pw||!pw->pw_uid||strlen(u)>19)return ma_err("User active/protected or Linux account invalid",-1);uint8 v[128]={0};memcpy(v,u,strlen(u));rc=nw_write_prop_value(1,n.name,strlen(name),1,1,(uint8*)"UNIX_USER",9,v);sync_dbm();return rc?ma_err("Mapping failed",rc):json_object_new_object();} + if(!strcmp(op,"create-group")){if(!ma_name(name)||!strcmp(name,"EVERYONE"))return ma_err("Invalid group",-1);if(!ma_find(&n,2,name))return ma_err("Already exists",-1);memset(&n,0,sizeof n);n.type=2;n.security=0x31;strcpy((char*)n.name,name);rc=nw_create_obj(&n,0);} + else if(!strcmp(op,"create-user")){const char *u=ma_s(r,"unix"),*p=ma_s(r,"password");struct passwd *pw=u?getpwnam(u):NULL;if(!ma_name(name)||!strcmp(name,"SUPERVISOR")||!pw||!pw->pw_uid||strlen(u)>19||!p||strlen(p)<8||strlen(p)>63||strspn(p,"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+-=.,:;")!=strlen(p))return ma_err("Invalid user, Linux mapping or password (uppercase ASCII)",-1);if(!ma_find(&n,1,name))return ma_err("Already exists",-1);if(ma_find(&g,2,"EVERYONE"))return ma_err("EVERYONE missing",-1);memset(&n,0,sizeof n);n.type=1;n.security=0x31;strcpy((char*)n.name,name);rc=nw_create_obj(&n,0);if(!rc){uint8 v[128]={0};memcpy(v,u,strlen(u));rc=nw_create_prop(1,n.name,strlen(name),(uint8*)"UNIX_USER",9,P_FL_ITEM,0x30);if(!rc)rc=nw_write_prop_value(1,n.name,strlen(name),1,1,(uint8*)"UNIX_USER",9,v);if(!rc)rc=ma_member(&n,&g,1);if(!rc)rc=ma_password(n.id,p);if(!rc)test_ins_unx_user(n.id);if(rc){int rollback=nw_delete_obj(&n);sync_dbm();if(rollback)return ma_err("User creation failed; rollback failed; inspect Bindery",rc);return ma_err("User creation failed; object removed",rc);}}} + else if(!strcmp(op,"password")||!strcmp(op,"disable")||!strcmp(op,"enable")){if(ma_find(&n,1,name)||n.id==1)return ma_err("User missing or SUPERVISOR protected",-1);if(!strcmp(op,"password"))rc=ma_password(n.id,ma_s(r,"password"));else{LOGIN_CONTROL lc;if(nw_get_login_control(n.id,&lc)){memset(&lc,0,sizeof lc);memset(lc.timeBitMap,0xff,sizeof lc.timeBitMap);}lc.accountExpired=!strcmp(op,"disable");rc=nw_set_login_control(n.id,&lc);}} + else if(!strcmp(op,"delete")){int type=json_object_get_int(ma_get(r,"type"));if((type!=1&&type!=2)||ma_find(&n,type,name)||n.id==1||!strcmp(name,"EVERYONE")||!strcmp(name,"SUPERVISOR")||ma_active(n.id))return ma_err("Object protected, missing or active",-1);/* group removal is deliberately refused if it still has member records */if(type==2){uint8 v[128],more,flags;if(!nw_get_prop_val_by_obj_id(n.id,1,(uint8*)"GROUP_MEMBERS",13,v,&more,&flags)){size_t j;for(j=0;j=0){close(ma_listener);unlink(MA_PATH);ma_listener=-1;}} +static void ma_accept(void){int fd=accept4(ma_listener,NULL,NULL,SOCK_CLOEXEC|SOCK_NONBLOCK);if(fd<0)return;struct ucred cred;socklen_t z=sizeof cred;struct pollfd p={fd,POLLIN,0};if(getsockopt(fd,SOL_SOCKET,SO_PEERCRED,&cred,&z)||cred.uid!=0||poll(&p,1,200)<=0){close(fd);return;}char buf[32769];ssize_t len=recv(fd,buf,32768,MSG_TRUNC);if(len>0&&len<=32768){buf[len]=0;json_object *req=json_tokener_parse(buf);json_object *out=NULL;if(json_object_is_type(req,json_type_object)){int old=internal_act;CONNECTION *prev=act_c;internal_act=1;act_c=NULL;out=ma_dispatch(req);act_c=prev;internal_act=old;}else out=ma_err("Invalid request",-1);const char *s=json_object_to_json_string_ext(out,JSON_C_TO_STRING_PLAIN);if(strlen(s)>190000){json_object_put(out);out=ma_err("Response exceeds limit",-1);s=json_object_to_json_string(out);}send(fd,s,strlen(s),MSG_NOSIGNAL);json_object_put(out);json_object_put(req);memset(buf,0,sizeof buf);}close(fd);} +static int ma_wait(int fd){if(ma_listener<0)return 1;struct pollfd p[2]={{fd,POLLIN,0},{ma_listener,POLLIN,0}};int n=poll(p,2,-1);if(n<0)return 0;if(p[1].revents&POLLIN)ma_accept();return !!(p[0].revents&(POLLIN|POLLERR|POLLHUP));} diff --git a/upstream-adapter/mars_scripts.inc b/upstream-adapter/mars_scripts.inc new file mode 100644 index 0000000..9e34073 --- /dev/null +++ b/upstream-adapter/mars_scripts.inc @@ -0,0 +1,32 @@ +/* Native NetWare 3.x script file access. Included in nwbind; no shell commands. */ +#include +#include +#include +#define MS_LIMIT 4096 +static int ms_dir(int parent,const char *name){return openat(parent,name,O_RDONLY|O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC);} +static int ms_write(int fd,const char *buf,size_t n){size_t p=0;while(p=32&&c<=126)||(old&&c==26&&i==n-1))continue;return 0;}return 1;} +static int ms_normalize(const char *in,char *out){size_t i,n=0;if(!in||strlen(in)>MS_LIMIT||!ms_ascii(in,strlen(in),0))return -1;for(i=0;in[i];i++){if(in[i]=='\r'||in[i]=='\n'){if(in[i]=='\r'&&in[i+1]=='\n')i++;if(n+2>MS_LIMIT)return -1;out[n++]='\r';out[n++]='\n';}else{if(n==MS_LIMIT)return -1;out[n++]=in[i];}}if(n&&out[n-1]!='\n'){if(n+2>MS_LIMIT)return -1;out[n++]='\r';out[n++]='\n';}out[n]=0;return (int)n;} +static int ms_backup(const char *base,const char *old,size_t n,char *path,size_t cap){struct stat st;if(lstat(base,&st)||!S_ISDIR(st.st_mode)||st.st_uid!=geteuid()||(st.st_mode&077))return -1;if(snprintf(path,cap,"%s/script-XXXXXX",base)>=(int)cap)return -1;int fd=mkstemp(path);if(fd<0)return -1;int rc=ms_write(fd,old,n);if(close(fd))rc=-1;if(rc)unlink(path);return rc;} +/* Old content is the optimistic revision. Existing inode is retained for MARS trustee metadata. */ +static json_object *ms_file(const char *root,int down,int personal,uint32_t id,const char *backup,json_object *r,int save){ + const char *fname=personal?(down?"login":"LOGIN"):(down?"net$log.dat":"NET$LOG.DAT");char rel[64],old[MS_LIMIT+2],next[MS_LIMIT+1],backupname[512]="";int dir=-1,fd=-1,exists=0,n=0,nn=0;struct stat ds,fs;json_object *o=NULL; + if(!root||root[0]!='/')return ma_err("SYS volume unavailable",-1); + /* Strip trailing slash to prevent O_NOFOLLOW from being bypassed on the final component. */ + char *rp=strdup(root);if(!rp)return ma_err("Out of memory",-1);size_t l=strlen(rp);while(l>1&&rp[l-1]=='/')rp[--l]=0;int sys=open(rp,O_RDONLY|O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC);free(rp);if(sys<0)return ma_err("SYS directory unavailable or symlink",errno); + dir=ms_dir(sys,personal?(down?"mail":"MAIL"):(down?"public":"PUBLIC"));close(sys);if(dir<0)return ma_err("SYS PUBLIC/MAIL missing or unsafe",errno); + if(personal){char obj[16];snprintf(obj,sizeof obj,down?"%x":"%X",(unsigned)id);int d=ms_dir(dir,obj);close(dir);dir=d;if(dir<0)return ma_err("User MAIL directory not initialized; check Linux mapping and original server initialization",errno);snprintf(rel,sizeof rel,"SYS:MAIL/%s/LOGIN",obj);}else snprintf(rel,sizeof rel,"SYS:PUBLIC/NET$LOG.DAT"); + if(fstat(dir,&ds)){o=ma_err("Directory stat failed",errno);goto done;} + if(!personal&&(ds.st_uid!=geteuid()||(ds.st_mode&022))){o=ma_err("PUBLIC must be admin-owned and not group/world writable",-1);goto done;} + fd=openat(dir,fname,(save?O_RDWR:O_RDONLY)|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC); + if(fd>=0){exists=1;if(fstat(fd,&fs)||!S_ISREG(fs.st_mode)||fs.st_nlink!=1||fs.st_uid!=(personal?ds.st_uid:geteuid())||(fs.st_mode&06000)||(!personal&&(fs.st_mode&022))||flock(fd,(save?LOCK_EX:LOCK_SH)|LOCK_NB)){o=ma_err("Script is unsafe, owned by another user, or locked",-1);goto done;}n=ms_read(fd,old);if(n<0||!ms_ascii(old,(size_t)n,1)){o=ma_err("Script is not supported ASCII or exceeds 4096 bytes; use original tools",-1);goto done;}} + else if(errno!=ENOENT){o=ma_err("Cannot open script safely",errno);goto done;}else old[0]=0; + if(save){const char *prev=ma_s(r,"previous"),*text=ma_s(r,"text");json_object *ex=ma_get(r,"exists");nn=ms_normalize(text,next);if(!prev||!json_object_is_type(ex,json_type_boolean)||json_object_get_boolean(ex)!=exists||strcmp(prev,old)){o=ma_err("Script changed; reload before saving",-1);goto done;}if(nn<0){o=ma_err("Only ASCII, maximum 4096 bytes including CRLF",-1);goto done;} + if(exists&&n==nn&&!memcmp(old,next,(size_t)n)){/* no change */} + else if(exists){if(ms_backup(backup,old,(size_t)n,backupname,sizeof backupname)){o=ma_err("Private backup failed; script not changed",errno);goto done;}if(ms_write(fd,next,(size_t)nn)){int failed=ms_write(fd,old,(size_t)n);o=ma_err(failed?"Write and rollback failed; recover private backup":"Write failed; original restored",errno);ma_text(o,"backup",backupname);goto done;}memcpy(old,next,(size_t)nn+1);} + else {fd=openat(dir,fname,O_CREAT|O_EXCL|O_WRONLY|O_NOFOLLOW|O_CLOEXEC,0600);if(fd<0){o=ma_err("Script creation failed; reload",errno);goto done;}if(ms_write(fd,next,(size_t)nn)||fchown(fd,personal?ds.st_uid:geteuid(),personal?ds.st_gid:getegid())||fchmod(fd,personal?0600:0644)||fsync(fd)){o=ma_err("New script creation incomplete; inspect file",errno);goto done;}exists=1;memcpy(old,next,(size_t)nn+1);} + } + o=json_object_new_object();ma_text(o,"path",rel);ma_text(o,"text",old);json_object_object_add(o,"exists",json_object_new_boolean(exists));if(*backupname)ma_text(o,"backup",backupname); + done:if(fd>=0)close(fd);if(dir>=0)close(dir);return o; +} diff --git a/upstream-adapter/mars_trustee.inc b/upstream-adapter/mars_trustee.inc new file mode 100644 index 0000000..a6a4d48 --- /dev/null +++ b/upstream-adapter/mars_trustee.inc @@ -0,0 +1,41 @@ +/* Native ftrustee extension: restricted direct assignments on configured data volumes. */ +#include +#include +#include +#include +/* Every directory must be root-owned, non-writable by other users and not a symlink. + * This protects the original path-based trustee routines from unprivileged rename races. */ +static int mt_path(const char *p,struct stat *st){ + char part[PATH_MAX];size_t n=strlen(p),i;if(!n||n>=sizeof part||p[0]!='/')return -1; + memcpy(part,p,n+1);while(n>1&&part[n-1]=='/')part[--n]=0; + for(i=1;i<=n;i++)if(part[i]=='/'||part[i]==0){char c=part[i];part[i]=0;if(lstat(part,st)||!S_ISDIR(st->st_mode)||st->st_uid!=0||(st->st_mode&022))return -1;part[i]=c;} + return 0; +} +static int mt_relative(const char *p){if(!*p)return 1;const char *s=p;while(*s){size_t n=strcspn(s,"/");if(!n||n>120||strspn(s,"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.-/")=min&&*v<=max;} +static int mt_admin(int argc,char **argv){ + if(argc!=9||geteuid()!=0)return 2; + const char *op=argv[2],*vol=argv[3],*expectedRoot=argv[4],*rel=argv[5];long id,mask,previous; + if((strcmp(op,"get")&&strcmp(op,"set")&&strcmp(op,"remove"))||!strcmp(vol,"SYS")||!mt_num(argv[6],2,UINT32_MAX,&id)||!mt_num(argv[7],0,255,&mask)||!mt_num(argv[8],-1,1023,&previous)||!mt_relative(rel))return 2; + int v=nw_get_volume_number((uint8*)vol,strlen(vol));if(v<0||v>=used_nw_volumes)return 3; + NW_VOL *nv=nw_volumes+v;int opts=nv->options; + if(!(opts&VOL_OPTION_TRUSTEES)||(opts&(VOL_OPTION_IS_HOME|VOL_OPTION_IS_PIPE|VOL_OPTION_NO_INODES|VOL_OPTION_REMOUNT|VOL_OPTION_READONLY)))return 4; + char root[PATH_MAX],path[PATH_MAX],exp[PATH_MAX];struct stat rs,st; + if(!nv->unixname||snprintf(root,sizeof root,"%s",nv->unixname)>=(int)sizeof root||snprintf(exp,sizeof exp,"%s",expectedRoot)>=(int)sizeof exp)return 4; + size_t n=strlen(root),e=strlen(exp);while(n>1&&root[n-1]=='/')root[--n]=0;while(e>1&&exp[e-1]=='/')exp[--e]=0; + if(!strcmp(root,"/")||strcmp(root,exp)||mt_path(root,&rs))return 5; + if(snprintf(path,sizeof path,"%s/%s",root,rel)>=(int)sizeof path)return 5; + for(size_t i=n+1;path[i];i++)path[i]=(char)((opts&VOL_OPTION_DOWNSHIFT)?tolower((unsigned char)path[i]):toupper((unsigned char)path[i])); + if(mt_path(path,&st)||rs.st_dev!=st.st_dev||st.st_ino>UINT32_MAX||(uintmax_t)st.st_dev>UINT32_MAX)return 5; + act_obj_id=1;act_id_flags=1;act_uid=0;act_gid=0; + int old=tru_get_id_trustee(v,(uint8*)path,&st,(uint32)id),rc=0;if(old< -1)return 6; + if(strcmp(op,"get")){ + if(old!=previous)return 7; + if(old>255)return 6; + if(!strcmp(op,"remove")){if(old!=-1)rc=tru_del_trustee(v,(uint8*)path,&st,(uint32)id);} + else if(old!=mask){NW_OIC entry;entry.id=(uint32)id;entry.trustee=(int)mask;rc=tru_add_trustee_set(v,(uint8*)path,&st,1,&entry);} + if(rc)return 8; + tru_free_cache(v);int now=tru_get_id_trustee(v,(uint8*)path,&st,(uint32)id);if(now!=(!strcmp(op,"remove")?-1:mask))return 9;old=now; + } + printf("\nMARS-TRUSTEE %d\n",old);fflush(stdout);return 0; +} diff --git a/upstream/patched b/upstream/patched new file mode 160000 index 0000000..ecde9c5 --- /dev/null +++ b/upstream/patched @@ -0,0 +1 @@ +Subproject commit ecde9c5a8a0dd1f3b60faeeee76cc6eda1273866 diff --git a/upstream/source-revision.txt b/upstream/source-revision.txt new file mode 100644 index 0000000..d6f03de --- /dev/null +++ b/upstream/source-revision.txt @@ -0,0 +1 @@ +ecde9c5a8a0dd1f3b60faeeee76cc6eda1273866 diff --git a/websetup/app.js b/websetup/app.js new file mode 100644 index 0000000..decb25f --- /dev/null +++ b/websetup/app.js @@ -0,0 +1,133 @@ +'use strict'; +const $=id=>document.getElementById(id), groups=['1','2','3','4','5','12','13','17','21','45','200']; +let scriptDoc=null, scriptOriginal='', scriptScope='system', scriptName=''; +let state=null, mode='guided', checked=null, dirty=false, busy=false, page=0, rawBase='', backupName=null; +function notice(text,kind='ok'){const el=$('notice');el.replaceChildren();if(text){const p=document.createElement('div');p.className='message '+kind;p.textContent=text;el.append(p);}if($('viewDialog').open)$('sheetNotice').textContent=text;} +function show(n){page=n;const dlg=$('viewDialog');if(n===0){if(dlg.open)dlg.close();}else{const target=$('page'+n);$('viewContent').append(target);target.hidden=false;if(!dlg.open)dlg.showModal();dlg.scrollTop=0;}$('page0').hidden=false;for(let i=1;i<=11;i++)$('page'+i).hidden=i!==n;document.querySelectorAll('[data-page]').forEach(b=>b.classList.toggle('active',Number(b.dataset.page)===n));$('sheetNotice').textContent='';if(state&&!state.defaultPassword&&n>=8&&!busy)task(n===8?refreshLive:n===9?refreshBindery:n===10?refreshPrint:refreshScripts);} + +function mark(value=true){dirty=value;$('dirty').hidden=!dirty;checked=null;$('save').disabled=true;$('diffDetails').hidden=true;$('diff').textContent='';$('validation').replaceChildren();$('modeLabel').textContent=mode==='raw'?'Expertenmodus':'Assistent';updateControls();} +function updateControls(){document.querySelectorAll('button,input,select,textarea').forEach(b=>b.disabled=busy||!state);$('restore').disabled=busy||!state?.backups.length;$('viewClose').disabled=false;$('actionClose').disabled=false;$('actionCancel').disabled=false;$('scriptClose').disabled=busy;$('scriptCancel').disabled=busy;$('aclClose').disabled=busy;document.querySelectorAll('[data-service]').forEach(b=>b.disabled=busy||!state?.services||(dirty&&b.dataset.service!=='stop'));$('preview').disabled=busy||!state;$('save').disabled=busy||!checked||checked.errors.length>0||!checked.diff;} +async function api(path,body){const options={cache:'no-store',credentials:'same-origin'};if(body){options.method='POST';options.headers={'Content-Type':'application/json','X-Mars-CSRF':state.csrf};options.body=JSON.stringify(body);}const r=await fetch(path,options);let d;try{d=await r.json();}catch{throw Error('Ungültige Antwort vom Setup-Dienst.');}if(r.status===401){dirty=false;location.replace('/login');throw Error('Sitzung beendet.');}if(!r.ok)throw Error(d.error||'Anfrage fehlgeschlagen.');return d;} +async function task(fn){if(busy)return;busy=true;updateControls();try{await fn();}catch(e){notice(e.message,'error');}finally{busy=false;updateControls();}} +function row(parent,values){const tr=document.createElement('tr');values.forEach(v=>{const td=document.createElement('td');td.textContent=v;tr.append(td);});parent.append(tr);} +function option(parent,value,label){const o=document.createElement('option');o.value=value;o.textContent=label;parent.append(o);} +function apply(s){state=s;$('defaultWarning').hidden=!s.defaultPassword;mode='guided';rawBase='';backupName=null;for(const k of groups)$('g'+k).value=s.groups[k].join('\n');$('raw').value='';$('rawArea').hidden=true;$('superPassword').value='';$('unixUser').value='';$('configPath').textContent=s.path;$('configStatus').textContent=s.validation.errors.length?'Einrichtung nötig':'Grundprüfung OK';$('deviceCount').textContent=s.devices.length;$('devices').replaceChildren();$('newDevice').replaceChildren();for(const d of s.devices){row($('devices'),[d.name,d.mac,d.state]);option($('newDevice'),d.name,d.name+' · '+d.state);}if(!s.devices.length)row($('devices'),['Kein geeignetes Interface','–','–']);$('backups').replaceChildren();for(const b of s.backups)option($('backups'),b,b);$('restore').disabled=!s.backups.length;$('serviceHint').textContent=s.services?'Aktionen werden erst nach einer Bestätigung ausgeführt.':'Dienststeuerung deaktiviert (Standardkennwort oder --no-services).';mark(false);} +async function status(){const s=await api('/api/status');const a=s['mars-nwe-pcap.service']||'Nicht verfügbar';const b=s['mars-pcapd.service']||'Nicht verfügbar';$('statusText').textContent='MARS NWE\n'+a+'\n\nPCAP\n'+b;$('serverStatus').textContent=a.match(/^ActiveState=(.*)$/m)?.[1]||'Nicht verfügbar';$('brokerStatus').textContent='PCAP: '+(b.match(/^ActiveState=(.*)$/m)?.[1]||'unbekannt');} +function rawPayload(){const value=$('raw').value;const normalized=rawBase.replace(/\r\n|\r/g,'\n');if(value===normalized){if(backupName)return {revision:state.revision,mode:'backup',name:backupName};return {revision:state.revision,mode:'raw',text:rawBase};}const text=rawBase.includes('\r\n')&&!rawBase.replace(/\r\n/g,'').includes('\n')?value.replace(/\n/g,'\r\n'):value;return {revision:state.revision,mode:'raw',text};} +function payload(){if(mode==='raw')return rawPayload();return {revision:state.revision,mode,groups:Object.fromEntries(groups.map(k=>[k,$('g'+k).value.split('\n').filter(x=>x.trim())]))};} +function renderCheck(r){checked=r;const el=$('validation');el.replaceChildren();for(const [label,items,kind] of [['Fehler',r.errors,'error'],['Hinweise',r.warnings,'warning']]){if(items.length){const box=document.createElement('div');box.className='message '+kind;const heading=document.createElement('strong');heading.textContent=label+' ('+items.length+')';box.append(heading);const ul=document.createElement('ul');for(const i of items){const li=document.createElement('li');li.textContent=i;ul.append(li);}box.append(ul);el.append(box);}}if(!r.errors.length){const p=document.createElement('p');p.textContent=r.diff?'Grundprüfung bestanden. Hinweise und Diff vor dem Speichern prüfen.':'Grundprüfung bestanden. Keine Änderung gegenüber gespeicherter Datei.';el.append(p);}$('diff').textContent=r.diff||'Keine Änderungen';$('diffDetails').hidden=false;$('diffDetails').open=false;updateControls();} +function canGuide(){if(!state){notice('Konfiguration zuerst laden.','error');return false;}if(mode!=='guided'){notice('Expertenmodus aktiv. Bitte dort zuerst prüfen oder den Entwurf verwerfen.','error');return false;}return true;} +function addLine(k,line){const el=$('g'+k);el.value+=(el.value.trim()?'\n':'')+line;mark();} +function safeToken(s){return s&&!/[\s#\x00]/.test(s);} +function netLine(){const v=['newNet','newDevice','newFrame','newTicks'].map(x=>$(x).value.trim());if(!v.every(safeToken))throw Error('Alle Netzwerkfelder ausfüllen, ohne Leerzeichen.');return v.join(' ');} +function guided(fn){if(!canGuide())return;try{fn();}catch(e){notice(e.message,'error');}} +document.querySelectorAll('[data-page],[data-go]').forEach(b=>b.addEventListener('click',()=>{const n=Number(b.dataset.page??b.dataset.go);if(mode==='raw'&&[1,2,3,10].includes(n)){notice('Expertenmodus verlassen, bevor der Assistent bearbeitet wird.','error');return;}show(n);})); +for(const k of groups)$('g'+k).addEventListener('input',()=>mark());$('raw').addEventListener('input',()=>mark()); +$('addNet').onclick=()=>guided(()=>addLine('4',netLine()));$('replaceNet').onclick=()=>guided(()=>{const line=netLine();if(confirm('Alle bisherigen aktiven Abschnitt-4-Einträge durch dieses Netz ersetzen?')){$('g4').value=line;mark();}}); +$('pcapDefaults').onclick=()=>guided(()=>{for(const k of ['5','200'])$('g'+k).value='0';mark();}); +$('addVol').onclick=()=>guided(()=>{const v=['volName','volPath','volFlags','volDir','volFile'].map(x=>$(x).value.trim());if(!v.every(safeToken)||!v[1].startsWith('/')||!/^[0-7]{3,4}$/.test(v[3])||!/^[0-7]{3,4}$/.test(v[4]))throw Error('Volume-Felder, absoluten Pfad und oktale Rechte prüfen.');addLine('1',v.join(' '));}); +$('setSupervisor').onclick=()=>guided(()=>{const u=$('unixUser').value.trim(),p=$('superPassword').value;if(!safeToken(u)||!safeToken(p)||p.length<8||!/^[\x21-\x7e]+$/.test(p))throw Error('Vorhandenen Linux-Benutzer und Initialpasswort mit mindestens 8 druckbaren ASCII-Zeichen ohne # oder Leerzeichen eingeben.');const lines=$('g12').value.split('\n').filter(x=>x.trim()&&!/^\s*SUPERVISOR(?:\s|$)/i.test(x));lines.push('SUPERVISOR '+u+' '+p);$('g12').value=lines.join('\n');$('superPassword').value='';mark();notice('Supervisor-Eintrag im Entwurf gesetzt.');}); +$('preview').onclick=()=>task(async()=>{renderCheck(await api('/api/preview',payload()));}); +$('save').onclick=()=>task(async()=>{if(!checked||checked.errors.length||!checked.diff)return;if(!confirm('Geprüfte Konfiguration speichern? Hinweise wurden gelesen. Der Server wird nicht automatisch neu gestartet.'))return;const r=await api('/api/save',{...payload(),confirm:true,candidateHash:checked.candidateHash});apply(r.state);notice('Gespeichert. '+(r.backup?'Backup: '+r.backup:'Keine Änderung.'));}); +$('reload').onclick=()=>task(async()=>{if(dirty&&!confirm('Ungespeicherte Änderungen verwerfen?'))return;apply(await api('/api/state'));notice('Konfiguration geladen.');}); +$('rawMode').onclick=()=>{if(!state||mode==='raw')return;if(dirty&&!confirm('Ungespeicherte Assistentenänderungen verwerfen und Originaldatei bearbeiten?'))return;apply(state);mode='raw';rawBase=state.text;$('raw').value=rawBase;$('rawArea').hidden=false;mark(false);}; +$('exitRaw').onclick=()=>{if(dirty&&!confirm('Expertenentwurf verwerfen?'))return;apply(state);show(0);}; +$('restore').onclick=()=>task(async()=>{if(!$('backups').value)return;if(dirty&&!confirm('Aktuellen Entwurf verwerfen?'))return;const name=$('backups').value;const r=await api('/api/preview',{revision:state.revision,mode:'backup',name});apply(state);mode='raw';rawBase=r.candidate;backupName=name;$('rawArea').hidden=false;$('raw').value=rawBase;mark();renderCheck(await api('/api/preview',payload()));show(4);notice('Backup als Entwurf geladen. Erst nach Speichern wird es aktiv.');}); +$('refreshStatus').onclick=()=>task(status);document.querySelectorAll('[data-service]').forEach(b=>b.onclick=()=>task(async()=>{if(!confirm('Dienstaktion '+b.dataset.service+' wirklich ausführen? Aktive Clients können getrennt werden.'))return;await api('/api/service',{revision:state.revision,action:b.dataset.service,confirm:true});await status();notice('Dienstaktion angenommen. Status erneut prüfen.');})); +window.addEventListener('beforeunload',e=>{if(dirty||scriptDirty()){e.preventDefault();e.returnValue='';}}); +show(0);task(async()=>{apply(await api('/api/state'));await status();}); + +$('logout').onclick=()=>task(async()=>{if(dirty&&!confirm('Ungespeicherte Änderungen verwerfen?'))return;await api('/api/logout',{});dirty=false;location.replace('/login');}); +$('changePassword').onclick=()=>task(async()=>{if(dirty&&!confirm('Ungespeicherte Änderungen gehen bei Neuanmeldung verloren. Fortfahren?'))return;await api('/api/password',{current:$('currentPassword').value,new:$('newPassword').value,repeat:$('repeatPassword').value});dirty=false;location.replace('/login');}); + +async function monitor(){const d=await api('/api/monitor');$('monitorText').textContent=Object.entries(d).map(([k,v])=>k+'\n'+v).join('\n\n');} +$('refreshMonitor').onclick=()=>task(monitor); +setInterval(()=>{if(page===5&&state&&!busy&&$('autoMonitor').checked)task(monitor);},5000); +$('downloadConfig').onclick=()=>task(async()=>{if(state.defaultPassword)throw Error('Zuerst Kennwort ändern.');if(!confirm('Konfiguration enthält möglicherweise Klartextkennwörter. Herunterladen?'))return;const r=await fetch('/api/download',{credentials:'same-origin',cache:'no-store'});if(!r.ok)throw Error('Download fehlgeschlagen.');const url=URL.createObjectURL(await r.blob());const a=document.createElement('a');a.href=url;a.download='nwserv.conf';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}); + +// iOS-style sheets retain the existing draft until explicitly saved or discarded. +$('viewClose').onclick=()=>show(0);$('viewDialog').addEventListener('cancel',e=>{e.preventDefault();show(0);}); +$('actionClose').onclick=$('actionCancel').onclick=()=>$('actionDialog').close(); +function cellButton(tr,label,fn,danger=false){const td=document.createElement('td'),b=document.createElement('button');b.textContent=label;if(danger)b.className='danger';b.onclick=fn;td.append(b);tr.append(td);} +function makeRow(parent,vals){row(parent,vals);return parent.lastElementChild;} +function dateLabel(t){return t?new Date(t*1000).toLocaleString('de-DE'):'–';} +function modal(title,fields,hint,fn){const form=$('actionForm');$('actionTitle').textContent=title;$('actionHint').textContent=hint||'';$('actionHint').classList.remove('property-list');$('actionError').textContent='';$('actionFields').replaceChildren();for(const f of fields){const lab=document.createElement('label');lab.textContent=f.label;const input=document.createElement(f.options?'select':'input');input.name=f.key;input.required=true;if(f.options){for(const v of f.options)option(input,v,v);}else{input.type=f.type||'text';input.value=f.value||'';input.autocomplete=f.type==='password'?'new-password':'off';}lab.append(input);$('actionFields').append(lab);}form.onsubmit=async e=>{e.preventDefault();if(busy)return;const data=Object.fromEntries(new FormData(form));busy=true;updateControls();try{await fn(data);$('actionDialog').close();form.reset();}catch(e){$('actionError').textContent=e.message;}finally{busy=false;updateControls();}};$('actionDialog').showModal();} +async function liveAPI(op,params={}){return api('/api/bindery',{op,...params,confirm:true});} +async function refreshLive(){const r=await liveAPI('sessions');$('liveRows').replaceChildren();$('liveSummary').textContent=r.sessions.length+' Verbindungen · '+r.sessions.filter(x=>x.authenticated).length+' angemeldet';for(const s of r.sessions){const tr=makeRow($('liveRows'),[s.connection,s.name||(s.authenticated?'Objekt '+s.object:'Nicht angemeldet'),s.address,dateLabel(s.login),s.semaphores]);if(s.authenticated)cellButton(tr,'Nachricht',()=>modal('Nachricht an '+(s.name||s.connection),[{key:'message',label:'Nachricht (max. 58 Byte)'}],'NetWare-Broadcast',async d=>{await liveAPI('message',{...d,connection:s.connection,object:s.object,login:s.login});notice('Nachricht übergeben.');}));if(s.authenticated)cellButton(tr,'Trennen',()=>modal('Verbindung '+s.connection+' trennen',[],'SIGTERM wie beim Originalserver; offene Dateien können betroffen sein.',async()=>{await liveAPI('disconnect',{connection:s.connection,object:s.object,login:s.login,pid:s.pid});await refreshLive();}),true);}} +$('liveRefresh').onclick=()=>task(refreshLive);setInterval(()=>{if(page===8&&state&&!busy&&$('liveAuto').checked)task(refreshLive);},5000); +let objects=[];const types={1:'Benutzer',2:'Gruppe',3:'Druckqueue',4:'Dateiserver',5:'Jobserver',7:'Printserver'}; +function renderObjects(){const q=$('bindFilter').value.toUpperCase();$('bindRows').replaceChildren();for(const o of objects.filter(x=>(x.name+' '+(types[x.type]||x.type)).toUpperCase().includes(q))){const tr=makeRow($('bindRows'),[o.name,types[o.type]||o.type,o.unix||'–',o.type===1?(o.disabled?'Gesperrt':o.disabled===false?'Aktiv':'Unbekannt'):'–']);if([1,2].includes(o.type)&&!['SUPERVISOR','EVERYONE'].includes(o.name))cellButton(tr,'Bearbeiten',()=>editObject(o));if(o.type===2)cellButton(tr,'Mitglieder',()=>task(async()=>{const r=await liveAPI('group-members',{name:o.name});modal('Mitglieder · '+o.name,[],r.members.join('\n')+(r.truncated?'\n(Begrenzte Liste)':'')||'Keine Mitglieder',async()=>{});$('actionHint').classList.add('property-list');}));if([1,2].includes(o.type))cellButton(tr,'Login-Skript',()=>task(()=>openScript(o.type===1?'user':'group',o.name)));cellButton(tr,'Properties',()=>task(async()=>{const r=await liveAPI('properties',{name:o.name,type:o.type});modal(o.name+' · Properties',[],r.properties.map(p=>p.name+' (Flags '+p.flags+', Security '+p.security+')').join('\n')||'Keine Properties',async()=>{});$('actionHint').classList.add('property-list');}));}} +async function refreshBindery(){const r=await liveAPI('objects');objects=r.objects;$('bindSummary').textContent=objects.length+' Objekte'+(r.truncated?' (begrenzte Liste)':'');renderObjects();} +$('bindRefresh').onclick=()=>task(refreshBindery);$('bindFilter').oninput=renderObjects; +const pwField={key:'password',label:'NetWare-Kennwort (8–63 Zeichen, Großbuchstaben/ASCII)',type:'password'}; +function editObject(o){modal(o.name,[{key:'op',label:'Aktion',options:o.type===1?['password','map-user','disable','enable','delete']:['delete']}],'Bei Änderungen an bestehenden Konten ggf. nwserv.conf anpassen. Löschen ist endgültig.',async d=>{const params={name:o.name,type:o.type};if(d.op==='map-user'){setTimeout(()=>modal('Linux-Zuordnung: '+o.name,[{key:'unix',label:'Bestehender Linux-Benutzer (nicht root)'}],'Nur bei abgemeldetem Benutzer.',async v=>{await liveAPI('map-user',{...params,...v});await refreshBindery();}),0);return;}if(d.op==='password'){/* open password sheet after closing first */setTimeout(()=>modal('Kennwort: '+o.name,[pwField],'Nur NetWare-Kennwort; Linux bleibt unverändert.',async v=>{await liveAPI('password',{...params,...v});await refreshBindery();}),0);return;}if(d.op==='delete'&&!confirm(o.name+' endgültig löschen?'))return;await liveAPI(d.op,params);await refreshBindery();});} +$('createUser').onclick=()=>modal('Benutzer anlegen',[{key:'name',label:'NetWare-Name (Großbuchstaben)'},{key:'unix',label:'Bestehendes Linux-Konto (nicht root)'},pwField],'Neues Objekt wird live angelegt und EVERYONE zugeordnet.',async d=>{await liveAPI('create-user',{...d,name:d.name.toUpperCase()});await refreshBindery();}); +$('createGroup').onclick=()=>modal('Gruppe anlegen',[{key:'name',label:'NetWare-Gruppenname'}],'Live-Bindery',async d=>{await liveAPI('create-group',{name:d.name.toUpperCase()});await refreshBindery();}); +$('membership').onclick=()=>modal('Gruppenzugehörigkeit',[{key:'name',label:'Benutzer',options:objects.filter(o=>o.type===1&&o.name!=='SUPERVISOR').map(o=>o.name)},{key:'group',label:'Gruppe',options:objects.filter(o=>o.type===2&&o.name!=='EVERYONE').map(o=>o.name)},{key:'op',label:'Aktion',options:['add-member','remove-member']}],'Benutzer vorher abmelden; alle drei NetWare-Mitgliedschaftseigenschaften werden gepflegt.',async d=>{await liveAPI(d.op,d);await refreshBindery();}); +let printers=[];const jstates={3:'Wartend',4:'Angehalten',5:'Druckt',6:'Gestoppt',7:'Abgebrochen',8:'Fehler',9:'Abgeschlossen'}; +async function printAPI(op,params={}){return api('/api/print',{op,...params,confirm:true});} +async function refreshPrint(){const r=await printAPI('list');printers=r.printers;$('printRows').replaceChildren();$('jobRows').replaceChildren();$('printSummary').textContent=printers.length+' Drucker · '+r.jobs.length+' bekannte Aufträge'+(r.jobsError?' · '+r.jobsError:'');for(const p of printers){const tr=makeRow($('printRows'),[p.name,({'3':'Bereit','4':'Druckt','5':'Gestoppt'})[p.state]||'Unbekannt',p.accepting==='true'?'Annahme aktiv':p.accepting||'–']);cellButton(tr,'Testseite',()=>modal('Testseite für '+p.name,[],'Sendet einen tatsächlichen Druckauftrag an CUPS.',async()=>{const r=await printAPI('test',{dest:p.name});notice('CUPS-Auftrag '+r.id+' angenommen.');await refreshPrint();}));}for(const j of r.jobs){const tr=makeRow($('jobRows'),[j.id,j.dest+' / '+j.title,j.user,jstates[j.state]||j.state]);if(j.state<7)cellButton(tr,'Abbrechen',()=>modal('Auftrag '+j.id+' abbrechen',[],'Der CUPS-Auftrag wird abgebrochen.',async()=>{await printAPI('cancel',{dest:j.dest,id:j.id});await refreshPrint();}),true);}} +$('printRefresh').onclick=()=>task(refreshPrint); +$('queueAdd').onclick=()=>{if(!canGuide())return;modal('NetWare-Druckqueue',[{key:'queue',label:'Queue-Name (z. B. LASER)'},{key:'path',label:'NetWare-Verzeichnis',value:'SYS:/PRINT/LASER'},{key:'dest',label:'CUPS-Drucker',...(printers.length?{options:printers.map(p=>p.name)}:{})},{key:'mode',label:'Druckmodus',options:['filtered','raw']}],'Erstellt einen Entwurf in Abschnitt 21. Nach Prüfung speichern und Server neu starten.',async d=>{const q=d.queue.toUpperCase();if(!/^[A-Z0-9_-]{1,47}$/.test(q)||!/^([A-Za-z0-9_-]+):[A-Za-z0-9_/.\-]+$/.test(d.path)||d.path.includes('..')||!/^[A-Za-z0-9_.-]{1,80}$/.test(d.dest))throw Error('Queue, Pfad oder Druckername ungültig.');if($('g21').value.split('\n').some(l=>l.trim().split(/\s+/)[0]?.toUpperCase()===q))throw Error('Queue bereits vorhanden.');addLine('21',q+' '+d.path+' /usr/local/sbin/mars-print '+d.dest+' '+d.mode);notice('Queue als Entwurf hinzugefügt.');});}; + +$('queueACL').onclick=()=>modal('NetWare-Druckberechtigungen',[{key:'name',label:'Druckqueue',options:objects.filter(o=>o.type===3).map(o=>o.name)},{key:'member',label:'Benutzer oder Gruppe (Name)'},{key:'memberType',label:'Objekttyp',options:['1','2']},{key:'role',label:'Rolle',options:['Q_USERS','Q_OPERATORS']},{key:'add',label:'Aktion',options:['Hinzufügen','Entfernen']}],'1 = Benutzer, 2 = Gruppe. EVERYONE-Freigabe bei Bedarf ausdrücklich entfernen.',async d=>{await liveAPI('queue-member',{...d,member:d.member.toUpperCase(),memberType:Number(d.memberType),add:d.add==='Hinzufügen'});notice('Druckberechtigung geändert.');}); +$('rawQueueAdd').onclick=()=>{if(!canGuide())return;modal('RAW TCP / JetDirect',[{key:'queue',label:'Queue-Name'},{key:'path',label:'NetWare-Verzeichnis',value:'SYS:/PRINT/RAW'},{key:'host',label:'IPv4-Adresse des Druckers'}],'Unveränderte Übertragung an TCP 9100; kein CUPS-Status oder Drucknachweis.',async d=>{const q=d.queue.toUpperCase();if(!/^[A-Z0-9_-]{1,47}$/.test(q)||!/^([A-Za-z0-9_-]+):[A-Za-z0-9_/.\-]+$/.test(d.path)||d.path.includes('..')||!/^\d{1,3}(\.\d{1,3}){3}$/.test(d.host)||d.host.split('.').some(v=>Number(v)>255||String(Number(v))!==v))throw Error('Queue, Pfad oder IPv4 ungültig.');if($('g21').value.split('\n').some(l=>l.trim().split(/\s+/)[0]?.toUpperCase()===q))throw Error('Queue bereits vorhanden.');addLine('21',q+' '+d.path+' /usr/local/sbin/mars-print '+d.host+' jetdirect');notice('Queue als Entwurf hinzugefügt.');});}; + +$('bindExport').onclick=()=>modal('Bindery sichern',[],'Exportiert die originalen Bindery-Objekte, Properties und Werte in ein vertrauliches Verzeichnis auf dem Server. Enthält auch Passwortdaten.',async()=>{const r=await liveAPI('export');notice('Bindery-Export: '+r.path);}); + +// Native NetWare login scripts; managed group blocks are inserted into NET$LOG.DAT. +function lf(s){return s.replace(/\r\n|\r/g,'\n').replace(/\x1a$/,'');} +function groupBounds(text,name){ + const begin='REM MARS-VME GROUP '+name+' BEGIN',end='REM MARS-VME GROUP '+name+' END'; + const lines=lf(text).split('\n'),starts=[],ends=[]; + lines.forEach((l,i)=>{if(l===begin)starts.push(i);if(l===end)ends.push(i);}); + if(!starts.length&&!ends.length)return {lines,body:'',start:-1,end:-1}; + if(starts.length!==1||ends.length!==1||ends[0]/^\s*REM MARS-VME GROUP /i.test(l)))throw Error('Verschachtelte Gruppenmarkierungen: Systemskript prüfen.'); + return {lines,body:body.join('\n'),start:starts[0],end:ends[0]}; +} +function groupMerge(text,name,body){ + if(!/^[A-Z0-9_.-]{1,47}$/.test(name))throw Error('Ungültiger Gruppenname'); + const b=groupBounds(text,name),content=lf(body).replace(/\n+$/,''); + if(/^\s*REM MARS-VME GROUP /mi.test(content))throw Error('Reservierte Gruppenmarkierung'); + // No nested IF/END inside managed group sections: preserves the outer condition. + if(/^\s*(IF|ELSE|END|ENDIF|EXIT|GOTO|INCLUDE)(?:\s|$)/mi.test(content))throw Error('Gruppenskript: keine Verzweigungen, EXIT oder INCLUDE. Dafür Systemskript verwenden.'); + const block=content?['REM MARS-VME GROUP '+name+' BEGIN','IF MEMBER OF "'+name+'" THEN',...content.split('\n'),'END','REM MARS-VME GROUP '+name+' END']:[]; + if(b.start>=0)b.lines.splice(b.start,b.end-b.start+1,...block); + else if(block.length){if(b.lines.at(-1)==='')b.lines.pop();b.lines.push(...block,'');} + return b.lines.join('\n'); +} +function scriptDirty(){return Boolean(scriptDoc&&$('scriptDialog').open&&$('scriptText').value!==scriptOriginal);} +function closeScript(){if(busy)return;if(scriptDirty()&&!confirm('Ungespeichertes Skript verwerfen?'))return;$('scriptDialog').close();scriptDoc=null;} +$('scriptClose').onclick=$('scriptCancel').onclick=closeScript;$('scriptDialog').addEventListener('cancel',e=>{e.preventDefault();closeScript();}); +function scriptTargets(){const scope=$('scriptScope').value,target=$('scriptTarget');target.replaceChildren();if(scope==='system')option(target,'','Alle Benutzer');else for(const o of objects.filter(o=>o.type===(scope==='group'?2:1)))option(target,o.name,o.name);} +$('scriptScope').onchange=scriptTargets; +async function refreshScripts(){await refreshBindery();scriptTargets();$('shareRows').replaceChildren();for(const line of state.groups['1']){const v=line.trim().split(/\s+/);row($('shareRows'),[v[0]||'–',v[1]||'–',v[2]||'–']);}$('scriptStatus').textContent=objects.filter(o=>o.type===1).length+' Benutzer · '+objects.filter(o=>o.type===2).length+' Gruppen';} +$('scriptRefresh').onclick=()=>task(refreshScripts); +async function openScript(scope,name){if(scope!=='system'&&!name)throw Error('Benutzer oder Gruppe auswählen.');const r=await liveAPI('script-get',{scope:scope==='user'?'user':'system',name});scriptScope=scope;scriptName=name;scriptDoc=r;scriptOriginal=scope==='group'?groupBounds(r.text,name).body:lf(r.text);$('scriptTitle').textContent=scope==='system'?'Systemskript':(scope==='group'?'Gruppenskript · ':'Benutzerskript · ')+name;$('scriptPath').textContent=r.path+(scope==='group'?' · verwalteter IF-Block':'');$('scriptText').value=scriptOriginal;$('scriptError').textContent='';$('scriptInfo').textContent=scope==='group'?'Leerer Editor entfernt den verwalteten Gruppenblock. Er wird nach dem übrigen Systemskript ausgeführt, sofern dieses nicht vorher endet.':'Speichern wirkt beim nächsten Client-Login. Bestehende Skripte werden gesichert.';$('scriptDialog').showModal();scriptUpdate();} +$('scriptOpen').onclick=()=>task(()=>openScript($('scriptScope').value,$('scriptTarget').value)); +function scriptCandidate(){return scriptScope==='group'?groupMerge(scriptDoc.text,scriptName,$('scriptText').value):$('scriptText').value;} +function scriptValidate(){const t=lf(scriptCandidate());if(/[^\x09\x0a\x20-\x7e]/.test(t))throw Error('Nur ASCII-Zeichen zulässig.');const normalized=t.replace(/\n/g,'\r\n')+(t&&!t.endsWith('\n')?'\r\n':'');if(normalized.length>4096)throw Error('Gesamtskript überschreitet 4096 Bytes.');return {bytes:normalized.length,warn:/^\s*(EXIT|GOTO)\b/mi.test(t)?' EXIT/GOTO kann spätere Zuordnungen überspringen.':''};} +function scriptUpdate(){const t=$('scriptText');$('scriptLines').textContent=t.value.split('\n').map((_,i)=>i+1).join('\n');$('scriptLines').scrollTop=t.scrollTop;try{const r=scriptValidate();$('scriptCount').textContent=r.bytes+' / 4096 Bytes'+(scriptDirty()?' · geändert':'');$('scriptError').textContent='';}catch(e){$('scriptCount').textContent='Prüfung erforderlich';$('scriptError').textContent=e.message;}} +$('scriptText').oninput=scriptUpdate;$('scriptText').onscroll=()=>{$('scriptLines').scrollTop=$('scriptText').scrollTop;}; +$('scriptText').onkeydown=e=>{if(e.key==='Tab'){e.preventDefault();const t=e.target;t.setRangeText(' ',t.selectionStart,t.selectionEnd,'end');scriptUpdate();}}; +function insertScript(s){const t=$('scriptText');const before=t.value.slice(0,t.selectionStart),after=t.value.slice(t.selectionEnd);t.setRangeText((before&&!before.endsWith('\n')?'\n':'')+s+(after&&!after.startsWith('\n')?'\n':''),t.selectionStart,t.selectionEnd,'end');scriptUpdate();} +$('scriptMap').onclick=()=>modal('Laufwerk verbinden',[{key:'drive',label:'Laufwerk',options:'FGHIJKLMNOPQRSTUVWXYZ'.split('')},{key:'volume',label:'Volume',options:state.groups['1'].map(v=>v.trim().split(/\s+/)[0]).filter(Boolean)},{key:'path',label:'Unterverzeichnis (optional)',value:'ROOT'},{key:'root',label:'Zuordnung',options:['MAP ROOT','MAP']}],'Unterverzeichnis ROOT = Volume-Wurzel. Keine Änderung der Dateirechte.',async d=>{const path=d.path==='ROOT'?'':d.path.replace(/\//g,'\\');if(!/^[A-Za-z0-9_.-]+$/.test(d.volume)||!/^([A-Za-z0-9_.-]+(\\[A-Za-z0-9_.-]+)*)?$/.test(path)||path.split('\\').some(v=>v==='.'||v==='..'))throw Error('Ungültiger Volume-Pfad');insertScript(d.root+' '+d.drive+':='+d.volume.toUpperCase()+':'+path);}); +$('scriptWelcome').onclick=()=>insertScript('WRITE "Welcome to the network"'); +$('scriptCheck').onclick=()=>{try{const r=scriptValidate();$('scriptError').textContent='';$('scriptInfo').textContent='Grundprüfung OK: '+r.bytes+' Bytes.'+r.warn+' Keine vollständige Prüfung durch LOGIN.EXE.';}catch(e){$('scriptError').textContent=e.message;}}; +$('scriptSave').onclick=async()=>{if(busy||!scriptDoc)return;try{const r=scriptValidate();if(!scriptDirty()&&scriptDoc.exists)return;if(!confirm('Login-Skript speichern?'+r.warn+' Änderungen wirken bei der nächsten Anmeldung.'))return;busy=true;updateControls();const saved=await liveAPI('script-save',{scope:scriptScope==='user'?'user':'system',name:scriptName,previous:scriptDoc.text,exists:scriptDoc.exists,text:scriptCandidate()});scriptDoc=saved;scriptOriginal=scriptScope==='group'?groupBounds(saved.text,scriptName).body:lf(saved.text);$('scriptText').value=scriptOriginal;scriptUpdate();$('scriptInfo').textContent='Gespeichert.'+(saved.backup?' Sicherung: '+saved.backup:'')+' Beim nächsten Login aktiv.';}catch(e){$('scriptError').textContent=e.message;}finally{busy=false;updateControls();}}; + +let aclDoc=null,aclVolumes=[]; +function aclInvalidate(){aclDoc=null;$('aclEditor').hidden=true;$('aclError').textContent='';} +$('aclVolume').onchange=$('aclTarget').onchange=$('aclPath').oninput=aclInvalidate; +$('aclOpen').onclick=()=>{if(dirty){notice('Zuerst Konfiguration speichern oder Entwurf verwerfen.','error');return;}aclVolumes=state.groups['1'].map(v=>v.trim().split(/\s+/)).filter(v=>v[0]?.toUpperCase()!=='SYS'&&v[1]?.startsWith('/')&&/[tT]/.test(v[2]||''));$('aclVolume').replaceChildren();$('aclTarget').replaceChildren();aclVolumes.forEach((v,i)=>option($('aclVolume'),String(i),v[0]));objects.filter(o=>[1,2].includes(o.type)&&o.id!==1&&o.name!=='SUPERVISOR').forEach(o=>option($('aclTarget'),o.type+':'+o.name,(o.type===1?'Benutzer · ':'Gruppe · ')+o.name));$('aclPath').value='';aclInvalidate();$('aclDialog').showModal();}; +$('aclClose').onclick=()=>{if(!busy)$('aclDialog').close();};$('aclDialog').addEventListener('cancel',e=>{if(busy)e.preventDefault();}); +function aclParams(){if(!$('aclVolume').value||!$('aclTarget').value)throw Error('Datenvolume mit t/T und Benutzer oder Gruppe wählen.');const v=aclVolumes[Number($('aclVolume').value)], [type,name]=$('aclTarget').value.split(':'),path=$('aclPath').value.trim().replace(/\\/g,'/');if(!v||!name||!/^([A-Za-z0-9_.-]+(\/[A-Za-z0-9_.-]+)*)?$/.test(path)||path.split('/').some(v=>v==='.'||v==='..'))throw Error('Ungültiger Ordnerpfad');return {volume:v[0].toUpperCase(),root:v[1],path,name,type:Number(type)};} +function aclMask(){return [...$('aclFlags').querySelectorAll('input:checked')].reduce((a,b)=>a+Number(b.value),0);} +function aclSetMask(n){$('aclFlags').querySelectorAll('input').forEach(b=>b.checked=Boolean(n&Number(b.value)));} +function aclRender(mask){aclDoc.mask=mask;$('aclExisting').textContent=mask===-1?'Keine direkte Zuweisung': 'Direkte Maske: 0x'+mask.toString(16).toUpperCase();if(mask>255){$('aclExisting').textContent+=' · Erweiterte Rechte: nur Originalwerkzeuge verwenden.';$('aclEditor').hidden=true;throw Error('Erweiterte Trustee-Rechte werden nicht überschrieben.');}aclSetMask(Math.max(0,mask));$('aclEditor').hidden=false;} +async function aclTask(fn){if(busy)return;busy=true;updateControls();$('aclError').textContent='';try{await fn();}catch(e){$('aclError').textContent=e.message;}finally{busy=false;updateControls();}} +$('aclLoad').onclick=()=>aclTask(async()=>{const params=aclParams();const r=await liveAPI('trustee-get',params);aclDoc={params,mask:r.mask};aclRender(r.mask);}); +$('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'); diff --git a/websetup/index.html b/websetup/index.html new file mode 100644 index 0000000..dd9d636 --- /dev/null +++ b/websetup/index.html @@ -0,0 +1,24 @@ + +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.
+ + + + + + + + + + + +
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
diff --git a/websetup/login.html b/websetup/login.html new file mode 100644 index 0000000..17fc388 --- /dev/null +++ b/websetup/login.html @@ -0,0 +1 @@ +MARS NWE · Anmeldung
MARS NWEPCAP / SERVER ADMINISTRATION

Administrator anmelden

Nur im vertrauenswürdigen Administrationsnetz. HTTP überträgt Anmeldedaten unverschlüsselt.

diff --git a/websetup/login.js b/websetup/login.js new file mode 100644 index 0000000..9f1b5a7 --- /dev/null +++ b/websetup/login.js @@ -0,0 +1,3 @@ +'use strict'; +const form=document.getElementById('login'), error=document.getElementById('loginError'); +form.addEventListener('submit',async e=>{e.preventDefault();const button=form.querySelector('button');button.disabled=true;error.textContent='';try{const r=await fetch('/api/login',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({user:document.getElementById('user').value,password:document.getElementById('password').value}),credentials:'same-origin'});const d=await r.json();if(!r.ok)throw Error(d.error||'Anmeldung fehlgeschlagen');location.replace('/');}catch(e){error.textContent=e.message;document.getElementById('password').value='';}finally{button.disabled=false;}}); diff --git a/websetup/style.css b/websetup/style.css new file mode 100644 index 0000000..e6028b2 --- /dev/null +++ b/websetup/style.css @@ -0,0 +1,13 @@ +:root{color-scheme:dark;--bg:#0e1520;--panel:#172231;--line:#2c3b4e;--text:#edf3fa;--muted:#a4b4c8;--accent:#5cc6b8;--warning:#f3cb80;--error:#ffaaaa}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:15px/1.55 system-ui,sans-serif}header{height:76px;border-bottom:1px solid var(--line);padding:0 28px;display:flex;align-items:center;justify-content:space-between;background:#111b29}.brand{display:flex;align-items:center;gap:12px}.logo{background:var(--accent);color:#0b2c2b;border-radius:8px;display:grid;place-items:center;width:38px;height:38px;font-weight:900;font-size:24px}.brand strong{font-size:18px;letter-spacing:.08em}.brand small{display:block;color:var(--muted);font-size:10px;letter-spacing:.12em}.local{font-size:12px;color:var(--accent)}.layout{display:grid;grid-template-columns:245px minmax(0,1fr);min-height:calc(100vh - 126px)}aside{padding:26px 16px;border-right:1px solid var(--line);background:#111b29}aside .eyebrow{margin-left:12px}nav{display:grid;gap:5px}nav button{background:transparent;border:0;text-align:left;color:var(--muted);padding:12px;font-size:14px}nav button.active{background:#203544;color:var(--accent);box-shadow:inset 3px 0 var(--accent)}.aside-note{font-size:12px;color:var(--muted);border-top:1px solid var(--line);margin:30px 12px;padding-top:20px}main{padding:32px 36px;max-width:1200px;width:100%;margin:auto;align-self:start}.eyebrow{font-size:11px;letter-spacing:.16em;color:var(--accent);font-weight:700;margin:0 0 8px}h1{font-size:30px;line-height:1.2;margin:0 0 12px;letter-spacing:-.03em}h2{font-size:17px;margin:0 0 12px}.lead{color:var(--muted);margin:0 0 24px;max-width:800px}.cards{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px;margin-bottom:20px}.cards article,.panel{border:1px solid var(--line);background:var(--panel);border-radius:10px;padding:20px}.cards small,.hint{color:var(--muted);font-size:13px}.cards strong{display:block;font-size:20px;margin-top:8px}.cards p{color:var(--muted);font-size:12px;margin:7px 0 0;overflow-wrap:anywhere}.panel{margin-bottom:16px}.panel p{margin:10px 0}.fields{display:grid;grid-template-columns:repeat(auto-fit,minmax(155px,1fr));gap:12px;margin:12px 0}label{display:block;font-size:13px;color:var(--muted);font-weight:600;margin:14px 0 8px}input,select,textarea{display:block;width:100%;color:var(--text);background:#101a27;border:1px solid #41536a;border-radius:6px;padding:10px 12px;font:inherit;margin:6px 0 0}textarea{font:13px/1.6 ui-monospace,monospace;resize:vertical}input:focus,select:focus,textarea:focus,button:focus-visible,summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px}button{cursor:pointer;background:#233246;border:1px solid #40536b;color:var(--text);border-radius:6px;padding:9px 14px;font:600 13px system-ui;margin:3px 4px 3px 0}button:hover{filter:brightness(1.15)}button.primary{background:var(--accent);border-color:var(--accent);color:#092a2a}button.danger{color:var(--error)}button:disabled{opacity:.42;cursor:not-allowed;filter:none}.actions{display:flex;align-items:center;flex-wrap:wrap;gap:8px;margin:14px 0}.steps{padding-left:23px;color:var(--muted)}.steps li{padding:4px 0}.alert,.dirty,.message{border:1px solid #65552f;background:#30291d;color:var(--warning);padding:11px 14px;border-radius:7px;margin:12px 0}.message.ok{color:#b8f4df;background:#16342f;border-color:#386b61}.message.error{color:var(--error);background:#39232a;border-color:#75414d}pre{background:#101a27;border:1px solid var(--line);padding:12px;border-radius:6px;white-space:pre-wrap;overflow-wrap:anywhere;font:13px/1.55 ui-monospace,monospace}summary{cursor:pointer;color:var(--accent);padding:8px 0}.scroll{overflow-x:auto}table{width:100%;border-collapse:collapse;text-align:left;font-size:13px}td,th{padding:9px;border-bottom:1px solid var(--line)}th{color:var(--muted);font-weight:500}footer{border-top:1px solid var(--line);padding:15px 28px;font-size:12px;color:var(--muted)}.mono{font-family:ui-monospace,monospace}[hidden]{display:none!important}@media(max-width:850px){.layout{grid-template-columns:1fr}aside{border-right:0;border-bottom:1px solid var(--line);padding:12px}aside .eyebrow,.aside-note{display:none}nav{display:flex;overflow-x:auto}nav button{flex-shrink:0}main{padding:22px 16px}.cards{grid-template-columns:1fr}header{padding:0 16px}.local{display:none}} + +.login{max-width:470px;margin:8vh auto;padding:24px}.login .brand{margin-bottom:24px}.login .panel{padding:30px}.login button{width:100%}#loginError{color:var(--error)}#defaultWarning{margin-bottom:18px}header .local{margin-left:auto;margin-right:16px} +/* iOS-inspired grouped settings, system typography, native accessible dialogs. */ +:root{color-scheme:light;--bg:#f2f2f7;--panel:#fff;--line:#d1d1d6;--text:#1c1c1e;--muted:#636366;--accent:#007aff;--warning:#925700;--error:#b91c1c;--control:#f2f2f7;--bar:rgba(255,255,255,.95);--hover:#e8e8ed} +@media(prefers-color-scheme:dark){:root{color-scheme:dark;--bg:#000;--panel:#1c1c1e;--line:#38383a;--text:#f2f2f7;--muted:#aeaeb2;--accent:#0a84ff;--warning:#ffd60a;--error:#ff6961;--control:#2c2c2e;--bar:rgba(28,28,30,.96);--hover:#3a3a3c}} +body{font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",system-ui,sans-serif;background:var(--bg)}header{background:var(--bar);height:64px;position:sticky;top:0;z-index:2;backdrop-filter:blur(16px);border-bottom:1px solid var(--line)}.logo{background:var(--accent);color:white;border-radius:11px}.brand strong{letter-spacing:-.025em}.brand small{letter-spacing:.04em}.layout{grid-template-columns:210px minmax(0,1fr);min-height:calc(100vh - 114px)}aside{background:var(--bar);padding:18px 10px}nav button{border-radius:10px;padding:10px 12px;margin:0}nav button.active{background:var(--control);color:var(--accent);box-shadow:none}main{max-width:1040px;padding:28px}h1{font-size:30px;letter-spacing:-.035em}h2{margin-top:12px}.cards article,.panel{border:0;border-radius:18px;box-shadow:0 2px 8px #00000008;background:var(--panel)}.cards article{padding:18px}.panel{padding:20px}.launchpad{display:grid;grid-template-columns:repeat(auto-fit,minmax(155px,1fr));gap:12px;margin:18px 0}.launchpad button{display:flex;flex-direction:column;align-items:flex-start;gap:4px;border:0;border-radius:18px;background:var(--panel);padding:17px;min-height:112px;text-align:left;box-shadow:0 2px 8px #00000008}.launchpad span{display:grid;place-items:center;background:var(--accent);color:white;width:32px;height:32px;border-radius:9px;font-size:19px}.launchpad strong{font-size:16px;letter-spacing:-.02em}.launchpad small{font-size:12px;color:var(--muted);font-weight:400}.launchpad button:hover{background:var(--hover)}input,select,textarea,pre{background:var(--control);border:1px solid var(--line);border-radius:11px;color:var(--text)}input[type=checkbox]{width:auto;display:inline;margin:0 5px 0 0;accent-color:var(--accent)}button{color:var(--accent);border:0;border-radius:11px;background:var(--control);padding:9px 14px;font-size:14px}button.primary{background:var(--accent);color:white}button.danger{color:var(--error)}.alert,.dirty,.message{background:var(--panel);border:1px solid var(--line);color:var(--warning);border-radius:12px}.message.ok{background:var(--panel);color:var(--text);border-color:var(--line)}.message.error{background:var(--panel);color:var(--error);border-color:var(--error)}.scroll{border-radius:12px;background:var(--panel)}th,td{padding:10px 12px}td{overflow-wrap:anywhere}table button{white-space:nowrap}dialog.sheet{width:min(920px,calc(100vw - 28px));max-height:calc(100dvh - 32px);padding:0;border:0;border-radius:22px;background:var(--bg);color:var(--text);box-shadow:0 24px 90px #0005;overflow:auto}dialog.sheet::backdrop{background:#0006;backdrop-filter:blur(6px)}.sheet-head{position:sticky;top:0;background:var(--bar);border-bottom:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;gap:8px;padding:12px 20px;z-index:1;color:var(--muted);font-size:13px}.sheet-head button{background:none;color:var(--accent);font-size:16px;margin:0}.sheet #viewContent,.sheet form{padding:20px 24px}.sheet-message{position:sticky;bottom:0;background:var(--bar);color:var(--text);padding:12px 24px;white-space:pre-wrap}.sheet-message:empty{display:none}dialog.action-sheet{width:min(480px,calc(100vw - 28px))}#actionError{color:var(--error)}.login .panel{background:var(--panel)}@media(max-width:850px){.layout{grid-template-columns:1fr}aside{display:none}main{padding:18px}.cards{grid-template-columns:repeat(2,minmax(0,1fr))}.launchpad{grid-template-columns:repeat(2,minmax(0,1fr))}dialog.sheet{width:100%;max-width:100%;max-height:94dvh;margin:auto 0 0;border-radius:22px 22px 0 0}.sheet #viewContent,.sheet form{padding:18px}header .local{display:none}} +.property-list{white-space:pre-line}.sheet #viewContent>section{max-width:100%} +/* Compact native-script editor, iOS-style modal. */ +.script-sheet{width:min(880px,96vw);max-width:96vw}.script-toolbar,.script-footer{display:flex;flex-wrap:wrap;gap:8px;align-items:center;justify-content:space-between;margin:12px 0}.editor-wrap{display:flex;overflow:hidden;border:1px solid var(--line,#c6c6c8);border-radius:12px;background:#161b24;color:#d8e4f2}.editor-wrap pre,.editor-wrap textarea{margin:0!important;border:0!important;border-radius:0!important;line-height:1.55!important;font:14px/1.55 ui-monospace,SFMono-Regular,Consolas,monospace!important;padding:12px!important;tab-size:2}.editor-wrap pre{flex:0 0 48px;text-align:right;color:#8293a9;background:#202938;overflow:hidden;user-select:none}.editor-wrap textarea{background:transparent!important;color:#e8f1ff!important;min-width:0;flex:1;resize:vertical;white-space:pre;overflow:auto;min-height:230px}.editor-wrap textarea:focus{outline:2px solid #0a84ff;outline-offset:-2px}.script-footer{font-size:12px}.script-sheet #scriptError{color:#d33;white-space:pre-wrap}.script-sheet #scriptInfo{overflow-wrap:anywhere} +.rights-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(135px,1fr));gap:6px;margin:12px 0}.rights-grid label{display:flex;align-items:center;gap:6px;margin:0;padding:8px;background:var(--panel,#f2f2f7);border-radius:9px}.rights-grid input{width:auto;margin:0}.rights-grid label input[type=checkbox]{width:18px;height:18px} + +#scriptDialog>:not(.sheet-head),#aclDialog>:not(.sheet-head){margin-left:20px;margin-right:20px}#scriptDialog>.actions,#aclDialog>p:last-child{margin-bottom:20px}#aclDialog{width:min(560px,96vw);max-width:96vw}#aclDialog>button{width:calc(100% - 40px)}